repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
Immortalin/python-for-android
refs/heads/master
python-build/python-libs/xmpppy/doc/examples/bot.py
87
#!/usr/bin/python # -*- coding: koi8-r -*- # $Id: bot.py,v 1.2 2006/10/06 12:30:42 normanr Exp $ import sys import xmpp commands={} i18n={'ru':{},'en':{}} ########################### user handlers start ################################## i18n['en']['HELP']="This is example jabber bot.\nAvailable commands: %s" def helpHandler(user,command,args,mess): lst=commands.keys() lst.sort() return "HELP",', '.join(lst) i18n['en']['EMPTY']="%s" i18n['en']['HOOK1']='Responce 1: %s' def hook1Handler(user,command,args,mess): return "HOOK1",'You requested: %s'%args i18n['en']['HOOK2']='Responce 2: %s' def hook2Handler(user,command,args,mess): return "HOOK2","hook2 called with %s"%(`(user,command,args,mess)`) i18n['en']['HOOK3']='Responce 3: static string' def hook3Handler(user,command,args,mess): return "HOOK3"*int(args) ########################### user handlers stop ################################### ############################ bot logic start ##################################### i18n['en']["UNKNOWN COMMAND"]='Unknown command "%s". Try "help"' i18n['en']["UNKNOWN USER"]="I do not know you. Register first." def messageCB(conn,mess): text=mess.getBody() user=mess.getFrom() user.lang='en' # dup if text.find(' ')+1: command,args=text.split(' ',1) else: command,args=text,'' cmd=command.lower() if commands.has_key(cmd): reply=commands[cmd](user,command,args,mess) else: reply=("UNKNOWN COMMAND",cmd) if type(reply)==type(()): key,args=reply if i18n[user.lang].has_key(key): pat=i18n[user.lang][key] elif i18n['en'].has_key(key): pat=i18n['en'][key] else: pat="%s" if type(pat)==type(''): reply=pat%args else: reply=pat(**args) else: try: reply=i18n[user.lang][reply] except KeyError: try: reply=i18n['en'][reply] except KeyError: pass if reply: conn.send(xmpp.Message(mess.getFrom(),reply)) for i in globals().keys(): if i[-7:]=='Handler' and i[:-7].lower()==i[:-7]: commands[i[:-7]]=globals()[i] ############################# bot logic stop ##################################### def StepOn(conn): try: conn.Process(1) except KeyboardInterrupt: return 0 return 1 def GoOn(conn): while StepOn(conn): pass if len(sys.argv)<3: print "Usage: bot.py username@server.net password" else: jid=xmpp.JID(sys.argv[1]) user,server,password=jid.getNode(),jid.getDomain(),sys.argv[2] conn=xmpp.Client(server)#,debug=[]) conres=conn.connect() if not conres: print "Unable to connect to server %s!"%server sys.exit(1) if conres<>'tls': print "Warning: unable to estabilish secure connection - TLS failed!" authres=conn.auth(user,password) if not authres: print "Unable to authorize on %s - check login/password."%server sys.exit(1) if authres<>'sasl': print "Warning: unable to perform SASL auth os %s. Old authentication method used!"%server conn.RegisterHandler('message',messageCB) conn.sendInitPresence() print "Bot started." GoOn(conn)
bkabrda/devassistant
refs/heads/master
devassistant/gui/path_window.py
6
# -*- coding: utf-8 -*- """ Created on Wed Apr 3 13:16:47 2013 @author: Petr Hracek """ import os from gi.repository import Gtk from devassistant.config_manager import config_manager from devassistant import utils class PathWindow(object): """ Class shows option dialogs and checks settings for each assistant """ def __init__(self, parent, main_window, builder, gui_helper): self.parent = parent self.main_window = main_window self.path_window = builder.get_object("pathWindow") self.dir_name = builder.get_object("dirName") self.dir_name_browse_btn = builder.get_object("browsePathBtn") self.entry_project_name = builder.get_object("entryProjectName") self.builder = builder self.gui_helper = gui_helper self.box_path_main = builder.get_object("boxPathMain") self.box_project = builder.get_object("boxProject") self.box6 = builder.get_object("box6") self.run_btn = builder.get_object("nextPathBtn") self.args = dict() self.grid = self.gui_helper.create_gtk_grid(row_spacing=0, col_homogenous=False, row_homogenous=False) self.title = self.gui_helper.create_label("Available options:") self.title.set_alignment(0, 0) self.box_path_main.pack_start(self.title, False, False, 0) self.box_path_main.pack_start(self.grid, False, False, 0) self.kwargs = dict() self.label_caption = self.builder.get_object("labelCaption") self.label_prj_name = self.builder.get_object("labelPrjName") self.label_prj_dir = self.builder.get_object("labelPrjDir") self.label_full_prj_dir = self.builder.get_object("labelFullPrjDir") self.h_separator = self.builder.get_object("hseparator") self.top_assistant = None self.project_name_shown = True self.current_main_assistant = None self.data = dict() def arg_is_selected(self, arg_dict): if arg_dict['arg'].kwargs.get('required'): return True else: return arg_dict['checkbox'].get_active() def check_for_directory(self, dirname): """ Function checks the directory and report it to user """ return self.gui_helper.execute_dialog( "Directory {0} already exists".format( dirname)) def get_full_dir_name(self): """ Function returns a full dir name """ return os.path.join(self.dir_name.get_text(), self.entry_project_name.get_text()) def next_window(self, widget, data=None): """ Function opens the run Window who executes the assistant project creation """ # check whether deps-only is selected deps_only = ('deps_only' in self.args and self.args['deps_only']['checkbox'].get_active()) # preserve argument value if it is needed to be preserved for arg_dict in [x for x in self.args.values() if 'preserved' in x['arg'].kwargs]: preserve_key = arg_dict['arg'].kwargs['preserved'] # preserve entry text (string value) if 'entry' in arg_dict: if self.arg_is_selected(arg_dict): config_manager.set_config_value(preserve_key, arg_dict['entry'].get_text()) # preserve if checkbox is ticked (boolean value) else: config_manager.set_config_value(preserve_key, self.arg_is_selected(arg_dict)) # save configuration into file config_manager.save_configuration_file() # get project directory and name project_dir = self.dir_name.get_text() full_name = self.get_full_dir_name() # check whether project directory and name is properly set if not deps_only and self.current_main_assistant.name == 'crt': if project_dir == "": return self.gui_helper.execute_dialog("Specify directory for project") else: # check whether directory is existing if not os.path.isdir(project_dir): response = self.gui_helper.create_question_dialog( "Directory {0} does not exists".format(project_dir), "Do you want to create them?" ) if response == Gtk.ResponseType.NO: # User do not want to create a directory return else: # Create directory try: os.makedirs(project_dir) except OSError as os_err: return self.gui_helper.execute_dialog("{0}".format(os_err)) elif os.path.isdir(full_name): return self.check_for_directory(full_name) if not self._build_flags(): return if not deps_only and self.current_main_assistant.name == 'crt': self.kwargs['name'] = full_name self.kwargs['__ui__'] = 'gui_gtk+' self.data['kwargs'] = self.kwargs self.data['top_assistant'] = self.top_assistant self.data['current_main_assistant'] = self.current_main_assistant self.parent.run_window.open_window(widget, self.data) self.path_window.hide() def _build_flags(self): """ Function builds kwargs variable for run_window """ # Check if all entries for selected arguments are nonempty for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: if 'entry' in arg_dict and not arg_dict['entry'].get_text(): self.gui_helper.execute_dialog("Entry {0} is empty".format(arg_dict['label'])) return False # Check for active CheckButtons for arg_dict in [x for x in self.args.values() if self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'entry' in arg_dict: self.kwargs[arg_name] = arg_dict['entry'].get_text() else: if arg_dict['arg'].get_gui_hint('type') == 'const': self.kwargs[arg_name] = arg_dict['arg'].kwargs['const'] else: self.kwargs[arg_name] = True # Check for non active CheckButtons but with defaults flag for arg_dict in [x for x in self.args.values() if not self.arg_is_selected(x)]: arg_name = arg_dict['arg'].get_dest() if 'default' in arg_dict['arg'].kwargs: self.kwargs[arg_name] = arg_dict['arg'].get_gui_hint('default') elif arg_name in self.kwargs: del self.kwargs[arg_name] return True def _remove_widget_items(self): """ Function removes widgets from grid """ for btn in self.grid: self.grid.remove(btn) def get_default_project_dir(self): """Returns a project directory to prefill in GUI. It is either stored value or current directory (if exists) or home directory. """ ret = config_manager.get_config_value('da.project_dir') return ret or utils.get_cwd_or_homedir() def open_window(self, data=None): """ Function opens the Options dialog """ self.args = dict() if data is not None: self.top_assistant = data.get('top_assistant', None) self.current_main_assistant = data.get('current_main_assistant', None) self.kwargs = data.get('kwargs', None) self.data['debugging'] = data.get('debugging', False) project_dir = self.get_default_project_dir() self.dir_name.set_text(project_dir) self.label_full_prj_dir.set_text(project_dir) self.dir_name.set_sensitive(True) self.dir_name_browse_btn.set_sensitive(True) self._remove_widget_items() if self.current_main_assistant.name != 'crt' and self.project_name_shown: self.box6.remove(self.box_project) self.project_name_shown = False elif self.current_main_assistant.name == 'crt' and not self.project_name_shown: self.box6.remove(self.box_path_main) self.box6.pack_start(self.box_project, False, False, 0) self.box6.pack_end(self.box_path_main, False, False, 0) self.project_name_shown = True caption_text = "Project: " row = 0 # get selectected assistants, but without TopAssistant itself path = self.top_assistant.get_selected_subassistant_path(**self.kwargs)[1:] caption_parts = [] # Finds any dependencies found_deps = [x for x in path if x.dependencies()] # This bool variable is used for showing text "Available options:" any_options = False for assistant in path: caption_parts.append("<b>" + assistant.fullname + "</b>") for arg in sorted([x for x in assistant.args if not '--name' in x.flags], key=lambda y: y.flags): if not (arg.name == "deps_only" and not found_deps): row = self._add_table_row(arg, len(arg.flags) - 1, row) + 1 any_options = True if not any_options: self.title.set_text("") else: self.title.set_text("Available options:") caption_text += ' -> '.join(caption_parts) self.label_caption.set_markup(caption_text) self.path_window.show_all() self.entry_project_name.set_text(os.path.basename(self.kwargs.get('name', ''))) self.entry_project_name.set_sensitive(True) self.run_btn.set_sensitive(not self.project_name_shown or self.entry_project_name.get_text() != "") if 'name' in self.kwargs: self.dir_name.set_text(os.path.dirname(self.kwargs.get('name', ''))) for arg_name, arg_dict in [(k, v) for (k, v) in self.args.items() if self.kwargs.get(k)]: if 'checkbox' in arg_dict: arg_dict['checkbox'].set_active(True) if 'entry' in arg_dict: arg_dict['entry'].set_sensitive(True) arg_dict['entry'].set_text(self.kwargs[arg_name]) if 'browse_btn' in arg_dict: arg_dict['browse_btn'].set_sensitive(True) def _check_box_toggled(self, widget, data=None): """ Function manipulates with entries and buttons. """ active = widget.get_active() arg_name = data if 'entry' in self.args[arg_name]: self.args[arg_name]['entry'].set_sensitive(active) if 'browse_btn' in self.args[arg_name]: self.args[arg_name]['browse_btn'].set_sensitive(active) self.path_window.show_all() def _deps_only_toggled(self, widget, data=None): """ Function deactivate options in case of deps_only and opposite """ active = widget.get_active() self.dir_name.set_sensitive(not active) self.entry_project_name.set_sensitive(not active) self.dir_name_browse_btn.set_sensitive(not active) self.run_btn.set_sensitive(active or not self.project_name_shown or self.entry_project_name.get_text() != "") def prev_window(self, widget, data=None): """ Function returns to Main Window """ self.path_window.hide() self.parent.open_window(widget, self.data) def get_data(self): """ Function returns project dirname and project name """ return self.dir_name.get_text(), self.entry_project_name.get_text() def browse_path(self, window): """ Function opens the file chooser dialog for settings project dir """ text = self.gui_helper.create_file_chooser_dialog("Choose project directory", self.path_window, name="Select") if text is not None: self.dir_name.set_text(text) def _add_table_row(self, arg, number, row): """ Function adds options to a grid """ self.args[arg.name] = dict() self.args[arg.name]['arg'] = arg check_box_title = arg.flags[number][2:].title() self.args[arg.name]['label'] = check_box_title align = self.gui_helper.create_alignment() if arg.kwargs.get('required'): # If argument is required then red star instead of checkbox star_label = self.gui_helper.create_label('<span color="#FF0000">*</span>') star_label.set_padding(0, 3) label = self.gui_helper.create_label(check_box_title) box = self.gui_helper.create_box() box.pack_start(star_label, False, False, 6) box.pack_start(label, False, False, 6) align.add(box) else: chbox = self.gui_helper.create_checkbox(check_box_title) chbox.set_alignment(0, 0) if arg.name == "deps_only": chbox.connect("clicked", self._deps_only_toggled) else: chbox.connect("clicked", self._check_box_toggled, arg.name) align.add(chbox) self.args[arg.name]['checkbox'] = chbox if row == 0: self.grid.add(align) else: self.grid.attach(align, 0, row, 1, 1) label = self.gui_helper.create_label(arg.kwargs['help'], justify=Gtk.Justification.LEFT) label.set_alignment(0, 0) label.set_padding(0, 3) self.grid.attach(label, 1, row, 1, 1) label_check_box = self.gui_helper.create_label(name="") self.grid.attach(label_check_box, 0, row, 1, 1) if arg.get_gui_hint('type') not in ['bool', 'const']: new_box = self.gui_helper.create_box(spacing=6) entry = self.gui_helper.create_entry(text="") align = self.gui_helper.create_alignment() align.add(entry) new_box.pack_start(align, False, False, 6) align_btn = self.gui_helper.create_alignment() ''' If a button is needed please add there and in function _check_box_toggled Also do not forget to create a function for that button This can not be done by any automatic tool from those reasons Some fields needs a input user like user name for GitHub and some fields needs to have interaction from user like selecting directory ''' entry.set_text(arg.get_gui_hint('default')) entry.set_sensitive(arg.kwargs.get('required') == True) if arg.get_gui_hint('type') == 'path': browse_btn = self.gui_helper.button_with_label("Browse") browse_btn.connect("clicked", self.browse_clicked, entry) browse_btn.set_sensitive(arg.kwargs.get('required') == True) align_btn.add(browse_btn) self.args[arg.name]['browse_btn'] = browse_btn elif arg.get_gui_hint('type') == 'str': if arg.name == 'github' or arg.name == 'github-login': link_button = self.gui_helper.create_link_button(text="For registration visit GitHub Homepage", uri="https://www.github.com") align_btn.add(link_button) new_box.pack_start(align_btn, False, False, 6) row += 1 self.args[arg.name]['entry'] = entry self.grid.attach(new_box, 1, row, 1, 1) else: if 'preserved' in arg.kwargs and config_manager.get_config_value(arg.kwargs['preserved']): if 'checkbox' in self.args[arg.name]: self.args[arg.name]['checkbox'].set_active(True) return row def browse_clicked(self, widget, data=None): """ Function sets the directory to entry """ text = self.gui_helper.create_file_chooser_dialog("Please select directory", self.path_window) if text is not None: data.set_text(text) def update_full_label(self): """ Function is used for updating whole path of project """ self.label_full_prj_dir.set_text(self.get_full_dir_name()) def project_name_changed(self, widget, data=None): """ Function controls whether run button is enabled """ if widget.get_text() != "": self.run_btn.set_sensitive(True) else: self.run_btn.set_sensitive(False) self.update_full_label() def dir_name_changed(self, widget, data=None): """ Function is used for controlling label Full Directory project name and storing current project directory in configuration manager """ config_manager.set_config_value("da.project_dir", self.dir_name.get_text()) self.update_full_label()
mglukhikh/intellij-community
refs/heads/master
python/lib/Lib/site-packages/django/contrib/admindocs/utils.py
314
"Misc. utility functions/classes for admin documentation generator." import re from email.Parser import HeaderParser from email.Errors import HeaderParseError from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from django.utils.encoding import smart_str try: import docutils.core import docutils.nodes import docutils.parsers.rst.roles except ImportError: docutils_is_available = False else: docutils_is_available = True def trim_docstring(docstring): """ Uniformly trims leading/trailing whitespace from docstrings. Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation """ if not docstring or not docstring.strip(): return '' # Convert tabs to spaces and split into lines lines = docstring.expandtabs().splitlines() indent = min([len(line) - len(line.lstrip()) for line in lines if line.lstrip()]) trimmed = [lines[0].lstrip()] + [line[indent:].rstrip() for line in lines[1:]] return "\n".join(trimmed).strip() def parse_docstring(docstring): """ Parse out the parts of a docstring. Returns (title, body, metadata). """ docstring = trim_docstring(docstring) parts = re.split(r'\n{2,}', docstring) title = parts[0] if len(parts) == 1: body = '' metadata = {} else: parser = HeaderParser() try: metadata = parser.parsestr(parts[-1]) except HeaderParseError: metadata = {} body = "\n\n".join(parts[1:]) else: metadata = dict(metadata.items()) if metadata: body = "\n\n".join(parts[1:-1]) else: body = "\n\n".join(parts[1:]) return title, body, metadata def parse_rst(text, default_reference_context, thing_being_parsed=None): """ Convert the string from reST to an XHTML fragment. """ overrides = { 'doctitle_xform' : True, 'inital_header_level' : 3, "default_reference_context" : default_reference_context, "link_base" : reverse('django-admindocs-docroot').rstrip('/') } if thing_being_parsed: thing_being_parsed = smart_str("<%s>" % thing_being_parsed) parts = docutils.core.publish_parts(text, source_path=thing_being_parsed, destination_path=None, writer_name='html', settings_overrides=overrides) return mark_safe(parts['fragment']) # # reST roles # ROLES = { 'model' : '%s/models/%s/', 'view' : '%s/views/%s/', 'template' : '%s/templates/%s/', 'filter' : '%s/filters/#%s', 'tag' : '%s/tags/#%s', } def create_reference_role(rolename, urlbase): def _role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] node = docutils.nodes.reference(rawtext, text, refuri=(urlbase % (inliner.document.settings.link_base, text.lower())), **options) return [node], [] docutils.parsers.rst.roles.register_canonical_role(rolename, _role) def default_reference_role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} if content is None: content = [] context = inliner.document.settings.default_reference_context node = docutils.nodes.reference(rawtext, text, refuri=(ROLES[context] % (inliner.document.settings.link_base, text.lower())), **options) return [node], [] if docutils_is_available: docutils.parsers.rst.roles.register_canonical_role('cmsreference', default_reference_role) docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE = 'cmsreference' for name, urlbase in ROLES.items(): create_reference_role(name, urlbase)
tafia/servo
refs/heads/master
tests/wpt/harness/wptrunner/executors/executorservo.py
20
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import base64 import hashlib import json import os import subprocess import tempfile import threading import urlparse import uuid from collections import defaultdict from mozprocess import ProcessHandler from .base import (ExecutorException, Protocol, RefTestImplementation, testharness_result_converter, reftest_result_converter) from .process import ProcessTestExecutor from ..browsers.base import browser_command hosts_text = """127.0.0.1 web-platform.test 127.0.0.1 www.web-platform.test 127.0.0.1 www1.web-platform.test 127.0.0.1 www2.web-platform.test 127.0.0.1 xn--n8j6ds53lwwkrqhv28a.web-platform.test 127.0.0.1 xn--lve-6lad.web-platform.test """ def make_hosts_file(): hosts_fd, hosts_path = tempfile.mkstemp() with os.fdopen(hosts_fd, "w") as f: f.write(hosts_text) return hosts_path class ServoTestharnessExecutor(ProcessTestExecutor): convert_result = testharness_result_converter def __init__(self, browser, server_config, timeout_multiplier=1, debug_info=None, pause_after_test=False): ProcessTestExecutor.__init__(self, browser, server_config, timeout_multiplier=timeout_multiplier, debug_info=debug_info) self.pause_after_test = pause_after_test self.result_data = None self.result_flag = None self.protocol = Protocol(self, browser) self.hosts_path = make_hosts_file() def teardown(self): try: os.unlink(self.hosts_path) except OSError: pass ProcessTestExecutor.teardown(self) def do_test(self, test): self.result_data = None self.result_flag = threading.Event() args = ["--cpu", "--hard-fail", "-u", "Servo/wptrunner", "-z", self.test_url(test)] for stylesheet in self.browser.user_stylesheets: args += ["--user-stylesheet", stylesheet] debug_args, command = browser_command(self.binary, args, self.debug_info) self.command = command if self.pause_after_test: self.command.remove("-z") self.command = debug_args + self.command env = os.environ.copy() env["HOST_FILE"] = self.hosts_path if not self.interactive: self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], onFinish=self.on_finish, env=env, storeOutput=False) self.proc.run() else: self.proc = subprocess.Popen(self.command, env=env) try: timeout = test.timeout * self.timeout_multiplier # Now wait to get the output we expect, or until we reach the timeout if not self.interactive and not self.pause_after_test: wait_timeout = timeout + 5 self.result_flag.wait(wait_timeout) else: wait_timeout = None self.proc.wait() proc_is_running = True if self.result_flag.is_set(): if self.result_data is not None: self.result_data["test"] = test.url result = self.convert_result(test, self.result_data) else: self.proc.wait() result = (test.result_cls("CRASH", None), []) proc_is_running = False else: result = (test.result_cls("TIMEOUT", None), []) if proc_is_running: if self.pause_after_test: self.logger.info("Pausing until the browser exits") self.proc.wait() else: self.proc.kill() except KeyboardInterrupt: self.proc.kill() raise return result def on_output(self, line): prefix = "ALERT: RESULT: " line = line.decode("utf8", "replace") if line.startswith(prefix): self.result_data = json.loads(line[len(prefix):]) self.result_flag.set() else: if self.interactive: print line else: self.logger.process_output(self.proc.pid, line, " ".join(self.command)) def on_finish(self): self.result_flag.set() class TempFilename(object): def __init__(self, directory): self.directory = directory self.path = None def __enter__(self): self.path = os.path.join(self.directory, str(uuid.uuid4())) return self.path def __exit__(self, *args, **kwargs): try: os.unlink(self.path) except OSError: pass class ServoRefTestExecutor(ProcessTestExecutor): convert_result = reftest_result_converter def __init__(self, browser, server_config, binary=None, timeout_multiplier=1, screenshot_cache=None, debug_info=None, pause_after_test=False): ProcessTestExecutor.__init__(self, browser, server_config, timeout_multiplier=timeout_multiplier, debug_info=debug_info) self.protocol = Protocol(self, browser) self.screenshot_cache = screenshot_cache self.implementation = RefTestImplementation(self) self.tempdir = tempfile.mkdtemp() self.hosts_path = make_hosts_file() def teardown(self): try: os.unlink(self.hosts_path) except OSError: pass os.rmdir(self.tempdir) ProcessTestExecutor.teardown(self) def screenshot(self, test): full_url = self.test_url(test) with TempFilename(self.tempdir) as output_path: self.command = [self.binary, "--cpu", "--hard-fail", "--exit", "-u", "Servo/wptrunner", "-Z", "disable-text-aa", "--output=%s" % output_path, full_url] for stylesheet in self.browser.user_stylesheets: self.command += ["--user-stylesheet", stylesheet] env = os.environ.copy() env["HOST_FILE"] = self.hosts_path self.proc = ProcessHandler(self.command, processOutputLine=[self.on_output], env=env) try: self.proc.run() timeout = test.timeout * self.timeout_multiplier + 5 rv = self.proc.wait(timeout=timeout) except KeyboardInterrupt: self.proc.kill() raise if rv is None: self.proc.kill() return False, ("EXTERNAL-TIMEOUT", None) if rv != 0 or not os.path.exists(output_path): return False, ("CRASH", None) with open(output_path) as f: # Might need to strip variable headers or something here data = f.read() return True, base64.b64encode(data) def do_test(self, test): result = self.implementation.run_test(test) return self.convert_result(test, result) def on_output(self, line): line = line.decode("utf8", "replace") if self.interactive: print line else: self.logger.process_output(self.proc.pid, line, " ".join(self.command))
glennq/scikit-learn
refs/heads/master
sklearn/model_selection/__init__.py
30
from ._split import BaseCrossValidator from ._split import KFold from ._split import GroupKFold from ._split import StratifiedKFold from ._split import TimeSeriesSplit from ._split import LeaveOneGroupOut from ._split import LeaveOneOut from ._split import LeavePGroupsOut from ._split import LeavePOut from ._split import ShuffleSplit from ._split import GroupShuffleSplit from ._split import StratifiedShuffleSplit from ._split import PredefinedSplit from ._split import train_test_split from ._split import check_cv from ._validation import cross_val_score from ._validation import cross_val_predict from ._validation import learning_curve from ._validation import permutation_test_score from ._validation import validation_curve from ._search import GridSearchCV from ._search import RandomizedSearchCV from ._search import ParameterGrid from ._search import ParameterSampler from ._search import fit_grid_point __all__ = ('BaseCrossValidator', 'GridSearchCV', 'TimeSeriesSplit', 'KFold', 'GroupKFold', 'GroupShuffleSplit', 'LeaveOneGroupOut', 'LeaveOneOut', 'LeavePGroupsOut', 'LeavePOut', 'ParameterGrid', 'ParameterSampler', 'PredefinedSplit', 'RandomizedSearchCV', 'ShuffleSplit', 'StratifiedKFold', 'StratifiedShuffleSplit', 'check_cv', 'cross_val_predict', 'cross_val_score', 'fit_grid_point', 'learning_curve', 'permutation_test_score', 'train_test_split', 'validation_curve')
barryloper/dorthy
refs/heads/master
dorthy/dp.py
2
import inspect import logging import weakref from collections import MutableMapping logger = logging.getLogger(__name__) class Singleton(object): """ A decorated to implement the singleton pattern. This implementation is not thread safe. Based on: http://stackoverflow.com/questions/42558/python-and-the-singleton-pattern """ def __init__(self, decorated_class): self.__decorated_class = decorated_class self.__doc__ = decorated_class.__doc__ def __call__(self): """ Returns the singleton instance. """ try: return self.__instance except AttributeError: self.__instance = self.__decorated_class() if hasattr(self.__instance, "initialize"): self.__instance.initialize() return self.__instance class MultipleObservableErrors(Exception): def __init__(self, message, errors=None): super().__init__(message) self.__errors = errors @property def errors(self): return self.__errors class Observable(object): """Provides an observable class the uses weak references so that objects are not held in memory by the observable. """ def __init__(self, handle_errors=True): self.__listeners = dict() self.__handle_errors = handle_errors def __call__(self, *args, **kwargs): """Calls the listeners with the given arguments and keyword arguments. """ if not self.__listeners: return errors = list() listeners = dict() for k, v in self.__listeners.items(): call_obj = None if v[0] == "f": call_obj = v[2] elif v[0] == "m": obj = v[2]() if obj: call_obj = getattr(obj, v[3].__name__) else: raise ValueError("Only supports functions or methods as listeners.") # execute callable if call_obj: listeners[v[1]] = v try: call_obj(*args, **kwargs) except Exception as e: if self.__handle_errors: logger.exception("Failed to execute observable callback.") else: # collect the errors errors.append(e) # clean out references that are no longer valid self.__listeners = listeners # raise exceptions generated if errors: raise MultipleObservableErrors("Failed to execute observable callbacks.", errors) def __contains__(self, item): if inspect.isfunction(item) or inspect.ismethod(item): return id(item) in self.__listeners else: return item in self.__listeners def register(self, listener): """Registers a listener with the observable class. The listener must either be a method or a function. returns: the listener id that can be used to remove the listener """ ref_key = id(listener) if inspect.isfunction(listener): ref = ("f", ref_key, listener) elif inspect.ismethod(listener): weak_obj = weakref.ref(listener.__self__) ref = ("m", ref_key, weak_obj, listener.__func__) else: raise ValueError("Only supports functions or methods as listeners.") self.__listeners[ref_key] = ref return ref_key def remove(self, listener_id): """Removes the listener for the given id. returns: True if the listener has been found and removed, otherwise False """ return True if self.__listeners.pop(listener_id, None) else False class ObjectMap(MutableMapping): """Converts object attribute access to a map view. """ def __init__(self, obj, ignore_=True): self.__object = obj self.__ignore_ = ignore_ def _get_attrs(self): if self.__ignore_: return [d for d in dir(self.__object) if not d.startswith("_")] else: return dir(self.__object) def _check_key(self, key): if self.__ignore_ and key.startswith("_"): raise KeyError("Invalid attribute: " + key) def __contains__(self, key): self._check_key(key) return hasattr(self.__object, key) def __len__(self): return len(self._get_attrs()) def __getitem__(self, key): self._check_key(key) try: return getattr(self.__object, key) except AttributeError: raise KeyError(key) def __delitem__(self, key): self._check_key(key) try: delattr(self.__object, key) except AttributeError: raise KeyError(key) def __setitem__(self, key, value): self._check_key(key) setattr(self.__object, key, value) def __iter__(self): return iter(self._get_attrs()) class ObjectDict(dict): """Extends dict to provide object attribute get and set access. """ def __delattr__(self, name): if name in self: del self[name] def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) def __setattr__(self, name, value): self[name] = value
EDUlib/edx-platform
refs/heads/master
import_shims/lms/util/password_policy_validators.py
4
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('util.password_policy_validators', 'common.djangoapps.util.password_policy_validators') from common.djangoapps.util.password_policy_validators import *
phenoxim/nova
refs/heads/master
nova/cmd/dhcpbridge.py
5
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # 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. """ Handle lease database updates from DHCP servers. """ from __future__ import print_function import os import sys from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import importutils from nova.cmd import common as cmd_common from nova.conductor import rpcapi as conductor_rpcapi import nova.conf from nova import config from nova import context from nova.network import rpcapi as network_rpcapi from nova import objects from nova.objects import base as objects_base from nova import rpc CONF = nova.conf.CONF LOG = logging.getLogger(__name__) def add_lease(mac, ip_address): """Set the IP that was assigned by the DHCP server.""" api = network_rpcapi.NetworkAPI() api.lease_fixed_ip(context.get_admin_context(), ip_address, CONF.host) def old_lease(mac, ip_address): """Called when an old lease is recognized.""" # NOTE(vish): We assume we heard about this lease the first time. # If not, we will get it the next time the lease is # renewed. pass def del_lease(mac, ip_address): """Called when a lease expires.""" api = network_rpcapi.NetworkAPI() api.release_fixed_ip(context.get_admin_context(), ip_address, CONF.host, mac) def init_leases(network_id): """Get the list of hosts for a network.""" ctxt = context.get_admin_context() network = objects.Network.get_by_id(ctxt, network_id) network_manager = importutils.import_object(CONF.network_manager) return network_manager.get_dhcp_leases(ctxt, network) def add_action_parsers(subparsers): subparsers.add_parser('init') # NOTE(cfb): dnsmasq always passes mac, and ip. hostname # is passed if known. We don't care about # hostname, but argparse will complain if we # do not accept it. actions = { 'add': add_lease, 'del': del_lease, 'old': old_lease, } for action, func in actions.items(): parser = subparsers.add_parser(action) parser.add_argument('mac') parser.add_argument('ip') parser.add_argument('hostname', nargs='?', default='') parser.set_defaults(func=func) CONF.register_cli_opt( cfg.SubCommandOpt('action', title='Action options', help='Available dhcpbridge options', handler=add_action_parsers)) def main(): """Parse environment and arguments and call the appropriate action.""" config.parse_args(sys.argv, default_config_files=jsonutils.loads(os.environ['CONFIG_FILE'])) logging.setup(CONF, "nova") global LOG LOG = logging.getLogger('nova.dhcpbridge') if CONF.action.name == 'old': # NOTE(sdague): old is the most frequent message sent, and # it's a noop. We should just exit immediately otherwise we # can stack up a bunch of requests in dnsmasq. A SIGHUP seems # to dump this list, so actions queued up get lost. return objects.register_all() cmd_common.block_db_access('nova-dhcpbridge') objects_base.NovaObject.indirection_api = conductor_rpcapi.ConductorAPI() if CONF.action.name in ['add', 'del']: LOG.debug("Called '%(action)s' for mac '%(mac)s' with IP '%(ip)s'", {"action": CONF.action.name, "mac": CONF.action.mac, "ip": CONF.action.ip}) CONF.action.func(CONF.action.mac, CONF.action.ip) else: try: network_id = int(os.environ.get('NETWORK_ID')) except TypeError: LOG.error("Environment variable 'NETWORK_ID' must be set.") return 1 print(init_leases(network_id)) rpc.cleanup()
seppi91/CouchPotatoServer
refs/heads/develop
libs/tornado/testing.py
66
#!/usr/bin/env python """Support classes for automated testing. * `AsyncTestCase` and `AsyncHTTPTestCase`: Subclasses of unittest.TestCase with additional support for testing asynchronous (`.IOLoop` based) code. * `ExpectLog` and `LogTrapTestCase`: Make test logs less spammy. * `main()`: A simple test runner (wrapper around unittest.main()) with support for the tornado.autoreload module to rerun the tests when code changes. """ from __future__ import absolute_import, division, print_function, with_statement try: from tornado import gen from tornado.httpclient import AsyncHTTPClient from tornado.httpserver import HTTPServer from tornado.simple_httpclient import SimpleAsyncHTTPClient from tornado.ioloop import IOLoop, TimeoutError from tornado import netutil from tornado.process import Subprocess except ImportError: # These modules are not importable on app engine. Parts of this module # won't work, but e.g. LogTrapTestCase and main() will. AsyncHTTPClient = None gen = None HTTPServer = None IOLoop = None netutil = None SimpleAsyncHTTPClient = None Subprocess = None from tornado.log import gen_log, app_log from tornado.stack_context import ExceptionStackContext from tornado.util import raise_exc_info, basestring_type import functools import logging import os import re import signal import socket import sys import types try: from cStringIO import StringIO # py2 except ImportError: from io import StringIO # py3 # Tornado's own test suite requires the updated unittest module # (either py27+ or unittest2) so tornado.test.util enforces # this requirement, but for other users of tornado.testing we want # to allow the older version if unitest2 is not available. if sys.version_info >= (3,): # On python 3, mixing unittest2 and unittest (including doctest) # doesn't seem to work, so always use unittest. import unittest else: # On python 2, prefer unittest2 when available. try: import unittest2 as unittest except ImportError: import unittest _next_port = 10000 def get_unused_port(): """Returns a (hopefully) unused port number. This function does not guarantee that the port it returns is available, only that a series of get_unused_port calls in a single process return distinct ports. .. deprecated:: Use bind_unused_port instead, which is guaranteed to find an unused port. """ global _next_port port = _next_port _next_port = _next_port + 1 return port def bind_unused_port(): """Binds a server socket to an available port on localhost. Returns a tuple (socket, port). """ [sock] = netutil.bind_sockets(None, 'localhost', family=socket.AF_INET) port = sock.getsockname()[1] return sock, port def get_async_test_timeout(): """Get the global timeout setting for async tests. Returns a float, the timeout in seconds. .. versionadded:: 3.1 """ try: return float(os.environ.get('ASYNC_TEST_TIMEOUT')) except (ValueError, TypeError): return 5 class _TestMethodWrapper(object): """Wraps a test method to raise an error if it returns a value. This is mainly used to detect undecorated generators (if a test method yields it must use a decorator to consume the generator), but will also detect other kinds of return values (these are not necessarily errors, but we alert anyway since there is no good reason to return a value from a test. """ def __init__(self, orig_method): self.orig_method = orig_method def __call__(self, *args, **kwargs): result = self.orig_method(*args, **kwargs) if isinstance(result, types.GeneratorType): raise TypeError("Generator test methods should be decorated with " "tornado.testing.gen_test") elif result is not None: raise ValueError("Return value from test method ignored: %r" % result) def __getattr__(self, name): """Proxy all unknown attributes to the original method. This is important for some of the decorators in the `unittest` module, such as `unittest.skipIf`. """ return getattr(self.orig_method, name) class AsyncTestCase(unittest.TestCase): """`~unittest.TestCase` subclass for testing `.IOLoop`-based asynchronous code. The unittest framework is synchronous, so the test must be complete by the time the test method returns. This means that asynchronous code cannot be used in quite the same way as usual. To write test functions that use the same ``yield``-based patterns used with the `tornado.gen` module, decorate your test methods with `tornado.testing.gen_test` instead of `tornado.gen.coroutine`. This class also provides the `stop()` and `wait()` methods for a more manual style of testing. The test method itself must call ``self.wait()``, and asynchronous callbacks should call ``self.stop()`` to signal completion. By default, a new `.IOLoop` is constructed for each test and is available as ``self.io_loop``. This `.IOLoop` should be used in the construction of HTTP clients/servers, etc. If the code being tested requires a global `.IOLoop`, subclasses should override `get_new_ioloop` to return it. The `.IOLoop`'s ``start`` and ``stop`` methods should not be called directly. Instead, use `self.stop <stop>` and `self.wait <wait>`. Arguments passed to ``self.stop`` are returned from ``self.wait``. It is possible to have multiple ``wait``/``stop`` cycles in the same test. Example:: # This test uses coroutine style. class MyTestCase(AsyncTestCase): @tornado.testing.gen_test def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) response = yield client.fetch("http://www.tornadoweb.org") # Test contents of response self.assertIn("FriendFeed", response.body) # This test uses argument passing between self.stop and self.wait. class MyTestCase2(AsyncTestCase): def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.tornadoweb.org/", self.stop) response = self.wait() # Test contents of response self.assertIn("FriendFeed", response.body) # This test uses an explicit callback-based style. class MyTestCase3(AsyncTestCase): def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.tornadoweb.org/", self.handle_fetch) self.wait() def handle_fetch(self, response): # Test contents of response (failures and exceptions here # will cause self.wait() to throw an exception and end the # test). # Exceptions thrown here are magically propagated to # self.wait() in test_http_fetch() via stack_context. self.assertIn("FriendFeed", response.body) self.stop() """ def __init__(self, methodName='runTest', **kwargs): super(AsyncTestCase, self).__init__(methodName, **kwargs) self.__stopped = False self.__running = False self.__failure = None self.__stop_args = None self.__timeout = None # It's easy to forget the @gen_test decorator, but if you do # the test will silently be ignored because nothing will consume # the generator. Replace the test method with a wrapper that will # make sure it's not an undecorated generator. setattr(self, methodName, _TestMethodWrapper(getattr(self, methodName))) def setUp(self): super(AsyncTestCase, self).setUp() self.io_loop = self.get_new_ioloop() self.io_loop.make_current() def tearDown(self): # Clean up Subprocess, so it can be used again with a new ioloop. Subprocess.uninitialize() self.io_loop.clear_current() if (not IOLoop.initialized() or self.io_loop is not IOLoop.instance()): # Try to clean up any file descriptors left open in the ioloop. # This avoids leaks, especially when tests are run repeatedly # in the same process with autoreload (because curl does not # set FD_CLOEXEC on its file descriptors) self.io_loop.close(all_fds=True) super(AsyncTestCase, self).tearDown() # In case an exception escaped or the StackContext caught an exception # when there wasn't a wait() to re-raise it, do so here. # This is our last chance to raise an exception in a way that the # unittest machinery understands. self.__rethrow() def get_new_ioloop(self): """Creates a new `.IOLoop` for this test. May be overridden in subclasses for tests that require a specific `.IOLoop` (usually the singleton `.IOLoop.instance()`). """ return IOLoop() def _handle_exception(self, typ, value, tb): if self.__failure is None: self.__failure = (typ, value, tb) else: app_log.error("multiple unhandled exceptions in test", exc_info=(typ, value, tb)) self.stop() return True def __rethrow(self): if self.__failure is not None: failure = self.__failure self.__failure = None raise_exc_info(failure) def run(self, result=None): with ExceptionStackContext(self._handle_exception): super(AsyncTestCase, self).run(result) # As a last resort, if an exception escaped super.run() and wasn't # re-raised in tearDown, raise it here. This will cause the # unittest run to fail messily, but that's better than silently # ignoring an error. self.__rethrow() def stop(self, _arg=None, **kwargs): """Stops the `.IOLoop`, causing one pending (or future) call to `wait()` to return. Keyword arguments or a single positional argument passed to `stop()` are saved and will be returned by `wait()`. """ assert _arg is None or not kwargs self.__stop_args = kwargs or _arg if self.__running: self.io_loop.stop() self.__running = False self.__stopped = True def wait(self, condition=None, timeout=None): """Runs the `.IOLoop` until stop is called or timeout has passed. In the event of a timeout, an exception will be thrown. The default timeout is 5 seconds; it may be overridden with a ``timeout`` keyword argument or globally with the ``ASYNC_TEST_TIMEOUT`` environment variable. If ``condition`` is not None, the `.IOLoop` will be restarted after `stop()` until ``condition()`` returns true. .. versionchanged:: 3.1 Added the ``ASYNC_TEST_TIMEOUT`` environment variable. """ if timeout is None: timeout = get_async_test_timeout() if not self.__stopped: if timeout: def timeout_func(): try: raise self.failureException( 'Async operation timed out after %s seconds' % timeout) except Exception: self.__failure = sys.exc_info() self.stop() self.__timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout, timeout_func) while True: self.__running = True self.io_loop.start() if (self.__failure is not None or condition is None or condition()): break if self.__timeout is not None: self.io_loop.remove_timeout(self.__timeout) self.__timeout = None assert self.__stopped self.__stopped = False self.__rethrow() result = self.__stop_args self.__stop_args = None return result class AsyncHTTPTestCase(AsyncTestCase): """A test case that starts up an HTTP server. Subclasses must override `get_app()`, which returns the `tornado.web.Application` (or other `.HTTPServer` callback) to be tested. Tests will typically use the provided ``self.http_client`` to fetch URLs from this server. Example:: class MyHTTPTest(AsyncHTTPTestCase): def get_app(self): return Application([('/', MyHandler)...]) def test_homepage(self): # The following two lines are equivalent to # response = self.fetch('/') # but are shown in full here to demonstrate explicit use # of self.stop and self.wait. self.http_client.fetch(self.get_url('/'), self.stop) response = self.wait() # test contents of response """ def setUp(self): super(AsyncHTTPTestCase, self).setUp() sock, port = bind_unused_port() self.__port = port self.http_client = self.get_http_client() self._app = self.get_app() self.http_server = self.get_http_server() self.http_server.add_sockets([sock]) def get_http_client(self): return AsyncHTTPClient(io_loop=self.io_loop) def get_http_server(self): return HTTPServer(self._app, io_loop=self.io_loop, **self.get_httpserver_options()) def get_app(self): """Should be overridden by subclasses to return a `tornado.web.Application` or other `.HTTPServer` callback. """ raise NotImplementedError() def fetch(self, path, **kwargs): """Convenience method to synchronously fetch a url. The given path will be appended to the local server's host and port. Any additional kwargs will be passed directly to `.AsyncHTTPClient.fetch` (and so could be used to pass ``method="POST"``, ``body="..."``, etc). """ self.http_client.fetch(self.get_url(path), self.stop, **kwargs) return self.wait() def get_httpserver_options(self): """May be overridden by subclasses to return additional keyword arguments for the server. """ return {} def get_http_port(self): """Returns the port used by the server. A new port is chosen for each test. """ return self.__port def get_protocol(self): return 'http' def get_url(self, path): """Returns an absolute url for the given path on the test server.""" return '%s://localhost:%s%s' % (self.get_protocol(), self.get_http_port(), path) def tearDown(self): self.http_server.stop() self.io_loop.run_sync(self.http_server.close_all_connections, timeout=get_async_test_timeout()) if (not IOLoop.initialized() or self.http_client.io_loop is not IOLoop.instance()): self.http_client.close() super(AsyncHTTPTestCase, self).tearDown() class AsyncHTTPSTestCase(AsyncHTTPTestCase): """A test case that starts an HTTPS server. Interface is generally the same as `AsyncHTTPTestCase`. """ def get_http_client(self): # Some versions of libcurl have deadlock bugs with ssl, # so always run these tests with SimpleAsyncHTTPClient. return SimpleAsyncHTTPClient(io_loop=self.io_loop, force_instance=True, defaults=dict(validate_cert=False)) def get_httpserver_options(self): return dict(ssl_options=self.get_ssl_options()) def get_ssl_options(self): """May be overridden by subclasses to select SSL options. By default includes a self-signed testing certificate. """ # Testing keys were generated with: # openssl req -new -keyout tornado/test/test.key -out tornado/test/test.crt -nodes -days 3650 -x509 module_dir = os.path.dirname(__file__) return dict( certfile=os.path.join(module_dir, 'test', 'test.crt'), keyfile=os.path.join(module_dir, 'test', 'test.key')) def get_protocol(self): return 'https' def gen_test(func=None, timeout=None): """Testing equivalent of ``@gen.coroutine``, to be applied to test methods. ``@gen.coroutine`` cannot be used on tests because the `.IOLoop` is not already running. ``@gen_test`` should be applied to test methods on subclasses of `AsyncTestCase`. Example:: class MyTest(AsyncHTTPTestCase): @gen_test def test_something(self): response = yield gen.Task(self.fetch('/')) By default, ``@gen_test`` times out after 5 seconds. The timeout may be overridden globally with the ``ASYNC_TEST_TIMEOUT`` environment variable, or for each test with the ``timeout`` keyword argument:: class MyTest(AsyncHTTPTestCase): @gen_test(timeout=10) def test_something_slow(self): response = yield gen.Task(self.fetch('/')) .. versionadded:: 3.1 The ``timeout`` argument and ``ASYNC_TEST_TIMEOUT`` environment variable. .. versionchanged:: 4.0 The wrapper now passes along ``*args, **kwargs`` so it can be used on functions with arguments. """ if timeout is None: timeout = get_async_test_timeout() def wrap(f): # Stack up several decorators to allow us to access the generator # object itself. In the innermost wrapper, we capture the generator # and save it in an attribute of self. Next, we run the wrapped # function through @gen.coroutine. Finally, the coroutine is # wrapped again to make it synchronous with run_sync. # # This is a good case study arguing for either some sort of # extensibility in the gen decorators or cancellation support. @functools.wraps(f) def pre_coroutine(self, *args, **kwargs): result = f(self, *args, **kwargs) if isinstance(result, types.GeneratorType): self._test_generator = result else: self._test_generator = None return result coro = gen.coroutine(pre_coroutine) @functools.wraps(coro) def post_coroutine(self, *args, **kwargs): try: return self.io_loop.run_sync( functools.partial(coro, self, *args, **kwargs), timeout=timeout) except TimeoutError as e: # run_sync raises an error with an unhelpful traceback. # If we throw it back into the generator the stack trace # will be replaced by the point where the test is stopped. self._test_generator.throw(e) # In case the test contains an overly broad except clause, # we may get back here. In this case re-raise the original # exception, which is better than nothing. raise return post_coroutine if func is not None: # Used like: # @gen_test # def f(self): # pass return wrap(func) else: # Used like @gen_test(timeout=10) return wrap # Without this attribute, nosetests will try to run gen_test as a test # anywhere it is imported. gen_test.__test__ = False class LogTrapTestCase(unittest.TestCase): """A test case that captures and discards all logging output if the test passes. Some libraries can produce a lot of logging output even when the test succeeds, so this class can be useful to minimize the noise. Simply use it as a base class for your test case. It is safe to combine with AsyncTestCase via multiple inheritance (``class MyTestCase(AsyncHTTPTestCase, LogTrapTestCase):``) This class assumes that only one log handler is configured and that it is a `~logging.StreamHandler`. This is true for both `logging.basicConfig` and the "pretty logging" configured by `tornado.options`. It is not compatible with other log buffering mechanisms, such as those provided by some test runners. .. deprecated:: 4.1 Use the unittest module's ``--buffer`` option instead, or `.ExpectLog`. """ def run(self, result=None): logger = logging.getLogger() if not logger.handlers: logging.basicConfig() handler = logger.handlers[0] if (len(logger.handlers) > 1 or not isinstance(handler, logging.StreamHandler)): # Logging has been configured in a way we don't recognize, # so just leave it alone. super(LogTrapTestCase, self).run(result) return old_stream = handler.stream try: handler.stream = StringIO() gen_log.info("RUNNING TEST: " + str(self)) old_error_count = len(result.failures) + len(result.errors) super(LogTrapTestCase, self).run(result) new_error_count = len(result.failures) + len(result.errors) if new_error_count != old_error_count: old_stream.write(handler.stream.getvalue()) finally: handler.stream = old_stream class ExpectLog(logging.Filter): """Context manager to capture and suppress expected log output. Useful to make tests of error conditions less noisy, while still leaving unexpected log entries visible. *Not thread safe.* Usage:: with ExpectLog('tornado.application', "Uncaught exception"): error_response = self.fetch("/some_page") """ def __init__(self, logger, regex, required=True): """Constructs an ExpectLog context manager. :param logger: Logger object (or name of logger) to watch. Pass an empty string to watch the root logger. :param regex: Regular expression to match. Any log entries on the specified logger that match this regex will be suppressed. :param required: If true, an exeption will be raised if the end of the ``with`` statement is reached without matching any log entries. """ if isinstance(logger, basestring_type): logger = logging.getLogger(logger) self.logger = logger self.regex = re.compile(regex) self.required = required self.matched = False def filter(self, record): message = record.getMessage() if self.regex.match(message): self.matched = True return False return True def __enter__(self): self.logger.addFilter(self) def __exit__(self, typ, value, tb): self.logger.removeFilter(self) if not typ and self.required and not self.matched: raise Exception("did not get expected log message") def main(**kwargs): """A simple test runner. This test runner is essentially equivalent to `unittest.main` from the standard library, but adds support for tornado-style option parsing and log formatting. The easiest way to run a test is via the command line:: python -m tornado.testing tornado.test.stack_context_test See the standard library unittest module for ways in which tests can be specified. Projects with many tests may wish to define a test script like ``tornado/test/runtests.py``. This script should define a method ``all()`` which returns a test suite and then call `tornado.testing.main()`. Note that even when a test script is used, the ``all()`` test suite may be overridden by naming a single test on the command line:: # Runs all tests python -m tornado.test.runtests # Runs one test python -m tornado.test.runtests tornado.test.stack_context_test Additional keyword arguments passed through to ``unittest.main()``. For example, use ``tornado.testing.main(verbosity=2)`` to show many test details as they are run. See http://docs.python.org/library/unittest.html#unittest.main for full argument list. """ from tornado.options import define, options, parse_command_line define('exception_on_interrupt', type=bool, default=True, help=("If true (default), ctrl-c raises a KeyboardInterrupt " "exception. This prints a stack trace but cannot interrupt " "certain operations. If false, the process is more reliably " "killed, but does not print a stack trace.")) # support the same options as unittest's command-line interface define('verbose', type=bool) define('quiet', type=bool) define('failfast', type=bool) define('catch', type=bool) define('buffer', type=bool) argv = [sys.argv[0]] + parse_command_line(sys.argv) if not options.exception_on_interrupt: signal.signal(signal.SIGINT, signal.SIG_DFL) if options.verbose is not None: kwargs['verbosity'] = 2 if options.quiet is not None: kwargs['verbosity'] = 0 if options.failfast is not None: kwargs['failfast'] = True if options.catch is not None: kwargs['catchbreak'] = True if options.buffer is not None: kwargs['buffer'] = True if __name__ == '__main__' and len(argv) == 1: print("No tests specified", file=sys.stderr) sys.exit(1) try: # In order to be able to run tests by their fully-qualified name # on the command line without importing all tests here, # module must be set to None. Python 3.2's unittest.main ignores # defaultTest if no module is given (it tries to do its own # test discovery, which is incompatible with auto2to3), so don't # set module if we're not asking for a specific test. if len(argv) > 1: unittest.main(module=None, argv=argv, **kwargs) else: unittest.main(defaultTest="all", argv=argv, **kwargs) except SystemExit as e: if e.code == 0: gen_log.info('PASS') else: gen_log.error('FAIL') raise if __name__ == '__main__': main()
aevum/moonstone
refs/heads/master
src/moonstone/gui/qt/widget/importwindow_ui.py
2
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/igor/Desenvolvimento/neppo/moonstone/src/resources/ui/qt/importwindow.ui' # # Created: Fri Sep 20 14:20:28 2013 # by: pyside-uic 0.2.14 running on PySide 1.1.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_ImportWindow(object): def setupUi(self, ImportWindow): ImportWindow.setObjectName("ImportWindow") ImportWindow.setWindowModality(QtCore.Qt.WindowModal) ImportWindow.resize(657, 539) ImportWindow.setCursor(QtCore.Qt.ArrowCursor) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/static/default/icon/22x22/moonstone.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) ImportWindow.setWindowIcon(icon) self.verticalLayout_3 = QtGui.QVBoxLayout(ImportWindow) self.verticalLayout_3.setSpacing(0) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.verticalLayout_3.setObjectName("verticalLayout_3") self.mainWidget = QtGui.QWidget(ImportWindow) self.mainWidget.setObjectName("mainWidget") self.horizontalLayout_2 = QtGui.QHBoxLayout(self.mainWidget) self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.splitter = QtGui.QSplitter(self.mainWidget) self.splitter.setMidLineWidth(0) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName("splitter") self.treeWidgetContainer = QtGui.QWidget(self.splitter) self.treeWidgetContainer.setObjectName("treeWidgetContainer") self.verticalLayout_2 = QtGui.QVBoxLayout(self.treeWidgetContainer) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName("verticalLayout_2") self.splitter_2 = QtGui.QSplitter(self.treeWidgetContainer) self.splitter_2.setOrientation(QtCore.Qt.Vertical) self.splitter_2.setObjectName("splitter_2") self.widget = QtGui.QWidget(self.splitter_2) self.widget.setObjectName("widget") self.verticalLayout = QtGui.QVBoxLayout(self.widget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.frame = QtGui.QFrame(self.widget) self.frame.setMinimumSize(QtCore.QSize(0, 40)) self.frame.setFrameShape(QtGui.QFrame.StyledPanel) self.frame.setFrameShadow(QtGui.QFrame.Raised) self.frame.setObjectName("frame") self.horizontalLayout = QtGui.QHBoxLayout(self.frame) self.horizontalLayout.setObjectName("horizontalLayout") self.searchText = QtGui.QLineEdit(self.frame) self.searchText.setObjectName("searchText") self.horizontalLayout.addWidget(self.searchText) self.searchButton = QtGui.QPushButton(self.frame) self.searchButton.setEnabled(True) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(":/static/default/icon/22x22/page-region.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.searchButton.setIcon(icon1) self.searchButton.setCheckable(False) self.searchButton.setChecked(False) self.searchButton.setFlat(False) self.searchButton.setObjectName("searchButton") self.horizontalLayout.addWidget(self.searchButton) self.resetButton = QtGui.QPushButton(self.frame) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(":/static/default/icon/22x22/view-refresh.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.resetButton.setIcon(icon2) self.resetButton.setObjectName("resetButton") self.horizontalLayout.addWidget(self.resetButton) self.verticalLayout.addWidget(self.frame) self.treeWidget = QtGui.QTreeWidget(self.widget) self.treeWidget.setAlternatingRowColors(True) self.treeWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection) self.treeWidget.setAnimated(False) self.treeWidget.setWordWrap(True) self.treeWidget.setHeaderHidden(False) self.treeWidget.setObjectName("treeWidget") self.treeWidget.header().setCascadingSectionResizes(False) self.treeWidget.header().setHighlightSections(False) self.treeWidget.header().setSortIndicatorShown(True) self.verticalLayout.addWidget(self.treeWidget) self.importContainer = QtGui.QWidget(self.splitter_2) self.importContainer.setObjectName("importContainer") self.verticalLayout_4 = QtGui.QVBoxLayout(self.importContainer) self.verticalLayout_4.setSpacing(0) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.verticalLayout_4.setObjectName("verticalLayout_4") self.verticalLayout_2.addWidget(self.splitter_2) self.imageGroupBox = QtGui.QGroupBox(self.splitter) self.imageGroupBox.setTitle("") self.imageGroupBox.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.imageGroupBox.setObjectName("imageGroupBox") self.gridLayout = QtGui.QGridLayout(self.imageGroupBox) self.gridLayout.setObjectName("gridLayout") spacerItem = QtGui.QSpacerItem(27, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 0, 0, 1, 1) self.label = QtGui.QLabel(self.imageGroupBox) self.label.setObjectName("label") self.gridLayout.addWidget(self.label, 0, 1, 1, 1) self.spinBox = QtGui.QSpinBox(self.imageGroupBox) self.spinBox.setMinimumSize(QtCore.QSize(0, 0)) self.spinBox.setMaximumSize(QtCore.QSize(40, 16777215)) self.spinBox.setObjectName("spinBox") self.gridLayout.addWidget(self.spinBox, 0, 2, 1, 1) self.imageViewWidget = QtGui.QFrame(self.imageGroupBox) self.imageViewWidget.setFrameShape(QtGui.QFrame.StyledPanel) self.imageViewWidget.setObjectName("imageViewWidget") self.gridLayout.addWidget(self.imageViewWidget, 1, 0, 1, 3) self.horizontalSlider = QtGui.QSlider(self.imageGroupBox) self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider.setObjectName("horizontalSlider") self.gridLayout.addWidget(self.horizontalSlider, 2, 0, 1, 2) spacerItem1 = QtGui.QSpacerItem(69, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem1, 3, 0, 1, 1) self.importButton = QtGui.QPushButton(self.imageGroupBox) icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(":/static/default/icon/22x22/dialog-ok-apply.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.importButton.setIcon(icon3) self.importButton.setDefault(True) self.importButton.setObjectName("importButton") self.gridLayout.addWidget(self.importButton, 3, 1, 1, 2) self.horizontalLayout_2.addWidget(self.splitter) self.verticalLayout_3.addWidget(self.mainWidget) self.retranslateUi(ImportWindow) QtCore.QMetaObject.connectSlotsByName(ImportWindow) def retranslateUi(self, ImportWindow): ImportWindow.setWindowTitle(QtGui.QApplication.translate("ImportWindow", "Moonstone :: Dicom Importing", None, QtGui.QApplication.UnicodeUTF8)) self.searchButton.setText(QtGui.QApplication.translate("ImportWindow", "Search", None, QtGui.QApplication.UnicodeUTF8)) self.resetButton.setText(QtGui.QApplication.translate("ImportWindow", "Reset", None, QtGui.QApplication.UnicodeUTF8)) self.treeWidget.setSortingEnabled(True) self.treeWidget.headerItem().setText(0, QtGui.QApplication.translate("ImportWindow", "Status", None, QtGui.QApplication.UnicodeUTF8)) self.treeWidget.headerItem().setText(1, QtGui.QApplication.translate("ImportWindow", "Name", None, QtGui.QApplication.UnicodeUTF8)) self.treeWidget.headerItem().setText(2, QtGui.QApplication.translate("ImportWindow", "Sex", None, QtGui.QApplication.UnicodeUTF8)) self.treeWidget.headerItem().setText(3, QtGui.QApplication.translate("ImportWindow", "Age", None, QtGui.QApplication.UnicodeUTF8)) self.treeWidget.headerItem().setText(4, QtGui.QApplication.translate("ImportWindow", "Modality", None, QtGui.QApplication.UnicodeUTF8)) self.treeWidget.headerItem().setText(5, QtGui.QApplication.translate("ImportWindow", "#Images", None, QtGui.QApplication.UnicodeUTF8)) self.treeWidget.headerItem().setText(6, QtGui.QApplication.translate("ImportWindow", "Institution", None, QtGui.QApplication.UnicodeUTF8)) self.treeWidget.headerItem().setText(7, QtGui.QApplication.translate("ImportWindow", "Date of Birth", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("ImportWindow", "Serie:", None, QtGui.QApplication.UnicodeUTF8)) self.importButton.setText(QtGui.QApplication.translate("ImportWindow", "&Load", None, QtGui.QApplication.UnicodeUTF8)) import resources_rc if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) ImportWindow = QtGui.QWidget() ui = Ui_ImportWindow() ui.setupUi(ImportWindow) ImportWindow.show() sys.exit(app.exec_())
CompassionCH/compassion-modules
refs/heads/10.0
mobile_app_connector/forms/registration_form.py
3
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2019 Compassion CH (http://www.compassion.ch) # @author: Sylvain Laydernier <sly.laydernier@yahoo.fr> # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import models, fields, tools, _ from odoo.exceptions import ValidationError import logging import re logger = logging.getLogger(__name__) testing = tools.config.get('test_enable') # prevent these forms to be registered when running tests if not testing: class UserRegistrationForm(models.AbstractModel): """ A form allowing to register an user account and link it to an existing partner """ _name = 'cms.form.res.users' _inherit = ['cms.form.wizard', 'cms.form.match.partner'] _wiz_name = _name form_buttons_template = 'mobile_app_connector.' \ 'mobile_form_buttons_registration' _wiz_step_stored_fields = () def wiz_configure_steps(self): return { 1: {'form_model': 'registration.base.form'}, 2: {'form_model': 'registration.supporter.form'}, 3: {'form_model': 'registration.not.supporter'}, } def wiz_next_step(self): return None def wiz_prev_step(self): return 1 def form_next_url(self, main_object=None): direction = self.request.form.get('wiz_submit', 'next') if direction == 'next': step = self.wiz_next_step() else: step = self.wiz_prev_step() if not step: # validate form return '/registration/confirm' return self._wiz_url_for_step(step, main_object=main_object) def _wiz_base_url(self): return '/registration' @property def form_widgets(self): # GTC field widget res = super(UserRegistrationForm, self).form_widgets res.update({ 'gtc_accept': 'cms_form_compassion.form.widget.terms', 'partner_birthdate': 'cms.form.widget.date.ch', }) return res @property def gtc(self): statement = self.env['compassion.privacy.statement'].sudo().search( [], limit=1) return statement.text @property def form_title(self): return _("Mobile app account registration") ####################################################################### # FORM'S FIELDS VALIDATION # ####################################################################### def _form_validate_partner_email(self, value, **req_values): # check if value is a correct email address if value and not re.match(r'[^@]+@[^@]+\.[^@]+', value): return 'email', _('Verify your e-mail address') # check if the email is already used as login for an account does_login_exists = self.env['res.users'].sudo().search([ ('login', '=', value), ('login_date', '!=', False) ]) if value and does_login_exists: return 'login', _( "This email is already linked to an account.") # No error return 0, 0 def _reactivate_users(self, res_users): """ Reactivate existing users that never connected to Odoo. :param res_users: users recordset :return: None """ res_users.action_reset_password() def _get_portal_user_vals(self, wizard_id, form_values): """ Used to customize the portal wizard values if needed. """ return { 'wizard_id': wizard_id, 'partner_id': form_values['partner_id'], 'email': form_values['email'], 'in_portal': True } def _form_create(self, values): """ Here we create the user using the portal wizard or reactivate existing users that never connected. """ existing_users = self.env['res.users'].sudo().search([ ('login_date', '=', False), '|', ('partner_id', '=', values['partner_id']), ('login', '=', values['email']) ]) if existing_users: self._reactivate_users(existing_users) self.main_object = existing_users[:1] else: wizard = self.env['portal.wizard'].sudo().create({ 'portal_id': self.env['res.groups'].sudo().search([ ('is_portal', '=', True)], limit=1).id }) portal_user = self.env['portal.wizard.user'].sudo().create( self._get_portal_user_vals(wizard.id, values)) portal_user.action_apply() self.main_object = portal_user.user_id def form_after_create_or_update(self, values, extra_values): """ Mark the privacy statement as accepted. """ super(UserRegistrationForm, self).form_after_create_or_update( values, extra_values) if self.form_next_url() == '/registration/confirm': # form submitted partner = self.env['res.partner'].sudo().browse( values.get('partner_id')).exists() partner.set_privacy_statement(origin='mobile_app') def form_check_permission(self): """Always allow access to the form""" return True @property def form_msg_success_created(self): if self.form_next_url() == '/registration/confirm': # form submitted return _( "Your account has been successfully created, you will now " "receive an email to finalize your registration." ) else: # form not submitted (previous) return None def form_validate(self, request_values=None): if self.form_next_url() == '/registration/confirm': # form submitted return super(UserRegistrationForm, self).form_validate( request_values) else: # form not submitted (previous) return 0, 0 def _sanitize_email(self, email): return email.strip().lower() class RegistrationBaseForm(models.AbstractModel): """ Registration form base """ _name = 'registration.base.form' _inherit = 'cms.form.res.users' _nextPage = 1 has_sponsorship = fields.Selection( [('yes', 'Yes'), ('no', 'No')], 'Do you currently sponsor a child?', required=True ) @property def _form_fieldsets(self): fieldset = [ { 'id': 'user', 'fields': [ 'has_sponsorship', ] }, ] return fieldset def wiz_current_step(self): return 1 def wiz_next_step(self): return self._nextPage def wiz_prev_step(self): return None def form_before_create_or_update(self, values, extra_values): if values['has_sponsorship'] == 'yes': self._nextPage = 2 else: self._nextPage = 3 def _form_create(self, values): pass class RegistrationNotSupporter(models.AbstractModel): """ Registration form for new users """ _name = 'registration.not.supporter' _inherit = 'cms.form.res.users' _form_model = 'res.users' _display_type = 'full' gtc_accept = fields.Boolean( "Terms and conditions", required=True ) @property def _form_fieldsets(self): fieldset = [ { 'id': 'partner', 'title': _('Your personal data'), 'fields': [ 'partner_title', 'partner_firstname', 'partner_lastname', 'partner_email', 'partner_street', 'partner_zip', 'partner_city', 'partner_country_id', 'partner_birthdate', 'gtc_accept', ] }, ] return fieldset def wiz_current_step(self): return 3 ####################################################################### # FORM SUBMISSION METHODS # ####################################################################### def form_before_create_or_update(self, values, extra_values): if self.form_next_url() == '/registration/confirm': # form submitted # Forbid update of an existing partner extra_values.update({'skip_update': True}) super(RegistrationNotSupporter, self).form_before_create_or_update(values, extra_values) partner = self.env['res.partner'].sudo().browse( values.get('partner_id')) # partner has already an user linked, add skip user creation # option if any(partner.user_ids.mapped('login_date')): raise ValidationError( _("This email is already linked to an account.")) # Push the email for user creation values['email'] = self._sanitize_email( extra_values['partner_email']) def _form_create(self, values): """ Here we create the user using the portal wizard or reactivate existing users that never connected. """ if self.form_next_url() == '/registration/confirm': super(RegistrationNotSupporter, self)._form_create(values) class RegistrationSupporterForm(models.AbstractModel): """ Registration form for people that are supporters """ _name = 'registration.supporter.form' _inherit = 'cms.form.res.users' _form_model = 'res.users' _form_required_fields = ['partner_email', 'gtc_accept'] _display_type = 'full' gtc_accept = fields.Boolean( "Terms and conditions", required=True ) @property def _form_fieldsets(self): fieldset = [ { 'id': 'partner', 'title': _('Your personal data'), 'fields': [ 'partner_email', 'gtc_accept', ] }, ] return fieldset def wiz_current_step(self): return 2 def form_next_url(self, main_object=None): direction = self.request.form.get('wiz_submit', 'next') if direction == 'next': return '/registration/confirm' else: step = self.wiz_prev_step() if not step: # fallback to page 1 step = 1 return self._wiz_url_for_step(step, main_object=main_object) ####################################################################### # FORM SUBMISSION METHODS # ####################################################################### def form_before_create_or_update(self, values, extra_values): if self.form_next_url() == '/registration/confirm': # form submitted partner_email = self._sanitize_email( extra_values['partner_email']) # Find sponsor given the e-mail partner = self.env['res.partner'].sudo().search([ ('email', 'ilike', partner_email), ('has_sponsorships', '=', True) ]) # partner has already an user linked, add skip user creation # option if any(partner.mapped('user_ids.login_date')): raise ValidationError( _("This email is already linked to an account.")) # partner is not sponsoring a child (but answered yes (form)) if not partner or len(partner) > 1: email_template = self.env.ref( 'mobile_app_connector.email_template_user_not_found')\ .sudo() link_text = _("Click here to send the template email " "request.") to = email_template.email_to subject = email_template.subject body = email_template.body_html.replace( '%(email_address)', partner_email) href_link = self._add_mailto(link_text, to, subject, body) raise ValidationError(_( "We couldn't find your sponsorships. Please contact " "us for setting up your account.") + " " + href_link) # Push the email for user creation values['email'] = partner_email values['partner_id'] = partner.id def _form_create(self, values): """ Here we create the user using the portal wizard or reactivate existing users that never connected. """ if self.form_next_url() == '/registration/confirm': super(RegistrationSupporterForm, self)._form_create(values) def _add_mailto(self, link_text, to, subject, body): subject_mail = subject.replace(' ', '%20') body_mail = body.replace(' ', '%20').replace('\"', '%22').replace( '<br/>', '%0D%0A') return '<a href="mailto:' + to + '?subject=' + subject_mail + \ '&amp;body=' + body_mail + '">' + link_text + '</a>'
pwong-mapr/private-hue
refs/heads/HUE-1096-abe
desktop/core/ext-py/Django-1.4.5/django/utils/regex_helper.py
86
""" Functions for reversing a regular expression (used in reverse URL resolving). Used internally by Django and not intended for external use. This is not, and is not intended to be, a complete reg-exp decompiler. It should be good enough for a large class of URLS, however. """ # Mapping of an escape character to a representative of that class. So, e.g., # "\w" is replaced by "x" in a reverse URL. A value of None means to ignore # this sequence. Any missing key is mapped to itself. ESCAPE_MAPPINGS = { "A": None, "b": None, "B": None, "d": u"0", "D": u"x", "s": u" ", "S": u"x", "w": u"x", "W": u"!", "Z": None, } class Choice(list): """ Used to represent multiple possibilities at this point in a pattern string. We use a distinguished type, rather than a list, so that the usage in the code is clear. """ class Group(list): """ Used to represent a capturing group in the pattern string. """ class NonCapture(list): """ Used to represent a non-capturing group in the pattern string. """ def normalize(pattern): """ Given a reg-exp pattern, normalizes it to a list of forms that suffice for reverse matching. This does the following: (1) For any repeating sections, keeps the minimum number of occurrences permitted (this means zero for optional groups). (2) If an optional group includes parameters, include one occurrence of that group (along with the zero occurrence case from step (1)). (3) Select the first (essentially an arbitrary) element from any character class. Select an arbitrary character for any unordered class (e.g. '.' or '\w') in the pattern. (5) Ignore comments and any of the reg-exp flags that won't change what we construct ("iLmsu"). "(?x)" is an error, however. (6) Raise an error on all other non-capturing (?...) forms (e.g. look-ahead and look-behind matches) and any disjunctive ('|') constructs. Django's URLs for forward resolving are either all positional arguments or all keyword arguments. That is assumed here, as well. Although reverse resolving can be done using positional args when keyword args are specified, the two cannot be mixed in the same reverse() call. """ # Do a linear scan to work out the special features of this pattern. The # idea is that we scan once here and collect all the information we need to # make future decisions. result = [] non_capturing_groups = [] consume_next = True pattern_iter = next_char(iter(pattern)) num_args = 0 # A "while" loop is used here because later on we need to be able to peek # at the next character and possibly go around without consuming another # one at the top of the loop. try: ch, escaped = pattern_iter.next() except StopIteration: return zip([u''], [[]]) try: while True: if escaped: result.append(ch) elif ch == '.': # Replace "any character" with an arbitrary representative. result.append(u".") elif ch == '|': # FIXME: One day we'll should do this, but not in 1.0. raise NotImplementedError elif ch == "^": pass elif ch == '$': break elif ch == ')': # This can only be the end of a non-capturing group, since all # other unescaped parentheses are handled by the grouping # section later (and the full group is handled there). # # We regroup everything inside the capturing group so that it # can be quantified, if necessary. start = non_capturing_groups.pop() inner = NonCapture(result[start:]) result = result[:start] + [inner] elif ch == '[': # Replace ranges with the first character in the range. ch, escaped = pattern_iter.next() result.append(ch) ch, escaped = pattern_iter.next() while escaped or ch != ']': ch, escaped = pattern_iter.next() elif ch == '(': # Some kind of group. ch, escaped = pattern_iter.next() if ch != '?' or escaped: # A positional group name = "_%d" % num_args num_args += 1 result.append(Group(((u"%%(%s)s" % name), name))) walk_to_end(ch, pattern_iter) else: ch, escaped = pattern_iter.next() if ch in "iLmsu#": # All of these are ignorable. Walk to the end of the # group. walk_to_end(ch, pattern_iter) elif ch == ':': # Non-capturing group non_capturing_groups.append(len(result)) elif ch != 'P': # Anything else, other than a named group, is something # we cannot reverse. raise ValueError("Non-reversible reg-exp portion: '(?%s'" % ch) else: ch, escaped = pattern_iter.next() if ch not in ('<', '='): raise ValueError("Non-reversible reg-exp portion: '(?P%s'" % ch) # We are in a named capturing group. Extra the name and # then skip to the end. if ch == '<': terminal_char = '>' # We are in a named backreference. else: terminal_char = ')' name = [] ch, escaped = pattern_iter.next() while ch != terminal_char: name.append(ch) ch, escaped = pattern_iter.next() param = ''.join(name) # Named backreferences have already consumed the # parenthesis. if terminal_char != ')': result.append(Group(((u"%%(%s)s" % param), param))) walk_to_end(ch, pattern_iter) else: result.append(Group(((u"%%(%s)s" % param), None))) elif ch in "*?+{": # Quanitifers affect the previous item in the result list. count, ch = get_quantifier(ch, pattern_iter) if ch: # We had to look ahead, but it wasn't need to compute the # quanitifer, so use this character next time around the # main loop. consume_next = False if count == 0: if contains(result[-1], Group): # If we are quantifying a capturing group (or # something containing such a group) and the minimum is # zero, we must also handle the case of one occurrence # being present. All the quantifiers (except {0,0}, # which we conveniently ignore) that have a 0 minimum # also allow a single occurrence. result[-1] = Choice([None, result[-1]]) else: result.pop() elif count > 1: result.extend([result[-1]] * (count - 1)) else: # Anything else is a literal. result.append(ch) if consume_next: ch, escaped = pattern_iter.next() else: consume_next = True except StopIteration: pass except NotImplementedError: # A case of using the disjunctive form. No results for you! return zip([u''], [[]]) return zip(*flatten_result(result)) def next_char(input_iter): """ An iterator that yields the next character from "pattern_iter", respecting escape sequences. An escaped character is replaced by a representative of its class (e.g. \w -> "x"). If the escaped character is one that is skipped, it is not returned (the next character is returned instead). Yields the next character, along with a boolean indicating whether it is a raw (unescaped) character or not. """ for ch in input_iter: if ch != '\\': yield ch, False continue ch = input_iter.next() representative = ESCAPE_MAPPINGS.get(ch, ch) if representative is None: continue yield representative, True def walk_to_end(ch, input_iter): """ The iterator is currently inside a capturing group. We want to walk to the close of this group, skipping over any nested groups and handling escaped parentheses correctly. """ if ch == '(': nesting = 1 else: nesting = 0 for ch, escaped in input_iter: if escaped: continue elif ch == '(': nesting += 1 elif ch == ')': if not nesting: return nesting -= 1 def get_quantifier(ch, input_iter): """ Parse a quantifier from the input, where "ch" is the first character in the quantifier. Returns the minimum number of occurences permitted by the quantifier and either None or the next character from the input_iter if the next character is not part of the quantifier. """ if ch in '*?+': try: ch2, escaped = input_iter.next() except StopIteration: ch2 = None if ch2 == '?': ch2 = None if ch == '+': return 1, ch2 return 0, ch2 quant = [] while ch != '}': ch, escaped = input_iter.next() quant.append(ch) quant = quant[:-1] values = ''.join(quant).split(',') # Consume the trailing '?', if necessary. try: ch, escaped = input_iter.next() except StopIteration: ch = None if ch == '?': ch = None return int(values[0]), ch def contains(source, inst): """ Returns True if the "source" contains an instance of "inst". False, otherwise. """ if isinstance(source, inst): return True if isinstance(source, NonCapture): for elt in source: if contains(elt, inst): return True return False def flatten_result(source): """ Turns the given source sequence into a list of reg-exp possibilities and their arguments. Returns a list of strings and a list of argument lists. Each of the two lists will be of the same length. """ if source is None: return [u''], [[]] if isinstance(source, Group): if source[1] is None: params = [] else: params = [source[1]] return [source[0]], [params] result = [u''] result_args = [[]] pos = last = 0 for pos, elt in enumerate(source): if isinstance(elt, basestring): continue piece = u''.join(source[last:pos]) if isinstance(elt, Group): piece += elt[0] param = elt[1] else: param = None last = pos + 1 for i in range(len(result)): result[i] += piece if param: result_args[i].append(param) if isinstance(elt, (Choice, NonCapture)): if isinstance(elt, NonCapture): elt = [elt] inner_result, inner_args = [], [] for item in elt: res, args = flatten_result(item) inner_result.extend(res) inner_args.extend(args) new_result = [] new_args = [] for item, args in zip(result, result_args): for i_item, i_args in zip(inner_result, inner_args): new_result.append(item + i_item) new_args.append(args[:] + i_args) result = new_result result_args = new_args if pos >= last: piece = u''.join(source[last:]) for i in range(len(result)): result[i] += piece return result, result_args
vvv1559/intellij-community
refs/heads/master
python/testData/refactoring/extractsuperclass/multifile/target.append.py
83
# existing module A = 1 class Suppa: def foo(self): print "bar"
soldag/home-assistant
refs/heads/dev
tests/components/media_player/common.py
21
"""Collection of helper methods. All containing methods are legacy helpers that should not be used by new components. Instead call the service directly. """ from homeassistant.components.media_player.const import ( ATTR_INPUT_SOURCE, ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_ENQUEUE, ATTR_MEDIA_SEEK_POSITION, ATTR_MEDIA_VOLUME_LEVEL, ATTR_MEDIA_VOLUME_MUTED, DOMAIN, SERVICE_CLEAR_PLAYLIST, SERVICE_PLAY_MEDIA, SERVICE_SELECT_SOURCE, ) from homeassistant.const import ( ATTR_ENTITY_ID, ENTITY_MATCH_ALL, SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PAUSE, SERVICE_MEDIA_PLAY, SERVICE_MEDIA_PLAY_PAUSE, SERVICE_MEDIA_PREVIOUS_TRACK, SERVICE_MEDIA_SEEK, SERVICE_MEDIA_STOP, SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON, SERVICE_VOLUME_DOWN, SERVICE_VOLUME_MUTE, SERVICE_VOLUME_SET, SERVICE_VOLUME_UP, ) from homeassistant.loader import bind_hass async def async_turn_on(hass, entity_id=ENTITY_MATCH_ALL): """Turn on specified media player or all.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_TURN_ON, data, blocking=True) @bind_hass def turn_on(hass, entity_id=ENTITY_MATCH_ALL): """Turn on specified media player or all.""" hass.add_job(async_turn_on, hass, entity_id) async def async_turn_off(hass, entity_id=ENTITY_MATCH_ALL): """Turn off specified media player or all.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_TURN_OFF, data, blocking=True) @bind_hass def turn_off(hass, entity_id=ENTITY_MATCH_ALL): """Turn off specified media player or all.""" hass.add_job(async_turn_off, hass, entity_id) async def async_toggle(hass, entity_id=ENTITY_MATCH_ALL): """Toggle specified media player or all.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_TOGGLE, data, blocking=True) @bind_hass def toggle(hass, entity_id=ENTITY_MATCH_ALL): """Toggle specified media player or all.""" hass.add_job(async_toggle, hass, entity_id) async def async_volume_up(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for volume up.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_VOLUME_UP, data, blocking=True) @bind_hass def volume_up(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for volume up.""" hass.add_job(async_volume_up, hass, entity_id) async def async_volume_down(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for volume down.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_VOLUME_DOWN, data, blocking=True) @bind_hass def volume_down(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for volume down.""" hass.add_job(async_volume_down, hass, entity_id) async def async_mute_volume(hass, mute, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for muting the volume.""" data = {ATTR_MEDIA_VOLUME_MUTED: mute} if entity_id: data[ATTR_ENTITY_ID] = entity_id await hass.services.async_call(DOMAIN, SERVICE_VOLUME_MUTE, data, blocking=True) @bind_hass def mute_volume(hass, mute, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for muting the volume.""" hass.add_job(async_mute_volume, hass, mute, entity_id) async def async_set_volume_level(hass, volume, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for setting the volume.""" data = {ATTR_MEDIA_VOLUME_LEVEL: volume} if entity_id: data[ATTR_ENTITY_ID] = entity_id await hass.services.async_call(DOMAIN, SERVICE_VOLUME_SET, data, blocking=True) @bind_hass def set_volume_level(hass, volume, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for setting the volume.""" hass.add_job(async_set_volume_level, hass, volume, entity_id) async def async_media_play_pause(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for play/pause.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call( DOMAIN, SERVICE_MEDIA_PLAY_PAUSE, data, blocking=True ) @bind_hass def media_play_pause(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for play/pause.""" hass.add_job(async_media_play_pause, hass, entity_id) async def async_media_play(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for play/pause.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_MEDIA_PLAY, data, blocking=True) @bind_hass def media_play(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for play/pause.""" hass.add_job(async_media_play, hass, entity_id) async def async_media_pause(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for pause.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_MEDIA_PAUSE, data, blocking=True) @bind_hass def media_pause(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for pause.""" hass.add_job(async_media_pause, hass, entity_id) async def async_media_stop(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for stop.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_MEDIA_STOP, data, blocking=True) @bind_hass def media_stop(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for stop.""" hass.add_job(async_media_stop, hass, entity_id) async def async_media_next_track(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for next track.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call( DOMAIN, SERVICE_MEDIA_NEXT_TRACK, data, blocking=True ) @bind_hass def media_next_track(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for next track.""" hass.add_job(async_media_next_track, hass, entity_id) async def async_media_previous_track(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for prev track.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call( DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK, data, blocking=True ) @bind_hass def media_previous_track(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for prev track.""" hass.add_job(async_media_previous_track, hass, entity_id) async def async_media_seek(hass, position, entity_id=ENTITY_MATCH_ALL): """Send the media player the command to seek in current playing media.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} data[ATTR_MEDIA_SEEK_POSITION] = position await hass.services.async_call(DOMAIN, SERVICE_MEDIA_SEEK, data, blocking=True) @bind_hass def media_seek(hass, position, entity_id=ENTITY_MATCH_ALL): """Send the media player the command to seek in current playing media.""" hass.add_job(async_media_seek, hass, position, entity_id) async def async_play_media( hass, media_type, media_id, entity_id=ENTITY_MATCH_ALL, enqueue=None ): """Send the media player the command for playing media.""" data = {ATTR_MEDIA_CONTENT_TYPE: media_type, ATTR_MEDIA_CONTENT_ID: media_id} if entity_id: data[ATTR_ENTITY_ID] = entity_id if enqueue: data[ATTR_MEDIA_ENQUEUE] = enqueue await hass.services.async_call(DOMAIN, SERVICE_PLAY_MEDIA, data, blocking=True) @bind_hass def play_media(hass, media_type, media_id, entity_id=ENTITY_MATCH_ALL, enqueue=None): """Send the media player the command for playing media.""" hass.add_job(async_play_media, hass, media_type, media_id, entity_id, enqueue) async def async_select_source(hass, source, entity_id=ENTITY_MATCH_ALL): """Send the media player the command to select input source.""" data = {ATTR_INPUT_SOURCE: source} if entity_id: data[ATTR_ENTITY_ID] = entity_id await hass.services.async_call(DOMAIN, SERVICE_SELECT_SOURCE, data, blocking=True) @bind_hass def select_source(hass, source, entity_id=ENTITY_MATCH_ALL): """Send the media player the command to select input source.""" hass.add_job(async_select_source, hass, source, entity_id) async def async_clear_playlist(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for clear playlist.""" data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} await hass.services.async_call(DOMAIN, SERVICE_CLEAR_PLAYLIST, data, blocking=True) @bind_hass def clear_playlist(hass, entity_id=ENTITY_MATCH_ALL): """Send the media player the command for clear playlist.""" hass.add_job(async_clear_playlist, hass, entity_id)
quasiyoke/router-bot
refs/heads/master
router_bot/human_setup_wizard.py
1
# router-bot # Copyright (C) 2017 quasiyoke # # You should have received a copy of the GNU Affero General Public License v3 # along with this program. If not, see <http://www.gnu.org/licenses/>. import asyncio import logging import re import sys import telepot from .error import MissingPartnerError, UserError from .human_sender_service import HumanSenderService from .wizard import Wizard from telepot.exception import TelegramError LOGGER = logging.getLogger('router_bot.human_setup_wizard') class HumanSetupWizard(Wizard): """Wizard which guides human through process of customizing her parameters. Activates automatically for novices. """ def __init__(self, user): super(HumanSetupWizard, self).__init__() self._user = user self._sender = HumanSenderService.get_instance().get_or_create_human_sender(user) async def activate(self): self._user.wizard = 'setup' self._user.wizard_step = 'languages' self._user.save() await self._prompt() async def deactivate(self): self._user.wizard = 'none' self._user.wizard_step = None self._user.save() try: await self._sender.send_notification( 'Thank you. Use /begin to start looking for a conversational partner, ' 'once you\'re matched you can use /end to end the conversation.', reply_markup={'hide_keyboard': True}, ) except TelegramError as e: LOGGER.warning('Deactivate. Can\'t notify user. %s', e) async def handle(self, message): """ @returns `True` if message was interpreted in this method. `False` if message still needs interpretation. """ if self._user.wizard == 'none': # Wizard isn't active. Check if we should activate it. if self._user.is_novice(): await self.activate() return True else: return False elif self._user.wizard != 'setup': return False try: if self._user.wizard_step == 'languages': pass elif self._user.wizard_step == 'sex': pass elif self._user.wizard_step == 'partner_sex': pass else: LOGGER.warning( 'Undknown wizard_step value was found: \"%s\"', self._user.wizard_step, ) except TelegramError as e: LOGGER.warning('handle() Can not notify user. %s', e) return True async def handle_command(self, message): """ @returns `True` if command was interpreted in this method. `False` if command still needs interpretation. """ if self._user.wizard == 'none': # Wizard isn't active. Check if we should activate it. return (await self.handle(message)) and message.command != 'start' elif self._user.is_full(): if self._user.wizard == 'setup': await self.deactivate() return False else: try: await self._sender.send_notification( 'Finish setup process please. After that you can start using bot.', ) except TelegramError as e: LOGGER.warning('Handle command. Cant notify user. %s', e) await self._prompt() return True async def _prompt(self): wizard_step = self._user.wizard_step try: if wizard_step == 'languages': pass elif wizard_step == 'sex': await self._sender.send_notification( 'Set up your sex. If you pick \"Not Specified\" you can\'t choose ' 'your partner\'s sex.', reply_markup=SEX_KEYBOARD, ) elif wizard_step == 'partner_sex': await self._sender.send_notification( 'Choose your partner\'s sex', reply_markup=SEX_KEYBOARD, ) except TelegramError as e: LOGGER.warning('_prompt() Can not notify user. %s', e)
aguai/TMDLang
refs/heads/master
src/tmd.py
2
#!/usr/local/bin/python3 from pathlib import Path import TMDScanner as Scan import re import sys ''' necessary variables ''' ReservedInstrument = set({'CHORD', 'GROOVE'}) InstrumentSet = set() PartSet = set() Key = 'C' # default key is C Tempo = 120.0 # default tempo 120 SongName = '' # defult no name Signature = [4, 4] # defult to 4/4 PartsContent = [] PartNameList = [] InputFile = '' def FileChecker(ARGV): MarkupTypePattern = r"^\:\:(?P<MarkType>\S+)\:\:\s*?$" if len(ARGV) == 1: print("usage:\n%s InputFile.tmd\n" % ARGV[0]) return False elif not Path(ARGV[1]).is_file(): print("there is no file named %s!" % ARGV[1]) return False elif re.search(MarkupTypePattern, open(ARGV[1], 'r').readline()) is None: print("unknown filetype") return False else: return True def main(): ARGV = sys.argv if not FileChecker(ARGV): sys.exit('File Type Error') InputFile = open(ARGV[1], 'r').read() Key = Scan.KeyGetter(InputFile) Tempo = float(Scan.TempoGetter(InputFile)) Signature = Scan.SignatureGetter(InputFile) SongName = Scan.SongNameGetter(InputFile) PartsContent = Scan.PartContentGetter(InputFile) PartNameList = Scan.PartSequenceGetter(InputFile) PartSet = Scan.PartSetGetter(PartsContent) InstrumentSet = Scan.InstrumentSetGetter(PartsContent) PreDrawChordMsg = Scan.PerChordSymbolAndPosition(PartsContent, Signature) # print(PreDrawChordMsg) for i in PreDrawChordMsg: print('This Part Length: ', i[1]) for j in i[0]: print(j, ':') for k in i[0][j]: # print(k[1], k[0], 'bar behind\n-> \trow:', int(k[0] // 6), '\tcol:', k[0] % 6, # '\n==>', k[0] - (k[0] // 6) * 6) print(k[0], '\n', k[1], 'bar behind->', 'at bar ', str(int(k[0])), '\trow:', int(k[0] // 6), '\tcol:', int(k[0]) % 6) print('\nthe sequence: ', PartNameList) if __name__ == '__main__': main()
matt-kwong/grpc
refs/heads/master
examples/python/helloworld/helloworld_pb2_grpc.py
85
import grpc from grpc.framework.common import cardinality from grpc.framework.interfaces.face import utilities as face_utilities import helloworld_pb2 as helloworld__pb2 class GreeterStub(object): """The greeting service definition. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.SayHello = channel.unary_unary( '/helloworld.Greeter/SayHello', request_serializer=helloworld__pb2.HelloRequest.SerializeToString, response_deserializer=helloworld__pb2.HelloReply.FromString, ) class GreeterServicer(object): """The greeting service definition. """ def SayHello(self, request, context): """Sends a greeting """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_GreeterServicer_to_server(servicer, server): rpc_method_handlers = { 'SayHello': grpc.unary_unary_rpc_method_handler( servicer.SayHello, request_deserializer=helloworld__pb2.HelloRequest.FromString, response_serializer=helloworld__pb2.HelloReply.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'helloworld.Greeter', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
fizzoo/miniprojekt
refs/heads/master
albumartfeh/albumart.py
1
#!/usr/bin/env python3 # Copyright (c) 2015, doggone # Permission to use, copy, modify, and 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. # Most code courtesy of above person, edited to just change the background # Requires python-mpd2 from subprocess import call import mpd, sys import glob, re import signal # Required variables MUSICDIR = "/home/fizzo/musik/" RESETSCRIPT = "/home/fizzo/.fehbg" PATTERN = "front.*" # Looks for albumart according to PATTERN in MUSICDIR/<song's directory>/ def get_albumart(song): albumArt = None if(song != "STOPPED"): aaDir = re.sub(r"[^/]*$", "", song["file"]) for albumArt in glob.glob(glob.escape(MUSICDIR + aaDir) + PATTERN): break return(albumArt) # Returns the currently playing song or "STOPPED" if playback is stopped def get_song(): if(client.status()["state"] == "stop"): return("STOPPED") else: return(client.currentsong()) # Signal handler that resets bg def term_handler(signal, frame): call(RESETSCRIPT) sys.exit(0) # Connect with mpd server try: client = mpd.MPDClient() client.connect("localhost", 6600) except(mpd.ConnectionError): print("Could not connect to MPD. Exiting.") sys.exit(1) # Register signal handler signal.signal(signal.SIGTERM, term_handler) # Monitors mpd for changes and if so, changes image while True: client.idle() #Waits for song change/other albumart = get_albumart(get_song()) if albumart is not None: call(["feh", "--bg-max", "--no-fehbg", albumart]) else: call(["sh", RESETSCRIPT])
jwren/intellij-community
refs/heads/master
python/testData/quickFixes/PyTypeHintsQuickFixTest/parenthesesAndCustomTarget.py
18
from typing import Generic, TypeVar T = TypeVar("T") class A(Generic[T]): def __init__(self, v): pass v2 = None # type: <warning descr="Generics should be specified through square brackets">A<caret>(int)</warning>
ClovisIRex/Snake-django
refs/heads/master
env/lib/python3.6/site-packages/django/contrib/gis/gdal/raster/band.py
108
from ctypes import byref, c_double, c_int, c_void_p from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.error import GDALException from django.contrib.gis.gdal.prototypes import raster as capi from django.contrib.gis.shortcuts import numpy from django.utils import six from django.utils.encoding import force_text from django.utils.six.moves import range from .const import GDAL_INTEGER_TYPES, GDAL_PIXEL_TYPES, GDAL_TO_CTYPES class GDALBand(GDALBase): """ Wraps a GDAL raster band, needs to be obtained from a GDALRaster object. """ def __init__(self, source, index): self.source = source self._ptr = capi.get_ds_raster_band(source._ptr, index) def _flush(self): """ Call the flush method on the Band's parent raster and force a refresh of the statistics attribute when requested the next time. """ self.source._flush() self._stats_refresh = True @property def description(self): """ Returns the description string of the band. """ return force_text(capi.get_band_description(self._ptr)) @property def width(self): """ Width (X axis) in pixels of the band. """ return capi.get_band_xsize(self._ptr) @property def height(self): """ Height (Y axis) in pixels of the band. """ return capi.get_band_ysize(self._ptr) @property def pixel_count(self): """ Returns the total number of pixels in this band. """ return self.width * self.height _stats_refresh = False def statistics(self, refresh=False, approximate=False): """ Compute statistics on the pixel values of this band. The return value is a tuple with the following structure: (minimum, maximum, mean, standard deviation). If approximate=True, the statistics may be computed based on overviews or a subset of image tiles. If refresh=True, the statistics will be computed from the data directly, and the cache will be updated where applicable. For empty bands (where all pixel values are nodata), all statistics values are returned as None. For raster formats using Persistent Auxiliary Metadata (PAM) services, the statistics might be cached in an auxiliary file. """ # Prepare array with arguments for capi function smin, smax, smean, sstd = c_double(), c_double(), c_double(), c_double() stats_args = [ self._ptr, c_int(approximate), byref(smin), byref(smax), byref(smean), byref(sstd), c_void_p(), c_void_p(), ] if refresh or self._stats_refresh: func = capi.compute_band_statistics else: # Add additional argument to force computation if there is no # existing PAM file to take the values from. force = True stats_args.insert(2, c_int(force)) func = capi.get_band_statistics # Computation of statistics fails for empty bands. try: func(*stats_args) result = smin.value, smax.value, smean.value, sstd.value except GDALException: result = (None, None, None, None) self._stats_refresh = False return result @property def min(self): """ Return the minimum pixel value for this band. """ return self.statistics()[0] @property def max(self): """ Return the maximum pixel value for this band. """ return self.statistics()[1] @property def mean(self): """ Return the mean of all pixel values of this band. """ return self.statistics()[2] @property def std(self): """ Return the standard deviation of all pixel values of this band. """ return self.statistics()[3] @property def nodata_value(self): """ Returns the nodata value for this band, or None if it isn't set. """ # Get value and nodata exists flag nodata_exists = c_int() value = capi.get_band_nodata_value(self._ptr, nodata_exists) if not nodata_exists: value = None # If the pixeltype is an integer, convert to int elif self.datatype() in GDAL_INTEGER_TYPES: value = int(value) return value @nodata_value.setter def nodata_value(self, value): """ Sets the nodata value for this band. """ if value is None: if not capi.delete_band_nodata_value: raise ValueError('GDAL >= 2.1 required to delete nodata values.') capi.delete_band_nodata_value(self._ptr) elif not isinstance(value, (int, float)): raise ValueError('Nodata value must be numeric or None.') else: capi.set_band_nodata_value(self._ptr, value) self._flush() def datatype(self, as_string=False): """ Returns the GDAL Pixel Datatype for this band. """ dtype = capi.get_band_datatype(self._ptr) if as_string: dtype = GDAL_PIXEL_TYPES[dtype] return dtype def data(self, data=None, offset=None, size=None, shape=None, as_memoryview=False): """ Reads or writes pixel values for this band. Blocks of data can be accessed by specifying the width, height and offset of the desired block. The same specification can be used to update parts of a raster by providing an array of values. Allowed input data types are bytes, memoryview, list, tuple, and array. """ if not offset: offset = (0, 0) if not size: size = (self.width - offset[0], self.height - offset[1]) if not shape: shape = size if any(x <= 0 for x in size): raise ValueError('Offset too big for this raster.') if size[0] > self.width or size[1] > self.height: raise ValueError('Size is larger than raster.') # Create ctypes type array generator ctypes_array = GDAL_TO_CTYPES[self.datatype()] * (shape[0] * shape[1]) if data is None: # Set read mode access_flag = 0 # Prepare empty ctypes array data_array = ctypes_array() else: # Set write mode access_flag = 1 # Instantiate ctypes array holding the input data if isinstance(data, (bytes, six.memoryview)) or (numpy and isinstance(data, numpy.ndarray)): data_array = ctypes_array.from_buffer_copy(data) else: data_array = ctypes_array(*data) # Access band capi.band_io(self._ptr, access_flag, offset[0], offset[1], size[0], size[1], byref(data_array), shape[0], shape[1], self.datatype(), 0, 0) # Return data as numpy array if possible, otherwise as list if data is None: if as_memoryview: return memoryview(data_array) elif numpy: # reshape() needs a reshape parameter with the height first. return numpy.frombuffer( data_array, dtype=numpy.dtype(data_array) ).reshape(tuple(reversed(size))) else: return list(data_array) else: self._flush() class BandList(list): def __init__(self, source): self.source = source list.__init__(self) def __iter__(self): for idx in range(1, len(self) + 1): yield GDALBand(self.source, idx) def __len__(self): return capi.get_ds_raster_count(self.source._ptr) def __getitem__(self, index): try: return GDALBand(self.source, index + 1) except GDALException: raise GDALException('Unable to get band index %d' % index)
savioabuga/phoenix-template
refs/heads/master
phoenix/apps/utils/test_utils.py
1
from model_mommy import mommy def login_user(test_case, user, password): test_case.client.logout() test_case.client.login(username=user.username, password=password) def create_logged_in_user(test_case, username='mary', password='marypassword'): user = mommy.make('auth.User') user.username = username user.set_password(password) user.save() login_user(test_case, user, password) return user
stahlnow/paulhaller
refs/heads/master
website/apps/website/views.py
1
from endless_pagination.views import AjaxListView from django.views.generic import ListView, DetailView from django.utils import timezone from .models import Post, Poem, Letter class PostListView(AjaxListView): model = Post queryset = Post.objects.all() context_object_name = "posts" def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['now'] = timezone.now() return context class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) return context class PoemListView(ListView): model = Poem queryset = Poem.objects.all() context_object_name = "poems" def get_context_data(self, **kwargs): context = super(PoemListView, self).get_context_data(**kwargs) context['now'] = timezone.now() return context class PoemDetailView(DetailView): model = Poem def get_context_data(self, **kwargs): context = super(PoemDetailView, self).get_context_data(**kwargs) context['poems'] = Poem.objects.all() return context class LetterListView(ListView): model = Letter queryset = Letter.objects.all() context_object_name = "letters" def get_context_data(self, **kwargs): context = super(LetterListView, self).get_context_data(**kwargs) context['now'] = timezone.now() return context class LetterDetailView(DetailView): model = Letter def get_context_data(self, **kwargs): context = super(LetterDetailView, self).get_context_data(**kwargs) context['letters'] = Letter.objects.all() return context
lihui7115/ChromiumGStreamerBackend
refs/heads/master
third_party/cython/src/setupegg.py
97
#!/usr/bin/env python """Wrapper to run setup.py using setuptools.""" import setuptools execfile('setup.py')
nishad-jobsglobal/odoo-marriot
refs/heads/master
addons/mrp_repair/wizard/cancel_repair.py
384
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import osv,fields from openerp.tools.translate import _ class repair_cancel(osv.osv_memory): _name = 'mrp.repair.cancel' _description = 'Cancel Repair' def cancel_repair(self, cr, uid, ids, context=None): """ Cancels the repair @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary @return: """ if context is None: context = {} record_id = context and context.get('active_id', False) or False assert record_id, _('Active ID not Found') repair_order_obj = self.pool.get('mrp.repair') repair_line_obj = self.pool.get('mrp.repair.line') repair_order = repair_order_obj.browse(cr, uid, record_id, context=context) if repair_order.invoiced or repair_order.invoice_method == 'none': repair_order_obj.action_cancel(cr, uid, [record_id], context=context) else: raise osv.except_osv(_('Warning!'),_('Repair order is not invoiced.')) return {'type': 'ir.actions.act_window_close'} def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): """ Changes the view dynamically @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return: New arch of view. """ if context is None: context = {} res = super(repair_cancel, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar,submenu=False) record_id = context and context.get('active_id', False) or False active_model = context.get('active_model') if not record_id or (active_model and active_model != 'mrp.repair'): return res repair_order = self.pool.get('mrp.repair').browse(cr, uid, record_id, context=context) if not repair_order.invoiced: res['arch'] = """ <form string="Cancel Repair" version="7.0"> <header> <button name="cancel_repair" string="_Yes" type="object" class="oe_highlight"/> or <button string="Cancel" class="oe_link" special="cancel"/> </header> <label string="Do you want to continue?"/> </form> """ return res # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
xujb/odoo
refs/heads/8.0
addons/website_hr_recruitment/models/__init__.py
390
import hr_job
santels/raspberry-dsp
refs/heads/master
src/voice_processor-google.py
1
#!/usr/bin/env python3 import speech_recognition as sr recognizer = sr.Recognizer(); with sr.Microphone() as mic: print("Go say something! I'm listening..."); audio = recognizer.listen(mic); try: print("You said: '" + recognizer.recognize_google(audio)); except sr.UnknownValueError: print("Sorry. I can't understand ya."); except sr.RequestError as e: print("Sphinx error: {0}".format(e))
paninetworks/neutron
refs/heads/master
neutron/tests/unit/agent/metadata/test_namespace_proxy.py
21
# Copyright 2012 New Dream Network, LLC (DreamHost) # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock import testtools import webob from neutron.agent.linux import utils as agent_utils from neutron.agent.metadata import namespace_proxy as ns_proxy from neutron.common import exceptions from neutron.common import utils from neutron.tests import base class FakeConf(object): admin_user = 'neutron' admin_password = 'password' admin_tenant_name = 'tenant' auth_url = 'http://127.0.0.1' auth_strategy = 'keystone' auth_region = 'region' nova_metadata_ip = '9.9.9.9' nova_metadata_port = 8775 metadata_proxy_shared_secret = 'secret' class TestNetworkMetadataProxyHandler(base.BaseTestCase): def setUp(self): super(TestNetworkMetadataProxyHandler, self).setUp() self.log_p = mock.patch.object(ns_proxy, 'LOG') self.log = self.log_p.start() self.handler = ns_proxy.NetworkMetadataProxyHandler('router_id') def test_call(self): req = mock.Mock(headers={}) with mock.patch.object(self.handler, '_proxy_request') as proxy_req: proxy_req.return_value = 'value' retval = self.handler(req) self.assertEqual(retval, 'value') proxy_req.assert_called_once_with(req.remote_addr, req.method, req.path_info, req.query_string, req.body) def test_no_argument_passed_to_init(self): with testtools.ExpectedException( exceptions.NetworkIdOrRouterIdRequiredError): ns_proxy.NetworkMetadataProxyHandler() def test_call_internal_server_error(self): req = mock.Mock(headers={}) with mock.patch.object(self.handler, '_proxy_request') as proxy_req: proxy_req.side_effect = Exception retval = self.handler(req) self.assertIsInstance(retval, webob.exc.HTTPInternalServerError) self.assertEqual(len(self.log.mock_calls), 2) self.assertTrue(proxy_req.called) def test_proxy_request_router_200(self): self.handler.router_id = 'router_id' resp = mock.MagicMock(status=200) with mock.patch('httplib2.Http') as mock_http: resp.__getitem__.return_value = "text/plain" mock_http.return_value.request.return_value = (resp, 'content') retval = self.handler._proxy_request('192.168.1.1', 'GET', '/latest/meta-data', '', '') mock_http.assert_has_calls([ mock.call().request( 'http://169.254.169.254/latest/meta-data', method='GET', headers={ 'X-Forwarded-For': '192.168.1.1', 'X-Neutron-Router-ID': 'router_id' }, connection_type=agent_utils.UnixDomainHTTPConnection, body='' )] ) self.assertEqual(retval.headers['Content-Type'], 'text/plain') self.assertEqual(retval.body, 'content') def test_proxy_request_network_200(self): self.handler.network_id = 'network_id' resp = mock.MagicMock(status=200) with mock.patch('httplib2.Http') as mock_http: resp.__getitem__.return_value = "application/json" mock_http.return_value.request.return_value = (resp, '{}') retval = self.handler._proxy_request('192.168.1.1', 'GET', '/latest/meta-data', '', '') mock_http.assert_has_calls([ mock.call().request( 'http://169.254.169.254/latest/meta-data', method='GET', headers={ 'X-Forwarded-For': '192.168.1.1', 'X-Neutron-Network-ID': 'network_id' }, connection_type=agent_utils.UnixDomainHTTPConnection, body='' )] ) self.assertEqual(retval.headers['Content-Type'], 'application/json') self.assertEqual(retval.body, '{}') def _test_proxy_request_network_4xx(self, status, method, expected): self.handler.network_id = 'network_id' resp = mock.Mock(status=status) with mock.patch('httplib2.Http') as mock_http: mock_http.return_value.request.return_value = (resp, '') retval = self.handler._proxy_request('192.168.1.1', method, '/latest/meta-data', '', '') mock_http.assert_has_calls([ mock.call().request( 'http://169.254.169.254/latest/meta-data', method=method, headers={ 'X-Forwarded-For': '192.168.1.1', 'X-Neutron-Network-ID': 'network_id' }, connection_type=agent_utils.UnixDomainHTTPConnection, body='' )] ) self.assertIsInstance(retval, expected) def test_proxy_request_network_400(self): self._test_proxy_request_network_4xx( 400, 'GET', webob.exc.HTTPBadRequest) def test_proxy_request_network_404(self): self._test_proxy_request_network_4xx( 404, 'GET', webob.exc.HTTPNotFound) def test_proxy_request_network_409(self): self._test_proxy_request_network_4xx( 409, 'POST', webob.exc.HTTPConflict) def test_proxy_request_network_500(self): self.handler.network_id = 'network_id' resp = mock.Mock(status=500) with mock.patch('httplib2.Http') as mock_http: mock_http.return_value.request.return_value = (resp, '') retval = self.handler._proxy_request('192.168.1.1', 'GET', '/latest/meta-data', '', '') mock_http.assert_has_calls([ mock.call().request( 'http://169.254.169.254/latest/meta-data', method='GET', headers={ 'X-Forwarded-For': '192.168.1.1', 'X-Neutron-Network-ID': 'network_id' }, connection_type=agent_utils.UnixDomainHTTPConnection, body='' )] ) self.assertIsInstance(retval, webob.exc.HTTPInternalServerError) def test_proxy_request_network_418(self): self.handler.network_id = 'network_id' resp = mock.Mock(status=418) with mock.patch('httplib2.Http') as mock_http: mock_http.return_value.request.return_value = (resp, '') with testtools.ExpectedException(Exception): self.handler._proxy_request('192.168.1.1', 'GET', '/latest/meta-data', '', '') mock_http.assert_has_calls([ mock.call().request( 'http://169.254.169.254/latest/meta-data', method='GET', headers={ 'X-Forwarded-For': '192.168.1.1', 'X-Neutron-Network-ID': 'network_id' }, connection_type=agent_utils.UnixDomainHTTPConnection, body='' )] ) def test_proxy_request_network_exception(self): self.handler.network_id = 'network_id' mock.Mock(status=500) with mock.patch('httplib2.Http') as mock_http: mock_http.return_value.request.side_effect = Exception with testtools.ExpectedException(Exception): self.handler._proxy_request('192.168.1.1', 'GET', '/latest/meta-data', '', '') mock_http.assert_has_calls([ mock.call().request( 'http://169.254.169.254/latest/meta-data', method='GET', headers={ 'X-Forwarded-For': '192.168.1.1', 'X-Neutron-Network-ID': 'network_id' }, connection_type=agent_utils.UnixDomainHTTPConnection, body='' )] ) class TestProxyDaemon(base.BaseTestCase): def test_init(self): with mock.patch('neutron.agent.linux.daemon.Pidfile'): pd = ns_proxy.ProxyDaemon('pidfile', 9697, 'net_id', 'router_id') self.assertEqual(pd.router_id, 'router_id') self.assertEqual(pd.network_id, 'net_id') def test_run(self): with mock.patch('neutron.agent.linux.daemon.Pidfile'): with mock.patch('neutron.wsgi.Server') as Server: pd = ns_proxy.ProxyDaemon('pidfile', 9697, 'net_id', 'router_id') pd.run() Server.assert_has_calls([ mock.call('neutron-network-metadata-proxy'), mock.call().start(mock.ANY, 9697), mock.call().wait()] ) def test_main(self): with mock.patch.object(ns_proxy, 'ProxyDaemon') as daemon: with mock.patch.object(ns_proxy, 'config') as config: with mock.patch.object(ns_proxy, 'cfg') as cfg: with mock.patch.object(utils, 'cfg') as utils_cfg: cfg.CONF.router_id = 'router_id' cfg.CONF.network_id = None cfg.CONF.metadata_port = 9697 cfg.CONF.pid_file = 'pidfile' cfg.CONF.daemonize = True utils_cfg.CONF.log_opt_values.return_value = None ns_proxy.main() self.assertTrue(config.setup_logging.called) daemon.assert_has_calls([ mock.call('pidfile', 9697, router_id='router_id', network_id=None, user=mock.ANY, group=mock.ANY, watch_log=mock.ANY), mock.call().start()] ) def test_main_dont_fork(self): with mock.patch.object(ns_proxy, 'ProxyDaemon') as daemon: with mock.patch.object(ns_proxy, 'config') as config: with mock.patch.object(ns_proxy, 'cfg') as cfg: with mock.patch.object(utils, 'cfg') as utils_cfg: cfg.CONF.router_id = 'router_id' cfg.CONF.network_id = None cfg.CONF.metadata_port = 9697 cfg.CONF.pid_file = 'pidfile' cfg.CONF.daemonize = False utils_cfg.CONF.log_opt_values.return_value = None ns_proxy.main() self.assertTrue(config.setup_logging.called) daemon.assert_has_calls([ mock.call('pidfile', 9697, router_id='router_id', network_id=None, user=mock.ANY, group=mock.ANY, watch_log=mock.ANY), mock.call().run()] )
keedio/hue
refs/heads/master
desktop/core/ext-py/Django-1.6.10/django/conf/__init__.py
106
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import logging import os import sys import time # Needed for Windows import warnings from django.conf import global_settings from django.core.exceptions import ImproperlyConfigured from django.utils.functional import LazyObject, empty from django.utils import importlib from django.utils.module_loading import import_by_path from django.utils import six ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE" class LazySettings(LazyObject): """ A lazy proxy for either global Django settings or a custom settings object. The user can manually configure settings prior to using them. Otherwise, Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE. """ def _setup(self, name=None): """ Load the settings module pointed to by the environment variable. This is used the first time we need any settings at all, if the user has not previously configured the settings manually. """ try: settings_module = os.environ[ENVIRONMENT_VARIABLE] if not settings_module: # If it's set but is an empty string. raise KeyError except KeyError: desc = ("setting %s" % name) if name else "settings" raise ImproperlyConfigured( "Requested %s, but settings are not configured. " "You must either define the environment variable %s " "or call settings.configure() before accessing settings." % (desc, ENVIRONMENT_VARIABLE)) self._wrapped = Settings(settings_module) self._configure_logging() def __getattr__(self, name): if self._wrapped is empty: self._setup(name) return getattr(self._wrapped, name) def _configure_logging(self): """ Setup logging from LOGGING_CONFIG and LOGGING settings. """ if not sys.warnoptions: try: # Route warnings through python logging logging.captureWarnings(True) # Allow DeprecationWarnings through the warnings filters warnings.simplefilter("default", DeprecationWarning) except AttributeError: # No captureWarnings on Python 2.6, DeprecationWarnings are on anyway pass if self.LOGGING_CONFIG: from django.utils.log import DEFAULT_LOGGING # First find the logging configuration function ... logging_config_func = import_by_path(self.LOGGING_CONFIG) logging_config_func(DEFAULT_LOGGING) # ... then invoke it with the logging settings if self.LOGGING: logging_config_func(self.LOGGING) def configure(self, default_settings=global_settings, **options): """ Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)). """ if self._wrapped is not empty: raise RuntimeError('Settings already configured.') holder = UserSettingsHolder(default_settings) for name, value in options.items(): setattr(holder, name, value) self._wrapped = holder self._configure_logging() @property def configured(self): """ Returns True if the settings have already been configured. """ return self._wrapped is not empty class BaseSettings(object): """ Common logic for settings whether set by a module or by the user. """ def __setattr__(self, name, value): if name in ("MEDIA_URL", "STATIC_URL") and value and not value.endswith('/'): raise ImproperlyConfigured("If set, %s must end with a slash" % name) elif name == "ALLOWED_INCLUDE_ROOTS" and isinstance(value, six.string_types): raise ValueError("The ALLOWED_INCLUDE_ROOTS setting must be set " "to a tuple, not a string.") object.__setattr__(self, name, value) class Settings(BaseSettings): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting == setting.upper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module try: mod = importlib.import_module(self.SETTINGS_MODULE) except ImportError as e: raise ImportError( "Could not import settings '%s' (Is it on sys.path? Is there an import error in the settings file?): %s" % (self.SETTINGS_MODULE, e) ) # Settings that should be converted into tuples if they're mistakenly entered # as strings. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS") for setting in dir(mod): if setting == setting.upper(): setting_value = getattr(mod, setting) if setting in tuple_settings and \ isinstance(setting_value, six.string_types): warnings.warn("The %s setting must be a tuple. Please fix your " "settings, as auto-correction is now deprecated." % setting, DeprecationWarning, stacklevel=2) setting_value = (setting_value,) # In case the user forgot the comma. setattr(self, setting, setting_value) if not self.SECRET_KEY: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") if hasattr(time, 'tzset') and self.TIME_ZONE: # When we can, attempt to validate the timezone. If we can't find # this file, no check happens and it's harmless. zoneinfo_root = '/usr/share/zoneinfo' if (os.path.exists(zoneinfo_root) and not os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))): raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE) # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ['TZ'] = self.TIME_ZONE time.tzset() class UserSettingsHolder(BaseSettings): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.__dict__['_deleted'] = set() self.default_settings = default_settings def __getattr__(self, name): if name in self._deleted: raise AttributeError return getattr(self.default_settings, name) def __setattr__(self, name, value): self._deleted.discard(name) return super(UserSettingsHolder, self).__setattr__(name, value) def __delattr__(self, name): self._deleted.add(name) return super(UserSettingsHolder, self).__delattr__(name) def __dir__(self): return list(self.__dict__) + dir(self.default_settings) settings = LazySettings()
askeing/servo
refs/heads/master
tests/wpt/web-platform-tests/tools/wptserve/wptserve/stash.py
13
import base64 import json import os import uuid import threading from multiprocessing.managers import AcquirerProxy, BaseManager, DictProxy class ServerDictManager(BaseManager): shared_data = {} def _get_shared(): return ServerDictManager.shared_data ServerDictManager.register("get_dict", callable=_get_shared, proxytype=DictProxy) ServerDictManager.register('Lock', threading.Lock, AcquirerProxy) class ClientDictManager(BaseManager): pass ClientDictManager.register("get_dict") ClientDictManager.register("Lock") class StashServer(object): def __init__(self, address=None, authkey=None): self.address = address self.authkey = authkey self.manager = None def __enter__(self): self.manager, self.address, self.authkey = start_server(self.address, self.authkey) store_env_config(self.address, self.authkey) def __exit__(self, *args, **kwargs): if self.manager is not None: self.manager.shutdown() def load_env_config(): address, authkey = json.loads(os.environ["WPT_STASH_CONFIG"]) if isinstance(address, list): address = tuple(address) else: address = str(address) authkey = base64.decodestring(authkey) return address, authkey def store_env_config(address, authkey): authkey = base64.encodestring(authkey) os.environ["WPT_STASH_CONFIG"] = json.dumps((address, authkey)) def start_server(address=None, authkey=None): manager = ServerDictManager(address, authkey) manager.start() return (manager, manager._address, manager._authkey) class LockWrapper(object): def __init__(self, lock): self.lock = lock def acquire(self): self.lock.acquire() def release(self): self.lock.release() def __enter__(self): self.acquire() def __exit__(self, *args, **kwargs): self.release() #TODO: Consider expiring values after some fixed time for long-running #servers class Stash(object): """Key-value store for persisting data across HTTP/S and WS/S requests. This data store is specifically designed for persisting data across server requests. The synchronization is achieved by using the BaseManager from the multiprocessing module so different processes can acccess the same data. Stash can be used interchangeably between HTTP, HTTPS, WS and WSS servers. A thing to note about WS/S servers is that they require additional steps in the handlers for accessing the same underlying shared data in the Stash. This can usually be achieved by using load_env_config(). When using Stash interchangeably between HTTP/S and WS/S request, the path part of the key should be expliclitly specified if accessing the same key/value subset. The store has several unusual properties. Keys are of the form (path, uuid), where path is, by default, the path in the HTTP request and uuid is a unique id. In addition, the store is write-once, read-once, i.e. the value associated with a particular key cannot be changed once written and the read operation (called "take") is destructive. Taken together, these properties make it difficult for data to accidentally leak between different resources or different requests for the same resource. """ _proxy = None lock = None def __init__(self, default_path, address=None, authkey=None): self.default_path = default_path self._get_proxy(address, authkey) self.data = Stash._proxy def _get_proxy(self, address=None, authkey=None): if address is None and authkey is None: Stash._proxy = {} Stash.lock = threading.Lock() if Stash._proxy is None: manager = ClientDictManager(address, authkey) manager.connect() Stash._proxy = manager.get_dict() Stash.lock = LockWrapper(manager.Lock()) def _wrap_key(self, key, path): if path is None: path = self.default_path # This key format is required to support using the path. Since the data # passed into the stash can be a DictProxy which wouldn't detect changes # when writing to a subdict. return (str(path), str(uuid.UUID(key))) def put(self, key, value, path=None): """Place a value in the shared stash. :param key: A UUID to use as the data's key. :param value: The data to store. This can be any python object. :param path: The path that has access to read the data (by default the current request path)""" if value is None: raise ValueError("SharedStash value may not be set to None") internal_key = self._wrap_key(key, path) if internal_key in self.data: raise StashError("Tried to overwrite existing shared stash value " "for key %s (old value was %s, new value is %s)" % (internal_key, self.data[str(internal_key)], value)) else: self.data[internal_key] = value def take(self, key, path=None): """Remove a value from the shared stash and return it. :param key: A UUID to use as the data's key. :param path: The path that has access to read the data (by default the current request path)""" internal_key = self._wrap_key(key, path) value = self.data.get(internal_key, None) if value is not None: try: self.data.pop(internal_key) except KeyError: # Silently continue when pop error occurs. pass return value class StashError(Exception): pass
amyshi188/osf.io
refs/heads/develop
manage.py
9
#!/usr/bin/env python import sys if __name__ == '__main__': from django.core.management import execute_from_command_line # allow the osf app/model initialization to be skipped so we can run django # commands like collectstatic w/o requiring a database to be running if '--no-init-app' in sys.argv: sys.argv.remove('--no-init-app') else: from website.app import init_app init_app(set_backends=True, routes=False, attach_request_handlers=False) execute_from_command_line(sys.argv)
andrewyoung1991/supriya
refs/heads/master
supriya/tools/servertools/test/test_Node__handle_response.py
1
# -*- encoding: utf-8 -*- import pytest import pytest from abjad.tools import systemtools from supriya import synthdefs from supriya.tools import osctools from supriya.tools import servertools @pytest.fixture(scope='function') def server(request): def server_teardown(): server.quit() server = servertools.Server().boot() server.debug_osc = True request.addfinalizer(server_teardown) return server def test_Node__handle_response_01(server): group_a = servertools.Group().allocate() group_b = servertools.Group().allocate() synth_a = servertools.Synth(synthdefs.test) synth_b = servertools.Synth(synthdefs.test) group_a.append(synth_a) group_b.append(synth_b) remote_state = str(server.query_remote_nodes()) assert systemtools.TestManager.compare( remote_state, ''' NODE TREE 0 group 1 group 1001 group 1003 test 1000 group 1002 test ''', ), remote_state local_state = str(server.query_local_nodes()) assert local_state == remote_state osc_message = osctools.OscMessage( '/n_after', synth_b.node_id, synth_a.node_id, ) server.send_message(osc_message) remote_state = str(server.query_remote_nodes()) assert systemtools.TestManager.compare( remote_state, ''' NODE TREE 0 group 1 group 1001 group 1000 group 1002 test 1003 test ''', ), remote_state local_state = str(server.query_local_nodes()) assert local_state == remote_state osc_message = osctools.OscMessage( '/n_order', 0, group_b.node_id, synth_b.node_id, synth_a.node_id, ) server.send_message(osc_message) remote_state = str(server.query_remote_nodes()) assert systemtools.TestManager.compare( remote_state, ''' NODE TREE 0 group 1 group 1001 group 1003 test 1002 test 1000 group ''', ), remote_state local_state = str(server.query_local_nodes()) assert local_state == remote_state
nikolas/edx-platform
refs/heads/master
common/djangoapps/third_party_auth/tests/specs/base.py
27
"""Base integration test for provider implementations.""" import unittest import json import mock from django import test from django.contrib import auth from django.contrib.auth import models as auth_models from django.contrib.messages.storage import fallback from django.contrib.sessions.backends import cache from django.test import utils as django_utils from django.conf import settings as django_settings from edxmako.tests import mako_middleware_process_request from social import actions, exceptions from social.apps.django_app import utils as social_utils from social.apps.django_app import views as social_views from student import models as student_models from student import views as student_views from student_account.views import account_settings_context from third_party_auth import middleware, pipeline from third_party_auth import settings as auth_settings from third_party_auth.tests import testutil @unittest.skipUnless( testutil.AUTH_FEATURES_KEY in django_settings.FEATURES, testutil.AUTH_FEATURES_KEY + ' not in settings.FEATURES') @django_utils.override_settings() # For settings reversion on a method-by-method basis. class IntegrationTest(testutil.TestCase, test.TestCase): """Abstract base class for provider integration tests.""" # Override setUp and set this: provider = None # Methods you must override in your children. def get_response_data(self): """Gets a dict of response data of the form given by the provider. To determine what the provider returns, drop into a debugger in your provider's do_auth implementation. Providers may merge different kinds of data (for example, data about the user and data about the user's credentials). """ raise NotImplementedError def get_username(self): """Gets username based on response data from a provider. Each provider has different logic for username generation. Sadly, this is not extracted into its own method in python-social-auth, so we must provide a getter ourselves. Note that this is the *initial* value the framework will attempt to use. If it collides, the pipeline will generate a new username. We extract it here so we can force collisions in a polymorphic way. """ raise NotImplementedError # Asserts you can optionally override and make more specific. def assert_redirect_to_provider_looks_correct(self, response): """Asserts the redirect to the provider's site looks correct. When we hit /auth/login/<provider>, we should be redirected to the provider's site. Here we check that we're redirected, but we don't know enough about the provider to check what we're redirected to. Child test implementations may optionally strengthen this assertion with, for example, more details about the format of the Location header. """ self.assertEqual(302, response.status_code) self.assertTrue(response.has_header('Location')) def assert_register_response_in_pipeline_looks_correct(self, response, pipeline_kwargs): """Performs spot checks of the rendered register.html page. When we display the new account registration form after the user signs in with a third party, we prepopulate the form with values sent back from the provider. The exact set of values varies on a provider-by- provider basis and is generated by provider.BaseProvider.get_register_form_data. We provide some stock assertions based on the provider's implementation; if you want more assertions in your test, override this method. """ self.assertEqual(200, response.status_code) # Check that the correct provider was selected. self.assertIn('successfully signed in with <strong>%s</strong>' % self.provider.name, response.content) # Expect that each truthy value we've prepopulated the register form # with is actually present. for prepopulated_form_value in self.provider.get_register_form_data(pipeline_kwargs).values(): if prepopulated_form_value: self.assertIn(prepopulated_form_value, response.content) # Implementation details and actual tests past this point -- no more # configuration needed. def setUp(self): super(IntegrationTest, self).setUp() self.request_factory = test.RequestFactory() @property def backend_name(self): """ Shortcut for the backend name """ return self.provider.backend_name # pylint: disable=invalid-name def assert_account_settings_context_looks_correct(self, context, _user, duplicate=False, linked=None): """Asserts the user's account settings page context is in the expected state. If duplicate is True, we expect context['duplicate_provider'] to contain the duplicate provider backend name. If linked is passed, we conditionally check that the provider is included in context['auth']['providers'] and its connected state is correct. """ if duplicate: self.assertEqual(context['duplicate_provider'], self.provider.backend_name) else: self.assertIsNone(context['duplicate_provider']) if linked is not None: expected_provider = [ provider for provider in context['auth']['providers'] if provider['name'] == self.provider.name ][0] self.assertIsNotNone(expected_provider) self.assertEqual(expected_provider['connected'], linked) def assert_exception_redirect_looks_correct(self, expected_uri, auth_entry=None): """Tests middleware conditional redirection. middleware.ExceptionMiddleware makes sure the user ends up in the right place when they cancel authentication via the provider's UX. """ exception_middleware = middleware.ExceptionMiddleware() request, _ = self.get_request_and_strategy(auth_entry=auth_entry) response = exception_middleware.process_exception( request, exceptions.AuthCanceled(request.backend)) location = response.get('Location') self.assertEqual(302, response.status_code) self.assertIn('canceled', location) self.assertIn(self.backend_name, location) self.assertTrue(location.startswith(expected_uri + '?')) def assert_first_party_auth_trumps_third_party_auth(self, email=None, password=None, success=None): """Asserts first party auth was used in place of third party auth. Args: email: string. The user's email. If not None, will be set on POST. password: string. The user's password. If not None, will be set on POST. success: None or bool. Whether we expect auth to be successful. Set to None to indicate we expect the request to be invalid (meaning one of username or password will be missing). """ _, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete') strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) self.create_user_models_for_existing_account( strategy, email, password, self.get_username(), skip_social_auth=True) strategy.request.POST = dict(strategy.request.POST) if email: strategy.request.POST['email'] = email if password: strategy.request.POST['password'] = 'bad_' + password if success is False else password self.assert_pipeline_running(strategy.request) payload = json.loads(student_views.login_user(strategy.request).content) if success is None: # Request malformed -- just one of email/password given. self.assertFalse(payload.get('success')) self.assertIn('There was an error receiving your login information', payload.get('value')) elif success: # Request well-formed and credentials good. self.assertTrue(payload.get('success')) else: # Request well-formed but credentials bad. self.assertFalse(payload.get('success')) self.assertIn('incorrect', payload.get('value')) def assert_json_failure_response_is_inactive_account(self, response): """Asserts failure on /login for inactive account looks right.""" self.assertEqual(200, response.status_code) # Yes, it's a 200 even though it's a failure. payload = json.loads(response.content) self.assertFalse(payload.get('success')) self.assertIn('This account has not been activated', payload.get('value')) def assert_json_failure_response_is_missing_social_auth(self, response): """Asserts failure on /login for missing social auth looks right.""" self.assertEqual(403, response.status_code) self.assertIn( "successfully logged into your %s account, but this account isn't linked" % self.provider.name, response.content ) def assert_json_failure_response_is_username_collision(self, response): """Asserts the json response indicates a username collision.""" self.assertEqual(400, response.status_code) payload = json.loads(response.content) self.assertFalse(payload.get('success')) self.assertIn('already exists', payload.get('value')) def assert_json_success_response_looks_correct(self, response): """Asserts the json response indicates success and redirection.""" self.assertEqual(200, response.status_code) payload = json.loads(response.content) self.assertTrue(payload.get('success')) self.assertEqual(pipeline.get_complete_url(self.provider.backend_name), payload.get('redirect_url')) def assert_login_response_before_pipeline_looks_correct(self, response): """Asserts a GET of /login not in the pipeline looks correct.""" self.assertEqual(200, response.status_code) # The combined login/registration page dynamically generates the login button, # but we can still check that the provider name is passed in the data attribute # for the container element. self.assertIn(self.provider.name, response.content) def assert_login_response_in_pipeline_looks_correct(self, response): """Asserts a GET of /login in the pipeline looks correct.""" self.assertEqual(200, response.status_code) def assert_password_overridden_by_pipeline(self, username, password): """Verifies that the given password is not correct. The pipeline overrides POST['password'], if any, with random data. """ self.assertIsNone(auth.authenticate(password=password, username=username)) def assert_pipeline_running(self, request): """Makes sure the given request is running an auth pipeline.""" self.assertTrue(pipeline.running(request)) def assert_redirect_to_dashboard_looks_correct(self, response): """Asserts a response would redirect to /dashboard.""" self.assertEqual(302, response.status_code) # pylint: disable=protected-access self.assertEqual(auth_settings._SOCIAL_AUTH_LOGIN_REDIRECT_URL, response.get('Location')) def assert_redirect_to_login_looks_correct(self, response): """Asserts a response would redirect to /login.""" self.assertEqual(302, response.status_code) self.assertEqual('/login', response.get('Location')) def assert_redirect_to_register_looks_correct(self, response): """Asserts a response would redirect to /register.""" self.assertEqual(302, response.status_code) self.assertEqual('/register', response.get('Location')) def assert_register_response_before_pipeline_looks_correct(self, response): """Asserts a GET of /register not in the pipeline looks correct.""" self.assertEqual(200, response.status_code) # The combined login/registration page dynamically generates the register button, # but we can still check that the provider name is passed in the data attribute # for the container element. self.assertIn(self.provider.name, response.content) def assert_social_auth_does_not_exist_for_user(self, user, strategy): """Asserts a user does not have an auth with the expected provider.""" social_auths = strategy.storage.user.get_social_auth_for_user( user, provider=self.provider.backend_name) self.assertEqual(0, len(social_auths)) def assert_social_auth_exists_for_user(self, user, strategy): """Asserts a user has a social auth with the expected provider.""" social_auths = strategy.storage.user.get_social_auth_for_user( user, provider=self.provider.backend_name) self.assertEqual(1, len(social_auths)) self.assertEqual(self.backend_name, social_auths[0].provider) def create_user_models_for_existing_account(self, strategy, email, password, username, skip_social_auth=False): """Creates user, profile, registration, and (usually) social auth. This synthesizes what happens during /register. See student.views.register and student.views._do_create_account. """ response_data = self.get_response_data() uid = strategy.request.backend.get_user_id(response_data, response_data) user = social_utils.Storage.user.create_user(email=email, password=password, username=username) profile = student_models.UserProfile(user=user) profile.save() registration = student_models.Registration() registration.register(user) registration.save() if not skip_social_auth: social_utils.Storage.user.create_social_auth(user, uid, self.provider.backend_name) return user def fake_auth_complete(self, strategy): """Fake implementation of social.backends.BaseAuth.auth_complete. Unlike what the docs say, it does not need to return a user instance. Sometimes (like when directing users to the /register form) it instead returns a response that 302s to /register. """ args = () kwargs = { 'request': strategy.request, 'backend': strategy.request.backend, 'user': None, 'response': self.get_response_data(), } return strategy.authenticate(*args, **kwargs) def get_registration_post_vars(self, overrides=None): """POST vars generated by the registration form.""" defaults = { 'username': 'username', 'name': 'First Last', 'gender': '', 'year_of_birth': '', 'level_of_education': '', 'goals': '', 'honor_code': 'true', 'terms_of_service': 'true', 'password': 'password', 'mailing_address': '', 'email': 'user@email.com', } if overrides: defaults.update(overrides) return defaults def get_request_and_strategy(self, auth_entry=None, redirect_uri=None): """Gets a fully-configured request and strategy. These two objects contain circular references, so we create them together. The references themselves are a mixture of normal __init__ stuff and monkey-patching done by python-social-auth. See, for example, social.apps.django_apps.utils.strategy(). """ request = self.request_factory.get( pipeline.get_complete_url(self.backend_name) + '?redirect_state=redirect_state_value&code=code_value&state=state_value') request.user = auth_models.AnonymousUser() request.session = cache.SessionStore() request.session[self.backend_name + '_state'] = 'state_value' if auth_entry: request.session[pipeline.AUTH_ENTRY_KEY] = auth_entry strategy = social_utils.load_strategy(request=request) request.social_strategy = strategy request.backend = social_utils.load_backend(strategy, self.backend_name, redirect_uri) return request, strategy def get_user_by_email(self, strategy, email): """Gets a user by email, using the given strategy.""" return strategy.storage.user.user_model().objects.get(email=email) def assert_logged_in_cookie_redirect(self, response): """Verify that the user was redirected in order to set the logged in cookie. """ self.assertEqual(response.status_code, 302) self.assertEqual( response["Location"], pipeline.get_complete_url(self.provider.backend_name) ) self.assertEqual(response.cookies[django_settings.EDXMKTG_LOGGED_IN_COOKIE_NAME].value, 'true') self.assertIn(django_settings.EDXMKTG_USER_INFO_COOKIE_NAME, response.cookies) def set_logged_in_cookies(self, request): """Simulate setting the marketing site cookie on the request. """ request.COOKIES[django_settings.EDXMKTG_LOGGED_IN_COOKIE_NAME] = 'true' request.COOKIES[django_settings.EDXMKTG_USER_INFO_COOKIE_NAME] = json.dumps({ 'version': django_settings.EDXMKTG_USER_INFO_COOKIE_VERSION, }) # Actual tests, executed once per child. def test_canceling_authentication_redirects_to_login_when_auth_entry_login(self): self.assert_exception_redirect_looks_correct('/login', auth_entry=pipeline.AUTH_ENTRY_LOGIN) def test_canceling_authentication_redirects_to_register_when_auth_entry_register(self): self.assert_exception_redirect_looks_correct('/register', auth_entry=pipeline.AUTH_ENTRY_REGISTER) def test_canceling_authentication_redirects_to_login_when_auth_login_2(self): self.assert_exception_redirect_looks_correct('/account/login/', auth_entry=pipeline.AUTH_ENTRY_LOGIN_2) def test_canceling_authentication_redirects_to_login_when_auth_register_2(self): self.assert_exception_redirect_looks_correct('/account/register/', auth_entry=pipeline.AUTH_ENTRY_REGISTER_2) def test_canceling_authentication_redirects_to_account_settings_when_auth_entry_account_settings(self): self.assert_exception_redirect_looks_correct( '/account/settings', auth_entry=pipeline.AUTH_ENTRY_ACCOUNT_SETTINGS ) def test_canceling_authentication_redirects_to_root_when_auth_entry_not_set(self): self.assert_exception_redirect_looks_correct('/') def test_full_pipeline_succeeds_for_linking_account(self): # First, create, the request and strategy that store pipeline state, # configure the backend, and mock out wire traffic. request, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete') request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) pipeline.analytics.track = mock.MagicMock() request.user = self.create_user_models_for_existing_account( strategy, 'user@example.com', 'password', self.get_username(), skip_social_auth=True) # Instrument the pipeline to get to the dashboard with the full # expected state. self.client.get( pipeline.get_login_url(self.provider.provider_id, pipeline.AUTH_ENTRY_LOGIN)) actions.do_complete(request.backend, social_views._do_login) # pylint: disable=protected-access mako_middleware_process_request(strategy.request) student_views.signin_user(strategy.request) student_views.login_user(strategy.request) actions.do_complete(request.backend, social_views._do_login) # pylint: disable=protected-access # First we expect that we're in the unlinked state, and that there # really is no association in the backend. self.assert_account_settings_context_looks_correct(account_settings_context(request), request.user, linked=False) self.assert_social_auth_does_not_exist_for_user(request.user, strategy) # We should be redirected back to the complete page, setting # the "logged in" cookie for the marketing site. self.assert_logged_in_cookie_redirect(actions.do_complete( request.backend, social_views._do_login, request.user, None, # pylint: disable=protected-access redirect_field_name=auth.REDIRECT_FIELD_NAME )) # Set the cookie and try again self.set_logged_in_cookies(request) # Fire off the auth pipeline to link. self.assert_redirect_to_dashboard_looks_correct(actions.do_complete( request.backend, social_views._do_login, request.user, None, # pylint: disable=protected-access redirect_field_name=auth.REDIRECT_FIELD_NAME)) # Now we expect to be in the linked state, with a backend entry. self.assert_social_auth_exists_for_user(request.user, strategy) self.assert_account_settings_context_looks_correct(account_settings_context(request), request.user, linked=True) def test_full_pipeline_succeeds_for_unlinking_account(self): # First, create, the request and strategy that store pipeline state, # configure the backend, and mock out wire traffic. request, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete') request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) user = self.create_user_models_for_existing_account( strategy, 'user@example.com', 'password', self.get_username()) self.assert_social_auth_exists_for_user(user, strategy) # We're already logged in, so simulate that the cookie is set correctly self.set_logged_in_cookies(request) # Instrument the pipeline to get to the dashboard with the full # expected state. self.client.get( pipeline.get_login_url(self.provider.provider_id, pipeline.AUTH_ENTRY_LOGIN)) actions.do_complete(request.backend, social_views._do_login) # pylint: disable=protected-access mako_middleware_process_request(strategy.request) student_views.signin_user(strategy.request) student_views.login_user(strategy.request) actions.do_complete(request.backend, social_views._do_login, user=user) # pylint: disable=protected-access # First we expect that we're in the linked state, with a backend entry. self.assert_account_settings_context_looks_correct(account_settings_context(request), user, linked=True) self.assert_social_auth_exists_for_user(request.user, strategy) # Fire off the disconnect pipeline to unlink. self.assert_redirect_to_dashboard_looks_correct(actions.do_disconnect( request.backend, request.user, None, redirect_field_name=auth.REDIRECT_FIELD_NAME)) # Now we expect to be in the unlinked state, with no backend entry. self.assert_account_settings_context_looks_correct(account_settings_context(request), user, linked=False) self.assert_social_auth_does_not_exist_for_user(user, strategy) def test_linking_already_associated_account_raises_auth_already_associated(self): # This is of a piece with # test_already_associated_exception_populates_dashboard_with_error. It # verifies the exception gets raised when we expect; the latter test # covers exception handling. email = 'user@example.com' password = 'password' username = self.get_username() _, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete') backend = strategy.request.backend backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) linked_user = self.create_user_models_for_existing_account(strategy, email, password, username) unlinked_user = social_utils.Storage.user.create_user( email='other_' + email, password=password, username='other_' + username) self.assert_social_auth_exists_for_user(linked_user, strategy) self.assert_social_auth_does_not_exist_for_user(unlinked_user, strategy) with self.assertRaises(exceptions.AuthAlreadyAssociated): # pylint: disable=protected-access actions.do_complete(backend, social_views._do_login, user=unlinked_user) def test_already_associated_exception_populates_dashboard_with_error(self): # Instrument the pipeline with an exception. We test that the # exception is raised correctly separately, so it's ok that we're # raising it artificially here. This makes the linked=True artificial # in the final assert because in practice the account would be # unlinked, but getting that behavior is cumbersome here and already # covered in other tests. Using linked=True does, however, let us test # that the duplicate error has no effect on the state of the controls. request, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete') strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) user = self.create_user_models_for_existing_account( strategy, 'user@example.com', 'password', self.get_username()) self.assert_social_auth_exists_for_user(user, strategy) self.client.get('/login') self.client.get(pipeline.get_login_url(self.provider.provider_id, pipeline.AUTH_ENTRY_LOGIN)) actions.do_complete(request.backend, social_views._do_login) # pylint: disable=protected-access mako_middleware_process_request(strategy.request) student_views.signin_user(strategy.request) student_views.login_user(strategy.request) actions.do_complete(request.backend, social_views._do_login, user=user) # pylint: disable=protected-access # Monkey-patch storage for messaging; pylint: disable=protected-access request._messages = fallback.FallbackStorage(request) middleware.ExceptionMiddleware().process_exception( request, exceptions.AuthAlreadyAssociated(self.provider.backend_name, 'account is already in use.')) self.assert_account_settings_context_looks_correct( account_settings_context(request), user, duplicate=True, linked=True) def test_full_pipeline_succeeds_for_signing_in_to_existing_active_account(self): # First, create, the request and strategy that store pipeline state, # configure the backend, and mock out wire traffic. request, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete') strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) pipeline.analytics.track = mock.MagicMock() user = self.create_user_models_for_existing_account( strategy, 'user@example.com', 'password', self.get_username()) self.assert_social_auth_exists_for_user(user, strategy) self.assertTrue(user.is_active) # Begin! Ensure that the login form contains expected controls before # the user starts the pipeline. self.assert_login_response_before_pipeline_looks_correct(self.client.get('/login')) # The pipeline starts by a user GETting /auth/login/<provider>. # Synthesize that request and check that it redirects to the correct # provider page. self.assert_redirect_to_provider_looks_correct(self.client.get( pipeline.get_login_url(self.provider.provider_id, pipeline.AUTH_ENTRY_LOGIN))) # Next, the provider makes a request against /auth/complete/<provider> # to resume the pipeline. # pylint: disable=protected-access self.assert_redirect_to_login_looks_correct(actions.do_complete(request.backend, social_views._do_login)) mako_middleware_process_request(strategy.request) # At this point we know the pipeline has resumed correctly. Next we # fire off the view that displays the login form and posts it via JS. self.assert_login_response_in_pipeline_looks_correct(student_views.signin_user(strategy.request)) # Next, we invoke the view that handles the POST, and expect it # redirects to /auth/complete. In the browser ajax handlers will # redirect the user to the dashboard; we invoke it manually here. self.assert_json_success_response_looks_correct(student_views.login_user(strategy.request)) # We should be redirected back to the complete page, setting # the "logged in" cookie for the marketing site. self.assert_logged_in_cookie_redirect(actions.do_complete( request.backend, social_views._do_login, request.user, None, # pylint: disable=protected-access redirect_field_name=auth.REDIRECT_FIELD_NAME )) # Set the cookie and try again self.set_logged_in_cookies(request) self.assert_redirect_to_dashboard_looks_correct( actions.do_complete(request.backend, social_views._do_login, user=user)) self.assert_account_settings_context_looks_correct(account_settings_context(request), user) def test_signin_fails_if_account_not_active(self): _, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete') strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) user = self.create_user_models_for_existing_account(strategy, 'user@example.com', 'password', self.get_username()) user.is_active = False user.save() mako_middleware_process_request(strategy.request) self.assert_json_failure_response_is_inactive_account(student_views.login_user(strategy.request)) def test_signin_fails_if_no_account_associated(self): _, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete') strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) self.create_user_models_for_existing_account( strategy, 'user@example.com', 'password', self.get_username(), skip_social_auth=True) self.assert_json_failure_response_is_missing_social_auth(student_views.login_user(strategy.request)) def test_first_party_auth_trumps_third_party_auth_but_is_invalid_when_only_email_in_request(self): self.assert_first_party_auth_trumps_third_party_auth(email='user@example.com') def test_first_party_auth_trumps_third_party_auth_but_is_invalid_when_only_password_in_request(self): self.assert_first_party_auth_trumps_third_party_auth(password='password') def test_first_party_auth_trumps_third_party_auth_and_fails_when_credentials_bad(self): self.assert_first_party_auth_trumps_third_party_auth( email='user@example.com', password='password', success=False) def test_first_party_auth_trumps_third_party_auth_and_succeeds_when_credentials_good(self): self.assert_first_party_auth_trumps_third_party_auth( email='user@example.com', password='password', success=True) def test_full_pipeline_succeeds_registering_new_account(self): # First, create, the request and strategy that store pipeline state. # Mock out wire traffic. request, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete') strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) # Begin! Grab the registration page and check the login control on it. self.assert_register_response_before_pipeline_looks_correct(self.client.get('/register')) # The pipeline starts by a user GETting /auth/login/<provider>. # Synthesize that request and check that it redirects to the correct # provider page. self.assert_redirect_to_provider_looks_correct(self.client.get( pipeline.get_login_url(self.provider.provider_id, pipeline.AUTH_ENTRY_LOGIN))) # Next, the provider makes a request against /auth/complete/<provider>. # pylint: disable=protected-access self.assert_redirect_to_register_looks_correct(actions.do_complete(request.backend, social_views._do_login)) mako_middleware_process_request(strategy.request) # At this point we know the pipeline has resumed correctly. Next we # fire off the view that displays the registration form. self.assert_register_response_in_pipeline_looks_correct( student_views.register_user(strategy.request), pipeline.get(request)['kwargs']) # Next, we invoke the view that handles the POST. Not all providers # supply email. Manually add it as the user would have to; this # also serves as a test of overriding provider values. Always provide a # password for us to check that we override it properly. overridden_password = strategy.request.POST.get('password') email = 'new@example.com' if not strategy.request.POST.get('email'): strategy.request.POST = self.get_registration_post_vars({'email': email}) # The user must not exist yet... with self.assertRaises(auth_models.User.DoesNotExist): self.get_user_by_email(strategy, email) # ...but when we invoke create_account the existing edX view will make # it, but not social auths. The pipeline creates those later. self.assert_json_success_response_looks_correct(student_views.create_account(strategy.request)) # We've overridden the user's password, so authenticate() with the old # value won't work: created_user = self.get_user_by_email(strategy, email) self.assert_password_overridden_by_pipeline(overridden_password, created_user.username) # At this point the user object exists, but there is no associated # social auth. self.assert_social_auth_does_not_exist_for_user(created_user, strategy) # We should be redirected back to the complete page, setting # the "logged in" cookie for the marketing site. self.assert_logged_in_cookie_redirect(actions.do_complete( request.backend, social_views._do_login, request.user, None, # pylint: disable=protected-access redirect_field_name=auth.REDIRECT_FIELD_NAME )) # Set the cookie and try again self.set_logged_in_cookies(request) self.assert_redirect_to_dashboard_looks_correct( actions.do_complete(strategy.request.backend, social_views._do_login, user=created_user)) # Now the user has been redirected to the dashboard. Their third party account should now be linked. self.assert_social_auth_exists_for_user(created_user, strategy) self.assert_account_settings_context_looks_correct(account_settings_context(request), created_user, linked=True) def test_new_account_registration_assigns_distinct_username_on_collision(self): original_username = self.get_username() request, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete') # Create a colliding username in the backend, then proceed with # assignment via pipeline to make sure a distinct username is created. strategy.storage.user.create_user(username=self.get_username(), email='user@email.com', password='password') backend = strategy.request.backend backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) # pylint: disable=protected-access self.assert_redirect_to_register_looks_correct(actions.do_complete(backend, social_views._do_login)) distinct_username = pipeline.get(request)['kwargs']['username'] self.assertNotEqual(original_username, distinct_username) def test_new_account_registration_fails_if_email_exists(self): request, strategy = self.get_request_and_strategy( auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete') backend = strategy.request.backend backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) # pylint: disable=protected-access self.assert_redirect_to_register_looks_correct(actions.do_complete(backend, social_views._do_login)) mako_middleware_process_request(strategy.request) self.assert_register_response_in_pipeline_looks_correct( student_views.register_user(strategy.request), pipeline.get(request)['kwargs']) strategy.request.POST = self.get_registration_post_vars() # Create twice: once successfully, and once causing a collision. student_views.create_account(strategy.request) self.assert_json_failure_response_is_username_collision(student_views.create_account(strategy.request)) def test_pipeline_raises_auth_entry_error_if_auth_entry_invalid(self): auth_entry = 'invalid' self.assertNotIn(auth_entry, pipeline._AUTH_ENTRY_CHOICES) # pylint: disable=protected-access _, strategy = self.get_request_and_strategy(auth_entry=auth_entry, redirect_uri='social:complete') with self.assertRaises(pipeline.AuthEntryError): strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) def test_pipeline_raises_auth_entry_error_if_auth_entry_missing(self): _, strategy = self.get_request_and_strategy(auth_entry=None, redirect_uri='social:complete') with self.assertRaises(pipeline.AuthEntryError): strategy.request.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy)) class Oauth2IntegrationTest(IntegrationTest): # pylint: disable=abstract-method """Base test case for integration tests of Oauth2 providers.""" # Dict of string -> object. Information about the token granted to the # user. Override with test values in subclass; None to force a throw. TOKEN_RESPONSE_DATA = None # Dict of string -> object. Information about the user themself. Override # with test values in subclass; None to force a throw. USER_RESPONSE_DATA = None def get_response_data(self): """Gets dict (string -> object) of merged data about the user.""" response_data = dict(self.TOKEN_RESPONSE_DATA) response_data.update(self.USER_RESPONSE_DATA) return response_data
jaloren/robotframework
refs/heads/master
utest/reporting/test_jsbuildingcontext.py
9
import random import unittest from robot.output.loggerhelper import LEVELS from robot.reporting.jsmodelbuilders import JsBuildingContext from robot.utils.asserts import assert_equal class TestStringContext(unittest.TestCase): def test_add_empty_string(self): self._verify([''], [0], []) def test_add_string(self): self._verify(['Hello!'], [1], ['Hello!']) def test_add_several_strings(self): self._verify(['Hello!', 'Foo'], [1, 2], ['Hello!', 'Foo']) def test_cache_strings(self): self._verify(['Foo', '', 'Foo', 'Foo', ''], [1, 0, 1, 1, 0], ['Foo']) def test_escape_strings(self): self._verify(['</script>', '&', '&'], [1, 2, 2], ['&lt;/script&gt;', '&amp;']) def test_no_escape(self): self._verify(['</script>', '&', '&'], [1, 2, 2], ['</script>', '&'], escape=False) def test_none_string(self): self._verify([None, '', None], [0, 0, 0], []) def _verify(self, strings, exp_ids, exp_strings, escape=True): exp_strings = tuple('*'+s for s in [''] + exp_strings) ctx = JsBuildingContext() results = [ctx.string(s, escape=escape) for s in strings] assert_equal(results, exp_ids) assert_equal(ctx.strings, exp_strings) class TestTimestamp(unittest.TestCase): def setUp(self): self._context = JsBuildingContext() def test_timestamp(self): assert_equal(self._context.timestamp('20110603 12:00:00.042'), 0) assert_equal(self._context.timestamp('20110603 12:00:00.043'), 1) assert_equal(self._context.timestamp('20110603 12:00:00.000'), -42) assert_equal(self._context.timestamp('20110603 12:00:01.041'), 999) assert_equal(self._context.timestamp('20110604 12:00:00.042'), 24 * 60 * 60 * 1000) def test_none_timestamp(self): assert_equal(self._context.timestamp(None), None) class TestMinLogLevel(unittest.TestCase): def setUp(self): self._context = JsBuildingContext() def test_trace_is_identified_as_smallest_log_level(self): self._messages(list(LEVELS)) assert_equal('TRACE', self._context.min_level) def test_debug_is_identified_when_no_trace(self): self._messages([l for l in LEVELS if l != 'TRACE']) assert_equal('DEBUG', self._context.min_level) def test_info_is_smallest_when_no_debug_or_trace(self): self._messages(['INFO', 'WARN', 'ERROR', 'FAIL']) assert_equal('INFO', self._context.min_level) def _messages(self, levels): levels = levels[:] random.shuffle(levels) for level in levels: self._context.message_level(level) if __name__ == '__main__': unittest.main()
JShadowMan/package
refs/heads/master
python/python-packages/PIL_/verification_code.py
2
#!/usr/bin/env python3 from PIL import Image, ImageFilter, ImageDraw, ImageFont import random, platform def randomChar(): return chr(random.randint(65, 90)) def randomColor(): return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)) def randomFontClolor(): return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) w, h = (240, 60) fontPath = 'C:/Windows/Fonts/Arial.ttf' if platform.system() is 'Windows' else '/Library/Fonts/Arial.ttf' if platform.system() is 'Darwin' else '/usr/share/fonts/Arial.ttf' im = Image.new('RGB', (w, h), (225, 225, 225)) font = ImageFont.truetype(fontPath, 36) draw = ImageDraw.Draw(im) for x in range(w): for y in range(h): draw.point((x, y), fill = randomColor()) for word in range(4): draw.text((60 * word + 10, 10), randomChar(), font = font, fill = randomFontClolor()) im = im.filter(ImageFilter.BLUR) im.save('verification_code.jpg', 'jpeg') print(im.tobytes())
StepanBakshayev/funrun
refs/heads/master
src/funrun/match/views.py
2
from datetime import datetime from dateutil.relativedelta import relativedelta from django import forms from django.shortcuts import render, get_object_or_404, redirect from django.conf import settings from django.core.paginator import InvalidPage, EmptyPage, Paginator from django.utils import timezone from .models import Match, Player def paginate_list(request, queryset, per_page): try: page = int(request.GET.get('page', 1)) except ValueError: page = 1 paginator = Paginator(queryset, per_page) try: return paginator.page(page) except (EmptyPage, InvalidPage): return paginator.page(paginator.num_pages) def index(request): matches = Match.objects.all() matches_page = paginate_list(request, matches, settings.MATCHES_PER_PAGE) previous_month = datetime.now() - relativedelta(months=1) return render(request, "match/index.html", { 'page': matches_page, 'month_stats': get_month_stats(), 'previous_month': previous_month, }) def start_match(request): match_id = Match.objects.create().id return redirect('match:match', match_id=match_id) class PlayersForm(forms.ModelForm): class Meta: model = Match fields = 'players', def match(request, match_id): match = get_object_or_404(Match, id=match_id) players_form = None if match.end_time is None: players_form = PlayersForm(instance=match, data=request.POST or None) if request.method == 'POST': finish = request.POST.get('finish') update = request.POST.get('update') leave = request.POST.get('leave') if update and players_form.is_valid(): players_form.save() if leave: player = match.players.get(id=leave) stats = match.get_stats(exclude_winners=True) max_wins = 0 player_wins = 0 for record in stats: if record[0] == player.id: player_wins = record[2] if record[2] > max_wins: max_wins = record[2] if player_wins == max_wins: place = match.leave_set.exclude(place=0).count() + 1 else: place = 0 match.leave_set.create(player=player, place=place) if len(match.get_stats(exclude_winners=True)) == 0: finish = True if finish: if match.players.count() < 2: match.delete() return redirect(index) else: match.end_time = timezone.now() match.save() return redirect('match:match', match_id=match.id) return render(request, "match/match.html", { 'match': match, 'players_form': players_form, }) def round(request, match_id): match = get_object_or_404(Match, id=match_id) if request.method == 'POST': round = request.POST.get('round') winner = request.POST.get('winner') current_round = match.round_set.first() if round == 'new': new_round = match.round_set.create() if match.round_set.filter(winner=None).count() > 1: match.round_set.filter(winner=None).exclude(id=new_round.id).delete() elif round == 'cancel': current_round.winner = None current_round.save() elif round == 'delete': current_round.delete() if winner: if not match.leave_set.filter(player_id=winner).exists(): current_round.winner_id = winner current_round.end_time = timezone.now() current_round.save() return redirect('match:match', match_id=match.id) def get_month_stats(month=None): if not month: month = datetime.now() stats = [] for player in Player.objects.all(): stats.append({ 'player': player, 'match_count': player.match_set.filter(end_time__year=month.year, end_time__month=month.month).count(), 'round_count': player.round_set.filter(end_time__year=month.year, end_time__month=month.month).count(), 'place1_number': player.leave_set.filter(place=1, match__end_time__year=month.year, match__end_time__month=month.month).count(), 'place2_number': player.leave_set.filter(place=2, match__end_time__year=month.year, match__end_time__month=month.month).count(), 'place3_number': player.leave_set.filter(place=3, match__end_time__year=month.year, match__end_time__month=month.month).count(), }) return stats def month_stats(request): month_string = request.GET.get('month') month = datetime.now() if month_string: month = datetime.strptime(month_string, '%Y-%m') previous_month = month - relativedelta(months=1) next_month = month + relativedelta(months=1) return render(request, "match/month_stats.html", { 'current_month': month, 'previous_month': previous_month, 'next_month': next_month, 'month_stats': get_month_stats(month), })
prakritish/ansible
refs/heads/devel
lib/ansible/modules/cloud/digital_ocean/digital_ocean_sshkey.py
32
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: digital_ocean_sshkey short_description: Create/delete an SSH key in DigitalOcean description: - Create/delete an SSH key. version_added: "1.6" author: "Michael Gregson (@mgregson)" options: state: description: - Indicate desired state of the target. default: present choices: ['present', 'absent'] client_id: description: - DigitalOcean manager id. api_key: description: - DigitalOcean api key. id: description: - Numeric, the SSH key id you want to operate on. name: description: - String, this is the name of an SSH key to create or destroy. ssh_pub_key: description: - The public SSH key you want to add to your account. notes: - Two environment variables can be used, DO_CLIENT_ID and DO_API_KEY. - Version 1 of DigitalOcean API is used. requirements: - "python >= 2.6" - dopy ''' EXAMPLES = ''' # Ensure a SSH key is present # If a key matches this name, will return the ssh key id and changed = False # If no existing key matches this name, a new key is created, the ssh key id is returned and changed = False - digital_ocean_sshkey: state: present name: my_ssh_key ssh_pub_key: 'ssh-rsa AAAA...' client_id: XXX api_key: XXX ''' import os import traceback try: from dopy.manager import DoError, DoManager HAS_DOPY = True except ImportError: HAS_DOPY = False from ansible.module_utils.basic import AnsibleModule class JsonfyMixIn(object): def to_json(self): return self.__dict__ class SSH(JsonfyMixIn): manager = None def __init__(self, ssh_key_json): self.__dict__.update(ssh_key_json) update_attr = __init__ def destroy(self): self.manager.destroy_ssh_key(self.id) return True @classmethod def setup(cls, client_id, api_key): cls.manager = DoManager(client_id, api_key) @classmethod def find(cls, name): if not name: return False keys = cls.list_all() for key in keys: if key.name == name: return key return False @classmethod def list_all(cls): json = cls.manager.all_ssh_keys() return map(cls, json) @classmethod def add(cls, name, key_pub): json = cls.manager.new_ssh_key(name, key_pub) return cls(json) def core(module): def getkeyordie(k): v = module.params[k] if v is None: module.fail_json(msg='Unable to load %s' % k) return v try: # params['client_id'] will be None even if client_id is not passed in client_id = module.params['client_id'] or os.environ['DO_CLIENT_ID'] api_key = module.params['api_key'] or os.environ['DO_API_KEY'] except KeyError as e: module.fail_json(msg='Unable to load %s' % e.message) state = module.params['state'] SSH.setup(client_id, api_key) name = getkeyordie('name') if state in ('present'): key = SSH.find(name) if key: module.exit_json(changed=False, ssh_key=key.to_json()) key = SSH.add(name, getkeyordie('ssh_pub_key')) module.exit_json(changed=True, ssh_key=key.to_json()) elif state in ('absent'): key = SSH.find(name) if not key: module.exit_json(changed=False, msg='SSH key with the name of %s is not found.' % name) key.destroy() module.exit_json(changed=True) def main(): module = AnsibleModule( argument_spec = dict( state = dict(choices=['present', 'absent'], default='present'), client_id = dict(aliases=['CLIENT_ID'], no_log=True), api_key = dict(aliases=['API_KEY'], no_log=True), name = dict(type='str'), id = dict(aliases=['droplet_id'], type='int'), ssh_pub_key = dict(type='str'), ), required_one_of = ( ['id', 'name'], ), ) if not HAS_DOPY: module.fail_json(msg='dopy required for this module') try: core(module) except (DoError, Exception) as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) if __name__ == '__main__': main()
Titulacion-Sistemas/PracticasDjango
refs/heads/master
ServiciosWeb/Sentencias/__init__.py
6
__author__ = 'Jhonsson'
areitz/pants
refs/heads/master
src/python/pants/base/build_file_aliases.py
8
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import functools from collections import namedtuple class BuildFileAliases(namedtuple('BuildFileAliases', ['targets', 'objects', 'context_aware_object_factories', 'addressables'])): """A structure containing set of symbols to be exposed in BUILD files. There are three types of symbols that can be exposed: - targets: These are Target subclasses. - objects: These are any python object, from constants to types. - addressables: Exposed objects which optionally establish an alias via the AddressMapper for themselves. Notably all Target aliases in BUILD files are actually exposed as proxy objects via Target.get_addressable_type. - context_aware_object_factories: These are object factories that are passed a ParseContext and produce some object that uses data from the context to enable some feature or utility. Common uses include objects that must be aware of the current BUILD file path or functions that need to be able to create targets or objects from within the BUILD file parse. """ @classmethod def create(cls, targets=None, objects=None, context_aware_object_factories=None, addressables=None): """A convenience constructor that can accept zero to all alias types.""" def copy(orig): return orig.copy() if orig else {} return cls(copy(targets), copy(objects), copy(context_aware_object_factories), copy(addressables)) @classmethod def curry_context(cls, wrappee): """Curry a function with a build file context. Given a function foo(ctx, bar) that you want to expose in BUILD files as foo(bar), use:: context_aware_object_factories={ 'foo': BuildFileAliases.curry_context(foo), } """ # You might wonder: why not just use lambda and functools.partial? # That loses the __doc__, thus messing up the BUILD dictionary. wrapper = lambda ctx: functools.partial(wrappee, ctx) wrapper.__doc__ = wrappee.__doc__ wrapper.__name__ = str(".".join(["curry_context", wrappee.__module__, wrappee.__name__])) return wrapper def merge(self, other): """Merges a set of build file aliases and returns a new set of aliases containing both. Any duplicate aliases from `other` will trump. """ if not isinstance(other, BuildFileAliases): raise TypeError('Can only merge other BuildFileAliases, given {0}'.format(other)) all_aliases = self._asdict() other_aliases = other._asdict() for alias_type, alias_map in all_aliases.items(): alias_map.update(other_aliases[alias_type]) return BuildFileAliases(**all_aliases)
denfromufa/PTVS
refs/heads/master
Python/Product/PythonTools/Templates/Projects/StarterFlaskProject/views.py
18
""" Routes and views for the flask application. """ from datetime import datetime from flask import render_template from $safeprojectname$ import app @app.route('/') @app.route('/home') def home(): """Renders the home page.""" return render_template( 'index.html', title='Home Page', year=datetime.now().year, ) @app.route('/contact') def contact(): """Renders the contact page.""" return render_template( 'contact.html', title='Contact', year=datetime.now().year, message='Your contact page.' ) @app.route('/about') def about(): """Renders the about page.""" return render_template( 'about.html', title='About', year=datetime.now().year, message='Your application description page.' )
fabioticconi/scikit-learn
refs/heads/master
examples/cluster/plot_kmeans_silhouette_analysis.py
83
""" =============================================================================== Selecting the number of clusters with silhouette analysis on KMeans clustering =============================================================================== Silhouette analysis can be used to study the separation distance between the resulting clusters. The silhouette plot displays a measure of how close each point in one cluster is to points in the neighboring clusters and thus provides a way to assess parameters like number of clusters visually. This measure has a range of [-1, 1]. Silhouette coefficients (as these values are referred to as) near +1 indicate that the sample is far away from the neighboring clusters. A value of 0 indicates that the sample is on or very close to the decision boundary between two neighboring clusters and negative values indicate that those samples might have been assigned to the wrong cluster. In this example the silhouette analysis is used to choose an optimal value for ``n_clusters``. The silhouette plot shows that the ``n_clusters`` value of 3, 5 and 6 are a bad pick for the given data due to the presence of clusters with below average silhouette scores and also due to wide fluctuations in the size of the silhouette plots. Silhouette analysis is more ambivalent in deciding between 2 and 4. Also from the thickness of the silhouette plot the cluster size can be visualized. The silhouette plot for cluster 0 when ``n_clusters`` is equal to 2, is bigger in size owing to the grouping of the 3 sub clusters into one big cluster. However when the ``n_clusters`` is equal to 4, all the plots are more or less of similar thickness and hence are of similar sizes as can be also verified from the labelled scatter plot on the right. """ from __future__ import print_function from sklearn.datasets import make_blobs from sklearn.cluster import KMeans from sklearn.metrics import silhouette_samples, silhouette_score import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np print(__doc__) # Generating the sample data from make_blobs # This particular setting has one distinct cluster and 3 clusters placed close # together. X, y = make_blobs(n_samples=500, n_features=2, centers=4, cluster_std=1, center_box=(-10.0, 10.0), shuffle=True, random_state=1) # For reproducibility range_n_clusters = [2, 3, 4, 5, 6] for n_clusters in range_n_clusters: # Create a subplot with 1 row and 2 columns fig, (ax1, ax2) = plt.subplots(1, 2) fig.set_size_inches(18, 7) # The 1st subplot is the silhouette plot # The silhouette coefficient can range from -1, 1 but in this example all # lie within [-0.1, 1] ax1.set_xlim([-0.1, 1]) # The (n_clusters+1)*10 is for inserting blank space between silhouette # plots of individual clusters, to demarcate them clearly. ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10]) # Initialize the clusterer with n_clusters value and a random generator # seed of 10 for reproducibility. clusterer = KMeans(n_clusters=n_clusters, random_state=10) cluster_labels = clusterer.fit_predict(X) # The silhouette_score gives the average value for all the samples. # This gives a perspective into the density and separation of the formed # clusters silhouette_avg = silhouette_score(X, cluster_labels) print("For n_clusters =", n_clusters, "The average silhouette_score is :", silhouette_avg) # Compute the silhouette scores for each sample sample_silhouette_values = silhouette_samples(X, cluster_labels) y_lower = 10 for i in range(n_clusters): # Aggregate the silhouette scores for samples belonging to # cluster i, and sort them ith_cluster_silhouette_values = \ sample_silhouette_values[cluster_labels == i] ith_cluster_silhouette_values.sort() size_cluster_i = ith_cluster_silhouette_values.shape[0] y_upper = y_lower + size_cluster_i color = cm.spectral(float(i) / n_clusters) ax1.fill_betweenx(np.arange(y_lower, y_upper), 0, ith_cluster_silhouette_values, facecolor=color, edgecolor=color, alpha=0.7) # Label the silhouette plots with their cluster numbers at the middle ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i)) # Compute the new y_lower for next plot y_lower = y_upper + 10 # 10 for the 0 samples ax1.set_title("The silhouette plot for the various clusters.") ax1.set_xlabel("The silhouette coefficient values") ax1.set_ylabel("Cluster label") # The vertical line for average silhouette score of all the values ax1.axvline(x=silhouette_avg, color="red", linestyle="--") ax1.set_yticks([]) # Clear the yaxis labels / ticks ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1]) # 2nd Plot showing the actual clusters formed colors = cm.spectral(cluster_labels.astype(float) / n_clusters) ax2.scatter(X[:, 0], X[:, 1], marker='.', s=30, lw=0, alpha=0.7, c=colors) # Labeling the clusters centers = clusterer.cluster_centers_ # Draw white circles at cluster centers ax2.scatter(centers[:, 0], centers[:, 1], marker='o', c="white", alpha=1, s=200) for i, c in enumerate(centers): ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1, s=50) ax2.set_title("The visualization of the clustered data.") ax2.set_xlabel("Feature space for the 1st feature") ax2.set_ylabel("Feature space for the 2nd feature") plt.suptitle(("Silhouette analysis for KMeans clustering on sample data " "with n_clusters = %d" % n_clusters), fontsize=14, fontweight='bold') plt.show()
ndp-systemes/odoo-addons
refs/heads/8.0
base_res_config_improved/__init__.py
1
# -*- coding: utf8 -*- # # Copyright (C) 2018 NDP Systèmes (<http://www.ndp-systemes.fr>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from . import res_config
vikasraunak/mptcp-1
refs/heads/development
src/flow-monitor/bindings/modulegen__gcc_LP64.py
6
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.flow_monitor', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## 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']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## flow-monitor-helper.h (module 'flow-monitor'): ns3::FlowMonitorHelper [class] module.add_class('FlowMonitorHelper') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## histogram.h (module 'flow-monitor'): ns3::Histogram [class] module.add_class('Histogram') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## 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', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress [class] module.add_class('Ipv6InterfaceAddress', import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e [enumeration] module.add_enum('State_e', ['TENTATIVE', 'DEPRECATED', 'PREFERRED', 'PERMANENT', 'HOMEADDRESS', 'TENTATIVE_OPTIMISTIC', 'INVALID'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e [enumeration] module.add_enum('Scope_e', ['HOST', 'LINKLOCAL', 'GLOBAL'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## 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') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## timer.h (module 'core'): ns3::Timer [class] module.add_class('Timer', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration] module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::State [enumeration] module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer-impl.h (module 'core'): ns3::TimerImpl [class] module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv6-header.h (module 'internet'): ns3::Ipv6Header [class] module.add_class('Ipv6Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::NextHeader_e [enumeration] module.add_enum('NextHeader_e', ['IPV6_EXT_HOP_BY_HOP', 'IPV6_IPV4', 'IPV6_TCP', 'IPV6_UDP', 'IPV6_IPV6', 'IPV6_EXT_ROUTING', 'IPV6_EXT_FRAGMENTATION', 'IPV6_EXT_CONFIDENTIALITY', 'IPV6_EXT_AUTHENTIFICATION', 'IPV6_ICMPV6', 'IPV6_EXT_END', 'IPV6_EXT_DESTINATION', 'IPV6_SCTP', 'IPV6_EXT_MOBILITY', 'IPV6_UDP_LITE'], outer_class=root_module['ns3::Ipv6Header'], import_from_module='ns.internet') ## 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']) ## 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::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, template_parameters=['ns3::FlowClassifier', 'ns3::empty', 'ns3::DefaultDeleter<ns3::FlowClassifier>'], 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::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketAddressTag [class] module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## flow-classifier.h (module 'flow-monitor'): ns3::FlowClassifier [class] module.add_class('FlowClassifier', parent=root_module['ns3::SimpleRefCount< ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >']) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor [class] module.add_class('FlowMonitor', parent=root_module['ns3::Object']) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats [struct] module.add_class('FlowStats', outer_class=root_module['ns3::FlowMonitor']) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe [class] module.add_class('FlowProbe', parent=root_module['ns3::Object']) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats [struct] module.add_class('FlowStats', outer_class=root_module['ns3::FlowProbe']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol [class] module.add_class('IpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus [enumeration] module.add_enum('RxStatus', ['RX_OK', 'RX_CSUM_FAILED', 'RX_ENDPOINT_CLOSED', 'RX_ENDPOINT_UNREACH'], outer_class=root_module['ns3::IpL4Protocol'], import_from_module='ns.internet') ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier [class] module.add_class('Ipv4FlowClassifier', parent=root_module['ns3::FlowClassifier']) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple [struct] module.add_class('FiveTuple', outer_class=root_module['ns3::Ipv4FlowClassifier']) ## ipv4-flow-probe.h (module 'flow-monitor'): ns3::Ipv4FlowProbe [class] module.add_class('Ipv4FlowProbe', parent=root_module['ns3::FlowProbe']) ## ipv4-flow-probe.h (module 'flow-monitor'): ns3::Ipv4FlowProbe::DropReason [enumeration] module.add_enum('DropReason', ['DROP_NO_ROUTE', 'DROP_TTL_EXPIRE', 'DROP_BAD_CHECKSUM', 'DROP_QUEUE', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT', 'DROP_INVALID_REASON'], outer_class=root_module['ns3::Ipv4FlowProbe']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface [class] module.add_class('Ipv6Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## 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']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) module.add_container('std::vector< unsigned int >', 'unsigned int', container_type='vector') module.add_container('std::vector< unsigned long >', 'long unsigned int', container_type='vector') module.add_container('std::map< unsigned int, ns3::FlowMonitor::FlowStats >', ('unsigned int', 'ns3::FlowMonitor::FlowStats'), container_type='map') module.add_container('std::vector< ns3::Ptr< ns3::FlowProbe > >', 'ns3::Ptr< ns3::FlowProbe >', container_type='vector') module.add_container('std::map< unsigned int, ns3::FlowProbe::FlowStats >', ('unsigned int', 'ns3::FlowProbe::FlowStats'), container_type='map') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map') typehandlers.add_type_alias('uint32_t', 'ns3::FlowPacketId') typehandlers.add_type_alias('uint32_t*', 'ns3::FlowPacketId*') typehandlers.add_type_alias('uint32_t&', 'ns3::FlowPacketId&') typehandlers.add_type_alias('uint32_t', 'ns3::FlowId') typehandlers.add_type_alias('uint32_t*', 'ns3::FlowId*') typehandlers.add_type_alias('uint32_t&', 'ns3::FlowId&') ## 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) 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('uint32_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *&', '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_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_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_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3FlowMonitorHelper_methods(root_module, root_module['ns3::FlowMonitorHelper']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Histogram_methods(root_module, root_module['ns3::Histogram']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_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_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3Timer_methods(root_module, root_module['ns3::Timer']) register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl']) 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_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) 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__Ns3FlowClassifier_Ns3Empty_Ns3DefaultDeleter__lt__ns3FlowClassifier__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >']) 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__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag']) 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_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_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3FlowClassifier_methods(root_module, root_module['ns3::FlowClassifier']) register_Ns3FlowMonitor_methods(root_module, root_module['ns3::FlowMonitor']) register_Ns3FlowMonitorFlowStats_methods(root_module, root_module['ns3::FlowMonitor::FlowStats']) register_Ns3FlowProbe_methods(root_module, root_module['ns3::FlowProbe']) register_Ns3FlowProbeFlowStats_methods(root_module, root_module['ns3::FlowProbe::FlowStats']) register_Ns3IpL4Protocol_methods(root_module, root_module['ns3::IpL4Protocol']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4FlowClassifier_methods(root_module, root_module['ns3::Ipv4FlowClassifier']) register_Ns3Ipv4FlowClassifierFiveTuple_methods(root_module, root_module['ns3::Ipv4FlowClassifier::FiveTuple']) register_Ns3Ipv4FlowProbe_methods(root_module, root_module['ns3::Ipv4FlowProbe']) register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6Interface_methods(root_module, root_module['ns3::Ipv6Interface']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) 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_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3FlowMonitorHelper_methods(root_module, cls): ## flow-monitor-helper.h (module 'flow-monitor'): ns3::FlowMonitorHelper::FlowMonitorHelper(ns3::FlowMonitorHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::FlowMonitorHelper const &', 'arg0')]) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::FlowMonitorHelper::FlowMonitorHelper() [constructor] cls.add_constructor([]) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowClassifier> ns3::FlowMonitorHelper::GetClassifier() [member function] cls.add_method('GetClassifier', 'ns3::Ptr< ns3::FlowClassifier >', []) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowMonitor> ns3::FlowMonitorHelper::GetMonitor() [member function] cls.add_method('GetMonitor', 'ns3::Ptr< ns3::FlowMonitor >', []) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowMonitor> ns3::FlowMonitorHelper::Install(ns3::NodeContainer nodes) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::FlowMonitor >', [param('ns3::NodeContainer', 'nodes')]) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowMonitor> ns3::FlowMonitorHelper::Install(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Install', 'ns3::Ptr< ns3::FlowMonitor >', [param('ns3::Ptr< ns3::Node >', 'node')]) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowMonitor> ns3::FlowMonitorHelper::InstallAll() [member function] cls.add_method('InstallAll', 'ns3::Ptr< ns3::FlowMonitor >', []) ## flow-monitor-helper.h (module 'flow-monitor'): void ns3::FlowMonitorHelper::SetMonitorAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetMonitorAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Histogram_methods(root_module, cls): ## histogram.h (module 'flow-monitor'): ns3::Histogram::Histogram(ns3::Histogram const & arg0) [copy constructor] cls.add_constructor([param('ns3::Histogram const &', 'arg0')]) ## histogram.h (module 'flow-monitor'): ns3::Histogram::Histogram(double binWidth) [constructor] cls.add_constructor([param('double', 'binWidth')]) ## histogram.h (module 'flow-monitor'): ns3::Histogram::Histogram() [constructor] cls.add_constructor([]) ## histogram.h (module 'flow-monitor'): void ns3::Histogram::AddValue(double value) [member function] cls.add_method('AddValue', 'void', [param('double', 'value')]) ## histogram.h (module 'flow-monitor'): uint32_t ns3::Histogram::GetBinCount(uint32_t index) [member function] cls.add_method('GetBinCount', 'uint32_t', [param('uint32_t', 'index')]) ## histogram.h (module 'flow-monitor'): double ns3::Histogram::GetBinEnd(uint32_t index) [member function] cls.add_method('GetBinEnd', 'double', [param('uint32_t', 'index')]) ## histogram.h (module 'flow-monitor'): double ns3::Histogram::GetBinStart(uint32_t index) [member function] cls.add_method('GetBinStart', 'double', [param('uint32_t', 'index')]) ## histogram.h (module 'flow-monitor'): double ns3::Histogram::GetBinWidth(uint32_t index) const [member function] cls.add_method('GetBinWidth', 'double', [param('uint32_t', 'index')], is_const=True) ## histogram.h (module 'flow-monitor'): uint32_t ns3::Histogram::GetNBins() const [member function] cls.add_method('GetNBins', 'uint32_t', [], is_const=True) ## histogram.h (module 'flow-monitor'): void ns3::Histogram::SerializeToXmlStream(std::ostream & os, int indent, std::string elementName) const [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent'), param('std::string', 'elementName')], is_const=True) ## histogram.h (module 'flow-monitor'): void ns3::Histogram::SetDefaultBinWidth(double binWidth) [member function] cls.add_method('SetDefaultBinWidth', 'void', [param('double', 'binWidth')]) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy 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) [copy 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'): 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')]) return def register_Ns3IntToType__0_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')]) return def register_Ns3IntToType__1_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')]) return def register_Ns3IntToType__2_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')]) return def register_Ns3IntToType__3_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')]) return def register_Ns3IntToType__4_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')]) return def register_Ns3IntToType__5_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')]) return def register_Ns3IntToType__6_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address, ns3::Ipv6Prefix prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'prefix')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv6InterfaceAddress const &', 'o')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceAddress::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): uint32_t ns3::Ipv6InterfaceAddress::GetNsDadUid() const [member function] cls.add_method('GetNsDadUid', 'uint32_t', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Prefix ns3::Ipv6InterfaceAddress::GetPrefix() const [member function] cls.add_method('GetPrefix', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e ns3::Ipv6InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv6InterfaceAddress::Scope_e', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e ns3::Ipv6InterfaceAddress::GetState() const [member function] cls.add_method('GetState', 'ns3::Ipv6InterfaceAddress::State_e', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetAddress(ns3::Ipv6Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetNsDadUid(uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('uint32_t', 'uid')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetScope(ns3::Ipv6InterfaceAddress::Scope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv6InterfaceAddress::Scope_e', 'scope')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetState(ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3Timer_methods(root_module, cls): ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Timer const &', 'arg0')]) ## timer.h (module 'core'): ns3::Timer::Timer() [constructor] cls.add_constructor([]) ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor] cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')]) ## timer.h (module 'core'): void ns3::Timer::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function] cls.add_method('GetState', 'ns3::Timer::State', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function] cls.add_method('IsSuspended', 'bool', [], is_const=True) ## timer.h (module 'core'): void ns3::Timer::Remove() [member function] cls.add_method('Remove', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Resume() [member function] cls.add_method('Resume', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule() [member function] cls.add_method('Schedule', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function] cls.add_method('Schedule', 'void', [param('ns3::Time', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function] cls.add_method('SetDelay', 'void', [param('ns3::Time const &', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::Suspend() [member function] cls.add_method('Suspend', 'void', []) return def register_Ns3TimerImpl_methods(root_module, cls): ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor] cls.add_constructor([]) ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')]) ## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function] cls.add_method('Invoke', 'void', [], is_pure_virtual=True, is_virtual=True) ## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function] cls.add_method('Schedule', 'ns3::EventId', [param('ns3::Time const &', 'delay')], is_pure_virtual=True, is_virtual=True) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Ipv6Header_methods(root_module, cls): ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header(ns3::Ipv6Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Header const &', 'arg0')]) ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header() [constructor] cls.add_constructor([]) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetDestinationAddress() const [member function] cls.add_method('GetDestinationAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetFlowLabel() const [member function] cls.add_method('GetFlowLabel', 'uint32_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): ns3::TypeId ns3::Ipv6Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetNextHeader() const [member function] cls.add_method('GetNextHeader', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint16_t ns3::Ipv6Header::GetPayloadLength() const [member function] cls.add_method('GetPayloadLength', 'uint16_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetSourceAddress() const [member function] cls.add_method('GetSourceAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetTrafficClass() const [member function] cls.add_method('GetTrafficClass', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): static ns3::TypeId ns3::Ipv6Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetDestinationAddress(ns3::Ipv6Address dst) [member function] cls.add_method('SetDestinationAddress', 'void', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetFlowLabel(uint32_t flow) [member function] cls.add_method('SetFlowLabel', 'void', [param('uint32_t', 'flow')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetHopLimit(uint8_t limit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'limit')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetNextHeader(uint8_t next) [member function] cls.add_method('SetNextHeader', 'void', [param('uint8_t', 'next')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetPayloadLength(uint16_t len) [member function] cls.add_method('SetPayloadLength', 'void', [param('uint16_t', 'len')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetSourceAddress(ns3::Ipv6Address src) [member function] cls.add_method('SetSourceAddress', 'void', [param('ns3::Ipv6Address', 'src')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetTrafficClass(uint8_t traffic) [member function] cls.add_method('SetTrafficClass', 'void', [param('uint8_t', 'traffic')]) return def register_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'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3FlowClassifier_Ns3Empty_Ns3DefaultDeleter__lt__ns3FlowClassifier__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >::SimpleRefCount(ns3::SimpleRefCount<ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter< ns3::FlowClassifier > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::FlowClassifier, ns3::empty, ns3::DefaultDeleter<ns3::FlowClassifier> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): 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'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::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>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::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::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::IsManualIpTos() const [member function] cls.add_method('IsManualIpTos', 'bool', [], is_const=True, visibility='protected') ## 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_Ns3SocketAddressTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::Address ns3::SocketAddressTag::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::SetAddress(ns3::Address addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'addr')]) return def register_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy 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) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy 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) [copy 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_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::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 timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3FlowClassifier_methods(root_module, cls): ## flow-classifier.h (module 'flow-monitor'): ns3::FlowClassifier::FlowClassifier() [constructor] cls.add_constructor([]) ## flow-classifier.h (module 'flow-monitor'): void ns3::FlowClassifier::SerializeToXmlStream(std::ostream & os, int indent) const [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent')], is_pure_virtual=True, is_const=True, is_virtual=True) ## flow-classifier.h (module 'flow-monitor'): ns3::FlowId ns3::FlowClassifier::GetNewFlowId() [member function] cls.add_method('GetNewFlowId', 'ns3::FlowId', [], visibility='protected') return def register_Ns3FlowMonitor_methods(root_module, cls): ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowMonitor(ns3::FlowMonitor const & arg0) [copy constructor] cls.add_constructor([param('ns3::FlowMonitor const &', 'arg0')]) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowMonitor() [constructor] cls.add_constructor([]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::AddProbe(ns3::Ptr<ns3::FlowProbe> probe) [member function] cls.add_method('AddProbe', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::CheckForLostPackets() [member function] cls.add_method('CheckForLostPackets', 'void', []) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::CheckForLostPackets(ns3::Time maxDelay) [member function] cls.add_method('CheckForLostPackets', 'void', [param('ns3::Time', 'maxDelay')]) ## flow-monitor.h (module 'flow-monitor'): std::vector<ns3::Ptr<ns3::FlowProbe>, std::allocator<ns3::Ptr<ns3::FlowProbe> > > ns3::FlowMonitor::GetAllProbes() const [member function] cls.add_method('GetAllProbes', 'std::vector< ns3::Ptr< ns3::FlowProbe > >', [], is_const=True) ## flow-monitor.h (module 'flow-monitor'): std::map<unsigned int, ns3::FlowMonitor::FlowStats, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, ns3::FlowMonitor::FlowStats> > > ns3::FlowMonitor::GetFlowStats() const [member function] cls.add_method('GetFlowStats', 'std::map< unsigned int, ns3::FlowMonitor::FlowStats >', [], is_const=True) ## flow-monitor.h (module 'flow-monitor'): ns3::TypeId ns3::FlowMonitor::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## flow-monitor.h (module 'flow-monitor'): static ns3::TypeId ns3::FlowMonitor::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::ReportDrop(ns3::Ptr<ns3::FlowProbe> probe, ns3::FlowId flowId, ns3::FlowPacketId packetId, uint32_t packetSize, uint32_t reasonCode) [member function] cls.add_method('ReportDrop', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe'), param('ns3::FlowId', 'flowId'), param('ns3::FlowPacketId', 'packetId'), param('uint32_t', 'packetSize'), param('uint32_t', 'reasonCode')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::ReportFirstTx(ns3::Ptr<ns3::FlowProbe> probe, ns3::FlowId flowId, ns3::FlowPacketId packetId, uint32_t packetSize) [member function] cls.add_method('ReportFirstTx', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe'), param('ns3::FlowId', 'flowId'), param('ns3::FlowPacketId', 'packetId'), param('uint32_t', 'packetSize')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::ReportForwarding(ns3::Ptr<ns3::FlowProbe> probe, ns3::FlowId flowId, ns3::FlowPacketId packetId, uint32_t packetSize) [member function] cls.add_method('ReportForwarding', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe'), param('ns3::FlowId', 'flowId'), param('ns3::FlowPacketId', 'packetId'), param('uint32_t', 'packetSize')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::ReportLastRx(ns3::Ptr<ns3::FlowProbe> probe, ns3::FlowId flowId, ns3::FlowPacketId packetId, uint32_t packetSize) [member function] cls.add_method('ReportLastRx', 'void', [param('ns3::Ptr< ns3::FlowProbe >', 'probe'), param('ns3::FlowId', 'flowId'), param('ns3::FlowPacketId', 'packetId'), param('uint32_t', 'packetSize')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::SerializeToXmlFile(std::string fileName, bool enableHistograms, bool enableProbes) [member function] cls.add_method('SerializeToXmlFile', 'void', [param('std::string', 'fileName'), param('bool', 'enableHistograms'), param('bool', 'enableProbes')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::SerializeToXmlStream(std::ostream & os, int indent, bool enableHistograms, bool enableProbes) [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent'), param('bool', 'enableHistograms'), param('bool', 'enableProbes')]) ## flow-monitor.h (module 'flow-monitor'): std::string ns3::FlowMonitor::SerializeToXmlString(int indent, bool enableHistograms, bool enableProbes) [member function] cls.add_method('SerializeToXmlString', 'std::string', [param('int', 'indent'), param('bool', 'enableHistograms'), param('bool', 'enableProbes')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::SetFlowClassifier(ns3::Ptr<ns3::FlowClassifier> classifier) [member function] cls.add_method('SetFlowClassifier', 'void', [param('ns3::Ptr< ns3::FlowClassifier >', 'classifier')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::Start(ns3::Time const & time) [member function] cls.add_method('Start', 'void', [param('ns3::Time const &', 'time')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::StartRightNow() [member function] cls.add_method('StartRightNow', 'void', []) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')]) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::StopRightNow() [member function] cls.add_method('StopRightNow', 'void', []) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## flow-monitor.h (module 'flow-monitor'): void ns3::FlowMonitor::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3FlowMonitorFlowStats_methods(root_module, cls): ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::FlowStats() [constructor] cls.add_constructor([]) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::FlowStats(ns3::FlowMonitor::FlowStats const & arg0) [copy constructor] cls.add_constructor([param('ns3::FlowMonitor::FlowStats const &', 'arg0')]) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::bytesDropped [variable] cls.add_instance_attribute('bytesDropped', 'std::vector< unsigned long >', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::delayHistogram [variable] cls.add_instance_attribute('delayHistogram', 'ns3::Histogram', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::delaySum [variable] cls.add_instance_attribute('delaySum', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::flowInterruptionsHistogram [variable] cls.add_instance_attribute('flowInterruptionsHistogram', 'ns3::Histogram', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::jitterHistogram [variable] cls.add_instance_attribute('jitterHistogram', 'ns3::Histogram', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::jitterSum [variable] cls.add_instance_attribute('jitterSum', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::lastDelay [variable] cls.add_instance_attribute('lastDelay', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::lostPackets [variable] cls.add_instance_attribute('lostPackets', 'uint32_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::packetSizeHistogram [variable] cls.add_instance_attribute('packetSizeHistogram', 'ns3::Histogram', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::packetsDropped [variable] cls.add_instance_attribute('packetsDropped', 'std::vector< unsigned int >', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::rxBytes [variable] cls.add_instance_attribute('rxBytes', 'uint64_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::rxPackets [variable] cls.add_instance_attribute('rxPackets', 'uint32_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timeFirstRxPacket [variable] cls.add_instance_attribute('timeFirstRxPacket', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timeFirstTxPacket [variable] cls.add_instance_attribute('timeFirstTxPacket', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timeLastRxPacket [variable] cls.add_instance_attribute('timeLastRxPacket', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timeLastTxPacket [variable] cls.add_instance_attribute('timeLastTxPacket', 'ns3::Time', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::timesForwarded [variable] cls.add_instance_attribute('timesForwarded', 'uint32_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::txBytes [variable] cls.add_instance_attribute('txBytes', 'uint64_t', is_const=False) ## flow-monitor.h (module 'flow-monitor'): ns3::FlowMonitor::FlowStats::txPackets [variable] cls.add_instance_attribute('txPackets', 'uint32_t', is_const=False) return def register_Ns3FlowProbe_methods(root_module, cls): ## flow-probe.h (module 'flow-monitor'): void ns3::FlowProbe::AddPacketDropStats(ns3::FlowId flowId, uint32_t packetSize, uint32_t reasonCode) [member function] cls.add_method('AddPacketDropStats', 'void', [param('ns3::FlowId', 'flowId'), param('uint32_t', 'packetSize'), param('uint32_t', 'reasonCode')]) ## flow-probe.h (module 'flow-monitor'): void ns3::FlowProbe::AddPacketStats(ns3::FlowId flowId, uint32_t packetSize, ns3::Time delayFromFirstProbe) [member function] cls.add_method('AddPacketStats', 'void', [param('ns3::FlowId', 'flowId'), param('uint32_t', 'packetSize'), param('ns3::Time', 'delayFromFirstProbe')]) ## flow-probe.h (module 'flow-monitor'): std::map<unsigned int, ns3::FlowProbe::FlowStats, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, ns3::FlowProbe::FlowStats> > > ns3::FlowProbe::GetStats() const [member function] cls.add_method('GetStats', 'std::map< unsigned int, ns3::FlowProbe::FlowStats >', [], is_const=True) ## flow-probe.h (module 'flow-monitor'): void ns3::FlowProbe::SerializeToXmlStream(std::ostream & os, int indent, uint32_t index) const [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent'), param('uint32_t', 'index')], is_const=True) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowProbe(ns3::Ptr<ns3::FlowMonitor> flowMonitor) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::FlowMonitor >', 'flowMonitor')], visibility='protected') ## flow-probe.h (module 'flow-monitor'): void ns3::FlowProbe::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3FlowProbeFlowStats_methods(root_module, cls): ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::FlowStats(ns3::FlowProbe::FlowStats const & arg0) [copy constructor] cls.add_constructor([param('ns3::FlowProbe::FlowStats const &', 'arg0')]) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::FlowStats() [constructor] cls.add_constructor([]) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::bytes [variable] cls.add_instance_attribute('bytes', 'uint64_t', is_const=False) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::bytesDropped [variable] cls.add_instance_attribute('bytesDropped', 'std::vector< unsigned long >', is_const=False) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::delayFromFirstProbeSum [variable] cls.add_instance_attribute('delayFromFirstProbeSum', 'ns3::Time', is_const=False) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::packets [variable] cls.add_instance_attribute('packets', 'uint32_t', is_const=False) ## flow-probe.h (module 'flow-monitor'): ns3::FlowProbe::FlowStats::packetsDropped [variable] cls.add_instance_attribute('packetsDropped', 'std::vector< unsigned int >', is_const=False) return def register_Ns3IpL4Protocol_methods(root_module, cls): ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol() [constructor] cls.add_constructor([]) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol(ns3::IpL4Protocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::IpL4Protocol const &', 'arg0')]) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget() const [member function] cls.add_method('GetDownTarget', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget6() const [member function] cls.add_method('GetDownTarget6', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): int ns3::IpL4Protocol::GetProtocolNumber() const [member function] cls.add_method('GetProtocolNumber', 'int', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::IpL4Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::Ipv4Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::Ipv4Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Header const & header, ns3::Ptr<ns3::Ipv6Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Header const &', 'header'), param('ns3::Ptr< ns3::Ipv6Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv4Address payloadSource, ns3::Ipv4Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv4Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv4Address', 'payloadSource'), param('ns3::Ipv4Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv6Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv6Address payloadSource, ns3::Ipv6Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv6Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv6Address', 'payloadSource'), param('ns3::Ipv6Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget6(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget6', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4FlowClassifier_methods(root_module, cls): ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::Ipv4FlowClassifier() [constructor] cls.add_constructor([]) ## ipv4-flow-classifier.h (module 'flow-monitor'): bool ns3::Ipv4FlowClassifier::Classify(ns3::Ipv4Header const & ipHeader, ns3::Ptr<const ns3::Packet> ipPayload, uint32_t * out_flowId, uint32_t * out_packetId) [member function] cls.add_method('Classify', 'bool', [param('ns3::Ipv4Header const &', 'ipHeader'), param('ns3::Ptr< ns3::Packet const >', 'ipPayload'), param('uint32_t *', 'out_flowId'), param('uint32_t *', 'out_packetId')]) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple ns3::Ipv4FlowClassifier::FindFlow(ns3::FlowId flowId) const [member function] cls.add_method('FindFlow', 'ns3::Ipv4FlowClassifier::FiveTuple', [param('ns3::FlowId', 'flowId')], is_const=True) ## ipv4-flow-classifier.h (module 'flow-monitor'): void ns3::Ipv4FlowClassifier::SerializeToXmlStream(std::ostream & os, int indent) const [member function] cls.add_method('SerializeToXmlStream', 'void', [param('std::ostream &', 'os'), param('int', 'indent')], is_const=True, is_virtual=True) return def register_Ns3Ipv4FlowClassifierFiveTuple_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('==') ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::FiveTuple() [constructor] cls.add_constructor([]) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::FiveTuple(ns3::Ipv4FlowClassifier::FiveTuple const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4FlowClassifier::FiveTuple const &', 'arg0')]) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::destinationAddress [variable] cls.add_instance_attribute('destinationAddress', 'ns3::Ipv4Address', is_const=False) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::destinationPort [variable] cls.add_instance_attribute('destinationPort', 'uint16_t', is_const=False) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::protocol [variable] cls.add_instance_attribute('protocol', 'uint8_t', is_const=False) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::sourceAddress [variable] cls.add_instance_attribute('sourceAddress', 'ns3::Ipv4Address', is_const=False) ## ipv4-flow-classifier.h (module 'flow-monitor'): ns3::Ipv4FlowClassifier::FiveTuple::sourcePort [variable] cls.add_instance_attribute('sourcePort', 'uint16_t', is_const=False) return def register_Ns3Ipv4FlowProbe_methods(root_module, cls): ## ipv4-flow-probe.h (module 'flow-monitor'): ns3::Ipv4FlowProbe::Ipv4FlowProbe(ns3::Ptr<ns3::FlowMonitor> monitor, ns3::Ptr<ns3::Ipv4FlowClassifier> classifier, ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::FlowMonitor >', 'monitor'), param('ns3::Ptr< ns3::Ipv4FlowClassifier >', 'classifier'), param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-flow-probe.h (module 'flow-monitor'): void ns3::Ipv4FlowProbe::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv4L3Protocol_methods(root_module, cls): ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor] cls.add_constructor([]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv4Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], visibility='private', is_virtual=True) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv4MulticastRoute_methods(root_module, cls): ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetOutputTtl(uint32_t oif) [member function] cls.add_method('GetOutputTtl', 'uint32_t', [param('uint32_t', 'oif')], deprecated=True) ## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function] cls.add_method('GetOutputTtlMap', 'std::map< unsigned int, unsigned int >', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'src')]) return def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void,ns3::Ptr<ns3::Ipv4Route>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6Interface_methods(root_module, cls): ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface(ns3::Ipv6Interface const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Interface const &', 'arg0')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface() [constructor] cls.add_constructor([]) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::AddAddress(ns3::Ipv6InterfaceAddress iface) [member function] cls.add_method('AddAddress', 'bool', [param('ns3::Ipv6InterfaceAddress', 'iface')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddress(uint32_t index) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddressMatchingDestination(ns3::Ipv6Address dst) [member function] cls.add_method('GetAddressMatchingDestination', 'ns3::Ipv6InterfaceAddress', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetBaseReachableTime() const [member function] cls.add_method('GetBaseReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint8_t ns3::Ipv6Interface::GetCurHopLimit() const [member function] cls.add_method('GetCurHopLimit', 'uint8_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6Interface::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True, is_virtual=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetLinkLocalAddress() const [member function] cls.add_method('GetLinkLocalAddress', 'ns3::Ipv6InterfaceAddress', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetMetric() const [member function] cls.add_method('GetMetric', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint32_t ns3::Ipv6Interface::GetNAddresses() const [member function] cls.add_method('GetNAddresses', 'uint32_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetReachableTime() const [member function] cls.add_method('GetReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetRetransTimer() const [member function] cls.add_method('GetRetransTimer', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv6Interface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsDown() const [member function] cls.add_method('IsDown', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsForwarding() const [member function] cls.add_method('IsForwarding', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsUp() const [member function] cls.add_method('IsUp', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(uint32_t index) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(ns3::Ipv6Address address) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv6InterfaceAddress', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address dest) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address', 'dest')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetBaseReachableTime(uint16_t baseReachableTime) [member function] cls.add_method('SetBaseReachableTime', 'void', [param('uint16_t', 'baseReachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetCurHopLimit(uint8_t curHopLimit) [member function] cls.add_method('SetCurHopLimit', 'void', [param('uint8_t', 'curHopLimit')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDown() [member function] cls.add_method('SetDown', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetForwarding(bool forward) [member function] cls.add_method('SetForwarding', 'void', [param('bool', 'forward')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetMetric(uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint16_t', 'metric')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNsDadUid(ns3::Ipv6Address address, uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('ns3::Ipv6Address', 'address'), param('uint32_t', 'uid')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetReachableTime(uint16_t reachableTime) [member function] cls.add_method('SetReachableTime', 'void', [param('uint16_t', 'reachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetRetransTimer(uint16_t retransTimer) [member function] cls.add_method('SetRetransTimer', 'void', [param('uint16_t', 'retransTimer')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetState(ns3::Ipv6Address address, ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetUp() [member function] cls.add_method('SetUp', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): 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> arg0) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def 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()
Endika/django
refs/heads/master
tests/migrations/test_migrations_squashed_erroneous/6_auto.py
770
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("migrations", "5_auto")] operations = [ migrations.RunPython(migrations.RunPython.noop) ]
farooqsheikhpk/Aspose.BarCode-for-Cloud
refs/heads/master
SDKs/Aspose.BarCode-Cloud-SDK-for-Python/asposebarcodecloud/models/Barcode.py
5
#!/usr/bin/env python class Barcode(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): """ Attributes: swaggerTypes (dict): The key is attribute name and the value is attribute type. attributeMap (dict): The key is attribute name and the value is json key in definition. """ self.swaggerTypes = { 'Checksum': 'str', 'Region': 'list[str]', 'BarcodeValue': 'str', 'BarcodeType': 'str' } self.attributeMap = { 'Checksum': 'Checksum','Region': 'Region','BarcodeValue': 'BarcodeValue','BarcodeType': 'BarcodeType'} self.ChecksumValidation = None self.Region = None self.BarcodeValue = None self.BarcodeType = None
ilexius/odoo
refs/heads/master
openerp/report/render/rml2pdf/__init__.py
49
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from trml2pdf import parseString, parseNode
galtys/odoo
refs/heads/8.0
addons/l10n_ma/l10n_ma.py
336
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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/>. # ############################################################################## from openerp.osv import fields, osv class l10n_ma_report(osv.osv): _name = 'l10n.ma.report' _description = 'Report for l10n_ma_kzc' _columns = { 'code': fields.char('Code', size=64), 'name': fields.char('Name'), 'line_ids': fields.one2many('l10n.ma.line', 'report_id', 'Lines', copy=True), } _sql_constraints = [ ('code_uniq', 'unique (code)','The code report must be unique !') ] class l10n_ma_line(osv.osv): _name = 'l10n.ma.line' _description = 'Report Lines for l10n_ma' _columns = { 'code': fields.char('Variable Name', size=64), 'definition': fields.char('Definition'), 'name': fields.char('Name'), 'report_id': fields.many2one('l10n.ma.report', 'Report'), } _sql_constraints = [ ('code_uniq', 'unique (code)', 'The variable name must be unique !') ] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
bit-jmm/ttarm
refs/heads/master
demo/demo_at_tsinghua.py
1
# encoding: utf-8 import sys sys.path.append('/home/zjd/jmm/JPPCF/') import os import numpy as np import util from JPPCF import * import logging argvs = sys.argv # We fix the num of latent feature k = 100 lambd = 0.5 if len(argvs) == 3: k = int(float(argvs[1])) lambd = float(argvs[2]) print 'k: ', k, '\tlambda: ', lambd, '\n' data_path = './data/preprocessed_data/filtered_by_user_doc_like_list_len_5/' R = np.loadtxt(data_path + 'rating_file.dat.txt', int) user_num = R[:, 0].max() doc_num = R[:, 1].max() time_step_num = R[:, 2].max() print 'user num: ', user_num, '\n' print 'doc num: ', doc_num, '\n' print 'time step num: ', time_step_num, '\n' regl1nmf = 0.005 regl1jpp = 0.05 epsilon = 1 maxiter = 70 #recall_num = 100 fold_num = 5 Rall = util.generate_matrice_between_time(R, user_num, doc_num, 1, time_step_num) #Rall = np.ones((100, 50)) print Rall.shape logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d]\ %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='./log/tsinghua_server/k_' + str(k) + '_lambda_' + \ str(lambd) + '_alpha_' + str(regl1jpp) + '.log', filemode='w') ################################################################## #定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误, #并将其添加到当前的日志处理对象# console = logging.StreamHandler() console.setLevel(logging.INFO) formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) ################################################################## #logging.debug('This is debug message') #logging.info('This is info message') #logging.warning('This is warning message') result_dir = './result/tsinghua_server/cross_validate_fold_' + str(fold_num) + \ '_3models_k_' + str(k) + '_lambda_' + str(lambd) + '_alpha_' + str(regl1jpp) if not os.path.isdir(result_dir): os.mkdir(result_dir) # the start time period used for init of W(1) and H(1), using normal NMF start = 1 Rt = util.generate_matrice_between_time(R, user_num, doc_num, start, start) #Rt = np.ones((100, 50)) logging.info('non zero cell num: ' + str(len(np.nonzero(Rt)[0]))) logging.info('start nmf:\n') (P, Q) = util.nmf(Rt, k, maxiter, regl1nmf, epsilon) print P.shape, Q.shape # number of period we consider finT = time_step_num #for all the consecutive periods for current_time_step in range(start+1, finT + 1): logging.info('\n=========================\n') logging.info('time_step number %i:\n' + str(current_time_step)) logging.info('----------------\n') #Rtall = util.generate_matrice_between_time(R, user_num, doc_num, # current_time_step, current_time_step) Po = P trecall_dict = {} frecall_dict = {} jrecall_dict = {} for fold_id in range(fold_num): #for fold_id in [0]: train_data_path = data_path + 'time_step_' + str(current_time_step) + \ '/data_' + str(fold_id) + '/train.dat.txt' Rt = util.generate_matrice_for_file(train_data_path, user_num, doc_num) logging.info('non zero cell num: ' + str(len(np.nonzero(Rt)[0]))) #Rt = np.ones((100, 50)) logging.info('computing JPP decomposition...') P, Q, S = JPPCF(Rt, Po, Po.shape[1], lambd, regl1jpp, epsilon, maxiter, True) PredictR = np.dot(P, Q) NormPR = PredictR / PredictR.max() logging.info('[ok]\ncomputing t-model NMF decomposition...') Pbaseline, Qbaseline = util.nmf(Rt, k, maxiter, regl1nmf, epsilon) PredictRbaseline = np.dot(Pbaseline, Qbaseline) NormPRbaseline = PredictRbaseline / PredictRbaseline.max() logging.info('[ok]\ncomputing fix_model NMF decomposition...') Rt = util.generate_matrice_between_time(R, user_num, doc_num, start + 1, current_time_step-1, train_data_path) #Rt = np.ones((100, 50)) logging.info('non zero cell num: ' + str(len(np.nonzero(Rt)[0]))) Pbaseline2, Qbaseline2 = util.nmf(Rt, k, maxiter, regl1nmf, epsilon) PredictRbaseline2 = np.dot(Pbaseline2, Qbaseline2) NormPRbaseline2 = PredictRbaseline2 / PredictRbaseline2.max() logging.info('[ok]\n') logging.info('\t fold_id:' + str(fold_id) + '\n') for recall_num in [10,50,100,300,500,1000]: logging.info('\trecall at ' + str(recall_num) + ':') current_data_path = data_path + 'time_step_' + \ str(current_time_step) + '/data_' + \ str(fold_id) tnmf_recall = util.performance_cross_validate_recall( NormPRbaseline, current_data_path, recall_num) fnmf_recall = util.performance_cross_validate_recall( NormPRbaseline2, current_data_path, recall_num) jppcf_recall = util.performance_cross_validate_recall( NormPR, current_data_path, recall_num) if trecall_dict.has_key(recall_num): trecall_dict[recall_num].append(tnmf_recall) else: trecall_dict[recall_num] = [tnmf_recall] if frecall_dict.has_key(recall_num): frecall_dict[recall_num].append(fnmf_recall) else: frecall_dict[recall_num] = [fnmf_recall] if jrecall_dict.has_key(recall_num): jrecall_dict[recall_num].append(jppcf_recall) else: jrecall_dict[recall_num] = [jppcf_recall] logging.info('\t\tt-model NMF : ' + str(tnmf_recall) + '\n') logging.info('\t\tf-model NMF : ' + str(fnmf_recall) + '\n') logging.info('\t\tJPPCF : ' + str(jppcf_recall) + '\n') logging.info('current_time_step: ' + str(current_time_step) + '\n') for recall_num in [10,50,100,300,500,1000]: print '\tcross validate recall at ',recall_num, ':' avg_tnmf_recall = util.avg_of_list(trecall_dict[recall_num]) avg_fnmf_recall = util.avg_of_list(frecall_dict[recall_num]) avg_jppcf_recall = util.avg_of_list(jrecall_dict[recall_num]) logging.info('\t\tavg t-model NMF : ' + str(avg_tnmf_recall) + '\n') logging.info('\t\tavg f-model NMF : ' + str(avg_fnmf_recall) + '\n') logging.info('\t\tavg JPPCF : ' + str(avg_jppcf_recall) + '\n') exist = False if os.path.isfile(result_dir + '/recall_at_' + str(recall_num) + '.txt'): exist = True result_file = open(result_dir + '/recall_at_' + str(recall_num) + '.txt', 'a') if not exist: result_file.write('t-model-nmf\tfix-model-nmf\tjppcf\n') result_file.write(str(avg_tnmf_recall) + '\t' + str(avg_fnmf_recall) + \ '\t' + str(avg_jppcf_recall) + '\n') result_file.close() logging.info('=========================\n') logging.info('all process done! exit now...')
benjaminrigaud/django
refs/heads/master
tests/proxy_model_inheritance/tests.py
24
from __future__ import absolute_import, unicode_literals import os from django.core.management import call_command from django.test import TestCase, TransactionTestCase from django.test.utils import extend_sys_path from django.utils._os import upath from .models import (ConcreteModel, ConcreteModelSubclass, ConcreteModelSubclassProxy) class ProxyModelInheritanceTests(TransactionTestCase): """ Proxy model inheritance across apps can result in migrate not creating the table for the proxied model (as described in #12286). This test creates two dummy apps and calls migrate, then verifies that the table has been created. """ available_apps = [] def test_table_exists(self): with extend_sys_path(os.path.dirname(os.path.abspath(upath(__file__)))): with self.modify_settings(INSTALLED_APPS={'append': ['app1', 'app2']}): call_command('migrate', verbosity=0) from app1.models import ProxyModel from app2.models import NiceModel self.assertEqual(NiceModel.objects.all().count(), 0) self.assertEqual(ProxyModel.objects.all().count(), 0) class MultiTableInheritanceProxyTest(TestCase): def test_model_subclass_proxy(self): """ Deleting an instance of a model proxying a multi-table inherited subclass should cascade delete down the whole inheritance chain (see #18083). """ instance = ConcreteModelSubclassProxy.objects.create() instance.delete() self.assertEqual(0, ConcreteModelSubclassProxy.objects.count()) self.assertEqual(0, ConcreteModelSubclass.objects.count()) self.assertEqual(0, ConcreteModel.objects.count())
DazWorrall/ansible
refs/heads/devel
lib/ansible/modules/cloud/amazon/ec2_vol_facts.py
29
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ec2_vol_facts short_description: Gather facts about ec2 volumes in AWS description: - Gather facts about ec2 volumes in AWS version_added: "2.1" author: "Rob White (@wimnat)" options: filters: description: - A dict of filters to apply. Each dict item consists of a filter key and a filter value. See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVolumes.html) for possible filters. required: false default: null extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Gather facts about all volumes - ec2_vol_facts: # Gather facts about a particular volume using volume ID - ec2_vol_facts: filters: volume-id: vol-00112233 # Gather facts about any volume with a tag key Name and value Example - ec2_vol_facts: filters: "tag:Name": Example # Gather facts about any volume that is attached - ec2_vol_facts: filters: attachment.status: attached ''' # TODO: Disabled the RETURN as it was breaking docs building. Someone needs to # fix this RETURN = '''# ''' import traceback try: import boto.ec2 from boto.exception import BotoServerError HAS_BOTO = True except ImportError: HAS_BOTO = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import connect_to_aws, ec2_argument_spec, get_aws_connection_info from ansible.module_utils._text import to_native def get_volume_info(volume): attachment = volume.attach_data volume_info = { 'create_time': volume.create_time, 'id': volume.id, 'encrypted': volume.encrypted, 'iops': volume.iops, 'size': volume.size, 'snapshot_id': volume.snapshot_id, 'status': volume.status, 'type': volume.type, 'zone': volume.zone, 'region': volume.region.name, 'attachment_set': { 'attach_time': attachment.attach_time, 'device': attachment.device, 'instance_id': attachment.instance_id, 'status': attachment.status }, 'tags': volume.tags } return volume_info def list_ec2_volumes(connection, module): filters = module.params.get("filters") volume_dict_array = [] try: all_volumes = connection.get_all_volumes(filters=filters) except BotoServerError as e: module.fail_json(msg=e.message) for volume in all_volumes: volume_dict_array.append(get_volume_info(volume)) module.exit_json(volumes=volume_dict_array) def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( filters = dict(default=None, type='dict') ) ) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module) if region: try: connection = connect_to_aws(boto.ec2, region, **aws_connect_params) except (boto.exception.NoAuthHandlerFound, Exception) as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) else: module.fail_json(msg="region must be specified") list_ec2_volumes(connection, module) if __name__ == '__main__': main()
markYoungH/chromium.src
refs/heads/nw12
third_party/cython/src/Cython/Tests/__init__.py
1472
# empty file
dcosentino/edx-platform
refs/heads/master
common/test/acceptance/pages/studio/__init__.py
232
import os # Get the URL of the instance under test BASE_URL = os.environ.get('test_url', 'http://localhost:8031')
nicolargo/intellij-community
refs/heads/master
python/helpers/pydev/pydevd_attach_to_process/winappdbg/win32/dbghelp.py
88
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2014, Mario Vilas # 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 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. """ Wrapper for dbghelp.dll in ctypes. """ __revision__ = "$Id$" from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * # DbgHelp versions and features list: # http://msdn.microsoft.com/en-us/library/windows/desktop/ms679294(v=vs.85).aspx #------------------------------------------------------------------------------ # Tries to load the newest version of dbghelp.dll if available. def _load_latest_dbghelp_dll(): from os import getenv from os.path import join if arch == ARCH_AMD64: if wow64: pathname = join( getenv("ProgramFiles(x86)", getenv("ProgramFiles")), "Debugging Tools for Windows (x86)", "dbghelp.dll") else: pathname = join( getenv("ProgramFiles"), "Debugging Tools for Windows (x64)", "dbghelp.dll") elif arch == ARCH_I386: pathname = join( getenv("ProgramFiles"), "Debugging Tools for Windows (x86)", "dbghelp.dll") else: pathname = None if pathname: try: _dbghelp = ctypes.windll.LoadLibrary(pathname) ctypes.windll.dbghelp = _dbghelp except Exception: pass _load_latest_dbghelp_dll() # Recover the old binding of the "os" symbol. # XXX FIXME not sure if I really need to do this! ##from version import os #------------------------------------------------------------------------------ #============================================================================== # This is used later on to calculate the list of exported symbols. _all = None _all = set(vars().keys()) #============================================================================== # SymGetHomeDirectory "type" values hdBase = 0 hdSym = 1 hdSrc = 2 UNDNAME_32_BIT_DECODE = 0x0800 UNDNAME_COMPLETE = 0x0000 UNDNAME_NAME_ONLY = 0x1000 UNDNAME_NO_ACCESS_SPECIFIERS = 0x0080 UNDNAME_NO_ALLOCATION_LANGUAGE = 0x0010 UNDNAME_NO_ALLOCATION_MODEL = 0x0008 UNDNAME_NO_ARGUMENTS = 0x2000 UNDNAME_NO_CV_THISTYPE = 0x0040 UNDNAME_NO_FUNCTION_RETURNS = 0x0004 UNDNAME_NO_LEADING_UNDERSCORES = 0x0001 UNDNAME_NO_MEMBER_TYPE = 0x0200 UNDNAME_NO_MS_KEYWORDS = 0x0002 UNDNAME_NO_MS_THISTYPE = 0x0020 UNDNAME_NO_RETURN_UDT_MODEL = 0x0400 UNDNAME_NO_SPECIAL_SYMS = 0x4000 UNDNAME_NO_THISTYPE = 0x0060 UNDNAME_NO_THROW_SIGNATURES = 0x0100 #--- IMAGEHLP_MODULE structure and related ------------------------------------ SYMOPT_ALLOW_ABSOLUTE_SYMBOLS = 0x00000800 SYMOPT_ALLOW_ZERO_ADDRESS = 0x01000000 SYMOPT_AUTO_PUBLICS = 0x00010000 SYMOPT_CASE_INSENSITIVE = 0x00000001 SYMOPT_DEBUG = 0x80000000 SYMOPT_DEFERRED_LOADS = 0x00000004 SYMOPT_DISABLE_SYMSRV_AUTODETECT = 0x02000000 SYMOPT_EXACT_SYMBOLS = 0x00000400 SYMOPT_FAIL_CRITICAL_ERRORS = 0x00000200 SYMOPT_FAVOR_COMPRESSED = 0x00800000 SYMOPT_FLAT_DIRECTORY = 0x00400000 SYMOPT_IGNORE_CVREC = 0x00000080 SYMOPT_IGNORE_IMAGEDIR = 0x00200000 SYMOPT_IGNORE_NT_SYMPATH = 0x00001000 SYMOPT_INCLUDE_32BIT_MODULES = 0x00002000 SYMOPT_LOAD_ANYTHING = 0x00000040 SYMOPT_LOAD_LINES = 0x00000010 SYMOPT_NO_CPP = 0x00000008 SYMOPT_NO_IMAGE_SEARCH = 0x00020000 SYMOPT_NO_PROMPTS = 0x00080000 SYMOPT_NO_PUBLICS = 0x00008000 SYMOPT_NO_UNQUALIFIED_LOADS = 0x00000100 SYMOPT_OVERWRITE = 0x00100000 SYMOPT_PUBLICS_ONLY = 0x00004000 SYMOPT_SECURE = 0x00040000 SYMOPT_UNDNAME = 0x00000002 ##SSRVOPT_DWORD ##SSRVOPT_DWORDPTR ##SSRVOPT_GUIDPTR ## ##SSRVOPT_CALLBACK ##SSRVOPT_DOWNSTREAM_STORE ##SSRVOPT_FLAT_DEFAULT_STORE ##SSRVOPT_FAVOR_COMPRESSED ##SSRVOPT_NOCOPY ##SSRVOPT_OVERWRITE ##SSRVOPT_PARAMTYPE ##SSRVOPT_PARENTWIN ##SSRVOPT_PROXY ##SSRVOPT_RESET ##SSRVOPT_SECURE ##SSRVOPT_SETCONTEXT ##SSRVOPT_TRACE ##SSRVOPT_UNATTENDED # typedef enum # { # SymNone = 0, # SymCoff, # SymCv, # SymPdb, # SymExport, # SymDeferred, # SymSym, # SymDia, # SymVirtual, # NumSymTypes # } SYM_TYPE; SymNone = 0 SymCoff = 1 SymCv = 2 SymPdb = 3 SymExport = 4 SymDeferred = 5 SymSym = 6 SymDia = 7 SymVirtual = 8 NumSymTypes = 9 # typedef struct _IMAGEHLP_MODULE64 { # DWORD SizeOfStruct; # DWORD64 BaseOfImage; # DWORD ImageSize; # DWORD TimeDateStamp; # DWORD CheckSum; # DWORD NumSyms; # SYM_TYPE SymType; # TCHAR ModuleName[32]; # TCHAR ImageName[256]; # TCHAR LoadedImageName[256]; # TCHAR LoadedPdbName[256]; # DWORD CVSig; # TCHAR CVData[MAX_PATH*3]; # DWORD PdbSig; # GUID PdbSig70; # DWORD PdbAge; # BOOL PdbUnmatched; # BOOL DbgUnmatched; # BOOL LineNumbers; # BOOL GlobalSymbols; # BOOL TypeInfo; # BOOL SourceIndexed; # BOOL Publics; # } IMAGEHLP_MODULE64, *PIMAGEHLP_MODULE64; class IMAGEHLP_MODULE (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("BaseOfImage", DWORD), ("ImageSize", DWORD), ("TimeDateStamp", DWORD), ("CheckSum", DWORD), ("NumSyms", DWORD), ("SymType", DWORD), # SYM_TYPE ("ModuleName", CHAR * 32), ("ImageName", CHAR * 256), ("LoadedImageName", CHAR * 256), ] PIMAGEHLP_MODULE = POINTER(IMAGEHLP_MODULE) class IMAGEHLP_MODULE64 (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("BaseOfImage", DWORD64), ("ImageSize", DWORD), ("TimeDateStamp", DWORD), ("CheckSum", DWORD), ("NumSyms", DWORD), ("SymType", DWORD), # SYM_TYPE ("ModuleName", CHAR * 32), ("ImageName", CHAR * 256), ("LoadedImageName", CHAR * 256), ("LoadedPdbName", CHAR * 256), ("CVSig", DWORD), ("CVData", CHAR * (MAX_PATH * 3)), ("PdbSig", DWORD), ("PdbSig70", GUID), ("PdbAge", DWORD), ("PdbUnmatched", BOOL), ("DbgUnmatched", BOOL), ("LineNumbers", BOOL), ("GlobalSymbols", BOOL), ("TypeInfo", BOOL), ("SourceIndexed", BOOL), ("Publics", BOOL), ] PIMAGEHLP_MODULE64 = POINTER(IMAGEHLP_MODULE64) class IMAGEHLP_MODULEW (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("BaseOfImage", DWORD), ("ImageSize", DWORD), ("TimeDateStamp", DWORD), ("CheckSum", DWORD), ("NumSyms", DWORD), ("SymType", DWORD), # SYM_TYPE ("ModuleName", WCHAR * 32), ("ImageName", WCHAR * 256), ("LoadedImageName", WCHAR * 256), ] PIMAGEHLP_MODULEW = POINTER(IMAGEHLP_MODULEW) class IMAGEHLP_MODULEW64 (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("BaseOfImage", DWORD64), ("ImageSize", DWORD), ("TimeDateStamp", DWORD), ("CheckSum", DWORD), ("NumSyms", DWORD), ("SymType", DWORD), # SYM_TYPE ("ModuleName", WCHAR * 32), ("ImageName", WCHAR * 256), ("LoadedImageName", WCHAR * 256), ("LoadedPdbName", WCHAR * 256), ("CVSig", DWORD), ("CVData", WCHAR * (MAX_PATH * 3)), ("PdbSig", DWORD), ("PdbSig70", GUID), ("PdbAge", DWORD), ("PdbUnmatched", BOOL), ("DbgUnmatched", BOOL), ("LineNumbers", BOOL), ("GlobalSymbols", BOOL), ("TypeInfo", BOOL), ("SourceIndexed", BOOL), ("Publics", BOOL), ] PIMAGEHLP_MODULEW64 = POINTER(IMAGEHLP_MODULEW64) #--- dbghelp.dll -------------------------------------------------------------- # XXX the ANSI versions of these functions don't end in "A" as expected! # BOOL WINAPI MakeSureDirectoryPathExists( # _In_ PCSTR DirPath # ); def MakeSureDirectoryPathExistsA(DirPath): _MakeSureDirectoryPathExists = windll.dbghelp.MakeSureDirectoryPathExists _MakeSureDirectoryPathExists.argtypes = [LPSTR] _MakeSureDirectoryPathExists.restype = bool _MakeSureDirectoryPathExists.errcheck = RaiseIfZero return _MakeSureDirectoryPathExists(DirPath) MakeSureDirectoryPathExistsW = MakeWideVersion(MakeSureDirectoryPathExistsA) MakeSureDirectoryPathExists = GuessStringType(MakeSureDirectoryPathExistsA, MakeSureDirectoryPathExistsW) # BOOL WINAPI SymInitialize( # __in HANDLE hProcess, # __in_opt PCTSTR UserSearchPath, # __in BOOL fInvadeProcess # ); def SymInitializeA(hProcess, UserSearchPath = None, fInvadeProcess = False): _SymInitialize = windll.dbghelp.SymInitialize _SymInitialize.argtypes = [HANDLE, LPSTR, BOOL] _SymInitialize.restype = bool _SymInitialize.errcheck = RaiseIfZero if not UserSearchPath: UserSearchPath = None _SymInitialize(hProcess, UserSearchPath, fInvadeProcess) SymInitializeW = MakeWideVersion(SymInitializeA) SymInitialize = GuessStringType(SymInitializeA, SymInitializeW) # BOOL WINAPI SymCleanup( # __in HANDLE hProcess # ); def SymCleanup(hProcess): _SymCleanup = windll.dbghelp.SymCleanup _SymCleanup.argtypes = [HANDLE] _SymCleanup.restype = bool _SymCleanup.errcheck = RaiseIfZero _SymCleanup(hProcess) # BOOL WINAPI SymRefreshModuleList( # __in HANDLE hProcess # ); def SymRefreshModuleList(hProcess): _SymRefreshModuleList = windll.dbghelp.SymRefreshModuleList _SymRefreshModuleList.argtypes = [HANDLE] _SymRefreshModuleList.restype = bool _SymRefreshModuleList.errcheck = RaiseIfZero _SymRefreshModuleList(hProcess) # BOOL WINAPI SymSetParentWindow( # __in HWND hwnd # ); def SymSetParentWindow(hwnd): _SymSetParentWindow = windll.dbghelp.SymSetParentWindow _SymSetParentWindow.argtypes = [HWND] _SymSetParentWindow.restype = bool _SymSetParentWindow.errcheck = RaiseIfZero _SymSetParentWindow(hwnd) # DWORD WINAPI SymSetOptions( # __in DWORD SymOptions # ); def SymSetOptions(SymOptions): _SymSetOptions = windll.dbghelp.SymSetOptions _SymSetOptions.argtypes = [DWORD] _SymSetOptions.restype = DWORD _SymSetOptions.errcheck = RaiseIfZero _SymSetOptions(SymOptions) # DWORD WINAPI SymGetOptions(void); def SymGetOptions(): _SymGetOptions = windll.dbghelp.SymGetOptions _SymGetOptions.argtypes = [] _SymGetOptions.restype = DWORD return _SymGetOptions() # DWORD WINAPI SymLoadModule( # __in HANDLE hProcess, # __in_opt HANDLE hFile, # __in_opt PCSTR ImageName, # __in_opt PCSTR ModuleName, # __in DWORD BaseOfDll, # __in DWORD SizeOfDll # ); def SymLoadModuleA(hProcess, hFile = None, ImageName = None, ModuleName = None, BaseOfDll = None, SizeOfDll = None): _SymLoadModule = windll.dbghelp.SymLoadModule _SymLoadModule.argtypes = [HANDLE, HANDLE, LPSTR, LPSTR, DWORD, DWORD] _SymLoadModule.restype = DWORD if not ImageName: ImageName = None if not ModuleName: ModuleName = None if not BaseOfDll: BaseOfDll = 0 if not SizeOfDll: SizeOfDll = 0 SetLastError(ERROR_SUCCESS) lpBaseAddress = _SymLoadModule(hProcess, hFile, ImageName, ModuleName, BaseOfDll, SizeOfDll) if lpBaseAddress == NULL: dwErrorCode = GetLastError() if dwErrorCode != ERROR_SUCCESS: raise ctypes.WinError(dwErrorCode) return lpBaseAddress SymLoadModuleW = MakeWideVersion(SymLoadModuleA) SymLoadModule = GuessStringType(SymLoadModuleA, SymLoadModuleW) # DWORD64 WINAPI SymLoadModule64( # __in HANDLE hProcess, # __in_opt HANDLE hFile, # __in_opt PCSTR ImageName, # __in_opt PCSTR ModuleName, # __in DWORD64 BaseOfDll, # __in DWORD SizeOfDll # ); def SymLoadModule64A(hProcess, hFile = None, ImageName = None, ModuleName = None, BaseOfDll = None, SizeOfDll = None): _SymLoadModule64 = windll.dbghelp.SymLoadModule64 _SymLoadModule64.argtypes = [HANDLE, HANDLE, LPSTR, LPSTR, DWORD64, DWORD] _SymLoadModule64.restype = DWORD64 if not ImageName: ImageName = None if not ModuleName: ModuleName = None if not BaseOfDll: BaseOfDll = 0 if not SizeOfDll: SizeOfDll = 0 SetLastError(ERROR_SUCCESS) lpBaseAddress = _SymLoadModule64(hProcess, hFile, ImageName, ModuleName, BaseOfDll, SizeOfDll) if lpBaseAddress == NULL: dwErrorCode = GetLastError() if dwErrorCode != ERROR_SUCCESS: raise ctypes.WinError(dwErrorCode) return lpBaseAddress SymLoadModule64W = MakeWideVersion(SymLoadModule64A) SymLoadModule64 = GuessStringType(SymLoadModule64A, SymLoadModule64W) # BOOL WINAPI SymUnloadModule( # __in HANDLE hProcess, # __in DWORD BaseOfDll # ); def SymUnloadModule(hProcess, BaseOfDll): _SymUnloadModule = windll.dbghelp.SymUnloadModule _SymUnloadModule.argtypes = [HANDLE, DWORD] _SymUnloadModule.restype = bool _SymUnloadModule.errcheck = RaiseIfZero _SymUnloadModule(hProcess, BaseOfDll) # BOOL WINAPI SymUnloadModule64( # __in HANDLE hProcess, # __in DWORD64 BaseOfDll # ); def SymUnloadModule64(hProcess, BaseOfDll): _SymUnloadModule64 = windll.dbghelp.SymUnloadModule64 _SymUnloadModule64.argtypes = [HANDLE, DWORD64] _SymUnloadModule64.restype = bool _SymUnloadModule64.errcheck = RaiseIfZero _SymUnloadModule64(hProcess, BaseOfDll) # BOOL WINAPI SymGetModuleInfo( # __in HANDLE hProcess, # __in DWORD dwAddr, # __out PIMAGEHLP_MODULE ModuleInfo # ); def SymGetModuleInfoA(hProcess, dwAddr): _SymGetModuleInfo = windll.dbghelp.SymGetModuleInfo _SymGetModuleInfo.argtypes = [HANDLE, DWORD, PIMAGEHLP_MODULE] _SymGetModuleInfo.restype = bool _SymGetModuleInfo.errcheck = RaiseIfZero ModuleInfo = IMAGEHLP_MODULE() ModuleInfo.SizeOfStruct = sizeof(ModuleInfo) _SymGetModuleInfo(hProcess, dwAddr, byref(ModuleInfo)) return ModuleInfo def SymGetModuleInfoW(hProcess, dwAddr): _SymGetModuleInfoW = windll.dbghelp.SymGetModuleInfoW _SymGetModuleInfoW.argtypes = [HANDLE, DWORD, PIMAGEHLP_MODULEW] _SymGetModuleInfoW.restype = bool _SymGetModuleInfoW.errcheck = RaiseIfZero ModuleInfo = IMAGEHLP_MODULEW() ModuleInfo.SizeOfStruct = sizeof(ModuleInfo) _SymGetModuleInfoW(hProcess, dwAddr, byref(ModuleInfo)) return ModuleInfo SymGetModuleInfo = GuessStringType(SymGetModuleInfoA, SymGetModuleInfoW) # BOOL WINAPI SymGetModuleInfo64( # __in HANDLE hProcess, # __in DWORD64 dwAddr, # __out PIMAGEHLP_MODULE64 ModuleInfo # ); def SymGetModuleInfo64A(hProcess, dwAddr): _SymGetModuleInfo64 = windll.dbghelp.SymGetModuleInfo64 _SymGetModuleInfo64.argtypes = [HANDLE, DWORD64, PIMAGEHLP_MODULE64] _SymGetModuleInfo64.restype = bool _SymGetModuleInfo64.errcheck = RaiseIfZero ModuleInfo = IMAGEHLP_MODULE64() ModuleInfo.SizeOfStruct = sizeof(ModuleInfo) _SymGetModuleInfo64(hProcess, dwAddr, byref(ModuleInfo)) return ModuleInfo def SymGetModuleInfo64W(hProcess, dwAddr): _SymGetModuleInfo64W = windll.dbghelp.SymGetModuleInfo64W _SymGetModuleInfo64W.argtypes = [HANDLE, DWORD64, PIMAGEHLP_MODULE64W] _SymGetModuleInfo64W.restype = bool _SymGetModuleInfo64W.errcheck = RaiseIfZero ModuleInfo = IMAGEHLP_MODULE64W() ModuleInfo.SizeOfStruct = sizeof(ModuleInfo) _SymGetModuleInfo64W(hProcess, dwAddr, byref(ModuleInfo)) return ModuleInfo SymGetModuleInfo64 = GuessStringType(SymGetModuleInfo64A, SymGetModuleInfo64W) # BOOL CALLBACK SymEnumerateModulesProc( # __in PCTSTR ModuleName, # __in DWORD BaseOfDll, # __in_opt PVOID UserContext # ); PSYM_ENUMMODULES_CALLBACK = WINFUNCTYPE(BOOL, LPSTR, DWORD, PVOID) PSYM_ENUMMODULES_CALLBACKW = WINFUNCTYPE(BOOL, LPWSTR, DWORD, PVOID) # BOOL CALLBACK SymEnumerateModulesProc64( # __in PCTSTR ModuleName, # __in DWORD64 BaseOfDll, # __in_opt PVOID UserContext # ); PSYM_ENUMMODULES_CALLBACK64 = WINFUNCTYPE(BOOL, LPSTR, DWORD64, PVOID) PSYM_ENUMMODULES_CALLBACKW64 = WINFUNCTYPE(BOOL, LPWSTR, DWORD64, PVOID) # BOOL WINAPI SymEnumerateModules( # __in HANDLE hProcess, # __in PSYM_ENUMMODULES_CALLBACK EnumModulesCallback, # __in_opt PVOID UserContext # ); def SymEnumerateModulesA(hProcess, EnumModulesCallback, UserContext = None): _SymEnumerateModules = windll.dbghelp.SymEnumerateModules _SymEnumerateModules.argtypes = [HANDLE, PSYM_ENUMMODULES_CALLBACK, PVOID] _SymEnumerateModules.restype = bool _SymEnumerateModules.errcheck = RaiseIfZero EnumModulesCallback = PSYM_ENUMMODULES_CALLBACK(EnumModulesCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateModules(hProcess, EnumModulesCallback, UserContext) def SymEnumerateModulesW(hProcess, EnumModulesCallback, UserContext = None): _SymEnumerateModulesW = windll.dbghelp.SymEnumerateModulesW _SymEnumerateModulesW.argtypes = [HANDLE, PSYM_ENUMMODULES_CALLBACKW, PVOID] _SymEnumerateModulesW.restype = bool _SymEnumerateModulesW.errcheck = RaiseIfZero EnumModulesCallback = PSYM_ENUMMODULES_CALLBACKW(EnumModulesCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateModulesW(hProcess, EnumModulesCallback, UserContext) SymEnumerateModules = GuessStringType(SymEnumerateModulesA, SymEnumerateModulesW) # BOOL WINAPI SymEnumerateModules64( # __in HANDLE hProcess, # __in PSYM_ENUMMODULES_CALLBACK64 EnumModulesCallback, # __in_opt PVOID UserContext # ); def SymEnumerateModules64A(hProcess, EnumModulesCallback, UserContext = None): _SymEnumerateModules64 = windll.dbghelp.SymEnumerateModules64 _SymEnumerateModules64.argtypes = [HANDLE, PSYM_ENUMMODULES_CALLBACK64, PVOID] _SymEnumerateModules64.restype = bool _SymEnumerateModules64.errcheck = RaiseIfZero EnumModulesCallback = PSYM_ENUMMODULES_CALLBACK64(EnumModulesCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateModules64(hProcess, EnumModulesCallback, UserContext) def SymEnumerateModules64W(hProcess, EnumModulesCallback, UserContext = None): _SymEnumerateModules64W = windll.dbghelp.SymEnumerateModules64W _SymEnumerateModules64W.argtypes = [HANDLE, PSYM_ENUMMODULES_CALLBACK64W, PVOID] _SymEnumerateModules64W.restype = bool _SymEnumerateModules64W.errcheck = RaiseIfZero EnumModulesCallback = PSYM_ENUMMODULES_CALLBACK64W(EnumModulesCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateModules64W(hProcess, EnumModulesCallback, UserContext) SymEnumerateModules64 = GuessStringType(SymEnumerateModules64A, SymEnumerateModules64W) # BOOL CALLBACK SymEnumerateSymbolsProc( # __in PCTSTR SymbolName, # __in DWORD SymbolAddress, # __in ULONG SymbolSize, # __in_opt PVOID UserContext # ); PSYM_ENUMSYMBOLS_CALLBACK = WINFUNCTYPE(BOOL, LPSTR, DWORD, ULONG, PVOID) PSYM_ENUMSYMBOLS_CALLBACKW = WINFUNCTYPE(BOOL, LPWSTR, DWORD, ULONG, PVOID) # BOOL CALLBACK SymEnumerateSymbolsProc64( # __in PCTSTR SymbolName, # __in DWORD64 SymbolAddress, # __in ULONG SymbolSize, # __in_opt PVOID UserContext # ); PSYM_ENUMSYMBOLS_CALLBACK64 = WINFUNCTYPE(BOOL, LPSTR, DWORD64, ULONG, PVOID) PSYM_ENUMSYMBOLS_CALLBACKW64 = WINFUNCTYPE(BOOL, LPWSTR, DWORD64, ULONG, PVOID) # BOOL WINAPI SymEnumerateSymbols( # __in HANDLE hProcess, # __in ULONG BaseOfDll, # __in PSYM_ENUMSYMBOLS_CALLBACK EnumSymbolsCallback, # __in_opt PVOID UserContext # ); def SymEnumerateSymbolsA(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext = None): _SymEnumerateSymbols = windll.dbghelp.SymEnumerateSymbols _SymEnumerateSymbols.argtypes = [HANDLE, ULONG, PSYM_ENUMSYMBOLS_CALLBACK, PVOID] _SymEnumerateSymbols.restype = bool _SymEnumerateSymbols.errcheck = RaiseIfZero EnumSymbolsCallback = PSYM_ENUMSYMBOLS_CALLBACK(EnumSymbolsCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateSymbols(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext) def SymEnumerateSymbolsW(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext = None): _SymEnumerateSymbolsW = windll.dbghelp.SymEnumerateSymbolsW _SymEnumerateSymbolsW.argtypes = [HANDLE, ULONG, PSYM_ENUMSYMBOLS_CALLBACKW, PVOID] _SymEnumerateSymbolsW.restype = bool _SymEnumerateSymbolsW.errcheck = RaiseIfZero EnumSymbolsCallback = PSYM_ENUMSYMBOLS_CALLBACKW(EnumSymbolsCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateSymbolsW(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext) SymEnumerateSymbols = GuessStringType(SymEnumerateSymbolsA, SymEnumerateSymbolsW) # BOOL WINAPI SymEnumerateSymbols64( # __in HANDLE hProcess, # __in ULONG64 BaseOfDll, # __in PSYM_ENUMSYMBOLS_CALLBACK64 EnumSymbolsCallback, # __in_opt PVOID UserContext # ); def SymEnumerateSymbols64A(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext = None): _SymEnumerateSymbols64 = windll.dbghelp.SymEnumerateSymbols64 _SymEnumerateSymbols64.argtypes = [HANDLE, ULONG64, PSYM_ENUMSYMBOLS_CALLBACK64, PVOID] _SymEnumerateSymbols64.restype = bool _SymEnumerateSymbols64.errcheck = RaiseIfZero EnumSymbolsCallback = PSYM_ENUMSYMBOLS_CALLBACK64(EnumSymbolsCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateSymbols64(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext) def SymEnumerateSymbols64W(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext = None): _SymEnumerateSymbols64W = windll.dbghelp.SymEnumerateSymbols64W _SymEnumerateSymbols64W.argtypes = [HANDLE, ULONG64, PSYM_ENUMSYMBOLS_CALLBACK64W, PVOID] _SymEnumerateSymbols64W.restype = bool _SymEnumerateSymbols64W.errcheck = RaiseIfZero EnumSymbolsCallback = PSYM_ENUMSYMBOLS_CALLBACK64W(EnumSymbolsCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateSymbols64W(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext) SymEnumerateSymbols64 = GuessStringType(SymEnumerateSymbols64A, SymEnumerateSymbols64W) # DWORD WINAPI UnDecorateSymbolName( # __in PCTSTR DecoratedName, # __out PTSTR UnDecoratedName, # __in DWORD UndecoratedLength, # __in DWORD Flags # ); def UnDecorateSymbolNameA(DecoratedName, Flags = UNDNAME_COMPLETE): _UnDecorateSymbolNameA = windll.dbghelp.UnDecorateSymbolName _UnDecorateSymbolNameA.argtypes = [LPSTR, LPSTR, DWORD, DWORD] _UnDecorateSymbolNameA.restype = DWORD _UnDecorateSymbolNameA.errcheck = RaiseIfZero UndecoratedLength = _UnDecorateSymbolNameA(DecoratedName, None, 0, Flags) UnDecoratedName = ctypes.create_string_buffer('', UndecoratedLength + 1) _UnDecorateSymbolNameA(DecoratedName, UnDecoratedName, UndecoratedLength, Flags) return UnDecoratedName.value def UnDecorateSymbolNameW(DecoratedName, Flags = UNDNAME_COMPLETE): _UnDecorateSymbolNameW = windll.dbghelp.UnDecorateSymbolNameW _UnDecorateSymbolNameW.argtypes = [LPWSTR, LPWSTR, DWORD, DWORD] _UnDecorateSymbolNameW.restype = DWORD _UnDecorateSymbolNameW.errcheck = RaiseIfZero UndecoratedLength = _UnDecorateSymbolNameW(DecoratedName, None, 0, Flags) UnDecoratedName = ctypes.create_unicode_buffer(u'', UndecoratedLength + 1) _UnDecorateSymbolNameW(DecoratedName, UnDecoratedName, UndecoratedLength, Flags) return UnDecoratedName.value UnDecorateSymbolName = GuessStringType(UnDecorateSymbolNameA, UnDecorateSymbolNameW) # BOOL WINAPI SymGetSearchPath( # __in HANDLE hProcess, # __out PTSTR SearchPath, # __in DWORD SearchPathLength # ); def SymGetSearchPathA(hProcess): _SymGetSearchPath = windll.dbghelp.SymGetSearchPath _SymGetSearchPath.argtypes = [HANDLE, LPSTR, DWORD] _SymGetSearchPath.restype = bool _SymGetSearchPath.errcheck = RaiseIfZero SearchPathLength = MAX_PATH SearchPath = ctypes.create_string_buffer("", SearchPathLength) _SymGetSearchPath(hProcess, SearchPath, SearchPathLength) return SearchPath.value def SymGetSearchPathW(hProcess): _SymGetSearchPathW = windll.dbghelp.SymGetSearchPathW _SymGetSearchPathW.argtypes = [HANDLE, LPWSTR, DWORD] _SymGetSearchPathW.restype = bool _SymGetSearchPathW.errcheck = RaiseIfZero SearchPathLength = MAX_PATH SearchPath = ctypes.create_unicode_buffer(u"", SearchPathLength) _SymGetSearchPathW(hProcess, SearchPath, SearchPathLength) return SearchPath.value SymGetSearchPath = GuessStringType(SymGetSearchPathA, SymGetSearchPathW) # BOOL WINAPI SymSetSearchPath( # __in HANDLE hProcess, # __in_opt PCTSTR SearchPath # ); def SymSetSearchPathA(hProcess, SearchPath = None): _SymSetSearchPath = windll.dbghelp.SymSetSearchPath _SymSetSearchPath.argtypes = [HANDLE, LPSTR] _SymSetSearchPath.restype = bool _SymSetSearchPath.errcheck = RaiseIfZero if not SearchPath: SearchPath = None _SymSetSearchPath(hProcess, SearchPath) def SymSetSearchPathW(hProcess, SearchPath = None): _SymSetSearchPathW = windll.dbghelp.SymSetSearchPathW _SymSetSearchPathW.argtypes = [HANDLE, LPWSTR] _SymSetSearchPathW.restype = bool _SymSetSearchPathW.errcheck = RaiseIfZero if not SearchPath: SearchPath = None _SymSetSearchPathW(hProcess, SearchPath) SymSetSearchPath = GuessStringType(SymSetSearchPathA, SymSetSearchPathW) # PTCHAR WINAPI SymGetHomeDirectory( # __in DWORD type, # __out PTSTR dir, # __in size_t size # ); def SymGetHomeDirectoryA(type): _SymGetHomeDirectoryA = windll.dbghelp.SymGetHomeDirectoryA _SymGetHomeDirectoryA.argtypes = [DWORD, LPSTR, SIZE_T] _SymGetHomeDirectoryA.restype = LPSTR _SymGetHomeDirectoryA.errcheck = RaiseIfZero size = MAX_PATH dir = ctypes.create_string_buffer("", size) _SymGetHomeDirectoryA(type, dir, size) return dir.value def SymGetHomeDirectoryW(type): _SymGetHomeDirectoryW = windll.dbghelp.SymGetHomeDirectoryW _SymGetHomeDirectoryW.argtypes = [DWORD, LPWSTR, SIZE_T] _SymGetHomeDirectoryW.restype = LPWSTR _SymGetHomeDirectoryW.errcheck = RaiseIfZero size = MAX_PATH dir = ctypes.create_unicode_buffer(u"", size) _SymGetHomeDirectoryW(type, dir, size) return dir.value SymGetHomeDirectory = GuessStringType(SymGetHomeDirectoryA, SymGetHomeDirectoryW) # PTCHAR WINAPI SymSetHomeDirectory( # __in HANDLE hProcess, # __in_opt PCTSTR dir # ); def SymSetHomeDirectoryA(hProcess, dir = None): _SymSetHomeDirectoryA = windll.dbghelp.SymSetHomeDirectoryA _SymSetHomeDirectoryA.argtypes = [HANDLE, LPSTR] _SymSetHomeDirectoryA.restype = LPSTR _SymSetHomeDirectoryA.errcheck = RaiseIfZero if not dir: dir = None _SymSetHomeDirectoryA(hProcess, dir) return dir def SymSetHomeDirectoryW(hProcess, dir = None): _SymSetHomeDirectoryW = windll.dbghelp.SymSetHomeDirectoryW _SymSetHomeDirectoryW.argtypes = [HANDLE, LPWSTR] _SymSetHomeDirectoryW.restype = LPWSTR _SymSetHomeDirectoryW.errcheck = RaiseIfZero if not dir: dir = None _SymSetHomeDirectoryW(hProcess, dir) return dir SymSetHomeDirectory = GuessStringType(SymSetHomeDirectoryA, SymSetHomeDirectoryW) #--- DbgHelp 5+ support, patch by Neitsa -------------------------------------- # XXX TODO # + use the GuessStringType decorator for ANSI/Wide versions # + replace hardcoded struct sizes with sizeof() calls # + StackWalk64 should raise on error, but something has to be done about it # not setting the last error code (maybe we should call SetLastError # ourselves with a default error code?) # /Mario #maximum length of a symbol name MAX_SYM_NAME = 2000 class SYM_INFO(Structure): _fields_ = [ ("SizeOfStruct", ULONG), ("TypeIndex", ULONG), ("Reserved", ULONG64 * 2), ("Index", ULONG), ("Size", ULONG), ("ModBase", ULONG64), ("Flags", ULONG), ("Value", ULONG64), ("Address", ULONG64), ("Register", ULONG), ("Scope", ULONG), ("Tag", ULONG), ("NameLen", ULONG), ("MaxNameLen", ULONG), ("Name", CHAR * (MAX_SYM_NAME + 1)), ] PSYM_INFO = POINTER(SYM_INFO) class SYM_INFOW(Structure): _fields_ = [ ("SizeOfStruct", ULONG), ("TypeIndex", ULONG), ("Reserved", ULONG64 * 2), ("Index", ULONG), ("Size", ULONG), ("ModBase", ULONG64), ("Flags", ULONG), ("Value", ULONG64), ("Address", ULONG64), ("Register", ULONG), ("Scope", ULONG), ("Tag", ULONG), ("NameLen", ULONG), ("MaxNameLen", ULONG), ("Name", WCHAR * (MAX_SYM_NAME + 1)), ] PSYM_INFOW = POINTER(SYM_INFOW) #=============================================================================== # BOOL WINAPI SymFromName( # __in HANDLE hProcess, # __in PCTSTR Name, # __inout PSYMBOL_INFO Symbol # ); #=============================================================================== def SymFromName(hProcess, Name): _SymFromNameA = windll.dbghelp.SymFromName _SymFromNameA.argtypes = [HANDLE, LPSTR, PSYM_INFO] _SymFromNameA.restype = bool _SymFromNameA.errcheck = RaiseIfZero SymInfo = SYM_INFO() SymInfo.SizeOfStruct = 88 # *don't modify*: sizeof(SYMBOL_INFO) in C. SymInfo.MaxNameLen = MAX_SYM_NAME _SymFromNameA(hProcess, Name, byref(SymInfo)) return SymInfo def SymFromNameW(hProcess, Name): _SymFromNameW = windll.dbghelp.SymFromNameW _SymFromNameW.argtypes = [HANDLE, LPWSTR, PSYM_INFOW] _SymFromNameW.restype = bool _SymFromNameW.errcheck = RaiseIfZero SymInfo = SYM_INFOW() SymInfo.SizeOfStruct = 88 # *don't modify*: sizeof(SYMBOL_INFOW) in C. SymInfo.MaxNameLen = MAX_SYM_NAME _SymFromNameW(hProcess, Name, byref(SymInfo)) return SymInfo #=============================================================================== # BOOL WINAPI SymFromAddr( # __in HANDLE hProcess, # __in DWORD64 Address, # __out_opt PDWORD64 Displacement, # __inout PSYMBOL_INFO Symbol # ); #=============================================================================== def SymFromAddr(hProcess, Address): _SymFromAddr = windll.dbghelp.SymFromAddr _SymFromAddr.argtypes = [HANDLE, DWORD64, PDWORD64, PSYM_INFO] _SymFromAddr.restype = bool _SymFromAddr.errcheck = RaiseIfZero SymInfo = SYM_INFO() SymInfo.SizeOfStruct = 88 # *don't modify*: sizeof(SYMBOL_INFO) in C. SymInfo.MaxNameLen = MAX_SYM_NAME Displacement = DWORD64(0) _SymFromAddr(hProcess, Address, byref(Displacement), byref(SymInfo)) return (Displacement.value, SymInfo) def SymFromAddrW(hProcess, Address): _SymFromAddr = windll.dbghelp.SymFromAddrW _SymFromAddr.argtypes = [HANDLE, DWORD64, PDWORD64, PSYM_INFOW] _SymFromAddr.restype = bool _SymFromAddr.errcheck = RaiseIfZero SymInfo = SYM_INFOW() SymInfo.SizeOfStruct = 88 # *don't modify*: sizeof(SYMBOL_INFOW) in C. SymInfo.MaxNameLen = MAX_SYM_NAME Displacement = DWORD64(0) _SymFromAddr(hProcess, Address, byref(Displacement), byref(SymInfo)) return (Displacement.value, SymInfo) #=============================================================================== # typedef struct _IMAGEHLP_SYMBOL64 { # DWORD SizeOfStruct; # DWORD64 Address; # DWORD Size; # DWORD Flags; # DWORD MaxNameLength; # CHAR Name[1]; # } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64; #=============================================================================== class IMAGEHLP_SYMBOL64 (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("Address", DWORD64), ("Size", DWORD), ("Flags", DWORD), ("MaxNameLength", DWORD), ("Name", CHAR * (MAX_SYM_NAME + 1)), ] PIMAGEHLP_SYMBOL64 = POINTER(IMAGEHLP_SYMBOL64) #=============================================================================== # typedef struct _IMAGEHLP_SYMBOLW64 { # DWORD SizeOfStruct; # DWORD64 Address; # DWORD Size; # DWORD Flags; # DWORD MaxNameLength; # WCHAR Name[1]; # } IMAGEHLP_SYMBOLW64, *PIMAGEHLP_SYMBOLW64; #=============================================================================== class IMAGEHLP_SYMBOLW64 (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("Address", DWORD64), ("Size", DWORD), ("Flags", DWORD), ("MaxNameLength", DWORD), ("Name", WCHAR * (MAX_SYM_NAME + 1)), ] PIMAGEHLP_SYMBOLW64 = POINTER(IMAGEHLP_SYMBOLW64) #=============================================================================== # BOOL WINAPI SymGetSymFromAddr64( # __in HANDLE hProcess, # __in DWORD64 Address, # __out_opt PDWORD64 Displacement, # __inout PIMAGEHLP_SYMBOL64 Symbol # ); #=============================================================================== def SymGetSymFromAddr64(hProcess, Address): _SymGetSymFromAddr64 = windll.dbghelp.SymGetSymFromAddr64 _SymGetSymFromAddr64.argtypes = [HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64] _SymGetSymFromAddr64.restype = bool _SymGetSymFromAddr64.errcheck = RaiseIfZero imagehlp_symbol64 = IMAGEHLP_SYMBOL64() imagehlp_symbol64.SizeOfStruct = 32 # *don't modify*: sizeof(IMAGEHLP_SYMBOL64) in C. imagehlp_symbol64.MaxNameLen = MAX_SYM_NAME Displacement = DWORD64(0) _SymGetSymFromAddr64(hProcess, Address, byref(Displacement), byref(imagehlp_symbol64)) return (Displacement.value, imagehlp_symbol64) #TODO: check for the 'W' version of SymGetSymFromAddr64() #=============================================================================== # typedef struct API_VERSION { # USHORT MajorVersion; # USHORT MinorVersion; # USHORT Revision; # USHORT Reserved; # } API_VERSION, *LPAPI_VERSION; #=============================================================================== class API_VERSION (Structure): _fields_ = [ ("MajorVersion", USHORT), ("MinorVersion", USHORT), ("Revision", USHORT), ("Reserved", USHORT), ] PAPI_VERSION = POINTER(API_VERSION) LPAPI_VERSION = PAPI_VERSION #=============================================================================== # LPAPI_VERSION WINAPI ImagehlpApiVersion(void); #=============================================================================== def ImagehlpApiVersion(): _ImagehlpApiVersion = windll.dbghelp.ImagehlpApiVersion _ImagehlpApiVersion.restype = LPAPI_VERSION api_version = _ImagehlpApiVersion() return api_version.contents #=============================================================================== # LPAPI_VERSION WINAPI ImagehlpApiVersionEx( # __in LPAPI_VERSION AppVersion # ); #=============================================================================== def ImagehlpApiVersionEx(MajorVersion, MinorVersion, Revision): _ImagehlpApiVersionEx = windll.dbghelp.ImagehlpApiVersionEx _ImagehlpApiVersionEx.argtypes = [LPAPI_VERSION] _ImagehlpApiVersionEx.restype = LPAPI_VERSION api_version = API_VERSION(MajorVersion, MinorVersion, Revision, 0) ret_api_version = _ImagehlpApiVersionEx(byref(api_version)) return ret_api_version.contents #=============================================================================== # typedef enum { # AddrMode1616, # AddrMode1632, # AddrModeReal, # AddrModeFlat # } ADDRESS_MODE; #=============================================================================== AddrMode1616 = 0 AddrMode1632 = 1 AddrModeReal = 2 AddrModeFlat = 3 ADDRESS_MODE = DWORD #needed for the size of an ADDRESS_MODE (see ADDRESS64) #=============================================================================== # typedef struct _tagADDRESS64 { # DWORD64 Offset; # WORD Segment; # ADDRESS_MODE Mode; # } ADDRESS64, *LPADDRESS64; #=============================================================================== class ADDRESS64 (Structure): _fields_ = [ ("Offset", DWORD64), ("Segment", WORD), ("Mode", ADDRESS_MODE), #it's a member of the ADDRESS_MODE enum. ] LPADDRESS64 = POINTER(ADDRESS64) #=============================================================================== # typedef struct _KDHELP64 { # DWORD64 Thread; # DWORD ThCallbackStack; # DWORD ThCallbackBStore; # DWORD NextCallback; # DWORD FramePointer; # DWORD64 KiCallUserMode; # DWORD64 KeUserCallbackDispatcher; # DWORD64 SystemRangeStart; # DWORD64 KiUserExceptionDispatcher; # DWORD64 StackBase; # DWORD64 StackLimit; # DWORD64 Reserved[5]; # } KDHELP64, *PKDHELP64; #=============================================================================== class KDHELP64 (Structure): _fields_ = [ ("Thread", DWORD64), ("ThCallbackStack", DWORD), ("ThCallbackBStore", DWORD), ("NextCallback", DWORD), ("FramePointer", DWORD), ("KiCallUserMode", DWORD64), ("KeUserCallbackDispatcher", DWORD64), ("SystemRangeStart", DWORD64), ("KiUserExceptionDispatcher", DWORD64), ("StackBase", DWORD64), ("StackLimit", DWORD64), ("Reserved", DWORD64 * 5), ] PKDHELP64 = POINTER(KDHELP64) #=============================================================================== # typedef struct _tagSTACKFRAME64 { # ADDRESS64 AddrPC; # ADDRESS64 AddrReturn; # ADDRESS64 AddrFrame; # ADDRESS64 AddrStack; # ADDRESS64 AddrBStore; # PVOID FuncTableEntry; # DWORD64 Params[4]; # BOOL Far; # BOOL Virtual; # DWORD64 Reserved[3]; # KDHELP64 KdHelp; # } STACKFRAME64, *LPSTACKFRAME64; #=============================================================================== class STACKFRAME64(Structure): _fields_ = [ ("AddrPC", ADDRESS64), ("AddrReturn", ADDRESS64), ("AddrFrame", ADDRESS64), ("AddrStack", ADDRESS64), ("AddrBStore", ADDRESS64), ("FuncTableEntry", PVOID), ("Params", DWORD64 * 4), ("Far", BOOL), ("Virtual", BOOL), ("Reserved", DWORD64 * 3), ("KdHelp", KDHELP64), ] LPSTACKFRAME64 = POINTER(STACKFRAME64) #=============================================================================== # BOOL CALLBACK ReadProcessMemoryProc64( # __in HANDLE hProcess, # __in DWORD64 lpBaseAddress, # __out PVOID lpBuffer, # __in DWORD nSize, # __out LPDWORD lpNumberOfBytesRead # ); #=============================================================================== PREAD_PROCESS_MEMORY_ROUTINE64 = WINFUNCTYPE(BOOL, HANDLE, DWORD64, PVOID, DWORD, LPDWORD) #=============================================================================== # PVOID CALLBACK FunctionTableAccessProc64( # __in HANDLE hProcess, # __in DWORD64 AddrBase # ); #=============================================================================== PFUNCTION_TABLE_ACCESS_ROUTINE64 = WINFUNCTYPE(PVOID, HANDLE, DWORD64) #=============================================================================== # DWORD64 CALLBACK GetModuleBaseProc64( # __in HANDLE hProcess, # __in DWORD64 Address # ); #=============================================================================== PGET_MODULE_BASE_ROUTINE64 = WINFUNCTYPE(DWORD64, HANDLE, DWORD64) #=============================================================================== # DWORD64 CALLBACK GetModuleBaseProc64( # __in HANDLE hProcess, # __in DWORD64 Address # ); #=============================================================================== PTRANSLATE_ADDRESS_ROUTINE64 = WINFUNCTYPE(DWORD64, HANDLE, DWORD64) # Valid machine types for StackWalk64 function IMAGE_FILE_MACHINE_I386 = 0x014c #Intel x86 IMAGE_FILE_MACHINE_IA64 = 0x0200 #Intel Itanium Processor Family (IPF) IMAGE_FILE_MACHINE_AMD64 = 0x8664 #x64 (AMD64 or EM64T) #=============================================================================== # BOOL WINAPI StackWalk64( # __in DWORD MachineType, # __in HANDLE hProcess, # __in HANDLE hThread, # __inout LPSTACKFRAME64 StackFrame, # __inout PVOID ContextRecord, # __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, # __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, # __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, # __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress # ); #=============================================================================== def StackWalk64(MachineType, hProcess, hThread, StackFrame, ContextRecord = None, ReadMemoryRoutine = None, FunctionTableAccessRoutine = None, GetModuleBaseRoutine = None, TranslateAddress = None): _StackWalk64 = windll.dbghelp.StackWalk64 _StackWalk64.argtypes = [DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64] _StackWalk64.restype = bool pReadMemoryRoutine = None if ReadMemoryRoutine: pReadMemoryRoutine = PREAD_PROCESS_MEMORY_ROUTINE64(ReadMemoryRoutine) else: pReadMemoryRoutine = ctypes.cast(None, PREAD_PROCESS_MEMORY_ROUTINE64) pFunctionTableAccessRoutine = None if FunctionTableAccessRoutine: pFunctionTableAccessRoutine = PFUNCTION_TABLE_ACCESS_ROUTINE64(FunctionTableAccessRoutine) else: pFunctionTableAccessRoutine = ctypes.cast(None, PFUNCTION_TABLE_ACCESS_ROUTINE64) pGetModuleBaseRoutine = None if GetModuleBaseRoutine: pGetModuleBaseRoutine = PGET_MODULE_BASE_ROUTINE64(GetModuleBaseRoutine) else: pGetModuleBaseRoutine = ctypes.cast(None, PGET_MODULE_BASE_ROUTINE64) pTranslateAddress = None if TranslateAddress: pTranslateAddress = PTRANSLATE_ADDRESS_ROUTINE64(TranslateAddress) else: pTranslateAddress = ctypes.cast(None, PTRANSLATE_ADDRESS_ROUTINE64) pContextRecord = None if ContextRecord is None: ContextRecord = GetThreadContext(hThread, raw=True) pContextRecord = PCONTEXT(ContextRecord) #this function *DOESN'T* set last error [GetLastError()] properly most of the time. ret = _StackWalk64(MachineType, hProcess, hThread, byref(StackFrame), pContextRecord, pReadMemoryRoutine, pFunctionTableAccessRoutine, pGetModuleBaseRoutine, pTranslateAddress) return ret #============================================================================== # This calculates the list of exported symbols. _all = set(vars().keys()).difference(_all) __all__ = [_x for _x in _all if not _x.startswith('_')] __all__.sort() #==============================================================================
noorul/os-project-config
refs/heads/master
jenkins/scripts/check_app_catalog_yaml.py
5
#!/usr/bin/env python # # 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 requests import requestsexceptions import yaml def main(): requestsexceptions.squelch_warnings() data = yaml.load(open('openstack_catalog/web/static/assets.yaml')) assets = {} for a in data['assets']: url = a.get('attributes', {}).get('url') if url: r = requests.head(url, allow_redirects=True) if r.status_code != 200: assets[a['name']] = {'active': False} with open('openstack_catalog/web/static/assets_dead.yaml', 'w') as out: out.write(yaml.safe_dump({"assets": assets})) if __name__ == '__main__': main()
rodorad/spark-tk
refs/heads/master
python/sparktk/models/classification/__init__.py
137
# vim: set encoding=utf-8 # Copyright (c) 2016 Intel Corporation  # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #       http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from sparktk.loggers import log_load; log_load(__name__); del log_load
imruahmed/microblog
refs/heads/master
flask/lib/python2.7/site-packages/sqlalchemy/testing/exclusions.py
3
# testing/exclusions.py # Copyright (C) 2005-2015 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import operator from ..util import decorator from . import config from .. import util import inspect import contextlib from sqlalchemy.util.compat import inspect_getargspec def skip_if(predicate, reason=None): rule = compound() pred = _as_predicate(predicate, reason) rule.skips.add(pred) return rule def fails_if(predicate, reason=None): rule = compound() pred = _as_predicate(predicate, reason) rule.fails.add(pred) return rule class compound(object): def __init__(self): self.fails = set() self.skips = set() self.tags = set() def __add__(self, other): return self.add(other) def add(self, *others): copy = compound() copy.fails.update(self.fails) copy.skips.update(self.skips) copy.tags.update(self.tags) for other in others: copy.fails.update(other.fails) copy.skips.update(other.skips) copy.tags.update(other.tags) return copy def not_(self): copy = compound() copy.fails.update(NotPredicate(fail) for fail in self.fails) copy.skips.update(NotPredicate(skip) for skip in self.skips) copy.tags.update(self.tags) return copy @property def enabled(self): return self.enabled_for_config(config._current) def enabled_for_config(self, config): for predicate in self.skips.union(self.fails): if predicate(config): return False else: return True def matching_config_reasons(self, config): return [ predicate._as_string(config) for predicate in self.skips.union(self.fails) if predicate(config) ] def include_test(self, include_tags, exclude_tags): return bool( not self.tags.intersection(exclude_tags) and (not include_tags or self.tags.intersection(include_tags)) ) def _extend(self, other): self.skips.update(other.skips) self.fails.update(other.fails) self.tags.update(other.tags) def __call__(self, fn): if hasattr(fn, '_sa_exclusion_extend'): fn._sa_exclusion_extend._extend(self) return fn @decorator def decorate(fn, *args, **kw): return self._do(config._current, fn, *args, **kw) decorated = decorate(fn) decorated._sa_exclusion_extend = self return decorated @contextlib.contextmanager def fail_if(self): all_fails = compound() all_fails.fails.update(self.skips.union(self.fails)) try: yield except Exception as ex: all_fails._expect_failure(config._current, ex) else: all_fails._expect_success(config._current) def _do(self, config, fn, *args, **kw): for skip in self.skips: if skip(config): msg = "'%s' : %s" % ( fn.__name__, skip._as_string(config) ) config.skip_test(msg) try: return_value = fn(*args, **kw) except Exception as ex: self._expect_failure(config, ex, name=fn.__name__) else: self._expect_success(config, name=fn.__name__) return return_value def _expect_failure(self, config, ex, name='block'): for fail in self.fails: if fail(config): print(("%s failed as expected (%s): %s " % ( name, fail._as_string(config), str(ex)))) break else: util.raise_from_cause(ex) def _expect_success(self, config, name='block'): if not self.fails: return for fail in self.fails: if not fail(config): break else: raise AssertionError( "Unexpected success for '%s' (%s)" % ( name, " and ".join( fail._as_string(config) for fail in self.fails ) ) ) def requires_tag(tagname): return tags([tagname]) def tags(tagnames): comp = compound() comp.tags.update(tagnames) return comp def only_if(predicate, reason=None): predicate = _as_predicate(predicate) return skip_if(NotPredicate(predicate), reason) def succeeds_if(predicate, reason=None): predicate = _as_predicate(predicate) return fails_if(NotPredicate(predicate), reason) class Predicate(object): @classmethod def as_predicate(cls, predicate, description=None): if isinstance(predicate, compound): return cls.as_predicate(predicate.enabled_for_config, description) elif isinstance(predicate, Predicate): if description and predicate.description is None: predicate.description = description return predicate elif isinstance(predicate, (list, set)): return OrPredicate( [cls.as_predicate(pred) for pred in predicate], description) elif isinstance(predicate, tuple): return SpecPredicate(*predicate) elif isinstance(predicate, util.string_types): tokens = predicate.split(" ", 2) op = spec = None db = tokens.pop(0) if tokens: op = tokens.pop(0) if tokens: spec = tuple(int(d) for d in tokens.pop(0).split(".")) return SpecPredicate(db, op, spec, description=description) elif util.callable(predicate): return LambdaPredicate(predicate, description) else: assert False, "unknown predicate type: %s" % predicate def _format_description(self, config, negate=False): bool_ = self(config) if negate: bool_ = not negate return self.description % { "driver": config.db.url.get_driver_name(), "database": config.db.url.get_backend_name(), "doesnt_support": "doesn't support" if bool_ else "does support", "does_support": "does support" if bool_ else "doesn't support" } def _as_string(self, config=None, negate=False): raise NotImplementedError() class BooleanPredicate(Predicate): def __init__(self, value, description=None): self.value = value self.description = description or "boolean %s" % value def __call__(self, config): return self.value def _as_string(self, config, negate=False): return self._format_description(config, negate=negate) class SpecPredicate(Predicate): def __init__(self, db, op=None, spec=None, description=None): self.db = db self.op = op self.spec = spec self.description = description _ops = { '<': operator.lt, '>': operator.gt, '==': operator.eq, '!=': operator.ne, '<=': operator.le, '>=': operator.ge, 'in': operator.contains, 'between': lambda val, pair: val >= pair[0] and val <= pair[1], } def __call__(self, config): engine = config.db if "+" in self.db: dialect, driver = self.db.split('+') else: dialect, driver = self.db, None if dialect and engine.name != dialect: return False if driver is not None and engine.driver != driver: return False if self.op is not None: assert driver is None, "DBAPI version specs not supported yet" version = _server_version(engine) oper = hasattr(self.op, '__call__') and self.op \ or self._ops[self.op] return oper(version, self.spec) else: return True def _as_string(self, config, negate=False): if self.description is not None: return self._format_description(config) elif self.op is None: if negate: return "not %s" % self.db else: return "%s" % self.db else: if negate: return "not %s %s %s" % ( self.db, self.op, self.spec ) else: return "%s %s %s" % ( self.db, self.op, self.spec ) class LambdaPredicate(Predicate): def __init__(self, lambda_, description=None, args=None, kw=None): spec = inspect_getargspec(lambda_) if not spec[0]: self.lambda_ = lambda db: lambda_() else: self.lambda_ = lambda_ self.args = args or () self.kw = kw or {} if description: self.description = description elif lambda_.__doc__: self.description = lambda_.__doc__ else: self.description = "custom function" def __call__(self, config): return self.lambda_(config) def _as_string(self, config, negate=False): return self._format_description(config) class NotPredicate(Predicate): def __init__(self, predicate, description=None): self.predicate = predicate self.description = description def __call__(self, config): return not self.predicate(config) def _as_string(self, config, negate=False): if self.description: return self._format_description(config, not negate) else: return self.predicate._as_string(config, not negate) class OrPredicate(Predicate): def __init__(self, predicates, description=None): self.predicates = predicates self.description = description def __call__(self, config): for pred in self.predicates: if pred(config): return True return False def _eval_str(self, config, negate=False): if negate: conjunction = " and " else: conjunction = " or " return conjunction.join(p._as_string(config, negate=negate) for p in self.predicates) def _negation_str(self, config): if self.description is not None: return "Not " + self._format_description(config) else: return self._eval_str(config, negate=True) def _as_string(self, config, negate=False): if negate: return self._negation_str(config) else: if self.description is not None: return self._format_description(config) else: return self._eval_str(config) _as_predicate = Predicate.as_predicate def _is_excluded(db, op, spec): return SpecPredicate(db, op, spec)(config._current) def _server_version(engine): """Return a server_version_info tuple.""" # force metadata to be retrieved conn = engine.connect() version = getattr(engine.dialect, 'server_version_info', ()) conn.close() return version def db_spec(*dbs): return OrPredicate( [Predicate.as_predicate(db) for db in dbs] ) def open(): return skip_if(BooleanPredicate(False, "mark as execute")) def closed(): return skip_if(BooleanPredicate(True, "marked as skip")) def fails(): return fails_if(BooleanPredicate(True, "expected to fail")) @decorator def future(fn, *arg): return fails_if(LambdaPredicate(fn), "Future feature") def fails_on(db, reason=None): return fails_if(SpecPredicate(db), reason) def fails_on_everything_except(*dbs): return succeeds_if( OrPredicate([ SpecPredicate(db) for db in dbs ]) ) def skip(db, reason=None): return skip_if(SpecPredicate(db), reason) def only_on(dbs, reason=None): return only_if( OrPredicate([Predicate.as_predicate(db) for db in util.to_list(dbs)]) ) def exclude(db, op, spec, reason=None): return skip_if(SpecPredicate(db, op, spec), reason) def against(config, *queries): assert queries, "no queries sent!" return OrPredicate([ Predicate.as_predicate(query) for query in queries ])(config)
adobe/chromium
refs/heads/master
native_client_sdk/src/build_tools/tests/update_manifest_test.py
7
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for update_manifest.py.""" __author__ = 'mball@google.com (Matt Ball)' import errno import os import SimpleHTTPServer import SocketServer import sys import tempfile import threading import unittest import urllib import urlparse from build_tools.sdk_tools import sdk_update from build_tools.sdk_tools import update_manifest TEST_DIR = os.path.dirname(os.path.abspath(__file__)) def RemoveFile(filename): '''Remove a filename if it exists and do nothing if it doesn't exist''' try: os.remove(filename) except OSError as error: if error.errno != errno.ENOENT: raise def GetHTTPHandler(path, length=None): '''Returns a simple HTTP Request Handler that only servers up a given file Args: path: path and filename of the file to serve up length: (optional) only serve up the first |length| bytes Returns: A SimpleHTTPRequestHandler class''' class HTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): with open(path, 'rb') as f: # This code is largely lifted from SimpleHTTPRequestHandler.send_head self.send_response(200) self.send_header("Content-type", self.guess_type(path)) fs = os.fstat(f.fileno()) self.send_header("Content-Length", str(fs[6])) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() if length != None: self.wfile.write(f.read(length)) else: self.copyfile(f, self.wfile) return HTTPHandler class FakeOptions(object): ''' Just a place holder for options ''' def __init__(self): self.archive_id = None self.bundle_desc_url = None self.bundle_name = None self.bundle_version = None self.bundle_revision = None self.desc = None self.gsutil = os.path.join(TEST_DIR, 'fake_gsutil.bat' if sys.platform == 'win32' else 'fake_gsutil.py') self.linux_arch_url = None self.mac_arch_url = None self.manifest_file = os.path.join(TEST_DIR, 'naclsdk_manifest_test.json') self.manifest_version = None self.recommended = None self.root_url = 'file://%s' % urllib.pathname2url(TEST_DIR) self.stability = None self.upload = False self.win_arch_url = None class TestUpdateManifest(unittest.TestCase): ''' Test basic functionality of the update_manifest package. Note that update_manifest.py now imports sdk_update.py, so this file tests the update_manifest features within sdk_update.''' def setUp(self): self._json_boilerplate=( '{\n' ' "bundles": [],\n' ' "manifest_version": 1\n' '}\n') self._temp_dir = tempfile.gettempdir() # os.path.join('build_tools', 'tests', 'test_archive') self._manifest = update_manifest.UpdateSDKManifest() def testJSONBoilerplate(self): ''' Test creating a manifest object''' self.assertEqual(self._manifest.GetManifestString(), self._json_boilerplate) # Test using a manifest file with a version that is too high self.assertRaises(sdk_update.Error, self._manifest.LoadManifestString, '{"manifest_version": 2}') def testWriteLoadManifestFile(self): ''' Test writing to and loading from a manifest file''' # Remove old test file file_path = os.path.join(self._temp_dir, 'temp_manifest.json') if os.path.exists(file_path): os.remove(file_path) # Create a basic manifest file manifest_file = sdk_update.SDKManifestFile(file_path) manifest_file.WriteFile(); self.assertTrue(os.path.exists(file_path)) # Test re-loading the file manifest_file._manifest._manifest_data['manifest_version'] = 0 manifest_file._LoadFile() self.assertEqual(manifest_file._manifest.GetManifestString(), self._json_boilerplate) os.remove(file_path) def testValidateBundleName(self): ''' Test validating good and bad bundle names ''' self.assertTrue( self._manifest._ValidateBundleName('A_Valid.Bundle-Name(1)')) self.assertFalse(self._manifest._ValidateBundleName('A bad name')) self.assertFalse(self._manifest._ValidateBundleName('A bad/name')) self.assertFalse(self._manifest._ValidateBundleName('A bad;name')) self.assertFalse(self._manifest._ValidateBundleName('A bad,name')) def testUpdateManifestVersion(self): ''' Test updating the manifest version number ''' options = FakeOptions() options.manifest_version = 99 self.assertEqual(self._manifest._manifest_data['manifest_version'], 1) self._manifest._UpdateManifestVersion(options) self.assertEqual(self._manifest._manifest_data['manifest_version'], 99) def testVerifyAllOptionsConsumed(self): ''' Test function _VerifyAllOptionsConsumed ''' options = FakeOptions() options.opt1 = None self.assertTrue(self._manifest._VerifyAllOptionsConsumed(options, None)) options.opt2 = 'blah' self.assertRaises(update_manifest.Error, self._manifest._VerifyAllOptionsConsumed, options, 'no bundle name') def testBundleUpdate(self): ''' Test function Bundle.Update ''' bundle = sdk_update.Bundle('test') options = FakeOptions() options.bundle_revision = 1 options.bundle_version = 2 options.desc = 'What a hoot' options.stability = 'dev' options.recommended = 'yes' update_manifest.UpdateBundle(bundle, options) self.assertEqual(bundle['revision'], 1) def testUpdateManifestModifyTopLevel(self): ''' Test function UpdateManifest: modifying top-level info ''' options = FakeOptions() options.manifest_version = 0 options.bundle_name = None self._manifest.UpdateManifest(options) self.assertEqual(self._manifest._manifest_data['manifest_version'], 0) def testUpdateManifestModifyBundle(self): ''' Test function UpdateManifest: adding/modifying a bundle ''' # Add a bundle options = FakeOptions() options.manifest_version = 1 options.bundle_name = 'test' options.bundle_revision = 2 options.bundle_version = 3 options.desc = 'nice bundle' options.stability = 'canary' options.recommended = 'yes' self._manifest.UpdateManifest(options) bundle = self._manifest.GetBundle('test') self.assertNotEqual(bundle, None) # Modify the same bundle options = FakeOptions() options.manifest_version = None options.bundle_name = 'test' options.desc = 'changed' self._manifest.UpdateManifest(options) bundle = self._manifest.GetBundle('test') self.assertEqual(bundle['description'], 'changed') def testUpdateManifestBadBundle1(self): ''' Test function UpdateManifest: bad bundle data ''' options = FakeOptions() options.manifest_version = None options.bundle_name = 'test' options.stability = 'excellent' self.assertRaises(sdk_update.Error, self._manifest.UpdateManifest, options) def testUpdateManifestBadBundle2(self): ''' Test function UpdateManifest: incomplete bundle data ''' options = FakeOptions() options.manifest_version = None options.bundle_name = 'another_bundle' self.assertRaises(sdk_update.Error, self._manifest.UpdateManifest, options) def testUpdateManifestArchiveComputeSha1AndSize(self): ''' Test function Archive.Update ''' temp_file_path = None try: with tempfile.NamedTemporaryFile(delete=False) as temp_file: # Create a temp file with some data temp_file.write(r'abcdefghijklmnopqrstuvwxyz0123456789') temp_file_path = temp_file.name # Windows requires that we close the file before reading from it. temp_file.close() # Create an archive with a url to the file we created above. url_parts = urlparse.ParseResult('file', '', temp_file_path, '', '', '') url = urlparse.urlunparse(url_parts) archive = sdk_update.Archive('mac') archive.Update(url) self.assertEqual(archive['checksum']['sha1'], 'd2985049a677bbc4b4e8dea3b89c4820e5668e3a') finally: if temp_file_path and os.path.exists(temp_file_path): os.remove(temp_file_path) def testUpdateManifestArchiveValidate(self): ''' Test function Archive.Validate ''' # Test invalid host-os name archive = sdk_update.Archive('atari') self.assertRaises(sdk_update.Error, archive.Validate) # Test missing url archive['host_os'] = 'mac' self.assertRaises(sdk_update.Error, archive.Validate) # Valid archive archive['url'] = 'http://www.google.com' archive.Validate() # Test invalid key name archive['guess'] = 'who' self.assertRaises(sdk_update.Error, archive.Validate) def testUpdatePartialFile(self): '''Test updating with a partially downloaded file''' server = None server_thread = None temp_filename = os.path.join(self._temp_dir, 'testUpdatePartialFile_temp.txt') try: # Create a new local server on an arbitrary port that just serves-up # the first 10 bytes of this file. server = SocketServer.TCPServer( ("", 0), GetHTTPHandler(__file__, 10)) ip, port = server.server_address server_thread = threading.Thread(target=server.serve_forever) server_thread.start() archive = sdk_update.Archive('mac') self.assertRaises(sdk_update.Error, archive.Update, 'http://localhost:%s' % port) try: self.assertRaises(sdk_update.Error, archive.DownloadToFile, temp_filename) finally: RemoveFile(temp_filename) finally: if server_thread and server_thread.isAlive(): server.shutdown() server_thread.join() def testUpdateManifestMain(self): ''' test the main function from update_manifest ''' temp_filename = os.path.join(self._temp_dir, 'testUpdateManifestMain.json') try: argv = ['--bundle-version', '0', '--bundle-revision', '0', '--description', 'test bundle for update_manifest unit tests', '--bundle-name', 'test_bundle', '--stability', 'dev', '--recommended', 'no', '--manifest-file', temp_filename] update_manifest.main(argv) finally: RemoveFile(temp_filename) def testPush(self): '''Test whether the push function does the right thing''' options = FakeOptions() argv = ['-g', options.gsutil, 'push'] update_manifest.main(argv) def testHandleSDKTools(self): '''Test the handling of the sdk_tools bundle''' options = FakeOptions() options.bundle_name = 'sdk_tools' options.upload = True options.bundle_version = 0 self.assertRaises( update_manifest.Error, update_manifest.UpdateSDKManifestFile(options).HandleBundles) options.bundle_version = None options.bundle_revision = 0 self.assertRaises( update_manifest.Error, update_manifest.UpdateSDKManifestFile(options).HandleBundles) options.bundle_revision = None update_manifest.UpdateSDKManifestFile(options).HandleBundles() def testHandlePepper(self): '''Test the handling of pepper bundles''' options = FakeOptions() options.bundle_name = 'pepper' options.bundle_version = None self.assertRaises( update_manifest.Error, update_manifest.UpdateSDKManifestFile(options).HandleBundles) options.bundle_name = 'pepper' options.bundle_version = 1 options.bundle_revision = None self.assertRaises( update_manifest.Error, update_manifest.UpdateSDKManifestFile(options).HandleBundles) options.bundle_name = 'pepper' options.bundle_revision = 0 manifest_object = update_manifest.UpdateSDKManifestFile(options) manifest_object.HandleBundles() manifest_object.UpdateWithOptions() options = FakeOptions() options.bundle_name = 'pepper_1' options.bundle_revision = 0 manifest_object = update_manifest.UpdateSDKManifestFile(options) manifest_object.HandleBundles() manifest_object.UpdateWithOptions() # Verify that the bundle can be found via the --archive-id option. options = FakeOptions() options.archive_id = 'pepper_1_0' options.bundle_name = 'pepper_phony' options.bundle_version = -1 options.bundle_revision = -1 options.stability = 'dev' options.recommended = 'no' manifest_object = update_manifest.UpdateSDKManifestFile(options) manifest_object.HandleBundles() manifest_object.UpdateWithOptions() def main(): suite = unittest.TestLoader().loadTestsFromTestCase(TestUpdateManifest) result = unittest.TextTestRunner(verbosity=2).run(suite) return int(not result.wasSuccessful()) if __name__ == '__main__': sys.exit(main())
nnethercote/servo
refs/heads/master
tests/wpt/web-platform-tests/tools/lint/tests/test_lint.py
12
from __future__ import unicode_literals import os import sys import mock import six from ...localpaths import repo_root from .. import lint as lint_mod from ..lint import filter_whitelist_errors, parse_whitelist, lint, create_parser _dummy_repo = os.path.join(os.path.dirname(__file__), "dummy") def _mock_lint(name, **kwargs): wrapped = getattr(lint_mod, name) return mock.patch(lint_mod.__name__ + "." + name, wraps=wrapped, **kwargs) def test_filter_whitelist_errors(): whitelist = { 'CONSOLE': { 'svg/*': {12} }, 'INDENT TABS': { 'svg/*': {None} } } # parse_whitelist normalises the case/path of the match string so need to do the same whitelist = {e: {os.path.normcase(k): v for k, v in p.items()} for e, p in whitelist.items()} # paths passed into filter_whitelist_errors are always Unix style filteredfile = 'svg/test.html' unfilteredfile = 'html/test.html' # Tests for passing no errors filtered = filter_whitelist_errors(whitelist, []) assert filtered == [] filtered = filter_whitelist_errors(whitelist, []) assert filtered == [] # Tests for filtering on file and line number filtered = filter_whitelist_errors(whitelist, [['CONSOLE', '', filteredfile, 12]]) assert filtered == [] filtered = filter_whitelist_errors(whitelist, [['CONSOLE', '', unfilteredfile, 12]]) assert filtered == [['CONSOLE', '', unfilteredfile, 12]] filtered = filter_whitelist_errors(whitelist, [['CONSOLE', '', filteredfile, 11]]) assert filtered == [['CONSOLE', '', filteredfile, 11]] # Tests for filtering on just file filtered = filter_whitelist_errors(whitelist, [['INDENT TABS', '', filteredfile, 12]]) assert filtered == [] filtered = filter_whitelist_errors(whitelist, [['INDENT TABS', '', filteredfile, 11]]) assert filtered == [] filtered = filter_whitelist_errors(whitelist, [['INDENT TABS', '', unfilteredfile, 11]]) assert filtered == [['INDENT TABS', '', unfilteredfile, 11]] def test_parse_whitelist(): input_buffer = six.StringIO(""" # Comment CR AT EOL: svg/import/* CR AT EOL: streams/resources/test-utils.js INDENT TABS: .gitmodules INDENT TABS: app-uri/* INDENT TABS: svg/* TRAILING WHITESPACE: app-uri/* CONSOLE:streams/resources/test-utils.js: 12 CR AT EOL, INDENT TABS: html/test.js CR AT EOL, INDENT TABS: html/test2.js: 42 *:*.pdf *:resources/* *, CR AT EOL: *.png """) expected_data = { 'INDENT TABS': { '.gitmodules': {None}, 'app-uri/*': {None}, 'svg/*': {None}, 'html/test.js': {None}, 'html/test2.js': {42}, }, 'TRAILING WHITESPACE': { 'app-uri/*': {None}, }, 'CONSOLE': { 'streams/resources/test-utils.js': {12}, }, 'CR AT EOL': { 'streams/resources/test-utils.js': {None}, 'svg/import/*': {None}, 'html/test.js': {None}, 'html/test2.js': {42}, } } expected_data = {e: {os.path.normcase(k): v for k, v in p.items()} for e, p in expected_data.items()} expected_ignored = {os.path.normcase(x) for x in {"*.pdf", "resources/*", "*.png"}} data, ignored = parse_whitelist(input_buffer) assert data == expected_data assert ignored == expected_ignored def test_lint_no_files(caplog): rv = lint(_dummy_repo, [], "normal") assert rv == 0 assert caplog.text == "" def test_lint_ignored_file(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["broken_ignored.html"], "normal") assert rv == 0 assert not mocked_check_path.called assert not mocked_check_file_contents.called assert caplog.text == "" def test_lint_not_existing_file(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: # really long path-linted filename name = "a" * 256 + ".html" rv = lint(_dummy_repo, [name], "normal") assert rv == 0 assert not mocked_check_path.called assert not mocked_check_file_contents.called assert caplog.text == "" def test_lint_passing(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["okay.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert caplog.text == "" def test_lint_failing(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["broken.html"], "normal") assert rv == 1 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert "TRAILING WHITESPACE" in caplog.text assert "broken.html:1" in caplog.text def test_ref_existent_relative(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["ref/existent_relative.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert caplog.text == "" def test_ref_existent_root_relative(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["ref/existent_root_relative.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert caplog.text == "" def test_ref_non_existent_relative(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["ref/non_existent_relative.html"], "normal") assert rv == 1 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert "NON-EXISTENT-REF" in caplog.text assert "ref/non_existent_relative.html" in caplog.text assert "non_existent_file.html" in caplog.text def test_ref_non_existent_root_relative(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["ref/non_existent_root_relative.html"], "normal") assert rv == 1 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert "NON-EXISTENT-REF" in caplog.text assert "ref/non_existent_root_relative.html" in caplog.text assert "/non_existent_file.html" in caplog.text def test_ref_absolute_url(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["ref/absolute.html"], "normal") assert rv == 1 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert "ABSOLUTE-URL-REF" in caplog.text assert "http://example.com/reference.html" in caplog.text assert "ref/absolute.html" in caplog.text def test_about_blank_as_ref(caplog): with _mock_lint("check_path"): with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["about_blank.html"], "normal") assert rv == 0 assert mocked_check_file_contents.call_count == 1 assert caplog.text == "" def test_ref_same_file_empty(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["ref/same_file_empty.html"], "normal") assert rv == 1 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert "SAME-FILE-REF" in caplog.text assert "same_file_empty.html" in caplog.text def test_ref_same_file_path(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["ref/same_file_path.html"], "normal") assert rv == 1 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert "SAME-FILE-REF" in caplog.text assert "same_file_path.html" in caplog.text def test_manual_path_testharness(caplog): rv = lint(_dummy_repo, ["tests/relative-testharness-manual.html"], "normal") assert rv == 2 assert "TESTHARNESS-PATH" in caplog.text assert "TESTHARNESSREPORT-PATH" in caplog.text def test_css_visual_path_testharness(caplog): rv = lint(_dummy_repo, ["css/css-unique/relative-testharness.html"], "normal") assert rv == 3 assert "CONTENT-VISUAL" in caplog.text assert "TESTHARNESS-PATH" in caplog.text assert "TESTHARNESSREPORT-PATH" in caplog.text def test_css_manual_path_testharness(caplog): rv = lint(_dummy_repo, ["css/css-unique/relative-testharness-interact.html"], "normal") assert rv == 3 assert "CONTENT-MANUAL" in caplog.text assert "TESTHARNESS-PATH" in caplog.text assert "TESTHARNESSREPORT-PATH" in caplog.text def test_lint_passing_and_failing(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["broken.html", "okay.html"], "normal") assert rv == 1 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert "TRAILING WHITESPACE" in caplog.text assert "broken.html:1" in caplog.text assert "okay.html" not in caplog.text def test_check_css_globally_unique_identical_test(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/match/a.html", "css/css-unique/a.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert caplog.text == "" def test_check_css_globally_unique_different_test(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/not-match/a.html", "css/css-unique/a.html"], "normal") assert rv == 2 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert "CSS-COLLIDING-TEST-NAME" in caplog.text def test_check_css_globally_unique_different_spec_test(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/selectors/a.html", "css/css-unique/a.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert caplog.text == "" def test_check_css_globally_unique_support_ignored(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/support/a.html", "css/css-unique/support/tools/a.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert caplog.text == "" def test_check_css_globally_unique_support_identical(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/support/a.html", "css/css-unique/match/support/a.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert caplog.text == "" def test_check_css_globally_unique_support_different(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/not-match/support/a.html", "css/css-unique/support/a.html"], "normal") assert rv == 2 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert "CSS-COLLIDING-SUPPORT-NAME" in caplog.text def test_check_css_globally_unique_test_support(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/support/a.html", "css/css-unique/a.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert caplog.text == "" def test_check_css_globally_unique_ref_identical(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/a-ref.html", "css/css-unique/match/a-ref.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert caplog.text == "" def test_check_css_globally_unique_ref_different(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/not-match/a-ref.html", "css/css-unique/a-ref.html"], "normal") assert rv == 2 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert "CSS-COLLIDING-REF-NAME" in caplog.text def test_check_css_globally_unique_test_ref(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/a-ref.html", "css/css-unique/a.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert caplog.text == "" def test_check_css_globally_unique_ignored(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/tools/a.html", "css/css-unique/not-match/tools/a.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 2 assert mocked_check_file_contents.call_count == 2 assert caplog.text == "" def test_check_css_globally_unique_ignored_dir(caplog): with _mock_lint("check_path") as mocked_check_path: with _mock_lint("check_file_contents") as mocked_check_file_contents: rv = lint(_dummy_repo, ["css/css-unique/support/a.html"], "normal") assert rv == 0 assert mocked_check_path.call_count == 1 assert mocked_check_file_contents.call_count == 1 assert caplog.text == "" def test_all_filesystem_paths(): with mock.patch( 'tools.lint.lint.walk', return_value=[('', [('dir_a', None), ('dir_b', None)], [('file_a', None), ('file_b', None)]), ('dir_a', [], [('file_c', None), ('file_d', None)])] ): got = list(lint_mod.all_filesystem_paths('.')) assert got == ['file_a', 'file_b', os.path.join('dir_a', 'file_c'), os.path.join('dir_a', 'file_d')] def test_filesystem_paths_subdir(): with mock.patch( 'tools.lint.lint.walk', return_value=[('', [('dir_a', None), ('dir_b', None)], [('file_a', None), ('file_b', None)]), ('dir_a', [], [('file_c', None), ('file_d', None)])] ): got = list(lint_mod.all_filesystem_paths('.', 'dir')) assert got == [os.path.join('dir', 'file_a'), os.path.join('dir', 'file_b'), os.path.join('dir', 'dir_a', 'file_c'), os.path.join('dir', 'dir_a', 'file_d')] def test_main_with_args(): orig_argv = sys.argv try: sys.argv = ['./lint', 'a', 'b', 'c'] with mock.patch(lint_mod.__name__ + ".os.path.isfile") as mock_isfile: mock_isfile.return_value = True with _mock_lint('lint', return_value=True) as m: lint_mod.main(**vars(create_parser().parse_args())) m.assert_called_once_with(repo_root, [os.path.relpath(os.path.join(os.getcwd(), x), repo_root) for x in ['a', 'b', 'c']], "normal") finally: sys.argv = orig_argv def test_main_no_args(): orig_argv = sys.argv try: sys.argv = ['./lint'] with _mock_lint('lint', return_value=True) as m: with _mock_lint('changed_files', return_value=['foo', 'bar']): lint_mod.main(**vars(create_parser().parse_args())) m.assert_called_once_with(repo_root, ['foo', 'bar'], "normal") finally: sys.argv = orig_argv def test_main_all(): orig_argv = sys.argv try: sys.argv = ['./lint', '--all'] with _mock_lint('lint', return_value=True) as m: with _mock_lint('all_filesystem_paths', return_value=['foo', 'bar']): lint_mod.main(**vars(create_parser().parse_args())) m.assert_called_once_with(repo_root, ['foo', 'bar'], "normal") finally: sys.argv = orig_argv
Nick-Hall/gramps
refs/heads/master
gramps/gen/plug/report/_paper.py
9
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # Copyright (C) 2010 Jakim Friant # # 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. # #------------------------------------------------------------------------- # # Python modules # #------------------------------------------------------------------------- #------------------------------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from ..docgen import PaperSize from ...const import PAPERSIZE #------------------------------------------------------------------------- # # Try to abstract SAX1 from SAX2 # #------------------------------------------------------------------------- from xml.sax import make_parser, handler, SAXParseException #------------------------------------------------------------------------- # # Constants # #------------------------------------------------------------------------- paper_sizes = [] #------------------------------------------------------------------------- # # PageSizeParser # #------------------------------------------------------------------------- class PageSizeParser(handler.ContentHandler): """Parses the XML file and builds the list of page sizes""" def __init__(self, paper_list): handler.ContentHandler.__init__(self) self.paper_list = paper_list self.locator = None def setDocumentLocator(self, locator): self.locator = locator def startElement(self, tag, attrs): if tag == "page": name = attrs['name'] height = float(attrs['height']) width = float(attrs['width']) self.paper_list.append(PaperSize(name, height, width)) #------------------------------------------------------------------------- # # Parse XML file. If it fails, use the default # #------------------------------------------------------------------------- try: parser = make_parser() parser.setContentHandler(PageSizeParser(paper_sizes)) with open(PAPERSIZE) as the_file: parser.parse(the_file) paper_sizes.append(PaperSize("Custom Size", -1, -1)) # always in English except (IOError, OSError, SAXParseException): paper_sizes = [ PaperSize("Letter",27.94,21.59), PaperSize("Legal",35.56,21.59), PaperSize("A0",118.9,84.1), PaperSize("A1",84.1,59.4), PaperSize("A2",59.4,42.0), PaperSize("A3",42.0,29.7), PaperSize("A4",29.7,21.0), PaperSize("A5",21.0,14.8), PaperSize("B0",141.4,100.0), PaperSize("B1",100.0,70.7), PaperSize("B2",70.7,50.0), PaperSize("B3",50.0,35.3), PaperSize("B4",35.3,25.0), PaperSize("B5",25.0,17.6), PaperSize("B6",17.6,12.5), PaperSize("B",43.18,27.94), PaperSize("C",55.88,43.18), PaperSize("D",86.36, 55.88), PaperSize("E",111.76,86.36), PaperSize("Custom Size",-1,-1) # always in English ]
NelisVerhoef/scikit-learn
refs/heads/master
doc/tutorial/text_analytics/solutions/exercise_02_sentiment.py
254
"""Build a sentiment analysis / polarity model Sentiment analysis can be casted as a binary text classification problem, that is fitting a linear classifier on features extracted from the text of the user messages so as to guess wether the opinion of the author is positive or negative. In this examples we will use a movie review dataset. """ # Author: Olivier Grisel <olivier.grisel@ensta.org> # License: Simplified BSD import sys from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.svm import LinearSVC from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV from sklearn.datasets import load_files from sklearn.cross_validation import train_test_split from sklearn import metrics if __name__ == "__main__": # NOTE: we put the following in a 'if __name__ == "__main__"' protected # block to be able to use a multi-core grid search that also works under # Windows, see: http://docs.python.org/library/multiprocessing.html#windows # The multiprocessing module is used as the backend of joblib.Parallel # that is used when n_jobs != 1 in GridSearchCV # the training data folder must be passed as first argument movie_reviews_data_folder = sys.argv[1] dataset = load_files(movie_reviews_data_folder, shuffle=False) print("n_samples: %d" % len(dataset.data)) # split the dataset in training and test set: docs_train, docs_test, y_train, y_test = train_test_split( dataset.data, dataset.target, test_size=0.25, random_state=None) # TASK: Build a vectorizer / classifier pipeline that filters out tokens # that are too rare or too frequent pipeline = Pipeline([ ('vect', TfidfVectorizer(min_df=3, max_df=0.95)), ('clf', LinearSVC(C=1000)), ]) # TASK: Build a grid search to find out whether unigrams or bigrams are # more useful. # Fit the pipeline on the training set using grid search for the parameters parameters = { 'vect__ngram_range': [(1, 1), (1, 2)], } grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1) grid_search.fit(docs_train, y_train) # TASK: print the cross-validated scores for the each parameters set # explored by the grid search print(grid_search.grid_scores_) # TASK: Predict the outcome on the testing set and store it in a variable # named y_predicted y_predicted = grid_search.predict(docs_test) # Print the classification report print(metrics.classification_report(y_test, y_predicted, target_names=dataset.target_names)) # Print and plot the confusion matrix cm = metrics.confusion_matrix(y_test, y_predicted) print(cm) # import matplotlib.pyplot as plt # plt.matshow(cm) # plt.show()
sadmansk/servo
refs/heads/master
tests/wpt/web-platform-tests/tools/pywebsocket/mod_pywebsocket/msgutil.py
23
# Copyright 2011, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Message related utilities. Note: request.connection.write/read are used in this module, even though mod_python document says that they should be used only in connection handlers. Unfortunately, we have no other options. For example, request.write/read are not suitable because they don't allow direct raw bytes writing/reading. """ from six.moves import queue import threading # Export Exception symbols from msgutil for backward compatibility from mod_pywebsocket._stream_base import ConnectionTerminatedException from mod_pywebsocket._stream_base import InvalidFrameException from mod_pywebsocket._stream_base import BadOperationException from mod_pywebsocket._stream_base import UnsupportedFrameException # An API for handler to send/receive WebSocket messages. def close_connection(request): """Close connection. Args: request: mod_python request. """ request.ws_stream.close_connection() def send_message(request, payload_data, end=True, binary=False): """Send a message (or part of a message). Args: request: mod_python request. payload_data: unicode text or str binary to send. end: True to terminate a message. False to send payload_data as part of a message that is to be terminated by next or later send_message call with end=True. binary: send payload_data as binary frame(s). Raises: BadOperationException: when server already terminated. """ request.ws_stream.send_message(payload_data, end, binary) def receive_message(request): """Receive a WebSocket frame and return its payload as a text in unicode or a binary in str. Args: request: mod_python request. Raises: InvalidFrameException: when client send invalid frame. UnsupportedFrameException: when client send unsupported frame e.g. some of reserved bit is set but no extension can recognize it. InvalidUTF8Exception: when client send a text frame containing any invalid UTF-8 string. ConnectionTerminatedException: when the connection is closed unexpectedly. BadOperationException: when client already terminated. """ return request.ws_stream.receive_message() def send_ping(request, body=''): request.ws_stream.send_ping(body) class MessageReceiver(threading.Thread): """This class receives messages from the client. This class provides three ways to receive messages: blocking, non-blocking, and via callback. Callback has the highest precedence. Note: This class should not be used with the standalone server for wss because pyOpenSSL used by the server raises a fatal error if the socket is accessed from multiple threads. """ def __init__(self, request, onmessage=None): """Construct an instance. Args: request: mod_python request. onmessage: a function to be called when a message is received. May be None. If not None, the function is called on another thread. In that case, MessageReceiver.receive and MessageReceiver.receive_nowait are useless because they will never return any messages. """ threading.Thread.__init__(self) self._request = request self._queue = queue.Queue() self._onmessage = onmessage self._stop_requested = False self.setDaemon(True) self.start() def run(self): try: while not self._stop_requested: message = receive_message(self._request) if self._onmessage: self._onmessage(message) else: self._queue.put(message) finally: close_connection(self._request) def receive(self): """ Receive a message from the channel, blocking. Returns: message as a unicode string. """ return self._queue.get() def receive_nowait(self): """ Receive a message from the channel, non-blocking. Returns: message as a unicode string if available. None otherwise. """ try: message = self._queue.get_nowait() except queue.Empty: message = None return message def stop(self): """Request to stop this instance. The instance will be stopped after receiving the next message. This method may not be very useful, but there is no clean way in Python to forcefully stop a running thread. """ self._stop_requested = True class MessageSender(threading.Thread): """This class sends messages to the client. This class provides both synchronous and asynchronous ways to send messages. Note: This class should not be used with the standalone server for wss because pyOpenSSL used by the server raises a fatal error if the socket is accessed from multiple threads. """ def __init__(self, request): """Construct an instance. Args: request: mod_python request. """ threading.Thread.__init__(self) self._request = request self._queue = queue.Queue() self.setDaemon(True) self.start() def run(self): while True: message, condition = self._queue.get() condition.acquire() send_message(self._request, message) condition.notify() condition.release() def send(self, message): """Send a message, blocking.""" condition = threading.Condition() condition.acquire() self._queue.put((message, condition)) condition.wait() def send_nowait(self, message): """Send a message, non-blocking.""" self._queue.put((message, threading.Condition())) # vi:sts=4 sw=4 et
birocorneliu/youtube-dl
refs/heads/master
youtube_dl/extractor/ynet.py
105
# coding: utf-8 from __future__ import unicode_literals import re import json from .common import InfoExtractor from ..compat import compat_urllib_parse_unquote_plus class YnetIE(InfoExtractor): _VALID_URL = r'http://(?:.+?\.)?ynet\.co\.il/(?:.+?/)?0,7340,(?P<id>L(?:-[0-9]+)+),00\.html' _TESTS = [ { 'url': 'http://hot.ynet.co.il/home/0,7340,L-11659-99244,00.html', 'info_dict': { 'id': 'L-11659-99244', 'ext': 'flv', 'title': 'איש לא יודע מאיפה באנו', 'thumbnail': 're:^https?://.*\.jpg', } }, { 'url': 'http://hot.ynet.co.il/home/0,7340,L-8859-84418,00.html', 'info_dict': { 'id': 'L-8859-84418', 'ext': 'flv', 'title': "צפו: הנשיקה הלוהטת של תורגי' ויוליה פלוטקין", 'thumbnail': 're:^https?://.*\.jpg', } } ] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) content = compat_urllib_parse_unquote_plus(self._og_search_video_url(webpage)) config = json.loads(self._search_regex(r'config=({.+?})$', content, 'video config')) f4m_url = config['clip']['url'] title = self._og_search_title(webpage) m = re.search(r'ynet - HOT -- (["\']+)(?P<title>.+?)\1', title) if m: title = m.group('title') return { 'id': video_id, 'title': title, 'formats': self._extract_f4m_formats(f4m_url, video_id), 'thumbnail': self._og_search_thumbnail(webpage), }
aperigault/ansible
refs/heads/devel
test/units/modules/cloud/docker/test_docker_container.py
23
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import unittest from ansible.modules.cloud.docker.docker_container import TaskParameters class TestTaskParameters(unittest.TestCase): """Unit tests for TaskParameters.""" def test_parse_exposed_ports_tcp_udp(self): """ Ensure _parse_exposed_ports does not cancel ports with the same number but different protocol. """ task_params = TaskParameters.__new__(TaskParameters) task_params.exposed_ports = None result = task_params._parse_exposed_ports([80, '443', '443/udp']) self.assertTrue((80, 'tcp') in result) self.assertTrue((443, 'tcp') in result) self.assertTrue((443, 'udp') in result)
SunghanKim/numpy
refs/heads/master
benchmarks/benchmarks/bench_io.py
29
from __future__ import absolute_import, division, print_function from .common import Benchmark, squares import numpy as np class Copy(Benchmark): params = ["int8", "int16", "float32", "float64", "complex64", "complex128"] param_names = ['type'] def setup(self, typename): dtype = np.dtype(typename) self.d = np.arange((50 * 500), dtype=dtype).reshape((500, 50)) self.e = np.arange((50 * 500), dtype=dtype).reshape((50, 500)) self.e_d = self.e.reshape(self.d.shape) self.dflat = np.arange((50 * 500), dtype=dtype) def time_memcpy(self, typename): self.d[...] = self.e_d def time_cont_assign(self, typename): self.d[...] = 1 def time_strided_copy(self, typename): self.d[...] = self.e.T def time_strided_assign(self, typename): self.dflat[::2] = 2 class CopyTo(Benchmark): def setup(self): self.d = np.ones(50000) self.e = self.d.copy() self.m = (self.d == 1) self.im = (~ self.m) self.m8 = self.m.copy() self.m8[::8] = (~ self.m[::8]) self.im8 = (~ self.m8) def time_copyto(self): np.copyto(self.d, self.e) def time_copyto_sparse(self): np.copyto(self.d, self.e, where=self.m) def time_copyto_dense(self): np.copyto(self.d, self.e, where=self.im) def time_copyto_8_sparse(self): np.copyto(self.d, self.e, where=self.m8) def time_copyto_8_dense(self): np.copyto(self.d, self.e, where=self.im8) class Savez(Benchmark): def time_vb_savez_squares(self): np.savez('tmp.npz', squares)
2014c2g2/2015cda
refs/heads/master
static/Brython3.1.1-20150328-091302/Lib/unittest/result.py
727
"""Test result object""" import io import sys import traceback from . import util from functools import wraps __unittest = True def failfast(method): @wraps(method) def inner(self, *args, **kw): if getattr(self, 'failfast', False): self.stop() return method(self, *args, **kw) return inner STDOUT_LINE = '\nStdout:\n%s' STDERR_LINE = '\nStderr:\n%s' class TestResult(object): """Holder for test result information. Test results are automatically managed by the TestCase and TestSuite classes, and do not need to be explicitly manipulated by writers of tests. Each instance holds the total number of tests run, and collections of failures and errors that occurred among those test runs. The collections contain tuples of (testcase, exceptioninfo), where exceptioninfo is the formatted traceback of the error that occurred. """ _previousTestClass = None _testRunEntered = False _moduleSetUpFailed = False def __init__(self, stream=None, descriptions=None, verbosity=None): self.failfast = False self.failures = [] self.errors = [] self.testsRun = 0 self.skipped = [] self.expectedFailures = [] self.unexpectedSuccesses = [] self.shouldStop = False self.buffer = False self._stdout_buffer = None self._stderr_buffer = None self._original_stdout = sys.stdout self._original_stderr = sys.stderr self._mirrorOutput = False def printErrors(self): "Called by TestRunner after test run" #fixme brython pass def startTest(self, test): "Called when the given test is about to be run" self.testsRun += 1 self._mirrorOutput = False self._setupStdout() def _setupStdout(self): if self.buffer: if self._stderr_buffer is None: self._stderr_buffer = io.StringIO() self._stdout_buffer = io.StringIO() sys.stdout = self._stdout_buffer sys.stderr = self._stderr_buffer def startTestRun(self): """Called once before any tests are executed. See startTest for a method called before each test. """ def stopTest(self, test): """Called when the given test has been run""" self._restoreStdout() self._mirrorOutput = False def _restoreStdout(self): if self.buffer: if self._mirrorOutput: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' self._original_stdout.write(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' self._original_stderr.write(STDERR_LINE % error) sys.stdout = self._original_stdout sys.stderr = self._original_stderr self._stdout_buffer.seek(0) self._stdout_buffer.truncate() self._stderr_buffer.seek(0) self._stderr_buffer.truncate() def stopTestRun(self): """Called once after all tests are executed. See stopTest for a method called after each test. """ @failfast def addError(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """ self.errors.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True @failfast def addFailure(self, test, err): """Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info().""" self.failures.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True def addSuccess(self, test): "Called when a test has completed successfully" pass def addSkip(self, test, reason): """Called when a test is skipped.""" self.skipped.append((test, reason)) def addExpectedFailure(self, test, err): """Called when an expected failure/error occured.""" self.expectedFailures.append( (test, self._exc_info_to_string(err, test))) @failfast def addUnexpectedSuccess(self, test): """Called when a test was expected to fail, but succeed.""" self.unexpectedSuccesses.append(test) def wasSuccessful(self): "Tells whether or not this result was a success" return len(self.failures) == len(self.errors) == 0 def stop(self): "Indicates that the tests should be aborted" self.shouldStop = True def _exc_info_to_string(self, err, test): """Converts a sys.exc_info()-style tuple of values into a string.""" exctype, value, tb = err # Skip test runner traceback levels while tb and self._is_relevant_tb_level(tb): tb = tb.tb_next if exctype is test.failureException: # Skip assert*() traceback levels length = self._count_relevant_tb_levels(tb) msgLines = traceback.format_exception(exctype, value, tb, length) else: msgLines = traceback.format_exception(exctype, value, tb) if self.buffer: output = sys.stdout.getvalue() error = sys.stderr.getvalue() if output: if not output.endswith('\n'): output += '\n' msgLines.append(STDOUT_LINE % output) if error: if not error.endswith('\n'): error += '\n' msgLines.append(STDERR_LINE % error) return ''.join(msgLines) def _is_relevant_tb_level(self, tb): #fix me brython #return '__unittest' in tb.tb_frame.f_globals return True #for now, lets just return False def _count_relevant_tb_levels(self, tb): length = 0 while tb and not self._is_relevant_tb_level(tb): length += 1 tb = tb.tb_next return length def __repr__(self): return ("<%s run=%i errors=%i failures=%i>" % (util.strclass(self.__class__), self.testsRun, len(self.errors), len(self.failures)))
BlackLight/Snort_AIPreproc
refs/heads/master
corr_modules/example_module.py
1
#!/usr/bin/python # Example correlation index in Python # It simply does nothing (both the correlation index # and the correlation weight are zero), use it as # track for writing your own correlation modules # Go to pymodule and run # $ python setup.py build # $ [sudo] python setup.py install # in order to build and install the snortai Python module import snortai # Function that takes two alerts as arguments (arguments of # alert object: # id, gid, sid, rev, description, priority, classification, # timestamp, src_addr, dst_addr, src_port, dst_port, latitude, # longitude) and returns a correlation index between 0 and 1 # expressing how correlated these two alerts are def AI_corr_index ( alert1, alert2 ): # alerts = snortai.alerts() # for alert in alerts: # do_something # # print alert1.gid, alert1.sid, alert1.rev # print alert2.gid, alert2.sid, alert2.rev return 0.0 # Return the weight of this index, between 0 and 1 def AI_corr_index_weight(): return 0.0
iemejia/beam
refs/heads/master
sdks/python/apache_beam/io/kafka.py
5
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Unbounded source and sink transforms for `Kafka <href="http://kafka.apache.org/>`_. These transforms are currently supported by Beam portable runners (for example, portable Flink and Spark) as well as Dataflow runner. **Setup** Transforms provided in this module are cross-language transforms implemented in the Beam Java SDK. During the pipeline construction, Python SDK will connect to a Java expansion service to expand these transforms. To facilitate this, a small amount of setup is needed before using these transforms in a Beam Python pipeline. There are several ways to setup cross-language Kafka transforms. * Option 1: use the default expansion service * Option 2: specify a custom expansion service See below for details regarding each of these options. *Option 1: Use the default expansion service* This is the recommended and easiest setup option for using Python Kafka transforms. This option is only available for Beam 2.22.0 and later. This option requires following pre-requisites before running the Beam pipeline. * Install Java runtime in the computer from where the pipeline is constructed and make sure that 'java' command is available. In this option, Python SDK will either download (for released Beam version) or build (when running from a Beam Git clone) a expansion service jar and use that to expand transforms. Currently Kafka transforms use the 'beam-sdks-java-io-expansion-service' jar for this purpose. *Option 2: specify a custom expansion service* In this option, you startup your own expansion service and provide that as a parameter when using the transforms provided in this module. This option requires following pre-requisites before running the Beam pipeline. * Startup your own expansion service. * Update your pipeline to provide the expansion service address when initiating Kafka transforms provided in this module. Flink Users can use the built-in Expansion Service of the Flink Runner's Job Server. If you start Flink's Job Server, the expansion service will be started on port 8097. For a different address, please set the expansion_service parameter. **More information** For more information regarding cross-language transforms see: - https://beam.apache.org/roadmap/portability/ For more information specific to Flink runner see: - https://beam.apache.org/documentation/runners/flink/ """ # pytype: skip-file import typing from apache_beam.transforms.external import BeamJarExpansionService from apache_beam.transforms.external import ExternalTransform from apache_beam.transforms.external import NamedTupleBasedPayloadBuilder ReadFromKafkaSchema = typing.NamedTuple( 'ReadFromKafkaSchema', [('consumer_config', typing.Mapping[str, str]), ('topics', typing.List[str]), ('key_deserializer', str), ('value_deserializer', str), ('start_read_time', typing.Optional[int]), ('max_num_records', typing.Optional[int]), ('max_read_time', typing.Optional[int]), ('commit_offset_in_finalize', bool), ('timestamp_policy', str)]) def default_io_expansion_service(): return BeamJarExpansionService('sdks:java:io:expansion-service:shadowJar') class ReadFromKafka(ExternalTransform): """ An external PTransform which reads from Kafka and returns a KV pair for each item in the specified Kafka topics. If no Kafka Deserializer for key/value is provided, then the data will be returned as a raw byte array. Experimental; no backwards compatibility guarantees. """ # Returns the key/value data as raw byte arrays byte_array_deserializer = ( 'org.apache.kafka.common.serialization.ByteArrayDeserializer') processing_time_policy = 'ProcessingTime' create_time_policy = 'CreateTime' log_append_time = 'LogAppendTime' URN = 'beam:external:java:kafka:read:v1' def __init__( self, consumer_config, topics, key_deserializer=byte_array_deserializer, value_deserializer=byte_array_deserializer, start_read_time=None, max_num_records=None, max_read_time=None, commit_offset_in_finalize=False, timestamp_policy=processing_time_policy, expansion_service=None, ): """ Initializes a read operation from Kafka. :param consumer_config: A dictionary containing the consumer configuration. :param topics: A list of topic strings. :param key_deserializer: A fully-qualified Java class name of a Kafka Deserializer for the topic's key, e.g. 'org.apache.kafka.common.serialization.LongDeserializer'. Default: 'org.apache.kafka.common.serialization.ByteArrayDeserializer'. :param value_deserializer: A fully-qualified Java class name of a Kafka Deserializer for the topic's value, e.g. 'org.apache.kafka.common.serialization.LongDeserializer'. Default: 'org.apache.kafka.common.serialization.ByteArrayDeserializer'. :param start_read_time: Use timestamp to set up start offset in milliseconds epoch. :param max_num_records: Maximum amount of records to be read. Mainly used for tests and demo applications. :param max_read_time: Maximum amount of time in seconds the transform executes. Mainly used for tests and demo applications. :param commit_offset_in_finalize: Whether to commit offsets when finalizing. :param timestamp_policy: The built-in timestamp policy which is used for extracting timestamp from KafkaRecord. :param expansion_service: The address (host:port) of the ExpansionService. """ if timestamp_policy not in [ReadFromKafka.processing_time_policy, ReadFromKafka.create_time_policy, ReadFromKafka.log_append_time]: raise ValueError( 'timestamp_policy should be one of ' '[ProcessingTime, CreateTime, LogAppendTime]') super(ReadFromKafka, self).__init__( self.URN, NamedTupleBasedPayloadBuilder( ReadFromKafkaSchema( consumer_config=consumer_config, topics=topics, key_deserializer=key_deserializer, value_deserializer=value_deserializer, max_num_records=max_num_records, max_read_time=max_read_time, start_read_time=start_read_time, commit_offset_in_finalize=commit_offset_in_finalize, timestamp_policy=timestamp_policy)), expansion_service or default_io_expansion_service()) WriteToKafkaSchema = typing.NamedTuple( 'WriteToKafkaSchema', [ ('producer_config', typing.Mapping[str, str]), ('topic', str), ('key_serializer', str), ('value_serializer', str), ]) class WriteToKafka(ExternalTransform): """ An external PTransform which writes KV data to a specified Kafka topic. If no Kafka Serializer for key/value is provided, then key/value are assumed to be byte arrays. Experimental; no backwards compatibility guarantees. """ # Default serializer which passes raw bytes to Kafka byte_array_serializer = ( 'org.apache.kafka.common.serialization.ByteArraySerializer') URN = 'beam:external:java:kafka:write:v1' def __init__( self, producer_config, topic, key_serializer=byte_array_serializer, value_serializer=byte_array_serializer, expansion_service=None): """ Initializes a write operation to Kafka. :param producer_config: A dictionary containing the producer configuration. :param topic: A Kafka topic name. :param key_deserializer: A fully-qualified Java class name of a Kafka Serializer for the topic's key, e.g. 'org.apache.kafka.common.serialization.LongSerializer'. Default: 'org.apache.kafka.common.serialization.ByteArraySerializer'. :param value_deserializer: A fully-qualified Java class name of a Kafka Serializer for the topic's value, e.g. 'org.apache.kafka.common.serialization.LongSerializer'. Default: 'org.apache.kafka.common.serialization.ByteArraySerializer'. :param expansion_service: The address (host:port) of the ExpansionService. """ super(WriteToKafka, self).__init__( self.URN, NamedTupleBasedPayloadBuilder( WriteToKafkaSchema( producer_config=producer_config, topic=topic, key_serializer=key_serializer, value_serializer=value_serializer, )), expansion_service or default_io_expansion_service())
tapomayukh/projects_in_python
refs/heads/master
sandbox_tapo/src/skin_related/Misc/freq_analysis.py
1
from scipy import signal import math, numpy as np from matplotlib import pyplot import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3') import rospy import hrl_lib.matplotlib_util as mpu import hrl_lib.util as ut if __name__ == '__main__': ### Frequency Analysis for Experimental Data ta_fs = ut.load_pickle('time_varying_data_fixed_styrofoam.pkl') ta_fp = ut.load_pickle('time_varying_data_fixed_pillow.pkl') ta_ms = ut.load_pickle('time_varying_data_movable_styrofoam.pkl') ta_mp = ut.load_pickle('time_varying_data_movable_pillow.pkl') ### FOR Fixed_Styrofoam (Total_Forces) # some constants samp_rate = 100 sim_time = ta_mp[-1,0] nsamps = int(samp_rate*sim_time) #cutoff_freq = 5 #for HPF ?? cutoff_freq = 0.5 #for LPF ?? fig = pyplot.figure() # generate input signal t = ta_mp[:,0] x = ta_mp[:,1] time_dom = fig.add_subplot(232) pyplot.plot(t, x) pyplot.title('Filter Input - Time Domain') pyplot.grid(True) # input signal spectrum xfreq = np.fft.fft(x) fft_freqs = np.fft.fftfreq(nsamps, d=1./samp_rate) fig.add_subplot(233) pyplot.loglog(fft_freqs[0:nsamps/2], np.abs(xfreq)[0:nsamps/2]) pyplot.title('Filter Input - Frequency Domain') pyplot.grid(True) # design filter (Low-Pass Butterworth) norm_pass = 2*math.pi*cutoff_freq/samp_rate norm_stop = 1.5*norm_pass (N, Wn) = signal.buttord(wp=norm_pass, ws=norm_stop, gpass=2, gstop=30, analog=0) (b, a) = signal.butter(N, Wn, btype='low', analog=0, output='ba') b *= 1e3 print("b="+str(b)+", a="+str(a)) # design filter (High-Pass Butterworth) #norm_stop = 2*math.pi*cutoff_freq/samp_rate #norm_pass = 1.5*norm_stop #(N, Wn) = signal.buttord(wp=norm_pass, ws=norm_stop, gpass=2, gstop=30, analog=0) #(b, a) = signal.butter(N, Wn, btype='high', analog=0, output='ba') #b *= 1e3 #print("b="+str(b)+", a="+str(a)) # design filter (Low-Pass FIR) #b = signal.firwin(5,cutoff_freq) #a = 1 # design filter (High-Pass FIR) (This feature is enabled only in the latest version of SciPy(v0.10.dev) #b = signal.firwin(5,cutoff_freq,pass_zero=False) #a = 1 # filter frequency response (w, h) = signal.freqz(b, a) fig.add_subplot(131) pyplot.loglog(w, np.abs(h)) pyplot.title('Filter Frequency Response') pyplot.text(2e-3, 1e-5, str(N)+"-th order Butterworth filter") pyplot.grid(True) # filtered output y = signal.lfilter(b, a, x) fig.add_subplot(235) pyplot.plot(t, y) pyplot.title('Filter output - Time Domain') pyplot.grid(True) # output spectrum yfreq = np.fft.fft(y) fig.add_subplot(236) pyplot.loglog(fft_freqs[0:nsamps/2], np.abs(yfreq)[0:nsamps/2]) pyplot.title('Filter Output - Frequency Domain') pyplot.grid(True) pyplot.show()
sumnerevans/wireless-debugging
refs/heads/master
server/parsing_lib/__init__.py
1
from parsing_lib.log_parser import LogParser
infilect/ml-course1
refs/heads/master
deep-learning-tensorflow/week3/assignments/style_transfer/vgg_model_sols.py
2
""" Load VGGNet weights needed for the implementation of the paper For more details, please read the assignment handout: http://web.stanford.edu/class/cs20si/assignments/a2.pdf """ import numpy as np import tensorflow as tf import scipy.io def _weights(vgg_layers, layer, expected_layer_name): """ Return the weights and biases already trained by VGG """ W = vgg_layers[0][layer][0][0][2][0][0] b = vgg_layers[0][layer][0][0][2][0][1] layer_name = vgg_layers[0][layer][0][0][0][0] assert layer_name == expected_layer_name return W, b.reshape(b.size) def _conv2d_relu(vgg_layers, prev_layer, layer, layer_name): """ Return the Conv2D layer with RELU using the weights, biases from the VGG model at 'layer'. Inputs: vgg_layers: holding all the layers of VGGNet prev_layer: the output tensor from the previous layer layer: the index to current layer in vgg_layers layer_name: the string that is the name of the current layer. It's used to specify variable_scope. Output: relu applied on the convolution. Note that you first need to obtain W and b from vgg-layers using the function _weights() defined above. W and b returned from _weights() are numpy arrays, so you have to convert them to TF tensors using tf.constant. Note that you'll have to do apply relu on the convolution. Hint for choosing strides size: for small images, you probably don't want to skip any pixel """ with tf.variable_scope(layer_name) as scope: W, b = _weights(vgg_layers, layer, layer_name) W = tf.constant(W, name='weights') b = tf.constant(b, name='bias') conv2d = tf.nn.conv2d(prev_layer, filter=W, strides=[1, 1, 1, 1], padding='SAME') return tf.nn.relu(conv2d + b) def _avgpool(prev_layer): """ Return the average pooling layer. The paper suggests that average pooling actually works better than max pooling. Input: prev_layer: the output tensor from the previous layer Output: the output of the tf.nn.avg_pool() function. Hint for choosing strides and kszie: choose what you feel appropriate """ return tf.nn.avg_pool(prev_layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name='avg_pool_') def load_vgg(path, input_image): """ Load VGG into a TensorFlow model. Use a dictionary to hold the model instead of using a Python class """ vgg = scipy.io.loadmat(path) vgg_layers = vgg['layers'] graph = {} graph['conv1_1'] = _conv2d_relu(vgg_layers, input_image, 0, 'conv1_1') graph['conv1_2'] = _conv2d_relu(vgg_layers, graph['conv1_1'], 2, 'conv1_2') graph['avgpool1'] = _avgpool(graph['conv1_2']) graph['conv2_1'] = _conv2d_relu(vgg_layers, graph['avgpool1'], 5, 'conv2_1') graph['conv2_2'] = _conv2d_relu(vgg_layers, graph['conv2_1'], 7, 'conv2_2') graph['avgpool2'] = _avgpool(graph['conv2_2']) graph['conv3_1'] = _conv2d_relu(vgg_layers, graph['avgpool2'], 10, 'conv3_1') graph['conv3_2'] = _conv2d_relu(vgg_layers, graph['conv3_1'], 12, 'conv3_2') graph['conv3_3'] = _conv2d_relu(vgg_layers, graph['conv3_2'], 14, 'conv3_3') graph['conv3_4'] = _conv2d_relu(vgg_layers, graph['conv3_3'], 16, 'conv3_4') graph['avgpool3'] = _avgpool(graph['conv3_4']) graph['conv4_1'] = _conv2d_relu(vgg_layers, graph['avgpool3'], 19, 'conv4_1') graph['conv4_2'] = _conv2d_relu(vgg_layers, graph['conv4_1'], 21, 'conv4_2') graph['conv4_3'] = _conv2d_relu(vgg_layers, graph['conv4_2'], 23, 'conv4_3') graph['conv4_4'] = _conv2d_relu(vgg_layers, graph['conv4_3'], 25, 'conv4_4') graph['avgpool4'] = _avgpool(graph['conv4_4']) graph['conv5_1'] = _conv2d_relu(vgg_layers, graph['avgpool4'], 28, 'conv5_1') graph['conv5_2'] = _conv2d_relu(vgg_layers, graph['conv5_1'], 30, 'conv5_2') graph['conv5_3'] = _conv2d_relu(vgg_layers, graph['conv5_2'], 32, 'conv5_3') graph['conv5_4'] = _conv2d_relu(vgg_layers, graph['conv5_3'], 34, 'conv5_4') graph['avgpool5'] = _avgpool(graph['conv5_4']) return graph
sdaftuar/bitcoin
refs/heads/master
qa/rpc-tests/httpbasics.py
106
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test rpc http basics # from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import http.client import urllib.parse class HTTPBasicsTest (BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 3 self.setup_clean_chain = False def setup_network(self): self.nodes = self.setup_nodes() def run_test(self): ################################################# # lowlevel check for http persistent connection # ################################################# url = urllib.parse.urlparse(self.nodes[0].url) authpair = url.username + ':' + url.password headers = {"Authorization": "Basic " + str_to_b64str(authpair)} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert(b'"error":null' in out1) assert(conn.sock!=None) #according to http/1.1 connection must still be open! #send 2nd request without closing connection conn.request('POST', '/', '{"method": "getchaintips"}', headers) out1 = conn.getresponse().read() assert(b'"error":null' in out1) #must also response with a correct json-rpc message assert(conn.sock!=None) #according to http/1.1 connection must still be open! conn.close() #same should be if we add keep-alive because this should be the std. behaviour headers = {"Authorization": "Basic " + str_to_b64str(authpair), "Connection": "keep-alive"} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert(b'"error":null' in out1) assert(conn.sock!=None) #according to http/1.1 connection must still be open! #send 2nd request without closing connection conn.request('POST', '/', '{"method": "getchaintips"}', headers) out1 = conn.getresponse().read() assert(b'"error":null' in out1) #must also response with a correct json-rpc message assert(conn.sock!=None) #according to http/1.1 connection must still be open! conn.close() #now do the same with "Connection: close" headers = {"Authorization": "Basic " + str_to_b64str(authpair), "Connection":"close"} conn = http.client.HTTPConnection(url.hostname, url.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert(b'"error":null' in out1) assert(conn.sock==None) #now the connection must be closed after the response #node1 (2nd node) is running with disabled keep-alive option urlNode1 = urllib.parse.urlparse(self.nodes[1].url) authpair = urlNode1.username + ':' + urlNode1.password headers = {"Authorization": "Basic " + str_to_b64str(authpair)} conn = http.client.HTTPConnection(urlNode1.hostname, urlNode1.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert(b'"error":null' in out1) #node2 (third node) is running with standard keep-alive parameters which means keep-alive is on urlNode2 = urllib.parse.urlparse(self.nodes[2].url) authpair = urlNode2.username + ':' + urlNode2.password headers = {"Authorization": "Basic " + str_to_b64str(authpair)} conn = http.client.HTTPConnection(urlNode2.hostname, urlNode2.port) conn.connect() conn.request('POST', '/', '{"method": "getbestblockhash"}', headers) out1 = conn.getresponse().read() assert(b'"error":null' in out1) assert(conn.sock!=None) #connection must be closed because bitcoind should use keep-alive by default # Check excessive request size conn = http.client.HTTPConnection(urlNode2.hostname, urlNode2.port) conn.connect() conn.request('GET', '/' + ('x'*1000), '', headers) out1 = conn.getresponse() assert_equal(out1.status, http.client.NOT_FOUND) conn = http.client.HTTPConnection(urlNode2.hostname, urlNode2.port) conn.connect() conn.request('GET', '/' + ('x'*10000), '', headers) out1 = conn.getresponse() assert_equal(out1.status, http.client.BAD_REQUEST) if __name__ == '__main__': HTTPBasicsTest ().main ()
Reagankm/KnockKnock
refs/heads/master
venv/lib/python3.4/site-packages/numpy/distutils/setup.py
263
#!/usr/bin/env python from __future__ import division, print_function def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('distutils', parent_package, top_path) config.add_subpackage('command') config.add_subpackage('fcompiler') config.add_data_dir('tests') config.add_data_files('site.cfg') config.add_data_files('mingw/gfortran_vs2003_hack.c') config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
MechCoder/sympy
refs/heads/master
sympy/physics/quantum/tests/test_qubit.py
83
import random from sympy import Integer, Matrix, Rational, sqrt, symbols from sympy.core.compatibility import range from sympy.physics.quantum.qubit import (measure_all, measure_partial, matrix_to_qubit, matrix_to_density, qubit_to_matrix, IntQubit, IntQubitBra, QubitBra) from sympy.physics.quantum.gate import (HadamardGate, CNOT, XGate, YGate, ZGate, PhaseGate) from sympy.physics.quantum.qapply import qapply from sympy.physics.quantum.represent import represent from sympy.physics.quantum.shor import Qubit from sympy.utilities.pytest import raises from sympy.physics.quantum.density import Density from sympy.core.trace import Tr x, y = symbols('x,y') epsilon = .000001 def test_Qubit(): array = [0, 0, 1, 1, 0] qb = Qubit('00110') assert qb.flip(0) == Qubit('00111') assert qb.flip(1) == Qubit('00100') assert qb.flip(4) == Qubit('10110') assert qb.qubit_values == (0, 0, 1, 1, 0) assert qb.dimension == 5 for i in range(5): assert qb[i] == array[4 - i] assert len(qb) == 5 qb = Qubit('110') def test_QubitBra(): qb = Qubit(0) qb_bra = QubitBra(0) assert qb.dual_class() == QubitBra assert qb_bra.dual_class() == Qubit qb = Qubit(1, 1, 0) qb_bra = QubitBra(1, 1, 0) assert represent(qb, nqubits=3).H == represent(qb_bra, nqubits=3) qb = Qubit(0, 1) qb_bra = QubitBra(1,0) assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(0) qb_bra = QubitBra(0, 1) assert qb._eval_innerproduct_QubitBra(qb_bra) == Integer(1) def test_IntQubit(): iqb = IntQubit(8) assert iqb.as_int() == 8 assert iqb.qubit_values == (1, 0, 0, 0) iqb = IntQubit(7, 4) assert iqb.qubit_values == (0, 1, 1, 1) assert IntQubit(3) == IntQubit(3, 2) #test Dual Classes iqb = IntQubit(3) iqb_bra = IntQubitBra(3) assert iqb.dual_class() == IntQubitBra assert iqb_bra.dual_class() == IntQubit iqb = IntQubit(5) iqb_bra = IntQubitBra(5) assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(1) iqb = IntQubit(4) iqb_bra = IntQubitBra(5) assert iqb._eval_innerproduct_IntQubitBra(iqb_bra) == Integer(0) raises(ValueError, lambda: IntQubit(4, 1)) def test_superposition_of_states(): state = 1/sqrt(2)*Qubit('01') + 1/sqrt(2)*Qubit('10') state_gate = CNOT(0, 1)*HadamardGate(0)*state state_expanded = Qubit('01')/2 + Qubit('00')/2 - Qubit('11')/2 + Qubit('10')/2 assert qapply(state_gate).expand() == state_expanded assert matrix_to_qubit(represent(state_gate, nqubits=2)) == state_expanded #test apply methods def test_apply_represent_equality(): gates = [HadamardGate(int(3*random.random())), XGate(int(3*random.random())), ZGate(int(3*random.random())), YGate(int(3*random.random())), ZGate(int(3*random.random())), PhaseGate(int(3*random.random()))] circuit = Qubit(int(random.random()*2), int(random.random()*2), int(random.random()*2), int(random.random()*2), int(random.random()*2), int(random.random()*2)) for i in range(int(random.random()*6)): circuit = gates[int(random.random()*6)]*circuit mat = represent(circuit, nqubits=6) states = qapply(circuit) state_rep = matrix_to_qubit(mat) states = states.expand() state_rep = state_rep.expand() assert state_rep == states def test_matrix_to_qubits(): qb = Qubit(0, 0, 0, 0) mat = Matrix([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) assert matrix_to_qubit(mat) == qb assert qubit_to_matrix(qb) == mat state = 2*sqrt(2)*(Qubit(0, 0, 0) + Qubit(0, 0, 1) + Qubit(0, 1, 0) + Qubit(0, 1, 1) + Qubit(1, 0, 0) + Qubit(1, 0, 1) + Qubit(1, 1, 0) + Qubit(1, 1, 1)) ones = sqrt(2)*2*Matrix([1, 1, 1, 1, 1, 1, 1, 1]) assert matrix_to_qubit(ones) == state.expand() assert qubit_to_matrix(state) == ones def test_measure_normalize(): a, b = symbols('a b') state = a*Qubit('110') + b*Qubit('111') assert measure_partial(state, (0,), normalize=False) == \ [(a*Qubit('110'), a*a.conjugate()), (b*Qubit('111'), b*b.conjugate())] assert measure_all(state, normalize=False) == \ [(Qubit('110'), a*a.conjugate()), (Qubit('111'), b*b.conjugate())] def test_measure_partial(): #Basic test of collapse of entangled two qubits (Bell States) state = Qubit('01') + Qubit('10') assert measure_partial(state, (0,)) == \ [(Qubit('10'), Rational(1, 2)), (Qubit('01'), Rational(1, 2))] assert measure_partial(state, (0,)) == \ measure_partial(state, (1,))[::-1] #Test of more complex collapse and probability calculation state1 = sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111') assert measure_partial(state1, (0,)) == \ [(sqrt(2)/sqrt(3)*Qubit('00001') + 1/sqrt(3)*Qubit('11111'), 1)] assert measure_partial(state1, (1, 2)) == measure_partial(state1, (3, 4)) assert measure_partial(state1, (1, 2, 3)) == \ [(Qubit('00001'), Rational(2, 3)), (Qubit('11111'), Rational(1, 3))] #test of measuring multiple bits at once state2 = Qubit('1111') + Qubit('1101') + Qubit('1011') + Qubit('1000') assert measure_partial(state2, (0, 1, 3)) == \ [(Qubit('1000'), Rational(1, 4)), (Qubit('1101'), Rational(1, 4)), (Qubit('1011')/sqrt(2) + Qubit('1111')/sqrt(2), Rational(1, 2))] assert measure_partial(state2, (0,)) == \ [(Qubit('1000'), Rational(1, 4)), (Qubit('1111')/sqrt(3) + Qubit('1101')/sqrt(3) + Qubit('1011')/sqrt(3), Rational(3, 4))] def test_measure_all(): assert measure_all(Qubit('11')) == [(Qubit('11'), 1)] state = Qubit('11') + Qubit('10') assert measure_all(state) == [(Qubit('10'), Rational(1, 2)), (Qubit('11'), Rational(1, 2))] state2 = Qubit('11')/sqrt(5) + 2*Qubit('00')/sqrt(5) assert measure_all(state2) == \ [(Qubit('00'), Rational(4, 5)), (Qubit('11'), Rational(1, 5))] def test_eval_trace(): q1 = Qubit('10110') q2 = Qubit('01010') d = Density([q1, 0.6], [q2, 0.4]) t = Tr(d) assert t.doit() == 1 # extreme bits t = Tr(d, 0) assert t.doit() == (0.4*Density([Qubit('0101'), 1]) + 0.6*Density([Qubit('1011'), 1])) t = Tr(d, 4) assert t.doit() == (0.4*Density([Qubit('1010'), 1]) + 0.6*Density([Qubit('0110'), 1])) # index somewhere in between t = Tr(d, 2) assert t.doit() == (0.4*Density([Qubit('0110'), 1]) + 0.6*Density([Qubit('1010'), 1])) #trace all indices t = Tr(d, [0, 1, 2, 3, 4]) assert t.doit() == 1 # trace some indices, initialized in # non-canonical order t = Tr(d, [2, 1, 3]) assert t.doit() == (0.4*Density([Qubit('00'), 1]) + 0.6*Density([Qubit('10'), 1])) # mixed states q = (1/sqrt(2)) * (Qubit('00') + Qubit('11')) d = Density( [q, 1.0] ) t = Tr(d, 0) assert t.doit() == (0.5*Density([Qubit('0'), 1]) + 0.5*Density([Qubit('1'), 1])) def test_matrix_to_density(): mat = Matrix([[0, 0], [0, 1]]) assert matrix_to_density(mat) == Density([Qubit('1'), 1]) mat = Matrix([[1, 0], [0, 0]]) assert matrix_to_density(mat) == Density([Qubit('0'), 1]) mat = Matrix([[0, 0], [0, 0]]) assert matrix_to_density(mat) == 0 mat = Matrix([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0]]) assert matrix_to_density(mat) == Density([Qubit('10'), 1]) mat = Matrix([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) assert matrix_to_density(mat) == Density([Qubit('00'), 1])
mr-niels-christensen/environment-scotland-dot-rural
refs/heads/master
src/main/rdflib/plugins/parsers/pyMicrodata/microdata.py
7
# -*- coding: utf-8 -*- """ The core of the Microdata->RDF conversion, a more or less verbatim implementation of the U{W3C IG Note<http://www.w3.org/TR/microdata-rdf/>}. Because the implementation was also used to check the note itself, it tries to be fairly close to the text. @organization: U{World Wide Web Consortium<http://www.w3.org>} @author: U{Ivan Herman<a href="http://www.w3.org/People/Ivan/">} @license: This software is available for use under the U{W3C® SOFTWARE NOTICE AND LICENSE<href="http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231">} """ """ $Id: microdata.py,v 1.4 2012/09/05 16:40:43 ivan Exp $ $Date: 2012/09/05 16:40:43 $ Added a reaction on the RDFaStopParsing exception: if raised while setting up the local execution context, parsing is stopped (on the whole subtree) """ import sys if sys.version_info[0] >= 3 : from urllib.parse import urlsplit, urlunsplit else : from urlparse import urlsplit, urlunsplit from types import * import rdflib from rdflib import URIRef from rdflib import Literal from rdflib import BNode from rdflib import Namespace if rdflib.__version__ >= "3.0.0" : from rdflib import Graph from rdflib import RDF as ns_rdf from rdflib import RDFS as ns_rdfs else : from rdflib.Graph import Graph from rdflib.RDFS import RDFSNS as ns_rdfs from rdflib.RDF import RDFNS as ns_rdf ns_owl = Namespace("http://www.w3.org/2002/07/owl#") from .registry import registry, vocab_names from .utils import generate_RDF_collection, get_Literal, get_time_type from .utils import get_lang_from_hierarchy, is_absolute_URI, generate_URI, fragment_escape MD_VOCAB = "http://www.w3.org/ns/md#" RDFA_VOCAB = URIRef("http://www.w3.org/ns/rdfa#usesVocabulary") from . import debug # Existing predicate schemes class PropertySchemes : vocabulary = "vocabulary" contextual = "contextual" class ValueMethod : unordered = "unordered" list = "list" # ---------------------------------------------------------------------------- class Evaluation_Context : """ Evaluation context structure. See Section 4.1 of the U{W3C IG Note<http://www.w3.org/TR/microdata-rdf/>}for the details. @ivar current_type : an absolute URL for the current type, used when an item does not contain an item type @ivar memory: mapping from items to RDF subjects @type memory: dictionary @ivar current_name: an absolute URL for the in-scope name, used for generating URIs for properties of items without an item type @ivar current_vocabulary: an absolute URL for the current vocabulary, from the registry """ def __init__( self ) : self.current_type = None self.memory = {} self.current_name = None self.current_vocabulary = None def get_memory( self, item ) : """ Get the memory content (ie, RDF subject) for 'item', or None if not stored yet @param item: an 'item', in microdata terminology @type item: DOM Element Node @return: None, or an RDF Subject (URIRef or BNode) """ if item in self.memory : return self.memory[item] else : return None def set_memory( self, item, subject ) : """ Set the memory content, ie, the subject, for 'item'. @param item: an 'item', in microdata terminology @type item: DOM Element Node @param subject: RDF Subject @type subject: URIRef or Blank Node """ self.memory[item] = subject def new_copy(self, itype) : """ During the generation algorithm a new copy of the current context has to be done with a new current type. At the moment, the content of memory is copied, ie, a fresh dictionary is created and the content copied over. Not clear whether that is necessary, though, maybe a simple reference is enough... @param itype : an absolute URL for the current type @return: a new evaluation context instance """ retval = Evaluation_Context() for k in self.memory : retval.memory[k] = self.memory[k] retval.current_type = itype retval.current_name = self.current_name retval.current_vocabulary = self.current_vocabulary return retval def __str__(self) : retval = "Evaluation context:\n" retval += " current type: %s\n" % self.current_type retval += " current name: %s\n" % self.current_name retval += " current vocabulary: %s\n" % self.current_vocabulary retval += " memory: %s\n" % self.memory retval += "----\n" return retval class Microdata : """ This class encapsulates methods that are defined by the U{microdata spec<http://dev.w3.org/html5/md/Overview.html>}, as opposed to the RDF conversion note. @ivar document: top of the DOM tree, as returned by the HTML5 parser @ivar base: the base URI of the Dom tree, either set from the outside or via a @base element """ def __init__( self, document, base = None) : """ @param document: top of the DOM tree, as returned by the HTML5 parser @param base: the base URI of the Dom tree, either set from the outside or via a @base element """ self.document = document #----------------------------------------------------------------- # set the document base, will be used to generate top level URIs self.base = None # handle the base element case for HTML for set_base in document.getElementsByTagName("base") : if set_base.hasAttribute("href") : # Yep, there is a local setting for base self.base = set_base.getAttribute("href") return # If got here, ie, if no local setting for base occurs, the input argument has it self.base = base def get_top_level_items( self ) : """ A top level item is and element that has the @itemscope set, but no @itemtype. They have to be collected in pre-order and depth-first fashion. @return: list of items (ie, DOM Nodes) """ def collect_items( node ) : items = [] for child in node.childNodes : if child.nodeType == node.ELEMENT_NODE : items += collect_items( child ) if node.hasAttribute("itemscope") and not node.hasAttribute("itemprop") : # This is also a top level item items.append(node) return items return collect_items( self.document ) def get_item_properties( self, item ) : """ Collect the item's properties, ie, all DOM descendent nodes with @itemprop until the subtree hits another @itemscope. @itemrefs are also added at this point. @param item: current item @type item: DOM Node @return: array of items, ie, DOM Nodes """ # go down the tree until another itemprop is hit, take care of the itemrefs, too; see the microdata doc # probably the ugliest stuff # returns a series of element nodes. # Is it worth filtering the ones with itemprop at that level??? results = [] memory = [ item ] pending = [ child for child in item.childNodes if child.nodeType == item.ELEMENT_NODE ] if item.hasAttribute("itemref") : for id in item.getAttribute("itemref").strip().split() : obj = self.getElementById(id) if obj != None : pending.append(obj) while len(pending) > 0 : current = pending.pop(0) if current in memory : # in general this raises an error; the same item cannot be there twice. In this case this is # simply ignored continue else : # this for the check above memory.append(current) # @itemscope is the barrier... if not current.hasAttribute("itemscope") : pending = [ child for child in current.childNodes if child.nodeType == child.ELEMENT_NODE ] + pending if current.hasAttribute("itemprop") and current.getAttribute("itemprop").strip() != "" : results.append(current) return results def getElementById(self, id) : """This is a method defined for DOM 2 HTML, but the HTML5 parser does not seem to define it. Oh well... @param id: value of an @id attribute to look for @return: array of nodes whose @id attribute matches C{id} (formally, there should be only one...) """ def collect_ids( node ) : ids = [] for child in node.childNodes : if child.nodeType == node.ELEMENT_NODE : ids += collect_ids( child ) if node.hasAttribute("id") and node.getAttribute("id") == id : # This is also a top level item ids.append(node) return ids ids = collect_ids(self.document) if len(ids) > 0 : return ids[0] else : return None class MicrodataConversion(Microdata) : """ Top level class encapsulating the conversion algorithms as described in the W3C note. @ivar graph: an RDF graph; an RDFLib Graph @type graph: RDFLib Graph @ivar document: top of the DOM tree, as returned by the HTML5 parser @ivar ns_md: the Namespace for the microdata vocabulary @ivar base: the base of the Dom tree, either set from the outside or via a @base element """ def __init__( self, document, graph, base = None, vocab_expansion = False, vocab_cache = True ) : """ @param graph: an RDF graph; an RDFLib Graph @type graph: RDFLib Graph @param document: top of the DOM tree, as returned by the HTML5 parser @keyword base: the base of the Dom tree, either set from the outside or via a @base element @keyword vocab_expansion: whether vocab expansion should be performed or not @type vocab_expansion: Boolean @keyword vocab_cache: if vocabulary expansion is done, then perform caching of the vocabulary data @type vocab_cache: Boolean """ Microdata.__init__(self, document, base) self.vocab_expansion = vocab_expansion self.vocab_cache = vocab_cache self.graph = graph self.ns_md = Namespace( MD_VOCAB ) self.graph.bind( "md",MD_VOCAB ) self.vocabularies_used = False # Get the vocabularies defined in the registry bound to proper names, if any... def _use_rdfa_context () : try : from ..pyRdfa.initialcontext import initial_context except : from pyRdfa.initialcontext import initial_context retval = {} vocabs = initial_context["http://www.w3.org/2011/rdfa-context/rdfa-1.1"].ns for prefix in list(vocabs.keys()) : uri = vocabs[prefix] if uri not in vocab_names and uri not in registry : retval[uri] = prefix return retval for vocab in registry : if vocab in vocab_names : self.graph.bind( vocab_names[vocab],vocab ) else : hvocab = vocab + '#' if hvocab in vocab_names : self.graph.bind( vocab_names[hvocab],hvocab ) # Add the prefixes defined in the RDFa initial context to improve the outlook of the output # I put this into a try: except: in case the pyRdfa package is not available... try : try : from ..pyRdfa.initialcontext import initial_context except : from pyRdfa.initialcontext import initial_context vocabs = initial_context["http://www.w3.org/2011/rdfa-context/rdfa-1.1"].ns for prefix in list(vocabs.keys()) : uri = vocabs[prefix] if uri not in registry : # if it is in the registry, then it may have needed some special microdata massage... self.graph.bind( prefix,uri ) except : pass def convert( self ) : """ Top level entry to convert and generate all the triples. It finds the top level items, and generates triples for each of them; additionally, it generates a top level entry point to the items from base in the form of an RDF list. """ item_list = [] for top_level_item in self.get_top_level_items() : item_list.append( self.generate_triples(top_level_item, Evaluation_Context()) ) list = generate_RDF_collection( self.graph, item_list ) self.graph.add( (URIRef(self.base),self.ns_md["item"],list) ) # If the vocab expansion is also switched on, this is the time to do it. # This is the version with my current proposal: the basic expansion is always there; # the follow-your-nose inclusion of vocabulary is optional if self.vocabularies_used : try : try : from ..pyRdfa.rdfs.process import MiniOWL, process_rdfa_sem from ..pyRdfa.options import Options except : from pyRdfa.rdfs.process import MiniOWL, process_rdfa_sem from pyRdfa.options import Options # if we did not get here, the pyRdfa package could not be # imported. Too bad, but life should go on in the except branch... if self.vocab_expansion : # This is the full deal options = Options(vocab_expansion = self.vocab_expansion, vocab_cache = self.vocab_cache) process_rdfa_sem(self.graph, options) else : MiniOWL(self.graph).closure() except : pass def generate_triples( self, item, context ) : """ Generate the triples for a specific item. See the W3C Note for the details. @param item: the DOM Node for the specific item @type item: DOM Node @param context: an instance of an evaluation context @type context: L{Evaluation_Context} @return: a URIRef or a BNode for the (RDF) subject """ # Step 1,2: if the subject has to be set, store it in memory subject = context.get_memory( item ) if subject == None : # nop, there is no subject set. If there is a valid @itemid, that carries it if item.hasAttribute("itemid") and is_absolute_URI( item.getAttribute("itemid") ): subject = URIRef( item.getAttribute("itemid").strip() ) else : subject = BNode() context.set_memory( item, subject ) # Step 3: set the type triples if any types = [] if item.hasAttribute("itemtype") : types = item.getAttribute("itemtype").strip().split() for t in types : if is_absolute_URI( t ) : self.graph.add( (subject, ns_rdf["type"], URIRef(t)) ) # Step 4, 5 and 6 to set the typing variable if len(types) == 0 : itype = None else : if is_absolute_URI(types[0]) : itype = types[0] context.current_name = None elif context.current_type != None : itype = context.current_type else : itype = None # Step 7, 8, 9: Check the registry for possible keys and set the vocab vocab = None if itype != None : for key in list(registry.keys()) : if itype.startswith(key) : # There is a predefined vocabulary for this type... vocab = key # Step 7: Issue an rdfa usesVocabulary triple self.graph.add( (URIRef(self.base), RDFA_VOCAB, URIRef(vocab))) self.vocabularies_used = True break # The registry has not set the vocabulary; has to be extracted from the type if vocab == None : parsed = urlsplit(itype) if parsed.fragment != "" : vocab = urlunsplit( (parsed.scheme,parsed.netloc,parsed.path,parsed.query,"") ) + '#' elif parsed.path == "" and parsed.query == "" : vocab = itype if vocab[-1] != '/' : vocab += '/' else : vocab = itype.rsplit('/',1)[0] + '/' # Step 9: update vocab in the context if vocab != None : context.current_vocabulary = vocab elif item.hasAttribute("itemtype") : context.current_vocabulary = None # Step 10: set up a property list; this will be used to generate triples later. # each entry in the dictionary is an array of RDF objects property_list = {} # Step 11: Get the item properties and run a cycle on those for prop in self.get_item_properties(item) : for name in prop.getAttribute("itemprop").strip().split() : # 11.1.1. set a new context new_context = context.new_copy(itype) # 11.1.2, generate the URI for the property name, that will be the predicate # Also update the context new_context.current_name = predicate = self.generate_predicate_URI( name,new_context ) # 11.1.3, generate the property value. The extra flag signals that the value is a new item # Note that 10.1.4 step is done in the method itself, ie, a recursion may occur there # if a new item is hit (in which case the return value is a RDF resource chaining to a subject) value = self.get_property_value( prop, new_context ) # 11.1.5, store all the values if predicate in property_list : property_list[predicate].append(value) else : property_list[predicate] = [ value ] # step 12: generate the triples for property in list(property_list.keys()) : self.generate_property_values( subject, URIRef(property), property_list[property], context ) # Step 13: return the subject to the caller return subject def generate_predicate_URI( self, name, context ) : """ Generate a full URI for a predicate, using the type, the vocabulary, etc. For details of this entry, see Section 4.4 @param name: name of the property, ie, what appears in @itemprop @param context: an instance of an evaluation context @type context: L{Evaluation_Context} """ if debug: print( "name: %s, %s" % (name,context) ) # Step 1: absolute URI-s are fine, take them as they are if is_absolute_URI(name) : return name # Step 2: if type is none, that this is just used as a fragment # if not context.current_type : if context.current_type == None and context.current_vocabulary == None : if self.base[-1] == '#' : b = self.base[:-1] else : b = self.base return b + '#' + fragment_escape(name) #if context.current_type == None : # return generate_URI( self.base, name ) # Step 3: set the scheme try : if context.current_vocabulary in registry and "propertyURI" in registry[context.current_vocabulary] : scheme = registry[context.current_vocabulary]["propertyURI"] else : scheme = PropertySchemes.vocabulary except : # This is when the structure of the registry is broken scheme = PropertySchemes.vocabulary name = fragment_escape( name ) if scheme == PropertySchemes.contextual : # Step 5.1 s = context.current_name # s = context.current_type if s != None and s.startswith("http://www.w3.org/ns/md?type=") : # Step 5.2 expandedURI = s + '.' + name else : # Step 5.3 expandedURI = "http://www.w3.org/ns/md?type=" + fragment_escape(context.current_type) + "&prop=" + name else : # Step 4 if context.current_vocabulary[-1] == '#' or context.current_vocabulary[-1] == '/' : expandedURI = context.current_vocabulary + name else : expandedURI = context.current_vocabulary + '#' + name # see if there are subproperty/equivalentproperty relations try : vocab_mapping = registry[context.current_vocabulary]["properties"][name] # if we got that far, we may have some mappings expandedURIRef = URIRef(expandedURI) try : subpr = vocab_mapping["subPropertyOf"] if subpr != None : if isinstance(subpr,list) : for p in subpr : self.graph.add( (expandedURIRef, ns_rdfs["subPropertyOf"], URIRef(p)) ) else : self.graph.add( (expandedURIRef, ns_rdfs["subPropertyOf"], URIRef(subpr)) ) except : # Ok, no sub property pass try : subpr = vocab_mapping["equivalentProperty"] if subpr != None : if isinstance(subpr,list) : for p in subpr : self.graph.add( (expandedURIRef, ns_owl["equivalentProperty"], URIRef(p)) ) else : self.graph.add( (expandedURIRef, ns_owl["equivalentProperty"], URIRef(subpr)) ) except : # Ok, no sub property pass except : # no harm done, no extra vocabulary term pass return expandedURI def get_property_value(self, node, context) : """ Generate an RDF object, ie, the value of a property. Note that if this element contains an @itemscope, then a recursive call to L{MicrodataConversion.generate_triples} is done and the return value of that method (ie, the subject for the corresponding item) is return as an object. Otherwise, either URIRefs are created for <a>, <img>, etc, elements, or a Literal; the latter gets a time-related type for the <time> element. @param node: the DOM Node for which the property values should be generated @type node: DOM Node @param context: an instance of an evaluation context @type context: L{Evaluation_Context} @return: an RDF resource (URIRef, BNode, or Literal) """ URI_attrs = { "audio" : "src", "embed" : "src", "iframe" : "src", "img" : "src", "source" : "src", "track" : "src", "video" : "src", "data" : "src", "a" : "href", "area" : "href", "link" : "href", "object" : "data" } lang = get_lang_from_hierarchy( self.document, node ) if node.hasAttribute("itemscope") : # THIS IS A RECURSION ENTRY POINT! return self.generate_triples( node, context ) elif node.tagName in URI_attrs and node.hasAttribute(URI_attrs[node.tagName]) : return URIRef( generate_URI( self.base, node.getAttribute(URI_attrs[node.tagName]).strip() ) ) elif node.tagName == "meta" and node.hasAttribute("content") : if lang : return Literal( node.getAttribute("content"), lang = lang ) else : return Literal( node.getAttribute("content") ) elif node.tagName == "time" and node.hasAttribute("datetime") : litval = node.getAttribute("datetime") dtype = get_time_type(litval) if dtype : return Literal( litval, datatype = dtype ) else : return Literal( litval ) else : if lang : return Literal( get_Literal(node), lang = lang ) else : return Literal( get_Literal(node) ) def generate_property_values( self, subject, predicate, objects, context) : """ Generate the property values for for a specific subject and predicate. The context should specify whether the objects should be added in an RDF list or each triples individually. @param subject: RDF subject @type subject: RDFLib Node (URIRef or blank node) @param predicate: RDF predicate @type predicate: RDFLib URIRef @param objects: RDF objects @type objects: list of RDFLib nodes (URIRefs, Blank Nodes, or literals) @param context: evaluation context @type context: L{Evaluation_Context} """ # generate triples with a list, or a bunch of triples, depending on the context # The biggest complication is to find the method... method = ValueMethod.unordered superproperties = None # This is necessary because predicate is a URIRef, and I am not sure the comparisons would work well # to be tested, in fact... pred_key = "%s" % predicate for key in registry : if predicate.startswith(key) : # This the part of the registry corresponding to the predicate's vocabulary registry_object = registry[key] try : if "multipleValues" in registry_object : method = registry_object["multipleValues"] # The generic definition can be overwritten for a specific property. The simplest is to rely on a 'try' # with the right structure... try : method = registry_object["properties"][pred_key[len(key):]]["multipleValues"] except : pass except : pass if method == ValueMethod.unordered : for object in objects : self.graph.add( (subject, predicate, object) ) else : self.graph.add( (subject,predicate,generate_RDF_collection( self.graph, objects )) )
tjma12/pycbc
refs/heads/master
test/test_skymax.py
3
import copy import unittest import random import os from numpy import complex128, real, sqrt, sin, cos, angle, ceil, log from numpy import zeros, argmax, array from pycbc import DYN_RANGE_FAC from pycbc.waveform import get_td_waveform, get_fd_waveform, td_approximants, fd_approximants from pycbc.pnutils import nearest_larger_binary_number from pycbc.types import FrequencySeries, TimeSeries, complex_same_precision_as from pycbc.types import load_frequencyseries from pycbc.filter import sigmasq, overlap_cplx, matched_filter_core from pycbc.filter import compute_max_snr_over_sky_loc_stat from pycbc.filter import compute_max_snr_over_sky_loc_stat_no_phase from pycbc.filter import compute_u_val_for_sky_loc_stat_no_phase from pycbc.filter import compute_u_val_for_sky_loc_stat from pycbc import psd from pycbc import vetoes from utils import parse_args_all_schemes, simple_exit _scheme, _context = parse_args_all_schemes("correlate") expected_results = {} for idx in range(4): expected_results[idx] = {} for jdx in range(4): expected_results[idx][jdx] = {} expected_results[0][0]['Ip_snr'] = 100.0 expected_results[0][0]['Ip_angle'] = -1.88619488652e-18 expected_results[0][0]['Ip_argmax'] = 0 expected_results[0][0]['Ic_snr'] = 98.7349100759 expected_results[0][0]['Ic_angle'] = 1.60960753393 expected_results[0][0]['Ic_argmax'] = 3 expected_results[0][1]['Ip_snr'] = 96.3390579783 expected_results[0][1]['Ip_angle'] = 0.511744420131 expected_results[0][1]['Ip_argmax'] = 1387 expected_results[0][1]['Ic_snr'] = 96.3390579783 expected_results[0][1]['Ic_angle'] = 2.08254074693 expected_results[0][1]['Ic_argmax'] = 1387 expected_results[0][2]['Ip_snr'] = 98.8434423546 expected_results[0][2]['Ip_angle'] = 0.566451407787 expected_results[0][2]['Ip_argmax'] = 1100 expected_results[0][2]['Ic_snr'] = 98.8485523538 expected_results[0][2]['Ic_angle'] = 2.10418718318 expected_results[0][2]['Ic_argmax'] = 1099 expected_results[0][3]['Ip_snr'] = 96.4239530554 expected_results[0][3]['Ip_angle'] = -0.946889162447 expected_results[0][3]['Ip_argmax'] = 1447 expected_results[0][3]['Ic_snr'] = 95.6528566731 expected_results[0][3]['Ic_angle'] = 1.10466400896 expected_results[0][3]['Ic_argmax'] = 1484 expected_results[1][0]['Ip_snr'] = 96.3390579783 expected_results[1][0]['Ip_angle'] = -0.511744420131 expected_results[1][0]['Ip_argmax'] = 260757 expected_results[1][0]['Ic_snr'] = 94.4282712604 expected_results[1][0]['Ic_angle'] = 0.957548192904 expected_results[1][0]['Ic_argmax'] = 260753 expected_results[1][1]['Ip_snr'] = 100.0 expected_results[1][1]['Ip_angle'] = -1.73241699772e-18 expected_results[1][1]['Ip_argmax'] = 0 expected_results[1][1]['Ic_snr'] = 100.0 expected_results[1][1]['Ic_angle'] = 1.57079632679 expected_results[1][1]['Ic_argmax'] = 0 expected_results[1][2]['Ip_snr'] = 97.6397283701 expected_results[1][2]['Ip_angle'] = 0.156578884423 expected_results[1][2]['Ip_argmax'] = 261862 expected_results[1][2]['Ic_snr'] = 97.7584101045 expected_results[1][2]['Ic_angle'] = 1.69481552225 expected_results[1][2]['Ic_argmax'] = 261861 expected_results[1][3]['Ip_snr'] = 99.4434573331 expected_results[1][3]['Ip_angle'] = -1.50330148916 expected_results[1][3]['Ip_argmax'] = 58 expected_results[1][3]['Ic_snr'] = 98.0771994342 expected_results[1][3]['Ic_angle'] = 0.521399663782 expected_results[1][3]['Ic_argmax'] = 94 expected_results[2][0]['Ip_snr'] = 98.8434423546 expected_results[2][0]['Ip_angle'] = -0.566451407787 expected_results[2][0]['Ip_argmax'] = 261044 expected_results[2][0]['Ic_snr'] = 96.8727372348 expected_results[2][0]['Ic_angle'] = 0.921151545297 expected_results[2][0]['Ic_argmax'] = 261041 expected_results[2][1]['Ip_snr'] = 97.6397283701 expected_results[2][1]['Ip_angle'] = -0.156578884423 expected_results[2][1]['Ip_argmax'] = 282 expected_results[2][1]['Ic_snr'] = 97.6397283701 expected_results[2][1]['Ic_angle'] = 1.41421744237 expected_results[2][1]['Ic_argmax'] = 282 expected_results[2][2]['Ip_snr'] = 100.0 expected_results[2][2]['Ip_angle'] = 2.41820532326e-18 expected_results[2][2]['Ip_argmax'] = 0 expected_results[2][2]['Ic_snr'] = 99.988543227 expected_results[2][2]['Ic_angle'] = 1.5377922043 expected_results[2][2]['Ic_argmax'] = 262143 expected_results[2][3]['Ip_snr'] = 97.3725007917 expected_results[2][3]['Ip_angle'] = -1.61086911817 expected_results[2][3]['Ip_argmax'] = 342 expected_results[2][3]['Ic_snr'] = 96.2035744912 expected_results[2][3]['Ic_angle'] = 0.442670138337 expected_results[2][3]['Ic_argmax'] = 379 expected_results[3][0]['Ip_snr'] = 96.4239530554 expected_results[3][0]['Ip_angle'] = 0.946889162447 expected_results[3][0]['Ip_argmax'] = 260697 expected_results[3][0]['Ic_snr'] = 94.4958639934 expected_results[3][0]['Ic_angle'] = 2.41579357775 expected_results[3][0]['Ic_argmax'] = 260693 expected_results[3][1]['Ip_snr'] = 99.4434573331 expected_results[3][1]['Ip_angle'] = 1.50330148916 expected_results[3][1]['Ip_argmax'] = 262086 expected_results[3][1]['Ic_snr'] = 99.4434573331 expected_results[3][1]['Ic_angle'] = 3.07409781595 expected_results[3][1]['Ic_argmax'] = 262086 expected_results[3][2]['Ip_snr'] = 97.3725007917 expected_results[3][2]['Ip_angle'] = 1.61086911817 expected_results[3][2]['Ip_argmax'] = 261802 expected_results[3][2]['Ic_snr'] = 97.3906866656 expected_results[3][2]['Ic_angle'] = -3.11216854627 expected_results[3][2]['Ic_argmax'] = 261802 expected_results[3][3]['Ip_snr'] = 100.0 expected_results[3][3]['Ip_angle'] = 9.03608368726e-19 expected_results[3][3]['Ip_argmax'] = 0 expected_results[3][3]['Ic_snr'] = 99.4335056063 expected_results[3][3]['Ic_angle'] = 2.02876392072 expected_results[3][3]['Ic_argmax'] = 36 def generate_detector_strain(template_params, h_plus, h_cross): polarization = 0 if hasattr(template_params, 'polarization'): polarization = template_params.polarization f_plus = cos(polarization) f_cross = sin(polarization) return h_plus * f_plus + h_cross * f_cross def make_padded_frequency_series(vec, filter_N=None, delta_f=None): """Convert vec (TimeSeries or FrequencySeries) to a FrequencySeries. If filter_N and/or delta_f are given, the output will take those values. If not told otherwise the code will attempt to pad a timeseries first such that the waveform will not wraparound. However, if delta_f is specified to be shorter than the waveform length then wraparound *will* be allowed. """ if filter_N is None: power = ceil(log(len(vec), 2)) + 1 N = 2 ** power else: N = filter_N n = N / 2 + 1 if isinstance(vec, FrequencySeries): vectilde = FrequencySeries(zeros(n, dtype=complex_same_precision_as(vec)), delta_f=1.0, copy=False) if len(vectilde) < len(vec): cplen = len(vectilde) else: cplen = len(vec) vectilde[0:cplen] = vec[0:cplen] delta_f = vec.delta_f elif isinstance(vec, TimeSeries): # First determine if the timeseries is too short for the specified df # and increase if necessary curr_length = len(vec) new_length = int(nearest_larger_binary_number(curr_length)) while new_length * vec.delta_t < 1./delta_f: new_length = new_length * 2 vec.resize(new_length) # Then convert to frequencyseries v_tilde = vec.to_frequencyseries() # Then convert frequencyseries to required length and spacing by keeping # only every nth sample if delta_f needs increasing, and cutting at # Nyquist if the max frequency is too high. # NOTE: This assumes that the input and output data is using binary # lengths. i_delta_f = v_tilde.get_delta_f() v_tilde = v_tilde.numpy() df_ratio = int(delta_f / i_delta_f) n_freq_len = int((n-1) * df_ratio +1) assert(n <= len(v_tilde)) df_ratio = int(delta_f / i_delta_f) v_tilde = v_tilde[:n_freq_len:df_ratio] vectilde = FrequencySeries(v_tilde, delta_f=delta_f, dtype=complex128) return FrequencySeries(vectilde * DYN_RANGE_FAC, delta_f=delta_f, dtype=complex128) def get_waveform(wf_params, start_frequency, sample_rate, length, filter_rate, sky_max_template=False): delta_f = filter_rate / float(length) if wf_params.approximant in fd_approximants(): hp, hc = get_fd_waveform(wf_params, delta_f=delta_f, f_lower=start_frequency) elif wf_params.approximant in td_approximants(): hp, hc = get_td_waveform(wf_params, delta_t=1./sample_rate, f_lower=start_frequency) if not sky_max_template: hvec = generate_detector_strain(wf_params, hp, hc) return make_padded_frequency_series(hvec, length, delta_f=delta_f) else: return make_padded_frequency_series(hp, length, delta_f=delta_f), \ make_padded_frequency_series(hc, length, delta_f=delta_f) class DummyClass(object): pass class TestChisq(unittest.TestCase): def setUp(self, *args): # Where are my data files? if os.path.isfile('test/data/ZERO_DET_high_P.txt'): self.dataDir = 'test/data/' elif os.path.isfile('data/ZERO_DET_high_P.txt'): self.dataDir = 'data/' else: self.assertTrue(False, msg="Cannot find data files!") self.context = _context self.scheme = _scheme self.tolerance = 1e-6 self.filter_t_length = 16 self.low_freq_filter = 30. self.sample_rate = 16384 self.filter_N = self.filter_t_length * self.sample_rate self.filter_n = self.filter_N / 2 + 1 self.filter_delta_f = 1.0 / self.filter_t_length self.psd = psd.from_string('aLIGOZeroDetHighPowerGWINC', self.filter_n, self.filter_delta_f, self.low_freq_filter) self.psd *= DYN_RANGE_FAC*DYN_RANGE_FAC wps1 = DummyClass() wps1.mass1 = 123.7627 wps1.mass2 = 72.55471 wps1.inclination = 1.125029 wps1.coa_phase = 2.906049 wps1.approximant='EOBNRv2HM' self.wps1 = wps1 wps2 = DummyClass() wps2.mass1 = 131.460647583 wps2.mass2 = 69.0030059814 wps2.inclination = 0.8432287 wps2.coa_phase = 0.2 wps2.approximant = 'SEOBNRv4_ROM' self.wps2 = wps2 wps3 = copy.deepcopy(wps2) wps3.approximant = 'EOBNRv2HM_ROM' self.wps3 = wps3 wps4 = copy.deepcopy(wps2) wps4.spin1x = 0.8 wps4.spin2y = -0.9 wps4.approximant = 'IMRPhenomPv2' self.wps4 = wps4 self.wps_list = [wps1, wps2, wps3, wps4] self.sm_power_chisq = vetoes.SingleDetSkyMaxPowerChisq(num_bins='1') self.sm_power_chisq2 = vetoes.SingleDetSkyMaxPowerChisq(num_bins='10') self.power_chisq = vetoes.SingleDetPowerChisq(num_bins='1') self.power_chisq2 = vetoes.SingleDetPowerChisq(num_bins='10') def test_filtering(self): idx = self.idx jdx = self.jdx #w1 = self.wps_list[idx] #w2 = self.wps_list[jdx] #stilde = get_waveform(w1, self.low_freq_filter-1, # self.sample_rate, self.filter_N, # self.sample_rate) #try: # stilde.save('data/skymaxtest_stilde_%d.hdf' % idx) #except: # pass stilde = load_frequencyseries(self.dataDir + \ 'skymaxtest_stilde_%d.hdf' % idx) s_norm = sigmasq(stilde, psd=self.psd, low_frequency_cutoff=self.low_freq_filter) stilde /= sqrt(float(s_norm)) stilde *= 100 #hplus, hcross = get_waveform(w2, self.low_freq_filter-1, # self.sample_rate, self.filter_N, # self.sample_rate, sky_max_template=True) #try: # hplus.save('data/skymaxtest_hplus_%d.hdf' % jdx) # hcross.save('data/skymaxtest_hcross_%d.hdf' % jdx) #except: # pass hplus = load_frequencyseries(self.dataDir + \ 'skymaxtest_hplus_%d.hdf' % jdx) hcross = load_frequencyseries(self.dataDir + \ 'skymaxtest_hcross_%d.hdf' % jdx) hplus.f_lower = self.low_freq_filter hplus.params = random.randint(0,100000000000) hcross.f_lower = self.low_freq_filter hcross.params = random.randint(0,100000000000) hp_norm = sigmasq(hplus, psd=self.psd, low_frequency_cutoff=self.low_freq_filter) hc_norm = sigmasq(hcross, psd=self.psd, low_frequency_cutoff=self.low_freq_filter) hplus /= sqrt(float(hp_norm)) hcross /= sqrt(float(hc_norm)) hpc_corr = overlap_cplx(hplus, hcross, psd=self.psd, low_frequency_cutoff=self.low_freq_filter, normalized=False) hpc_corr_R = real(hpc_corr) I_plus, corr_plus, n_plus = matched_filter_core\ (hplus, stilde, psd=self.psd, low_frequency_cutoff=self.low_freq_filter, h_norm=1.) # FIXME: Remove the deepcopies before merging with master I_plus = copy.deepcopy(I_plus) corr_plus = copy.deepcopy(corr_plus) I_cross, corr_cross, n_cross = matched_filter_core\ (hcross, stilde, psd=self.psd, low_frequency_cutoff=self.low_freq_filter, h_norm=1.) I_cross = copy.deepcopy(I_cross) corr_cross = copy.deepcopy(corr_cross) I_plus = I_plus * n_plus I_cross = I_cross * n_cross IPM = abs(I_plus.data).argmax() ICM = abs(I_cross.data).argmax() self.assertAlmostEqual(abs(I_plus[IPM]), expected_results[idx][jdx]['Ip_snr']) self.assertAlmostEqual(angle(I_plus[IPM]), expected_results[idx][jdx]['Ip_angle']) self.assertEqual(IPM, expected_results[idx][jdx]['Ip_argmax']) self.assertAlmostEqual(abs(I_cross[ICM]), expected_results[idx][jdx]['Ic_snr']) self.assertAlmostEqual(angle(I_cross[ICM]), expected_results[idx][jdx]['Ic_angle']) self.assertEqual(ICM, expected_results[idx][jdx]['Ic_argmax']) #print "expected_results[{}][{}]['Ip_snr'] = {}" .format(idx,jdx,abs(I_plus[IPM])) #print "expected_results[{}][{}]['Ip_angle'] = {}".format(idx,jdx,angle(I_plus[IPM])) #print "expected_results[{}][{}]['Ip_argmax'] = {}".format(idx,jdx, IPM) #print "expected_results[{}][{}]['Ic_snr'] = {}" .format(idx,jdx,abs(I_cross[ICM])) #print "expected_results[{}][{}]['Ic_angle'] = {}".format(idx,jdx,angle(I_cross[ICM])) #print "expected_results[{}][{}]['Ic_argmax'] = {}".format(idx,jdx, ICM) det_stat_prec = compute_max_snr_over_sky_loc_stat\ (I_plus, I_cross, hpc_corr_R, hpnorm=1., hcnorm=1., thresh=0.1, analyse_slice=slice(0,len(I_plus.data))) det_stat_hom = compute_max_snr_over_sky_loc_stat_no_phase\ (I_plus, I_cross, hpc_corr_R, hpnorm=1., hcnorm=1., thresh=0.1, analyse_slice=slice(0,len(I_plus.data))) idx_max_prec = argmax(det_stat_prec.data) idx_max_hom = argmax(det_stat_hom.data) max_ds_prec = det_stat_prec[idx_max_prec] max_ds_hom = det_stat_hom[idx_max_hom] uvals_prec, _ = compute_u_val_for_sky_loc_stat\ (I_plus.data, I_cross.data, hpc_corr_R, indices=[idx_max_prec], hpnorm=1., hcnorm=1.) uvals_hom, _ = compute_u_val_for_sky_loc_stat_no_phase\ (I_plus.data, I_cross.data, hpc_corr_R, indices=[idx_max_hom], hpnorm=1., hcnorm=1.) ht = hplus * uvals_hom[0] + hcross ht_norm = sigmasq(ht, psd=self.psd, low_frequency_cutoff=self.low_freq_filter) ht /= sqrt(float(ht_norm)) ht.f_lower = self.low_freq_filter ht.params = random.randint(0,100000000000) I_t, corr_t, n_t = matched_filter_core\ (ht, stilde, psd=self.psd, low_frequency_cutoff=self.low_freq_filter, h_norm=1.) I_t = I_t * n_t self.assertAlmostEqual(abs(real(I_t.data[idx_max_hom])), max_ds_hom) self.assertEqual(abs(real(I_t.data[idx_max_hom])), max(abs(real(I_t.data)))) chisq, _ = self.power_chisq.values\ (corr_t, array([max_ds_hom]) / n_plus, n_t, self.psd, array([idx_max_hom]), ht) ht = hplus * uvals_prec[0] + hcross ht_norm = sigmasq(ht, psd=self.psd, low_frequency_cutoff=self.low_freq_filter) ht /= sqrt(float(ht_norm)) ht.f_lower = self.low_freq_filter ht.params = random.randint(0,100000000000) I_t, corr_t, n_t = matched_filter_core\ (ht, stilde, psd=self.psd, low_frequency_cutoff=self.low_freq_filter, h_norm=1.) I_t = I_t * n_t chisq, _ = self.power_chisq.values\ (corr_t, array([max_ds_prec]) / n_plus, n_t, self.psd, array([idx_max_prec]), ht) self.assertAlmostEqual(abs(I_t.data[idx_max_prec]), max_ds_prec) self.assertEqual(idx_max_prec, abs(I_t.data).argmax()) self.assertTrue(chisq < 1E-4) def test_maker(class_name, idx, jdx): class Test(class_name): idx = idx jdx = jdx Test.__name__ = "Test %s" % '_'.join([str(idx),str(jdx)]) return Test suite = unittest.TestSuite() for idx in range(4): for jdx in range(4): curr_cls = test_maker(TestChisq, idx, jdx) suite.addTest(unittest.TestLoader().loadTestsFromTestCase(curr_cls)) if __name__ == '__main__': results = unittest.TextTestRunner(verbosity=2).run(suite) simple_exit(results)
v-iam/azure-sdk-for-python
refs/heads/master
azure-mgmt-network/azure/mgmt/network/v2016_09_01/models/express_route_circuit_paged.py
11
# 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 msrest.paging import Paged class ExpressRouteCircuitPaged(Paged): """ A paging container for iterating over a list of ExpressRouteCircuit object """ _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, 'current_page': {'key': 'value', 'type': '[ExpressRouteCircuit]'} } def __init__(self, *args, **kwargs): super(ExpressRouteCircuitPaged, self).__init__(*args, **kwargs)
kevinlondon/youtube-dl
refs/heads/master
youtube_dl/extractor/cbs.py
93
from __future__ import unicode_literals from .common import InfoExtractor class CBSIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?(?:cbs\.com/shows/[^/]+/(?:video|artist)|colbertlateshow\.com/(?:video|podcasts))/[^/]+/(?P<id>[^/]+)' _TESTS = [{ 'url': 'http://www.cbs.com/shows/garth-brooks/video/_u7W953k6la293J7EPTd9oHkSPs6Xn6_/connect-chat-feat-garth-brooks/', 'info_dict': { 'id': '4JUVEwq3wUT7', 'display_id': 'connect-chat-feat-garth-brooks', 'ext': 'flv', 'title': 'Connect Chat feat. Garth Brooks', 'description': 'Connect with country music singer Garth Brooks, as he chats with fans on Wednesday November 27, 2013. Be sure to tune in to Garth Brooks: Live from Las Vegas, Friday November 29, at 9/8c on CBS!', 'duration': 1495, }, 'params': { # rtmp download 'skip_download': True, }, '_skip': 'Blocked outside the US', }, { 'url': 'http://www.cbs.com/shows/liveonletterman/artist/221752/st-vincent/', 'info_dict': { 'id': 'WWF_5KqY3PK1', 'display_id': 'st-vincent', 'ext': 'flv', 'title': 'Live on Letterman - St. Vincent', 'description': 'Live On Letterman: St. Vincent in concert from New York\'s Ed Sullivan Theater on Tuesday, July 16, 2014.', 'duration': 3221, }, 'params': { # rtmp download 'skip_download': True, }, '_skip': 'Blocked outside the US', }, { 'url': 'http://colbertlateshow.com/video/8GmB0oY0McANFvp2aEffk9jZZZ2YyXxy/the-colbeard/', 'only_matching': True, }, { 'url': 'http://www.colbertlateshow.com/podcasts/dYSwjqPs_X1tvbV_P2FcPWRa_qT6akTC/in-the-bad-room-with-stephen/', 'only_matching': True, }] def _real_extract(self, url): display_id = self._match_id(url) webpage = self._download_webpage(url, display_id) real_id = self._search_regex( [r"video\.settings\.pid\s*=\s*'([^']+)';", r"cbsplayer\.pid\s*=\s*'([^']+)';"], webpage, 'real video ID') return { '_type': 'url_transparent', 'ie_key': 'ThePlatform', 'url': 'theplatform:%s' % real_id, 'display_id': display_id, }
spiegela/elasticsearch
refs/heads/master
docs/src/test/cluster/config/scripts/my_script.py
46
doc["num"].value * factor
sadleader/odoo
refs/heads/master
addons/anonymization/anonymization.py
95
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU 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/>. # ############################################################################## from lxml import etree import os import base64 try: import cPickle as pickle except ImportError: import pickle import random import datetime from openerp.osv import fields, osv from openerp.tools.translate import _ from itertools import groupby from operator import itemgetter FIELD_STATES = [('clear', 'Clear'), ('anonymized', 'Anonymized'), ('not_existing', 'Not Existing'), ('new', 'New')] ANONYMIZATION_STATES = FIELD_STATES + [('unstable', 'Unstable')] WIZARD_ANONYMIZATION_STATES = [('clear', 'Clear'), ('anonymized', 'Anonymized'), ('unstable', 'Unstable')] ANONYMIZATION_HISTORY_STATE = [('started', 'Started'), ('done', 'Done'), ('in_exception', 'Exception occured')] ANONYMIZATION_DIRECTION = [('clear -> anonymized', 'clear -> anonymized'), ('anonymized -> clear', 'anonymized -> clear')] def group(lst, cols): if isinstance(cols, basestring): cols = [cols] return dict((k, [v for v in itr]) for k, itr in groupby(sorted(lst, key=itemgetter(*cols)), itemgetter(*cols))) class ir_model_fields_anonymization(osv.osv): _name = 'ir.model.fields.anonymization' _rec_name = 'field_id' _columns = { 'model_name': fields.char('Object Name', required=True), 'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'), 'field_name': fields.char('Field Name', required=True), 'field_id': fields.many2one('ir.model.fields', 'Field', ondelete='set null'), 'state': fields.selection(selection=FIELD_STATES, String='Status', required=True, readonly=True), } _sql_constraints = [ ('model_id_field_id_uniq', 'unique (model_name, field_name)', _("You cannot have two fields with the same name on the same object!")), ] def _get_global_state(self, cr, uid, context=None): ids = self.search(cr, uid, [('state', '<>', 'not_existing')], context=context) fields = self.browse(cr, uid, ids, context=context) if not len(fields) or len(fields) == len([f for f in fields if f.state == 'clear']): state = 'clear' # all fields are clear elif len(fields) == len([f for f in fields if f.state == 'anonymized']): state = 'anonymized' # all fields are anonymized else: state = 'unstable' # fields are mixed: this should be fixed return state def _check_write(self, cr, uid, context=None): """check that the field is created from the menu and not from an database update otherwise the database update can crash:""" if context is None: context = {} if context.get('manual'): global_state = self._get_global_state(cr, uid, context=context) if global_state == 'anonymized': raise osv.except_osv('Error!', "The database is currently anonymized, you cannot create, modify or delete fields.") elif global_state == 'unstable': msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to create, write or delete fields.") raise osv.except_osv('Error!', msg) return True def _get_model_and_field_ids(self, cr, uid, vals, context=None): model_and_field_ids = (False, False) if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']: ir_model_fields_obj = self.pool.get('ir.model.fields') ir_model_obj = self.pool.get('ir.model') model_ids = ir_model_obj.search(cr, uid, [('model', '=', vals['model_name'])], context=context) if model_ids: field_ids = ir_model_fields_obj.search(cr, uid, [('name', '=', vals['field_name']), ('model_id', '=', model_ids[0])], context=context) if field_ids: field_id = field_ids[0] model_and_field_ids = (model_ids[0], field_id) return model_and_field_ids def create(self, cr, uid, vals, context=None): # check field state: all should be clear before we can add a new field to anonymize: self._check_write(cr, uid, context=context) global_state = self._get_global_state(cr, uid, context=context) if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']: vals['model_id'], vals['field_id'] = self._get_model_and_field_ids(cr, uid, vals, context=context) # check not existing fields: if not vals.get('field_id'): vals['state'] = 'not_existing' else: vals['state'] = global_state res = super(ir_model_fields_anonymization, self).create(cr, uid, vals, context=context) return res def write(self, cr, uid, ids, vals, context=None): # check field state: all should be clear before we can modify a field: if not (len(vals.keys()) == 1 and vals.get('state') == 'clear'): self._check_write(cr, uid, context=context) if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']: vals['model_id'], vals['field_id'] = self._get_model_and_field_ids(cr, uid, vals, context=context) # check not existing fields: if 'field_id' in vals: if not vals.get('field_id'): vals['state'] = 'not_existing' else: global_state = self._get_global_state(cr, uid, context) if global_state != 'unstable': vals['state'] = global_state res = super(ir_model_fields_anonymization, self).write(cr, uid, ids, vals, context=context) return res def unlink(self, cr, uid, ids, context=None): # check field state: all should be clear before we can unlink a field: self._check_write(cr, uid, context=context) res = super(ir_model_fields_anonymization, self).unlink(cr, uid, ids, context=context) return res def onchange_model_id(self, cr, uid, ids, model_id, context=None): res = {'value': { 'field_name': False, 'field_id': False, 'model_name': False, }} if model_id: ir_model_obj = self.pool.get('ir.model') model_ids = ir_model_obj.search(cr, uid, [('id', '=', model_id)]) model_id = model_ids and model_ids[0] or None model_name = model_id and ir_model_obj.browse(cr, uid, model_id).model or False res['value']['model_name'] = model_name return res def onchange_model_name(self, cr, uid, ids, model_name, context=None): res = {'value': { 'field_name': False, 'field_id': False, 'model_id': False, }} if model_name: ir_model_obj = self.pool.get('ir.model') model_ids = ir_model_obj.search(cr, uid, [('model', '=', model_name)]) model_id = model_ids and model_ids[0] or False res['value']['model_id'] = model_id return res def onchange_field_name(self, cr, uid, ids, field_name, model_name): res = {'value': { 'field_id': False, }} if field_name and model_name: ir_model_fields_obj = self.pool.get('ir.model.fields') field_ids = ir_model_fields_obj.search(cr, uid, [('name', '=', field_name), ('model', '=', model_name)]) field_id = field_ids and field_ids[0] or False res['value']['field_id'] = field_id return res def onchange_field_id(self, cr, uid, ids, field_id, model_name): res = {'value': { 'field_name': False, }} if field_id: ir_model_fields_obj = self.pool.get('ir.model.fields') field = ir_model_fields_obj.browse(cr, uid, field_id) res['value']['field_name'] = field.name return res _defaults = { 'state': lambda *a: 'clear', } class ir_model_fields_anonymization_history(osv.osv): _name = 'ir.model.fields.anonymization.history' _order = "date desc" _columns = { 'date': fields.datetime('Date', required=True, readonly=True), 'field_ids': fields.many2many('ir.model.fields.anonymization', 'anonymized_field_to_history_rel', 'field_id', 'history_id', 'Fields', readonly=True), 'state': fields.selection(selection=ANONYMIZATION_HISTORY_STATE, string='Status', required=True, readonly=True), 'direction': fields.selection(selection=ANONYMIZATION_DIRECTION, string='Direction', size=20, required=True, readonly=True), 'msg': fields.text('Message', readonly=True), 'filepath': fields.char(string='File path', readonly=True), } class ir_model_fields_anonymize_wizard(osv.osv_memory): _name = 'ir.model.fields.anonymize.wizard' def _get_state(self, cr, uid, ids, name, arg, context=None): res = {} state = self._get_state_value(cr, uid, context=None) for id in ids: res[id] = state return res def _get_summary(self, cr, uid, ids, name, arg, context=None): res = {} summary = self._get_summary_value(cr, uid, context) for id in ids: res[id] = summary return res _columns = { 'name': fields.char(string='File Name'), 'summary': fields.function(_get_summary, type='text', string='Summary'), 'file_export': fields.binary(string='Export'), 'file_import': fields.binary(string='Import', help="This is the file created by the anonymization process. It should have the '.pickle' extention."), 'state': fields.function(_get_state, string='Status', type='selection', selection=WIZARD_ANONYMIZATION_STATES, readonly=False), 'msg': fields.text(string='Message'), } def _get_state_value(self, cr, uid, context=None): state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context) return state def _get_summary_value(self, cr, uid, context=None): summary = u'' anon_field_obj = self.pool.get('ir.model.fields.anonymization') ir_model_fields_obj = self.pool.get('ir.model.fields') anon_field_ids = anon_field_obj.search(cr, uid, [('state', '<>', 'not_existing')], context=context) anon_fields = anon_field_obj.browse(cr, uid, anon_field_ids, context=context) field_ids = [anon_field.field_id.id for anon_field in anon_fields if anon_field.field_id] fields = ir_model_fields_obj.browse(cr, uid, field_ids, context=context) fields_by_id = dict([(f.id, f) for f in fields]) for anon_field in anon_fields: field = fields_by_id.get(anon_field.field_id.id) values = { 'model_name': field.model_id.name, 'model_code': field.model_id.model, 'field_code': field.name, 'field_name': field.field_description, 'state': anon_field.state, } summary += u" * %(model_name)s (%(model_code)s) -> %(field_name)s (%(field_code)s): state: (%(state)s)\n" % values return summary def default_get(self, cr, uid, fields_list, context=None): res = {} res['name'] = '.pickle' res['summary'] = self._get_summary_value(cr, uid, context) res['state'] = self._get_state_value(cr, uid, context) res['msg'] = _("""Before executing the anonymization process, you should make a backup of your database.""") return res def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, *args, **kwargs): state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context) if context is None: context = {} step = context.get('step', 'new_window') res = super(ir_model_fields_anonymize_wizard, self).fields_view_get(cr, uid, view_id, view_type, context, *args, **kwargs) eview = etree.fromstring(res['arch']) placeholder = eview.xpath("group[@name='placeholder1']") if len(placeholder): placeholder = placeholder[0] if step == 'new_window' and state == 'clear': # clicked in the menu and the fields are not anonymized: warn the admin that backuping the db is very important placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'})) placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('label', {'string': 'Warning'})) eview.remove(placeholder) elif step == 'new_window' and state == 'anonymized': # clicked in the menu and the fields are already anonymized placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('field', {'name': 'file_import', 'required': "1"})) placeholder.addnext(etree.Element('label', {'string': 'Anonymization file'})) eview.remove(placeholder) elif step == 'just_anonymized': # we just ran the anonymization process, we need the file export field placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('field', {'name': 'file_export'})) # we need to remove the button: buttons = eview.xpath("button") for button in buttons: eview.remove(button) # and add a message: placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'})) placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('label', {'string': 'Result'})) # remove the placeholer: eview.remove(placeholder) elif step == 'just_desanonymized': # we just reversed the anonymization process, we don't need any field # we need to remove the button buttons = eview.xpath("button") for button in buttons: eview.remove(button) # and add a message # and add a message: placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'})) placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('label', {'string': 'Result'})) # remove the placeholer: eview.remove(placeholder) else: msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to do anything else.") raise osv.except_osv('Error!', msg) res['arch'] = etree.tostring(eview) return res def _raise_after_history_update(self, cr, uid, history_id, error_type, error_msg): self.pool.get('ir.model.fields.anonymization.history').write(cr, uid, history_id, { 'state': 'in_exception', 'msg': error_msg, }) raise osv.except_osv(error_type, error_msg) def anonymize_database(self, cr, uid, ids, context=None): """Sets the 'anonymized' state to defined fields""" # create a new history record: anonymization_history_model = self.pool.get('ir.model.fields.anonymization.history') vals = { 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'state': 'started', 'direction': 'clear -> anonymized', } history_id = anonymization_history_model.create(cr, uid, vals) # check that all the defined fields are in the 'clear' state state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context) if state == 'anonymized': self._raise_after_history_update(cr, uid, history_id, _('Error !'), _("The database is currently anonymized, you cannot anonymize it again.")) elif state == 'unstable': msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to do anything.") self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) # do the anonymization: dirpath = os.environ.get('HOME') or os.getcwd() rel_filepath = 'field_anonymization_%s_%s.pickle' % (cr.dbname, history_id) abs_filepath = os.path.abspath(os.path.join(dirpath, rel_filepath)) ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization') field_ids = ir_model_fields_anonymization_model.search(cr, uid, [('state', '<>', 'not_existing')], context=context) fields = ir_model_fields_anonymization_model.browse(cr, uid, field_ids, context=context) if not fields: msg = "No fields are going to be anonymized." self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) data = [] for field in fields: model_name = field.model_id.model field_name = field.field_id.name field_type = field.field_id.ttype table_name = self.pool[model_name]._table # get the current value sql = "select id, %s from %s" % (field_name, table_name) cr.execute(sql) records = cr.dictfetchall() for record in records: data.append({"model_id": model_name, "field_id": field_name, "id": record['id'], "value": record[field_name]}) # anonymize the value: anonymized_value = None sid = str(record['id']) if field_type == 'char': anonymized_value = 'xxx'+sid elif field_type == 'selection': anonymized_value = 'xxx'+sid elif field_type == 'text': anonymized_value = 'xxx'+sid elif field_type == 'boolean': anonymized_value = random.choice([True, False]) elif field_type == 'date': anonymized_value = '2011-11-11' elif field_type == 'datetime': anonymized_value = '2011-11-11 11:11:11' elif field_type == 'float': anonymized_value = 0.0 elif field_type == 'integer': anonymized_value = 0 elif field_type in ['binary', 'many2many', 'many2one', 'one2many', 'reference']: # cannot anonymize these kind of fields msg = _("Cannot anonymize fields of these types: binary, many2many, many2one, one2many, reference.") self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) if anonymized_value is None: self._raise_after_history_update(cr, uid, history_id, _('Error !'), _("Anonymized value is None. This cannot happens.")) sql = "update %(table)s set %(field)s = %%(anonymized_value)s where id = %%(id)s" % { 'table': table_name, 'field': field_name, } cr.execute(sql, { 'anonymized_value': anonymized_value, 'id': record['id'] }) # save pickle: fn = open(abs_filepath, 'w') pickle.dump(data, fn, pickle.HIGHEST_PROTOCOL) # update the anonymization fields: values = { 'state': 'anonymized', } ir_model_fields_anonymization_model.write(cr, uid, field_ids, values, context=context) # add a result message in the wizard: msgs = ["Anonymization successful.", "", "Donot forget to save the resulting file to a safe place because you will not be able to revert the anonymization without this file.", "", "This file is also stored in the %s directory. The absolute file path is: %s.", ] msg = '\n'.join(msgs) % (dirpath, abs_filepath) fn = open(abs_filepath, 'r') self.write(cr, uid, ids, { 'msg': msg, 'file_export': base64.encodestring(fn.read()), }) fn.close() # update the history record: anonymization_history_model.write(cr, uid, history_id, { 'field_ids': [[6, 0, field_ids]], 'msg': msg, 'filepath': abs_filepath, 'state': 'done', }) # handle the view: view_id = self._id_get(cr, uid, 'ir.ui.view', 'view_ir_model_fields_anonymize_wizard_form', 'anonymization') return { 'res_id': ids[0], 'view_id': [view_id], 'view_type': 'form', "view_mode": 'form', 'res_model': 'ir.model.fields.anonymize.wizard', 'type': 'ir.actions.act_window', 'context': {'step': 'just_anonymized'}, 'target':'new', } def reverse_anonymize_database(self, cr, uid, ids, context=None): """Set the 'clear' state to defined fields""" ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization') anonymization_history_model = self.pool.get('ir.model.fields.anonymization.history') # create a new history record: vals = { 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'state': 'started', 'direction': 'anonymized -> clear', } history_id = anonymization_history_model.create(cr, uid, vals) # check that all the defined fields are in the 'anonymized' state state = ir_model_fields_anonymization_model._get_global_state(cr, uid, context=context) if state == 'clear': raise osv.except_osv_('Error!', "The database is not currently anonymized, you cannot reverse the anonymization.") elif state == 'unstable': msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to do anything.") raise osv.except_osv('Error!', msg) wizards = self.browse(cr, uid, ids, context=context) for wizard in wizards: if not wizard.file_import: msg = _("It is not possible to reverse the anonymization process without supplying the anonymization export file.") self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) # reverse the anonymization: # load the pickle file content into a data structure: data = pickle.loads(base64.decodestring(wizard.file_import)) migration_fix_obj = self.pool.get('ir.model.fields.anonymization.migration.fix') fix_ids = migration_fix_obj.search(cr, uid, [('target_version', '=', '7.0')]) fixes = migration_fix_obj.read(cr, uid, fix_ids, ['model_name', 'field_name', 'query', 'query_type', 'sequence']) fixes = group(fixes, ('model_name', 'field_name')) for line in data: queries = [] table_name = self.pool[line['model_id']]._table if line['model_id'] in self.pool else None # check if custom sql exists: key = (line['model_id'], line['field_id']) custom_updates = fixes.get(key) if custom_updates: custom_updates.sort(key=itemgetter('sequence')) queries = [(record['query'], record['query_type']) for record in custom_updates if record['query_type']] elif table_name: queries = [("update %(table)s set %(field)s = %%(value)s where id = %%(id)s" % { 'table': table_name, 'field': line['field_id'], }, 'sql')] for query in queries: if query[1] == 'sql': sql = query[0] cr.execute(sql, { 'value': line['value'], 'id': line['id'] }) elif query[1] == 'python': raw_code = query[0] code = raw_code % line eval(code) else: raise Exception("Unknown query type '%s'. Valid types are: sql, python." % (query['query_type'], )) # update the anonymization fields: ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization') field_ids = ir_model_fields_anonymization_model.search(cr, uid, [('state', '<>', 'not_existing')], context=context) values = { 'state': 'clear', } ir_model_fields_anonymization_model.write(cr, uid, field_ids, values, context=context) # add a result message in the wizard: msg = '\n'.join(["Successfully reversed the anonymization.", "", ]) self.write(cr, uid, ids, {'msg': msg}) # update the history record: anonymization_history_model.write(cr, uid, history_id, { 'field_ids': [[6, 0, field_ids]], 'msg': msg, 'filepath': False, 'state': 'done', }) # handle the view: view_id = self._id_get(cr, uid, 'ir.ui.view', 'view_ir_model_fields_anonymize_wizard_form', 'anonymization') return { 'res_id': ids[0], 'view_id': [view_id], 'view_type': 'form', "view_mode": 'form', 'res_model': 'ir.model.fields.anonymize.wizard', 'type': 'ir.actions.act_window', 'context': {'step': 'just_desanonymized'}, 'target':'new', } def _id_get(self, cr, uid, model, id_str, mod): if '.' in id_str: mod, id_str = id_str.split('.') try: idn = self.pool.get('ir.model.data')._get_id(cr, uid, mod, id_str) res = int(self.pool.get('ir.model.data').read(cr, uid, [idn], ['res_id'])[0]['res_id']) except: res = None return res class ir_model_fields_anonymization_migration_fix(osv.osv): _name = 'ir.model.fields.anonymization.migration.fix' _order = "sequence" _columns = { 'target_version': fields.char('Target Version'), 'model_name': fields.char('Model'), 'field_name': fields.char('Field'), 'query': fields.text('Query'), 'query_type': fields.selection(string='Query', selection=[('sql', 'sql'), ('python', 'python')]), 'sequence': fields.integer('Sequence'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Panos512/inspire-next
refs/heads/master
inspirehep/modules/search/walkers/tree_printer.py
5
# -*- coding: utf-8 -*- # # This file is part of Invenio-Query-Parser. # Copyright (C) 2014 CERN. # # Invenio-Query-Parser 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. # # Invenio-Query-Parser 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # # In applying this licence, CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization # or submit itself to any jurisdiction. """SPIRES extended repr printer.""" from invenio_query_parser.visitor import make_visitor from invenio_query_parser.walkers import repr_printer from .. import parser from ..ast import SpiresOp class TreeRepr(repr_printer.TreeRepr): visitor = make_visitor(repr_printer.TreeRepr.visitor) @visitor(SpiresOp) def visit(self, node, left, right): return "find %s %s" % (left, right)
tungvx/deploy
refs/heads/master
.google_appengine/google/appengine/ext/webapp/xmpp_handlers.py
15
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """XMPP webapp handler classes. This module provides handler classes for XMPP bots, including both basic messaging functionality and a command handler for commands such as "/foo bar" """ import logging from google.appengine.api import xmpp from google.appengine.ext import webapp class BaseHandler(webapp.RequestHandler): """A webapp baseclass for XMPP handlers. Implements a straightforward message delivery pattern. When a message is received, message_received is called with a Message object that encapsulates the relevant details. Users can reply using the standard XMPP API, or the convenient .reply() method on the Message object. """ def message_received(self, message): """Called when a message is sent to the XMPP bot. Args: message: Message: The message that was sent by the user. """ raise NotImplementedError() def handle_exception(self, exception, debug_mode): """Called if this handler throws an exception during execution. Args: exception: the exception that was thrown debug_mode: True if the web application is running in debug mode """ super(BaseHandler, self).handle_exception(exception, debug_mode) if self.xmpp_message: self.xmpp_message.reply('Oops. Something went wrong.') def post(self): try: self.xmpp_message = xmpp.Message(self.request.POST) except xmpp.InvalidMessageError, e: logging.error("Invalid XMPP request: Missing required field %s", e[0]) return self.message_received(self.xmpp_message) class CommandHandlerMixin(object): """A command handler for XMPP bots. Implements a command handler pattern. XMPP messages are processed by calling message_received. Message objects handled by this class are annotated with 'command' and 'arg' fields. On receipt of a message starting with a forward or backward slash, the handler calls a method named after the command - eg, if the user sends "/foo bar", the handler will call foo_command(message). If no handler method matches, unhandled_command is called. The default behaviour of unhandled_command is to send the message "Unknown command" back to the sender. If the user sends a message not prefixed with a slash, text_message(message) is called. """ def unhandled_command(self, message): """Called when an unknown command is sent to the XMPP bot. Args: message: Message: The message that was sent by the user. """ message.reply('Unknown command') def text_message(self, message): """Called when a message not prefixed by a /command is sent to the XMPP bot. Args: message: Message: The message that was sent by the user. """ pass def message_received(self, message): """Called when a message is sent to the XMPP bot. Args: message: Message: The message that was sent by the user. """ if message.command: handler_name = '%s_command' % (message.command,) handler = getattr(self, handler_name, None) if handler: handler(message) else: self.unhandled_command(message) else: self.text_message(message) class CommandHandler(CommandHandlerMixin, BaseHandler): """A webapp implementation of CommandHandlerMixin.""" pass
Eric89GXL/scipy
refs/heads/master
scipy/signal/tests/test_signaltools.py
2
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import sys from decimal import Decimal from itertools import product import warnings import pytest from pytest import raises as assert_raises from numpy.testing import ( assert_equal, assert_almost_equal, assert_array_equal, assert_array_almost_equal, assert_allclose, assert_, assert_warns, assert_array_less) from scipy._lib._numpy_compat import suppress_warnings from numpy import array, arange import numpy as np from scipy.ndimage.filters import correlate1d from scipy.optimize import fmin from scipy import signal from scipy.signal import ( correlate, convolve, convolve2d, fftconvolve, choose_conv_method, hilbert, hilbert2, lfilter, lfilter_zi, filtfilt, butter, zpk2tf, zpk2sos, invres, invresz, vectorstrength, lfiltic, tf2sos, sosfilt, sosfiltfilt, sosfilt_zi, tf2zpk, BadCoefficients) from scipy.signal.windows import hann from scipy.signal.signaltools import _filtfilt_gust if sys.version_info.major >= 3 and sys.version_info.minor >= 5: from math import gcd else: from fractions import gcd class _TestConvolve(object): def test_basic(self): a = [3, 4, 5, 6, 5, 4] b = [1, 2, 3] c = convolve(a, b) assert_array_equal(c, array([3, 10, 22, 28, 32, 32, 23, 12])) def test_same(self): a = [3, 4, 5] b = [1, 2, 3, 4] c = convolve(a, b, mode="same") assert_array_equal(c, array([10, 22, 34])) def test_same_eq(self): a = [3, 4, 5] b = [1, 2, 3] c = convolve(a, b, mode="same") assert_array_equal(c, array([10, 22, 22])) def test_complex(self): x = array([1 + 1j, 2 + 1j, 3 + 1j]) y = array([1 + 1j, 2 + 1j]) z = convolve(x, y) assert_array_equal(z, array([2j, 2 + 6j, 5 + 8j, 5 + 5j])) def test_zero_rank(self): a = 1289 b = 4567 c = convolve(a, b) assert_equal(c, a * b) def test_single_element(self): a = array([4967]) b = array([3920]) c = convolve(a, b) assert_equal(c, a * b) def test_2d_arrays(self): a = [[1, 2, 3], [3, 4, 5]] b = [[2, 3, 4], [4, 5, 6]] c = convolve(a, b) d = array([[2, 7, 16, 17, 12], [10, 30, 62, 58, 38], [12, 31, 58, 49, 30]]) assert_array_equal(c, d) def test_input_swapping(self): small = arange(8).reshape(2, 2, 2) big = 1j * arange(27).reshape(3, 3, 3) big += arange(27)[::-1].reshape(3, 3, 3) out_array = array( [[[0 + 0j, 26 + 0j, 25 + 1j, 24 + 2j], [52 + 0j, 151 + 5j, 145 + 11j, 93 + 11j], [46 + 6j, 133 + 23j, 127 + 29j, 81 + 23j], [40 + 12j, 98 + 32j, 93 + 37j, 54 + 24j]], [[104 + 0j, 247 + 13j, 237 + 23j, 135 + 21j], [282 + 30j, 632 + 96j, 604 + 124j, 330 + 86j], [246 + 66j, 548 + 180j, 520 + 208j, 282 + 134j], [142 + 66j, 307 + 161j, 289 + 179j, 153 + 107j]], [[68 + 36j, 157 + 103j, 147 + 113j, 81 + 75j], [174 + 138j, 380 + 348j, 352 + 376j, 186 + 230j], [138 + 174j, 296 + 432j, 268 + 460j, 138 + 278j], [70 + 138j, 145 + 323j, 127 + 341j, 63 + 197j]], [[32 + 72j, 68 + 166j, 59 + 175j, 30 + 100j], [68 + 192j, 139 + 433j, 117 + 455j, 57 + 255j], [38 + 222j, 73 + 499j, 51 + 521j, 21 + 291j], [12 + 144j, 20 + 318j, 7 + 331j, 0 + 182j]]]) assert_array_equal(convolve(small, big, 'full'), out_array) assert_array_equal(convolve(big, small, 'full'), out_array) assert_array_equal(convolve(small, big, 'same'), out_array[1:3, 1:3, 1:3]) assert_array_equal(convolve(big, small, 'same'), out_array[0:3, 0:3, 0:3]) assert_array_equal(convolve(small, big, 'valid'), out_array[1:3, 1:3, 1:3]) assert_array_equal(convolve(big, small, 'valid'), out_array[1:3, 1:3, 1:3]) def test_invalid_params(self): a = [3, 4, 5] b = [1, 2, 3] assert_raises(ValueError, convolve, a, b, mode='spam') assert_raises(ValueError, convolve, a, b, mode='eggs', method='fft') assert_raises(ValueError, convolve, a, b, mode='ham', method='direct') assert_raises(ValueError, convolve, a, b, mode='full', method='bacon') assert_raises(ValueError, convolve, a, b, mode='same', method='bacon') class TestConvolve(_TestConvolve): def test_valid_mode2(self): # See gh-5897 a = [1, 2, 3, 6, 5, 3] b = [2, 3, 4, 5, 3, 4, 2, 2, 1] expected = [70, 78, 73, 65] out = convolve(a, b, 'valid') assert_array_equal(out, expected) out = convolve(b, a, 'valid') assert_array_equal(out, expected) a = [1 + 5j, 2 - 1j, 3 + 0j] b = [2 - 3j, 1 + 0j] expected = [2 - 3j, 8 - 10j] out = convolve(a, b, 'valid') assert_array_equal(out, expected) out = convolve(b, a, 'valid') assert_array_equal(out, expected) def test_same_mode(self): a = [1, 2, 3, 3, 1, 2] b = [1, 4, 3, 4, 5, 6, 7, 4, 3, 2, 1, 1, 3] c = convolve(a, b, 'same') d = array([57, 61, 63, 57, 45, 36]) assert_array_equal(c, d) def test_invalid_shapes(self): # By "invalid," we mean that no one # array has dimensions that are all at # least as large as the corresponding # dimensions of the other array. This # setup should throw a ValueError. a = np.arange(1, 7).reshape((2, 3)) b = np.arange(-6, 0).reshape((3, 2)) assert_raises(ValueError, convolve, *(a, b), **{'mode': 'valid'}) assert_raises(ValueError, convolve, *(b, a), **{'mode': 'valid'}) def test_convolve_method(self, n=100): types = sum([t for _, t in np.sctypes.items()], []) types = {np.dtype(t).name for t in types} # These types include 'bool' and all precisions (int8, float32, etc) # The removed types throw errors in correlate or fftconvolve for dtype in ['complex256', 'complex192', 'float128', 'float96', 'str', 'void', 'bytes', 'object', 'unicode', 'string']: if dtype in types: types.remove(dtype) args = [(t1, t2, mode) for t1 in types for t2 in types for mode in ['valid', 'full', 'same']] # These are random arrays, which means test is much stronger than # convolving testing by convolving two np.ones arrays np.random.seed(42) array_types = {'i': np.random.choice([0, 1], size=n), 'f': np.random.randn(n)} array_types['b'] = array_types['u'] = array_types['i'] array_types['c'] = array_types['f'] + 0.5j*array_types['f'] for t1, t2, mode in args: x1 = array_types[np.dtype(t1).kind].astype(t1) x2 = array_types[np.dtype(t2).kind].astype(t2) results = {key: convolve(x1, x2, method=key, mode=mode) for key in ['fft', 'direct']} assert_equal(results['fft'].dtype, results['direct'].dtype) if 'bool' in t1 and 'bool' in t2: assert_equal(choose_conv_method(x1, x2), 'direct') continue # Found by experiment. Found approx smallest value for (rtol, atol) # threshold to have tests pass. if any([t in {'complex64', 'float32'} for t in [t1, t2]]): kwargs = {'rtol': 1.0e-4, 'atol': 1e-6} elif 'float16' in [t1, t2]: # atol is default for np.allclose kwargs = {'rtol': 1e-3, 'atol': 1e-8} else: # defaults for np.allclose (different from assert_allclose) kwargs = {'rtol': 1e-5, 'atol': 1e-8} assert_allclose(results['fft'], results['direct'], **kwargs) def test_convolve_method_large_input(self): # This is really a test that convolving two large integers goes to the # direct method even if they're in the fft method. for n in [10, 20, 50, 51, 52, 53, 54, 60, 62]: z = np.array([2**n], dtype=np.int64) fft = convolve(z, z, method='fft') direct = convolve(z, z, method='direct') # this is the case when integer precision gets to us # issue #6076 has more detail, hopefully more tests after resolved if n < 50: assert_equal(fft, direct) assert_equal(fft, 2**(2*n)) assert_equal(direct, 2**(2*n)) def test_mismatched_dims(self): # Input arrays should have the same number of dimensions assert_raises(ValueError, convolve, [1], 2, method='direct') assert_raises(ValueError, convolve, 1, [2], method='direct') assert_raises(ValueError, convolve, [1], 2, method='fft') assert_raises(ValueError, convolve, 1, [2], method='fft') assert_raises(ValueError, convolve, [1], [[2]]) assert_raises(ValueError, convolve, [3], 2) class _TestConvolve2d(object): def test_2d_arrays(self): a = [[1, 2, 3], [3, 4, 5]] b = [[2, 3, 4], [4, 5, 6]] d = array([[2, 7, 16, 17, 12], [10, 30, 62, 58, 38], [12, 31, 58, 49, 30]]) e = convolve2d(a, b) assert_array_equal(e, d) def test_valid_mode(self): e = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] f = [[1, 2, 3], [3, 4, 5]] h = array([[62, 80, 98, 116, 134]]) g = convolve2d(e, f, 'valid') assert_array_equal(g, h) # See gh-5897 g = convolve2d(f, e, 'valid') assert_array_equal(g, h) def test_valid_mode_complx(self): e = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] f = np.array([[1, 2, 3], [3, 4, 5]], dtype=complex) + 1j h = array([[62.+24.j, 80.+30.j, 98.+36.j, 116.+42.j, 134.+48.j]]) g = convolve2d(e, f, 'valid') assert_array_almost_equal(g, h) # See gh-5897 g = convolve2d(f, e, 'valid') assert_array_equal(g, h) def test_fillvalue(self): a = [[1, 2, 3], [3, 4, 5]] b = [[2, 3, 4], [4, 5, 6]] fillval = 1 c = convolve2d(a, b, 'full', 'fill', fillval) d = array([[24, 26, 31, 34, 32], [28, 40, 62, 64, 52], [32, 46, 67, 62, 48]]) assert_array_equal(c, d) def test_fillvalue_deprecations(self): # Deprecated 2017-07, scipy version 1.0.0 with suppress_warnings() as sup: sup.filter(np.ComplexWarning, "Casting complex values to real") r = sup.record(DeprecationWarning, "could not cast `fillvalue`") convolve2d([[1]], [[1, 2]], fillvalue=1j) assert_(len(r) == 1) warnings.filterwarnings( "error", message="could not cast `fillvalue`", category=DeprecationWarning) assert_raises(DeprecationWarning, convolve2d, [[1]], [[1, 2]], fillvalue=1j) with suppress_warnings(): warnings.filterwarnings( "always", message="`fillvalue` must be scalar or an array ", category=DeprecationWarning) assert_warns(DeprecationWarning, convolve2d, [[1]], [[1, 2]], fillvalue=[1, 2]) warnings.filterwarnings( "error", message="`fillvalue` must be scalar or an array ", category=DeprecationWarning) assert_raises(DeprecationWarning, convolve2d, [[1]], [[1, 2]], fillvalue=[1, 2]) def test_fillvalue_empty(self): # Check that fillvalue being empty raises an error: assert_raises(ValueError, convolve2d, [[1]], [[1, 2]], fillvalue=[]) def test_wrap_boundary(self): a = [[1, 2, 3], [3, 4, 5]] b = [[2, 3, 4], [4, 5, 6]] c = convolve2d(a, b, 'full', 'wrap') d = array([[80, 80, 74, 80, 80], [68, 68, 62, 68, 68], [80, 80, 74, 80, 80]]) assert_array_equal(c, d) def test_sym_boundary(self): a = [[1, 2, 3], [3, 4, 5]] b = [[2, 3, 4], [4, 5, 6]] c = convolve2d(a, b, 'full', 'symm') d = array([[34, 30, 44, 62, 66], [52, 48, 62, 80, 84], [82, 78, 92, 110, 114]]) assert_array_equal(c, d) def test_invalid_shapes(self): # By "invalid," we mean that no one # array has dimensions that are all at # least as large as the corresponding # dimensions of the other array. This # setup should throw a ValueError. a = np.arange(1, 7).reshape((2, 3)) b = np.arange(-6, 0).reshape((3, 2)) assert_raises(ValueError, convolve2d, *(a, b), **{'mode': 'valid'}) assert_raises(ValueError, convolve2d, *(b, a), **{'mode': 'valid'}) class TestConvolve2d(_TestConvolve2d): def test_same_mode(self): e = [[1, 2, 3], [3, 4, 5]] f = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] g = convolve2d(e, f, 'same') h = array([[22, 28, 34], [80, 98, 116]]) assert_array_equal(g, h) def test_valid_mode2(self): # See gh-5897 e = [[1, 2, 3], [3, 4, 5]] f = [[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]] expected = [[62, 80, 98, 116, 134]] out = convolve2d(e, f, 'valid') assert_array_equal(out, expected) out = convolve2d(f, e, 'valid') assert_array_equal(out, expected) e = [[1 + 1j, 2 - 3j], [3 + 1j, 4 + 0j]] f = [[2 - 1j, 3 + 2j, 4 + 0j], [4 - 0j, 5 + 1j, 6 - 3j]] expected = [[27 - 1j, 46. + 2j]] out = convolve2d(e, f, 'valid') assert_array_equal(out, expected) # See gh-5897 out = convolve2d(f, e, 'valid') assert_array_equal(out, expected) def test_consistency_convolve_funcs(self): # Compare np.convolve, signal.convolve, signal.convolve2d a = np.arange(5) b = np.array([3.2, 1.4, 3]) for mode in ['full', 'valid', 'same']: assert_almost_equal(np.convolve(a, b, mode=mode), signal.convolve(a, b, mode=mode)) assert_almost_equal(np.squeeze( signal.convolve2d([a], [b], mode=mode)), signal.convolve(a, b, mode=mode)) def test_invalid_dims(self): assert_raises(ValueError, convolve2d, 3, 4) assert_raises(ValueError, convolve2d, [3], [4]) assert_raises(ValueError, convolve2d, [[[3]]], [[[4]]]) class TestFFTConvolve(object): @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) def test_real(self, axes): a = array([1, 2, 3]) expected = array([1, 4, 10, 12, 9.]) if axes == '': out = fftconvolve(a, a) else: out = fftconvolve(a, a, axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) def test_real_axes(self, axes): a = array([1, 2, 3]) expected = array([1, 4, 10, 12, 9.]) a = np.tile(a, [2, 1]) expected = np.tile(expected, [2, 1]) out = fftconvolve(a, a, axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) def test_complex(self, axes): a = array([1 + 1j, 2 + 2j, 3 + 3j]) expected = array([0 + 2j, 0 + 8j, 0 + 20j, 0 + 24j, 0 + 18j]) if axes == '': out = fftconvolve(a, a) else: out = fftconvolve(a, a, axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) def test_complex_axes(self, axes): a = array([1 + 1j, 2 + 2j, 3 + 3j]) expected = array([0 + 2j, 0 + 8j, 0 + 20j, 0 + 24j, 0 + 18j]) a = np.tile(a, [2, 1]) expected = np.tile(expected, [2, 1]) out = fftconvolve(a, a, axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', ['', None, [0, 1], [1, 0], [0, -1], [-1, 0], [-2, 1], [1, -2], [-2, -1], [-1, -2]]) def test_2d_real_same(self, axes): a = array([[1, 2, 3], [4, 5, 6]]) expected = array([[1, 4, 10, 12, 9], [8, 26, 56, 54, 36], [16, 40, 73, 60, 36]]) if axes == '': out = fftconvolve(a, a) else: out = fftconvolve(a, a, axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', [[1, 2], [2, 1], [1, -1], [-1, 1], [-2, 2], [2, -2], [-2, -1], [-1, -2]]) def test_2d_real_same_axes(self, axes): a = array([[1, 2, 3], [4, 5, 6]]) expected = array([[1, 4, 10, 12, 9], [8, 26, 56, 54, 36], [16, 40, 73, 60, 36]]) a = np.tile(a, [2, 1, 1]) expected = np.tile(expected, [2, 1, 1]) out = fftconvolve(a, a, axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', ['', None, [0, 1], [1, 0], [0, -1], [-1, 0], [-2, 1], [1, -2], [-2, -1], [-1, -2]]) def test_2d_complex_same(self, axes): a = array([[1 + 2j, 3 + 4j, 5 + 6j], [2 + 1j, 4 + 3j, 6 + 5j]]) expected = array([ [-3 + 4j, -10 + 20j, -21 + 56j, -18 + 76j, -11 + 60j], [10j, 44j, 118j, 156j, 122j], [3 + 4j, 10 + 20j, 21 + 56j, 18 + 76j, 11 + 60j] ]) if axes == '': out = fftconvolve(a, a) else: out = fftconvolve(a, a, axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', [[1, 2], [2, 1], [1, -1], [-1, 1], [-2, 2], [2, -2], [-2, -1], [-1, -2]]) def test_2d_complex_same_axes(self, axes): a = array([[1 + 2j, 3 + 4j, 5 + 6j], [2 + 1j, 4 + 3j, 6 + 5j]]) expected = array([ [-3 + 4j, -10 + 20j, -21 + 56j, -18 + 76j, -11 + 60j], [10j, 44j, 118j, 156j, 122j], [3 + 4j, 10 + 20j, 21 + 56j, 18 + 76j, 11 + 60j] ]) a = np.tile(a, [2, 1, 1]) expected = np.tile(expected, [2, 1, 1]) out = fftconvolve(a, a, axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) def test_real_same_mode(self, axes): a = array([1, 2, 3]) b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) expected_1 = array([35., 41., 47.]) expected_2 = array([9., 20., 25., 35., 41., 47., 39., 28., 2.]) if axes == '': out = fftconvolve(a, b, 'same') else: out = fftconvolve(a, b, 'same', axes=axes) assert_array_almost_equal(out, expected_1) if axes == '': out = fftconvolve(b, a, 'same') else: out = fftconvolve(b, a, 'same', axes=axes) assert_array_almost_equal(out, expected_2) @pytest.mark.parametrize('axes', [1, -1, [1], [-1]]) def test_real_same_mode_axes(self, axes): a = array([1, 2, 3]) b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) expected_1 = array([35., 41., 47.]) expected_2 = array([9., 20., 25., 35., 41., 47., 39., 28., 2.]) a = np.tile(a, [2, 1]) b = np.tile(b, [2, 1]) expected_1 = np.tile(expected_1, [2, 1]) expected_2 = np.tile(expected_2, [2, 1]) out = fftconvolve(a, b, 'same', axes=axes) assert_array_almost_equal(out, expected_1) out = fftconvolve(b, a, 'same', axes=axes) assert_array_almost_equal(out, expected_2) @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) def test_valid_mode_real(self, axes): # See gh-5897 a = array([3, 2, 1]) b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) expected = array([24., 31., 41., 43., 49., 25., 12.]) if axes == '': out = fftconvolve(a, b, 'valid') else: out = fftconvolve(a, b, 'valid', axes=axes) assert_array_almost_equal(out, expected) if axes == '': out = fftconvolve(b, a, 'valid') else: out = fftconvolve(b, a, 'valid', axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', [1, [1]]) def test_valid_mode_real_axes(self, axes): # See gh-5897 a = array([3, 2, 1]) b = array([3, 3, 5, 6, 8, 7, 9, 0, 1]) expected = array([24., 31., 41., 43., 49., 25., 12.]) a = np.tile(a, [2, 1]) b = np.tile(b, [2, 1]) expected = np.tile(expected, [2, 1]) out = fftconvolve(a, b, 'valid', axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) def test_valid_mode_complex(self, axes): a = array([3 - 1j, 2 + 7j, 1 + 0j]) b = array([3 + 2j, 3 - 3j, 5 + 0j, 6 - 1j, 8 + 0j]) expected = array([45. + 12.j, 30. + 23.j, 48 + 32.j]) if axes == '': out = fftconvolve(a, b, 'valid') else: out = fftconvolve(a, b, 'valid', axes=axes) assert_array_almost_equal(out, expected) if axes == '': out = fftconvolve(b, a, 'valid') else: out = fftconvolve(b, a, 'valid', axes=axes) assert_array_almost_equal(out, expected) @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) def test_valid_mode_complex_axes(self, axes): a = array([3 - 1j, 2 + 7j, 1 + 0j]) b = array([3 + 2j, 3 - 3j, 5 + 0j, 6 - 1j, 8 + 0j]) expected = array([45. + 12.j, 30. + 23.j, 48 + 32.j]) a = np.tile(a, [2, 1]) b = np.tile(b, [2, 1]) expected = np.tile(expected, [2, 1]) out = fftconvolve(a, b, 'valid', axes=axes) assert_array_almost_equal(out, expected) out = fftconvolve(b, a, 'valid', axes=axes) assert_array_almost_equal(out, expected) def test_empty(self): # Regression test for #1745: crashes with 0-length input. assert_(fftconvolve([], []).size == 0) assert_(fftconvolve([5, 6], []).size == 0) assert_(fftconvolve([], [7]).size == 0) def test_zero_rank(self): a = array(4967) b = array(3920) out = fftconvolve(a, b) assert_equal(out, a * b) def test_single_element(self): a = array([4967]) b = array([3920]) out = fftconvolve(a, b) assert_equal(out, a * b) @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]]) def test_random_data(self, axes): np.random.seed(1234) a = np.random.rand(1233) + 1j * np.random.rand(1233) b = np.random.rand(1321) + 1j * np.random.rand(1321) expected = np.convolve(a, b, 'full') if axes == '': out = fftconvolve(a, b, 'full') else: out = fftconvolve(a, b, 'full', axes=axes) assert_(np.allclose(out, expected, rtol=1e-10)) @pytest.mark.parametrize('axes', [1, [1], -1, [-1]]) def test_random_data_axes(self, axes): np.random.seed(1234) a = np.random.rand(1233) + 1j * np.random.rand(1233) b = np.random.rand(1321) + 1j * np.random.rand(1321) expected = np.convolve(a, b, 'full') a = np.tile(a, [2, 1]) b = np.tile(b, [2, 1]) expected = np.tile(expected, [2, 1]) out = fftconvolve(a, b, 'full', axes=axes) assert_(np.allclose(out, expected, rtol=1e-10)) @pytest.mark.parametrize('axes', [[1, 4], [4, 1], [1, -1], [-1, 1], [-4, 4], [4, -4], [-4, -1], [-1, -4]]) def test_random_data_multidim_axes(self, axes): np.random.seed(1234) a = np.random.rand(123, 222) + 1j * np.random.rand(123, 222) b = np.random.rand(132, 111) + 1j * np.random.rand(132, 111) expected = convolve2d(a, b, 'full') a = a[:, :, None, None, None] b = b[:, :, None, None, None] expected = expected[:, :, None, None, None] a = np.rollaxis(a.swapaxes(0, 2), 1, 5) b = np.rollaxis(b.swapaxes(0, 2), 1, 5) expected = np.rollaxis(expected.swapaxes(0, 2), 1, 5) # use 1 for dimension 2 in a and 3 in b to test broadcasting a = np.tile(a, [2, 1, 3, 1, 1]) b = np.tile(b, [2, 1, 1, 4, 1]) expected = np.tile(expected, [2, 1, 3, 4, 1]) out = fftconvolve(a, b, 'full', axes=axes) assert_(np.allclose(out, expected, rtol=1e-10)) @pytest.mark.slow @pytest.mark.parametrize( 'n', list(range(1, 100)) + list(range(1000, 1500)) + np.random.RandomState(1234).randint(1001, 10000, 5).tolist()) def test_many_sizes(self, n): a = np.random.rand(n) + 1j * np.random.rand(n) b = np.random.rand(n) + 1j * np.random.rand(n) expected = np.convolve(a, b, 'full') out = fftconvolve(a, b, 'full') assert_allclose(out, expected, atol=1e-10) out = fftconvolve(a, b, 'full', axes=[0]) assert_allclose(out, expected, atol=1e-10) def test_invalid_shapes(self): a = np.arange(1, 7).reshape((2, 3)) b = np.arange(-6, 0).reshape((3, 2)) with assert_raises(ValueError, match="For 'valid' mode, one must be at least " "as large as the other in every dimension"): fftconvolve(a, b, mode='valid') def test_invalid_shapes_axes(self): a = np.zeros([5, 6, 2, 1]) b = np.zeros([5, 6, 3, 1]) with assert_raises(ValueError, match=r"incompatible shapes for in1 and in2:" r" \(5L?, 6L?, 2L?, 1L?\) and" r" \(5L?, 6L?, 3L?, 1L?\)"): fftconvolve(a, b, axes=[0, 1]) @pytest.mark.parametrize('a,b', [([1], 2), (1, [2]), ([3], [[2]])]) def test_mismatched_dims(self, a, b): with assert_raises(ValueError, match="in1 and in2 should have the same" " dimensionality"): fftconvolve(a, b) def test_invalid_flags(self): with assert_raises(ValueError, match="acceptable mode flags are 'valid'," " 'same', or 'full'"): fftconvolve([1], [2], mode='chips') with assert_raises(ValueError, match="when provided, axes cannot be empty"): fftconvolve([1], [2], axes=[]) with assert_raises(ValueError, match="when given, axes values must be a scalar" " or vector"): fftconvolve([1], [2], axes=[[1, 2], [3, 4]]) with assert_raises(ValueError, match="when given, axes values must be integers"): fftconvolve([1], [2], axes=[1., 2., 3., 4.]) with assert_raises(ValueError, match="axes exceeds dimensionality of input"): fftconvolve([1], [2], axes=[1]) with assert_raises(ValueError, match="axes exceeds dimensionality of input"): fftconvolve([1], [2], axes=[-2]) with assert_raises(ValueError, match="all axes must be unique"): fftconvolve([1], [2], axes=[0, 0]) class TestMedFilt(object): def test_basic(self): f = [[50, 50, 50, 50, 50, 92, 18, 27, 65, 46], [50, 50, 50, 50, 50, 0, 72, 77, 68, 66], [50, 50, 50, 50, 50, 46, 47, 19, 64, 77], [50, 50, 50, 50, 50, 42, 15, 29, 95, 35], [50, 50, 50, 50, 50, 46, 34, 9, 21, 66], [70, 97, 28, 68, 78, 77, 61, 58, 71, 42], [64, 53, 44, 29, 68, 32, 19, 68, 24, 84], [3, 33, 53, 67, 1, 78, 74, 55, 12, 83], [7, 11, 46, 70, 60, 47, 24, 43, 61, 26], [32, 61, 88, 7, 39, 4, 92, 64, 45, 61]] d = signal.medfilt(f, [7, 3]) e = signal.medfilt2d(np.array(f, float), [7, 3]) assert_array_equal(d, [[0, 50, 50, 50, 42, 15, 15, 18, 27, 0], [0, 50, 50, 50, 50, 42, 19, 21, 29, 0], [50, 50, 50, 50, 50, 47, 34, 34, 46, 35], [50, 50, 50, 50, 50, 50, 42, 47, 64, 42], [50, 50, 50, 50, 50, 50, 46, 55, 64, 35], [33, 50, 50, 50, 50, 47, 46, 43, 55, 26], [32, 50, 50, 50, 50, 47, 46, 45, 55, 26], [7, 46, 50, 50, 47, 46, 46, 43, 45, 21], [0, 32, 33, 39, 32, 32, 43, 43, 43, 0], [0, 7, 11, 7, 4, 4, 19, 19, 24, 0]]) assert_array_equal(d, e) def test_none(self): # Ticket #1124. Ensure this does not segfault. signal.medfilt(None) # Expand on this test to avoid a regression with possible contiguous # numpy arrays that have odd strides. The stride value below gets # us into wrong memory if used (but it does not need to be used) dummy = np.arange(10, dtype=np.float64) a = dummy[5:6] a.strides = 16 assert_(signal.medfilt(a, 1) == 5.) def test_refcounting(self): # Check a refcounting-related crash a = Decimal(123) x = np.array([a, a], dtype=object) if hasattr(sys, 'getrefcount'): n = 2 * sys.getrefcount(a) else: n = 10 # Shouldn't segfault: for j in range(n): signal.medfilt(x) if hasattr(sys, 'getrefcount'): assert_(sys.getrefcount(a) < n) assert_equal(x, [a, a]) class TestWiener(object): def test_basic(self): g = array([[5, 6, 4, 3], [3, 5, 6, 2], [2, 3, 5, 6], [1, 6, 9, 7]], 'd') h = array([[2.16374269, 3.2222222222, 2.8888888889, 1.6666666667], [2.666666667, 4.33333333333, 4.44444444444, 2.8888888888], [2.222222222, 4.4444444444, 5.4444444444, 4.801066874837], [1.33333333333, 3.92735042735, 6.0712560386, 5.0404040404]]) assert_array_almost_equal(signal.wiener(g), h, decimal=6) assert_array_almost_equal(signal.wiener(g, mysize=3), h, decimal=6) class TestResample(object): def test_basic(self): # Some basic tests # Regression test for issue #3603. # window.shape must equal to sig.shape[0] sig = np.arange(128) num = 256 win = signal.get_window(('kaiser', 8.0), 160) assert_raises(ValueError, signal.resample, sig, num, window=win) # Other degenerate conditions assert_raises(ValueError, signal.resample_poly, sig, 'yo', 1) assert_raises(ValueError, signal.resample_poly, sig, 1, 0) # test for issue #6505 - should not modify window.shape when axis ≠ 0 sig2 = np.tile(np.arange(160), (2,1)) signal.resample(sig2, num, axis=-1, window=win) assert_(win.shape == (160,)) def test_fft(self): # Test FFT-based resampling self._test_data(method='fft') def test_polyphase(self): # Test polyphase resampling self._test_data(method='polyphase') def test_polyphase_extfilter(self): # Test external specification of downsampling filter self._test_data(method='polyphase', ext=True) def test_mutable_window(self): # Test that a mutable window is not modified impulse = np.zeros(3) window = np.random.RandomState(0).randn(2) window_orig = window.copy() signal.resample_poly(impulse, 5, 1, window=window) assert_array_equal(window, window_orig) def test_output_float32(self): # Test that float32 inputs yield a float32 output x = np.arange(10, dtype=np.float32) h = np.array([1,1,1], dtype=np.float32) y = signal.resample_poly(x, 1, 2, window=h) assert_(y.dtype == np.float32) def _test_data(self, method, ext=False): # Test resampling of sinusoids and random noise (1-sec) rate = 100 rates_to = [49, 50, 51, 99, 100, 101, 199, 200, 201] # Sinusoids, windowed to avoid edge artifacts t = np.arange(rate) / float(rate) freqs = np.array((1., 10., 40.))[:, np.newaxis] x = np.sin(2 * np.pi * freqs * t) * hann(rate) for rate_to in rates_to: t_to = np.arange(rate_to) / float(rate_to) y_tos = np.sin(2 * np.pi * freqs * t_to) * hann(rate_to) if method == 'fft': y_resamps = signal.resample(x, rate_to, axis=-1) else: if ext and rate_to != rate: # Match default window design g = gcd(rate_to, rate) up = rate_to // g down = rate // g max_rate = max(up, down) f_c = 1. / max_rate half_len = 10 * max_rate window = signal.firwin(2 * half_len + 1, f_c, window=('kaiser', 5.0)) polyargs = {'window': window} else: polyargs = {} y_resamps = signal.resample_poly(x, rate_to, rate, axis=-1, **polyargs) for y_to, y_resamp, freq in zip(y_tos, y_resamps, freqs): if freq >= 0.5 * rate_to: y_to.fill(0.) # mostly low-passed away assert_allclose(y_resamp, y_to, atol=1e-3) else: assert_array_equal(y_to.shape, y_resamp.shape) corr = np.corrcoef(y_to, y_resamp)[0, 1] assert_(corr > 0.99, msg=(corr, rate, rate_to)) # Random data rng = np.random.RandomState(0) x = hann(rate) * np.cumsum(rng.randn(rate)) # low-pass, wind for rate_to in rates_to: # random data t_to = np.arange(rate_to) / float(rate_to) y_to = np.interp(t_to, t, x) if method == 'fft': y_resamp = signal.resample(x, rate_to) else: y_resamp = signal.resample_poly(x, rate_to, rate) assert_array_equal(y_to.shape, y_resamp.shape) corr = np.corrcoef(y_to, y_resamp)[0, 1] assert_(corr > 0.99, msg=corr) # More tests of fft method (Master 0.18.1 fails these) if method == 'fft': x1 = np.array([1.+0.j,0.+0.j]) y1_test = signal.resample(x1,4) y1_true = np.array([1.+0.j,0.5+0.j,0.+0.j,0.5+0.j]) # upsampling a complex array assert_allclose(y1_test, y1_true, atol=1e-12) x2 = np.array([1.,0.5,0.,0.5]) y2_test = signal.resample(x2,2) # downsampling a real array y2_true = np.array([1.,0.]) assert_allclose(y2_test, y2_true, atol=1e-12) def test_poly_vs_filtfilt(self): # Check that up=1.0 gives same answer as filtfilt + slicing random_state = np.random.RandomState(17) try_types = (int, np.float32, np.complex64, float, complex) size = 10000 down_factors = [2, 11, 79] for dtype in try_types: x = random_state.randn(size).astype(dtype) if dtype in (np.complex64, np.complex128): x += 1j * random_state.randn(size) # resample_poly assumes zeros outside of signl, whereas filtfilt # can only constant-pad. Make them equivalent: x[0] = 0 x[-1] = 0 for down in down_factors: h = signal.firwin(31, 1. / down, window='hamming') yf = filtfilt(h, 1.0, x, padtype='constant')[::down] # Need to pass convolved version of filter to resample_poly, # since filtfilt does forward and backward, but resample_poly # only goes forward hc = convolve(h, h[::-1]) y = signal.resample_poly(x, 1, down, window=hc) assert_allclose(yf, y, atol=1e-7, rtol=1e-7) def test_correlate1d(self): for down in [2, 4]: for nx in range(1, 40, down): for nweights in (32, 33): x = np.random.random((nx,)) weights = np.random.random((nweights,)) y_g = correlate1d(x, weights[::-1], mode='constant') y_s = signal.resample_poly(x, up=1, down=down, window=weights) assert_allclose(y_g[::down], y_s) class TestCSpline1DEval(object): def test_basic(self): y = array([1, 2, 3, 4, 3, 2, 1, 2, 3.0]) x = arange(len(y)) dx = x[1] - x[0] cj = signal.cspline1d(y) x2 = arange(len(y) * 10.0) / 10.0 y2 = signal.cspline1d_eval(cj, x2, dx=dx, x0=x[0]) # make sure interpolated values are on knot points assert_array_almost_equal(y2[::10], y, decimal=5) def test_complex(self): # create some smoothly varying complex signal to interpolate x = np.arange(2) y = np.zeros(x.shape, dtype=np.complex64) T = 10.0 f = 1.0 / T y = np.exp(2.0J * np.pi * f * x) # get the cspline transform cy = signal.cspline1d(y) # determine new test x value and interpolate xnew = np.array([0.5]) ynew = signal.cspline1d_eval(cy, xnew) assert_equal(ynew.dtype, y.dtype) class TestOrderFilt(object): def test_basic(self): assert_array_equal(signal.order_filter([1, 2, 3], [1, 0, 1], 1), [2, 3, 2]) class _TestLinearFilter(object): def generate(self, shape): x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) return self.convert_dtype(x) def convert_dtype(self, arr): if self.dtype == np.dtype('O'): arr = np.asarray(arr) out = np.empty(arr.shape, self.dtype) iter = np.nditer([arr, out], ['refs_ok','zerosize_ok'], [['readonly'],['writeonly']]) for x, y in iter: y[...] = self.type(x[()]) return out else: return np.array(arr, self.dtype, copy=False) def test_rank_1_IIR(self): x = self.generate((6,)) b = self.convert_dtype([1, -1]) a = self.convert_dtype([0.5, -0.5]) y_r = self.convert_dtype([0, 2, 4, 6, 8, 10.]) assert_array_almost_equal(lfilter(b, a, x), y_r) def test_rank_1_FIR(self): x = self.generate((6,)) b = self.convert_dtype([1, 1]) a = self.convert_dtype([1]) y_r = self.convert_dtype([0, 1, 3, 5, 7, 9.]) assert_array_almost_equal(lfilter(b, a, x), y_r) def test_rank_1_IIR_init_cond(self): x = self.generate((6,)) b = self.convert_dtype([1, 0, -1]) a = self.convert_dtype([0.5, -0.5]) zi = self.convert_dtype([1, 2]) y_r = self.convert_dtype([1, 5, 9, 13, 17, 21]) zf_r = self.convert_dtype([13, -10]) y, zf = lfilter(b, a, x, zi=zi) assert_array_almost_equal(y, y_r) assert_array_almost_equal(zf, zf_r) def test_rank_1_FIR_init_cond(self): x = self.generate((6,)) b = self.convert_dtype([1, 1, 1]) a = self.convert_dtype([1]) zi = self.convert_dtype([1, 1]) y_r = self.convert_dtype([1, 2, 3, 6, 9, 12.]) zf_r = self.convert_dtype([9, 5]) y, zf = lfilter(b, a, x, zi=zi) assert_array_almost_equal(y, y_r) assert_array_almost_equal(zf, zf_r) def test_rank_2_IIR_axis_0(self): x = self.generate((4, 3)) b = self.convert_dtype([1, -1]) a = self.convert_dtype([0.5, 0.5]) y_r2_a0 = self.convert_dtype([[0, 2, 4], [6, 4, 2], [0, 2, 4], [6, 4, 2]]) y = lfilter(b, a, x, axis=0) assert_array_almost_equal(y_r2_a0, y) def test_rank_2_IIR_axis_1(self): x = self.generate((4, 3)) b = self.convert_dtype([1, -1]) a = self.convert_dtype([0.5, 0.5]) y_r2_a1 = self.convert_dtype([[0, 2, 0], [6, -4, 6], [12, -10, 12], [18, -16, 18]]) y = lfilter(b, a, x, axis=1) assert_array_almost_equal(y_r2_a1, y) def test_rank_2_IIR_axis_0_init_cond(self): x = self.generate((4, 3)) b = self.convert_dtype([1, -1]) a = self.convert_dtype([0.5, 0.5]) zi = self.convert_dtype(np.ones((4,1))) y_r2_a0_1 = self.convert_dtype([[1, 1, 1], [7, -5, 7], [13, -11, 13], [19, -17, 19]]) zf_r = self.convert_dtype([-5, -17, -29, -41])[:, np.newaxis] y, zf = lfilter(b, a, x, axis=1, zi=zi) assert_array_almost_equal(y_r2_a0_1, y) assert_array_almost_equal(zf, zf_r) def test_rank_2_IIR_axis_1_init_cond(self): x = self.generate((4,3)) b = self.convert_dtype([1, -1]) a = self.convert_dtype([0.5, 0.5]) zi = self.convert_dtype(np.ones((1,3))) y_r2_a0_0 = self.convert_dtype([[1, 3, 5], [5, 3, 1], [1, 3, 5], [5, 3, 1]]) zf_r = self.convert_dtype([[-23, -23, -23]]) y, zf = lfilter(b, a, x, axis=0, zi=zi) assert_array_almost_equal(y_r2_a0_0, y) assert_array_almost_equal(zf, zf_r) def test_rank_3_IIR(self): x = self.generate((4, 3, 2)) b = self.convert_dtype([1, -1]) a = self.convert_dtype([0.5, 0.5]) for axis in range(x.ndim): y = lfilter(b, a, x, axis) y_r = np.apply_along_axis(lambda w: lfilter(b, a, w), axis, x) assert_array_almost_equal(y, y_r) def test_rank_3_IIR_init_cond(self): x = self.generate((4, 3, 2)) b = self.convert_dtype([1, -1]) a = self.convert_dtype([0.5, 0.5]) for axis in range(x.ndim): zi_shape = list(x.shape) zi_shape[axis] = 1 zi = self.convert_dtype(np.ones(zi_shape)) zi1 = self.convert_dtype([1]) y, zf = lfilter(b, a, x, axis, zi) lf0 = lambda w: lfilter(b, a, w, zi=zi1)[0] lf1 = lambda w: lfilter(b, a, w, zi=zi1)[1] y_r = np.apply_along_axis(lf0, axis, x) zf_r = np.apply_along_axis(lf1, axis, x) assert_array_almost_equal(y, y_r) assert_array_almost_equal(zf, zf_r) def test_rank_3_FIR(self): x = self.generate((4, 3, 2)) b = self.convert_dtype([1, 0, -1]) a = self.convert_dtype([1]) for axis in range(x.ndim): y = lfilter(b, a, x, axis) y_r = np.apply_along_axis(lambda w: lfilter(b, a, w), axis, x) assert_array_almost_equal(y, y_r) def test_rank_3_FIR_init_cond(self): x = self.generate((4, 3, 2)) b = self.convert_dtype([1, 0, -1]) a = self.convert_dtype([1]) for axis in range(x.ndim): zi_shape = list(x.shape) zi_shape[axis] = 2 zi = self.convert_dtype(np.ones(zi_shape)) zi1 = self.convert_dtype([1, 1]) y, zf = lfilter(b, a, x, axis, zi) lf0 = lambda w: lfilter(b, a, w, zi=zi1)[0] lf1 = lambda w: lfilter(b, a, w, zi=zi1)[1] y_r = np.apply_along_axis(lf0, axis, x) zf_r = np.apply_along_axis(lf1, axis, x) assert_array_almost_equal(y, y_r) assert_array_almost_equal(zf, zf_r) def test_zi_pseudobroadcast(self): x = self.generate((4, 5, 20)) b,a = signal.butter(8, 0.2, output='ba') b = self.convert_dtype(b) a = self.convert_dtype(a) zi_size = b.shape[0] - 1 # lfilter requires x.ndim == zi.ndim exactly. However, zi can have # length 1 dimensions. zi_full = self.convert_dtype(np.ones((4, 5, zi_size))) zi_sing = self.convert_dtype(np.ones((1, 1, zi_size))) y_full, zf_full = lfilter(b, a, x, zi=zi_full) y_sing, zf_sing = lfilter(b, a, x, zi=zi_sing) assert_array_almost_equal(y_sing, y_full) assert_array_almost_equal(zf_full, zf_sing) # lfilter does not prepend ones assert_raises(ValueError, lfilter, b, a, x, -1, np.ones(zi_size)) def test_scalar_a(self): # a can be a scalar. x = self.generate(6) b = self.convert_dtype([1, 0, -1]) a = self.convert_dtype([1]) y_r = self.convert_dtype([0, 1, 2, 2, 2, 2]) y = lfilter(b, a[0], x) assert_array_almost_equal(y, y_r) def test_zi_some_singleton_dims(self): # lfilter doesn't really broadcast (no prepending of 1's). But does # do singleton expansion if x and zi have the same ndim. This was # broken only if a subset of the axes were singletons (gh-4681). x = self.convert_dtype(np.zeros((3,2,5), 'l')) b = self.convert_dtype(np.ones(5, 'l')) a = self.convert_dtype(np.array([1,0,0])) zi = np.ones((3,1,4), 'l') zi[1,:,:] *= 2 zi[2,:,:] *= 3 zi = self.convert_dtype(zi) zf_expected = self.convert_dtype(np.zeros((3,2,4), 'l')) y_expected = np.zeros((3,2,5), 'l') y_expected[:,:,:4] = [[[1]], [[2]], [[3]]] y_expected = self.convert_dtype(y_expected) # IIR y_iir, zf_iir = lfilter(b, a, x, -1, zi) assert_array_almost_equal(y_iir, y_expected) assert_array_almost_equal(zf_iir, zf_expected) # FIR y_fir, zf_fir = lfilter(b, a[0], x, -1, zi) assert_array_almost_equal(y_fir, y_expected) assert_array_almost_equal(zf_fir, zf_expected) def base_bad_size_zi(self, b, a, x, axis, zi): b = self.convert_dtype(b) a = self.convert_dtype(a) x = self.convert_dtype(x) zi = self.convert_dtype(zi) assert_raises(ValueError, lfilter, b, a, x, axis, zi) def test_bad_size_zi(self): # rank 1 x1 = np.arange(6) self.base_bad_size_zi([1], [1], x1, -1, [1]) self.base_bad_size_zi([1, 1], [1], x1, -1, [0, 1]) self.base_bad_size_zi([1, 1], [1], x1, -1, [[0]]) self.base_bad_size_zi([1, 1], [1], x1, -1, [0, 1, 2]) self.base_bad_size_zi([1, 1, 1], [1], x1, -1, [[0]]) self.base_bad_size_zi([1, 1, 1], [1], x1, -1, [0, 1, 2]) self.base_bad_size_zi([1], [1, 1], x1, -1, [0, 1]) self.base_bad_size_zi([1], [1, 1], x1, -1, [[0]]) self.base_bad_size_zi([1], [1, 1], x1, -1, [0, 1, 2]) self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0]) self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [[0], [1]]) self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0, 1, 2]) self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0, 1, 2, 3]) self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0]) self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [[0], [1]]) self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0, 1, 2]) self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0, 1, 2, 3]) # rank 2 x2 = np.arange(12).reshape((4,3)) # for axis=0 zi.shape should == (max(len(a),len(b))-1, 3) self.base_bad_size_zi([1], [1], x2, 0, [0]) # for each of these there are 5 cases tested (in this order): # 1. not deep enough, right # elements # 2. too deep, right # elements # 3. right depth, right # elements, transposed # 4. right depth, too few elements # 5. right depth, too many elements self.base_bad_size_zi([1, 1], [1], x2, 0, [0,1,2]) self.base_bad_size_zi([1, 1], [1], x2, 0, [[[0,1,2]]]) self.base_bad_size_zi([1, 1], [1], x2, 0, [[0], [1], [2]]) self.base_bad_size_zi([1, 1], [1], x2, 0, [[0,1]]) self.base_bad_size_zi([1, 1], [1], x2, 0, [[0,1,2,3]]) self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [0,1,2,3,4,5]) self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[[0,1,2],[3,4,5]]]) self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0,1],[2,3],[4,5]]) self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0,1],[2,3]]) self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0,1,2,3],[4,5,6,7]]) self.base_bad_size_zi([1], [1, 1], x2, 0, [0,1,2]) self.base_bad_size_zi([1], [1, 1], x2, 0, [[[0,1,2]]]) self.base_bad_size_zi([1], [1, 1], x2, 0, [[0], [1], [2]]) self.base_bad_size_zi([1], [1, 1], x2, 0, [[0,1]]) self.base_bad_size_zi([1], [1, 1], x2, 0, [[0,1,2,3]]) self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [0,1,2,3,4,5]) self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[[0,1,2],[3,4,5]]]) self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0,1],[2,3],[4,5]]) self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0,1],[2,3]]) self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0,1,2,3],[4,5,6,7]]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [0,1,2,3,4,5]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[[0,1,2],[3,4,5]]]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0,1],[2,3],[4,5]]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0,1],[2,3]]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0,1,2,3],[4,5,6,7]]) # for axis=1 zi.shape should == (4, max(len(a),len(b))-1) self.base_bad_size_zi([1], [1], x2, 1, [0]) self.base_bad_size_zi([1, 1], [1], x2, 1, [0,1,2,3]) self.base_bad_size_zi([1, 1], [1], x2, 1, [[[0],[1],[2],[3]]]) self.base_bad_size_zi([1, 1], [1], x2, 1, [[0, 1, 2, 3]]) self.base_bad_size_zi([1, 1], [1], x2, 1, [[0],[1],[2]]) self.base_bad_size_zi([1, 1], [1], x2, 1, [[0],[1],[2],[3],[4]]) self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [0,1,2,3,4,5,6,7]) self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[[0,1],[2,3],[4,5],[6,7]]]) self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0,1,2,3],[4,5,6,7]]) self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0,1],[2,3],[4,5]]) self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0,1],[2,3],[4,5],[6,7],[8,9]]) self.base_bad_size_zi([1], [1, 1], x2, 1, [0,1,2,3]) self.base_bad_size_zi([1], [1, 1], x2, 1, [[[0],[1],[2],[3]]]) self.base_bad_size_zi([1], [1, 1], x2, 1, [[0, 1, 2, 3]]) self.base_bad_size_zi([1], [1, 1], x2, 1, [[0],[1],[2]]) self.base_bad_size_zi([1], [1, 1], x2, 1, [[0],[1],[2],[3],[4]]) self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [0,1,2,3,4,5,6,7]) self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[[0,1],[2,3],[4,5],[6,7]]]) self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0,1,2,3],[4,5,6,7]]) self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0,1],[2,3],[4,5]]) self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0,1],[2,3],[4,5],[6,7],[8,9]]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [0,1,2,3,4,5,6,7]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[[0,1],[2,3],[4,5],[6,7]]]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0,1,2,3],[4,5,6,7]]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0,1],[2,3],[4,5]]) self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0,1],[2,3],[4,5],[6,7],[8,9]]) def test_empty_zi(self): # Regression test for #880: empty array for zi crashes. x = self.generate((5,)) a = self.convert_dtype([1]) b = self.convert_dtype([1]) zi = self.convert_dtype([]) y, zf = lfilter(b, a, x, zi=zi) assert_array_almost_equal(y, x) assert_equal(zf.dtype, self.dtype) assert_equal(zf.size, 0) def test_lfiltic_bad_zi(self): # Regression test for #3699: bad initial conditions a = self.convert_dtype([1]) b = self.convert_dtype([1]) # "y" sets the datatype of zi, so it truncates if int zi = lfiltic(b, a, [1., 0]) zi_1 = lfiltic(b, a, [1, 0]) zi_2 = lfiltic(b, a, [True, False]) assert_array_equal(zi, zi_1) assert_array_equal(zi, zi_2) def test_short_x_FIR(self): # regression test for #5116 # x shorter than b, with non None zi fails a = self.convert_dtype([1]) b = self.convert_dtype([1, 0, -1]) zi = self.convert_dtype([2, 7]) x = self.convert_dtype([72]) ye = self.convert_dtype([74]) zfe = self.convert_dtype([7, -72]) y, zf = lfilter(b, a, x, zi=zi) assert_array_almost_equal(y, ye) assert_array_almost_equal(zf, zfe) def test_short_x_IIR(self): # regression test for #5116 # x shorter than b, with non None zi fails a = self.convert_dtype([1, 1]) b = self.convert_dtype([1, 0, -1]) zi = self.convert_dtype([2, 7]) x = self.convert_dtype([72]) ye = self.convert_dtype([74]) zfe = self.convert_dtype([-67, -72]) y, zf = lfilter(b, a, x, zi=zi) assert_array_almost_equal(y, ye) assert_array_almost_equal(zf, zfe) def test_do_not_modify_a_b_IIR(self): x = self.generate((6,)) b = self.convert_dtype([1, -1]) b0 = b.copy() a = self.convert_dtype([0.5, -0.5]) a0 = a.copy() y_r = self.convert_dtype([0, 2, 4, 6, 8, 10.]) y_f = lfilter(b, a, x) assert_array_almost_equal(y_f, y_r) assert_equal(b, b0) assert_equal(a, a0) def test_do_not_modify_a_b_FIR(self): x = self.generate((6,)) b = self.convert_dtype([1, 0, 1]) b0 = b.copy() a = self.convert_dtype([2]) a0 = a.copy() y_r = self.convert_dtype([0, 0.5, 1, 2, 3, 4.]) y_f = lfilter(b, a, x) assert_array_almost_equal(y_f, y_r) assert_equal(b, b0) assert_equal(a, a0) class TestLinearFilterFloat32(_TestLinearFilter): dtype = np.dtype('f') class TestLinearFilterFloat64(_TestLinearFilter): dtype = np.dtype('d') class TestLinearFilterFloatExtended(_TestLinearFilter): dtype = np.dtype('g') class TestLinearFilterComplex64(_TestLinearFilter): dtype = np.dtype('F') class TestLinearFilterComplex128(_TestLinearFilter): dtype = np.dtype('D') class TestLinearFilterComplexExtended(_TestLinearFilter): dtype = np.dtype('G') class TestLinearFilterDecimal(_TestLinearFilter): dtype = np.dtype('O') def type(self, x): return Decimal(str(x)) class TestLinearFilterObject(_TestLinearFilter): dtype = np.dtype('O') type = float def test_lfilter_bad_object(): # lfilter: object arrays with non-numeric objects raise TypeError. # Regression test for ticket #1452. assert_raises(TypeError, lfilter, [1.0], [1.0], [1.0, None, 2.0]) assert_raises(TypeError, lfilter, [1.0], [None], [1.0, 2.0, 3.0]) assert_raises(TypeError, lfilter, [None], [1.0], [1.0, 2.0, 3.0]) with assert_raises(ValueError, match='common type'): lfilter([1.], [1., 1.], ['a', 'b', 'c']) def test_lfilter_notimplemented_input(): # Should not crash, gh-7991 assert_raises(NotImplementedError, lfilter, [2,3], [4,5], [1,2,3,4,5]) @pytest.mark.parametrize('dt', [np.ubyte, np.byte, np.ushort, np.short, np.uint, int, np.ulonglong, np.ulonglong, np.float32, np.float64, np.longdouble, Decimal]) class TestCorrelateReal(object): def _setup_rank1(self, dt): a = np.linspace(0, 3, 4).astype(dt) b = np.linspace(1, 2, 2).astype(dt) y_r = np.array([0, 2, 5, 8, 3]).astype(dt) return a, b, y_r def equal_tolerance(self, res_dt): # default value of keyword decimal = 6 try: dt_info = np.finfo(res_dt) if hasattr(dt_info, 'resolution'): decimal = int(-0.5*np.log10(dt_info.resolution)) except Exception: pass return decimal def equal_tolerance_fft(self, res_dt): # FFT implementations convert longdouble arguments down to # double so don't expect better precision, see gh-9520 if res_dt == np.longdouble: return self.equal_tolerance(np.double) else: return self.equal_tolerance(res_dt) def test_method(self, dt): if dt == Decimal: method = choose_conv_method([Decimal(4)], [Decimal(3)]) assert_equal(method, 'direct') else: a, b, y_r = self._setup_rank3(dt) y_fft = correlate(a, b, method='fft') y_direct = correlate(a, b, method='direct') assert_array_almost_equal(y_r, y_fft, decimal=self.equal_tolerance_fft(y_fft.dtype)) assert_array_almost_equal(y_r, y_direct, decimal=self.equal_tolerance(y_direct.dtype)) assert_equal(y_fft.dtype, dt) assert_equal(y_direct.dtype, dt) def test_rank1_valid(self, dt): a, b, y_r = self._setup_rank1(dt) y = correlate(a, b, 'valid') assert_array_almost_equal(y, y_r[1:4]) assert_equal(y.dtype, dt) # See gh-5897 y = correlate(b, a, 'valid') assert_array_almost_equal(y, y_r[1:4][::-1]) assert_equal(y.dtype, dt) def test_rank1_same(self, dt): a, b, y_r = self._setup_rank1(dt) y = correlate(a, b, 'same') assert_array_almost_equal(y, y_r[:-1]) assert_equal(y.dtype, dt) def test_rank1_full(self, dt): a, b, y_r = self._setup_rank1(dt) y = correlate(a, b, 'full') assert_array_almost_equal(y, y_r) assert_equal(y.dtype, dt) def _setup_rank3(self, dt): a = np.linspace(0, 39, 40).reshape((2, 4, 5), order='F').astype( dt) b = np.linspace(0, 23, 24).reshape((2, 3, 4), order='F').astype( dt) y_r = array([[[0., 184., 504., 912., 1360., 888., 472., 160.], [46., 432., 1062., 1840., 2672., 1698., 864., 266.], [134., 736., 1662., 2768., 3920., 2418., 1168., 314.], [260., 952., 1932., 3056., 4208., 2580., 1240., 332.], [202., 664., 1290., 1984., 2688., 1590., 712., 150.], [114., 344., 642., 960., 1280., 726., 296., 38.]], [[23., 400., 1035., 1832., 2696., 1737., 904., 293.], [134., 920., 2166., 3680., 5280., 3306., 1640., 474.], [325., 1544., 3369., 5512., 7720., 4683., 2192., 535.], [571., 1964., 3891., 6064., 8272., 4989., 2324., 565.], [434., 1360., 2586., 3920., 5264., 3054., 1312., 230.], [241., 700., 1281., 1888., 2496., 1383., 532., 39.]], [[22., 214., 528., 916., 1332., 846., 430., 132.], [86., 484., 1098., 1832., 2600., 1602., 772., 206.], [188., 802., 1698., 2732., 3788., 2256., 1018., 218.], [308., 1006., 1950., 2996., 4052., 2400., 1078., 230.], [230., 692., 1290., 1928., 2568., 1458., 596., 78.], [126., 354., 636., 924., 1212., 654., 234., 0.]]], dtype=dt) return a, b, y_r def test_rank3_valid(self, dt): a, b, y_r = self._setup_rank3(dt) y = correlate(a, b, "valid") assert_array_almost_equal(y, y_r[1:2, 2:4, 3:5]) assert_equal(y.dtype, dt) # See gh-5897 y = correlate(b, a, "valid") assert_array_almost_equal(y, y_r[1:2, 2:4, 3:5][::-1, ::-1, ::-1]) assert_equal(y.dtype, dt) def test_rank3_same(self, dt): a, b, y_r = self._setup_rank3(dt) y = correlate(a, b, "same") assert_array_almost_equal(y, y_r[0:-1, 1:-1, 1:-2]) assert_equal(y.dtype, dt) def test_rank3_all(self, dt): a, b, y_r = self._setup_rank3(dt) y = correlate(a, b) assert_array_almost_equal(y, y_r) assert_equal(y.dtype, dt) class TestCorrelate(object): # Tests that don't depend on dtype def test_invalid_shapes(self): # By "invalid," we mean that no one # array has dimensions that are all at # least as large as the corresponding # dimensions of the other array. This # setup should throw a ValueError. a = np.arange(1, 7).reshape((2, 3)) b = np.arange(-6, 0).reshape((3, 2)) assert_raises(ValueError, correlate, *(a, b), **{'mode': 'valid'}) assert_raises(ValueError, correlate, *(b, a), **{'mode': 'valid'}) def test_invalid_params(self): a = [3, 4, 5] b = [1, 2, 3] assert_raises(ValueError, correlate, a, b, mode='spam') assert_raises(ValueError, correlate, a, b, mode='eggs', method='fft') assert_raises(ValueError, correlate, a, b, mode='ham', method='direct') assert_raises(ValueError, correlate, a, b, mode='full', method='bacon') assert_raises(ValueError, correlate, a, b, mode='same', method='bacon') def test_mismatched_dims(self): # Input arrays should have the same number of dimensions assert_raises(ValueError, correlate, [1], 2, method='direct') assert_raises(ValueError, correlate, 1, [2], method='direct') assert_raises(ValueError, correlate, [1], 2, method='fft') assert_raises(ValueError, correlate, 1, [2], method='fft') assert_raises(ValueError, correlate, [1], [[2]]) assert_raises(ValueError, correlate, [3], 2) def test_numpy_fastpath(self): a = [1, 2, 3] b = [4, 5] assert_allclose(correlate(a, b, mode='same'), [5, 14, 23]) a = [1, 2, 3] b = [4, 5, 6] assert_allclose(correlate(a, b, mode='same'), [17, 32, 23]) assert_allclose(correlate(a, b, mode='full'), [6, 17, 32, 23, 12]) assert_allclose(correlate(a, b, mode='valid'), [32]) @pytest.mark.parametrize('dt', [np.csingle, np.cdouble, np.clongdouble]) class TestCorrelateComplex(object): # The decimal precision to be used for comparing results. # This value will be passed as the 'decimal' keyword argument of # assert_array_almost_equal(). # Since correlate may chose to use FFT method which converts # longdoubles to doubles internally don't expect better precision # for longdouble than for double (see gh-9520). def decimal(self, dt): if dt == np.clongdouble: dt = np.cdouble return int(2 * np.finfo(dt).precision / 3) def _setup_rank1(self, dt, mode): np.random.seed(9) a = np.random.randn(10).astype(dt) a += 1j * np.random.randn(10).astype(dt) b = np.random.randn(8).astype(dt) b += 1j * np.random.randn(8).astype(dt) y_r = (correlate(a.real, b.real, mode=mode) + correlate(a.imag, b.imag, mode=mode)).astype(dt) y_r += 1j * (-correlate(a.real, b.imag, mode=mode) + correlate(a.imag, b.real, mode=mode)) return a, b, y_r def test_rank1_valid(self, dt): a, b, y_r = self._setup_rank1(dt, 'valid') y = correlate(a, b, 'valid') assert_array_almost_equal(y, y_r, decimal=self.decimal(dt)) assert_equal(y.dtype, dt) # See gh-5897 y = correlate(b, a, 'valid') assert_array_almost_equal(y, y_r[::-1].conj(), decimal=self.decimal(dt)) assert_equal(y.dtype, dt) def test_rank1_same(self, dt): a, b, y_r = self._setup_rank1(dt, 'same') y = correlate(a, b, 'same') assert_array_almost_equal(y, y_r, decimal=self.decimal(dt)) assert_equal(y.dtype, dt) def test_rank1_full(self, dt): a, b, y_r = self._setup_rank1(dt, 'full') y = correlate(a, b, 'full') assert_array_almost_equal(y, y_r, decimal=self.decimal(dt)) assert_equal(y.dtype, dt) def test_swap_full(self, dt): d = np.array([0.+0.j, 1.+1.j, 2.+2.j], dtype=dt) k = np.array([1.+3.j, 2.+4.j, 3.+5.j, 4.+6.j], dtype=dt) y = correlate(d, k) assert_equal(y, [0.+0.j, 10.-2.j, 28.-6.j, 22.-6.j, 16.-6.j, 8.-4.j]) def test_swap_same(self, dt): d = [0.+0.j, 1.+1.j, 2.+2.j] k = [1.+3.j, 2.+4.j, 3.+5.j, 4.+6.j] y = correlate(d, k, mode="same") assert_equal(y, [10.-2.j, 28.-6.j, 22.-6.j]) def test_rank3(self, dt): a = np.random.randn(10, 8, 6).astype(dt) a += 1j * np.random.randn(10, 8, 6).astype(dt) b = np.random.randn(8, 6, 4).astype(dt) b += 1j * np.random.randn(8, 6, 4).astype(dt) y_r = (correlate(a.real, b.real) + correlate(a.imag, b.imag)).astype(dt) y_r += 1j * (-correlate(a.real, b.imag) + correlate(a.imag, b.real)) y = correlate(a, b, 'full') assert_array_almost_equal(y, y_r, decimal=self.decimal(dt) - 1) assert_equal(y.dtype, dt) def test_rank0(self, dt): a = np.array(np.random.randn()).astype(dt) a += 1j * np.array(np.random.randn()).astype(dt) b = np.array(np.random.randn()).astype(dt) b += 1j * np.array(np.random.randn()).astype(dt) y_r = (correlate(a.real, b.real) + correlate(a.imag, b.imag)).astype(dt) y_r += 1j * (-correlate(a.real, b.imag) + correlate(a.imag, b.real)) y = correlate(a, b, 'full') assert_array_almost_equal(y, y_r, decimal=self.decimal(dt) - 1) assert_equal(y.dtype, dt) assert_equal(correlate([1], [2j]), correlate(1, 2j)) assert_equal(correlate([2j], [3j]), correlate(2j, 3j)) assert_equal(correlate([3j], [4]), correlate(3j, 4)) class TestCorrelate2d(object): def test_consistency_correlate_funcs(self): # Compare np.correlate, signal.correlate, signal.correlate2d a = np.arange(5) b = np.array([3.2, 1.4, 3]) for mode in ['full', 'valid', 'same']: assert_almost_equal(np.correlate(a, b, mode=mode), signal.correlate(a, b, mode=mode)) assert_almost_equal(np.squeeze(signal.correlate2d([a], [b], mode=mode)), signal.correlate(a, b, mode=mode)) # See gh-5897 if mode == 'valid': assert_almost_equal(np.correlate(b, a, mode=mode), signal.correlate(b, a, mode=mode)) assert_almost_equal(np.squeeze(signal.correlate2d([b], [a], mode=mode)), signal.correlate(b, a, mode=mode)) def test_invalid_shapes(self): # By "invalid," we mean that no one # array has dimensions that are all at # least as large as the corresponding # dimensions of the other array. This # setup should throw a ValueError. a = np.arange(1, 7).reshape((2, 3)) b = np.arange(-6, 0).reshape((3, 2)) assert_raises(ValueError, signal.correlate2d, *(a, b), **{'mode': 'valid'}) assert_raises(ValueError, signal.correlate2d, *(b, a), **{'mode': 'valid'}) def test_complex_input(self): assert_equal(signal.correlate2d([[1]], [[2j]]), -2j) assert_equal(signal.correlate2d([[2j]], [[3j]]), 6) assert_equal(signal.correlate2d([[3j]], [[4]]), 12j) class TestLFilterZI(object): def test_basic(self): a = np.array([1.0, -1.0, 0.5]) b = np.array([1.0, 0.0, 2.0]) zi_expected = np.array([5.0, -1.0]) zi = lfilter_zi(b, a) assert_array_almost_equal(zi, zi_expected) def test_scale_invariance(self): # Regression test. There was a bug in which b was not correctly # rescaled when a[0] was nonzero. b = np.array([2, 8, 5]) a = np.array([1, 1, 8]) zi1 = lfilter_zi(b, a) zi2 = lfilter_zi(2*b, 2*a) assert_allclose(zi2, zi1, rtol=1e-12) class TestFiltFilt(object): filtfilt_kind = 'tf' def filtfilt(self, zpk, x, axis=-1, padtype='odd', padlen=None, method='pad', irlen=None): if self.filtfilt_kind == 'tf': b, a = zpk2tf(*zpk) return filtfilt(b, a, x, axis, padtype, padlen, method, irlen) elif self.filtfilt_kind == 'sos': sos = zpk2sos(*zpk) return sosfiltfilt(sos, x, axis, padtype, padlen) def test_basic(self): zpk = tf2zpk([1, 2, 3], [1, 2, 3]) out = self.filtfilt(zpk, np.arange(12)) assert_allclose(out, arange(12), atol=1e-11) def test_sine(self): rate = 2000 t = np.linspace(0, 1.0, rate + 1) # A signal with low frequency and a high frequency. xlow = np.sin(5 * 2 * np.pi * t) xhigh = np.sin(250 * 2 * np.pi * t) x = xlow + xhigh zpk = butter(8, 0.125, output='zpk') # r is the magnitude of the largest pole. r = np.abs(zpk[1]).max() eps = 1e-5 # n estimates the number of steps for the # transient to decay by a factor of eps. n = int(np.ceil(np.log(eps) / np.log(r))) # High order lowpass filter... y = self.filtfilt(zpk, x, padlen=n) # Result should be just xlow. err = np.abs(y - xlow).max() assert_(err < 1e-4) # A 2D case. x2d = np.vstack([xlow, xlow + xhigh]) y2d = self.filtfilt(zpk, x2d, padlen=n, axis=1) assert_equal(y2d.shape, x2d.shape) err = np.abs(y2d - xlow).max() assert_(err < 1e-4) # Use the previous result to check the use of the axis keyword. # (Regression test for ticket #1620) y2dt = self.filtfilt(zpk, x2d.T, padlen=n, axis=0) assert_equal(y2d, y2dt.T) def test_axis(self): # Test the 'axis' keyword on a 3D array. x = np.arange(10.0 * 11.0 * 12.0).reshape(10, 11, 12) zpk = butter(3, 0.125, output='zpk') y0 = self.filtfilt(zpk, x, padlen=0, axis=0) y1 = self.filtfilt(zpk, np.swapaxes(x, 0, 1), padlen=0, axis=1) assert_array_equal(y0, np.swapaxes(y1, 0, 1)) y2 = self.filtfilt(zpk, np.swapaxes(x, 0, 2), padlen=0, axis=2) assert_array_equal(y0, np.swapaxes(y2, 0, 2)) def test_acoeff(self): if self.filtfilt_kind != 'tf': return # only necessary for TF # test for 'a' coefficient as single number out = signal.filtfilt([.5, .5], 1, np.arange(10)) assert_allclose(out, np.arange(10), rtol=1e-14, atol=1e-14) def test_gust_simple(self): if self.filtfilt_kind != 'tf': pytest.skip('gust only implemented for TF systems') # The input array has length 2. The exact solution for this case # was computed "by hand". x = np.array([1.0, 2.0]) b = np.array([0.5]) a = np.array([1.0, -0.5]) y, z1, z2 = _filtfilt_gust(b, a, x) assert_allclose([z1[0], z2[0]], [0.3*x[0] + 0.2*x[1], 0.2*x[0] + 0.3*x[1]]) assert_allclose(y, [z1[0] + 0.25*z2[0] + 0.25*x[0] + 0.125*x[1], 0.25*z1[0] + z2[0] + 0.125*x[0] + 0.25*x[1]]) def test_gust_scalars(self): if self.filtfilt_kind != 'tf': pytest.skip('gust only implemented for TF systems') # The filter coefficients are both scalars, so the filter simply # multiplies its input by b/a. When it is used in filtfilt, the # factor is (b/a)**2. x = np.arange(12) b = 3.0 a = 2.0 y = filtfilt(b, a, x, method="gust") expected = (b/a)**2 * x assert_allclose(y, expected) class TestSOSFiltFilt(TestFiltFilt): filtfilt_kind = 'sos' def test_equivalence(self): """Test equivalence between sosfiltfilt and filtfilt""" x = np.random.RandomState(0).randn(1000) for order in range(1, 6): zpk = signal.butter(order, 0.35, output='zpk') b, a = zpk2tf(*zpk) sos = zpk2sos(*zpk) y = filtfilt(b, a, x) y_sos = sosfiltfilt(sos, x) assert_allclose(y, y_sos, atol=1e-12, err_msg='order=%s' % order) def filtfilt_gust_opt(b, a, x): """ An alternative implementation of filtfilt with Gustafsson edges. This function computes the same result as `scipy.signal.signaltools._filtfilt_gust`, but only 1-d arrays are accepted. The problem is solved using `fmin` from `scipy.optimize`. `_filtfilt_gust` is significanly faster than this implementation. """ def filtfilt_gust_opt_func(ics, b, a, x): """Objective function used in filtfilt_gust_opt.""" m = max(len(a), len(b)) - 1 z0f = ics[:m] z0b = ics[m:] y_f = lfilter(b, a, x, zi=z0f)[0] y_fb = lfilter(b, a, y_f[::-1], zi=z0b)[0][::-1] y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1] y_bf = lfilter(b, a, y_b, zi=z0f)[0] value = np.sum((y_fb - y_bf)**2) return value m = max(len(a), len(b)) - 1 zi = lfilter_zi(b, a) ics = np.concatenate((x[:m].mean()*zi, x[-m:].mean()*zi)) result = fmin(filtfilt_gust_opt_func, ics, args=(b, a, x), xtol=1e-10, ftol=1e-12, maxfun=10000, maxiter=10000, full_output=True, disp=False) opt, fopt, niter, funcalls, warnflag = result if warnflag > 0: raise RuntimeError("minimization failed in filtfilt_gust_opt: " "warnflag=%d" % warnflag) z0f = opt[:m] z0b = opt[m:] # Apply the forward-backward filter using the computed initial # conditions. y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1] y = lfilter(b, a, y_b, zi=z0f)[0] return y, z0f, z0b def check_filtfilt_gust(b, a, shape, axis, irlen=None): # Generate x, the data to be filtered. np.random.seed(123) x = np.random.randn(*shape) # Apply filtfilt to x. This is the main calculation to be checked. y = filtfilt(b, a, x, axis=axis, method="gust", irlen=irlen) # Also call the private function so we can test the ICs. yg, zg1, zg2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen) # filtfilt_gust_opt is an independent implementation that gives the # expected result, but it only handles 1-d arrays, so use some looping # and reshaping shenanigans to create the expected output arrays. xx = np.swapaxes(x, axis, -1) out_shape = xx.shape[:-1] yo = np.empty_like(xx) m = max(len(a), len(b)) - 1 zo1 = np.empty(out_shape + (m,)) zo2 = np.empty(out_shape + (m,)) for indx in product(*[range(d) for d in out_shape]): yo[indx], zo1[indx], zo2[indx] = filtfilt_gust_opt(b, a, xx[indx]) yo = np.swapaxes(yo, -1, axis) zo1 = np.swapaxes(zo1, -1, axis) zo2 = np.swapaxes(zo2, -1, axis) assert_allclose(y, yo, rtol=1e-9, atol=1e-10) assert_allclose(yg, yo, rtol=1e-9, atol=1e-10) assert_allclose(zg1, zo1, rtol=1e-9, atol=1e-10) assert_allclose(zg2, zo2, rtol=1e-9, atol=1e-10) def test_choose_conv_method(): for mode in ['valid', 'same', 'full']: for ndims in [1, 2]: n, k, true_method = 8, 6, 'direct' x = np.random.randn(*((n,) * ndims)) h = np.random.randn(*((k,) * ndims)) method = choose_conv_method(x, h, mode=mode) assert_equal(method, true_method) method_try, times = choose_conv_method(x, h, mode=mode, measure=True) assert_(method_try in {'fft', 'direct'}) assert_(type(times) is dict) assert_('fft' in times.keys() and 'direct' in times.keys()) n = 10 for not_fft_conv_supp in ["complex256", "complex192"]: if hasattr(np, not_fft_conv_supp): x = np.ones(n, dtype=not_fft_conv_supp) h = x.copy() assert_equal(choose_conv_method(x, h, mode=mode), 'direct') x = np.array([2**51], dtype=np.int64) h = x.copy() assert_equal(choose_conv_method(x, h, mode=mode), 'direct') x = [Decimal(3), Decimal(2)] h = [Decimal(1), Decimal(4)] assert_equal(choose_conv_method(x, h, mode=mode), 'direct') def test_filtfilt_gust(): # Design a filter. z, p, k = signal.ellip(3, 0.01, 120, 0.0875, output='zpk') # Find the approximate impulse response length of the filter. eps = 1e-10 r = np.max(np.abs(p)) approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r))) np.random.seed(123) b, a = zpk2tf(z, p, k) for irlen in [None, approx_impulse_len]: signal_len = 5 * approx_impulse_len # 1-d test case check_filtfilt_gust(b, a, (signal_len,), 0, irlen) # 3-d test case; test each axis. for axis in range(3): shape = [2, 2, 2] shape[axis] = signal_len check_filtfilt_gust(b, a, shape, axis, irlen) # Test case with length less than 2*approx_impulse_len. # In this case, `filtfilt_gust` should behave the same as if # `irlen=None` was given. length = 2*approx_impulse_len - 50 check_filtfilt_gust(b, a, (length,), 0, approx_impulse_len) class TestDecimate(object): def test_bad_args(self): x = np.arange(12) assert_raises(TypeError, signal.decimate, x, q=0.5, n=1) assert_raises(TypeError, signal.decimate, x, q=2, n=0.5) def test_basic_IIR(self): x = np.arange(12) y = signal.decimate(x, 2, n=1, ftype='iir', zero_phase=False).round() assert_array_equal(y, x[::2]) def test_basic_FIR(self): x = np.arange(12) y = signal.decimate(x, 2, n=1, ftype='fir', zero_phase=False).round() assert_array_equal(y, x[::2]) def test_shape(self): # Regression test for ticket #1480. z = np.zeros((30, 30)) d0 = signal.decimate(z, 2, axis=0, zero_phase=False) assert_equal(d0.shape, (15, 30)) d1 = signal.decimate(z, 2, axis=1, zero_phase=False) assert_equal(d1.shape, (30, 15)) def test_phaseshift_FIR(self): with suppress_warnings() as sup: sup.filter(BadCoefficients, "Badly conditioned filter") self._test_phaseshift(method='fir', zero_phase=False) def test_zero_phase_FIR(self): with suppress_warnings() as sup: sup.filter(BadCoefficients, "Badly conditioned filter") self._test_phaseshift(method='fir', zero_phase=True) def test_phaseshift_IIR(self): self._test_phaseshift(method='iir', zero_phase=False) def test_zero_phase_IIR(self): self._test_phaseshift(method='iir', zero_phase=True) def _test_phaseshift(self, method, zero_phase): rate = 120 rates_to = [15, 20, 30, 40] # q = 8, 6, 4, 3 t_tot = int(100) # Need to let antialiasing filters settle t = np.arange(rate*t_tot+1) / float(rate) # Sinusoids at 0.8*nyquist, windowed to avoid edge artifacts freqs = np.array(rates_to) * 0.8 / 2 d = (np.exp(1j * 2 * np.pi * freqs[:, np.newaxis] * t) * signal.windows.tukey(t.size, 0.1)) for rate_to in rates_to: q = rate // rate_to t_to = np.arange(rate_to*t_tot+1) / float(rate_to) d_tos = (np.exp(1j * 2 * np.pi * freqs[:, np.newaxis] * t_to) * signal.windows.tukey(t_to.size, 0.1)) # Set up downsampling filters, match v0.17 defaults if method == 'fir': n = 30 system = signal.dlti(signal.firwin(n + 1, 1. / q, window='hamming'), 1.) elif method == 'iir': n = 8 wc = 0.8*np.pi/q system = signal.dlti(*signal.cheby1(n, 0.05, wc/np.pi)) # Calculate expected phase response, as unit complex vector if zero_phase is False: _, h_resps = signal.freqz(system.num, system.den, freqs/rate*2*np.pi) h_resps /= np.abs(h_resps) else: h_resps = np.ones_like(freqs) y_resamps = signal.decimate(d.real, q, n, ftype=system, zero_phase=zero_phase) # Get phase from complex inner product, like CSD h_resamps = np.sum(d_tos.conj() * y_resamps, axis=-1) h_resamps /= np.abs(h_resamps) subnyq = freqs < 0.5*rate_to # Complex vectors should be aligned, only compare below nyquist assert_allclose(np.angle(h_resps.conj()*h_resamps)[subnyq], 0, atol=1e-3, rtol=1e-3) def test_auto_n(self): # Test that our value of n is a reasonable choice (depends on # the downsampling factor) sfreq = 100. n = 1000 t = np.arange(n) / sfreq # will alias for decimations (>= 15) x = np.sqrt(2. / n) * np.sin(2 * np.pi * (sfreq / 30.) * t) assert_allclose(np.linalg.norm(x), 1., rtol=1e-3) x_out = signal.decimate(x, 30, ftype='fir') assert_array_less(np.linalg.norm(x_out), 0.01) class TestHilbert(object): def test_bad_args(self): x = np.array([1.0 + 0.0j]) assert_raises(ValueError, hilbert, x) x = np.arange(8.0) assert_raises(ValueError, hilbert, x, N=0) def test_hilbert_theoretical(self): # test cases by Ariel Rokem decimal = 14 pi = np.pi t = np.arange(0, 2 * pi, pi / 256) a0 = np.sin(t) a1 = np.cos(t) a2 = np.sin(2 * t) a3 = np.cos(2 * t) a = np.vstack([a0, a1, a2, a3]) h = hilbert(a) h_abs = np.abs(h) h_angle = np.angle(h) h_real = np.real(h) # The real part should be equal to the original signals: assert_almost_equal(h_real, a, decimal) # The absolute value should be one everywhere, for this input: assert_almost_equal(h_abs, np.ones(a.shape), decimal) # For the 'slow' sine - the phase should go from -pi/2 to pi/2 in # the first 256 bins: assert_almost_equal(h_angle[0, :256], np.arange(-pi / 2, pi / 2, pi / 256), decimal) # For the 'slow' cosine - the phase should go from 0 to pi in the # same interval: assert_almost_equal( h_angle[1, :256], np.arange(0, pi, pi / 256), decimal) # The 'fast' sine should make this phase transition in half the time: assert_almost_equal(h_angle[2, :128], np.arange(-pi / 2, pi / 2, pi / 128), decimal) # Ditto for the 'fast' cosine: assert_almost_equal( h_angle[3, :128], np.arange(0, pi, pi / 128), decimal) # The imaginary part of hilbert(cos(t)) = sin(t) Wikipedia assert_almost_equal(h[1].imag, a0, decimal) def test_hilbert_axisN(self): # tests for axis and N arguments a = np.arange(18).reshape(3, 6) # test axis aa = hilbert(a, axis=-1) assert_equal(hilbert(a.T, axis=0), aa.T) # test 1d assert_almost_equal(hilbert(a[0]), aa[0], 14) # test N aan = hilbert(a, N=20, axis=-1) assert_equal(aan.shape, [3, 20]) assert_equal(hilbert(a.T, N=20, axis=0).shape, [20, 3]) # the next test is just a regression test, # no idea whether numbers make sense a0hilb = np.array([0.000000000000000e+00 - 1.72015830311905j, 1.000000000000000e+00 - 2.047794505137069j, 1.999999999999999e+00 - 2.244055555687583j, 3.000000000000000e+00 - 1.262750302935009j, 4.000000000000000e+00 - 1.066489252384493j, 5.000000000000000e+00 + 2.918022706971047j, 8.881784197001253e-17 + 3.845658908989067j, -9.444121133484362e-17 + 0.985044202202061j, -1.776356839400251e-16 + 1.332257797702019j, -3.996802888650564e-16 + 0.501905089898885j, 1.332267629550188e-16 + 0.668696078880782j, -1.192678053963799e-16 + 0.235487067862679j, -1.776356839400251e-16 + 0.286439612812121j, 3.108624468950438e-16 + 0.031676888064907j, 1.332267629550188e-16 - 0.019275656884536j, -2.360035624836702e-16 - 0.1652588660287j, 0.000000000000000e+00 - 0.332049855010597j, 3.552713678800501e-16 - 0.403810179797771j, 8.881784197001253e-17 - 0.751023775297729j, 9.444121133484362e-17 - 0.79252210110103j]) assert_almost_equal(aan[0], a0hilb, 14, 'N regression') class TestHilbert2(object): def test_bad_args(self): # x must be real. x = np.array([[1.0 + 0.0j]]) assert_raises(ValueError, hilbert2, x) # x must be rank 2. x = np.arange(24).reshape(2, 3, 4) assert_raises(ValueError, hilbert2, x) # Bad value for N. x = np.arange(16).reshape(4, 4) assert_raises(ValueError, hilbert2, x, N=0) assert_raises(ValueError, hilbert2, x, N=(2, 0)) assert_raises(ValueError, hilbert2, x, N=(2,)) class TestPartialFractionExpansion(object): def test_invresz_one_coefficient_bug(self): # Regression test for issue in gh-4646. r = [1] p = [2] k = [0] a_expected = [1.0, 0.0] b_expected = [1.0, -2.0] a_observed, b_observed = invresz(r, p, k) assert_allclose(a_observed, a_expected) assert_allclose(b_observed, b_expected) def test_invres_distinct_roots(self): # This test was inspired by github issue 2496. r = [3 / 10, -1 / 6, -2 / 15] p = [0, -2, -5] k = [] a_expected = [1, 3] b_expected = [1, 7, 10, 0] a_observed, b_observed = invres(r, p, k) assert_allclose(a_observed, a_expected) assert_allclose(b_observed, b_expected) rtypes = ('avg', 'mean', 'min', 'minimum', 'max', 'maximum') # With the default tolerance, the rtype does not matter # for this example. for rtype in rtypes: a_observed, b_observed = invres(r, p, k, rtype=rtype) assert_allclose(a_observed, a_expected) assert_allclose(b_observed, b_expected) # With unrealistically large tolerances, repeated roots may be inferred # and the rtype comes into play. ridiculous_tolerance = 1e10 for rtype in rtypes: a, b = invres(r, p, k, tol=ridiculous_tolerance, rtype=rtype) def test_invres_repeated_roots(self): r = [3 / 20, -7 / 36, -1 / 6, 2 / 45] p = [0, -2, -2, -5] k = [] a_expected = [1, 3] b_expected = [1, 9, 24, 20, 0] rtypes = ('avg', 'mean', 'min', 'minimum', 'max', 'maximum') for rtype in rtypes: a_observed, b_observed = invres(r, p, k, rtype=rtype) assert_allclose(a_observed, a_expected) assert_allclose(b_observed, b_expected) def test_invres_bad_rtype(self): r = [3 / 20, -7 / 36, -1 / 6, 2 / 45] p = [0, -2, -2, -5] k = [] assert_raises(ValueError, invres, r, p, k, rtype='median') class TestVectorstrength(object): def test_single_1dperiod(self): events = np.array([.5]) period = 5. targ_strength = 1. targ_phase = .1 strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 0) assert_equal(phase.ndim, 0) assert_almost_equal(strength, targ_strength) assert_almost_equal(phase, 2 * np.pi * targ_phase) def test_single_2dperiod(self): events = np.array([.5]) period = [1, 2, 5.] targ_strength = [1.] * 3 targ_phase = np.array([.5, .25, .1]) strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 1) assert_equal(phase.ndim, 1) assert_array_almost_equal(strength, targ_strength) assert_almost_equal(phase, 2 * np.pi * targ_phase) def test_equal_1dperiod(self): events = np.array([.25, .25, .25, .25, .25, .25]) period = 2 targ_strength = 1. targ_phase = .125 strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 0) assert_equal(phase.ndim, 0) assert_almost_equal(strength, targ_strength) assert_almost_equal(phase, 2 * np.pi * targ_phase) def test_equal_2dperiod(self): events = np.array([.25, .25, .25, .25, .25, .25]) period = [1, 2, ] targ_strength = [1.] * 2 targ_phase = np.array([.25, .125]) strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 1) assert_equal(phase.ndim, 1) assert_almost_equal(strength, targ_strength) assert_almost_equal(phase, 2 * np.pi * targ_phase) def test_spaced_1dperiod(self): events = np.array([.1, 1.1, 2.1, 4.1, 10.1]) period = 1 targ_strength = 1. targ_phase = .1 strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 0) assert_equal(phase.ndim, 0) assert_almost_equal(strength, targ_strength) assert_almost_equal(phase, 2 * np.pi * targ_phase) def test_spaced_2dperiod(self): events = np.array([.1, 1.1, 2.1, 4.1, 10.1]) period = [1, .5] targ_strength = [1.] * 2 targ_phase = np.array([.1, .2]) strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 1) assert_equal(phase.ndim, 1) assert_almost_equal(strength, targ_strength) assert_almost_equal(phase, 2 * np.pi * targ_phase) def test_partial_1dperiod(self): events = np.array([.25, .5, .75]) period = 1 targ_strength = 1. / 3. targ_phase = .5 strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 0) assert_equal(phase.ndim, 0) assert_almost_equal(strength, targ_strength) assert_almost_equal(phase, 2 * np.pi * targ_phase) def test_partial_2dperiod(self): events = np.array([.25, .5, .75]) period = [1., 1., 1., 1.] targ_strength = [1. / 3.] * 4 targ_phase = np.array([.5, .5, .5, .5]) strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 1) assert_equal(phase.ndim, 1) assert_almost_equal(strength, targ_strength) assert_almost_equal(phase, 2 * np.pi * targ_phase) def test_opposite_1dperiod(self): events = np.array([0, .25, .5, .75]) period = 1. targ_strength = 0 strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 0) assert_equal(phase.ndim, 0) assert_almost_equal(strength, targ_strength) def test_opposite_2dperiod(self): events = np.array([0, .25, .5, .75]) period = [1.] * 10 targ_strength = [0.] * 10 strength, phase = vectorstrength(events, period) assert_equal(strength.ndim, 1) assert_equal(phase.ndim, 1) assert_almost_equal(strength, targ_strength) def test_2d_events_ValueError(self): events = np.array([[1, 2]]) period = 1. assert_raises(ValueError, vectorstrength, events, period) def test_2d_period_ValueError(self): events = 1. period = np.array([[1]]) assert_raises(ValueError, vectorstrength, events, period) def test_zero_period_ValueError(self): events = 1. period = 0 assert_raises(ValueError, vectorstrength, events, period) def test_negative_period_ValueError(self): events = 1. period = -1 assert_raises(ValueError, vectorstrength, events, period) class TestSOSFilt(object): # For sosfilt we only test a single datatype. Since sosfilt wraps # to lfilter under the hood, it's hopefully good enough to ensure # lfilter is extensively tested. dt = np.float64 # The test_rank* tests are pulled from _TestLinearFilter def test_rank1(self): x = np.linspace(0, 5, 6).astype(self.dt) b = np.array([1, -1]).astype(self.dt) a = np.array([0.5, -0.5]).astype(self.dt) # Test simple IIR y_r = np.array([0, 2, 4, 6, 8, 10.]).astype(self.dt) assert_array_almost_equal(sosfilt(tf2sos(b, a), x), y_r) # Test simple FIR b = np.array([1, 1]).astype(self.dt) # NOTE: This was changed (rel. to TestLinear...) to add a pole @zero: a = np.array([1, 0]).astype(self.dt) y_r = np.array([0, 1, 3, 5, 7, 9.]).astype(self.dt) assert_array_almost_equal(sosfilt(tf2sos(b, a), x), y_r) b = [1, 1, 0] a = [1, 0, 0] x = np.ones(8) sos = np.concatenate((b, a)) sos.shape = (1, 6) y = sosfilt(sos, x) assert_allclose(y, [1, 2, 2, 2, 2, 2, 2, 2]) def test_rank2(self): shape = (4, 3) x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) x = x.astype(self.dt) b = np.array([1, -1]).astype(self.dt) a = np.array([0.5, 0.5]).astype(self.dt) y_r2_a0 = np.array([[0, 2, 4], [6, 4, 2], [0, 2, 4], [6, 4, 2]], dtype=self.dt) y_r2_a1 = np.array([[0, 2, 0], [6, -4, 6], [12, -10, 12], [18, -16, 18]], dtype=self.dt) y = sosfilt(tf2sos(b, a), x, axis=0) assert_array_almost_equal(y_r2_a0, y) y = sosfilt(tf2sos(b, a), x, axis=1) assert_array_almost_equal(y_r2_a1, y) def test_rank3(self): shape = (4, 3, 2) x = np.linspace(0, np.prod(shape) - 1, np.prod(shape)).reshape(shape) b = np.array([1, -1]).astype(self.dt) a = np.array([0.5, 0.5]).astype(self.dt) # Test last axis y = sosfilt(tf2sos(b, a), x) for i in range(x.shape[0]): for j in range(x.shape[1]): assert_array_almost_equal(y[i, j], lfilter(b, a, x[i, j])) def test_initial_conditions(self): b1, a1 = signal.butter(2, 0.25, 'low') b2, a2 = signal.butter(2, 0.75, 'low') b3, a3 = signal.butter(2, 0.75, 'low') b = np.convolve(np.convolve(b1, b2), b3) a = np.convolve(np.convolve(a1, a2), a3) sos = np.array((np.r_[b1, a1], np.r_[b2, a2], np.r_[b3, a3])) x = np.random.rand(50) # Stopping filtering and continuing y_true, zi = lfilter(b, a, x[:20], zi=np.zeros(6)) y_true = np.r_[y_true, lfilter(b, a, x[20:], zi=zi)[0]] assert_allclose(y_true, lfilter(b, a, x)) y_sos, zi = sosfilt(sos, x[:20], zi=np.zeros((3, 2))) y_sos = np.r_[y_sos, sosfilt(sos, x[20:], zi=zi)[0]] assert_allclose(y_true, y_sos) # Use a step function zi = sosfilt_zi(sos) x = np.ones(8) y, zf = sosfilt(sos, x, zi=zi) assert_allclose(y, np.ones(8)) assert_allclose(zf, zi) # Initial condition shape matching x.shape = (1, 1) + x.shape # 3D assert_raises(ValueError, sosfilt, sos, x, zi=zi) zi_nd = zi.copy() zi_nd.shape = (zi.shape[0], 1, 1, zi.shape[-1]) assert_raises(ValueError, sosfilt, sos, x, zi=zi_nd[:, :, :, [0, 1, 1]]) y, zf = sosfilt(sos, x, zi=zi_nd) assert_allclose(y[0, 0], np.ones(8)) assert_allclose(zf[:, 0, 0, :], zi) def test_initial_conditions_3d_axis1(self): # Test the use of zi when sosfilt is applied to axis 1 of a 3-d input. # Input array is x. x = np.random.RandomState(159).randint(0, 5, size=(2, 15, 3)) # Design a filter in ZPK format and convert to SOS zpk = signal.butter(6, 0.35, output='zpk') sos = zpk2sos(*zpk) nsections = sos.shape[0] # Filter along this axis. axis = 1 # Initial conditions, all zeros. shp = list(x.shape) shp[axis] = 2 shp = [nsections] + shp z0 = np.zeros(shp) # Apply the filter to x. yf, zf = sosfilt(sos, x, axis=axis, zi=z0) # Apply the filter to x in two stages. y1, z1 = sosfilt(sos, x[:, :5, :], axis=axis, zi=z0) y2, z2 = sosfilt(sos, x[:, 5:, :], axis=axis, zi=z1) # y should equal yf, and z2 should equal zf. y = np.concatenate((y1, y2), axis=axis) assert_allclose(y, yf, rtol=1e-10, atol=1e-13) assert_allclose(z2, zf, rtol=1e-10, atol=1e-13) # let's try the "step" initial condition zi = sosfilt_zi(sos) zi.shape = [nsections, 1, 2, 1] zi = zi * x[:, 0:1, :] y = sosfilt(sos, x, axis=axis, zi=zi)[0] # check it against the TF form b, a = zpk2tf(*zpk) zi = lfilter_zi(b, a) zi.shape = [1, zi.size, 1] zi = zi * x[:, 0:1, :] y_tf = lfilter(b, a, x, axis=axis, zi=zi)[0] assert_allclose(y, y_tf, rtol=1e-10, atol=1e-13) def test_bad_zi_shape(self): # The shape of zi is checked before using any values in the # arguments, so np.empty is fine for creating the arguments. x = np.empty((3, 15, 3)) sos = np.empty((4, 6)) zi = np.empty((4, 3, 3, 2)) # Correct shape is (4, 3, 2, 3) assert_raises(ValueError, sosfilt, sos, x, zi=zi, axis=1) def test_sosfilt_zi(self): sos = signal.butter(6, 0.2, output='sos') zi = sosfilt_zi(sos) y, zf = sosfilt(sos, np.ones(40), zi=zi) assert_allclose(zf, zi, rtol=1e-13) # Expected steady state value of the step response of this filter: ss = np.prod(sos[:, :3].sum(axis=-1) / sos[:, 3:].sum(axis=-1)) assert_allclose(y, ss, rtol=1e-13) class TestDeconvolve(object): def test_basic(self): # From docstring example original = [0, 1, 0, 0, 1, 1, 0, 0] impulse_response = [2, 1] recorded = [0, 2, 1, 0, 2, 3, 1, 0, 0] recovered, remainder = signal.deconvolve(recorded, impulse_response) assert_allclose(recovered, original)
xbmcmegapack/plugin.video.megapack.dev
refs/heads/master
resources/lib/menus/home_languages_limburgan.py
1
#!/usr/bin/python # -*- coding: utf-8 -*- """ This file is part of XBMC Mega Pack Addon. Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 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/gpl-3.0.html """ class Languages_Limburgan(): '''Class that manages this specific menu context.''' def open(self, plugin, menu): menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels", "Events", "Live", "Movies", "Sports", "TVShows"], languages=["Limburgan"]))
benssson/flatbuffers
refs/heads/master
tests/MyGame/Example/Color.py
23
# automatically generated by the FlatBuffers compiler, do not modify # namespace: Example class Color(object): Red = 1 Green = 2 Blue = 8
qwertzuhr/2015_Data_Analyst_Project_3
refs/heads/master
Lesson_5_Analyzing_Data/14-Using_push/push.py
4
#!/usr/bin/env python """ $push is similar to $addToSet. The difference is that rather than accumulating only unique values it aggregates all values into an array. Using an aggregation query, count the number of tweets for each user. In the same $group stage, use $push to accumulate all the tweet texts for each user. Limit your output to the 5 users with the most tweets. Your result documents should include only the fields: "_id" (screen name of user), "count" (number of tweets found for the user), "tweet_texts" (a list of the tweet texts found for the user). Please modify only the 'make_pipeline' function so that it creates and returns an aggregation pipeline that can be passed to the MongoDB aggregate function. As in our examples in this lesson, the aggregation pipeline should be a list of one or more dictionary objects. Please review the lesson examples if you are unsure of the syntax. Your code will be run against a MongoDB instance that we have provided. If you want to run this code locally on your machine, you have to install MongoDB, download and insert the dataset. For instructions related to MongoDB setup and datasets please see Course Materials. Please note that the dataset you are using here is a smaller version of the twitter dataset used in examples in this lesson. If you attempt some of the same queries that we looked at in the lesson examples, your results will be different. """ def get_db(db_name): from pymongo import MongoClient client = MongoClient('localhost:27017') db = client[db_name] return db def make_pipeline(): # complete the aggregation pipeline pipeline = [{"$group": {"_id": "$user.screen_name", "count": {"$sum": 1}, "tweet_texts": {"$push": "$text"}}}, {"$sort": {"count": -1}}, {"$limit": 5}] return pipeline def aggregate(db, pipeline): result = db.tweets.aggregate(pipeline) return result if __name__ == '__main__': db = get_db('twitter') pipeline = make_pipeline() result = aggregate(db, pipeline) assert len(result["result"]) == 5 assert result["result"][0]["count"] > result["result"][4]["count"] import pprint pprint.pprint(result)
erikr/django
refs/heads/master
django/conf/urls/__init__.py
133
import warnings from importlib import import_module from django.core.exceptions import ImproperlyConfigured from django.urls import ( LocaleRegexURLResolver, RegexURLPattern, RegexURLResolver, ) from django.utils import six from django.utils.deprecation import RemovedInDjango20Warning __all__ = ['handler400', 'handler403', 'handler404', 'handler500', 'include', 'url'] handler400 = 'django.views.defaults.bad_request' handler403 = 'django.views.defaults.permission_denied' handler404 = 'django.views.defaults.page_not_found' handler500 = 'django.views.defaults.server_error' def include(arg, namespace=None, app_name=None): if app_name and not namespace: raise ValueError('Must specify a namespace if specifying app_name.') if app_name: warnings.warn( 'The app_name argument to django.conf.urls.include() is deprecated. ' 'Set the app_name in the included URLconf instead.', RemovedInDjango20Warning, stacklevel=2 ) if isinstance(arg, tuple): # callable returning a namespace hint try: urlconf_module, app_name = arg except ValueError: if namespace: raise ImproperlyConfigured( 'Cannot override the namespace for a dynamic module that provides a namespace' ) warnings.warn( 'Passing a 3-tuple to django.conf.urls.include() is deprecated. ' 'Pass a 2-tuple containing the list of patterns and app_name, ' 'and provide the namespace argument to include() instead.', RemovedInDjango20Warning, stacklevel=2 ) urlconf_module, app_name, namespace = arg else: # No namespace hint - use manually provided namespace urlconf_module = arg if isinstance(urlconf_module, six.string_types): urlconf_module = import_module(urlconf_module) patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module) app_name = getattr(urlconf_module, 'app_name', app_name) if namespace and not app_name: warnings.warn( 'Specifying a namespace in django.conf.urls.include() without ' 'providing an app_name is deprecated. Set the app_name attribute ' 'in the included module, or pass a 2-tuple containing the list of ' 'patterns and app_name instead.', RemovedInDjango20Warning, stacklevel=2 ) namespace = namespace or app_name # Make sure we can iterate through the patterns (without this, some # testcases will break). if isinstance(patterns, (list, tuple)): for url_pattern in patterns: # Test if the LocaleRegexURLResolver is used within the include; # this should throw an error since this is not allowed! if isinstance(url_pattern, LocaleRegexURLResolver): raise ImproperlyConfigured( 'Using i18n_patterns in an included URLconf is not allowed.') return (urlconf_module, app_name, namespace) def url(regex, view, kwargs=None, name=None): if isinstance(view, (list, tuple)): # For include(...) processing. urlconf_module, app_name, namespace = view return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) elif callable(view): return RegexURLPattern(regex, view, kwargs, name) else: raise TypeError('view must be a callable or a list/tuple in the case of include().')
cyyber/QRL
refs/heads/master
src/qrl/services/PublicAPIService.py
1
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. import traceback import os from statistics import variance, mean from pyqrllib.pyqrllib import hstr2bin, QRLHelper, QRLDescriptor from qrl.core import config from qrl.core.AddressState import AddressState from qrl.core.misc import logger from qrl.core.qrlnode import QRLNode from qrl.core.txs.Transaction import Transaction, CODEMAP from qrl.generated import qrl_pb2 from qrl.generated.qrl_pb2_grpc import PublicAPIServicer from qrl.services.grpcHelper import GrpcExceptionWrapper class PublicAPIService(PublicAPIServicer): MAX_REQUEST_QUANTITY = 100 # TODO: Separate the Service from the node model def __init__(self, qrlnode: QRLNode): self.qrlnode = qrlnode @GrpcExceptionWrapper(qrl_pb2.GetAddressFromPKResp) def GetAddressFromPK(self, request: qrl_pb2.GetAddressFromPKReq, context) -> qrl_pb2.GetAddressFromPKResp: return qrl_pb2.GetAddressFromPKResp(address=bytes(QRLHelper.getAddress(request.pk))) @GrpcExceptionWrapper(qrl_pb2.GetPeersStatResp) def GetPeersStat(self, request: qrl_pb2.GetPeersStatReq, context) -> qrl_pb2.GetPeersStatResp: peers_stat_resp = qrl_pb2.GetPeersStatResp() peers_stat = self.qrlnode.get_peers_stat() for stat in peers_stat: peers_stat_resp.peers_stat.extend([stat]) return peers_stat_resp @GrpcExceptionWrapper(qrl_pb2.IsSlaveResp) def IsSlave(self, request: qrl_pb2.IsSlaveReq, context) -> qrl_pb2.IsSlaveResp: return qrl_pb2.IsSlaveResp(result=self.qrlnode.is_slave(request.master_address, request.slave_pk)) @GrpcExceptionWrapper(qrl_pb2.GetNodeStateResp) def GetNodeState(self, request: qrl_pb2.GetNodeStateReq, context) -> qrl_pb2.GetNodeStateResp: return qrl_pb2.GetNodeStateResp(info=self.qrlnode.get_node_info()) @GrpcExceptionWrapper(qrl_pb2.GetKnownPeersResp) def GetKnownPeers(self, request: qrl_pb2.GetKnownPeersReq, context) -> qrl_pb2.GetKnownPeersResp: response = qrl_pb2.GetKnownPeersResp() response.node_info.CopyFrom(self.qrlnode.get_node_info()) response.known_peers.extend([qrl_pb2.Peer(ip=p) for p in self.qrlnode.peer_manager.known_peer_addresses]) return response @GrpcExceptionWrapper(qrl_pb2.GetStatsResp) def GetStats(self, request: qrl_pb2.GetStatsReq, context) -> qrl_pb2.GetStatsResp: response = qrl_pb2.GetStatsResp() response.node_info.CopyFrom(self.qrlnode.get_node_info()) response.epoch = self.qrlnode.epoch response.uptime_network = self.qrlnode.uptime_network response.block_last_reward = self.qrlnode.block_last_reward response.coins_total_supply = int(self.qrlnode.coin_supply_max) response.coins_emitted = int(self.qrlnode.coin_supply) response.block_time_mean = 0 response.block_time_sd = 0 if request.include_timeseries: tmp = list(self.qrlnode.get_block_timeseries(config.dev.block_timeseries_size)) response.block_timeseries.extend(tmp) if len(tmp) > 2: vals = [v.time_last for v in tmp[1:]] response.block_time_mean = int(mean(vals)) response.block_time_sd = int(variance(vals) ** 0.5) return response @GrpcExceptionWrapper(qrl_pb2.GetChainStatsResp) def GetChainStats(self, request: qrl_pb2.GetChainStatsReq, context) -> qrl_pb2.GetChainStatsResp: response = qrl_pb2.GetChainStatsResp() for (path, dirs, files) in os.walk(config.user.data_dir + "/state"): for f in files: filename = os.path.join(path, f) response.state_size += os.path.getsize(filename) response.state_size_mb = str(response.state_size / (1024 * 1024)) response.state_size_gb = str(response.state_size / (1024 * 1024 * 1024)) return response @GrpcExceptionWrapper(qrl_pb2.ParseAddressResp) def ParseAddress(self, request: qrl_pb2.ParseAddressReq, context) -> qrl_pb2.ParseAddressResp: response = qrl_pb2.ParseAddressResp() response.is_valid = QRLHelper.addressIsValid(request.address) descriptor = QRLDescriptor.fromBytes(request.address[:3]) hf_dict = {0: 'SHA2-256', 1: 'SHAKE-128', 2: 'SHAKE-256', 3: 'RESERVED'} ss_dict = {0: 'XMSS', 1: 'XMSS-MT'} af_dict = {0: 'SHA2-256', 1: 'RESERVED', 3: 'RESERVED'} response.desc.hash_function = hf_dict[descriptor.getHashFunction()] response.desc.tree_height = descriptor.getHeight() response.desc.signatures = 2**response.desc.tree_height response.desc.signature_scheme = ss_dict[descriptor.getSignatureType()] response.desc.address_format = af_dict[descriptor.getAddrFormatType()] return response @GrpcExceptionWrapper(qrl_pb2.GetAddressStateResp) def GetAddressState(self, request: qrl_pb2.GetAddressStateReq, context) -> qrl_pb2.GetAddressStateResp: address_state = self.qrlnode.get_address_state(request.address) return qrl_pb2.GetAddressStateResp(state=address_state.pbdata) @GrpcExceptionWrapper(qrl_pb2.GetOptimizedAddressStateResp) def GetOptimizedAddressState(self, request: qrl_pb2.GetAddressStateReq, context) -> qrl_pb2.GetOptimizedAddressStateResp: address_state = self.qrlnode.get_optimized_address_state(request.address) return qrl_pb2.GetOptimizedAddressStateResp(state=address_state.pbdata) @GrpcExceptionWrapper(qrl_pb2.GetMultiSigAddressStateResp) def GetMultiSigAddressState(self, request: qrl_pb2.GetMultiSigAddressStateReq, context) -> qrl_pb2.GetMultiSigAddressStateResp: multi_sig_address_state = self.qrlnode.get_multi_sig_address_state(request.address) if multi_sig_address_state is None: return qrl_pb2.GetMultiSigAddressStateResp() return qrl_pb2.GetMultiSigAddressStateResp(state=multi_sig_address_state.pbdata) @GrpcExceptionWrapper(qrl_pb2.TransferCoinsResp) def TransferCoins(self, request: qrl_pb2.TransferCoinsReq, context) -> qrl_pb2.TransferCoinsResp: logger.debug("[PublicAPI] TransferCoins") tx = self.qrlnode.create_send_tx(addrs_to=request.addresses_to, amounts=request.amounts, message_data=request.message_data, fee=request.fee, xmss_pk=request.xmss_pk, master_addr=request.master_addr) extended_transaction_unsigned = qrl_pb2.TransactionExtended(tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) return qrl_pb2.TransferCoinsResp(extended_transaction_unsigned=extended_transaction_unsigned) @GrpcExceptionWrapper(qrl_pb2.PushTransactionResp) def PushTransaction(self, request: qrl_pb2.PushTransactionReq, context) -> qrl_pb2.PushTransactionResp: logger.debug("[PublicAPI] PushTransaction") answer = qrl_pb2.PushTransactionResp() try: tx = Transaction.from_pbdata(request.transaction_signed) tx.update_txhash() # FIXME: Full validation takes too much time. At least verify there is a signature # the validation happens later in the tx pool if len(tx.signature) > 1000: self.qrlnode.submit_send_tx(tx) answer.error_code = qrl_pb2.PushTransactionResp.SUBMITTED answer.tx_hash = tx.txhash else: answer.error_description = 'Signature too short' answer.error_code = qrl_pb2.PushTransactionResp.VALIDATION_FAILED except Exception as e: error_str = traceback.format_exception(None, e, e.__traceback__) answer.error_description = str(''.join(error_str)) answer.error_code = qrl_pb2.PushTransactionResp.ERROR return answer @GrpcExceptionWrapper(qrl_pb2.TransferCoinsResp) def GetMultiSigCreateTxn(self, request: qrl_pb2.MultiSigCreateTxnReq, context) -> qrl_pb2.TransferCoinsResp: logger.debug("[PublicAPI] GetMultiSigCreateTxnReq") tx = self.qrlnode.create_multi_sig_txn(signatories=request.signatories, weights=request.weights, threshold=request.threshold, fee=request.fee, xmss_pk=request.xmss_pk, master_addr=request.master_addr) extended_transaction_unsigned = qrl_pb2.TransactionExtended(tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) return qrl_pb2.TransferCoinsResp(extended_transaction_unsigned=extended_transaction_unsigned) @GrpcExceptionWrapper(qrl_pb2.TransferCoinsResp) def GetMultiSigSpendTxn(self, request: qrl_pb2.MultiSigSpendTxnReq, context) -> qrl_pb2.TransferCoinsResp: logger.debug("[PublicAPI] GetMultiSigSpendTxnReq") tx = self.qrlnode.create_multi_sig_spend_txn(multi_sig_address=request.multi_sig_address, addrs_to=request.addrs_to, amounts=request.amounts, expiry_block_number=request.expiry_block_number, fee=request.fee, xmss_pk=request.xmss_pk, master_addr=request.master_addr) extended_transaction_unsigned = qrl_pb2.TransactionExtended(tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) return qrl_pb2.TransferCoinsResp(extended_transaction_unsigned=extended_transaction_unsigned) @GrpcExceptionWrapper(qrl_pb2.TransferCoinsResp) def GetMultiSigVoteTxn(self, request: qrl_pb2.MultiSigVoteTxnReq, context) -> qrl_pb2.TransferCoinsResp: logger.debug("[PublicAPI] GetMultiSigSpendTxnReq") tx = self.qrlnode.create_multi_sig_vote_txn(shared_key=request.shared_key, unvote=request.unvote, fee=request.fee, xmss_pk=request.xmss_pk, master_addr=request.master_addr) extended_transaction_unsigned = qrl_pb2.TransactionExtended(tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) return qrl_pb2.TransferCoinsResp(extended_transaction_unsigned=extended_transaction_unsigned) @GrpcExceptionWrapper(qrl_pb2.TransferCoinsResp) def GetMessageTxn(self, request: qrl_pb2.MessageTxnReq, context) -> qrl_pb2.TransferCoinsResp: logger.debug("[PublicAPI] GetMessageTxn") tx = self.qrlnode.create_message_txn(message_hash=request.message, addr_to=request.addr_to, fee=request.fee, xmss_pk=request.xmss_pk, master_addr=request.master_addr) extended_transaction_unsigned = qrl_pb2.TransactionExtended(tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) return qrl_pb2.TransferCoinsResp(extended_transaction_unsigned=extended_transaction_unsigned) @GrpcExceptionWrapper(qrl_pb2.TransferCoinsResp) def GetTokenTxn(self, request: qrl_pb2.TokenTxnReq, context) -> qrl_pb2.TransferCoinsResp: logger.debug("[PublicAPI] GetTokenTxn") tx = self.qrlnode.create_token_txn(symbol=request.symbol, name=request.name, owner=request.owner, decimals=request.decimals, initial_balances=request.initial_balances, fee=request.fee, xmss_pk=request.xmss_pk, master_addr=request.master_addr) extended_transaction_unsigned = qrl_pb2.TransactionExtended(tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) return qrl_pb2.TransferCoinsResp(extended_transaction_unsigned=extended_transaction_unsigned) @GrpcExceptionWrapper(qrl_pb2.TransferCoinsResp) def GetTransferTokenTxn(self, request: qrl_pb2.TransferTokenTxnReq, context) -> qrl_pb2.TransferCoinsResp: logger.debug("[PublicAPI] GetTransferTokenTxn") bin_token_txhash = bytes(hstr2bin(request.token_txhash.decode())) tx = self.qrlnode.create_transfer_token_txn(addrs_to=request.addresses_to, token_txhash=bin_token_txhash, amounts=request.amounts, fee=request.fee, xmss_pk=request.xmss_pk, master_addr=request.master_addr) extended_transaction_unsigned = qrl_pb2.TransactionExtended(tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) return qrl_pb2.TransferCoinsResp(extended_transaction_unsigned=extended_transaction_unsigned) @GrpcExceptionWrapper(qrl_pb2.TransferCoinsResp) def GetSlaveTxn(self, request: qrl_pb2.SlaveTxnReq, context) -> qrl_pb2.TransferCoinsResp: logger.debug("[PublicAPI] GetSlaveTxn") tx = self.qrlnode.create_slave_tx(slave_pks=request.slave_pks, access_types=request.access_types, fee=request.fee, xmss_pk=request.xmss_pk, master_addr=request.master_addr) extended_transaction_unsigned = qrl_pb2.TransactionExtended(tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) return qrl_pb2.TransferCoinsResp(extended_transaction_unsigned=extended_transaction_unsigned) @GrpcExceptionWrapper(qrl_pb2.TransferCoinsResp) def GetLatticeTxn(self, request: qrl_pb2.LatticeTxnReq, context) -> qrl_pb2.TransferCoinsResp: logger.debug("[PublicAPI] GetLatticeTxn") tx = self.qrlnode.create_lattice_tx(pk1=request.pk1, pk2=request.pk2, pk3=request.pk3, fee=request.fee, xmss_pk=request.xmss_pk, master_addr=request.master_addr) extended_transaction_unsigned = qrl_pb2.TransactionExtended(tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) return qrl_pb2.TransferCoinsResp(extended_transaction_unsigned=extended_transaction_unsigned) @GrpcExceptionWrapper(qrl_pb2.GetObjectResp) def GetObject(self, request: qrl_pb2.GetObjectReq, context) -> qrl_pb2.GetObjectResp: logger.debug("[PublicAPI] GetObject") answer = qrl_pb2.GetObjectResp() answer.found = False # FIXME: We need a unified way to access and validate data. query = bytes(request.query) # query will be as a string, if Q is detected convert, etc. try: if AddressState.address_is_valid(query): if self.qrlnode.get_address_is_used(query): address_state = self.qrlnode.get_optimized_address_state(query) if address_state is not None: answer.found = True answer.address_state.CopyFrom(address_state.pbdata) return answer except ValueError: pass transaction_block_number = self.qrlnode.get_transaction(query) transaction = None blockheader = None if transaction_block_number: transaction, block_number = transaction_block_number answer.found = True block = self.qrlnode.get_block_from_index(block_number) blockheader = block.blockheader.pbdata timestamp = block.blockheader.timestamp else: transaction_timestamp = self.qrlnode.get_unconfirmed_transaction(query) if transaction_timestamp: transaction, timestamp = transaction_timestamp answer.found = True if transaction: txextended = qrl_pb2.TransactionExtended(header=blockheader, tx=transaction.pbdata, addr_from=transaction.addr_from, size=transaction.size, timestamp_seconds=timestamp) answer.transaction.CopyFrom(txextended) return answer # NOTE: This is temporary, indexes are accepted for blocks try: block = self.qrlnode.get_block_from_hash(query) if block is None or (block.block_number == 0 and block.prev_headerhash != config.user.genesis_prev_headerhash): query_str = query.decode() query_index = int(query_str) block = self.qrlnode.get_block_from_index(query_index) if not block: return answer answer.found = True block_extended = qrl_pb2.BlockExtended() block_extended.header.CopyFrom(block.blockheader.pbdata) block_extended.size = block.size for transaction in block.transactions: tx = Transaction.from_pbdata(transaction) extended_tx = qrl_pb2.TransactionExtended(tx=transaction, addr_from=tx.addr_from, size=tx.size, timestamp_seconds=block.blockheader.timestamp) block_extended.extended_transactions.extend([extended_tx]) answer.block_extended.CopyFrom(block_extended) return answer except Exception: pass return answer @GrpcExceptionWrapper(qrl_pb2.GetLatestDataResp) def GetLatestData(self, request: qrl_pb2.GetLatestDataReq, context) -> qrl_pb2.GetLatestDataResp: logger.debug("[PublicAPI] GetLatestData") response = qrl_pb2.GetLatestDataResp() all_requested = request.filter == qrl_pb2.GetLatestDataReq.ALL quantity = min(request.quantity, self.MAX_REQUEST_QUANTITY) if all_requested or request.filter == qrl_pb2.GetLatestDataReq.BLOCKHEADERS: result = [] for blk in self.qrlnode.get_latest_blocks(offset=request.offset, count=quantity): transaction_count = qrl_pb2.TransactionCount() for tx in blk.transactions: transaction_count.count[CODEMAP[tx.WhichOneof('transactionType')]] += 1 result.append(qrl_pb2.BlockHeaderExtended(header=blk.blockheader.pbdata, transaction_count=transaction_count)) response.blockheaders.extend(result) if all_requested or request.filter == qrl_pb2.GetLatestDataReq.TRANSACTIONS: result = [] for tx in self.qrlnode.get_latest_transactions(offset=request.offset, count=quantity): # FIXME: Improve this once we have a proper database schema block_index = self.qrlnode.get_blockidx_from_txhash(tx.txhash) block = self.qrlnode.get_block_from_index(block_index) header = None if block: header = block.blockheader.pbdata txextended = qrl_pb2.TransactionExtended(header=header, tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size) result.append(txextended) response.transactions.extend(result) if all_requested or request.filter == qrl_pb2.GetLatestDataReq.TRANSACTIONS_UNCONFIRMED: result = [] for tx_info in self.qrlnode.get_latest_transactions_unconfirmed(offset=request.offset, count=quantity): tx = tx_info.transaction txextended = qrl_pb2.TransactionExtended(header=None, tx=tx.pbdata, addr_from=tx.addr_from, size=tx.size, timestamp_seconds=tx_info.timestamp) result.append(txextended) response.transactions_unconfirmed.extend(result) return response # Obsolete # @GrpcExceptionWrapper(qrl_pb2.GetTransactionsByAddressResp) # def GetTransactionsByAddress(self, # request: qrl_pb2.GetTransactionsByAddressReq, # context) -> qrl_pb2.GetTransactionsByAddressResp: # logger.debug("[PublicAPI] GetTransactionsByAddress") # response = qrl_pb2.GetTransactionsByAddressResp() # mini_transactions, balance = self.qrlnode.get_transactions_by_address(request.address) # response.mini_transactions.extend(mini_transactions) # response.balance = balance # return response @GrpcExceptionWrapper(qrl_pb2.GetMiniTransactionsByAddressResp) def GetMiniTransactionsByAddress(self, request: qrl_pb2.GetMiniTransactionsByAddressReq, context) -> qrl_pb2.GetMiniTransactionsByAddressResp: logger.debug("[PublicAPI] GetTransactionsByAddress") return self.qrlnode.get_mini_transactions_by_address(request.address, request.item_per_page, request.page_number) @GrpcExceptionWrapper(qrl_pb2.GetTransactionsByAddressResp) def GetTransactionsByAddress(self, request: qrl_pb2.GetTransactionsByAddressReq, context) -> qrl_pb2.GetTransactionsByAddressResp: logger.debug("[PublicAPI] GetTransactionsByAddress") return self.qrlnode.get_transactions_by_address(request.address, request.item_per_page, request.page_number) @GrpcExceptionWrapper(qrl_pb2.GetTokensByAddressResp) def GetTokensByAddress(self, request: qrl_pb2.GetTransactionsByAddressReq, context) -> qrl_pb2.GetTokensByAddressResp: logger.debug("[PublicAPI] GetTokensByAddress") return self.qrlnode.get_tokens_by_address(request.address, request.item_per_page, request.page_number) @GrpcExceptionWrapper(qrl_pb2.GetSlavesByAddressResp) def GetSlavesByAddress(self, request: qrl_pb2.GetTransactionsByAddressReq, context) -> qrl_pb2.GetSlavesByAddressResp: logger.debug("[PublicAPI] GetSlavesByAddress") return self.qrlnode.get_slaves_by_address(request.address, request.item_per_page, request.page_number) @GrpcExceptionWrapper(qrl_pb2.GetLatticePKsByAddressResp) def GetLatticePKsByAddress(self, request: qrl_pb2.GetTransactionsByAddressReq, context) -> qrl_pb2.GetLatticePKsByAddressResp: logger.debug("[PublicAPI] GetLatticePKsByAddress") return self.qrlnode.get_lattice_pks_by_address(request.address, request.item_per_page, request.page_number) @GrpcExceptionWrapper(qrl_pb2.GetMultiSigAddressesByAddressResp) def GetMultiSigAddressesByAddress(self, request: qrl_pb2.GetTransactionsByAddressReq, context) -> qrl_pb2.GetMultiSigAddressesByAddressResp: logger.debug("[PublicAPI] GetMultiSigAddressesByAddress") return self.qrlnode.get_multi_sig_addresses_by_address(request.address, request.item_per_page, request.page_number) @GrpcExceptionWrapper(qrl_pb2.GetMultiSigSpendTxsByAddressResp) def GetMultiSigSpendTxsByAddress(self, request: qrl_pb2.GetMultiSigSpendTxsByAddressReq, context) -> qrl_pb2.GetMultiSigSpendTxsByAddressResp: logger.debug("[PublicAPI] GetMultiSigSpendTxsByAddress") return self.qrlnode.get_multi_sig_spend_txs_by_address(request.address, request.item_per_page, request.page_number, request.filter_type) @GrpcExceptionWrapper(qrl_pb2.GetInboxMessagesByAddressResp) def GetInboxMessagesByAddress(self, request: qrl_pb2.GetTransactionsByAddressReq, context) -> qrl_pb2.GetInboxMessagesByAddressResp: logger.debug("[PublicAPI] GetInboxMessagesByAddress") return self.qrlnode.get_inbox_messages_by_address(request.address, request.item_per_page, request.page_number) @GrpcExceptionWrapper(qrl_pb2.GetVoteStatsResp) def GetVoteStats(self, request: qrl_pb2.GetVoteStatsReq, context) -> qrl_pb2.GetVoteStatsResp: logger.debug("[PublicAPI] GetVoteStats") return self.qrlnode.get_vote_stats(request.multi_sig_spend_tx_hash) @GrpcExceptionWrapper(qrl_pb2.GetTransactionResp) def GetTransaction(self, request: qrl_pb2.GetTransactionReq, context) -> qrl_pb2.GetTransactionResp: logger.debug("[PublicAPI] GetTransaction") response = qrl_pb2.GetTransactionResp() tx_blocknumber = self.qrlnode.get_transaction(request.tx_hash) if tx_blocknumber: response.tx.MergeFrom(tx_blocknumber[0].pbdata) response.confirmations = self.qrlnode.block_height - tx_blocknumber[1] + 1 response.block_number = tx_blocknumber[1] response.block_header_hash = self.qrlnode.get_block_header_hash_by_number(tx_blocknumber[1]) else: tx_timestamp = self.qrlnode.get_unconfirmed_transaction(request.tx_hash) if tx_timestamp: response.tx.MergeFrom(tx_timestamp[0].pbdata) response.confirmations = 0 return response @GrpcExceptionWrapper(qrl_pb2.GetBalanceResp) def GetBalance(self, request: qrl_pb2.GetBalanceReq, context) -> qrl_pb2.GetBalanceResp: logger.debug("[PublicAPI] GetBalance") address_state = self.qrlnode.get_optimized_address_state(request.address) response = qrl_pb2.GetBalanceResp(balance=address_state.balance) return response @GrpcExceptionWrapper(qrl_pb2.GetTotalBalanceResp) def GetTotalBalance(self, request: qrl_pb2.GetTotalBalanceReq, context) -> qrl_pb2.GetTotalBalanceResp: logger.debug("[PublicAPI] GetTotalBalance") response = qrl_pb2.GetBalanceResp(balance=0) for address in request.addresses: address_state = self.qrlnode.get_optimized_address_state(address) response.balance += address_state.balance return response @GrpcExceptionWrapper(qrl_pb2.GetOTSResp) def GetOTS(self, request: qrl_pb2.GetOTSReq, context) -> qrl_pb2.GetOTSResp: logger.debug("[PublicAPI] GetOTS") ots_bitfield_by_page, next_unused_ots_index, unused_ots_index_found = \ self.qrlnode.get_ots(request.address, request.page_from, request.page_count, request.unused_ots_index_from) response = qrl_pb2.GetOTSResp(ots_bitfield_by_page=ots_bitfield_by_page, next_unused_ots_index=next_unused_ots_index, unused_ots_index_found=unused_ots_index_found) return response @GrpcExceptionWrapper(qrl_pb2.GetHeightResp) def GetHeight(self, request: qrl_pb2.GetHeightReq, context) -> qrl_pb2.GetHeightResp: logger.debug("[PublicAPI] GetHeight") return qrl_pb2.GetHeightResp(height=self.qrlnode.block_height) @GrpcExceptionWrapper(qrl_pb2.GetBlockResp) def GetBlock(self, request: qrl_pb2.GetBlockReq, context) -> qrl_pb2.GetBlockResp: logger.debug("[PublicAPI] GetBlock") block = self.qrlnode.get_block_from_hash(request.header_hash) if block: return qrl_pb2.GetBlockResp(block=block.pbdata) return qrl_pb2.GetBlockResp() @GrpcExceptionWrapper(qrl_pb2.GetBlockByNumberResp) def GetBlockByNumber(self, request: qrl_pb2.GetBlockByNumberReq, context) -> qrl_pb2.GetBlockByNumberResp: logger.debug("[PublicAPI] GetBlockFromNumber") block = self.qrlnode.get_block_from_index(request.block_number) if block: return qrl_pb2.GetBlockByNumberResp(block=block.pbdata) return qrl_pb2.GetBlockByNumberResp()
gerryhd/diabot-assistant
refs/heads/master
lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/universaldetector.py
1775
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from . import constants import sys import codecs from .latin1prober import Latin1Prober # windows-1252 from .mbcsgroupprober import MBCSGroupProber # multi-byte character sets from .sbcsgroupprober import SBCSGroupProber # single-byte character sets from .escprober import EscCharSetProber # ISO-2122, etc. import re MINIMUM_THRESHOLD = 0.20 ePureAscii = 0 eEscAscii = 1 eHighbyte = 2 class UniversalDetector: def __init__(self): self._highBitDetector = re.compile(b'[\x80-\xFF]') self._escDetector = re.compile(b'(\033|~{)') self._mEscCharSetProber = None self._mCharSetProbers = [] self.reset() def reset(self): self.result = {'encoding': None, 'confidence': 0.0} self.done = False self._mStart = True self._mGotData = False self._mInputState = ePureAscii self._mLastChar = b'' if self._mEscCharSetProber: self._mEscCharSetProber.reset() for prober in self._mCharSetProbers: prober.reset() def feed(self, aBuf): if self.done: return aLen = len(aBuf) if not aLen: return if not self._mGotData: # If the data starts with BOM, we know it is UTF if aBuf[:3] == codecs.BOM_UTF8: # EF BB BF UTF-8 with BOM self.result = {'encoding': "UTF-8-SIG", 'confidence': 1.0} elif aBuf[:4] == codecs.BOM_UTF32_LE: # FF FE 00 00 UTF-32, little-endian BOM self.result = {'encoding': "UTF-32LE", 'confidence': 1.0} elif aBuf[:4] == codecs.BOM_UTF32_BE: # 00 00 FE FF UTF-32, big-endian BOM self.result = {'encoding': "UTF-32BE", 'confidence': 1.0} elif aBuf[:4] == b'\xFE\xFF\x00\x00': # FE FF 00 00 UCS-4, unusual octet order BOM (3412) self.result = { 'encoding': "X-ISO-10646-UCS-4-3412", 'confidence': 1.0 } elif aBuf[:4] == b'\x00\x00\xFF\xFE': # 00 00 FF FE UCS-4, unusual octet order BOM (2143) self.result = { 'encoding': "X-ISO-10646-UCS-4-2143", 'confidence': 1.0 } elif aBuf[:2] == codecs.BOM_LE: # FF FE UTF-16, little endian BOM self.result = {'encoding': "UTF-16LE", 'confidence': 1.0} elif aBuf[:2] == codecs.BOM_BE: # FE FF UTF-16, big endian BOM self.result = {'encoding': "UTF-16BE", 'confidence': 1.0} self._mGotData = True if self.result['encoding'] and (self.result['confidence'] > 0.0): self.done = True return if self._mInputState == ePureAscii: if self._highBitDetector.search(aBuf): self._mInputState = eHighbyte elif ((self._mInputState == ePureAscii) and self._escDetector.search(self._mLastChar + aBuf)): self._mInputState = eEscAscii self._mLastChar = aBuf[-1:] if self._mInputState == eEscAscii: if not self._mEscCharSetProber: self._mEscCharSetProber = EscCharSetProber() if self._mEscCharSetProber.feed(aBuf) == constants.eFoundIt: self.result = {'encoding': self._mEscCharSetProber.get_charset_name(), 'confidence': self._mEscCharSetProber.get_confidence()} self.done = True elif self._mInputState == eHighbyte: if not self._mCharSetProbers: self._mCharSetProbers = [MBCSGroupProber(), SBCSGroupProber(), Latin1Prober()] for prober in self._mCharSetProbers: if prober.feed(aBuf) == constants.eFoundIt: self.result = {'encoding': prober.get_charset_name(), 'confidence': prober.get_confidence()} self.done = True break def close(self): if self.done: return if not self._mGotData: if constants._debug: sys.stderr.write('no data received!\n') return self.done = True if self._mInputState == ePureAscii: self.result = {'encoding': 'ascii', 'confidence': 1.0} return self.result if self._mInputState == eHighbyte: proberConfidence = None maxProberConfidence = 0.0 maxProber = None for prober in self._mCharSetProbers: if not prober: continue proberConfidence = prober.get_confidence() if proberConfidence > maxProberConfidence: maxProberConfidence = proberConfidence maxProber = prober if maxProber and (maxProberConfidence > MINIMUM_THRESHOLD): self.result = {'encoding': maxProber.get_charset_name(), 'confidence': maxProber.get_confidence()} return self.result if constants._debug: sys.stderr.write('no probers hit minimum threshhold\n') for prober in self._mCharSetProbers[0].mProbers: if not prober: continue sys.stderr.write('%s confidence = %s\n' % (prober.get_charset_name(), prober.get_confidence()))
krisys/django
refs/heads/master
tests/check_framework/models.py
396
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class SimpleModel(models.Model): field = models.IntegerField() manager = models.manager.Manager()
ibm-cds-labs/simple-data-pipe-connector-flightstats
refs/heads/master
pixiedust_flightpredict/pixiedust_flightpredict/__init__.py
1
# ------------------------------------------------------------------------------- # Copyright IBM Corp. 2016 # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------------------- from pixiedust.display.display import * from pixiedust.display import * from .flightPredict import * import pixiedust import pixiedust.utils.dataFrameMisc as dataFrameMisc from pixiedust.utils.shellAccess import ShellAccess from pyspark.rdd import RDD from pyspark.sql import DataFrame from pyspark.mllib.regression import LabeledPoint from six import iteritems, with_metaclass myLogger = pixiedust.getLogger(__name__) initialAirport = "BOS" @PixiedustDisplay() class PixieDustFlightPredictPluginMeta(DisplayHandlerMeta): def createCategories(self): return [{"id":"FlightPredict","title":"Flight Predictor", "icon-path":"flightPredict.jpeg"}] @addId def getMenuInfo(self,entity, dataHandler): if entity==self.__class__: return [{"id": "flightpredict"}] elif entity == "fp_configure_training": return [{"id": "fp_configure_training"}] elif entity == "fp_map_results": return [{"id": "fp_map_results"}] menus = [] dataSetsValues = Configuration.getDataSets() dataSetsValues = dataSetsValues if len(dataSetsValues)==0 else list(zip(*dataSetsValues))[1] if entity in dataSetsValues: menus = menus + [ {"categoryId": "FlightPredict", "title": "Visualize Features", "icon-path":"vizFeatures.png", "id":"fp_viz_features"}, {"categoryId": "FlightPredict", "title": "Show Histogram", "icon-path":"vizFeatures.png", "id":"fp_histogram"} ] if len(Configuration.getModels())>0 and Configuration.getLabeledData(entity) is not None: menus.append( {"categoryId": "FlightPredict", "title": "Measure Accuracy", "icon-path":"vizFeatures.png", "id":"fp_run_metrics"} ) return menus def isLabeledRDD(self, entity): if isinstance(entity,RDD): sample = entity.take(1) if sample is not None and len(sample)>0: return isinstance(sample[0], LabeledPoint) return False def newDisplayHandler(self,options,entity): handlerId=options.get("handlerId") myLogger.debug("Creating a new Display Handler with id {0}".format(handlerId)) if handlerId == "fp_viz_features": from . import vizFeatures return vizFeatures.VizualizeFeatures(options,entity) elif handlerId == "fp_configure_training": from . import configureTraining return configureTraining.ConfigureTraining(options,entity) elif handlerId == "fp_create_models": from . import createModels return createModels.CreateModels(options, entity) elif handlerId == "fp_histogram": from . import histogramDisplay return histogramDisplay.HistogramDisplay(options, entity) elif handlerId == "fp_run_metrics": from . import runMetrics return runMetrics.RunMetricsDisplay(options, entity) elif handlerId == "fp_map_results": from . import mapResults return mapResults.MapResultsDisplay(options, entity) else: options["initialAirport"] = initialAirport return PixieDustFlightPredict(options,entity) def flightPredict(depAir="BOS"): global initialAirport initialAirport = depAir display(PixieDustFlightPredictPluginMeta) def displayMapResults(): display("fp_map_results") def configure(): display("fp_configure_training") class Configuration(with_metaclass( type("",(type,),{ "configDict":{}, "__getitem__":lambda cls, key: cls.configDict.get(key), "__setitem__":lambda cls, key,val: cls.configDict.update({key:val}), "__getattr__":lambda cls, key: cls.configDict.get(key), "__setattr__":lambda cls, key, val: cls.configDict.update({key:val}) }), object )): @staticmethod def update(**kwargs): for key,val in iteritems(kwargs): Configuration[key]=val @staticmethod def getModels(): return [(x,ShellAccess[x]) for x in ShellAccess if hasattr(ShellAccess[x], "predict") and callable(getattr(ShellAccess[x], "predict"))] @staticmethod def getDataSets(): return [(x,ShellAccess[x]) for x in ShellAccess if (x=="trainingData" or x=="testData") and isinstance(ShellAccess[x], DataFrame)] @staticmethod def getLabeledData(entity): if ShellAccess[Configuration.DFTrainingVarName] == entity and ShellAccess[Configuration.LabeledRDDTrainingVarName] is not None: return (ShellAccess[Configuration.LabeledRDDTrainingVarName], Configuration.TrainingSQLTableName) elif ShellAccess[Configuration.DFTestVarName] == entity and ShellAccess[Configuration.LabeledRDDTestVarName] is not None: return (ShellAccess[Configuration.LabeledRDDTestVarName], Configuration.TestSQLTableName) return None @staticmethod def isReadyForRun(): return len(Configuration.getModels())>0 and Configuration.weatherUrl is not None def loadDataSet(dbName,sqlTable): if Configuration.cloudantHost is None or Configuration.cloudantUserName is None or Configuration.cloudantPassword is None: raise Exception("Missing credentials") cloudantdata = get_ipython().user_ns.get("sqlContext").read.format("com.cloudant.spark")\ .option("cloudant.host",Configuration.cloudantHost)\ .option("cloudant.username",Configuration.cloudantUserName)\ .option("cloudant.password",Configuration.cloudantPassword)\ .option("schemaSampleSize", "-1")\ .load(dbName) cloudantdata.cache() print("Successfully cached dataframe") cloudantdata.registerTempTable(sqlTable) print("Successfully registered SQL table " + sqlTable); return cloudantdata
AydinSakar/node-gyp
refs/heads/master
gyp/pylib/gyp/generator/gypd.py
912
# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """gypd output module This module produces gyp input as its output. Output files are given the .gypd extension to avoid overwriting the .gyp files that they are generated from. Internal references to .gyp files (such as those found in "dependencies" sections) are not adjusted to point to .gypd files instead; unlike other paths, which are relative to the .gyp or .gypd file, such paths are relative to the directory from which gyp was run to create the .gypd file. This generator module is intended to be a sample and a debugging aid, hence the "d" for "debug" in .gypd. It is useful to inspect the results of the various merges, expansions, and conditional evaluations performed by gyp and to see a representation of what would be fed to a generator module. It's not advisable to rename .gypd files produced by this module to .gyp, because they will have all merges, expansions, and evaluations already performed and the relevant constructs not present in the output; paths to dependencies may be wrong; and various sections that do not belong in .gyp files such as such as "included_files" and "*_excluded" will be present. Output will also be stripped of comments. This is not intended to be a general-purpose gyp pretty-printer; for that, you probably just want to run "pprint.pprint(eval(open('source.gyp').read()))", which will still strip comments but won't do all of the other things done to this module's output. The specific formatting of the output generated by this module is subject to change. """ import gyp.common import errno import os import pprint # These variables should just be spit back out as variable references. _generator_identity_variables = [ 'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX', 'INTERMEDIATE_DIR', 'PRODUCT_DIR', 'RULE_INPUT_ROOT', 'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT', 'RULE_INPUT_NAME', 'RULE_INPUT_PATH', 'SHARED_INTERMEDIATE_DIR', ] # gypd doesn't define a default value for OS like many other generator # modules. Specify "-D OS=whatever" on the command line to provide a value. generator_default_variables = { } # gypd supports multiple toolsets generator_supports_multiple_toolsets = True # TODO(mark): This always uses <, which isn't right. The input module should # notify the generator to tell it which phase it is operating in, and this # module should use < for the early phase and then switch to > for the late # phase. Bonus points for carrying @ back into the output too. for v in _generator_identity_variables: generator_default_variables[v] = '<(%s)' % v def GenerateOutput(target_list, target_dicts, data, params): output_files = {} for qualified_target in target_list: [input_file, target] = \ gyp.common.ParseQualifiedTarget(qualified_target)[0:2] if input_file[-4:] != '.gyp': continue input_file_stem = input_file[:-4] output_file = input_file_stem + params['options'].suffix + '.gypd' if not output_file in output_files: output_files[output_file] = input_file for output_file, input_file in output_files.iteritems(): output = open(output_file, 'w') pprint.pprint(data[input_file], output) output.close()
ceccode/restify-auth
refs/heads/master
node_modules/restify/node_modules/bunyan/tools/cutarelease.py
171
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2009-2012 Trent Mick """cutarelease -- Cut a release of your project. A script that will help cut a release for a git-based project that follows a few conventions. It'll update your changelog (CHANGES.md), add a git tag, push those changes, update your version to the next patch level release and create a new changelog section for that new version. Conventions: - XXX """ __version_info__ = (1, 0, 7) __version__ = '.'.join(map(str, __version_info__)) import sys import os from os.path import join, dirname, normpath, abspath, exists, basename, splitext from glob import glob from pprint import pprint import re import codecs import logging import optparse import json #---- globals and config log = logging.getLogger("cutarelease") class Error(Exception): pass #---- main functionality def cutarelease(project_name, version_files, dry_run=False): """Cut a release. @param project_name {str} @param version_files {list} List of paths to files holding the version info for this project. If none are given it attempts to guess the version file: package.json or VERSION.txt or VERSION or $project_name.py or lib/$project_name.py or $project_name.js or lib/$project_name.js. The version file can be in one of the following forms: - A .py file, in which case the file is expect to have a top-level global called "__version_info__" as follows. [1] __version_info__ = (0, 7, 6) Note that I typically follow that with the following to get a string version attribute on my modules: __version__ = '.'.join(map(str, __version_info__)) - A .js file, in which case the file is expected to have a top-level global called "VERSION" as follows: ver VERSION = "1.2.3"; - A "package.json" file, typical of a node.js npm-using project. The package.json file must have a "version" field. - TODO: A simple version file whose only content is a "1.2.3"-style version string. [1]: This is a convention I tend to follow in my projects. Granted it might not be your cup of tea. I should add support for just `__version__ = "1.2.3"`. I'm open to other suggestions too. """ dry_run_str = dry_run and " (dry-run)" or "" if not version_files: log.info("guessing version file") candidates = [ "package.json", "VERSION.txt", "VERSION", "%s.py" % project_name, "lib/%s.py" % project_name, "%s.js" % project_name, "lib/%s.js" % project_name, ] for candidate in candidates: if exists(candidate): version_files = [candidate] break else: raise Error("could not find a version file: specify its path or " "add one of the following to your project: '%s'" % "', '".join(candidates)) log.info("using '%s' as version file", version_files[0]) parsed_version_files = [_parse_version_file(f) for f in version_files] version_file_type, version_info = parsed_version_files[0] version = _version_from_version_info(version_info) # Confirm if not dry_run: answer = query_yes_no("* * *\n" "Are you sure you want cut a %s release?\n" "This will involved commits and a push." % version, default="no") print "* * *" if answer != "yes": log.info("user abort") return log.info("cutting a %s release%s", version, dry_run_str) # Checks: Ensure there is a section in changes for this version. changes_path = "CHANGES.md" changes_txt, changes, nyr = parse_changelog(changes_path) #pprint(changes) top_ver = changes[0]["version"] if top_ver != version: raise Error("changelog '%s' top section says " "version %r, expected version %r: aborting" % (changes_path, top_ver, version)) top_verline = changes[0]["verline"] if not top_verline.endswith(nyr): answer = query_yes_no("\n* * *\n" "The changelog '%s' top section doesn't have the expected\n" "'%s' marker. Has this been released already?" % (changes_path, nyr), default="yes") print "* * *" if answer != "no": log.info("abort") return top_body = changes[0]["body"] if top_body.strip() == "(nothing yet)": raise Error("top section body is `(nothing yet)': it looks like " "nothing has been added to this release") # Commits to prepare release. changes_txt_before = changes_txt changes_txt = changes_txt.replace(" (not yet released)", "", 1) if not dry_run and changes_txt != changes_txt_before: log.info("prepare `%s' for release", changes_path) f = codecs.open(changes_path, 'w', 'utf-8') f.write(changes_txt) f.close() run('git commit %s -m "prepare for %s release"' % (changes_path, version)) # Tag version and push. curr_tags = set(t for t in _capture_stdout(["git", "tag", "-l"]).split('\n') if t) if not dry_run and version not in curr_tags: log.info("tag the release") run('git tag -a "%s" -m "version %s"' % (version, version)) run('git push --tags') # Optionally release. if exists("package.json"): answer = query_yes_no("\n* * *\nPublish to npm?", default="yes") print "* * *" if answer == "yes": if dry_run: log.info("skipping npm publish (dry-run)") else: run('npm publish') elif exists("setup.py"): answer = query_yes_no("\n* * *\nPublish to pypi?", default="yes") print "* * *" if answer == "yes": if dry_run: log.info("skipping pypi publish (dry-run)") else: run("%spython setup.py sdist --formats zip upload" % _setup_command_prefix()) # Commits to prepare for future dev and push. # - update changelog file next_version_info = _get_next_version_info(version_info) next_version = _version_from_version_info(next_version_info) log.info("prepare for future dev (version %s)", next_version) marker = "## " + changes[0]["verline"] if marker.endswith(nyr): marker = marker[0:-len(nyr)] if marker not in changes_txt: raise Error("couldn't find `%s' marker in `%s' " "content: can't prep for subsequent dev" % (marker, changes_path)) next_verline = "%s %s%s" % (marker.rsplit(None, 1)[0], next_version, nyr) changes_txt = changes_txt.replace(marker + '\n', "%s\n\n(nothing yet)\n\n\n%s\n" % (next_verline, marker)) if not dry_run: f = codecs.open(changes_path, 'w', 'utf-8') f.write(changes_txt) f.close() # - update version file next_version_tuple = _tuple_from_version(next_version) for i, ver_file in enumerate(version_files): ver_content = codecs.open(ver_file, 'r', 'utf-8').read() ver_file_type, ver_info = parsed_version_files[i] if ver_file_type == "json": marker = '"version": "%s"' % version if marker not in ver_content: raise Error("couldn't find `%s' version marker in `%s' " "content: can't prep for subsequent dev" % (marker, ver_file)) ver_content = ver_content.replace(marker, '"version": "%s"' % next_version) elif ver_file_type == "javascript": candidates = [ ("single", "var VERSION = '%s';" % version), ("double", 'var VERSION = "%s";' % version), ] for quote_type, marker in candidates: if marker in ver_content: break else: raise Error("couldn't find any candidate version marker in " "`%s' content: can't prep for subsequent dev: %r" % (ver_file, candidates)) if quote_type == "single": ver_content = ver_content.replace(marker, "var VERSION = '%s';" % next_version) else: ver_content = ver_content.replace(marker, 'var VERSION = "%s";' % next_version) elif ver_file_type == "python": marker = "__version_info__ = %r" % (version_info,) if marker not in ver_content: raise Error("couldn't find `%s' version marker in `%s' " "content: can't prep for subsequent dev" % (marker, ver_file)) ver_content = ver_content.replace(marker, "__version_info__ = %r" % (next_version_tuple,)) elif ver_file_type == "version": ver_content = next_version else: raise Error("unknown ver_file_type: %r" % ver_file_type) if not dry_run: log.info("update version to '%s' in '%s'", next_version, ver_file) f = codecs.open(ver_file, 'w', 'utf-8') f.write(ver_content) f.close() if not dry_run: run('git commit %s %s -m "prep for future dev"' % ( changes_path, ' '.join(version_files))) run('git push') #---- internal support routines def _indent(s, indent=' '): return indent + indent.join(s.splitlines(True)) def _tuple_from_version(version): def _intify(s): try: return int(s) except ValueError: return s return tuple(_intify(b) for b in version.split('.')) def _get_next_version_info(version_info): next = list(version_info[:]) next[-1] += 1 return tuple(next) def _version_from_version_info(version_info): v = str(version_info[0]) state_dot_join = True for i in version_info[1:]: if state_dot_join: try: int(i) except ValueError: state_dot_join = False else: pass if state_dot_join: v += "." + str(i) else: v += str(i) return v _version_re = re.compile(r"^(\d+)\.(\d+)(?:\.(\d+)([abc](\d+)?)?)?$") def _version_info_from_version(version): m = _version_re.match(version) if not m: raise Error("could not convert '%s' version to version info" % version) version_info = [] for g in m.groups(): if g is None: break try: version_info.append(int(g)) except ValueError: version_info.append(g) return tuple(version_info) def _parse_version_file(version_file): """Get version info from the given file. It can be any of: Supported version file types (i.e. types of files from which we know how to parse the version string/number -- often by some convention): - json: use the "version" key - javascript: look for a `var VERSION = "1.2.3";` or `var VERSION = '1.2.3';` - python: Python script/module with `__version_info__ = (1, 2, 3)` - version: a VERSION.txt or VERSION file where the whole contents are the version string @param version_file {str} Can be a path or "type:path", where "type" is one of the supported types. """ # Get version file *type*. version_file_type = None match = re.compile("^([a-z]+):(.*)$").search(version_file) if match: version_file = match.group(2) version_file_type = match.group(1) aliases = { "js": "javascript" } if version_file_type in aliases: version_file_type = aliases[version_file_type] f = codecs.open(version_file, 'r', 'utf-8') content = f.read() f.close() if not version_file_type: # Guess the type. base = basename(version_file) ext = splitext(base)[1] if ext == ".json": version_file_type = "json" elif ext == ".py": version_file_type = "python" elif ext == ".js": version_file_type = "javascript" elif content.startswith("#!"): shebang = content.splitlines(False)[0] shebang_bits = re.split(r'[/ \t]', shebang) for name, typ in {"python": "python", "node": "javascript"}.items(): if name in shebang_bits: version_file_type = typ break elif base in ("VERSION", "VERSION.txt"): version_file_type = "version" if not version_file_type: raise RuntimeError("can't extract version from '%s': no idea " "what type of file it it" % version_file) if version_file_type == "json": obj = json.loads(content) version_info = _version_info_from_version(obj["version"]) elif version_file_type == "python": m = re.search(r'^__version_info__ = (.*?)$', content, re.M) version_info = eval(m.group(1)) elif version_file_type == "javascript": m = re.search(r'^var VERSION = (\'|")(.*?)\1;$', content, re.M) version_info = _version_info_from_version(m.group(2)) elif version_file_type == "version": version_info = _version_info_from_version(content.strip()) else: raise RuntimeError("unexpected version_file_type: %r" % version_file_type) return version_file_type, version_info def parse_changelog(changes_path): """Parse the given changelog path and return `(content, parsed, nyr)` where `nyr` is the ' (not yet released)' marker and `parsed` looks like: [{'body': u'\n(nothing yet)\n\n', 'verline': u'restify 1.0.1 (not yet released)', 'version': u'1.0.1'}, # version is parsed out for top section only {'body': u'...', 'verline': u'1.0.0'}, {'body': u'...', 'verline': u'1.0.0-rc2'}, {'body': u'...', 'verline': u'1.0.0-rc1'}] A changelog (CHANGES.md) is expected to look like this: # $project Changelog ## $next_version (not yet released) ... ## $version1 ... ## $version2 ... and so on The version lines are enforced as follows: - The top entry should have a " (not yet released)" suffix. "Should" because recovery from half-cutarelease failures is supported. - A version string must be extractable from there, but it tries to be loose (though strict "X.Y.Z" versioning is preferred). Allowed ## 1.0.0 ## my project 1.0.1 ## foo 1.2.3-rc2 Basically, (a) the " (not yet released)" is stripped, (b) the last token is the version, and (c) that version must start with a digit (sanity check). """ if not exists(changes_path): raise Error("changelog file '%s' not found" % changes_path) content = codecs.open(changes_path, 'r', 'utf-8').read() parser = re.compile( r'^##\s*(?P<verline>[^\n]*?)\s*$(?P<body>.*?)(?=^##|\Z)', re.M | re.S) sections = parser.findall(content) # Sanity checks on changelog format. if not sections: template = "## 1.0.0 (not yet released)\n\n(nothing yet)\n" raise Error("changelog '%s' must have at least one section, " "suggestion:\n\n%s" % (changes_path, _indent(template))) first_section_verline = sections[0][0] nyr = ' (not yet released)' #if not first_section_verline.endswith(nyr): # eg = "## %s%s" % (first_section_verline, nyr) # raise Error("changelog '%s' top section must end with %r, " # "naive e.g.: '%s'" % (changes_path, nyr, eg)) items = [] for i, section in enumerate(sections): item = { "verline": section[0], "body": section[1] } if i == 0: # We only bother to pull out 'version' for the top section. verline = section[0] if verline.endswith(nyr): verline = verline[0:-len(nyr)] version = verline.split()[-1] try: int(version[0]) except ValueError: msg = '' if version.endswith(')'): msg = " (cutarelease is picky about the trailing %r " \ "on the top version line. Perhaps you misspelled " \ "that?)" % nyr raise Error("changelog '%s' top section version '%s' is " "invalid: first char isn't a number%s" % (changes_path, version, msg)) item["version"] = version items.append(item) return content, items, nyr ## {{{ http://code.activestate.com/recipes/577058/ (r2) def query_yes_no(question, default="yes"): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is one of "yes" or "no". """ valid = {"yes":"yes", "y":"yes", "ye":"yes", "no":"no", "n":"no"} if default == None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default) while 1: sys.stdout.write(question + prompt) choice = raw_input().lower() if default is not None and choice == '': return default elif choice in valid.keys(): return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' "\ "(or 'y' or 'n').\n") ## end of http://code.activestate.com/recipes/577058/ }}} def _capture_stdout(argv): import subprocess p = subprocess.Popen(argv, stdout=subprocess.PIPE) return p.communicate()[0] class _NoReflowFormatter(optparse.IndentedHelpFormatter): """An optparse formatter that does NOT reflow the description.""" def format_description(self, description): return description or "" def run(cmd): """Run the given command. Raises OSError is the command returns a non-zero exit status. """ log.debug("running '%s'", cmd) fixed_cmd = cmd if sys.platform == "win32" and cmd.count('"') > 2: fixed_cmd = '"' + cmd + '"' retval = os.system(fixed_cmd) if hasattr(os, "WEXITSTATUS"): status = os.WEXITSTATUS(retval) else: status = retval if status: raise OSError(status, "error running '%s'" % cmd) def _setup_command_prefix(): prefix = "" if sys.platform == "darwin": # http://forums.macosxhints.com/archive/index.php/t-43243.html # This is an Apple customization to `tar` to avoid creating # '._foo' files for extended-attributes for archived files. prefix = "COPY_EXTENDED_ATTRIBUTES_DISABLE=1 " return prefix #---- mainline def main(argv): logging.basicConfig(format="%(name)s: %(levelname)s: %(message)s") log.setLevel(logging.INFO) # Parse options. parser = optparse.OptionParser(prog="cutarelease", usage='', version="%prog " + __version__, description=__doc__, formatter=_NoReflowFormatter()) parser.add_option("-v", "--verbose", dest="log_level", action="store_const", const=logging.DEBUG, help="more verbose output") parser.add_option("-q", "--quiet", dest="log_level", action="store_const", const=logging.WARNING, help="quieter output (just warnings and errors)") parser.set_default("log_level", logging.INFO) parser.add_option("--test", action="store_true", help="run self-test and exit (use 'eol.py -v --test' for verbose test output)") parser.add_option("-p", "--project-name", metavar="NAME", help='the name of this project (default is the base dir name)', default=basename(os.getcwd())) parser.add_option("-f", "--version-file", metavar="[TYPE:]PATH", action='append', dest="version_files", help='The path to the project file holding the version info. Can be ' 'specified multiple times if more than one file should be updated ' 'with new version info. If excluded, it will be guessed.') parser.add_option("-n", "--dry-run", action="store_true", help='Do a dry-run', default=False) opts, args = parser.parse_args() log.setLevel(opts.log_level) cutarelease(opts.project_name, opts.version_files, dry_run=opts.dry_run) ## {{{ http://code.activestate.com/recipes/577258/ (r5+) if __name__ == "__main__": try: retval = main(sys.argv) except KeyboardInterrupt: sys.exit(1) except SystemExit: raise except: import traceback, logging if not log.handlers and not logging.root.handlers: logging.basicConfig() skip_it = False exc_info = sys.exc_info() if hasattr(exc_info[0], "__name__"): exc_class, exc, tb = exc_info if isinstance(exc, IOError) and exc.args[0] == 32: # Skip 'IOError: [Errno 32] Broken pipe': often a cancelling of `less`. skip_it = True if not skip_it: tb_path, tb_lineno, tb_func = traceback.extract_tb(tb)[-1][:3] log.error("%s (%s:%s in %s)", exc_info[1], tb_path, tb_lineno, tb_func) else: # string exception log.error(exc_info[0]) if not skip_it: if log.isEnabledFor(logging.DEBUG): traceback.print_exception(*exc_info) sys.exit(1) else: sys.exit(retval) ## end of http://code.activestate.com/recipes/577258/ }}}
alexdevmotion/scrapy-elastic-web-crawling
refs/heads/master
scrapy_redis/pipelines.py
19
from scrapy.utils.serialize import ScrapyJSONEncoder from twisted.internet.threads import deferToThread from . import connection class RedisPipeline(object): """Pushes serialized item into a redis list/queue""" def __init__(self, server): self.server = server self.encoder = ScrapyJSONEncoder() @classmethod def from_settings(cls, settings): server = connection.from_settings(settings) return cls(server) @classmethod def from_crawler(cls, crawler): return cls.from_settings(crawler.settings) def process_item(self, item, spider): return deferToThread(self._process_item, item, spider) def _process_item(self, item, spider): key = self.item_key(item, spider) data = self.encoder.encode(item) self.server.rpush(key, data) return item def item_key(self, item, spider): """Returns redis key based on given spider""" return "%s:items" % spider.name
codeworldprodigy/lab2
refs/heads/master
lib/werkzeug/contrib/fixers.py
464
# -*- coding: utf-8 -*- """ werkzeug.contrib.fixers ~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 0.5 This module includes various helpers that fix bugs in web servers. They may be necessary for some versions of a buggy web server but not others. We try to stay updated with the status of the bugs as good as possible but you have to make sure whether they fix the problem you encounter. If you notice bugs in webservers not fixed in this module consider contributing a patch. :copyright: Copyright 2009 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ try: from urllib import unquote except ImportError: from urllib.parse import unquote from werkzeug.http import parse_options_header, parse_cache_control_header, \ parse_set_header from werkzeug.useragents import UserAgent from werkzeug.datastructures import Headers, ResponseCacheControl class CGIRootFix(object): """Wrap the application in this middleware if you are using FastCGI or CGI and you have problems with your app root being set to the cgi script's path instead of the path users are going to visit .. versionchanged:: 0.9 Added `app_root` parameter and renamed from `LighttpdCGIRootFix`. :param app: the WSGI application :param app_root: Defaulting to ``'/'``, you can set this to something else if your app is mounted somewhere else. """ def __init__(self, app, app_root='/'): self.app = app self.app_root = app_root def __call__(self, environ, start_response): # only set PATH_INFO for older versions of Lighty or if no # server software is provided. That's because the test was # added in newer Werkzeug versions and we don't want to break # people's code if they are using this fixer in a test that # does not set the SERVER_SOFTWARE key. if 'SERVER_SOFTWARE' not in environ or \ environ['SERVER_SOFTWARE'] < 'lighttpd/1.4.28': environ['PATH_INFO'] = environ.get('SCRIPT_NAME', '') + \ environ.get('PATH_INFO', '') environ['SCRIPT_NAME'] = self.app_root.strip('/') return self.app(environ, start_response) # backwards compatibility LighttpdCGIRootFix = CGIRootFix class PathInfoFromRequestUriFix(object): """On windows environment variables are limited to the system charset which makes it impossible to store the `PATH_INFO` variable in the environment without loss of information on some systems. This is for example a problem for CGI scripts on a Windows Apache. This fixer works by recreating the `PATH_INFO` from `REQUEST_URI`, `REQUEST_URL`, or `UNENCODED_URL` (whatever is available). Thus the fix can only be applied if the webserver supports either of these variables. :param app: the WSGI application """ def __init__(self, app): self.app = app def __call__(self, environ, start_response): for key in 'REQUEST_URL', 'REQUEST_URI', 'UNENCODED_URL': if key not in environ: continue request_uri = unquote(environ[key]) script_name = unquote(environ.get('SCRIPT_NAME', '')) if request_uri.startswith(script_name): environ['PATH_INFO'] = request_uri[len(script_name):] \ .split('?', 1)[0] break return self.app(environ, start_response) class ProxyFix(object): """This middleware can be applied to add HTTP proxy support to an application that was not designed with HTTP proxies in mind. It sets `REMOTE_ADDR`, `HTTP_HOST` from `X-Forwarded` headers. If you have more than one proxy server in front of your app, set `num_proxies` accordingly. Do not use this middleware in non-proxy setups for security reasons. The original values of `REMOTE_ADDR` and `HTTP_HOST` are stored in the WSGI environment as `werkzeug.proxy_fix.orig_remote_addr` and `werkzeug.proxy_fix.orig_http_host`. :param app: the WSGI application :param num_proxies: the number of proxy servers in front of the app. """ def __init__(self, app, num_proxies=1): self.app = app self.num_proxies = num_proxies def get_remote_addr(self, forwarded_for): """Selects the new remote addr from the given list of ips in X-Forwarded-For. By default it picks the one that the `num_proxies` proxy server provides. Before 0.9 it would always pick the first. .. versionadded:: 0.8 """ if len(forwarded_for) >= self.num_proxies: return forwarded_for[-1 * self.num_proxies] def __call__(self, environ, start_response): getter = environ.get forwarded_proto = getter('HTTP_X_FORWARDED_PROTO', '') forwarded_for = getter('HTTP_X_FORWARDED_FOR', '').split(',') forwarded_host = getter('HTTP_X_FORWARDED_HOST', '') environ.update({ 'werkzeug.proxy_fix.orig_wsgi_url_scheme': getter('wsgi.url_scheme'), 'werkzeug.proxy_fix.orig_remote_addr': getter('REMOTE_ADDR'), 'werkzeug.proxy_fix.orig_http_host': getter('HTTP_HOST') }) forwarded_for = [x for x in [x.strip() for x in forwarded_for] if x] remote_addr = self.get_remote_addr(forwarded_for) if remote_addr is not None: environ['REMOTE_ADDR'] = remote_addr if forwarded_host: environ['HTTP_HOST'] = forwarded_host if forwarded_proto: environ['wsgi.url_scheme'] = forwarded_proto return self.app(environ, start_response) class HeaderRewriterFix(object): """This middleware can remove response headers and add others. This is for example useful to remove the `Date` header from responses if you are using a server that adds that header, no matter if it's present or not or to add `X-Powered-By` headers:: app = HeaderRewriterFix(app, remove_headers=['Date'], add_headers=[('X-Powered-By', 'WSGI')]) :param app: the WSGI application :param remove_headers: a sequence of header keys that should be removed. :param add_headers: a sequence of ``(key, value)`` tuples that should be added. """ def __init__(self, app, remove_headers=None, add_headers=None): self.app = app self.remove_headers = set(x.lower() for x in (remove_headers or ())) self.add_headers = list(add_headers or ()) def __call__(self, environ, start_response): def rewriting_start_response(status, headers, exc_info=None): new_headers = [] for key, value in headers: if key.lower() not in self.remove_headers: new_headers.append((key, value)) new_headers += self.add_headers return start_response(status, new_headers, exc_info) return self.app(environ, rewriting_start_response) class InternetExplorerFix(object): """This middleware fixes a couple of bugs with Microsoft Internet Explorer. Currently the following fixes are applied: - removing of `Vary` headers for unsupported mimetypes which causes troubles with caching. Can be disabled by passing ``fix_vary=False`` to the constructor. see: http://support.microsoft.com/kb/824847/en-us - removes offending headers to work around caching bugs in Internet Explorer if `Content-Disposition` is set. Can be disabled by passing ``fix_attach=False`` to the constructor. If it does not detect affected Internet Explorer versions it won't touch the request / response. """ # This code was inspired by Django fixers for the same bugs. The # fix_vary and fix_attach fixers were originally implemented in Django # by Michael Axiak and is available as part of the Django project: # http://code.djangoproject.com/ticket/4148 def __init__(self, app, fix_vary=True, fix_attach=True): self.app = app self.fix_vary = fix_vary self.fix_attach = fix_attach def fix_headers(self, environ, headers, status=None): if self.fix_vary: header = headers.get('content-type', '') mimetype, options = parse_options_header(header) if mimetype not in ('text/html', 'text/plain', 'text/sgml'): headers.pop('vary', None) if self.fix_attach and 'content-disposition' in headers: pragma = parse_set_header(headers.get('pragma', '')) pragma.discard('no-cache') header = pragma.to_header() if not header: headers.pop('pragma', '') else: headers['Pragma'] = header header = headers.get('cache-control', '') if header: cc = parse_cache_control_header(header, cls=ResponseCacheControl) cc.no_cache = None cc.no_store = False header = cc.to_header() if not header: headers.pop('cache-control', '') else: headers['Cache-Control'] = header def run_fixed(self, environ, start_response): def fixing_start_response(status, headers, exc_info=None): headers = Headers(headers) self.fix_headers(environ, headers, status) return start_response(status, headers.to_wsgi_list(), exc_info) return self.app(environ, fixing_start_response) def __call__(self, environ, start_response): ua = UserAgent(environ) if ua.browser != 'msie': return self.app(environ, start_response) return self.run_fixed(environ, start_response)
eeshangarg/oh-mainline
refs/heads/master
vendor/packages/twisted/twisted/spread/ui/tkutil.py
60
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Utilities for building L{PB<twisted.spread.pb>} clients with L{Tkinter}. """ from Tkinter import * from tkSimpleDialog import _QueryString from tkFileDialog import _Dialog from twisted.spread import pb from twisted.internet import reactor from twisted import copyright import string #normalFont = Font("-adobe-courier-medium-r-normal-*-*-120-*-*-m-*-iso8859-1") #boldFont = Font("-adobe-courier-bold-r-normal-*-*-120-*-*-m-*-iso8859-1") #errorFont = Font("-adobe-courier-medium-o-normal-*-*-120-*-*-m-*-iso8859-1") class _QueryPassword(_QueryString): def body(self, master): w = Label(master, text=self.prompt, justify=LEFT) w.grid(row=0, padx=5, sticky=W) self.entry = Entry(master, name="entry",show="*") self.entry.grid(row=1, padx=5, sticky=W+E) if self.initialvalue: self.entry.insert(0, self.initialvalue) self.entry.select_range(0, END) return self.entry def askpassword(title, prompt, **kw): '''get a password from the user @param title: the dialog title @param prompt: the label text @param **kw: see L{SimpleDialog} class @returns: a string ''' d = apply(_QueryPassword, (title, prompt), kw) return d.result def grid_setexpand(widget): cols,rows=widget.grid_size() for i in range(cols): widget.columnconfigure(i,weight=1) for i in range(rows): widget.rowconfigure(i,weight=1) class CList(Frame): def __init__(self,parent,labels,disablesorting=0,**kw): Frame.__init__(self,parent) self.labels=labels self.lists=[] self.disablesorting=disablesorting kw["exportselection"]=0 for i in range(len(labels)): b=Button(self,text=labels[i],anchor=W,height=1,pady=0) b.config(command=lambda s=self,i=i:s.setSort(i)) b.grid(column=i,row=0,sticky=N+E+W) box=apply(Listbox,(self,),kw) box.grid(column=i,row=1,sticky=N+E+S+W) self.lists.append(box) grid_setexpand(self) self.rowconfigure(0,weight=0) self._callall("bind",'<Button-1>',self.Button1) self._callall("bind",'<B1-Motion>',self.Button1) self.bind('<Up>',self.UpKey) self.bind('<Down>',self.DownKey) self.sort=None def _callall(self,funcname,*args,**kw): rets=[] for l in self.lists: func=getattr(l,funcname) ret=apply(func,args,kw) if ret!=None: rets.append(ret) if rets: return rets def Button1(self,e): index=self.nearest(e.y) self.select_clear(0,END) self.select_set(index) self.activate(index) return "break" def UpKey(self,e): index=self.index(ACTIVE) if index: self.select_clear(0,END) self.select_set(index-1) return "break" def DownKey(self,e): index=self.index(ACTIVE) if index!=self.size()-1: self.select_clear(0,END) self.select_set(index+1) return "break" def setSort(self,index): if self.sort==None: self.sort=[index,1] elif self.sort[0]==index: self.sort[1]=-self.sort[1] else: self.sort=[index,1] self._sort() def _sort(self): if self.disablesorting: return if self.sort==None: return ind,direc=self.sort li=list(self.get(0,END)) li.sort(lambda x,y,i=ind,d=direc:d*cmp(x[i],y[i])) self.delete(0,END) for l in li: self._insert(END,l) def activate(self,index): self._callall("activate",index) # def bbox(self,index): # return self._callall("bbox",index) def curselection(self): return self.lists[0].curselection() def delete(self,*args): apply(self._callall,("delete",)+args) def get(self,*args): bad=apply(self._callall,("get",)+args) if len(args)==1: return bad ret=[] for i in range(len(bad[0])): r=[] for j in range(len(bad)): r.append(bad[j][i]) ret.append(r) return ret def index(self,index): return self.lists[0].index(index) def insert(self,index,items): self._insert(index,items) self._sort() def _insert(self,index,items): for i in range(len(items)): self.lists[i].insert(index,items[i]) def nearest(self,y): return self.lists[0].nearest(y) def see(self,index): self._callall("see",index) def size(self): return self.lists[0].size() def selection_anchor(self,index): self._callall("selection_anchor",index) select_anchor=selection_anchor def selection_clear(self,*args): apply(self._callall,("selection_clear",)+args) select_clear=selection_clear def selection_includes(self,index): return self.lists[0].select_includes(index) select_includes=selection_includes def selection_set(self,*args): apply(self._callall,("selection_set",)+args) select_set=selection_set def xview(self,*args): if not args: return self.lists[0].xview() apply(self._callall,("xview",)+args) def yview(self,*args): if not args: return self.lists[0].yview() apply(self._callall,("yview",)+args) class ProgressBar: def __init__(self, master=None, orientation="horizontal", min=0, max=100, width=100, height=18, doLabel=1, appearance="sunken", fillColor="blue", background="gray", labelColor="yellow", labelFont="Verdana", labelText="", labelFormat="%d%%", value=0, bd=2): # preserve various values self.master=master self.orientation=orientation self.min=min self.max=max self.width=width self.height=height self.doLabel=doLabel self.fillColor=fillColor self.labelFont= labelFont self.labelColor=labelColor self.background=background self.labelText=labelText self.labelFormat=labelFormat self.value=value self.frame=Frame(master, relief=appearance, bd=bd) self.canvas=Canvas(self.frame, height=height, width=width, bd=0, highlightthickness=0, background=background) self.scale=self.canvas.create_rectangle(0, 0, width, height, fill=fillColor) self.label=self.canvas.create_text(self.canvas.winfo_reqwidth() / 2, height / 2, text=labelText, anchor="c", fill=labelColor, font=self.labelFont) self.update() self.canvas.pack(side='top', fill='x', expand='no') def updateProgress(self, newValue, newMax=None): if newMax: self.max = newMax self.value = newValue self.update() def update(self): # Trim the values to be between min and max value=self.value if value > self.max: value = self.max if value < self.min: value = self.min # Adjust the rectangle if self.orientation == "horizontal": self.canvas.coords(self.scale, 0, 0, float(value) / self.max * self.width, self.height) else: self.canvas.coords(self.scale, 0, self.height - (float(value) / self.max*self.height), self.width, self.height) # Now update the colors self.canvas.itemconfig(self.scale, fill=self.fillColor) self.canvas.itemconfig(self.label, fill=self.labelColor) # And update the label if self.doLabel: if value: if value >= 0: pvalue = int((float(value) / float(self.max)) * 100.0) else: pvalue = 0 self.canvas.itemconfig(self.label, text=self.labelFormat % pvalue) else: self.canvas.itemconfig(self.label, text='') else: self.canvas.itemconfig(self.label, text=self.labelFormat % self.labelText) self.canvas.update_idletasks() class DirectoryBrowser(_Dialog): command = "tk_chooseDirectory" def askdirectory(**options): "Ask for a directory to save to." return apply(DirectoryBrowser, (), options).show() class GenericLogin(Toplevel): def __init__(self,callback,buttons): Toplevel.__init__(self) self.callback=callback Label(self,text="Twisted v%s"%copyright.version).grid(column=0,row=0,columnspan=2) self.entries={} row=1 for stuff in buttons: label,value=stuff[:2] if len(stuff)==3: dict=stuff[2] else: dict={} Label(self,text=label+": ").grid(column=0,row=row) e=apply(Entry,(self,),dict) e.grid(column=1,row=row) e.insert(0,value) self.entries[label]=e row=row+1 Button(self,text="Login",command=self.doLogin).grid(column=0,row=row) Button(self,text="Cancel",command=self.close).grid(column=1,row=row) self.protocol('WM_DELETE_WINDOW',self.close) def close(self): self.tk.quit() self.destroy() def doLogin(self): values={} for k in self.entries.keys(): values[string.lower(k)]=self.entries[k].get() self.callback(values) self.destroy() class Login(Toplevel): def __init__(self, callback, referenced = None, initialUser = "guest", initialPassword = "guest", initialHostname = "localhost", initialService = "", initialPortno = pb.portno): Toplevel.__init__(self) version_label = Label(self,text="Twisted v%s" % copyright.version) self.pbReferenceable = referenced self.pbCallback = callback # version_label.show() self.username = Entry(self) self.password = Entry(self,show='*') self.hostname = Entry(self) self.service = Entry(self) self.port = Entry(self) self.username.insert(0,initialUser) self.password.insert(0,initialPassword) self.service.insert(0,initialService) self.hostname.insert(0,initialHostname) self.port.insert(0,str(initialPortno)) userlbl=Label(self,text="Username:") passlbl=Label(self,text="Password:") servicelbl=Label(self,text="Service:") hostlbl=Label(self,text="Hostname:") portlbl=Label(self,text="Port #:") self.logvar=StringVar() self.logvar.set("Protocol PB-%s"%pb.Broker.version) self.logstat = Label(self,textvariable=self.logvar) self.okbutton = Button(self,text="Log In", command=self.login) version_label.grid(column=0,row=0,columnspan=2) z=0 for i in [[userlbl,self.username], [passlbl,self.password], [hostlbl,self.hostname], [servicelbl,self.service], [portlbl,self.port]]: i[0].grid(column=0,row=z+1) i[1].grid(column=1,row=z+1) z = z+1 self.logstat.grid(column=0,row=6,columnspan=2) self.okbutton.grid(column=0,row=7,columnspan=2) self.protocol('WM_DELETE_WINDOW',self.tk.quit) def loginReset(self): self.logvar.set("Idle.") def loginReport(self, txt): self.logvar.set(txt) self.after(30000, self.loginReset) def login(self): host = self.hostname.get() port = self.port.get() service = self.service.get() try: port = int(port) except: pass user = self.username.get() pswd = self.password.get() pb.connect(host, port, user, pswd, service, client=self.pbReferenceable).addCallback(self.pbCallback).addErrback( self.couldNotConnect) def couldNotConnect(self,f): self.loginReport("could not connect:"+f.getErrorMessage()) if __name__=="__main__": root=Tk() o=CList(root,["Username","Online","Auto-Logon","Gateway"]) o.pack() for i in range(0,16,4): o.insert(END,[i,i+1,i+2,i+3]) mainloop()
Shiroy/servo
refs/heads/master
tests/wpt/harness/wptrunner/executors/base.py
21
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import hashlib import json import os import traceback import urlparse from abc import ABCMeta, abstractmethod from ..testrunner import Stop here = os.path.split(__file__)[0] def executor_kwargs(test_type, server_config, cache_manager, **kwargs): timeout_multiplier = kwargs["timeout_multiplier"] if timeout_multiplier is None: timeout_multiplier = 1 executor_kwargs = {"server_config": server_config, "timeout_multiplier": timeout_multiplier, "debug_info": kwargs["debug_info"]} if test_type == "reftest": executor_kwargs["screenshot_cache"] = cache_manager.dict() return executor_kwargs def strip_server(url): """Remove the scheme and netloc from a url, leaving only the path and any query or fragment. url - the url to strip e.g. http://example.org:8000/tests?id=1#2 becomes /tests?id=1#2""" url_parts = list(urlparse.urlsplit(url)) url_parts[0] = "" url_parts[1] = "" return urlparse.urlunsplit(url_parts) class TestharnessResultConverter(object): harness_codes = {0: "OK", 1: "ERROR", 2: "TIMEOUT"} test_codes = {0: "PASS", 1: "FAIL", 2: "TIMEOUT", 3: "NOTRUN"} def __call__(self, test, result): """Convert a JSON result into a (TestResult, [SubtestResult]) tuple""" result_url, status, message, stack, subtest_results = result assert result_url == test.url, ("Got results from %s, expected %s" % (result_url, test.url)) harness_result = test.result_cls(self.harness_codes[status], message) return (harness_result, [test.subtest_result_cls(name, self.test_codes[status], message, stack) for name, status, message, stack in subtest_results]) testharness_result_converter = TestharnessResultConverter() def reftest_result_converter(self, test, result): return (test.result_cls(result["status"], result["message"], extra=result.get("extra")), []) class ExecutorException(Exception): def __init__(self, status, message): self.status = status self.message = message class TestExecutor(object): __metaclass__ = ABCMeta test_type = None convert_result = None def __init__(self, browser, server_config, timeout_multiplier=1, debug_info=None): """Abstract Base class for object that actually executes the tests in a specific browser. Typically there will be a different TestExecutor subclass for each test type and method of executing tests. :param browser: ExecutorBrowser instance providing properties of the browser that will be tested. :param server_config: Dictionary of wptserve server configuration of the form stored in TestEnvironment.external_config :param timeout_multiplier: Multiplier relative to base timeout to use when setting test timeout. """ self.runner = None self.browser = browser self.server_config = server_config self.timeout_multiplier = timeout_multiplier self.debug_info = debug_info self.last_environment = {"protocol": "http", "prefs": {}} self.protocol = None # This must be set in subclasses @property def logger(self): """StructuredLogger for this executor""" if self.runner is not None: return self.runner.logger def setup(self, runner): """Run steps needed before tests can be started e.g. connecting to browser instance :param runner: TestRunner instance that is going to run the tests""" self.runner = runner self.protocol.setup(runner) def teardown(self): """Run cleanup steps after tests have finished""" self.protocol.teardown() def run_test(self, test): """Run a particular test. :param test: The test to run""" if test.environment != self.last_environment: self.on_environment_change(test.environment) try: result = self.do_test(test) except Exception as e: result = self.result_from_exception(test, e) if result is Stop: return result if result[0].status == "ERROR": self.logger.debug(result[0].message) self.last_environment = test.environment self.runner.send_message("test_ended", test, result) def server_url(self, protocol): return "%s://%s:%s" % (protocol, self.server_config["host"], self.server_config["ports"][protocol][0]) def test_url(self, test): return urlparse.urljoin(self.server_url(test.environment["protocol"]), test.url) @abstractmethod def do_test(self, test): """Test-type and protocol specific implementation of running a specific test. :param test: The test to run.""" pass def on_environment_change(self, new_environment): pass def result_from_exception(self, test, e): if hasattr(e, "status") and e.status in test.result_cls.statuses: status = e.status else: status = "ERROR" message = unicode(getattr(e, "message", "")) if message: message += "\n" message += traceback.format_exc(e) return test.result_cls(status, message), [] class TestharnessExecutor(TestExecutor): convert_result = testharness_result_converter class RefTestExecutor(TestExecutor): convert_result = reftest_result_converter def __init__(self, browser, server_config, timeout_multiplier=1, screenshot_cache=None, debug_info=None): TestExecutor.__init__(self, browser, server_config, timeout_multiplier=timeout_multiplier, debug_info=debug_info) self.screenshot_cache = screenshot_cache class RefTestImplementation(object): def __init__(self, executor): self.timeout_multiplier = executor.timeout_multiplier self.executor = executor # Cache of url:(screenshot hash, screenshot). Typically the # screenshot is None, but we set this value if a test fails # and the screenshot was taken from the cache so that we may # retrieve the screenshot from the cache directly in the future self.screenshot_cache = self.executor.screenshot_cache self.message = None @property def logger(self): return self.executor.logger def get_hash(self, test, viewport_size, dpi): timeout = test.timeout * self.timeout_multiplier key = (test.url, viewport_size, dpi) if key not in self.screenshot_cache: success, data = self.executor.screenshot(test, viewport_size, dpi) if not success: return False, data screenshot = data hash_value = hashlib.sha1(screenshot).hexdigest() self.screenshot_cache[key] = (hash_value, None) rv = (hash_value, screenshot) else: rv = self.screenshot_cache[key] self.message.append("%s %s" % (test.url, rv[0])) return True, rv def is_pass(self, lhs_hash, rhs_hash, relation): assert relation in ("==", "!=") self.message.append("Testing %s %s %s" % (lhs_hash, relation, rhs_hash)) return ((relation == "==" and lhs_hash == rhs_hash) or (relation == "!=" and lhs_hash != rhs_hash)) def run_test(self, test): viewport_size = test.viewport_size dpi = test.dpi self.message = [] # Depth-first search of reference tree, with the goal # of reachings a leaf node with only pass results stack = list(((test, item[0]), item[1]) for item in reversed(test.references)) while stack: hashes = [None, None] screenshots = [None, None] nodes, relation = stack.pop() for i, node in enumerate(nodes): success, data = self.get_hash(node, viewport_size, dpi) if success is False: return {"status": data[0], "message": data[1]} hashes[i], screenshots[i] = data if self.is_pass(hashes[0], hashes[1], relation): if nodes[1].references: stack.extend(list(((nodes[1], item[0]), item[1]) for item in reversed(nodes[1].references))) else: # We passed return {"status":"PASS", "message": None} # We failed, so construct a failure message for i, (node, screenshot) in enumerate(zip(nodes, screenshots)): if screenshot is None: success, screenshot = self.retake_screenshot(node, viewport_size, dpi) if success: screenshots[i] = screenshot log_data = [{"url": nodes[0].url, "screenshot": screenshots[0]}, relation, {"url": nodes[1].url, "screenshot": screenshots[1]}] return {"status": "FAIL", "message": "\n".join(self.message), "extra": {"reftest_screenshots": log_data}} def retake_screenshot(self, node, viewport_size, dpi): success, data = self.executor.screenshot(node, viewport_size, dpi) if not success: return False, data key = (node.url, viewport_size, dpi) hash_val, _ = self.screenshot_cache[key] self.screenshot_cache[key] = hash_val, data return True, data class Protocol(object): def __init__(self, executor, browser): self.executor = executor self.browser = browser @property def logger(self): return self.executor.logger def setup(self, runner): pass def teardown(self): pass def wait(self): pass
codenote/chromium-test
refs/heads/master
build/android/pylib/pexpect.py
70
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import os import sys _CHROME_SRC = os.path.join( os.path.abspath(os.path.dirname(__file__)), '..', '..', '..') _PEXPECT_PATH = os.path.join(_CHROME_SRC, 'third_party', 'pexpect') if _PEXPECT_PATH not in sys.path: sys.path.append(_PEXPECT_PATH) # pexpect is not available on all platforms. We allow this file to be imported # on platforms without pexpect and only fail when pexpect is actually used. try: from pexpect import * except: pass
todaychi/hue
refs/heads/master
desktop/core/ext-py/Django-1.6.10/tests/comment_tests/tests/__init__.py
56
from __future__ import absolute_import from django.contrib.auth.models import User from django.contrib.comments.forms import CommentForm from django.contrib.comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.test import TestCase from django.test.utils import override_settings from ..models import Article, Author # Shortcut CT = ContentType.objects.get_for_model # Helper base class for comment tests that need data. @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',)) class CommentTestCase(TestCase): fixtures = ["comment_tests"] urls = 'comment_tests.urls_default' def createSomeComments(self): # Two anonymous comments on two different objects c1 = Comment.objects.create( content_type = CT(Article), object_pk = "1", user_name = "Joe Somebody", user_email = "jsomebody@example.com", user_url = "http://example.com/~joe/", comment = "First!", site = Site.objects.get_current(), ) c2 = Comment.objects.create( content_type = CT(Author), object_pk = "1", user_name = "Joe Somebody", user_email = "jsomebody@example.com", user_url = "http://example.com/~joe/", comment = "First here, too!", site = Site.objects.get_current(), ) # Two authenticated comments: one on the same Article, and # one on a different Author user = User.objects.create( username = "frank_nobody", first_name = "Frank", last_name = "Nobody", email = "fnobody@example.com", password = "", is_staff = False, is_active = True, is_superuser = False, ) c3 = Comment.objects.create( content_type = CT(Article), object_pk = "1", user = user, user_url = "http://example.com/~frank/", comment = "Damn, I wanted to be first.", site = Site.objects.get_current(), ) c4 = Comment.objects.create( content_type = CT(Author), object_pk = "2", user = user, user_url = "http://example.com/~frank/", comment = "You get here first, too?", site = Site.objects.get_current(), ) return c1, c2, c3, c4 def getData(self): return { 'name' : 'Jim Bob', 'email' : 'jim.bob@example.com', 'url' : '', 'comment' : 'This is my comment', } def getValidData(self, obj): f = CommentForm(obj) d = self.getData() d.update(f.initial) return d from comment_tests.tests.test_app_api import * from comment_tests.tests.test_feeds import * from comment_tests.tests.test_models import * from comment_tests.tests.test_comment_form import * from comment_tests.tests.test_templatetags import * from comment_tests.tests.test_comment_view import * from comment_tests.tests.test_comment_utils_moderators import * from comment_tests.tests.test_moderation_views import *
pombredanne/pulp
refs/heads/master
server/pulp/server/db/model/consumer.py
6
# -*- coding: utf-8 -*- # # Copyright © 2012 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the implied warranties of MERCHANTABILITY, # NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should # have received a copy of GPLv2 along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. import datetime import hashlib import json from pulp.server.db.model.base import Model from pulp.server.db.model.reaper_base import ReaperMixin from pulp.common import dateutils # -- classes ----------------------------------------------------------------- class Consumer(Model): """ Represents a consumer of the content on Pulp server. :ivar consumer_id: uniquely identifies the consumer :type consumer_id: str :ivar display_name: user-friendly name of the consumer :type display_name: str :ivar description: user-friendly description of the consumer :type description: str :ivar notes: arbitrary key-value pairs pragmatically describing the consumer :type notes: dict :ivar capabilities: operations permitted on the consumer :type capabilities: dict :ivar rsa_pub: The consumer's RSA public key used for message authentication. :type rsa_pub: str """ RESOURCE_TEMPLATE = 'pulp:consumer:%s' collection_name = 'consumers' unique_indices = ('id',) search_indices = ('notes',) def __init__(self, consumer_id, display_name, description=None, notes=None, capabilities=None, rsa_pub=None): """ :param consumer_id: uniquely identifies the consumer :type consumer_id: str :param display_name: user-friendly name of the consumer :type display_name: str :param description: user-friendly description of the consumer :type description: str :param notes: arbitrary key-value pairs pragmatically describing the consumer :type notes: dict :param capabilities: operations permitted on the consumer :type capabilities: dict :param rsa_pub: The consumer's RSA public key used for authentication. :type rsa_pub: str """ super(Consumer, self).__init__() self.id = consumer_id self.display_name = display_name self.description = description self.notes = notes or {} self.capabilities = capabilities or {} self.rsa_pub = rsa_pub @classmethod def build_resource_tag(cls, consumer_id): """ :param consumer_id: unique ID for a consumer :type consumer_id: basestring :return: a globally unique identifier for the consumer that can be used in cross-type comparisons. :rtype: basestring """ return cls.RESOURCE_TEMPLATE % consumer_id class Bind(Model): """ Represents consumer binding to a repo/distributor. Each consumer action entry will be of the format: {id:<str>, action:<str>, status:<str>} * Status: (pending|succeeded|failed) * Action: (bind|unbind) :ivar consumer_id: uniquely identifies the consumer. :type consumer_id: str :ivar repo_id: uniquely identifies the repository :type repo_id: str :ivar distributor_id: uniquely identifies a distributor :type distributor_id: str :ivar notify_agent: indicates if the agent should be sent a message informing it of the binding :type notify_agent: bool :ivar binding_config: value only applicable to this particular binding :type binding_config: object :ivar consumer_actions: tracks consumer bind/unbind actions; see above for format :ivar deleted: indicates the bind has been deleted :type deleted: bool """ collection_name = 'consumer_bindings' unique_indices = ( ('repo_id', 'distributor_id', 'consumer_id'), ) search_indices = ( ('consumer_id',), ) class Action: # enumerated actions BIND = 'bind' UNBIND = 'unbind' class Status: # enumerated status PENDING = 'pending' SUCCEEDED = 'succeeded' FAILED = 'failed' def __init__(self, consumer_id, repo_id, distributor_id, notify_agent, binding_config): """ :param consumer_id: uniquely identifies the consumer. :type consumer_id: str :param repo_id: uniquely identifies the repository. :type repo_id: str :param distributor_id: uniquely identifies a distributor. :type distributor_id: str :ivar notify_agent: controls whether or not the consumer agent will be sent a message about the binding :type notify_agent: bool :ivar binding_config: configuration to pass the distributor during payload creation for this binding :type binding_config: object """ super(Bind, self).__init__() # Required, Unique self.consumer_id = consumer_id self.repo_id = repo_id self.distributor_id = distributor_id # Configuration self.notify_agent = notify_agent self.binding_config = binding_config # State self.consumer_actions = [] self.deleted = False class RepoProfileApplicability(Model): """ This class models a Mongo collection that is used to store pre-calculated applicability results for a given consumer profile_hash and repository ID. The applicability data is a dictionary structure that represents the applicable units for the given profile and repository. The profile itself is included here for ease of recalculating the applicability when a repository's contents change. The RepoProfileApplicabilityManager can be accessed through the classlevel "objects" attribute. """ collection_name = 'repo_profile_applicability' unique_indices = ( ('profile_hash', 'repo_id'), ) def __init__(self, profile_hash, repo_id, profile, applicability, _id=None, **kwargs): """ Construct a RepoProfileApplicability object. :param profile_hash: The hash of the profile that this object contains applicability data for :type profile_hash: basestring :param repo_id: The repo ID that this applicability data is for :type repo_id: basestring :param profile: The entire profile that resulted in the profile_hash :type profile: object :param applicability: A dictionary mapping content_type_ids to lists of applicable Unit IDs. :type applicability: dict :param _id: The MongoDB ID for this object, if it exists in the database :type _id: bson.objectid.ObjectId :param kwargs: unused, but collected to allow instantiation from Mongo query results :type kwargs: dict """ super(RepoProfileApplicability, self).__init__() self.profile_hash = profile_hash self.repo_id = repo_id self.profile = profile self.applicability = applicability self._id = _id # The superclass puts an unnecessary (and confusingly named) id attribute on this model. # Let's remove it. del self.id def delete(self): """ Delete this RepoProfileApplicability object from the database. """ self.get_collection().remove({'_id': self._id}) def save(self): """ Save any changes made to this RepoProfileApplicability model to the database. If it doesn't exist in the database already, insert a new record to represent it. """ # If this object's _id attribute is not None, then it represents an existing DB object. # Else, we need to create an object with this object's attributes new_document = {'profile_hash': self.profile_hash, 'repo_id': self.repo_id, 'profile': self.profile, 'applicability': self.applicability} if self._id is not None: self.get_collection().update({'_id': self._id}, new_document) else: # Let's set the _id attribute to the newly created document self._id = self.get_collection().insert(new_document) class UnitProfile(Model): """ Represents a consumer profile, which is a data structure that records which content is installed on a particular consumer for a particular type. Due to the nature of the data conversion used to generate a profile's hash, it is impossible for Pulp to know if the ordering of list structures found in the profile are significant or not. Therefore, the hash of a list must assume that the ordering of the list is significant. The SON objects that Pulp stores in the database cannot contain Python sets. It is up to the plugin Profilers to handle this limitation if they wish to store lists in the database in such a way that the order shouldn't matter for hash comparison purposes. In these cases, the Profiler must order the list in some repeatable manner, so that any two profiles that it wants the platform to consider as being the same will have exactly the same ordering to those lists. For example, the RPM profile contains a list of dictionaries, where each dictionary contains information about RPMs stored on a consumer. The order of the list is not important for the purpose of determining what is installed on the system - it might as well be a set. However, since a set cannot be stored in MongoDB, it is up to the RPM Profiler to sort the list of installed RPMs in some repeatable fashion, such that any two consumers that have exactly the same RPMs installed will end up with the same ordering of their RPMs in the database. :ivar consumer_id: A consumer ID. :type consumer_id: str :ivar content_type: The profile (unit) type ID. :type content_type: str :ivar profile: The stored profile. :type profile: object :ivar profile_hash: A hash of the profile, used for quick comparisons of profiles :type profile_hash: basestring """ collection_name = 'consumer_unit_profiles' unique_indices = ( ('consumer_id', 'content_type'), ) def __init__(self, consumer_id, content_type, profile, profile_hash=None): """ :param consumer_id: A consumer ID. :type consumer_id: str :param content_type: The profile (unit) type ID. :type content_type: str :param profile: The stored profile. :type profile: object :param profile_hash: A hash of the profile, used for quick comparisons of profiles. If it is None, the constructor will automatically calculate it based on the profile. :type profile_hash: basestring """ super(UnitProfile, self).__init__() self.consumer_id = consumer_id self.content_type = content_type self.profile = profile self.profile_hash = profile_hash if self.profile_hash is None: self.profile_hash = self.calculate_hash(self.profile) @staticmethod def calculate_hash(profile): """ Return a hash of profile. This hash is useful for quickly comparing profiles to determine if they are the same. :param profile: The profile structure you wish to hash :type profile: object :return: Hash of profile :rtype: basestring """ # Don't use any whitespace in the json separators, and sort dictionary keys to be repeatable serialized_profile = json.dumps(profile, separators=(',', ':'), sort_keys=True) hasher = hashlib.sha256(serialized_profile) return hasher.hexdigest() class ConsumerHistoryEvent(Model, ReaperMixin): """ Represents a consumer history event. The documents in this collection may be reaped, so it inherits from ReaperMixin. :ivar consumer_id: identifies the consumer :type consumer_id: str :ivar originator: consumer or username of the admin who initiated the event :type originator: str :param type: event type current supported event types: 'consumer_registered', 'consumer_unregistered', 'repo_bound', 'repo_unbound', 'content_unit_installed', 'content_unit_uninstalled', 'unit_profile_changed', 'added_to_group', 'removed_from_group' :type type: str :param details: event details :type details: dict """ collection_name = 'consumer_history' search_indices = ('consumer_id', 'originator', 'type', ) def __init__(self, consumer_id, originator, event_type, details): super(ConsumerHistoryEvent, self).__init__() self.consumer_id = consumer_id self.originator = originator self.type = event_type self.details = details now = datetime.datetime.now(dateutils.utc_tz()) self.timestamp = dateutils.format_iso8601_datetime(now) class ConsumerGroup(Model): """ Represents a group of consumers. """ collection_name = 'consumer_groups' search_indices = ('display_name', 'consumer_ids') def __init__(self, consumer_group_id, display_name=None, description=None, consumer_ids=None, notes=None): super(ConsumerGroup, self).__init__() self.id = consumer_group_id self.display_name = display_name self.description = description self.consumer_ids = consumer_ids or [] self.notes = notes or {} self.scratchpad = None
mcanthony/antlr4
refs/heads/master
runtime/Python3/src/antlr4/LL1Analyzer.py
17
# # [The "BSD license"] # Copyright (c) 2012 Terence Parr # Copyright (c) 2012 Sam Harwell # Copyright (c) 2014 Eric Vergnaud # 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. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 antlr4.IntervalSet import IntervalSet from antlr4.Token import Token from antlr4.PredictionContext import PredictionContext, SingletonPredictionContext, PredictionContextFromRuleContext from antlr4.RuleContext import RuleContext from antlr4.atn.ATN import ATN from antlr4.atn.ATNConfig import ATNConfig from antlr4.atn.ATNState import ATNState, RuleStopState from antlr4.atn.Transition import WildcardTransition, NotSetTransition, AbstractPredicateTransition, RuleTransition class LL1Analyzer (object): #* Special value added to the lookahead sets to indicate that we hit # a predicate during analysis if {@code seeThruPreds==false}. #/ HIT_PRED = Token.INVALID_TYPE def __init__(self, atn:ATN): self.atn = atn #* # Calculates the SLL(1) expected lookahead set for each outgoing transition # of an {@link ATNState}. The returned array has one element for each # outgoing transition in {@code s}. If the closure from transition # <em>i</em> leads to a semantic predicate before matching a symbol, the # element at index <em>i</em> of the result will be {@code null}. # # @param s the ATN state # @return the expected symbols for each outgoing transition of {@code s}. #/ def getDecisionLookahead(self, s:ATNState): if s is None: return None count = len(s.transitions) look = [] * count for alt in range(0, count): look[alt] = set() lookBusy = set() seeThruPreds = False # fail to get lookahead upon pred self._LOOK(s.transition(alt).target, None, PredictionContext.EMPTY, look[alt], lookBusy, set(), seeThruPreds, False) # Wipe out lookahead for this alternative if we found nothing # or we had a predicate when we !seeThruPreds if len(look[alt])==0 or self.HIT_PRED in look[alt]: look[alt] = None return look #* # Compute set of tokens that can follow {@code s} in the ATN in the # specified {@code ctx}. # # <p>If {@code ctx} is {@code null} and the end of the rule containing # {@code s} is reached, {@link Token#EPSILON} is added to the result set. # If {@code ctx} is not {@code null} and the end of the outermost rule is # reached, {@link Token#EOF} is added to the result set.</p> # # @param s the ATN state # @param stopState the ATN state to stop at. This can be a # {@link BlockEndState} to detect epsilon paths through a closure. # @param ctx the complete parser context, or {@code null} if the context # should be ignored # # @return The set of tokens that can follow {@code s} in the ATN in the # specified {@code ctx}. #/ def LOOK(self, s:ATNState, stopState:ATNState=None, ctx:RuleContext=None): r = IntervalSet() seeThruPreds = True # ignore preds; get all lookahead lookContext = PredictionContextFromRuleContext(s.atn, ctx) if ctx is not None else None self._LOOK(s, stopState, lookContext, r, set(), set(), seeThruPreds, True) return r #* # Compute set of tokens that can follow {@code s} in the ATN in the # specified {@code ctx}. # # <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the # rule containing {@code s} is reached, {@link Token#EPSILON} is added to # the result set. If {@code ctx} is not {@code null} and {@code addEOF} is # {@code true} and {@code stopState} or the end of the outermost rule is # reached, {@link Token#EOF} is added to the result set.</p> # # @param s the ATN state. # @param stopState the ATN state to stop at. This can be a # {@link BlockEndState} to detect epsilon paths through a closure. # @param ctx The outer context, or {@code null} if the outer context should # not be used. # @param look The result lookahead set. # @param lookBusy A set used for preventing epsilon closures in the ATN # from causing a stack overflow. Outside code should pass # {@code new HashSet<ATNConfig>} for this argument. # @param calledRuleStack A set used for preventing left recursion in the # ATN from causing a stack overflow. Outside code should pass # {@code new BitSet()} for this argument. # @param seeThruPreds {@code true} to true semantic predicates as # implicitly {@code true} and "see through them", otherwise {@code false} # to treat semantic predicates as opaque and add {@link #HIT_PRED} to the # result if one is encountered. # @param addEOF Add {@link Token#EOF} to the result if the end of the # outermost context is reached. This parameter has no effect if {@code ctx} # is {@code null}. #/ def _LOOK(self, s:ATNState, stopState:ATNState , ctx:PredictionContext, look:IntervalSet, lookBusy:set, calledRuleStack:set, seeThruPreds:bool, addEOF:bool): c = ATNConfig(s, 0, ctx) if c in lookBusy: return lookBusy.add(c) if s == stopState: if ctx is None: look.addOne(Token.EPSILON) return elif ctx.isEmpty() and addEOF: look.addOne(Token.EOF) return if isinstance(s, RuleStopState ): if ctx is None: look.addOne(Token.EPSILON) return elif ctx.isEmpty() and addEOF: look.addOne(Token.EOF) return if ctx != PredictionContext.EMPTY: # run thru all possible stack tops in ctx for i in range(0, len(ctx)): returnState = self.atn.states[ctx.getReturnState(i)] removed = returnState.ruleIndex in calledRuleStack try: calledRuleStack.discard(returnState.ruleIndex) self._LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF) finally: if removed: calledRuleStack.add(returnState.ruleIndex) return for t in s.transitions: if type(t) == RuleTransition: if t.target.ruleIndex in calledRuleStack: continue newContext = SingletonPredictionContext.create(ctx, t.followState.stateNumber) try: calledRuleStack.add(t.target.ruleIndex) self._LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) finally: calledRuleStack.remove(t.target.ruleIndex) elif isinstance(t, AbstractPredicateTransition ): if seeThruPreds: self._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) else: look.addOne(self.HIT_PRED) elif t.isEpsilon: self._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) elif type(t) == WildcardTransition: look.addRange( range(Token.MIN_USER_TOKEN_TYPE, self.atn.maxTokenType + 1) ) else: set_ = t.label if set_ is not None: if isinstance(t, NotSetTransition): set_ = set_.complement(Token.MIN_USER_TOKEN_TYPE, self.atn.maxTokenType) look.addSet(set_)
aleaxit/pysolper
refs/heads/master
permit/lib/dist/tipfy/appengine/__init__.py
9
import os # App Engine flags. SERVER_SOFTWARE = os.environ.get('SERVER_SOFTWARE', '') #: The application ID as defined in *app.yaml*. APPLICATION_ID = os.environ.get('APPLICATION_ID') #: The deployed version ID. Always '1' when using the dev server. CURRENT_VERSION_ID = os.environ.get('CURRENT_VERSION_ID', '1') #: True if the app is using App Engine dev server, False otherwise. DEV_APPSERVER = SERVER_SOFTWARE.startswith('Development') #: True if the app is running on App Engine, False otherwise. APPENGINE = (APPLICATION_ID is not None and (DEV_APPSERVER or SERVER_SOFTWARE.startswith('Google App Engine')))