code
stringlengths
1
25.8M
language
stringclasses
18 values
source
stringclasses
4 values
repo
stringclasses
78 values
path
stringlengths
0
268
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ TAP plugin for creating telnet- and ssh-accessible manhole servers. @author: Jp Calderone """ from zope.interface import implements from twisted.internet import protocol from twisted.application import service, strports from twisted.conch.ssh import session from twisted.conch import interfaces as iconch from twisted.cred import portal, checkers from twisted.python import usage from twisted.conch.insults import insults from twisted.conch import manhole, manhole_ssh, telnet class makeTelnetProtocol: def __init__(self, portal): self.portal = portal def __call__(self): auth = telnet.AuthenticatingTelnetProtocol args = (self.portal,) return telnet.TelnetTransport(auth, *args) class chainedProtocolFactory: def __init__(self, namespace): self.namespace = namespace def __call__(self): return insults.ServerProtocol(manhole.ColoredManhole, self.namespace) class _StupidRealm: implements(portal.IRealm) def __init__(self, proto, *a, **kw): self.protocolFactory = proto self.protocolArgs = a self.protocolKwArgs = kw def requestAvatar(self, avatarId, *interfaces): if telnet.ITelnetProtocol in interfaces: return (telnet.ITelnetProtocol, self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs), lambda: None) raise NotImplementedError() class Options(usage.Options): optParameters = [ ["telnetPort", "t", None, "strports description of the address on which to listen for telnet connections"], ["sshPort", "s", None, "strports description of the address on which to listen for ssh connections"], ["passwd", "p", "/etc/passwd", "name of a passwd(5)-format username/password file"]] def __init__(self): usage.Options.__init__(self) self.users = [] self['namespace'] = None def opt_user(self, name): self.users.append(name) def postOptions(self): if self['telnetPort'] is None and self['sshPort'] is None: raise usage.UsageError("At least one of --telnetPort and --sshPort must be specified") def makeService(options): """Create a manhole server service. @type options: C{dict} @param options: A mapping describing the configuration of the desired service. Recognized key/value pairs are:: "telnetPort": strports description of the address on which to listen for telnet connections. If None, no telnet service will be started. "sshPort": strports description of the address on which to listen for ssh connections. If None, no ssh service will be started. "namespace": dictionary containing desired initial locals for manhole connections. If None, an empty dictionary will be used. "passwd": Name of a passwd(5)-format username/password file. @rtype: L{twisted.application.service.IService} @return: A manhole service. """ svc = service.MultiService() namespace = options['namespace'] if namespace is None: namespace = {} checker = checkers.FilePasswordDB(options['passwd']) if options['telnetPort']: telnetRealm = _StupidRealm(telnet.TelnetBootstrapProtocol, insults.ServerProtocol, manhole.ColoredManhole, namespace) telnetPortal = portal.Portal(telnetRealm, [checker]) telnetFactory = protocol.ServerFactory() telnetFactory.protocol = makeTelnetProtocol(telnetPortal) telnetService = strports.service(options['telnetPort'], telnetFactory) telnetService.setServiceParent(svc) if options['sshPort']: sshRealm = manhole_ssh.TerminalRealm() sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace) sshPortal = portal.Portal(sshRealm, [checker]) sshFactory = manhole_ssh.ConchFactory(sshPortal) sshService = strports.service(options['sshPort'], sshFactory) sshService.setServiceParent(svc) return svc
unknown
codeparrot/codeparrot-clean
# module pyparsing.py # # Copyright (c) 2003-2008 Paul T. McGuire # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # #from __future__ import generators __doc__ = \ """ pyparsing module - Classes and methods to define and execute parsing grammars The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you don't need to learn a new syntax for defining grammars or matching expressions - the parsing module provides a library of classes that you use to construct the grammar directly in Python. Here is a program to parse "Hello, World!" (or any greeting of the form "<salutation>, <addressee>!"):: from pyparsing import Word, alphas # define grammar of a greeting greet = Word( alphas ) + "," + Word( alphas ) + "!" hello = "Hello, World!" print hello, "->", greet.parseString( hello ) The program outputs the following:: Hello, World! -> ['Hello', ',', 'World', '!'] The Python representation of the grammar is quite readable, owing to the self-explanatory class names, and the use of '+', '|' and '^' operators. The parsed results returned from parseString() can be accessed as a nested list, a dictionary, or an object with named attributes. The pyparsing module handles some of the problems that are typically vexing when writing text parsers: - extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.) - quoted strings - embedded comments """ __version__ = "1.4.11" __versionTime__ = "10 February 2008 17:28" __author__ = "Paul McGuire <ptmcg@users.sourceforge.net>" import string from weakref import ref as wkref import copy,sys import warnings import re import sre_constants import xml.sax.saxutils #~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) ) """ Detect if we are running version 3.X and make appropriate changes Robert A. Clark """ if sys.version_info[0] > 2: __MAX_INT__ = sys.maxsize __BASE_STRING__ = str else: __MAX_INT__ = sys.maxint __BASE_STRING__ = basestring def _ustr(obj): """Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It then < returns the unicode object | encodes it with the default encoding | ... >. """ try: # If this works, then _ustr(obj) has the same behaviour as str(obj), so # it won't break any existing code. return str(obj) except UnicodeEncodeError: # The Python docs (http://docs.python.org/ref/customization.html#l2h-182) # state that "The return value must be a string object". However, does a # unicode object (being a subclass of basestring) count as a "string # object"? # If so, then return a unicode object: return unicode(obj) # Else encode it... but how? There are many choices... :) # Replace unprintables with escape codes? #return unicode(obj).encode(sys.getdefaultencoding(), 'backslashreplace_errors') # Replace unprintables with question marks? #return unicode(obj).encode(sys.getdefaultencoding(), 'replace') # ... def _str2dict(strg): return dict( [(c,0) for c in strg] ) #~ return set( [c for c in strg] ) class _Constants(object): pass alphas = string.lowercase + string.uppercase nums = string.digits hexnums = nums + "ABCDEFabcdef" alphanums = alphas + nums _bslash = "\\" printables = "".join( [ c for c in string.printable if c not in string.whitespace ] ) class ParseBaseException(Exception): """base exception class for all parsing runtime exceptions""" __slots__ = ( "loc","msg","pstr","parserElement" ) # Performance tuning: we construct a *lot* of these, so keep this # constructor as small and fast as possible def __init__( self, pstr, loc=0, msg=None, elem=None ): self.loc = loc if msg is None: self.msg = pstr self.pstr = "" else: self.msg = msg self.pstr = pstr self.parserElement = elem def __getattr__( self, aname ): """supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text """ if( aname == "lineno" ): return lineno( self.loc, self.pstr ) elif( aname in ("col", "column") ): return col( self.loc, self.pstr ) elif( aname == "line" ): return line( self.loc, self.pstr ) else: raise AttributeError, aname def __str__( self ): return "%s (at char %d), (line:%d, col:%d)" % \ ( self.msg, self.loc, self.lineno, self.column ) def __repr__( self ): return _ustr(self) def markInputline( self, markerString = ">!<" ): """Extracts the exception line from the input string, and marks the location of the exception with a special symbol. """ line_str = self.line line_column = self.column - 1 if markerString: line_str = "".join( [line_str[:line_column], markerString, line_str[line_column:]]) return line_str.strip() class ParseException(ParseBaseException): """exception thrown when parse expressions don't match class; supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text """ pass class ParseFatalException(ParseBaseException): """user-throwable exception thrown when inconsistent parse content is found; stops all parsing immediately""" pass #~ class ReparseException(ParseBaseException): #~ """Experimental class - parse actions can raise this exception to cause #~ pyparsing to reparse the input string: #~ - with a modified input string, and/or #~ - with a modified start location #~ Set the values of the ReparseException in the constructor, and raise the #~ exception in a parse action to cause pyparsing to use the new string/location. #~ Setting the values as None causes no change to be made. #~ """ #~ def __init_( self, newstring, restartLoc ): #~ self.newParseText = newstring #~ self.reparseLoc = restartLoc class RecursiveGrammarException(Exception): """exception thrown by validate() if the grammar could be improperly recursive""" def __init__( self, parseElementList ): self.parseElementTrace = parseElementList def __str__( self ): return "RecursiveGrammarException: %s" % self.parseElementTrace class _ParseResultsWithOffset(object): def __init__(self,p1,p2): self.tup = (p1,p2) def __getitem__(self,i): return self.tup[i] def __repr__(self): return repr(self.tup) class ParseResults(object): """Structured parse results, to provide multiple means of access to the parsed data: - as a list (len(results)) - by list index (results[0], results[1], etc.) - by attribute (results.<resultsName>) """ __slots__ = ( "__toklist", "__tokdict", "__doinit", "__name", "__parent", "__accumNames", "__weakref__" ) def __new__(cls, toklist, name=None, asList=True, modal=True ): if isinstance(toklist, cls): return toklist retobj = object.__new__(cls) retobj.__doinit = True return retobj # Performance tuning: we construct a *lot* of these, so keep this # constructor as small and fast as possible def __init__( self, toklist, name=None, asList=True, modal=True ): if self.__doinit: self.__doinit = False self.__name = None self.__parent = None self.__accumNames = {} if isinstance(toklist, list): self.__toklist = toklist[:] else: self.__toklist = [toklist] self.__tokdict = dict() # this line is related to debugging the asXML bug #~ asList = False if name: if not modal: self.__accumNames[name] = 0 if isinstance(name,int): name = _ustr(name) # will always return a str, but use _ustr for consistency self.__name = name if not toklist in (None,'',[]): if isinstance(toklist,__BASE_STRING__): toklist = [ toklist ] if asList: if isinstance(toklist,ParseResults): self[name] = _ParseResultsWithOffset(toklist.copy(),-1) else: self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),-1) self[name].__name = name else: try: self[name] = toklist[0] except (KeyError,TypeError): self[name] = toklist def __getitem__( self, i ): if isinstance( i, (int,slice) ): return self.__toklist[i] else: if i not in self.__accumNames: return self.__tokdict[i][-1][0] else: return ParseResults([ v[0] for v in self.__tokdict[i] ]) def __setitem__( self, k, v ): if isinstance(v,_ParseResultsWithOffset): self.__tokdict[k] = self.__tokdict.get(k,list()) + [v] sub = v[0] elif isinstance(k,int): self.__toklist[k] = v sub = v else: self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)] sub = v if isinstance(sub,ParseResults): sub.__parent = wkref(self) def __delitem__( self, i ): if isinstance(i,(int,slice)): mylen = len( self.__toklist ) del self.__toklist[i] # convert int to slice if isinstance(i, int): if i < 0: i += mylen i = slice(i, i+1) # get removed indices removed = range(*i.indices(mylen)) removed.reverse() # fixup indices in token dictionary for name in self.__tokdict.keys(): occurrences = self.__tokdict[name] for j in removed: for k, (value, position) in enumerate(occurrences): occurrences[k] = _ParseResultsWithOffset(value, position - (position > j)) else: del self.__tokdict[i] def __contains__( self, k ): return self.__tokdict.has_key(k) def __len__( self ): return len( self.__toklist ) def __bool__(self): return len( self.__toklist ) > 0 def __nonzero__( self ): return self.__bool__() def __iter__( self ): return iter( self.__toklist ) def __reversed__( self ): return iter( reversed(self.__toklist) ) def keys( self ): """Returns all named result keys.""" return self.__tokdict.keys() def pop( self, index=-1 ): """Removes and returns item at specified index (default=last). Will work with either numeric indices or dict-key indicies.""" ret = self[index] del self[index] return ret def get(self, key, defaultValue=None): """Returns named result matching the given key, or if there is no such name, then returns the given defaultValue or None if no defaultValue is specified.""" if key in self: return self[key] else: return defaultValue def insert( self, index, insStr ): self.__toklist.insert(index, insStr) # fixup indices in token dictionary for name in self.__tokdict.keys(): occurrences = self.__tokdict[name] for k, (value, position) in enumerate(occurrences): occurrences[k] = _ParseResultsWithOffset(value, position + (position > j)) def items( self ): """Returns all named result keys and values as a list of tuples.""" return [(k,self[k]) for k in self.__tokdict.keys()] def values( self ): """Returns all named result values.""" return [ v[-1][0] for v in self.__tokdict.values() ] def __getattr__( self, name ): if name not in self.__slots__: if self.__tokdict.has_key( name ): if name not in self.__accumNames: return self.__tokdict[name][-1][0] else: return ParseResults([ v[0] for v in self.__tokdict[name] ]) else: return "" return None def __add__( self, other ): ret = self.copy() ret += other return ret def __iadd__( self, other ): if other.__tokdict: offset = len(self.__toklist) addoffset = ( lambda a: (a<0 and offset) or (a+offset) ) otheritems = other.__tokdict.items() otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) ) for (k,vlist) in otheritems for v in vlist] for k,v in otherdictitems: self[k] = v if isinstance(v[0],ParseResults): v[0].__parent = wkref(self) self.__toklist += other.__toklist self.__accumNames.update( other.__accumNames ) del other return self def __repr__( self ): return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) ) def __str__( self ): out = "[" sep = "" for i in self.__toklist: if isinstance(i, ParseResults): out += sep + _ustr(i) else: out += sep + repr(i) sep = ", " out += "]" return out def _asStringList( self, sep='' ): out = [] for item in self.__toklist: if out and sep: out.append(sep) if isinstance( item, ParseResults ): out += item._asStringList() else: out.append( _ustr(item) ) return out def asList( self ): """Returns the parse results as a nested list of matching tokens, all converted to strings.""" out = [] for res in self.__toklist: if isinstance(res,ParseResults): out.append( res.asList() ) else: out.append( res ) return out def asDict( self ): """Returns the named parse results as dictionary.""" return dict( self.items() ) def copy( self ): """Returns a new copy of a ParseResults object.""" ret = ParseResults( self.__toklist ) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update( self.__accumNames ) ret.__name = self.__name return ret def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ): """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.""" nl = "\n" out = [] namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items() for v in vlist ] ) nextLevelIndent = indent + " " # collapse out indents if formatting is not desired if not formatted: indent = "" nextLevelIndent = "" nl = "" selfTag = None if doctag is not None: selfTag = doctag else: if self.__name: selfTag = self.__name if not selfTag: if namedItemsOnly: return "" else: selfTag = "ITEM" out += [ nl, indent, "<", selfTag, ">" ] worklist = self.__toklist for i,res in enumerate(worklist): if isinstance(res,ParseResults): if i in namedItems: out += [ res.asXML(namedItems[i], namedItemsOnly and doctag is None, nextLevelIndent, formatted)] else: out += [ res.asXML(None, namedItemsOnly and doctag is None, nextLevelIndent, formatted)] else: # individual token, see if there is a name for it resTag = None if i in namedItems: resTag = namedItems[i] if not resTag: if namedItemsOnly: continue else: resTag = "ITEM" xmlBodyText = xml.sax.saxutils.escape(_ustr(res)) out += [ nl, nextLevelIndent, "<", resTag, ">", xmlBodyText, "</", resTag, ">" ] out += [ nl, indent, "</", selfTag, ">" ] return "".join(out) def __lookup(self,sub): for k,vlist in self.__tokdict.items(): for v,loc in vlist: if sub is v: return k return None def getName(self): """Returns the results name for this token expression.""" if self.__name: return self.__name elif self.__parent: par = self.__parent() if par: return par.__lookup(self) else: return None elif (len(self) == 1 and len(self.__tokdict) == 1 and self.__tokdict.values()[0][0][1] in (0,-1)): return self.__tokdict.keys()[0] else: return None def dump(self,indent='',depth=0): """Diagnostic method for listing out the contents of a ParseResults. Accepts an optional indent argument so that this string can be embedded in a nested display of other data.""" out = [] out.append( indent+_ustr(self.asList()) ) keys = self.items() keys.sort() for k,v in keys: if out: out.append('\n') out.append( "%s%s- %s: " % (indent,(' '*depth), k) ) if isinstance(v,ParseResults): if v.keys(): #~ out.append('\n') out.append( v.dump(indent,depth+1) ) #~ out.append('\n') else: out.append(_ustr(v)) else: out.append(_ustr(v)) #~ out.append('\n') return "".join(out) # add support for pickle protocol def __getstate__(self): return ( self.__toklist, ( self.__tokdict.copy(), self.__parent is not None and self.__parent() or None, self.__accumNames, self.__name ) ) def __setstate__(self,state): self.__toklist = state[0] self.__tokdict, \ par, \ inAccumNames, \ self.__name = state[1] self.__accumNames = {} self.__accumNames.update(inAccumNames) if par is not None: self.__parent = wkref(par) else: self.__parent = None def col (loc,strg): """Returns current column within a string, counting newlines as line separators. The first column is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing <TAB>s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. """ return (loc<len(strg) and strg[loc] == '\n') and 1 or loc - strg.rfind("\n", 0, loc) def lineno(loc,strg): """Returns current line number within a string, counting newlines as line separators. The first line is number 1. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information on parsing strings containing <TAB>s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. """ return strg.count("\n",0,loc) + 1 def line( loc, strg ): """Returns the line of text containing loc within a string, counting newlines as line separators. """ lastCR = strg.rfind("\n", 0, loc) nextCR = strg.find("\n", loc) if nextCR > 0: return strg[lastCR+1:nextCR] else: return strg[lastCR+1:] def _defaultStartDebugAction( instring, loc, expr ): print ("Match",_ustr(expr),"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )) def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ): print ("Matched",_ustr(expr),"->",toks.asList()) def _defaultExceptionDebugAction( instring, loc, expr, exc ): print ("Exception raised:", _ustr(exc)) def nullDebugAction(*args): """'Do-nothing' debug action, to suppress debugging output during parsing.""" pass class ParserElement(object): """Abstract base level parser element class.""" DEFAULT_WHITE_CHARS = " \n\t\r" def setDefaultWhitespaceChars( chars ): """Overrides the default whitespace chars """ ParserElement.DEFAULT_WHITE_CHARS = chars setDefaultWhitespaceChars = staticmethod(setDefaultWhitespaceChars) def __init__( self, savelist=False ): self.parseAction = list() self.failAction = None #~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall self.strRepr = None self.resultsName = None self.saveAsList = savelist self.skipWhitespace = True self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS self.copyDefaultWhiteChars = True self.mayReturnEmpty = False # used when checking for left-recursion self.keepTabs = False self.ignoreExprs = list() self.debug = False self.streamlined = False self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index self.errmsg = "" self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all) self.debugActions = ( None, None, None ) #custom debug actions self.re = None self.callPreparse = True # used to avoid redundant calls to preParse self.callDuringTry = False def copy( self ): """Make a copy of this ParserElement. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element.""" cpy = copy.copy( self ) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] if self.copyDefaultWhiteChars: cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS return cpy def setName( self, name ): """Define name for this expression, for use in debugging.""" self.name = name self.errmsg = "Expected " + self.name if hasattr(self,"exception"): self.exception.msg = self.errmsg return self def setResultsName( self, name, listAllMatches=False ): """Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original ParserElement object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names. """ newself = self.copy() newself.resultsName = name newself.modalResults = not listAllMatches return newself def setBreak(self,breakFlag = True): """Method to invoke the Python pdb debugger when this element is about to be parsed. Set breakFlag to True to enable, False to disable. """ if breakFlag: _parseMethod = self._parse def breaker(instring, loc, doActions=True, callPreParse=True): import pdb pdb.set_trace() _parseMethod( instring, loc, doActions, callPreParse ) breaker._originalParseMethod = _parseMethod self._parse = breaker else: if hasattr(self._parse,"_originalParseMethod"): self._parse = self._parse._originalParseMethod return self def _normalizeParseActionArgs( f ): """Internal method used to decorate parse actions that take fewer than 3 arguments, so that all parse actions can be called as f(s,l,t).""" STAR_ARGS = 4 try: restore = None if isinstance(f,type): restore = f f = f.__init__ if f.func_code.co_flags & STAR_ARGS: return f numargs = f.func_code.co_argcount if hasattr(f,"im_self"): numargs -= 1 if restore: f = restore except AttributeError: try: # not a function, must be a callable object, get info from the # im_func binding of its bound __call__ method if f.__call__.im_func.func_code.co_flags & STAR_ARGS: return f numargs = f.__call__.im_func.func_code.co_argcount if hasattr(f.__call__,"im_self"): numargs -= 1 except AttributeError: # not a bound method, get info directly from __call__ method if f.__call__.func_code.co_flags & STAR_ARGS: return f numargs = f.__call__.func_code.co_argcount if hasattr(f.__call__,"im_self"): numargs -= 1 #~ print ("adding function %s with %d args" % (f.func_name,numargs)) if numargs == 3: return f else: if numargs == 2: def tmp(s,l,t): return f(l,t) elif numargs == 1: def tmp(s,l,t): return f(t) else: #~ numargs == 0: def tmp(s,l,t): return f() try: tmp.__name__ = f.__name__ except AttributeError: # no need for special handling if attribute doesnt exist pass try: tmp.__doc__ = f.__doc__ except AttributeError: # no need for special handling if attribute doesnt exist pass try: tmp.__dict__.update(f.__dict__) except AttributeError: # no need for special handling if attribute doesnt exist pass return tmp _normalizeParseActionArgs = staticmethod(_normalizeParseActionArgs) def setParseAction( self, *fns, **kwargs ): """Define action to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as fn(s,loc,toks), fn(loc,toks), fn(toks), or just fn(), where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a ParseResults object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing <TAB>s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. """ self.parseAction = map(self._normalizeParseActionArgs, list(fns)) self.callDuringTry = ("callDuringTry" in kwargs and kwargs["callDuringTry"]) return self def addParseAction( self, *fns, **kwargs ): """Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.""" self.parseAction += map(self._normalizeParseActionArgs, list(fns)) self.callDuringTry = self.callDuringTry or ("callDuringTry" in kwargs and kwargs["callDuringTry"]) return self def setFailAction( self, fn ): """Define action to perform if parsing fails at this expression. Fail acton fn is a callable function that takes the arguments fn(s,loc,expr,err) where: - s = string being parsed - loc = location where expression match was attempted and failed - expr = the parse expression that failed - err = the exception thrown The function returns no value. It may throw ParseFatalException if it is desired to stop parsing immediately.""" self.failAction = fn return self def _skipIgnorables( self, instring, loc ): exprsFound = True while exprsFound: exprsFound = False for e in self.ignoreExprs: try: while 1: loc,dummy = e._parse( instring, loc ) exprsFound = True except ParseException: pass return loc def preParse( self, instring, loc ): if self.ignoreExprs: loc = self._skipIgnorables( instring, loc ) if self.skipWhitespace: wt = self.whiteChars instrlen = len(instring) while loc < instrlen and instring[loc] in wt: loc += 1 return loc def parseImpl( self, instring, loc, doActions=True ): return loc, [] def postParse( self, instring, loc, tokenlist ): return tokenlist #~ @profile def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ): debugging = ( self.debug ) #and doActions ) if debugging or self.failAction: #~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )) if (self.debugActions[0] ): self.debugActions[0]( instring, loc, self ) if callPreParse and self.callPreparse: preloc = self.preParse( instring, loc ) else: preloc = loc tokensStart = loc try: try: loc,tokens = self.parseImpl( instring, preloc, doActions ) except IndexError: raise ParseException( instring, len(instring), self.errmsg, self ) except ParseException, err: #~ print ("Exception raised:", err) if self.debugActions[2]: self.debugActions[2]( instring, tokensStart, self, err ) if self.failAction: self.failAction( instring, tokensStart, self, err ) raise else: if callPreParse and self.callPreparse: preloc = self.preParse( instring, loc ) else: preloc = loc tokensStart = loc if self.mayIndexError or loc >= len(instring): try: loc,tokens = self.parseImpl( instring, preloc, doActions ) except IndexError: raise ParseException( instring, len(instring), self.errmsg, self ) else: loc,tokens = self.parseImpl( instring, preloc, doActions ) tokens = self.postParse( instring, loc, tokens ) retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults ) if self.parseAction and (doActions or self.callDuringTry): if debugging: try: for fn in self.parseAction: tokens = fn( instring, tokensStart, retTokens ) if tokens is not None: retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), modal=self.modalResults ) except ParseException, err: #~ print "Exception raised in user parse action:", err if (self.debugActions[2] ): self.debugActions[2]( instring, tokensStart, self, err ) raise else: for fn in self.parseAction: tokens = fn( instring, tokensStart, retTokens ) if tokens is not None: retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList and isinstance(tokens,(ParseResults,list)), modal=self.modalResults ) if debugging: #~ print ("Matched",self,"->",retTokens.asList()) if (self.debugActions[1] ): self.debugActions[1]( instring, tokensStart, loc, self, retTokens ) return loc, retTokens def tryParse( self, instring, loc ): return self._parse( instring, loc, doActions=False )[0] # this method gets repeatedly called during backtracking with the same arguments - # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression def _parseCache( self, instring, loc, doActions=True, callPreParse=True ): lookup = (self,instring,loc,callPreParse,doActions) if lookup in ParserElement._exprArgCache: value = ParserElement._exprArgCache[ lookup ] if isinstance(value,Exception): if isinstance(value,ParseBaseException): value.loc = loc raise value return (value[0],value[1].copy()) else: try: value = self._parseNoCache( instring, loc, doActions, callPreParse ) ParserElement._exprArgCache[ lookup ] = (value[0],value[1].copy()) return value except ParseBaseException, pe: ParserElement._exprArgCache[ lookup ] = pe raise _parse = _parseNoCache # argument cache for optimizing repeated calls when backtracking through recursive expressions _exprArgCache = {} def resetCache(): ParserElement._exprArgCache.clear() resetCache = staticmethod(resetCache) _packratEnabled = False def enablePackrat(): """Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing parsing/validating code. Memoizing is done of both valid results and parsing exceptions. This speedup may break existing programs that use parse actions that have side-effects. For this reason, packrat parsing is disabled when you first import pyparsing. To activate the packrat feature, your program must call the class method ParserElement.enablePackrat(). If your program uses psyco to "compile as you go", you must call enablePackrat before calling psyco.full(). If you do not do this, Python will crash. For best results, call enablePackrat() immediately after importing pyparsing. """ if not ParserElement._packratEnabled: ParserElement._packratEnabled = True ParserElement._parse = ParserElement._parseCache enablePackrat = staticmethod(enablePackrat) def parseString( self, instring ): """Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. Note: parseString implicitly calls expandtabs() on the input string, in order to report proper column numbers in parse actions. If the input string contains tabs and the grammar uses parse actions that use the loc argument to index into the string being parsed, you can ensure you have a consistent view of the input string by: - calling parseWithTabs on your grammar before calling parseString (see L{I{parseWithTabs}<parseWithTabs>}) - define your parse action using the full (s,loc,toks) signature, and reference the input string using the parse action's s argument - explictly expand the tabs in your input string before calling parseString """ ParserElement.resetCache() if not self.streamlined: self.streamline() #~ self.saveAsList = True for e in self.ignoreExprs: e.streamline() if self.keepTabs: loc, tokens = self._parse( instring, 0 ) else: loc, tokens = self._parse( instring.expandtabs(), 0 ) return tokens def scanString( self, instring, maxMatches=__MAX_INT__ ): """Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional maxMatches argument, to clip scanning after 'n' matches are found. Note that the start and end locations are reported relative to the string being parsed. See L{I{parseString}<parseString>} for more information on parsing strings with embedded tabs.""" if not self.streamlined: self.streamline() for e in self.ignoreExprs: e.streamline() if not self.keepTabs: instring = _ustr(instring).expandtabs() instrlen = len(instring) loc = 0 preparseFn = self.preParse parseFn = self._parse ParserElement.resetCache() matches = 0 while loc <= instrlen and matches < maxMatches: try: preloc = preparseFn( instring, loc ) nextLoc,tokens = parseFn( instring, preloc, callPreParse=False ) except ParseException: loc = preloc+1 else: matches += 1 yield tokens, preloc, nextLoc loc = nextLoc def transformString( self, instring ): """Extension to scanString, to modify matching text with modified tokens that may be returned from a parse action. To use transformString, define a grammar and attach a parse action to it that modifies the returned token list. Invoking transformString() on a target string will then scan for matches, and replace the matched text patterns according to the logic in the parse action. transformString() returns the resulting transformed string.""" out = [] lastE = 0 # force preservation of <TAB>s, to minimize unwanted transformation of string, and to # keep string locs straight between transformString and scanString self.keepTabs = True for t,s,e in self.scanString( instring ): out.append( instring[lastE:s] ) if t: if isinstance(t,ParseResults): out += t.asList() elif isinstance(t,list): out += t else: out.append(t) lastE = e out.append(instring[lastE:]) return "".join(map(_ustr,out)) def searchString( self, instring, maxMatches=__MAX_INT__ ): """Another extension to scanString, simplifying the access to the tokens found to match the given parse expression. May be called with optional maxMatches argument, to clip searching after 'n' matches are found. """ return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ]) def __add__(self, other ): """Implementation of + operator - returns And""" if isinstance( other, __BASE_STRING__ ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return And( [ self, other ] ) def __radd__(self, other ): """Implementation of + operator when left operand is not a ParserElement""" if isinstance( other, __BASE_STRING__ ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other + self def __mul__(self,other): if isinstance(other,int): minElements, optElements = other,0 elif isinstance(other,tuple): if len(other)==2: if isinstance(other[0],int) and isinstance(other[1],int): minElements, optElements = other optElements -= minElements else: raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1])) else: raise TypeError("can only multiply 'ParserElement' and int or (int,int) objects") else: raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other)) if minElements < 0: raise ValueError("cannot multiply ParserElement by negative value") if optElements < 0: raise ValueError("second tuple value must be greater or equal to first tuple value") if minElements == optElements == 0: raise ValueError("cannot multiply ParserElement by 0 or (0,0)") if (optElements): def makeOptionalList(n): if n>1: return Optional(self + makeOptionalList(n-1)) else: return Optional(self) if minElements: ret = And([self]*minElements)+ makeOptionalList(optElements) else: ret = makeOptionalList(optElements) else: ret = And([self]*minElements) return ret def __rmul__(self, other): return self.__mul__(other) def __or__(self, other ): """Implementation of | operator - returns MatchFirst""" if isinstance( other, __BASE_STRING__ ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return MatchFirst( [ self, other ] ) def __ror__(self, other ): """Implementation of | operator when left operand is not a ParserElement""" if isinstance( other, __BASE_STRING__ ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other | self def __xor__(self, other ): """Implementation of ^ operator - returns Or""" if isinstance( other, __BASE_STRING__ ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return Or( [ self, other ] ) def __rxor__(self, other ): """Implementation of ^ operator when left operand is not a ParserElement""" if isinstance( other, __BASE_STRING__ ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other ^ self def __and__(self, other ): """Implementation of & operator - returns Each""" if isinstance( other, __BASE_STRING__ ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return Each( [ self, other ] ) def __rand__(self, other ): """Implementation of & operator when left operand is not a ParserElement""" if isinstance( other, __BASE_STRING__ ): other = Literal( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return other & self def __invert__( self ): """Implementation of ~ operator - returns NotAny""" return NotAny( self ) def __call__(self, name): """Shortcut for setResultsName, with listAllMatches=default:: userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno") could be written as:: userdata = Word(alphas)("name") + Word(nums+"-")("socsecno") """ return self.setResultsName(name) def suppress( self ): """Suppresses the output of this ParserElement; useful to keep punctuation from cluttering up returned output. """ return Suppress( self ) def leaveWhitespace( self ): """Disables the skipping of whitespace before matching the characters in the ParserElement's defined pattern. This is normally only used internally by the pyparsing module, but may be needed in some whitespace-sensitive grammars. """ self.skipWhitespace = False return self def setWhitespaceChars( self, chars ): """Overrides the default whitespace chars """ self.skipWhitespace = True self.whiteChars = chars self.copyDefaultWhiteChars = False return self def parseWithTabs( self ): """Overrides default behavior to expand <TAB>s to spaces before parsing the input string. Must be called before parseString when the input grammar contains elements that match <TAB> characters.""" self.keepTabs = True return self def ignore( self, other ): """Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. """ if isinstance( other, Suppress ): if other not in self.ignoreExprs: self.ignoreExprs.append( other ) else: self.ignoreExprs.append( Suppress( other ) ) return self def setDebugActions( self, startAction, successAction, exceptionAction ): """Enable display of debugging messages while doing pattern matching.""" self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction) self.debug = True return self def setDebug( self, flag=True ): """Enable display of debugging messages while doing pattern matching. Set flag to True to enable, False to disable.""" if flag: self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction ) else: self.debug = False return self def __str__( self ): return self.name def __repr__( self ): return _ustr(self) def streamline( self ): self.streamlined = True self.strRepr = None return self def checkRecursion( self, parseElementList ): pass def validate( self, validateTrace=[] ): """Check defined expressions for valid structure, check for infinite recursive definitions.""" self.checkRecursion( [] ) def parseFile( self, file_or_filename ): """Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing. """ try: file_contents = file_or_filename.read() except AttributeError: f = open(file_or_filename, "rb") file_contents = f.read() f.close() return self.parseString(file_contents) def getException(self): return ParseException("",0,self.errmsg,self) def __getattr__(self,aname): if aname == "myException": self.myException = ret = self.getException(); return ret; else: raise AttributeError, "no such attribute " + aname def __eq__(self,other): if isinstance(other, __BASE_STRING__): try: (self + StringEnd()).parseString(_ustr(other)) return True except ParseException: return False else: return super(ParserElement,self)==other def __req__(self,other): return self == other class Token(ParserElement): """Abstract ParserElement subclass, for defining atomic matching patterns.""" def __init__( self ): super(Token,self).__init__( savelist=False ) #self.myException = ParseException("",0,"",self) def setName(self, name): s = super(Token,self).setName(name) self.errmsg = "Expected " + self.name #s.myException.msg = self.errmsg return s class Empty(Token): """An empty token, will always match.""" def __init__( self ): super(Empty,self).__init__() self.name = "Empty" self.mayReturnEmpty = True self.mayIndexError = False class NoMatch(Token): """A token that will never match.""" def __init__( self ): super(NoMatch,self).__init__() self.name = "NoMatch" self.mayReturnEmpty = True self.mayIndexError = False self.errmsg = "Unmatchable token" #self.myException.msg = self.errmsg def parseImpl( self, instring, loc, doActions=True ): exc = self.myException exc.loc = loc exc.pstr = instring raise exc class Literal(Token): """Token to exactly match a specified string.""" def __init__( self, matchString ): super(Literal,self).__init__() self.match = matchString self.matchLen = len(matchString) try: self.firstMatchChar = matchString[0] except IndexError: warnings.warn("null string passed to Literal; use Empty() instead", SyntaxWarning, stacklevel=2) self.__class__ = Empty self.name = '"%s"' % _ustr(self.match) self.errmsg = "Expected " + self.name self.mayReturnEmpty = False #self.myException.msg = self.errmsg self.mayIndexError = False # Performance tuning: this routine gets called a *lot* # if this is a single character match string and the first character matches, # short-circuit as quickly as possible, and avoid calling startswith #~ @profile def parseImpl( self, instring, loc, doActions=True ): if (instring[loc] == self.firstMatchChar and (self.matchLen==1 or instring.startswith(self.match,loc)) ): return loc+self.matchLen, self.match #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc _L = Literal class Keyword(Token): """Token to exactly match a specified string as a keyword, that is, it must be immediately followed by a non-keyword character. Compare with Literal:: Literal("if") will match the leading 'if' in 'ifAndOnlyIf'. Keyword("if") will not; it will only match the leading 'if in 'if x=1', or 'if(y==2)' Accepts two optional constructor arguments in addition to the keyword string: identChars is a string of characters that would be valid identifier characters, defaulting to all alphanumerics + "_" and "$"; caseless allows case-insensitive matching, default is False. """ DEFAULT_KEYWORD_CHARS = alphanums+"_$" def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ): super(Keyword,self).__init__() self.match = matchString self.matchLen = len(matchString) try: self.firstMatchChar = matchString[0] except IndexError: warnings.warn("null string passed to Keyword; use Empty() instead", SyntaxWarning, stacklevel=2) self.name = '"%s"' % self.match self.errmsg = "Expected " + self.name self.mayReturnEmpty = False #self.myException.msg = self.errmsg self.mayIndexError = False self.caseless = caseless if caseless: self.caselessmatch = matchString.upper() identChars = identChars.upper() self.identChars = _str2dict(identChars) def parseImpl( self, instring, loc, doActions=True ): if self.caseless: if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and (loc == 0 or instring[loc-1].upper() not in self.identChars) ): return loc+self.matchLen, self.match else: if (instring[loc] == self.firstMatchChar and (self.matchLen==1 or instring.startswith(self.match,loc)) and (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and (loc == 0 or instring[loc-1] not in self.identChars) ): return loc+self.matchLen, self.match #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc def copy(self): c = super(Keyword,self).copy() c.identChars = Keyword.DEFAULT_KEYWORD_CHARS return c def setDefaultKeywordChars( chars ): """Overrides the default Keyword chars """ Keyword.DEFAULT_KEYWORD_CHARS = chars setDefaultKeywordChars = staticmethod(setDefaultKeywordChars) class CaselessLiteral(Literal): """Token to match a specified string, ignoring case of letters. Note: the matched results will always be in the case of the given match string, NOT the case of the input text. """ def __init__( self, matchString ): super(CaselessLiteral,self).__init__( matchString.upper() ) # Preserve the defining literal. self.returnString = matchString self.name = "'%s'" % self.returnString self.errmsg = "Expected " + self.name #self.myException.msg = self.errmsg def parseImpl( self, instring, loc, doActions=True ): if instring[ loc:loc+self.matchLen ].upper() == self.match: return loc+self.matchLen, self.returnString #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc class CaselessKeyword(Keyword): def __init__( self, matchString, identChars=Keyword.DEFAULT_KEYWORD_CHARS ): super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True ) def parseImpl( self, instring, loc, doActions=True ): if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and (loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ): return loc+self.matchLen, self.match #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc class Word(Token): """Token for matching words composed of allowed character sets. Defined with string containing all allowed initial characters, an optional string containing allowed body characters (if omitted, defaults to the initial character set), and an optional minimum, maximum, and/or exact length. The default value for min is 1 (a minimum value < 1 is not valid); the default values for max and exact are 0, meaning no maximum or exact length restriction. """ def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False ): super(Word,self).__init__() self.initCharsOrig = initChars self.initChars = _str2dict(initChars) if bodyChars : self.bodyCharsOrig = bodyChars self.bodyChars = _str2dict(bodyChars) else: self.bodyCharsOrig = initChars self.bodyChars = _str2dict(initChars) self.maxSpecified = max > 0 if min < 1: raise ValueError, "cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted" self.minLen = min if max > 0: self.maxLen = max else: self.maxLen = __MAX_INT__ if exact > 0: self.maxLen = exact self.minLen = exact self.name = _ustr(self) self.errmsg = "Expected " + self.name #self.myException.msg = self.errmsg self.mayIndexError = False self.asKeyword = asKeyword if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0): if self.bodyCharsOrig == self.initCharsOrig: self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig) elif len(self.bodyCharsOrig) == 1: self.reString = "%s[%s]*" % \ (re.escape(self.initCharsOrig), _escapeRegexRangeChars(self.bodyCharsOrig),) else: self.reString = "[%s][%s]*" % \ (_escapeRegexRangeChars(self.initCharsOrig), _escapeRegexRangeChars(self.bodyCharsOrig),) if self.asKeyword: self.reString = r"\b"+self.reString+r"\b" try: self.re = re.compile( self.reString ) except: self.re = None def parseImpl( self, instring, loc, doActions=True ): if self.re: result = self.re.match(instring,loc) if not result: exc = self.myException exc.loc = loc exc.pstr = instring raise exc loc = result.end() return loc,result.group() if not(instring[ loc ] in self.initChars): #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc start = loc loc += 1 instrlen = len(instring) bodychars = self.bodyChars maxloc = start + self.maxLen maxloc = min( maxloc, instrlen ) while loc < maxloc and instring[loc] in bodychars: loc += 1 throwException = False if loc - start < self.minLen: throwException = True if self.maxSpecified and loc < instrlen and instring[loc] in bodychars: throwException = True if self.asKeyword: if (start>0 and instring[start-1] in bodychars) or (loc<instrlen and instring[loc] in bodychars): throwException = True if throwException: #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, instring[start:loc] def __str__( self ): try: return super(Word,self).__str__() except: pass if self.strRepr is None: def charsAsStr(s): if len(s)>4: return s[:4]+"..." else: return s if ( self.initCharsOrig != self.bodyCharsOrig ): self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) ) else: self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig) return self.strRepr class Regex(Token): """Token for matching strings that match a given regular expression. Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module. """ def __init__( self, pattern, flags=0): """The parameters pattern and flags are passed to the re.compile() function as-is. See the Python re module for an explanation of the acceptable patterns and flags.""" super(Regex,self).__init__() if len(pattern) == 0: warnings.warn("null string passed to Regex; use Empty() instead", SyntaxWarning, stacklevel=2) self.pattern = pattern self.flags = flags try: self.re = re.compile(self.pattern, self.flags) self.reString = self.pattern except sre_constants.error,e: warnings.warn("invalid pattern (%s) passed to Regex" % pattern, SyntaxWarning, stacklevel=2) raise self.name = _ustr(self) self.errmsg = "Expected " + self.name #self.myException.msg = self.errmsg self.mayIndexError = False self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): result = self.re.match(instring,loc) if not result: exc = self.myException exc.loc = loc exc.pstr = instring raise exc loc = result.end() d = result.groupdict() ret = ParseResults(result.group()) if d: for k in d.keys(): ret[k] = d[k] return loc,ret def __str__( self ): try: return super(Regex,self).__str__() except: pass if self.strRepr is None: self.strRepr = "Re:(%s)" % repr(self.pattern) return self.strRepr class QuotedString(Token): """Token for matching strings that are delimited by quoting characters. """ def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None): """ Defined with the following parameters: - quoteChar - string of one or more characters defining the quote delimiting string - escChar - character to escape quotes, typically backslash (default=None) - escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=None) - multiline - boolean indicating whether quotes can span multiple lines (default=False) - unquoteResults - boolean indicating whether the matched text should be unquoted (default=True) - endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=None => same as quoteChar) """ super(QuotedString,self).__init__() # remove white space from quote chars - wont work anyway quoteChar = quoteChar.strip() if len(quoteChar) == 0: warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2) raise SyntaxError() if endQuoteChar is None: endQuoteChar = quoteChar else: endQuoteChar = endQuoteChar.strip() if len(endQuoteChar) == 0: warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2) raise SyntaxError() self.quoteChar = quoteChar self.quoteCharLen = len(quoteChar) self.firstQuoteChar = quoteChar[0] self.endQuoteChar = endQuoteChar self.endQuoteCharLen = len(endQuoteChar) self.escChar = escChar self.escQuote = escQuote self.unquoteResults = unquoteResults if multiline: self.flags = re.MULTILINE | re.DOTALL self.pattern = r'%s(?:[^%s%s]' % \ ( re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), (escChar is not None and _escapeRegexRangeChars(escChar) or '') ) else: self.flags = 0 self.pattern = r'%s(?:[^%s\n\r%s]' % \ ( re.escape(self.quoteChar), _escapeRegexRangeChars(self.endQuoteChar[0]), (escChar is not None and _escapeRegexRangeChars(escChar) or '') ) if len(self.endQuoteChar) > 1: self.pattern += ( '|(?:' + ')|(?:'.join(["%s[^%s]" % (re.escape(self.endQuoteChar[:i]), _escapeRegexRangeChars(self.endQuoteChar[i])) for i in range(len(self.endQuoteChar)-1,0,-1)]) + ')' ) if escQuote: self.pattern += (r'|(?:%s)' % re.escape(escQuote)) if escChar: self.pattern += (r'|(?:%s.)' % re.escape(escChar)) self.escCharReplacePattern = re.escape(self.escChar)+"(.)" self.pattern += (r')*%s' % re.escape(self.endQuoteChar)) try: self.re = re.compile(self.pattern, self.flags) self.reString = self.pattern except sre_constants.error,e: warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern, SyntaxWarning, stacklevel=2) raise self.name = _ustr(self) self.errmsg = "Expected " + self.name #self.myException.msg = self.errmsg self.mayIndexError = False self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None if not result: exc = self.myException exc.loc = loc exc.pstr = instring raise exc loc = result.end() ret = result.group() if self.unquoteResults: # strip off quotes ret = ret[self.quoteCharLen:-self.endQuoteCharLen] if isinstance(ret,__BASE_STRING__): # replace escaped characters if self.escChar: ret = re.sub(self.escCharReplacePattern,"\g<1>",ret) # replace escaped quotes if self.escQuote: ret = ret.replace(self.escQuote, self.endQuoteChar) return loc, ret def __str__( self ): try: return super(QuotedString,self).__str__() except: pass if self.strRepr is None: self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar) return self.strRepr class CharsNotIn(Token): """Token for matching words composed of characters *not* in a given set. Defined with string containing all disallowed characters, and an optional minimum, maximum, and/or exact length. The default value for min is 1 (a minimum value < 1 is not valid); the default values for max and exact are 0, meaning no maximum or exact length restriction. """ def __init__( self, notChars, min=1, max=0, exact=0 ): super(CharsNotIn,self).__init__() self.skipWhitespace = False self.notChars = notChars if min < 1: raise ValueError, "cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted" self.minLen = min if max > 0: self.maxLen = max else: self.maxLen = __MAX_INT__ if exact > 0: self.maxLen = exact self.minLen = exact self.name = _ustr(self) self.errmsg = "Expected " + self.name self.mayReturnEmpty = ( self.minLen == 0 ) #self.myException.msg = self.errmsg self.mayIndexError = False def parseImpl( self, instring, loc, doActions=True ): if instring[loc] in self.notChars: #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc start = loc loc += 1 notchars = self.notChars maxlen = min( start+self.maxLen, len(instring) ) while loc < maxlen and \ (instring[loc] not in notchars): loc += 1 if loc - start < self.minLen: #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, instring[start:loc] def __str__( self ): try: return super(CharsNotIn, self).__str__() except: pass if self.strRepr is None: if len(self.notChars) > 4: self.strRepr = "!W:(%s...)" % self.notChars[:4] else: self.strRepr = "!W:(%s)" % self.notChars return self.strRepr class White(Token): """Special matching class for matching whitespace. Normally, whitespace is ignored by pyparsing grammars. This class is included when some whitespace structures are significant. Define with a string containing the whitespace characters to be matched; default is " \\t\\n". Also takes optional min, max, and exact arguments, as defined for the Word class.""" whiteStrs = { " " : "<SPC>", "\t": "<TAB>", "\n": "<LF>", "\r": "<CR>", "\f": "<FF>", } def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0): super(White,self).__init__() self.matchWhite = ws self.setWhitespaceChars( "".join([c for c in self.whiteChars if c not in self.matchWhite]) ) #~ self.leaveWhitespace() self.name = ("".join([White.whiteStrs[c] for c in self.matchWhite])) self.mayReturnEmpty = True self.errmsg = "Expected " + self.name #self.myException.msg = self.errmsg self.minLen = min if max > 0: self.maxLen = max else: self.maxLen = __MAX_INT__ if exact > 0: self.maxLen = exact self.minLen = exact def parseImpl( self, instring, loc, doActions=True ): if not(instring[ loc ] in self.matchWhite): #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc start = loc loc += 1 maxloc = start + self.maxLen maxloc = min( maxloc, len(instring) ) while loc < maxloc and instring[loc] in self.matchWhite: loc += 1 if loc - start < self.minLen: #~ raise ParseException( instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, instring[start:loc] class _PositionToken(Token): def __init__( self ): super(_PositionToken,self).__init__() self.name=self.__class__.__name__ self.mayReturnEmpty = True self.mayIndexError = False class GoToColumn(_PositionToken): """Token to advance to a specific column of input text; useful for tabular report scraping.""" def __init__( self, colno ): super(GoToColumn,self).__init__() self.col = colno def preParse( self, instring, loc ): if col(loc,instring) != self.col: instrlen = len(instring) if self.ignoreExprs: loc = self._skipIgnorables( instring, loc ) while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col : loc += 1 return loc def parseImpl( self, instring, loc, doActions=True ): thiscol = col( loc, instring ) if thiscol > self.col: raise ParseException( instring, loc, "Text not in expected column", self ) newloc = loc + self.col - thiscol ret = instring[ loc: newloc ] return newloc, ret class LineStart(_PositionToken): """Matches if current position is at the beginning of a line within the parse string""" def __init__( self ): super(LineStart,self).__init__() self.setWhitespaceChars( " \t" ) self.errmsg = "Expected start of line" #self.myException.msg = self.errmsg def preParse( self, instring, loc ): preloc = super(LineStart,self).preParse(instring,loc) if instring[preloc] == "\n": loc += 1 return loc def parseImpl( self, instring, loc, doActions=True ): if not( loc==0 or (loc == self.preParse( instring, 0 )) or (instring[loc-1] == "\n") ): #col(loc, instring) != 1: #~ raise ParseException( instring, loc, "Expected start of line" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] class LineEnd(_PositionToken): """Matches if current position is at the end of a line within the parse string""" def __init__( self ): super(LineEnd,self).__init__() self.setWhitespaceChars( " \t" ) self.errmsg = "Expected end of line" #self.myException.msg = self.errmsg def parseImpl( self, instring, loc, doActions=True ): if loc<len(instring): if instring[loc] == "\n": return loc+1, "\n" else: #~ raise ParseException( instring, loc, "Expected end of line" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc elif loc == len(instring): return loc+1, [] else: exc = self.myException exc.loc = loc exc.pstr = instring raise exc class StringStart(_PositionToken): """Matches if current position is at the beginning of the parse string""" def __init__( self ): super(StringStart,self).__init__() self.errmsg = "Expected start of text" #self.myException.msg = self.errmsg def parseImpl( self, instring, loc, doActions=True ): if loc != 0: # see if entire string up to here is just whitespace and ignoreables if loc != self.preParse( instring, 0 ): #~ raise ParseException( instring, loc, "Expected start of text" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] class StringEnd(_PositionToken): """Matches if current position is at the end of the parse string""" def __init__( self ): super(StringEnd,self).__init__() self.errmsg = "Expected end of text" #self.myException.msg = self.errmsg def parseImpl( self, instring, loc, doActions=True ): if loc < len(instring): #~ raise ParseException( instring, loc, "Expected end of text" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc elif loc == len(instring): return loc+1, [] elif loc > len(instring): return loc, [] else: exc = self.myException exc.loc = loc exc.pstr = instring raise exc class WordStart(_PositionToken): """Matches if the current position is at the beginning of a Word, and is not preceded by any character in a given set of wordChars (default=printables). To emulate the \b behavior of regular expressions, use WordStart(alphanums). WordStart will also match at the beginning of the string being parsed, or at the beginning of a line. """ def __init__(self, wordChars = printables): super(WordStart,self).__init__() self.wordChars = _str2dict(wordChars) self.errmsg = "Not at the start of a word" def parseImpl(self, instring, loc, doActions=True ): if loc != 0: if (instring[loc-1] in self.wordChars or instring[loc] not in self.wordChars): exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] class WordEnd(_PositionToken): """Matches if the current position is at the end of a Word, and is not followed by any character in a given set of wordChars (default=printables). To emulate the \b behavior of regular expressions, use WordEnd(alphanums). WordEnd will also match at the end of the string being parsed, or at the end of a line. """ def __init__(self, wordChars = printables): super(WordEnd,self).__init__() self.wordChars = _str2dict(wordChars) self.skipWhitespace = False self.errmsg = "Not at the end of a word" def parseImpl(self, instring, loc, doActions=True ): instrlen = len(instring) if instrlen>0 and loc<instrlen: if (instring[loc] in self.wordChars or instring[loc-1] not in self.wordChars): #~ raise ParseException( instring, loc, "Expected end of word" ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] class ParseExpression(ParserElement): """Abstract subclass of ParserElement, for combining and post-processing parsed tokens.""" def __init__( self, exprs, savelist = False ): super(ParseExpression,self).__init__(savelist) if isinstance( exprs, list ): self.exprs = exprs elif isinstance( exprs, __BASE_STRING__ ): self.exprs = [ Literal( exprs ) ] else: self.exprs = [ exprs ] self.callPreparse = False def __getitem__( self, i ): return self.exprs[i] def append( self, other ): self.exprs.append( other ) self.strRepr = None return self def leaveWhitespace( self ): """Extends leaveWhitespace defined in base class, and also invokes leaveWhitespace on all contained expressions.""" self.skipWhitespace = False self.exprs = [ e.copy() for e in self.exprs ] for e in self.exprs: e.leaveWhitespace() return self def ignore( self, other ): if isinstance( other, Suppress ): if other not in self.ignoreExprs: super( ParseExpression, self).ignore( other ) for e in self.exprs: e.ignore( self.ignoreExprs[-1] ) else: super( ParseExpression, self).ignore( other ) for e in self.exprs: e.ignore( self.ignoreExprs[-1] ) return self def __str__( self ): try: return super(ParseExpression,self).__str__() except: pass if self.strRepr is None: self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) ) return self.strRepr def streamline( self ): super(ParseExpression,self).streamline() for e in self.exprs: e.streamline() # collapse nested And's of the form And( And( And( a,b), c), d) to And( a,b,c,d ) # but only if there are no parse actions or resultsNames on the nested And's # (likewise for Or's and MatchFirst's) if ( len(self.exprs) == 2 ): other = self.exprs[0] if ( isinstance( other, self.__class__ ) and not(other.parseAction) and other.resultsName is None and not other.debug ): self.exprs = other.exprs[:] + [ self.exprs[1] ] self.strRepr = None self.mayReturnEmpty |= other.mayReturnEmpty self.mayIndexError |= other.mayIndexError other = self.exprs[-1] if ( isinstance( other, self.__class__ ) and not(other.parseAction) and other.resultsName is None and not other.debug ): self.exprs = self.exprs[:-1] + other.exprs[:] self.strRepr = None self.mayReturnEmpty |= other.mayReturnEmpty self.mayIndexError |= other.mayIndexError return self def setResultsName( self, name, listAllMatches=False ): ret = super(ParseExpression,self).setResultsName(name,listAllMatches) return ret def validate( self, validateTrace=[] ): tmp = validateTrace[:]+[self] for e in self.exprs: e.validate(tmp) self.checkRecursion( [] ) class And(ParseExpression): """Requires all given ParseExpressions to be found in the given order. Expressions may be separated by whitespace. May be constructed using the '+' operator. """ def __init__( self, exprs, savelist = True ): super(And,self).__init__(exprs, savelist) self.mayReturnEmpty = True for e in self.exprs: if not e.mayReturnEmpty: self.mayReturnEmpty = False break self.setWhitespaceChars( exprs[0].whiteChars ) self.skipWhitespace = exprs[0].skipWhitespace self.callPreparse = True def parseImpl( self, instring, loc, doActions=True ): # pass False as last arg to _parse for first element, since we already # pre-parsed the string as part of our And pre-parsing loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False ) for e in self.exprs[1:]: loc, exprtokens = e._parse( instring, loc, doActions ) if exprtokens or exprtokens.keys(): resultlist += exprtokens return loc, resultlist def __iadd__(self, other ): if isinstance( other, __BASE_STRING__ ): other = Literal( other ) return self.append( other ) #And( [ self, other ] ) def checkRecursion( self, parseElementList ): subRecCheckList = parseElementList[:] + [ self ] for e in self.exprs: e.checkRecursion( subRecCheckList ) if not e.mayReturnEmpty: break def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + " ".join( [ _ustr(e) for e in self.exprs ] ) + "}" return self.strRepr class Or(ParseExpression): """Requires that at least one ParseExpression is found. If two expressions match, the expression that matches the longest string will be used. May be constructed using the '^' operator. """ def __init__( self, exprs, savelist = False ): super(Or,self).__init__(exprs, savelist) self.mayReturnEmpty = False for e in self.exprs: if e.mayReturnEmpty: self.mayReturnEmpty = True break def parseImpl( self, instring, loc, doActions=True ): maxExcLoc = -1 maxMatchLoc = -1 for e in self.exprs: try: loc2 = e.tryParse( instring, loc ) except ParseException, err: if err.loc > maxExcLoc: maxException = err maxExcLoc = err.loc except IndexError: if len(instring) > maxExcLoc: maxException = ParseException(instring,len(instring),e.errmsg,self) maxExcLoc = len(instring) else: if loc2 > maxMatchLoc: maxMatchLoc = loc2 maxMatchExp = e if maxMatchLoc < 0: if self.exprs: raise maxException else: raise ParseException(instring, loc, "no defined alternatives to match", self) return maxMatchExp._parse( instring, loc, doActions ) def __ixor__(self, other ): if isinstance( other, __BASE_STRING__ ): other = Literal( other ) return self.append( other ) #Or( [ self, other ] ) def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + " ^ ".join( [ _ustr(e) for e in self.exprs ] ) + "}" return self.strRepr def checkRecursion( self, parseElementList ): subRecCheckList = parseElementList[:] + [ self ] for e in self.exprs: e.checkRecursion( subRecCheckList ) class MatchFirst(ParseExpression): """Requires that at least one ParseExpression is found. If two expressions match, the first one listed is the one that will match. May be constructed using the '|' operator. """ def __init__( self, exprs, savelist = False ): super(MatchFirst,self).__init__(exprs, savelist) if exprs: self.mayReturnEmpty = False for e in self.exprs: if e.mayReturnEmpty: self.mayReturnEmpty = True break else: self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): maxExcLoc = -1 for e in self.exprs: try: ret = e._parse( instring, loc, doActions ) return ret except ParseException, err: if err.loc > maxExcLoc: maxException = err maxExcLoc = err.loc except IndexError: if len(instring) > maxExcLoc: maxException = ParseException(instring,len(instring),e.errmsg,self) maxExcLoc = len(instring) # only got here if no expression matched, raise exception for match that made it the furthest else: if self.exprs: raise maxException else: raise ParseException(instring, loc, "no defined alternatives to match", self) def __ior__(self, other ): if isinstance( other, __BASE_STRING__ ): other = Literal( other ) return self.append( other ) #MatchFirst( [ self, other ] ) def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + " | ".join( [ _ustr(e) for e in self.exprs ] ) + "}" return self.strRepr def checkRecursion( self, parseElementList ): subRecCheckList = parseElementList[:] + [ self ] for e in self.exprs: e.checkRecursion( subRecCheckList ) class Each(ParseExpression): """Requires all given ParseExpressions to be found, but in any order. Expressions may be separated by whitespace. May be constructed using the '&' operator. """ def __init__( self, exprs, savelist = True ): super(Each,self).__init__(exprs, savelist) self.mayReturnEmpty = True for e in self.exprs: if not e.mayReturnEmpty: self.mayReturnEmpty = False break self.skipWhitespace = True self.optionals = [ e.expr for e in exprs if isinstance(e,Optional) ] self.multioptionals = [ e.expr for e in exprs if isinstance(e,ZeroOrMore) ] self.multirequired = [ e.expr for e in exprs if isinstance(e,OneOrMore) ] self.required = [ e for e in exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ] self.required += self.multirequired def parseImpl( self, instring, loc, doActions=True ): tmpLoc = loc tmpReqd = self.required[:] tmpOpt = self.optionals[:] matchOrder = [] keepMatching = True while keepMatching: tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired failed = [] for e in tmpExprs: try: tmpLoc = e.tryParse( instring, tmpLoc ) except ParseException: failed.append(e) else: matchOrder.append(e) if e in tmpReqd: tmpReqd.remove(e) elif e in tmpOpt: tmpOpt.remove(e) if len(failed) == len(tmpExprs): keepMatching = False if tmpReqd: missing = ", ".join( [ _ustr(e) for e in tmpReqd ] ) raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing ) resultlist = [] for e in matchOrder: loc,results = e._parse(instring,loc,doActions) resultlist.append(results) finalResults = ParseResults([]) for r in resultlist: dups = {} for k in r.keys(): if k in finalResults.keys(): tmp = ParseResults(finalResults[k]) tmp += ParseResults(r[k]) dups[k] = tmp finalResults += ParseResults(r) for k,v in dups.items(): finalResults[k] = v return loc, finalResults def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + " & ".join( [ _ustr(e) for e in self.exprs ] ) + "}" return self.strRepr def checkRecursion( self, parseElementList ): subRecCheckList = parseElementList[:] + [ self ] for e in self.exprs: e.checkRecursion( subRecCheckList ) class ParseElementEnhance(ParserElement): """Abstract subclass of ParserElement, for combining and post-processing parsed tokens.""" def __init__( self, expr, savelist=False ): super(ParseElementEnhance,self).__init__(savelist) if isinstance( expr, __BASE_STRING__ ): expr = Literal(expr) self.expr = expr self.strRepr = None if expr is not None: self.mayIndexError = expr.mayIndexError self.mayReturnEmpty = expr.mayReturnEmpty self.setWhitespaceChars( expr.whiteChars ) self.skipWhitespace = expr.skipWhitespace self.saveAsList = expr.saveAsList self.callPreparse = expr.callPreparse self.ignoreExprs.extend(expr.ignoreExprs) def parseImpl( self, instring, loc, doActions=True ): if self.expr is not None: return self.expr._parse( instring, loc, doActions, callPreParse=False ) else: raise ParseException("",loc,self.errmsg,self) def leaveWhitespace( self ): self.skipWhitespace = False self.expr = self.expr.copy() if self.expr is not None: self.expr.leaveWhitespace() return self def ignore( self, other ): if isinstance( other, Suppress ): if other not in self.ignoreExprs: super( ParseElementEnhance, self).ignore( other ) if self.expr is not None: self.expr.ignore( self.ignoreExprs[-1] ) else: super( ParseElementEnhance, self).ignore( other ) if self.expr is not None: self.expr.ignore( self.ignoreExprs[-1] ) return self def streamline( self ): super(ParseElementEnhance,self).streamline() if self.expr is not None: self.expr.streamline() return self def checkRecursion( self, parseElementList ): if self in parseElementList: raise RecursiveGrammarException( parseElementList+[self] ) subRecCheckList = parseElementList[:] + [ self ] if self.expr is not None: self.expr.checkRecursion( subRecCheckList ) def validate( self, validateTrace=[] ): tmp = validateTrace[:]+[self] if self.expr is not None: self.expr.validate(tmp) self.checkRecursion( [] ) def __str__( self ): try: return super(ParseElementEnhance,self).__str__() except: pass if self.strRepr is None and self.expr is not None: self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) ) return self.strRepr class FollowedBy(ParseElementEnhance): """Lookahead matching of the given parse expression. FollowedBy does *not* advance the parsing position within the input string, it only verifies that the specified parse expression matches at the current position. FollowedBy always returns a null token list.""" def __init__( self, expr ): super(FollowedBy,self).__init__(expr) self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): self.expr.tryParse( instring, loc ) return loc, [] class NotAny(ParseElementEnhance): """Lookahead to disallow matching with the given parse expression. NotAny does *not* advance the parsing position within the input string, it only verifies that the specified parse expression does *not* match at the current position. Also, NotAny does *not* skip over leading whitespace. NotAny always returns a null token list. May be constructed using the '~' operator.""" def __init__( self, expr ): super(NotAny,self).__init__(expr) #~ self.leaveWhitespace() self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs self.mayReturnEmpty = True self.errmsg = "Found unwanted token, "+_ustr(self.expr) #self.myException = ParseException("",0,self.errmsg,self) def parseImpl( self, instring, loc, doActions=True ): try: self.expr.tryParse( instring, loc ) except (ParseException,IndexError): pass else: #~ raise ParseException(instring, loc, self.errmsg ) exc = self.myException exc.loc = loc exc.pstr = instring raise exc return loc, [] def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "~{" + _ustr(self.expr) + "}" return self.strRepr class ZeroOrMore(ParseElementEnhance): """Optional repetition of zero or more of the given expression.""" def __init__( self, expr ): super(ZeroOrMore,self).__init__(expr) self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): tokens = [] try: loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) hasIgnoreExprs = ( len(self.ignoreExprs) > 0 ) while 1: if hasIgnoreExprs: preloc = self._skipIgnorables( instring, loc ) else: preloc = loc loc, tmptokens = self.expr._parse( instring, preloc, doActions ) if tmptokens or tmptokens.keys(): tokens += tmptokens except (ParseException,IndexError): pass return loc, tokens def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "[" + _ustr(self.expr) + "]..." return self.strRepr def setResultsName( self, name, listAllMatches=False ): ret = super(ZeroOrMore,self).setResultsName(name,listAllMatches) ret.saveAsList = True return ret class OneOrMore(ParseElementEnhance): """Repetition of one or more of the given expression.""" def parseImpl( self, instring, loc, doActions=True ): # must be at least one loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) try: hasIgnoreExprs = ( len(self.ignoreExprs) > 0 ) while 1: if hasIgnoreExprs: preloc = self._skipIgnorables( instring, loc ) else: preloc = loc loc, tmptokens = self.expr._parse( instring, preloc, doActions ) if tmptokens or tmptokens.keys(): tokens += tmptokens except (ParseException,IndexError): pass return loc, tokens def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "{" + _ustr(self.expr) + "}..." return self.strRepr def setResultsName( self, name, listAllMatches=False ): ret = super(OneOrMore,self).setResultsName(name,listAllMatches) ret.saveAsList = True return ret class _NullToken(object): def __bool__(self): return False def __str__(self): return "" _optionalNotMatched = _NullToken() class Optional(ParseElementEnhance): """Optional matching of the given expression. A default return string can also be specified, if the optional expression is not found. """ def __init__( self, exprs, default=_optionalNotMatched ): super(Optional,self).__init__( exprs, savelist=False ) self.defaultValue = default self.mayReturnEmpty = True def parseImpl( self, instring, loc, doActions=True ): try: loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) except (ParseException,IndexError): if self.defaultValue is not _optionalNotMatched: tokens = [ self.defaultValue ] else: tokens = [] return loc, tokens def __str__( self ): if hasattr(self,"name"): return self.name if self.strRepr is None: self.strRepr = "[" + _ustr(self.expr) + "]" return self.strRepr class SkipTo(ParseElementEnhance): """Token for skipping over all undefined text until the matched expression is found. If include is set to true, the matched expression is also consumed. The ignore argument is used to define grammars (typically quoted strings and comments) that might contain false matches. """ def __init__( self, other, include=False, ignore=None ): super( SkipTo, self ).__init__( other ) if ignore is not None: self.expr = self.expr.copy() self.expr.ignore(ignore) self.mayReturnEmpty = True self.mayIndexError = False self.includeMatch = include self.asList = False self.errmsg = "No match found for "+_ustr(self.expr) #self.myException = ParseException("",0,self.errmsg,self) def parseImpl( self, instring, loc, doActions=True ): startLoc = loc instrlen = len(instring) expr = self.expr while loc <= instrlen: try: loc = expr._skipIgnorables( instring, loc ) expr._parse( instring, loc, doActions=False, callPreParse=False ) if self.includeMatch: skipText = instring[startLoc:loc] loc,mat = expr._parse(instring,loc,doActions,callPreParse=False) if mat: skipRes = ParseResults( skipText ) skipRes += mat return loc, [ skipRes ] else: return loc, [ skipText ] else: return loc, [ instring[startLoc:loc] ] except (ParseException,IndexError): loc += 1 exc = self.myException exc.loc = loc exc.pstr = instring raise exc class Forward(ParseElementEnhance): """Forward declaration of an expression to be defined later - used for recursive grammars, such as algebraic infix notation. When the expression is known, it is assigned to the Forward variable using the '<<' operator. Note: take care when assigning to Forward not to overlook precedence of operators. Specifically, '|' has a lower precedence than '<<', so that:: fwdExpr << a | b | c will actually be evaluated as:: (fwdExpr << a) | b | c thereby leaving b and c out as parseable alternatives. It is recommended that you explicitly group the values inserted into the Forward:: fwdExpr << (a | b | c) """ def __init__( self, other=None ): super(Forward,self).__init__( other, savelist=False ) def __lshift__( self, other ): if isinstance( other, __BASE_STRING__ ): other = Literal(other) self.expr = other self.mayReturnEmpty = other.mayReturnEmpty self.strRepr = None self.mayIndexError = self.expr.mayIndexError self.mayReturnEmpty = self.expr.mayReturnEmpty self.setWhitespaceChars( self.expr.whiteChars ) self.skipWhitespace = self.expr.skipWhitespace self.saveAsList = self.expr.saveAsList self.ignoreExprs.extend(self.expr.ignoreExprs) return None def leaveWhitespace( self ): self.skipWhitespace = False return self def streamline( self ): if not self.streamlined: self.streamlined = True if self.expr is not None: self.expr.streamline() return self def validate( self, validateTrace=[] ): if self not in validateTrace: tmp = validateTrace[:]+[self] if self.expr is not None: self.expr.validate(tmp) self.checkRecursion([]) def __str__( self ): if hasattr(self,"name"): return self.name self.__class__ = _ForwardNoRecurse try: if self.expr is not None: retString = _ustr(self.expr) else: retString = "None" finally: self.__class__ = Forward return "Forward: "+retString def copy(self): if self.expr is not None: return super(Forward,self).copy() else: ret = Forward() ret << self return ret class _ForwardNoRecurse(Forward): def __str__( self ): return "..." class TokenConverter(ParseElementEnhance): """Abstract subclass of ParseExpression, for converting parsed results.""" def __init__( self, expr, savelist=False ): super(TokenConverter,self).__init__( expr )#, savelist ) self.saveAsList = False class Upcase(TokenConverter): """Converter to upper case all matching tokens.""" def __init__(self, *args): super(Upcase,self).__init__(*args) warnings.warn("Upcase class is deprecated, use upcaseTokens parse action instead", DeprecationWarning,stacklevel=2) def postParse( self, instring, loc, tokenlist ): return map( string.upper, tokenlist ) class Combine(TokenConverter): """Converter to concatenate all matching tokens to a single string. By default, the matching patterns must also be contiguous in the input string; this can be disabled by specifying 'adjacent=False' in the constructor. """ def __init__( self, expr, joinString="", adjacent=True ): super(Combine,self).__init__( expr ) # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself if adjacent: self.leaveWhitespace() self.adjacent = adjacent self.skipWhitespace = True self.joinString = joinString def ignore( self, other ): if self.adjacent: ParserElement.ignore(self, other) else: super( Combine, self).ignore( other ) return self def postParse( self, instring, loc, tokenlist ): retToks = tokenlist.copy() del retToks[:] retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults) if self.resultsName and len(retToks.keys())>0: return [ retToks ] else: return retToks class Group(TokenConverter): """Converter to return the matched tokens as a list - useful for returning tokens of ZeroOrMore and OneOrMore expressions.""" def __init__( self, expr ): super(Group,self).__init__( expr ) self.saveAsList = True def postParse( self, instring, loc, tokenlist ): return [ tokenlist ] class Dict(TokenConverter): """Converter to return a repetitive expression as a list, but also as a dictionary. Each element can also be referenced using the first token in the expression as its key. Useful for tabular report scraping when the first column can be used as a item key. """ def __init__( self, exprs ): super(Dict,self).__init__( exprs ) self.saveAsList = True def postParse( self, instring, loc, tokenlist ): for i,tok in enumerate(tokenlist): if len(tok) == 0: continue ikey = tok[0] if isinstance(ikey,int): ikey = _ustr(tok[0]).strip() if len(tok)==1: tokenlist[ikey] = _ParseResultsWithOffset("",i) elif len(tok)==2 and not isinstance(tok[1],ParseResults): tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i) else: dictvalue = tok.copy() #ParseResults(i) del dictvalue[0] if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.keys()): tokenlist[ikey] = _ParseResultsWithOffset(dictvalue,i) else: tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0],i) if self.resultsName: return [ tokenlist ] else: return tokenlist class Suppress(TokenConverter): """Converter for ignoring the results of a parsed expression.""" def postParse( self, instring, loc, tokenlist ): return [] def suppress( self ): return self class OnlyOnce(object): """Wrapper for parse actions, to ensure they are only called once.""" def __init__(self, methodCall): self.callable = ParserElement._normalizeParseActionArgs(methodCall) self.called = False def __call__(self,s,l,t): if not self.called: results = self.callable(s,l,t) self.called = True return results raise ParseException(s,l,"") def reset(self): self.called = False def traceParseAction(f): """Decorator for debugging parse actions.""" f = ParserElement._normalizeParseActionArgs(f) def z(*paArgs): thisFunc = f.func_name s,l,t = paArgs[-3:] if len(paArgs)>3: thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc sys.stderr.write( ">>entering %s(line: '%s', %d, %s)\n" % (thisFunc,line(l,s),l,t) ) try: ret = f(*paArgs) except Exception, exc: sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) ) raise sys.stderr.write( "<<leaving %s (ret: %s)\n" % (thisFunc,ret) ) return ret try: z.__name__ = f.__name__ except AttributeError: pass return z # # global helpers # def delimitedList( expr, delim=",", combine=False ): """Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing 'combine=True' in the constructor. If combine is set to True, the matching tokens are returned as a single token string, with the delimiters included; otherwise, the matching tokens are returned as a list of tokens, with the delimiters suppressed. """ dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..." if combine: return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName) else: return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName) def countedArray( expr ): """Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. """ arrayExpr = Forward() def countFieldParseAction(s,l,t): n = int(t[0]) arrayExpr << (n and Group(And([expr]*n)) or Group(empty)) return [] return ( Word(nums).setName("arrayLen").setParseAction(countFieldParseAction, callDuringTry=True) + arrayExpr ) def _flatten(L): if type(L) is not list: return [L] if L == []: return L return _flatten(L[0]) + _flatten(L[1:]) def matchPreviousLiteral(expr): """Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousLiteral(first) matchExpr = first + ":" + second will match "1:1", but not "1:2". Because this matches a previous literal, will also match the leading "1:1" in "1:10". If this is not desired, use matchPreviousExpr. Do *not* use with packrat parsing enabled. """ rep = Forward() def copyTokenToRepeater(s,l,t): if t: if len(t) == 1: rep << t[0] else: # flatten t tokens tflat = _flatten(t.asList()) rep << And( [ Literal(tt) for tt in tflat ] ) else: rep << Empty() expr.addParseAction(copyTokenToRepeater, callDuringTry=True) return rep def matchPreviousExpr(expr): """Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = matchPreviousExpr(first) matchExpr = first + ":" + second will match "1:1", but not "1:2". Because this matches by expressions, will *not* match the leading "1:1" in "1:10"; the expressions are evaluated first, and then compared, so "1" is compared with "10". Do *not* use with packrat parsing enabled. """ rep = Forward() e2 = expr.copy() rep << e2 def copyTokenToRepeater(s,l,t): matchTokens = _flatten(t.asList()) def mustMatchTheseTokens(s,l,t): theseTokens = _flatten(t.asList()) if theseTokens != matchTokens: raise ParseException("",0,"") rep.setParseAction( mustMatchTheseTokens, callDuringTry=True ) expr.addParseAction(copyTokenToRepeater, callDuringTry=True) return rep def _escapeRegexRangeChars(s): #~ escape these chars: ^-] for c in r"\^-]": s = s.replace(c,"\\"+c) s = s.replace("\n",r"\n") s = s.replace("\t",r"\t") return _ustr(s) def oneOf( strs, caseless=False, useRegex=True ): """Helper to quickly define a set of alternative Literals, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a MatchFirst for best performance. Parameters: - strs - a string of space-delimited literals, or a list of string literals - caseless - (default=False) - treat all literals as caseless - useRegex - (default=True) - as an optimization, will generate a Regex object; otherwise, will generate a MatchFirst object (if caseless=True, or if creating a Regex raises an exception) """ if caseless: isequal = ( lambda a,b: a.upper() == b.upper() ) masks = ( lambda a,b: b.upper().startswith(a.upper()) ) parseElementClass = CaselessLiteral else: isequal = ( lambda a,b: a == b ) masks = ( lambda a,b: b.startswith(a) ) parseElementClass = Literal if isinstance(strs,(list,tuple)): symbols = strs[:] elif isinstance(strs,__BASE_STRING__): symbols = strs.split() else: warnings.warn("Invalid argument to oneOf, expected string or list", SyntaxWarning, stacklevel=2) i = 0 while i < len(symbols)-1: cur = symbols[i] for j,other in enumerate(symbols[i+1:]): if ( isequal(other, cur) ): del symbols[i+j+1] break elif ( masks(cur, other) ): del symbols[i+j+1] symbols.insert(i,other) cur = other break else: i += 1 if not caseless and useRegex: #~ print (strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] )) try: if len(symbols)==len("".join(symbols)): return Regex( "[%s]" % "".join( [ _escapeRegexRangeChars(sym) for sym in symbols] ) ) else: return Regex( "|".join( [ re.escape(sym) for sym in symbols] ) ) except: warnings.warn("Exception creating Regex for oneOf, building MatchFirst", SyntaxWarning, stacklevel=2) # last resort, just use MatchFirst return MatchFirst( [ parseElementClass(sym) for sym in symbols ] ) def dictOf( key, value ): """Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the Dict, ZeroOrMore, and Group tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the Dict results can include named token fields. """ return Dict( ZeroOrMore( Group ( key + value ) ) ) # convenience constants for positional expressions empty = Empty().setName("empty") lineStart = LineStart().setName("lineStart") lineEnd = LineEnd().setName("lineEnd") stringStart = StringStart().setName("stringStart") stringEnd = StringEnd().setName("stringEnd") _escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1]) _printables_less_backslash = "".join([ c for c in printables if c not in r"\]" ]) _escapedHexChar = Combine( Suppress(_bslash + "0x") + Word(hexnums) ).setParseAction(lambda s,l,t:unichr(int(t[0],16))) _escapedOctChar = Combine( Suppress(_bslash) + Word("0","01234567") ).setParseAction(lambda s,l,t:unichr(int(t[0],8))) _singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(_printables_less_backslash,exact=1) _charRange = Group(_singleChar + Suppress("-") + _singleChar) _reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]" _expanded = lambda p: (isinstance(p,ParseResults) and ''.join([ unichr(c) for c in range(ord(p[0]),ord(p[1])+1) ]) or p) def srange(s): r"""Helper to easily define string ranges for use in Word construction. Borrows syntax from regexp '[]' string range definitions:: srange("[0-9]") -> "0123456789" srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" The input string must be enclosed in []'s, and the returned string is the expanded character set joined into a single string. The values enclosed in the []'s may be:: a single character an escaped character with a leading backslash (such as \- or \]) an escaped hex character with a leading '\0x' (\0x21, which is a '!' character) an escaped octal character with a leading '\0' (\041, which is a '!' character) a range of any of the above, separated by a dash ('a-z', etc.) any combination of the above ('aeiouy', 'a-zA-Z0-9_$', etc.) """ try: return "".join([_expanded(part) for part in _reBracketExpr.parseString(s).body]) except: return "" def matchOnlyAtCol(n): """Helper method for defining parse actions that require matching at a specific column in the input text. """ def verifyCol(strg,locn,toks): if col(locn,strg) != n: raise ParseException(strg,locn,"matched token not at column %d" % n) return verifyCol def replaceWith(replStr): """Helper method for common parse actions that simply return a literal value. Especially useful when used with transformString(). """ def _replFunc(*args): return [replStr] return _replFunc def removeQuotes(s,l,t): """Helper parse action for removing quotation marks from parsed quoted strings. To use, add this parse action to quoted string using:: quotedString.setParseAction( removeQuotes ) """ return t[0][1:-1] def upcaseTokens(s,l,t): """Helper parse action to convert tokens to upper case.""" return [ tt.upper() for tt in map(_ustr,t) ] def downcaseTokens(s,l,t): """Helper parse action to convert tokens to lower case.""" return [ tt.lower() for tt in map(_ustr,t) ] def keepOriginalText(s,startLoc,t): """Helper parse action to preserve original parsed text, overriding any nested parse actions.""" try: endloc = getTokensEndLoc() except ParseException: raise ParseFatalException, "incorrect usage of keepOriginalText - may only be called as a parse action" del t[:] t += ParseResults(s[startLoc:endloc]) return t def getTokensEndLoc(): """Method to be called from within a parse action to determine the end location of the parsed tokens.""" import inspect fstack = inspect.stack() try: # search up the stack (through intervening argument normalizers) for correct calling routine for f in fstack[2:]: if f[3] == "_parseNoCache": endloc = f[0].f_locals["loc"] return endloc else: raise ParseFatalException, "incorrect usage of getTokensEndLoc - may only be called from within a parse action" finally: del fstack def _makeTags(tagStr, xml): """Internal helper to construct opening and closing tag expressions, given a tag name""" if isinstance(tagStr,__BASE_STRING__): resname = tagStr tagStr = Keyword(tagStr, caseless=not xml) else: resname = tagStr.name tagAttrName = Word(alphas,alphanums+"_-:") if (xml): tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes ) openTag = Suppress("<") + tagStr + \ Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") else: printablesLessRAbrack = "".join( [ c for c in printables if c not in ">" ] ) tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack) openTag = Suppress("<") + tagStr + \ Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \ Optional( Suppress("=") + tagAttrValue ) ))) + \ Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">") closeTag = Combine(_L("</") + tagStr + ">") openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % tagStr) closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % tagStr) return openTag, closeTag def makeHTMLTags(tagStr): """Helper to construct opening and closing tag expressions for HTML, given a tag name""" return _makeTags( tagStr, False ) def makeXMLTags(tagStr): """Helper to construct opening and closing tag expressions for XML, given a tag name""" return _makeTags( tagStr, True ) def withAttribute(*args,**attrDict): """Helper to create a validating parse action to be used with start tags created with makeXMLTags or makeHTMLTags. Use withAttribute to qualify a starting tag with a required attribute value, to avoid false matches on common tags such as <TD> or <DIV>. Call withAttribute with a series of attribute names and values. Specify the list of filter attributes names and values as: - keyword arguments, as in (class="Customer",align="right"), or - a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") ) For attribute names with a namespace prefix, you must use the second form. Attribute names are matched insensitive to upper/lower case. To verify that the attribute exists, but without specifying a value, pass withAttribute.ANY_VALUE as the value. """ if args: attrs = args[:] else: attrs = attrDict.items() attrs = [(k,v) for k,v in attrs] def pa(s,l,tokens): for attrName,attrValue in attrs: if attrName not in tokens: raise ParseException(s,l,"no matching attribute " + attrName) if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue: raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" % (attrName, tokens[attrName], attrValue)) return pa withAttribute.ANY_VALUE = object() opAssoc = _Constants() opAssoc.LEFT = object() opAssoc.RIGHT = object() def operatorPrecedence( baseExpr, opList ): """Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions. Parameters: - baseExpr - expression representing the most basic element for the nested - opList - list of tuples, one for each operator precedence level in the expression grammar; each tuple is of the form (opExpr, numTerms, rightLeftAssoc, parseAction), where: - opExpr is the pyparsing expression for the operator; may also be a string, which will be converted to a Literal - numTerms is the number of terms for this operator (must be 1 or 2) - rightLeftAssoc is the indicator whether the operator is right or left associative, using the pyparsing-defined constants opAssoc.RIGHT and opAssoc.LEFT. - parseAction is the parse action to be associated with expressions matching this operator expression (the parse action tuple member may be omitted) """ ret = Forward() lastExpr = baseExpr | ( Suppress('(') + ret + Suppress(')') ) for i,operDef in enumerate(opList): opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4] thisExpr = Forward()#.setName("expr%d" % i) if rightLeftAssoc == opAssoc.LEFT: if arity == 1: matchExpr = Group( FollowedBy(lastExpr + opExpr) + lastExpr + OneOrMore( opExpr ) ) elif arity == 2: matchExpr = Group( FollowedBy(lastExpr + opExpr + lastExpr) + lastExpr + OneOrMore( opExpr + lastExpr ) ) else: raise ValueError, "operator must be unary (1) or binary (2)" elif rightLeftAssoc == opAssoc.RIGHT: if arity == 1: # try to avoid LR with this extra test if not isinstance(opExpr, Optional): opExpr = Optional(opExpr) matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr ) elif arity == 2: matchExpr = Group( FollowedBy(lastExpr + opExpr + thisExpr) + lastExpr + OneOrMore( opExpr + thisExpr ) ) else: raise ValueError, "operator must be unary (1) or binary (2)" else: raise ValueError, "operator must indicate right or left associativity" if pa: matchExpr.setParseAction( pa ) thisExpr << ( matchExpr | lastExpr ) lastExpr = thisExpr ret << lastExpr return ret dblQuotedString = Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*"').setName("string enclosed in double quotes") sglQuotedString = Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*'").setName("string enclosed in single quotes") quotedString = Regex(r'''(?:"(?:[^"\n\r\\]|(?:"")|(?:\\x[0-9a-fA-F]+)|(?:\\.))*")|(?:'(?:[^'\n\r\\]|(?:'')|(?:\\x[0-9a-fA-F]+)|(?:\\.))*')''').setName("quotedString using single or double quotes") unicodeString = Combine(_L('u') + quotedString.copy()) def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString): """Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default="("); can also be a pyparsing expression - closer - closing character for a nested list (default=")"); can also be a pyparsing expression - content - expression for items within the nested lists (default=None) - ignoreExpr - expression for ignoring opening and closing delimiters (default=quotedString) If an expression is not provided for the content argument, the nested expression will capture all whitespace-delimited content between delimiters as a list of separate values. Use the ignoreExpr argument to define expressions that may contain opening or closing characters that should not be treated as opening or closing characters for nesting, such as quotedString or a comment expression. Specify multiple expressions using an Or or MatchFirst. The default is quotedString, but if no expressions are to be ignored, then pass None for this argument. """ if opener == closer: raise ValueError("opening and closing strings cannot be the same") if content is None: if isinstance(opener,__BASE_STRING__) and isinstance(closer,__BASE_STRING__): content = (empty+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS).setParseAction(lambda t:t[0].strip())) else: raise ValueError("opening and closing arguments must be strings if no content expression is given") ret = Forward() if ignoreExpr is not None: ret << Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) ) else: ret << Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) ) return ret alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]") punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]") anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:")) commonHTMLEntity = Combine(_L("&") + oneOf("gt lt amp nbsp quot").setResultsName("entity") +";") _htmlEntityMap = dict(zip("gt lt amp nbsp quot".split(),"><& '")) replaceHTMLEntity = lambda t : t.entity in _htmlEntityMap and _htmlEntityMap[t.entity] or None # it's easy to get these comment structures wrong - they're very common, so may as well make them available cStyleComment = Regex(r"/\*(?:[^*]*\*+)+?/").setName("C style comment") htmlComment = Regex(r"<!--[\s\S]*?-->") restOfLine = Regex(r".*").leaveWhitespace() dblSlashComment = Regex(r"\/\/(\\\n|.)*").setName("// comment") cppStyleComment = Regex(r"/(?:\*(?:[^*]*\*+)+?/|/[^\n]*(?:\n[^\n]*)*?(?:(?<!\\)|\Z))").setName("C++ style comment") javaStyleComment = cppStyleComment pythonStyleComment = Regex(r"#.*").setName("Python style comment") _noncomma = "".join( [ c for c in printables if c != "," ] ) _commasepitem = Combine(OneOrMore(Word(_noncomma) + Optional( Word(" \t") + ~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem") commaSeparatedList = delimitedList( Optional( quotedString | _commasepitem, default="") ).setName("commaSeparatedList") if __name__ == "__main__": def test( teststring ): print (teststring,"->",) try: tokens = simpleSQL.parseString( teststring ) tokenlist = tokens.asList() print (tokenlist) print ("tokens = ", tokens) print ("tokens.columns =", tokens.columns) print ("tokens.tables =", tokens.tables) print (tokens.asXML("SQL",True)) except ParseException,err: print (err.line) print (" "*(err.column-1) + "^") print (err) print() selectToken = CaselessLiteral( "select" ) fromToken = CaselessLiteral( "from" ) ident = Word( alphas, alphanums + "_$" ) columnName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens ) columnNameList = Group( delimitedList( columnName ) )#.setName("columns") tableName = delimitedList( ident, ".", combine=True ).setParseAction( upcaseTokens ) tableNameList = Group( delimitedList( tableName ) )#.setName("tables") simpleSQL = ( selectToken + \ ( '*' | columnNameList ).setResultsName( "columns" ) + \ fromToken + \ tableNameList.setResultsName( "tables" ) ) test( "SELECT * from XYZZY, ABC" ) test( "select * from SYS.XYZZY" ) test( "Select A from Sys.dual" ) test( "Select AA,BB,CC from Sys.dual" ) test( "Select A, B, C from Sys.dual" ) test( "Select A, B, C from Sys.dual" ) test( "Xelect A, B, C from Sys.dual" ) test( "Select A, B, C frox Sys.dual" ) test( "Select" ) test( "Select ^^^ frox Sys.dual" ) test( "Select A, B, C from Sys.dual, Table2 " )
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # Copyright (C) 2006-2007 Søren Roug, European Environment Agency # # 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 Street, Fifth Floor, Boston, MA 02110-1301 USA # # Contributor(s): # from namespaces import MATHNS from element import Element # ODF 1.0 section 12.5 # Mathematical content is represented by MathML 2.0 # Autogenerated def Math(**args): return Element(qname = (MATHNS,'math'), **args)
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python3 """Read all test files for a particular file format using a single importer instance. Read them again in reversed order. This is used to verify that a loader does proper cleanup and can be called repeatedly.""" import sys import os import subprocess # hack-load utils.py and settings.py from ../regression sys.path.append(os.path.join('..','regression')) import utils import settings def process_dir(thisdir): """Process /thisdir/ recursively""" res = [] shellparams = {'stdin':subprocess.PIPE,'stdout':sys.stdout,'shell':True} command = [utils.assimp_bin_path,"testbatchload"] for f in os.listdir(thisdir): if os.path.splitext(f)[-1] in settings.exclude_extensions: continue fullpath = os.path.join(thisdir, f) if os.path.isdir(fullpath): if f != ".svn": res += process_dir(fullpath) continue # import twice, importing the same file again introduces extra risk # to crash due to garbage data lying around in the importer. command.append(fullpath) command.append(fullpath) if len(command)>2: # testbatchload returns always 0 if more than one file in the list worked. # however, if it should segfault, the OS will return something not 0. command += reversed(command[2:]) if subprocess.call(command, **shellparams): res.append(thisdir) return res def main(): """Run the test on all registered test repositories""" utils.find_assimp_or_die() res = [] for tp in settings.model_directories: res += process_dir(tp) [print(f) for f in res] return 0 if __name__ == '__main__': res = main() input('All done, waiting for keystroke ') sys.exit(res) # vim: ai ts=4 sts=4 et sw=4
unknown
codeparrot/codeparrot-clean
#!/usr/bin/python import os import unittest from mock import Mock from testutils import setup_test_env setup_test_env() from softwarecenter.region import RegionDiscover, get_region_name from softwarecenter.i18n import init_locale class TestRegion(unittest.TestCase): """ tests the region detection """ def setUp(self): self.region = RegionDiscover() def test_get_region_dump(self): os.environ["LC_ALL"] = "en_ZM.utf8" init_locale() res = self.region._get_region_dumb() self.assertEqual(res["countrycode"], "ZM") self.assertEqual(res["country"], "Zambia") os.environ["LANG"] = "" def test_get_region_name(self): self.assertEqual(get_region_name("BO"), "Bolivia") self.assertEqual(get_region_name("DE"), "Germany") @unittest.skip("real ubuntu-geoip not always reliable") def test_get_region_geoclue(self): res = self.region._get_region_geoclue() self.assertNotEqual(len(res), 0) self.assertTrue("countrycode" in res) self.assertTrue("country" in res) # helper def _mock_internal_region_finders(self): self.region._get_region_dumb = Mock() self.region._get_region_geoclue = Mock() def test_get_region_no_mocks(self): res = self.region.get_region() self.assertNotEqual(len(res), 0) def test_get_region_normal(self): self._mock_internal_region_finders() self.region.get_region() self.assertTrue(self.region._get_region_geoclue.called) self.assertFalse(self.region._get_region_dumb.called) def test_get_region_fallback(self): # test fallback (no geoclue) self._mock_internal_region_finders() self.region._get_region_geoclue.side_effect = Exception("raise test exception") self.region.get_region() self.assertTrue(self.region._get_region_dumb.called) self.assertTrue(self.region._get_region_geoclue.called) if __name__ == "__main__": import logging logging.basicConfig(level=logging.DEBUG) unittest.main()
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. from bambou import NURESTFetcher class NUNetworkMacroGroupsFetcher(NURESTFetcher): """ Represents a NUNetworkMacroGroups fetcher Notes: This fetcher enables to fetch NUNetworkMacroGroup objects. See: bambou.NURESTFetcher """ @classmethod def managed_class(cls): """ Return NUNetworkMacroGroup class that is managed. Returns: .NUNetworkMacroGroup: the managed class """ from .. import NUNetworkMacroGroup return NUNetworkMacroGroup
unknown
codeparrot/codeparrot-clean
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005, 2006 Martin v. Löwis # Licensed to PSF under a Contributor Agreement. # The bdist_wininst command proper # based on bdist_wininst """ Implements the bdist_msi command. """ import sys, os from distutils.core import Command from distutils.dir_util import remove_tree from distutils.sysconfig import get_python_version from distutils.version import StrictVersion from distutils.errors import DistutilsOptionError from distutils.util import get_platform from distutils import log import msilib from msilib import schema, sequence, text from msilib import Directory, Feature, Dialog, add_data class PyDialog(Dialog): """Dialog class with a fixed layout: controls at the top, then a ruler, then a list of buttons: back, next, cancel. Optionally a bitmap at the left.""" def __init__(self, *args, **kw): """Dialog(database, name, x, y, w, h, attributes, title, first, default, cancel, bitmap=true)""" Dialog.__init__(self, *args) ruler = self.h - 36 bmwidth = 152*ruler/328 #if kw.get("bitmap", True): # self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin") self.line("BottomLine", 0, ruler, self.w, 0) def title(self, title): "Set the title text of the dialog at the top." # name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix, # text, in VerdanaBold10 self.text("Title", 15, 10, 320, 60, 0x30003, r"{\VerdanaBold10}%s" % title) def back(self, title, next, name = "Back", active = 1): """Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next) def cancel(self, title, next, name = "Cancel", active = 1): """Add a cancel button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next) def next(self, title, next, name = "Next", active = 1): """Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next) def xbutton(self, name, title, next, xpos): """Add a button with a given title, the tab-next button, its name in the Control table, giving its x position; the y-position is aligned with the other buttons. Return the button, so that events can be associated""" return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next) class bdist_msi (Command): description = "create a Microsoft Installer (.msi) binary distribution" user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), ('plat-name=', 'p', "platform name to embed in generated filenames " "(default: %s)" % get_platform()), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), ('target-version=', None, "require a specific python version" + " on the target system"), ('no-target-compile', 'c', "do not compile .py to .pyc on the target system"), ('no-target-optimize', 'o', "do not compile .py to .pyo (optimized)" "on the target system"), ('dist-dir=', 'd', "directory to put final built distributions in"), ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), ('install-script=', None, "basename of installation script to be run after" "installation or before deinstallation"), ('pre-install-script=', None, "Fully qualified filename of a script to be run before " "any files are installed. This script need not be in the " "distribution"), ] boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize', 'skip-build'] def initialize_options (self): self.bdist_dir = None self.plat_name = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 self.target_version = None self.dist_dir = None self.skip_build = 0 self.install_script = None self.pre_install_script = None def finalize_options (self): if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'msi') short_version = get_python_version() if self.target_version: if not self.skip_build and self.distribution.has_ext_modules()\ and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be %s, or the '--skip_build'" \ " option must be specified" % (short_version,) else: self.target_version = short_version self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'), ('plat_name', 'plat_name'), ) if self.pre_install_script: raise DistutilsOptionError, "the pre-install-script feature is not yet implemented" if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, \ "install_script '%s' not found in scripts" % \ self.install_script self.install_script_key = None # finalize_options() def run (self): if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.prefix = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files install_lib.compile = 0 install_lib.optimize = 0 if self.distribution.has_ext_modules(): # If we are building an installer for a Python version other # than the one we are currently running, then we need to ensure # our build_lib reflects the other Python version rather than ours. # Note that for target_version!=sys.version, we must have skipped the # build step, so there is no issue with enforcing the build of this # version. target_version = self.target_version if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] plat_specifier = ".%s-%s" % (self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) log.info("installing to %s", self.bdist_dir) install.ensure_finalized() # avoid warning of 'install_lib' about installing # into a directory not in sys.path sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB')) install.run() del sys.path[0] self.mkpath(self.dist_dir) fullname = self.distribution.get_fullname() installer_name = self.get_installer_filename(fullname) installer_name = os.path.abspath(installer_name) if os.path.exists(installer_name): os.unlink(installer_name) metadata = self.distribution.metadata author = metadata.author if not author: author = metadata.maintainer if not author: author = "UNKNOWN" version = metadata.get_version() # ProductVersion must be strictly numeric # XXX need to deal with prerelease versions sversion = "%d.%d.%d" % StrictVersion(version).version # Prefix ProductName with Python x.y, so that # it sorts together with the other Python packages # in Add-Remove-Programs (APR) product_name = "Python %s %s" % (self.target_version, self.distribution.get_fullname()) self.db = msilib.init_database(installer_name, schema, product_name, msilib.gen_uuid(), sversion, author) msilib.add_tables(self.db, sequence) props = [('DistVersion', version)] email = metadata.author_email or metadata.maintainer_email if email: props.append(("ARPCONTACT", email)) if metadata.url: props.append(("ARPURLINFOABOUT", metadata.url)) if props: add_data(self.db, 'Property', props) self.add_find_python() self.add_files() self.add_scripts() self.add_ui() self.db.Commit() if hasattr(self.distribution, 'dist_files'): self.distribution.dist_files.append(('bdist_msi', self.target_version, fullname)) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run) def add_files(self): db = self.db cab = msilib.CAB("distfiles") f = Feature(db, "default", "Default Feature", "Everything", 1, directory="TARGETDIR") f.set_current() rootdir = os.path.abspath(self.bdist_dir) root = Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir") db.Commit() todo = [root] while todo: dir = todo.pop() for file in os.listdir(dir.absolute): afile = os.path.join(dir.absolute, file) if os.path.isdir(afile): newdir = Directory(db, cab, dir, file, file, "%s|%s" % (dir.make_short(file), file)) todo.append(newdir) else: key = dir.add_file(file) if file==self.install_script: if self.install_script_key: raise DistutilsOptionError, "Multiple files with name %s" % file self.install_script_key = '[#%s]' % key cab.commit(db) def add_find_python(self): """Adds code to the installer to compute the location of Python. Properties PYTHON.MACHINE, PYTHON.USER, PYTHONDIR and PYTHON will be set in both the execute and UI sequences; PYTHONDIR will be set from PYTHON.USER if defined, else from PYTHON.MACHINE. PYTHON is PYTHONDIR\python.exe""" install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % self.target_version if msilib.Win64: # type: msidbLocatorTypeRawValue + msidbLocatorType64bit Type = 2+16 else: Type = 2 add_data(self.db, "RegLocator", [("python.machine", 2, install_path, None, Type), ("python.user", 1, install_path, None, Type)]) add_data(self.db, "AppSearch", [("PYTHON.MACHINE", "python.machine"), ("PYTHON.USER", "python.user")]) add_data(self.db, "CustomAction", [("PythonFromMachine", 51+256, "PYTHONDIR", "[PYTHON.MACHINE]"), ("PythonFromUser", 51+256, "PYTHONDIR", "[PYTHON.USER]"), ("PythonExe", 51+256, "PYTHON", "[PYTHONDIR]\\python.exe"), ("InitialTargetDir", 51+256, "TARGETDIR", "[PYTHONDIR]")]) add_data(self.db, "InstallExecuteSequence", [("PythonFromMachine", "PYTHON.MACHINE", 401), ("PythonFromUser", "PYTHON.USER", 402), ("PythonExe", None, 403), ("InitialTargetDir", 'TARGETDIR=""', 404), ]) add_data(self.db, "InstallUISequence", [("PythonFromMachine", "PYTHON.MACHINE", 401), ("PythonFromUser", "PYTHON.USER", 402), ("PythonExe", None, 403), ("InitialTargetDir", 'TARGETDIR=""', 404), ]) def add_scripts(self): if self.install_script: add_data(self.db, "CustomAction", [("install_script", 50, "PYTHON", self.install_script_key)]) add_data(self.db, "InstallExecuteSequence", [("install_script", "NOT Installed", 6800)]) if self.pre_install_script: scriptfn = os.path.join(self.bdist_dir, "preinstall.bat") f = open(scriptfn, "w") # The batch file will be executed with [PYTHON], so that %1 # is the path to the Python interpreter; %0 will be the path # of the batch file. # rem =""" # %1 %0 # exit # """ # <actual script> f.write('rem ="""\n%1 %0\nexit\n"""\n') f.write(open(self.pre_install_script).read()) f.close() add_data(self.db, "Binary", [("PreInstall", msilib.Binary(scriptfn)) ]) add_data(self.db, "CustomAction", [("PreInstall", 2, "PreInstall", None) ]) add_data(self.db, "InstallExecuteSequence", [("PreInstall", "NOT Installed", 450)]) def add_ui(self): db = self.db x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible track_disk_space = 32 # UI customization properties add_data(db, "Property", # See "DefaultUIFont Property" [("DefaultUIFont", "DlgFont8"), # See "ErrorDialog Style Bit" ("ErrorDialog", "ErrorDlg"), ("Progress1", "Install"), # modified in maintenance type dlg ("Progress2", "installs"), ("MaintenanceForm_Action", "Repair"), # possible values: ALL, JUSTME ("WhichUsers", "ALL") ]) # Fonts, see "TextStyle Table" add_data(db, "TextStyle", [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), #bold ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0), ]) # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table" # Numbers indicate sequence; see sequence.py for how these action integrate add_data(db, "InstallUISequence", [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140), ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), # In the user interface, assume all-users installation if privileged. ("SelectDirectoryDlg", "Not Installed", 1230), # XXX no support for resume installations yet #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250), ("ProgressDlg", None, 1280)]) add_data(db, 'ActionText', text.ActionText) add_data(db, 'UIText', text.UIText) ##################################################################### # Standard dialogs: FatalError, UserExit, ExitDialog fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish") fatal.title("[ProductName] Installer ended prematurely") fatal.back("< Back", "Finish", active = 0) fatal.cancel("Cancel", "Back", active = 0) fatal.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.") fatal.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c=fatal.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish") user_exit.title("[ProductName] Installer was interrupted") user_exit.back("< Back", "Finish", active = 0) user_exit.cancel("Cancel", "Back", active = 0) user_exit.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not been modified. " "To install this program at a later time, please run the installation again.") user_exit.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = user_exit.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish") exit_dialog.title("Completing the [ProductName] Installer") exit_dialog.back("< Back", "Finish", active = 0) exit_dialog.cancel("Cancel", "Back", active = 0) exit_dialog.text("Description", 15, 235, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = exit_dialog.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Return") ##################################################################### # Required dialog: FilesInUse, ErrorDlg inuse = PyDialog(db, "FilesInUse", x, y, w, h, 19, # KeepModeless|Modal|Visible title, "Retry", "Retry", "Retry", bitmap=False) inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") inuse.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") inuse.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.") inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) c=inuse.back("Exit", "Ignore", name="Exit") c.event("EndDialog", "Exit") c=inuse.next("Ignore", "Retry", name="Ignore") c.event("EndDialog", "Ignore") c=inuse.cancel("Retry", "Exit", name="Retry") c.event("EndDialog","Retry") # See "Error Dialog". See "ICE20" for the required names of the controls. error = Dialog(db, "ErrorDlg", 50, 10, 330, 101, 65543, # Error|Minimize|Modal|Visible title, "ErrorText", None, None) error.text("ErrorText", 50,9,280,48,3, "") #error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None) error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo") error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes") error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort") error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel") error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore") error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk") error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry") ##################################################################### # Global "Query Cancel" dialog cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No") cancel.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") #cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, # "py.ico", None, None) c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") c.event("EndDialog", "Exit") c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Global "Wait for costing" dialog costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title, "Return", "Return", "Return") costing.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your disk space requirements.") c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) c.event("EndDialog", "Exit") ##################################################################### # Preparation dialog: no user input except cancellation prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel") prep.text("Description", 15, 70, 320, 40, 0x30003, "Please wait while the Installer prepares to guide you through the installation.") prep.title("Welcome to the [ProductName] Installer") c=prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...") c.mapping("ActionText", "Text") c=prep.text("ActionData", 15, 135, 320, 30, 0x30003, None) c.mapping("ActionData", "Text") prep.back("Back", None, active=0) prep.next("Next", None, active=0) c=prep.cancel("Cancel", None) c.event("SpawnDialog", "CancelDlg") ##################################################################### # Target directory selection seldlg = PyDialog(db, "SelectDirectoryDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") seldlg.title("Select Destination Directory") version = sys.version[:3]+" " seldlg.text("Hint", 15, 30, 300, 40, 3, "The destination directory should contain a Python %sinstallation" % version) seldlg.back("< Back", None, active=0) c = seldlg.next("Next >", "Cancel") c.event("SetTargetPath", "TARGETDIR", ordering=1) c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=2) c.event("EndDialog", "Return", ordering=3) c = seldlg.cancel("Cancel", "DirectoryCombo") c.event("SpawnDialog", "CancelDlg") seldlg.control("DirectoryCombo", "DirectoryCombo", 15, 70, 272, 80, 393219, "TARGETDIR", None, "DirectoryList", None) seldlg.control("DirectoryList", "DirectoryList", 15, 90, 308, 136, 3, "TARGETDIR", None, "PathEdit", None) seldlg.control("PathEdit", "PathEdit", 15, 230, 306, 16, 3, "TARGETDIR", None, "Next", None) c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None) c.event("DirectoryListUp", "0") c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None) c.event("DirectoryListNew", "0") ##################################################################### # Disk cost cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False) cost.text("Title", 15, 6, 200, 15, 0x30003, "{\DlgFontBold8}Disk Space Requirements") cost.text("Description", 20, 20, 280, 20, 0x30003, "The disk space required for the installation of the selected features.") cost.text("Text", 20, 53, 330, 60, 3, "The highlighted volumes (if any) do not have enough disk space " "available for the currently selected features. You can either " "remove some files from the highlighted volumes, or choose to " "install less features onto local drive(s), or select different " "destination drive(s).") cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223, None, "{120}{70}{70}{70}{70}", None, None) cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return") ##################################################################### # WhichUsers Dialog. Only available on NT, and for privileged users. # This must be run before FindRelatedProducts, because that will # take into account whether the previous installation was per-user # or per-machine. We currently don't support going back to this # dialog after "Next" was selected; to support this, we would need to # find how to reset the ALLUSERS property, and how to re-run # FindRelatedProducts. # On Windows9x, the ALLUSERS property is ignored on the command line # and in the Property table, but installer fails according to the documentation # if a dialog attempts to set ALLUSERS. whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title, "AdminInstall", "Next", "Cancel") whichusers.title("Select whether to install [ProductName] for all users of this computer.") # A radio group with two options: allusers, justme g = whichusers.radiogroup("AdminInstall", 15, 60, 260, 50, 3, "WhichUsers", "", "Next") g.add("ALL", 0, 5, 150, 20, "Install for all users") g.add("JUSTME", 0, 25, 150, 20, "Install just for me") whichusers.back("Back", None, active=0) c = whichusers.next("Next >", "Cancel") c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1) c.event("EndDialog", "Return", ordering = 2) c = whichusers.cancel("Cancel", "AdminInstall") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Installation Progress dialog (modeless) progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel", bitmap=False) progress.text("Title", 20, 15, 200, 15, 0x30003, "{\DlgFontBold8}[Progress1] [ProductName]") progress.text("Text", 35, 65, 300, 30, 3, "Please wait while the Installer [Progress2] [ProductName]. " "This may take several minutes.") progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:") c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...") c.mapping("ActionText", "Text") #c=progress.text("ActionData", 35, 140, 300, 20, 3, None) #c.mapping("ActionData", "Text") c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) c.mapping("SetProgress", "Progress") progress.back("< Back", "Next", active=False) progress.next("Next >", "Cancel", active=False) progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg") ################################################################### # Maintenance type: repair/uninstall maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") maint.title("Welcome to the [ProductName] Setup Wizard") maint.text("BodyText", 15, 63, 330, 42, 3, "Select whether you want to repair or remove [ProductName].") g=maint.radiogroup("RepairRadioGroup", 15, 108, 330, 60, 3, "MaintenanceForm_Action", "", "Next") #g.add("Change", 0, 0, 200, 17, "&Change [ProductName]") g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]") g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]") maint.back("< Back", None, active=False) c=maint.next("Finish", "Cancel") # Change installation: Change progress dialog to "Change", then ask # for feature selection #c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1) #c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2) # Reinstall: Change progress dialog to "Repair", then invoke reinstall # Also set list of reinstalled features to "ALL" c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) # Uninstall: Change progress to "Remove", then invoke uninstall # Also set list of removed features to "ALL" c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) # Close dialog when maintenance action scheduled c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) #c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21) maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg") def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name, self.target_version) installer_name = os.path.join(self.dist_dir, base_name) return installer_name
unknown
codeparrot/codeparrot-clean
import {Component} from '@angular/core'; import {ReversePipe} from './reverse.pipe'; @Component({ selector: 'app-root', template: ` Reverse Machine: {{ word | reverse }} `, imports: [ReversePipe], }) export class App { word = 'You are a champion'; }
typescript
github
https://github.com/angular/angular
adev/src/content/tutorials/learn-angular/steps/24-create-a-pipe/answer/src/app/app.ts
import discord import json import re from discord.ext import commands from subprocess import call from sys import argv class Mod: """ Staff commands. """ def __init__(self, bot): self.bot = bot print('Addon "{}" loaded'.format(self.__class__.__name__)) async def add_restriction(self, member, rst): with open("data/restrictions.json", "r") as f: rsts = json.load(f) if member.id not in rsts: rsts[member.id] = [] if rst not in rsts[member.id]: rsts[member.id].append(rst) with open("data/restrictions.json", "w") as f: json.dump(rsts, f) async def remove_restriction(self, member, rst): with open("data/restrictions.json", "r") as f: rsts = json.load(f) if member.id not in rsts: rsts[member.id] = [] if rst in rsts[member.id]: rsts[member.id].remove(rst) with open("data/restrictions.json", "w") as f: json.dump(rsts, f) @commands.has_permissions(administrator=True) @commands.command() async def quit(self, *gamename): """Stops the bot.""" await self.bot.say("👋 Bye bye!") await self.bot.close() @commands.has_permissions(manage_server=True) @commands.command(hidden=True) async def pull(self, *gamename): """Pull new changes from GitHub and restart.""" await self.bot.say("Pulling changes...") call(['git', 'pull']) await self.bot.say("👋 Restarting bot!") await self.bot.close() @commands.has_permissions(manage_server=True) @commands.command(pass_context=True, hidden=True) async def userinfo(self, ctx, user): """Gets user info. SuperOP+.""" u = ctx.message.mentions[0] role = u.top_role.name if role == "@everyone": role = "@ everyone" await self.bot.say("name = {}\nid = {}\ndiscriminator = {}\navatar = {}\nbot = {}\navatar_url = {}\ndefault_avatar = {}\ndefault_avatar_url = <{}>\ncreated_at = {}\ndisplay_name = {}\njoined_at = {}\nstatus = {}\ngame = {}\ncolour = {}\ntop_role = {}\n".format(u.name, u.id, u.discriminator, u.avatar, u.bot, u.avatar_url, u.default_avatar, u.default_avatar_url, u.created_at, u.display_name, u.joined_at, u.status, u.game, u.colour, role)) @commands.has_permissions(administrator=True) @commands.command(pass_context=True, hidden=True) async def matchuser(self, ctx, *, rgx: str): """Match users by regex.""" author = ctx.message.author msg = "```\nmembers:\n" for m in self.bot.server.members: if bool(re.search(rgx, m.name, re.IGNORECASE)): msg += "{} - {}#{}\n".format(m.id, m.name, m.discriminator) msg += "```" await self.bot.send_message(author, msg) @commands.has_permissions(administrator=True) @commands.command(pass_context=True, hidden=True) async def multiban(self, ctx, *, members: str): """Multi-ban users.""" author = ctx.message.author msg = "```\nbanned:\n" for m in ctx.message.mentions: msg += "{} - {}#{}\n".format(m.id, m.name, m.discriminator) try: await self.bot.ban(m) except discord.error.NotFound: pass msg += "```" await self.bot.send_message(author, msg) @commands.has_permissions(administrator=True) @commands.command(pass_context=True, hidden=True) async def multibanre(self, ctx, *, rgx: str): """Multi-ban users by regex.""" author = ctx.message.author msg = "```\nbanned:\n" toban = [] # because "dictionary changed size during iteration" for m in self.bot.server.members: if bool(re.search(rgx, m.name, re.IGNORECASE)): msg += "{} - {}#{}\n".format(m.id, m.name, m.discriminator) toban.append(m) for m in toban: try: await self.bot.ban(m) except discord.error.NotFound: pass msg += "```" await self.bot.send_message(author, msg) @commands.has_permissions(manage_nicknames=True) @commands.command(pass_context=True, name="clear") async def purge(self, ctx, limit: int): """Clears a given number of messages. Staff only.""" try: await self.bot.purge_from(ctx.message.channel, limit=limit) msg = "🗑 **Cleared**: {} cleared {} messages in {}".format(ctx.message.author.mention, limit, ctx.message.channel.mention) await self.bot.send_message(self.bot.modlogs_channel, msg) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.has_permissions(manage_nicknames=True) @commands.command(pass_context=True, name="mute") async def mute(self, ctx, user, *, reason=""): """Mutes a user so they can't speak. Staff only.""" try: member = ctx.message.mentions[0] await self.add_restriction(member, "Muted") await self.bot.add_roles(member, self.bot.muted_role) msg_user = "You were muted!" if reason != "": msg_user += " The given reason is: " + reason try: await self.bot.send_message(member, msg_user) except discord.errors.Forbidden: pass # don't fail in case user has DMs disabled for this server, or blocked the bot await self.bot.say("{} can no longer speak.".format(member.mention)) msg = "🔇 **Muted**: {} muted {} | {}#{}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), self.bot.escape_name(member.discriminator)) if reason != "": msg += "\n✏️ __Reason__: " + reason else: msg += "\nPlease add an explanation below. In the future, it is recommended to use `.mute <user> [reason]` as the reason is automatically sent to the user." await self.bot.send_message(self.bot.modlogs_channel, msg) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.has_permissions(manage_nicknames=True) @commands.command(pass_context=True, name="unmute") async def unmute(self, ctx, user): """Unmutes a user so they can speak. Staff only.""" try: member = ctx.message.mentions[0] await self.remove_restriction(member, "Muted") await self.bot.remove_roles(member, self.bot.muted_role) await self.bot.say("{} can now speak again.".format(member.mention)) msg = "🔈 **Unmuted**: {} unmuted {} | {}#{}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), self.bot.escape_name(member.discriminator)) await self.bot.send_message(self.bot.modlogs_channel, msg) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.has_permissions(manage_nicknames=True) @commands.command(pass_context=True, name="noembed") async def noembed(self, ctx, user, *, reason=""): """Removes embed permissions from a user. Staff only.""" try: member = ctx.message.mentions[0] await self.add_restriction(member, "No-Embed") await self.bot.add_roles(member, self.bot.noembed_role) msg_user = "You lost embed and upload permissions!" if reason != "": msg_user += " The given reason is: " + reason try: await self.bot.send_message(member, msg_user) except discord.errors.Forbidden: pass # don't fail in case user has DMs disabled for this server, or blocked the bot await self.bot.say("{} can no longer embed links or attach files.".format(member.mention)) msg = "🚫 **Removed Embed**: {} removed embed from {} | {}#{}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), self.bot.escape_name(member.discriminator)) if reason != "": msg += "\n✏️ __Reason__: " + reason else: msg += "\nPlease add an explanation below. In the future, it is recommended to use `.noembed <user> [reason]` as the reason is automatically sent to the user." await self.bot.send_message(self.bot.modlogs_channel, msg) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.has_permissions(manage_nicknames=True) @commands.command(pass_context=True, name="embed") async def embed(self, ctx, user): """Restore embed permissios for a user. Staff only.""" try: member = ctx.message.mentions[0] await self.remove_restriction(member, "No-Embed") await self.bot.remove_roles(member, self.bot.noembed_role) await self.bot.say("{} can now embed links and attach files again.".format(member.mention)) msg = "⭕️ **Restored Embed**: {} restored embed to {} | {}#{}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), self.bot.escape_name(member.discriminator)) await self.bot.send_message(self.bot.modlogs_channel, msg) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.command(pass_context=True, name="takehelp") async def takehelp(self, ctx, user, *, reason=""): """Remove access to help-and-questions. Staff and Helpers only.""" author = ctx.message.author if (self.bot.helpers_role not in author.roles) and (self.bot.staff_role not in author.roles): msg = "{} You cannot use this command.".format(author.mention) await self.bot.say(msg) return try: member = ctx.message.mentions[0] await self.add_restriction(member, "No-Help") await self.bot.add_roles(member, self.bot.nohelp_role) msg_user = "You lost access to help channels!" if reason != "": msg_user += " The given reason is: " + reason try: await self.bot.send_message(member, msg_user) except discord.errors.Forbidden: pass # don't fail in case user has DMs disabled for this server, or blocked the bot await self.bot.say("{} can no longer access the help channels.".format(member.mention)) msg = "🚫 **Help access removed**: {} removed access to help channels from {} | {}#{}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), self.bot.escape_name(member.discriminator)) if reason != "": msg += "\n✏️ __Reason__: " + reason else: msg += "\nPlease add an explanation below. In the future, it is recommended to use `.takehelp <user> [reason]` as the reason is automatically sent to the user." await self.bot.send_message(self.bot.modlogs_channel, msg) await self.bot.send_message(self.bot.helpers_channel, msg) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.command(pass_context=True, name="givehelp") async def givehelp(self, ctx, user): """Restore access to help-and-questions. Staff and Helpers only.""" author = ctx.message.author if (self.bot.helpers_role not in author.roles) and (self.bot.staff_role not in author.roles): msg = "{} You cannot use this command.".format(author.mention) await self.bot.say(msg) return try: member = ctx.message.mentions[0] await self.remove_restriction(member, "No-Help") await self.bot.remove_roles(member, self.bot.nohelp_role) await self.bot.say("{} can access the help channels again.".format(member.mention)) msg = "⭕️ **Help access restored**: {} restored access to help channels to {} | {}#{}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), self.bot.escape_name(member.discriminator)) await self.bot.send_message(self.bot.modlogs_channel, msg) await self.bot.send_message(self.bot.helpers_channel, msg) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.has_permissions(manage_nicknames=True) @commands.command(pass_context=True, name="probate") async def probate(self, ctx, user, *, reason=""): """Probate a user. Staff only.""" try: member = ctx.message.mentions[0] await self.add_restriction(member, "Probation") await self.bot.add_roles(member, self.bot.probation_role) msg_user = "You are under probation!" if reason != "": msg_user += " The given reason is: " + reason try: await self.bot.send_message(member, msg_user) except discord.errors.Forbidden: pass # don't fail in case user has DMs disabled for this server, or blocked the bot await self.bot.say("{} is now in probation.".format(member.mention)) msg = "🚫 **Probated**: {} probated {} | {}#{}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), self.bot.escape_name(member.discriminator)) if reason != "": msg += "\n✏️ __Reason__: " + reason else: msg += "\nPlease add an explanation below. In the future, it is recommended to use `.probate <user> [reason]` as the reason is automatically sent to the user." await self.bot.send_message(self.bot.modlogs_channel, msg) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.has_permissions(manage_nicknames=True) @commands.command(pass_context=True, name="unprobate") async def unprobate(self, ctx, user): """Unprobate a user. Staff only.""" try: member = ctx.message.mentions[0] await self.remove_restriction(member, "Probation") await self.bot.remove_roles(member, self.bot.probation_role) await self.bot.say("{} is out of probation.".format(member.mention)) msg = "⭕️ **Un-probated**: {} un-probated {} | {}#{}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), self.bot.escape_name(member.discriminator)) await self.bot.send_message(self.bot.modlogs_channel, msg) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.has_permissions(ban_members=True) @commands.command(pass_context=True) async def playing(self, ctx, *gamename): """Sets playing message. Staff only.""" try: await self.bot.change_presence(game=discord.Game(name='{}'.format(" ".join(gamename)))) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.has_permissions(ban_members=True) @commands.command(pass_context=True) async def status(self, ctx, status): """Sets status. Staff only.""" try: if status == "online": await self.bot.change_presence(status=discord.Status.online) elif status == "offline": await self.bot.change_presence(status=discord.Status.offline) elif status == "idle": await self.bot.change_presence(status=discord.Status.idle) elif status == "dnd": await self.bot.change_presence(status=discord.Status.dnd) elif status == "invisible": await self.bot.change_presence(status=discord.Status.invisible) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") @commands.has_permissions(ban_members=True) @commands.command(pass_context=True, hidden=True) async def username(self, ctx, *, username): """Sets bot name. Staff only.""" try: await self.bot.edit_profile(username=('{}'.format(username))) except discord.errors.Forbidden: await self.bot.say("💢 I don't have permission to do this.") def setup(bot): bot.add_cog(Mod(bot))
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- ############################################################################### # # Inbox # Retrieves a list of messages in a specified user's inbox. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo 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 temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class Inbox(Choreography): def __init__(self, temboo_session): """ Create a new instance of the Inbox Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. """ super(Inbox, self).__init__(temboo_session, '/Library/Facebook/Reading/Inbox') def new_input_set(self): return InboxInputSet() def _make_result_set(self, result, path): return InboxResultSet(result, path) def _make_execution(self, session, exec_id, path): return InboxChoreographyExecution(session, exec_id, path) class InboxInputSet(InputSet): """ An InputSet with methods appropriate for specifying the inputs to the Inbox Choreo. The InputSet object is used to specify input parameters when executing this Choreo. """ def set_AccessToken(self, value): """ Set the value of the AccessToken input for this Choreo. ((required, string) The access token retrieved from the final step of the OAuth process.) """ super(InboxInputSet, self)._set_input('AccessToken', value) def set_Fields(self, value): """ Set the value of the Fields input for this Choreo. ((optional, string) A comma separated list of fields to return (i.e. id,name).) """ super(InboxInputSet, self)._set_input('Fields', value) def set_Limit(self, value): """ Set the value of the Limit input for this Choreo. ((optional, integer) Used to page through results. Limits the number of records returned in the response.) """ super(InboxInputSet, self)._set_input('Limit', value) def set_Offset(self, value): """ Set the value of the Offset input for this Choreo. ((optional, integer) Used to page through results. Returns results starting from the specified number.) """ super(InboxInputSet, self)._set_input('Offset', value) def set_ProfileID(self, value): """ Set the value of the ProfileID input for this Choreo. ((optional, string) The id of the profile to retrieve messages for. Defaults to "me" indicating the authenticated user.) """ super(InboxInputSet, self)._set_input('ProfileID', value) def set_ResponseFormat(self, value): """ Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Can be set to xml or json. Defaults to json.) """ super(InboxInputSet, self)._set_input('ResponseFormat', value) class InboxResultSet(ResultSet): """ A ResultSet with methods tailored to the values returned by the Inbox Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Response(self): """ Retrieve the value for the "Response" output from this Choreo execution. (The response from Facebook. Corresponds to the ResponseFormat input. Defaults to JSON.) """ return self._output.get('Response', None) class InboxChoreographyExecution(ChoreographyExecution): def _make_result_set(self, response, path): return InboxResultSet(response, path)
unknown
codeparrot/codeparrot-clean
{ "include": [ "**/*.ts", "**/*.tsx", "**/.server/**/*.ts", "**/.server/**/*.tsx", "**/.client/**/*.ts", "**/.client/**/*.tsx", ".react-router/types/**/*" ], "compilerOptions": { "lib": ["DOM", "DOM.Iterable", "ES2022"], "types": ["@react-router/node", "vite/client"], "verbatimModuleSyntax": true, "esModuleInterop": true, "jsx": "react-jsx", "module": "ESNext", "moduleResolution": "Bundler", "resolveJsonModule": true, "target": "ES2022", "strict": true, "allowJs": true, "skipLibCheck": true, "baseUrl": ".", "paths": { "~/*": ["./app/*"] }, "noEmit": true, "rootDirs": [".", "./.react-router/types"], "plugins": [{ "name": "@react-router/dev" }] } }
json
github
https://github.com/remix-run/react-router
packages/create-react-router/__tests__/fixtures/basic/tsconfig.json
import {useEffect} from 'react'; function Component() { let local; const reassignLocal = newValue => { local = newValue; }; const onMount = newValue => { reassignLocal('hello'); if (local === newValue) { // Without React Compiler, `reassignLocal` is freshly created // on each render, capturing a binding to the latest `local`, // such that invoking reassignLocal will reassign the same // binding that we are observing in the if condition, and // we reach this branch console.log('`local` was updated!'); } else { // With React Compiler enabled, `reassignLocal` is only created // once, capturing a binding to `local` in that render pass. // Therefore, calling `reassignLocal` will reassign the wrong // version of `local`, and not update the binding we are checking // in the if condition. // // To protect against this, we disallow reassigning locals from // functions that escape throw new Error('`local` not updated!'); } }; useEffect(() => { onMount(); }, [onMount]); return 'ok'; }
javascript
github
https://github.com/facebook/react
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-effect.js
#!/usr/bin/python # BSD LICENSE # # Copyright(c) 2010-2014 Intel Corporation. All rights reserved. # 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 Intel Corporation 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. # Script that uses either test app or qemu controlled by python-pexpect import sys, autotest_data, autotest_runner def usage(): print"Usage: autotest.py [test app|test iso image]", print "[target] [whitelist|-blacklist]" if len(sys.argv) < 3: usage() sys.exit(1) target = sys.argv[2] test_whitelist=None test_blacklist=None # get blacklist/whitelist if len(sys.argv) > 3: testlist = sys.argv[3].split(',') testlist = [test.lower() for test in testlist] if testlist[0].startswith('-'): testlist[0] = testlist[0].lstrip('-') test_blacklist = testlist else: test_whitelist = testlist # adjust test command line if "baremetal" in target: cmdline = "qemu-system-x86_64 -cdrom %s.iso -boot d " % (sys.argv[1]) cmdline += "-m 2000 -smp 4 -nographic -net nic,model=e1000" platform = "QEMU x86_64" else: cmdline = "%s -c f -n 4"%(sys.argv[1]) print cmdline runner = autotest_runner.AutotestRunner(cmdline, target, test_blacklist, test_whitelist) for test_group in autotest_data.parallel_test_group_list: runner.add_parallel_test_group(test_group) for test_group in autotest_data.non_parallel_test_group_list: runner.add_non_parallel_test_group(test_group) runner.run_all_tests()
unknown
codeparrot/codeparrot-clean
{ "name": "my-vend/my-app", "license": "MIT", "repositories": { } }
json
github
https://github.com/composer/composer
tests/Composer/Test/Config/Fixtures/composer-repositories.json
from django.contrib.auth.models import User from django.test import TestCase, RequestFactory from django.views.generic import TemplateView from blog.mixins import ResourceTypesMixin from blog.models import ResourceType from community.models import Community from users.models import SystersUser class ResourceTypesMixinTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user(username='foo', password='foobar') self.systers_user = SystersUser.objects.get() self.community = Community.objects.create(name="Foo", slug="foo", order=1, admin=self.systers_user) def test_get_context_data_empty(self): """Test mixin and no resource type objects""" class DummyView(ResourceTypesMixin, TemplateView): template_name = "dummy" request = self.factory.get("/dummy/") view = DummyView.as_view() response = view(request) context = response.context_data self.assertSequenceEqual(context.get('resource_types'), []) def test_get_context_data(self): """Test mixin with 2 resource types""" class DummyView(ResourceTypesMixin, TemplateView): template_name = "dummy" resource_type1 = ResourceType.objects.create(name="foo") resource_type2 = ResourceType.objects.create(name="bar") request = self.factory.get("/dummy/") view = DummyView.as_view() response = view(request) context = response.context_data self.assertSequenceEqual(context.get('resource_types'), [resource_type1, resource_type2])
unknown
codeparrot/codeparrot-clean
"""Tests covering the Programs listing on the Studio home.""" import json from django.conf import settings from django.core.urlresolvers import reverse import httpretty import mock from edx_oauth2_provider.tests.factories import ClientFactory from provider.constants import CONFIDENTIAL from openedx.core.djangoapps.programs.models import ProgramsApiConfig from openedx.core.djangoapps.programs.tests.mixins import ProgramsApiConfigMixin, ProgramsDataMixin from openedx.core.djangolib.markup import Text from student.tests.factories import UserFactory from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase class TestProgramListing(ProgramsApiConfigMixin, ProgramsDataMixin, SharedModuleStoreTestCase): """Verify Program listing behavior.""" def setUp(self): super(TestProgramListing, self).setUp() ClientFactory(name=ProgramsApiConfig.OAUTH2_CLIENT_NAME, client_type=CONFIDENTIAL) self.staff = UserFactory(is_staff=True) self.client.login(username=self.staff.username, password='test') self.studio_home = reverse('home') @httpretty.activate def test_programs_config_disabled(self): """Verify that the programs tab and creation button aren't rendered when config is disabled.""" self.create_programs_config(enable_studio_tab=False) self.mock_programs_api() response = self.client.get(self.studio_home) self.assertNotIn("You haven't created any programs yet.", response.content) for program_name in self.PROGRAM_NAMES: self.assertNotIn(program_name, response.content) @httpretty.activate def test_programs_requires_staff(self): """ Verify that the programs tab and creation button aren't rendered unless the user has global staff permissions. """ student = UserFactory(is_staff=False) self.client.login(username=student.username, password='test') self.create_programs_config() self.mock_programs_api() response = self.client.get(self.studio_home) self.assertNotIn("You haven't created any programs yet.", response.content) @httpretty.activate def test_programs_displayed(self): """Verify that the programs tab and creation button can be rendered when config is enabled.""" # When no data is provided, expect creation prompt. self.create_programs_config() self.mock_programs_api(data={'results': []}) response = self.client.get(self.studio_home) self.assertIn(Text("You haven't created any programs yet."), response.content.decode('utf-8')) # When data is provided, expect a program listing. self.mock_programs_api() response = self.client.get(self.studio_home) for program_name in self.PROGRAM_NAMES: self.assertIn(program_name, response.content) class TestProgramAuthoringView(ProgramsApiConfigMixin, SharedModuleStoreTestCase): """Verify the behavior of the program authoring app's host view.""" def setUp(self): super(TestProgramAuthoringView, self).setUp() self.staff = UserFactory(is_staff=True) self.programs_path = reverse('programs') def _assert_status(self, status_code): """Verify the status code returned by the Program authoring view.""" response = self.client.get(self.programs_path) self.assertEquals(response.status_code, status_code) return response def test_authoring_login_required(self): """Verify that accessing the view requires the user to be authenticated.""" response = self.client.get(self.programs_path) self.assertRedirects( response, '{login_url}?next={programs}'.format( login_url=settings.LOGIN_URL, programs=self.programs_path ) ) def test_authoring_header(self): """Verify that the header contains the expected text.""" self.client.login(username=self.staff.username, password='test') self.create_programs_config() response = self._assert_status(200) self.assertIn("Program Administration", response.content) def test_authoring_access(self): """ Verify that a 404 is returned if Programs authoring is disabled, or the user does not have global staff permissions. """ self.client.login(username=self.staff.username, password='test') self._assert_status(404) # Enable Programs authoring interface self.create_programs_config() student = UserFactory(is_staff=False) self.client.login(username=student.username, password='test') self._assert_status(404) class TestProgramsIdTokenView(ProgramsApiConfigMixin, SharedModuleStoreTestCase): """Tests for the programs id_token endpoint.""" def setUp(self): super(TestProgramsIdTokenView, self).setUp() self.user = UserFactory() self.client.login(username=self.user.username, password='test') self.path = reverse('programs_id_token') def test_config_disabled(self): """Ensure the endpoint returns 404 when Programs authoring is disabled.""" self.create_programs_config(enable_studio_tab=False) response = self.client.get(self.path) self.assertEqual(response.status_code, 404) def test_not_logged_in(self): """Ensure the endpoint denies access to unauthenticated users.""" self.create_programs_config() self.client.logout() response = self.client.get(self.path) self.assertEqual(response.status_code, 302) self.assertIn(settings.LOGIN_URL, response['Location']) @mock.patch('cms.djangoapps.contentstore.views.program.JwtBuilder.build_token') def test_config_enabled(self, mock_build_token): """ Ensure the endpoint responds with a valid JSON payload when authoring is enabled. """ mock_build_token.return_value = 'test-id-token' ClientFactory(name=ProgramsApiConfig.OAUTH2_CLIENT_NAME, client_type=CONFIDENTIAL) self.create_programs_config() response = self.client.get(self.path) self.assertEqual(response.status_code, 200) payload = json.loads(response.content) self.assertEqual(payload, {'id_token': 'test-id-token'})
unknown
codeparrot/codeparrot-clean
"""Tests for sync/async middleware composition with wrap_tool_call and awrap_tool_call. These tests verify the desired behavior: 1. If middleware defines both sync and async -> use both on respective paths 2. If middleware defines only sync -> use on sync path, raise NotImplementedError on async path 3. If middleware defines only async -> use on async path, raise NotImplementedError on sync path """ from collections.abc import Awaitable, Callable from typing import Any import pytest from langchain_core.messages import HumanMessage, ToolCall, ToolMessage from langchain_core.tools import tool from langgraph.checkpoint.memory import InMemorySaver from langgraph.types import Command from langchain.agents.factory import create_agent from langchain.agents.middleware.types import AgentMiddleware, ToolCallRequest, wrap_tool_call from tests.unit_tests.agents.model import FakeToolCallingModel @tool def search(query: str) -> str: """Search for information.""" return f"Results for: {query}" @tool def calculator(expression: str) -> str: """Calculate an expression.""" return f"Calculated: {expression}" class TestSyncAsyncMiddlewareComposition: """Test sync/async middleware composition behavior.""" def test_sync_only_middleware_works_on_sync_path(self) -> None: """Middleware with only sync wrap_tool_call works on sync path.""" call_log = [] class SyncOnlyMiddleware(AgentMiddleware): def wrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]], ) -> ToolMessage | Command[Any]: call_log.append("sync_called") return handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[SyncOnlyMiddleware()], checkpointer=InMemorySaver(), ) result = agent.invoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test"}}, ) assert "sync_called" in call_log tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)] assert len(tool_messages) == 1 assert "Results for: test" in tool_messages[0].content async def test_sync_only_middleware_raises_on_async_path(self) -> None: """Middleware with only sync wrap_tool_call raises NotImplementedError on async path.""" class SyncOnlyMiddleware(AgentMiddleware): def wrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]], ) -> ToolMessage | Command[Any]: return handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[SyncOnlyMiddleware()], checkpointer=InMemorySaver(), ) # Should raise NotImplementedError because SyncOnlyMiddleware doesn't support async path with pytest.raises(NotImplementedError): await agent.ainvoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test"}}, ) async def test_async_only_middleware_works_on_async_path(self) -> None: """Middleware with only async awrap_tool_call works on async path.""" call_log = [] class AsyncOnlyMiddleware(AgentMiddleware): async def awrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]], ) -> ToolMessage | Command[Any]: call_log.append("async_called") return await handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[AsyncOnlyMiddleware()], checkpointer=InMemorySaver(), ) result = await agent.ainvoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test"}}, ) assert "async_called" in call_log tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)] assert len(tool_messages) == 1 assert "Results for: test" in tool_messages[0].content def test_async_only_middleware_raises_on_sync_path(self) -> None: """Middleware with only async awrap_tool_call raises NotImplementedError on sync path.""" class AsyncOnlyMiddleware(AgentMiddleware): async def awrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]], ) -> ToolMessage | Command[Any]: return await handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[AsyncOnlyMiddleware()], checkpointer=InMemorySaver(), ) with pytest.raises(NotImplementedError): agent.invoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test"}}, ) def test_both_sync_and_async_middleware_uses_appropriate_path(self) -> None: """Middleware with both sync and async uses correct implementation per path.""" call_log = [] class BothSyncAsyncMiddleware(AgentMiddleware): def wrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]], ) -> ToolMessage | Command[Any]: call_log.append("sync_called") return handler(request) async def awrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]], ) -> ToolMessage | Command[Any]: call_log.append("async_called") return await handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[BothSyncAsyncMiddleware()], checkpointer=InMemorySaver(), ) # Sync path call_log.clear() agent.invoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test1"}}, ) assert "sync_called" in call_log assert "async_called" not in call_log async def test_both_sync_and_async_middleware_uses_appropriate_path_async( self, ) -> None: """Middleware with both sync and async uses correct implementation per path (async).""" call_log = [] class BothSyncAsyncMiddleware(AgentMiddleware): def wrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]], ) -> ToolMessage | Command[Any]: call_log.append("sync_called") return handler(request) async def awrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]], ) -> ToolMessage | Command[Any]: call_log.append("async_called") return await handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[BothSyncAsyncMiddleware()], checkpointer=InMemorySaver(), ) # Async path call_log.clear() await agent.ainvoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test2"}}, ) assert "async_called" in call_log assert "sync_called" not in call_log async def test_mixed_middleware_composition_async_path_fails_with_sync_only( self, ) -> None: """Multiple middleware on async path fails if any are sync-only.""" class SyncOnlyMiddleware(AgentMiddleware): name = "SyncOnly" def wrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]], ) -> ToolMessage | Command[Any]: return handler(request) class AsyncOnlyMiddleware(AgentMiddleware): name = "AsyncOnly" async def awrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]], ) -> ToolMessage | Command[Any]: return await handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[ SyncOnlyMiddleware(), AsyncOnlyMiddleware(), ], checkpointer=InMemorySaver(), ) # Should raise NotImplementedError because SyncOnlyMiddleware can't run on async path with pytest.raises(NotImplementedError): await agent.ainvoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test"}}, ) def test_mixed_middleware_composition_sync_path_with_async_only_fails(self) -> None: """Multiple middleware on sync path fails if any are async-only.""" class SyncOnlyMiddleware(AgentMiddleware): name = "SyncOnly" def wrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]], ) -> ToolMessage | Command[Any]: return handler(request) class AsyncOnlyMiddleware(AgentMiddleware): name = "AsyncOnly" async def awrap_tool_call( self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]], ) -> ToolMessage | Command[Any]: return await handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[ SyncOnlyMiddleware(), AsyncOnlyMiddleware(), # This will break sync path ], checkpointer=InMemorySaver(), ) # Should raise NotImplementedError because AsyncOnlyMiddleware can't run on sync path with pytest.raises(NotImplementedError): agent.invoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test"}}, ) def test_decorator_sync_only_works_both_paths(self) -> None: """Decorator-created sync-only middleware works on both paths.""" call_log = [] @wrap_tool_call def my_wrapper( request: ToolCallRequest, handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]], ) -> ToolMessage | Command[Any]: call_log.append("decorator_sync") return handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[my_wrapper], checkpointer=InMemorySaver(), ) # Sync path call_log.clear() result = agent.invoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test1"}}, ) assert "decorator_sync" in call_log assert len([m for m in result["messages"] if isinstance(m, ToolMessage)]) == 1 async def test_decorator_sync_only_raises_on_async_path(self) -> None: """Decorator-created sync-only middleware raises on async path.""" call_log = [] @wrap_tool_call def my_wrapper( request: ToolCallRequest, handler: Callable[[ToolCallRequest], ToolMessage | Command[Any]], ) -> ToolMessage | Command[Any]: call_log.append("decorator_sync") return handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[my_wrapper], checkpointer=InMemorySaver(), ) # Should raise NotImplementedError because sync-only decorator doesn't support async path with pytest.raises(NotImplementedError): await agent.ainvoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test2"}}, ) async def test_decorator_async_only_works_async_path(self) -> None: """Decorator-created async-only middleware works on async path.""" call_log = [] @wrap_tool_call async def my_async_wrapper( request: ToolCallRequest, handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]], ) -> ToolMessage | Command[Any]: call_log.append("decorator_async") return await handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[my_async_wrapper], checkpointer=InMemorySaver(), ) result = await agent.ainvoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test"}}, ) assert "decorator_async" in call_log assert len([m for m in result["messages"] if isinstance(m, ToolMessage)]) == 1 def test_decorator_async_only_raises_on_sync_path(self) -> None: """Decorator-created async-only middleware raises on sync path.""" @wrap_tool_call async def my_async_wrapper( request: ToolCallRequest, handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]], ) -> ToolMessage | Command[Any]: return await handler(request) model = FakeToolCallingModel( tool_calls=[ [ToolCall(name="search", args={"query": "test"}, id="1")], [], ] ) agent = create_agent( model=model, tools=[search], middleware=[my_async_wrapper], checkpointer=InMemorySaver(), ) with pytest.raises(NotImplementedError): agent.invoke( {"messages": [HumanMessage("Search")]}, {"configurable": {"thread_id": "test"}}, )
python
github
https://github.com/langchain-ai/langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_sync_async_wrappers.py
"""Provides the Module and Type base classes that user code inherits from.""" __all__ = ["Module", "Type", "member"] from framer import struct, template from framer.function import Function, Method from framer.member import member from framer.slots import * from framer.util import cstring, unindent from types import FunctionType def sortitems(dict): L = dict.items() L.sort() return L # The Module and Type classes are implemented using metaclasses, # because most of the methods are class methods. It is easier to use # metaclasses than the cumbersome classmethod() builtin. They have # class methods because they are exposed to user code as base classes. class BaseMetaclass(type): """Shared infrastructure for generating modules and types.""" # just methoddef so far def dump_methoddef(self, f, functions, vars): def p(templ, vars=vars): # helper function to generate output print >> f, templ % vars if not functions: return p(template.methoddef_start) for name, func in sortitems(functions): if func.__doc__: p(template.methoddef_def_doc, func.vars) else: p(template.methoddef_def, func.vars) p(template.methoddef_end) class ModuleMetaclass(BaseMetaclass): """Provides methods for Module class.""" def gen(self): self.analyze() self.initvars() f = open(self.__filename, "w") self.dump(f) f.close() def analyze(self): self.name = getattr(self, "abbrev", self.__name__) self.__functions = {} self.__types = {} self.__members = False for name, obj in self.__dict__.iteritems(): if isinstance(obj, FunctionType): self.__functions[name] = Function(obj, self) elif isinstance(obj, TypeMetaclass): obj._TypeMetaclass__module = self.name obj.analyze() self.__types[name] = obj if obj.has_members(): self.__members = True def initvars(self): v = self.__vars = {} filename = getattr(self, "__file__", None) if filename is None: filename = self.__name__ + "module.c" self.__filename = v["FileName"] = filename name = v["ModuleName"] = self.__name__ v["MethodDefName"] = "%s_methods" % name v["ModuleDocstring"] = cstring(unindent(self.__doc__)) def dump(self, f): def p(templ, vars=self.__vars): # helper function to generate output print >> f, templ % vars p(template.module_start) if self.__members: p(template.member_include) print >> f if self.__doc__: p(template.module_doc) for name, type in sortitems(self.__types): type.dump(f) for name, func in sortitems(self.__functions): func.dump(f) self.dump_methoddef(f, self.__functions, self.__vars) p(template.module_init_start) for name, type in sortitems(self.__types): type.dump_init(f) p("}") class Module: __metaclass__ = ModuleMetaclass class TypeMetaclass(BaseMetaclass): def dump(self, f): self.initvars() # defined after initvars() so that __vars is defined def p(templ, vars=self.__vars): print >> f, templ % vars if self.struct is not None: print >> f, unindent(self.struct, False) if self.__doc__: p(template.docstring) for name, func in sortitems(self.__methods): func.dump(f) self.dump_methoddef(f, self.__methods, self.__vars) self.dump_memberdef(f) self.dump_slots(f) def has_members(self): if self.__members: return True else: return False def analyze(self): # called by ModuleMetaclass analyze() self.name = getattr(self, "abbrev", self.__name__) src = getattr(self, "struct", None) if src is not None: self.__struct = struct.parse(src) else: self.__struct = None self.__methods = {} self.__members = {} for cls in self.__mro__: for k, v in cls.__dict__.iteritems(): if isinstance(v, FunctionType): self.__methods[k] = Method(v, self) if isinstance(v, member): self.__members[k] = v assert self.__struct is not None v.register(k, self.__struct) self.analyze_slots() def analyze_slots(self): self.__slots = {} for s in Slots: if s.special is not None: meth = self.__methods.get(s.special) if meth is not None: self.__slots[s] = meth self.__slots[TP_NAME] = '"%s.%s"' % (self.__module, self.__name__) if self.__doc__: self.__slots[TP_DOC] = "%s_doc" % self.name if self.__struct is not None: self.__slots[TP_BASICSIZE] = "sizeof(%s)" % self.__struct.name self.__slots[TP_DEALLOC] = "%s_dealloc" % self.name if self.__methods: self.__slots[TP_METHODS] = "%s_methods" % self.name if self.__members: self.__slots[TP_MEMBERS] = "%s_members" % self.name def initvars(self): v = self.__vars = {} v["TypeName"] = self.__name__ v["CTypeName"] = "Py%s_Type" % self.__name__ v["MethodDefName"] = self.__slots[TP_METHODS] if self.__doc__: v["DocstringVar"] = self.__slots[TP_DOC] v["Docstring"] = cstring(unindent(self.__doc__)) if self.__struct is not None: v["StructName"] = self.__struct.name if self.__members: v["MemberDefName"] = self.__slots[TP_MEMBERS] def dump_memberdef(self, f): def p(templ, vars=self.__vars): print >> f, templ % vars if not self.__members: return p(template.memberdef_start) for name, slot in sortitems(self.__members): slot.dump(f) p(template.memberdef_end) def dump_slots(self, f): def p(templ, vars=self.__vars): print >> f, templ % vars if self.struct: p(template.dealloc_func, {"name" : self.__slots[TP_DEALLOC]}) p(template.type_struct_start) for s in Slots[:-5]: # XXX val = self.__slots.get(s, s.default) ntabs = 4 - (4 + len(val)) / 8 line = " %s,%s/* %s */" % (val, "\t" * ntabs, s.name) print >> f, line p(template.type_struct_end) def dump_init(self, f): def p(templ): print >> f, templ % self.__vars p(template.type_init_type) p(template.module_add_type) class Type: __metaclass__ = TypeMetaclass
unknown
codeparrot/codeparrot-clean
#---------------------------------------------------------------------- # Copyright (c) 2011-2016 Raytheon BBN Technologies # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and/or hardware specification (the "Work") to # deal in the Work without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Work, and to permit persons to whom the Work # is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Work. # # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS # IN THE WORK. #---------------------------------------------------------------------- import tools.pluginmanager as pm from chapi.Clearinghouse import CHv1Handler, CHv1DelegateBase from chapi.MemberAuthority import MAv1Handler, MAv1DelegateBase from chapi.SliceAuthority import SAv1Handler, SAv1DelegateBase from chapi.GuardBase import GuardBase from chapi.Parameters import set_parameters, configure_logging def setup(): # load all the parameter values into the config database set_parameters() # Configure logging configure_logging() # register xmlrpc endpoint xmlrpc = pm.getService('xmlrpc') # Invoke the CH, SA and MA and set them with default/dummy # guards and delegates # Subsequent plugins should replace these with proper guard and delegate # implementations ch_handler = CHv1Handler() ch_delegate = CHv1DelegateBase() ch_guard = GuardBase() ch_handler.setDelegate(ch_delegate) ch_handler.setGuard(ch_guard) pm.registerService('chv1handler', ch_handler) xmlrpc.registerXMLRPC('ch1', ch_handler, '/CH') # name, handlerObj, endpoint sa_handler = SAv1Handler() sa_delegate = SAv1DelegateBase() sa_guard = GuardBase() sa_handler.setDelegate(sa_delegate) sa_handler.setGuard(sa_guard) pm.registerService('sav1handler', sa_handler) xmlrpc.registerXMLRPC('sa1', sa_handler, '/SA') # name, handlerObj, endpoint ma_handler = MAv1Handler() ma_delegate = MAv1DelegateBase() ma_guard = GuardBase() ma_handler.setDelegate(ma_delegate) ma_handler.setGuard(ma_guard) pm.registerService('mav1handler', ma_handler) xmlrpc.registerXMLRPC('ma1', ma_handler, '/MA') # name, handlerObj, endpoint
unknown
codeparrot/codeparrot-clean
/** @import { TaggedTemplateExpression } from 'estree' */ /** @import { Context } from '../types' */ import { is_pure } from './shared/utils.js'; /** * @param {TaggedTemplateExpression} node * @param {Context} context */ export function TaggedTemplateExpression(node, context) { if (context.state.expression && !is_pure(node.tag, context)) { context.state.expression.has_call = true; context.state.expression.has_state = true; } context.next(); }
javascript
github
https://github.com/sveltejs/svelte
packages/svelte/src/compiler/phases/2-analyze/visitors/TaggedTemplateExpression.js
#!/usr/bin/env python # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import calendar import email.utils import httparchive import unittest def create_request(headers): return httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/', None, headers) def create_response(headers): return httparchive.ArchivedHttpResponse( 11, 200, 'OK', headers, '') class HttpArchiveTest(unittest.TestCase): REQUEST_HEADERS = {} REQUEST = create_request(REQUEST_HEADERS) # Used for if-(un)modified-since checks DATE_PAST = 'Wed, 13 Jul 2011 03:58:08 GMT' DATE_PRESENT = 'Wed, 20 Jul 2011 04:58:08 GMT' DATE_FUTURE = 'Wed, 27 Jul 2011 05:58:08 GMT' DATE_INVALID = 'This is an invalid date!!' # etag values ETAG_VALID = 'etag' ETAG_INVALID = 'This is an invalid etag value!!' RESPONSE_HEADERS = [('last-modified', DATE_PRESENT), ('etag', ETAG_VALID)] RESPONSE = create_response(RESPONSE_HEADERS) def setUp(self): self.archive = httparchive.HttpArchive() self.archive[self.REQUEST] = self.RESPONSE # Also add an identical POST request for testing request = httparchive.ArchivedHttpRequest( 'POST', 'www.test.com', '/', None, self.REQUEST_HEADERS) self.archive[request] = self.RESPONSE def tearDown(self): pass def test_init(self): archive = httparchive.HttpArchive() self.assertEqual(len(archive), 0) def test_request__TrimHeaders(self): request = httparchive.ArchivedHttpRequest header1 = {'accept-encoding': 'gzip,deflate'} self.assertEqual(request._TrimHeaders(header1), [(k, v) for k, v in header1.items()]) header2 = {'referer': 'www.google.com'} self.assertEqual(request._TrimHeaders(header2), []) header3 = {'referer': 'www.google.com', 'cookie': 'cookie_monster!', 'hello': 'world'} self.assertEqual(request._TrimHeaders(header3), [('hello', 'world')]) # Tests that spaces and trailing comma get stripped. header4 = {'accept-encoding': 'gzip, deflate,, '} self.assertEqual(request._TrimHeaders(header4), [('accept-encoding', 'gzip,deflate')]) # Tests that 'lzma' gets stripped. header5 = {'accept-encoding': 'gzip, deflate, lzma'} self.assertEqual(request._TrimHeaders(header5), [('accept-encoding', 'gzip,deflate')]) # Tests that x-client-data gets stripped. header6 = {'x-client-data': 'testdata'} self.assertEqual(request._TrimHeaders(header6), []) def test_matches(self): headers = {} request1 = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/index.html?hello=world', None, headers) request2 = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/index.html?foo=bar', None, headers) self.assert_(not request1.matches( request2.command, request2.host, request2.full_path, use_query=True)) self.assert_(request1.matches( request2.command, request2.host, request2.full_path, use_query=False)) self.assert_(request1.matches( request2.command, request2.host, None, use_query=True)) self.assert_(request1.matches( request2.command, None, request2.full_path, use_query=False)) empty_request = httparchive.ArchivedHttpRequest( None, None, None, None, headers) self.assert_(not empty_request.matches( request2.command, request2.host, None, use_query=True)) self.assert_(not empty_request.matches( request2.command, None, request2.full_path, use_query=False)) def setup_find_closest_request(self): headers = {} request1 = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/a?hello=world', None, headers) request2 = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/a?foo=bar', None, headers) request3 = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/b?hello=world', None, headers) request4 = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/c?hello=world', None, headers) archive = httparchive.HttpArchive() # Add requests 2 and 3 and find closest match with request1 archive[request2] = self.RESPONSE archive[request3] = self.RESPONSE return archive, request1, request2, request3, request4 def test_find_closest_request(self): archive, request1, request2, request3, request4 = ( self.setup_find_closest_request()) # Always favor requests with same paths, even if use_path=False. self.assertEqual( request2, archive.find_closest_request(request1, use_path=False)) # If we match strictly on path, request2 is the only match self.assertEqual( request2, archive.find_closest_request(request1, use_path=True)) # request4 can be matched with request3, if use_path=False self.assertEqual( request3, archive.find_closest_request(request4, use_path=False)) # ...but None, if use_path=True self.assertEqual( None, archive.find_closest_request(request4, use_path=True)) def test_find_closest_request_delete_simple(self): archive, request1, request2, request3, request4 = ( self.setup_find_closest_request()) del archive[request3] self.assertEqual( request2, archive.find_closest_request(request1, use_path=False)) self.assertEqual( request2, archive.find_closest_request(request1, use_path=True)) def test_find_closest_request_delete_complex(self): archive, request1, request2, request3, request4 = ( self.setup_find_closest_request()) del archive[request2] self.assertEqual( request3, archive.find_closest_request(request1, use_path=False)) self.assertEqual( None, archive.find_closest_request(request1, use_path=True)) def test_find_closest_request_timestamp(self): headers = {} request1 = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/index.html?time=100000000&important=true', None, headers) request2 = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/index.html?time=99999999&important=true', None, headers) request3 = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/index.html?time=10000000&important=false', None, headers) archive = httparchive.HttpArchive() # Add requests 2 and 3 and find closest match with request1 archive[request2] = self.RESPONSE archive[request3] = self.RESPONSE # Although request3 is lexicographically closer, request2 is semantically # more similar. self.assertEqual( request2, archive.find_closest_request(request1, use_path=True)) def test_get_cmp_seq(self): # The order of key-value pairs in query and header respectively should not # matter. headers = {'k2': 'v2', 'k1': 'v1'} request = httparchive.ArchivedHttpRequest( 'GET', 'www.test.com', '/a?c=d&a=b;e=f', None, headers) self.assertEqual([('a', 'b'), ('c', 'd'), ('e', 'f'), ('k1', 'v1'), ('k2', 'v2')], request._GetCmpSeq('c=d&a=b;e=f')) def test_get_simple(self): request = self.REQUEST response = self.RESPONSE archive = self.archive self.assertEqual(archive.get(request), response) false_request_headers = {'foo': 'bar'} false_request = create_request(false_request_headers) self.assertEqual(archive.get(false_request, default=None), None) def test_get_modified_headers(self): request = self.REQUEST response = self.RESPONSE archive = self.archive not_modified_response = httparchive.create_response(304) # Fail check and return response again request_headers = {'if-modified-since': self.DATE_PAST} request = create_request(request_headers) self.assertEqual(archive.get(request), response) # Succeed check and return 304 Not Modified request_headers = {'if-modified-since': self.DATE_FUTURE} request = create_request(request_headers) self.assertEqual(archive.get(request), not_modified_response) # Succeed check and return 304 Not Modified request_headers = {'if-modified-since': self.DATE_PRESENT} request = create_request(request_headers) self.assertEqual(archive.get(request), not_modified_response) # Invalid date, fail check and return response again request_headers = {'if-modified-since': self.DATE_INVALID} request = create_request(request_headers) self.assertEqual(archive.get(request), response) # fail check since the request is not a GET or HEAD request (as per RFC) request_headers = {'if-modified-since': self.DATE_FUTURE} request = httparchive.ArchivedHttpRequest( 'POST', 'www.test.com', '/', None, request_headers) self.assertEqual(archive.get(request), response) def test_get_unmodified_headers(self): request = self.REQUEST response = self.RESPONSE archive = self.archive not_modified_response = httparchive.create_response(304) # Succeed check request_headers = {'if-unmodified-since': self.DATE_PAST} request = create_request(request_headers) self.assertEqual(archive.get(request), not_modified_response) # Fail check request_headers = {'if-unmodified-since': self.DATE_FUTURE} request = create_request(request_headers) self.assertEqual(archive.get(request), response) # Succeed check request_headers = {'if-unmodified-since': self.DATE_PRESENT} request = create_request(request_headers) self.assertEqual(archive.get(request), not_modified_response) # Fail check request_headers = {'if-unmodified-since': self.DATE_INVALID} request = create_request(request_headers) self.assertEqual(archive.get(request), response) # Fail check since the request is not a GET or HEAD request (as per RFC) request_headers = {'if-modified-since': self.DATE_PAST} request = httparchive.ArchivedHttpRequest( 'POST', 'www.test.com', '/', None, request_headers) self.assertEqual(archive.get(request), response) def test_get_etags(self): request = self.REQUEST response = self.RESPONSE archive = self.archive not_modified_response = httparchive.create_response(304) precondition_failed_response = httparchive.create_response(412) # if-match headers request_headers = {'if-match': self.ETAG_VALID} request = create_request(request_headers) self.assertEqual(archive.get(request), response) request_headers = {'if-match': self.ETAG_INVALID} request = create_request(request_headers) self.assertEqual(archive.get(request), precondition_failed_response) # if-none-match headers request_headers = {'if-none-match': self.ETAG_VALID} request = create_request(request_headers) self.assertEqual(archive.get(request), not_modified_response) request_headers = {'if-none-match': self.ETAG_INVALID} request = create_request(request_headers) self.assertEqual(archive.get(request), response) def test_get_multiple_match_headers(self): request = self.REQUEST response = self.RESPONSE archive = self.archive not_modified_response = httparchive.create_response(304) precondition_failed_response = httparchive.create_response(412) # if-match headers # If the request would, without the If-Match header field, # result in anything other than a 2xx or 412 status, # then the If-Match header MUST be ignored. request_headers = { 'if-match': self.ETAG_VALID, 'if-modified-since': self.DATE_PAST, } request = create_request(request_headers) self.assertEqual(archive.get(request), response) # Invalid etag, precondition failed request_headers = { 'if-match': self.ETAG_INVALID, 'if-modified-since': self.DATE_PAST, } request = create_request(request_headers) self.assertEqual(archive.get(request), precondition_failed_response) # 304 response; ignore if-match header request_headers = { 'if-match': self.ETAG_VALID, 'if-modified-since': self.DATE_FUTURE, } request = create_request(request_headers) self.assertEqual(archive.get(request), not_modified_response) # 304 response; ignore if-match header request_headers = { 'if-match': self.ETAG_INVALID, 'if-modified-since': self.DATE_PRESENT, } request = create_request(request_headers) self.assertEqual(archive.get(request), not_modified_response) # Invalid etag, precondition failed request_headers = { 'if-match': self.ETAG_INVALID, 'if-modified-since': self.DATE_INVALID, } request = create_request(request_headers) self.assertEqual(archive.get(request), precondition_failed_response) def test_get_multiple_none_match_headers(self): request = self.REQUEST response = self.RESPONSE archive = self.archive not_modified_response = httparchive.create_response(304) precondition_failed_response = httparchive.create_response(412) # if-none-match headers # If the request would, without the If-None-Match header field, # result in anything other than a 2xx or 304 status, # then the If-None-Match header MUST be ignored. request_headers = { 'if-none-match': self.ETAG_VALID, 'if-modified-since': self.DATE_PAST, } request = create_request(request_headers) self.assertEqual(archive.get(request), response) request_headers = { 'if-none-match': self.ETAG_INVALID, 'if-modified-since': self.DATE_PAST, } request = create_request(request_headers) self.assertEqual(archive.get(request), response) # etag match, precondition failed request_headers = { 'if-none-match': self.ETAG_VALID, 'if-modified-since': self.DATE_FUTURE, } request = create_request(request_headers) self.assertEqual(archive.get(request), not_modified_response) request_headers = { 'if-none-match': self.ETAG_INVALID, 'if-modified-since': self.DATE_PRESENT, } request = create_request(request_headers) self.assertEqual(archive.get(request), not_modified_response) request_headers = { 'if-none-match': self.ETAG_INVALID, 'if-modified-since': self.DATE_INVALID, } request = create_request(request_headers) self.assertEqual(archive.get(request), response) def test_response__TrimHeaders(self): response = httparchive.ArchivedHttpResponse header1 = [('access-control-allow-origin', '*'), ('content-type', 'image/jpeg'), ('content-length', 2878)] self.assertEqual(response._TrimHeaders(header1), header1) header2 = [('content-type', 'text/javascript; charset=utf-8'), ('connection', 'keep-alive'), ('cache-control', 'private, must-revalidate, max-age=0'), ('content-encoding', 'gzip')] self.assertEqual(response._TrimHeaders(header2), header2) header3 = [('content-security-policy', """\ default-src 'self' http://*.cnn.com:* https://*.cnn.com:* \ *.cnn.net:* *.turner.com:* *.ugdturner.com:* *.vgtf.net:*; \ script-src 'unsafe-inline' 'unsafe-eval' 'self' *; \ style-src 'unsafe-inline' 'self' *; frame-src 'self' *; \ object-src 'self' *; img-src 'self' * data:; media-src 'self' *; \ font-src 'self' *; connect-src 'self' *"""), ('access-control-allow-origin', '*'), ('content-type', 'text/html; charset=utf-8'), ('content-encoding', 'gzip')] self.assertEqual(response._TrimHeaders(header3), [ ('access-control-allow-origin', '*'), ('content-type', 'text/html; charset=utf-8'), ('content-encoding', 'gzip') ]) header4 = [('content-security-policy', """\ default-src * data: blob:;script-src *.facebook.com *.fbcdn.net \ *.facebook.net *.google-analytics.com *.virtualearth.net *.google.com \ 127.0.0.1:* *.spotilocal.com:* 'unsafe-inline' 'unsafe-eval' \ fbstatic-a.akamaihd.net fbcdn-static-b-a.akamaihd.net *.atlassolutions.com \ blob: chrome-extension://lifbcibllhkdhoafpjfnlhfpfgnpldfl \ *.liverail.com;style-src * 'unsafe-inline' data:;connect-src *.facebook.com \ *.fbcdn.net *.facebook.net *.spotilocal.com:* *.akamaihd.net \ wss://*.facebook.com:* https://fb.scanandcleanlocal.com:* \ *.atlassolutions.com attachment.fbsbx.com ws://localhost:* \ blob: 127.0.0.1:* *.liverail.com""")] self.assertEqual(response._TrimHeaders(header4), []) class ArchivedHttpResponse(unittest.TestCase): PAST_DATE_A = 'Tue, 13 Jul 2010 03:47:07 GMT' PAST_DATE_B = 'Tue, 13 Jul 2010 02:47:07 GMT' # PAST_DATE_A -1 hour PAST_DATE_C = 'Tue, 13 Jul 2010 04:47:07 GMT' # PAST_DATE_A +1 hour NOW_DATE_A = 'Wed, 20 Jul 2011 04:58:08 GMT' NOW_DATE_B = 'Wed, 20 Jul 2011 03:58:08 GMT' # NOW_DATE_A -1 hour NOW_DATE_C = 'Wed, 20 Jul 2011 05:58:08 GMT' # NOW_DATE_A +1 hour NOW_SECONDS = calendar.timegm(email.utils.parsedate(NOW_DATE_A)) def setUp(self): self.response = create_response([('date', self.PAST_DATE_A)]) def test_update_date_same_date(self): self.assertEqual( self.response.update_date(self.PAST_DATE_A, now=self.NOW_SECONDS), self.NOW_DATE_A) def test_update_date_before_date(self): self.assertEqual( self.response.update_date(self.PAST_DATE_B, now=self.NOW_SECONDS), self.NOW_DATE_B) def test_update_date_after_date(self): self.assertEqual( self.response.update_date(self.PAST_DATE_C, now=self.NOW_SECONDS), self.NOW_DATE_C) def test_update_date_bad_date_param(self): self.assertEqual( self.response.update_date('garbage date', now=self.NOW_SECONDS), 'garbage date') def test_update_date_bad_date_header(self): self.response.set_header('date', 'garbage date') self.assertEqual( self.response.update_date(self.PAST_DATE_B, now=self.NOW_SECONDS), self.PAST_DATE_B) if __name__ == '__main__': unittest.main()
unknown
codeparrot/codeparrot-clean
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic 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. // /////////////////////////////////////////////////////////////////////////// #ifndef INCLUDED_IMF_STD_IO_H #define INCLUDED_IMF_STD_IO_H //----------------------------------------------------------------------------- // // Low-level file input and output for OpenEXR // based on C++ standard iostreams. // //----------------------------------------------------------------------------- #include "ImfIO.h" #include "ImfNamespace.h" #include "ImfExport.h" #include <fstream> #include <sstream> OPENEXR_IMF_INTERNAL_NAMESPACE_HEADER_ENTER //------------------------------------------- // class StdIFStream -- an implementation of // class OPENEXR_IMF_INTERNAL_NAMESPACE::IStream based on class std::ifstream //------------------------------------------- class StdIFStream: public OPENEXR_IMF_INTERNAL_NAMESPACE::IStream { public: //------------------------------------------------------- // A constructor that opens the file with the given name. // The destructor will close the file. //------------------------------------------------------- IMF_EXPORT StdIFStream (const char fileName[]); //--------------------------------------------------------- // A constructor that uses a std::ifstream that has already // been opened by the caller. The StdIFStream's destructor // will not close the std::ifstream. //--------------------------------------------------------- IMF_EXPORT StdIFStream (std::ifstream &is, const char fileName[]); IMF_EXPORT virtual ~StdIFStream (); IMF_EXPORT virtual bool read (char c[/*n*/], int n); IMF_EXPORT virtual Int64 tellg (); IMF_EXPORT virtual void seekg (Int64 pos); IMF_EXPORT virtual void clear (); private: std::ifstream * _is; bool _deleteStream; }; //------------------------------------------- // class StdOFStream -- an implementation of // class OPENEXR_IMF_INTERNAL_NAMESPACE::OStream based on class std::ofstream //------------------------------------------- class StdOFStream: public OPENEXR_IMF_INTERNAL_NAMESPACE::OStream { public: //------------------------------------------------------- // A constructor that opens the file with the given name. // The destructor will close the file. //------------------------------------------------------- IMF_EXPORT StdOFStream (const char fileName[]); //--------------------------------------------------------- // A constructor that uses a std::ofstream that has already // been opened by the caller. The StdOFStream's destructor // will not close the std::ofstream. //--------------------------------------------------------- IMF_EXPORT StdOFStream (std::ofstream &os, const char fileName[]); IMF_EXPORT virtual ~StdOFStream (); IMF_EXPORT virtual void write (const char c[/*n*/], int n); IMF_EXPORT virtual Int64 tellp (); IMF_EXPORT virtual void seekp (Int64 pos); private: std::ofstream * _os; bool _deleteStream; }; //------------------------------------------------ // class StdOSStream -- an implementation of class // OPENEXR_IMF_INTERNAL_NAMESPACE::OStream, based on class std::ostringstream //------------------------------------------------ class StdOSStream: public OPENEXR_IMF_INTERNAL_NAMESPACE::OStream { public: IMF_EXPORT StdOSStream (); IMF_EXPORT virtual void write (const char c[/*n*/], int n); IMF_EXPORT virtual Int64 tellp (); IMF_EXPORT virtual void seekp (Int64 pos); IMF_EXPORT std::string str () const {return _os.str();} private: std::ostringstream _os; }; OPENEXR_IMF_INTERNAL_NAMESPACE_HEADER_EXIT #endif
c
github
https://github.com/opencv/opencv
3rdparty/openexr/IlmImf/ImfStdIO.h
# Copyright 2018 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. # ============================================================================== """Python helper for loading kafka ops and kernels.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.util import loader from tensorflow.python.platform import resource_loader _dataset_ops = loader.load_op_library( resource_loader.get_path_to_datafile("../../_dataset_ops.so"))
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- """ werkzeug.contrib.lint ~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 0.5 This module provides a middleware that performs sanity checks of the WSGI application. It checks that :pep:`333` is properly implemented and warns on some common HTTP errors such as non-empty responses for 304 status codes. This module provides a middleware, the :class:`LintMiddleware`. Wrap your application with it and it will warn about common problems with WSGI and HTTP while your application is running. It's strongly recommended to use it during development. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from urlparse import urlparse from warnings import warn from werkzeug.datastructures import Headers from werkzeug.http import is_entity_header from werkzeug.wsgi import FileWrapper from werkzeug._compat import string_types class WSGIWarning(Warning): """Warning class for WSGI warnings.""" class HTTPWarning(Warning): """Warning class for HTTP warnings.""" def check_string(context, obj, stacklevel=3): if type(obj) is not str: warn(WSGIWarning('%s requires bytestrings, got %s' % (context, obj.__class__.__name__))) class InputStream(object): def __init__(self, stream): self._stream = stream def read(self, *args): if len(args) == 0: warn(WSGIWarning('wsgi does not guarantee an EOF marker on the ' 'input stream, thus making calls to ' 'wsgi.input.read() unsafe. Conforming servers ' 'may never return from this call.'), stacklevel=2) elif len(args) != 1: warn(WSGIWarning('too many parameters passed to wsgi.input.read()'), stacklevel=2) return self._stream.read(*args) def readline(self, *args): if len(args) == 0: warn(WSGIWarning('Calls to wsgi.input.readline() without arguments' ' are unsafe. Use wsgi.input.read() instead.'), stacklevel=2) elif len(args) == 1: warn(WSGIWarning('wsgi.input.readline() was called with a size hint. ' 'WSGI does not support this, although it\'s available ' 'on all major servers.'), stacklevel=2) else: raise TypeError('too many arguments passed to wsgi.input.readline()') return self._stream.readline(*args) def __iter__(self): try: return iter(self._stream) except TypeError: warn(WSGIWarning('wsgi.input is not iterable.'), stacklevel=2) return iter(()) def close(self): warn(WSGIWarning('application closed the input stream!'), stacklevel=2) self._stream.close() class ErrorStream(object): def __init__(self, stream): self._stream = stream def write(self, s): check_string('wsgi.error.write()', s) self._stream.write(s) def flush(self): self._stream.flush() def writelines(self, seq): for line in seq: self.write(seq) def close(self): warn(WSGIWarning('application closed the error stream!'), stacklevel=2) self._stream.close() class GuardedWrite(object): def __init__(self, write, chunks): self._write = write self._chunks = chunks def __call__(self, s): check_string('write()', s) self._write.write(s) self._chunks.append(len(s)) class GuardedIterator(object): def __init__(self, iterator, headers_set, chunks): self._iterator = iterator self._next = iter(iterator).next self.closed = False self.headers_set = headers_set self.chunks = chunks def __iter__(self): return self def next(self): if self.closed: warn(WSGIWarning('iterated over closed app_iter'), stacklevel=2) rv = self._next() if not self.headers_set: warn(WSGIWarning('Application returned before it ' 'started the response'), stacklevel=2) check_string('application iterator items', rv) self.chunks.append(len(rv)) return rv def close(self): self.closed = True if hasattr(self._iterator, 'close'): self._iterator.close() if self.headers_set: status_code, headers = self.headers_set bytes_sent = sum(self.chunks) content_length = headers.get('content-length', type=int) if status_code == 304: for key, value in headers: key = key.lower() if key not in ('expires', 'content-location') and \ is_entity_header(key): warn(HTTPWarning('entity header %r found in 304 ' 'response' % key)) if bytes_sent: warn(HTTPWarning('304 responses must not have a body')) elif 100 <= status_code < 200 or status_code == 204: if content_length != 0: warn(HTTPWarning('%r responses must have an empty ' 'content length') % status_code) if bytes_sent: warn(HTTPWarning('%r responses must not have a body' % status_code)) elif content_length is not None and content_length != bytes_sent: warn(WSGIWarning('Content-Length and the number of bytes ' 'sent to the client do not match.')) def __del__(self): if not self.closed: try: warn(WSGIWarning('Iterator was garbage collected before ' 'it was closed.')) except Exception: pass class LintMiddleware(object): """This middleware wraps an application and warns on common errors. Among other thing it currently checks for the following problems: - invalid status codes - non-bytestrings sent to the WSGI server - strings returned from the WSGI application - non-empty conditional responses - unquoted etags - relative URLs in the Location header - unsafe calls to wsgi.input - unclosed iterators Detected errors are emitted using the standard Python :mod:`warnings` system and usually end up on :data:`stderr`. :: from werkzeug.contrib.lint import LintMiddleware app = LintMiddleware(app) :param app: the application to wrap """ def __init__(self, app): self.app = app def check_environ(self, environ): if type(environ) is not dict: warn(WSGIWarning('WSGI environment is not a standard python dict.'), stacklevel=4) for key in ('REQUEST_METHOD', 'SERVER_NAME', 'SERVER_PORT', 'wsgi.version', 'wsgi.input', 'wsgi.errors', 'wsgi.multithread', 'wsgi.multiprocess', 'wsgi.run_once'): if key not in environ: warn(WSGIWarning('required environment key %r not found' % key), stacklevel=3) if environ['wsgi.version'] != (1, 0): warn(WSGIWarning('environ is not a WSGI 1.0 environ'), stacklevel=3) script_name = environ.get('SCRIPT_NAME', '') if script_name and script_name[:1] != '/': warn(WSGIWarning('SCRIPT_NAME does not start with a slash: %r' % script_name), stacklevel=3) path_info = environ.get('PATH_INFO', '') if path_info[:1] != '/': warn(WSGIWarning('PATH_INFO does not start with a slash: %r' % path_info), stacklevel=3) def check_start_response(self, status, headers, exc_info): check_string('status', status) status_code = status.split(None, 1)[0] if len(status_code) != 3 or not status_code.isdigit(): warn(WSGIWarning('Status code must be three digits'), stacklevel=3) if len(status) < 4 or status[3] != ' ': warn(WSGIWarning('Invalid value for status %r. Valid ' 'status strings are three digits, a space ' 'and a status explanation'), stacklevel=3) status_code = int(status_code) if status_code < 100: warn(WSGIWarning('status code < 100 detected'), stacklevel=3) if type(headers) is not list: warn(WSGIWarning('header list is not a list'), stacklevel=3) for item in headers: if type(item) is not tuple or len(item) != 2: warn(WSGIWarning('Headers must tuple 2-item tuples'), stacklevel=3) name, value = item if type(name) is not str or type(value) is not str: warn(WSGIWarning('header items must be strings'), stacklevel=3) if name.lower() == 'status': warn(WSGIWarning('The status header is not supported due to ' 'conflicts with the CGI spec.'), stacklevel=3) if exc_info is not None and not isinstance(exc_info, tuple): warn(WSGIWarning('invalid value for exc_info'), stacklevel=3) headers = Headers(headers) self.check_headers(headers) return status_code, headers def check_headers(self, headers): etag = headers.get('etag') if etag is not None: if etag.startswith('w/'): etag = etag[2:] if not (etag[:1] == etag[-1:] == '"'): warn(HTTPWarning('unquoted etag emitted.'), stacklevel=4) location = headers.get('location') if location is not None: if not urlparse(location).netloc: warn(HTTPWarning('absolute URLs required for location header'), stacklevel=4) def check_iterator(self, app_iter): if isinstance(app_iter, string_types): warn(WSGIWarning('application returned string. Response will ' 'send character for character to the client ' 'which will kill the performance. Return a ' 'list or iterable instead.'), stacklevel=3) def __call__(self, *args, **kwargs): if len(args) != 2: warn(WSGIWarning('Two arguments to WSGI app required'), stacklevel=2) if kwargs: warn(WSGIWarning('No keyword arguments to WSGI app allowed'), stacklevel=2) environ, start_response = args self.check_environ(environ) environ['wsgi.input'] = InputStream(environ['wsgi.input']) environ['wsgi.errors'] = ErrorStream(environ['wsgi.errors']) # hook our own file wrapper in so that applications will always # iterate to the end and we can check the content length environ['wsgi.file_wrapper'] = FileWrapper headers_set = [] chunks = [] def checking_start_response(*args, **kwargs): if len(args) not in (2, 3): warn(WSGIWarning('Invalid number of arguments: %s, expected ' '2 or 3' % len(args), stacklevel=2)) if kwargs: warn(WSGIWarning('no keyword arguments allowed.')) status, headers = args[:2] if len(args) == 3: exc_info = args[2] else: exc_info = None headers_set[:] = self.check_start_response(status, headers, exc_info) return GuardedWrite(start_response(status, headers, exc_info), chunks) app_iter = self.app(environ, checking_start_response) self.check_iterator(app_iter) return GuardedIterator(app_iter, headers_set, chunks)
unknown
codeparrot/codeparrot-clean
"""fontTools.pens.pointInsidePen -- Pen implementing "point inside" testing for shapes. """ from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * from fontTools.pens.basePen import BasePen from fontTools.misc.bezierTools import solveQuadratic, solveCubic __all__ = ["PointInsidePen"] # working around floating point errors EPSILON = 1e-10 ONE_PLUS_EPSILON = 1 + EPSILON ZERO_MINUS_EPSILON = 0 - EPSILON class PointInsidePen(BasePen): """This pen implements "point inside" testing: to test whether a given point lies inside the shape (black) or outside (white). Instances of this class can be recycled, as long as the setTestPoint() method is used to set the new point to test. Typical usage: pen = PointInsidePen(glyphSet, (100, 200)) outline.draw(pen) isInside = pen.getResult() Both the even-odd algorithm and the non-zero-winding-rule algorithm are implemented. The latter is the default, specify True for the evenOdd argument of __init__ or setTestPoint to use the even-odd algorithm. """ # This class implements the classical "shoot a ray from the test point # to infinity and count how many times it intersects the outline" (as well # as the non-zero variant, where the counter is incremented if the outline # intersects the ray in one direction and decremented if it intersects in # the other direction). # I found an amazingly clear explanation of the subtleties involved in # implementing this correctly for polygons here: # http://graphics.cs.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html # I extended the principles outlined on that page to curves. def __init__(self, glyphSet, testPoint, evenOdd=0): BasePen.__init__(self, glyphSet) self.setTestPoint(testPoint, evenOdd) def setTestPoint(self, testPoint, evenOdd=0): """Set the point to test. Call this _before_ the outline gets drawn.""" self.testPoint = testPoint self.evenOdd = evenOdd self.firstPoint = None self.intersectionCount = 0 def getResult(self): """After the shape has been drawn, getResult() returns True if the test point lies within the (black) shape, and False if it doesn't. """ if self.firstPoint is not None: # always make sure the sub paths are closed; the algorithm only works # for closed paths. self.closePath() if self.evenOdd: result = self.intersectionCount % 2 else: result = self.intersectionCount return not not result def _addIntersection(self, goingUp): if self.evenOdd or goingUp: self.intersectionCount += 1 else: self.intersectionCount -= 1 def _moveTo(self, point): if self.firstPoint is not None: # always make sure the sub paths are closed; the algorithm only works # for closed paths. self.closePath() self.firstPoint = point def _lineTo(self, point): x, y = self.testPoint x1, y1 = self._getCurrentPoint() x2, y2 = point if x1 < x and x2 < x: return if y1 < y and y2 < y: return if y1 >= y and y2 >= y: return dx = x2 - x1 dy = y2 - y1 t = (y - y1) / dy ix = dx * t + x1 if ix < x: return self._addIntersection(y2 > y1) def _curveToOne(self, bcp1, bcp2, point): x, y = self.testPoint x1, y1 = self._getCurrentPoint() x2, y2 = bcp1 x3, y3 = bcp2 x4, y4 = point if x1 < x and x2 < x and x3 < x and x4 < x: return if y1 < y and y2 < y and y3 < y and y4 < y: return if y1 >= y and y2 >= y and y3 >= y and y4 >= y: return dy = y1 cy = (y2 - dy) * 3.0 by = (y3 - y2) * 3.0 - cy ay = y4 - dy - cy - by solutions = sorted(solveCubic(ay, by, cy, dy - y)) solutions = [t for t in solutions if ZERO_MINUS_EPSILON <= t <= ONE_PLUS_EPSILON] if not solutions: return dx = x1 cx = (x2 - dx) * 3.0 bx = (x3 - x2) * 3.0 - cx ax = x4 - dx - cx - bx above = y1 >= y lastT = None for t in solutions: if t == lastT: continue lastT = t t2 = t * t t3 = t2 * t direction = 3*ay*t2 + 2*by*t + cy if direction == 0.0: direction = 6*ay*t + 2*by if direction == 0.0: direction = ay goingUp = direction > 0.0 xt = ax*t3 + bx*t2 + cx*t + dx if xt < x: above = goingUp continue if t == 0.0: if not goingUp: self._addIntersection(goingUp) elif t == 1.0: if not above: self._addIntersection(goingUp) else: if above != goingUp: self._addIntersection(goingUp) #else: # we're not really intersecting, merely touching the 'top' above = goingUp def _qCurveToOne_unfinished(self, bcp, point): # XXX need to finish this, for now doing it through a cubic # (BasePen implements _qCurveTo in terms of a cubic) will # have to do. x, y = self.testPoint x1, y1 = self._getCurrentPoint() x2, y2 = bcp x3, y3 = point c = y1 b = (y2 - c) * 2.0 a = y3 - c - b solutions = sorted(solveQuadratic(a, b, c - y)) solutions = [t for t in solutions if ZERO_MINUS_EPSILON <= t <= ONE_PLUS_EPSILON] if not solutions: return XXX def _closePath(self): if self._getCurrentPoint() != self.firstPoint: self.lineTo(self.firstPoint) self.firstPoint = None _endPath = _closePath
unknown
codeparrot/codeparrot-clean
""" Multi-part parsing for file uploads. Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to file upload handlers for processing. """ from __future__ import unicode_literals import base64 import cgi from django.conf import settings from django.core.exceptions import SuspiciousOperation from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_text from django.utils import six from django.utils.text import unescape_entities from django.core.files.uploadhandler import StopUpload, SkipFile, StopFutureHandlers __all__ = ('MultiPartParser', 'MultiPartParserError', 'InputStreamExhausted') class MultiPartParserError(Exception): pass class InputStreamExhausted(Exception): """ No more reads are allowed from this device. """ pass RAW = "raw" FILE = "file" FIELD = "field" class MultiPartParser(object): """ A rfc2388 multipart/form-data parser. ``MultiValueDict.parse()`` reads the input stream in ``chunk_size`` chunks and returns a tuple of ``(MultiValueDict(POST), MultiValueDict(FILES))``. """ def __init__(self, META, input_data, upload_handlers, encoding=None): """ Initialize the MultiPartParser object. :META: The standard ``META`` dictionary in Django request objects. :input_data: The raw post data, as a file-like object. :upload_handler: An UploadHandler instance that performs operations on the uploaded data. :encoding: The encoding with which to treat the incoming data. """ # # Content-Type should containt multipart and the boundary information. # content_type = META.get('HTTP_CONTENT_TYPE', META.get('CONTENT_TYPE', '')) if not content_type.startswith('multipart/'): raise MultiPartParserError('Invalid Content-Type: %s' % content_type) # Parse the header to get the boundary to split the parts. ctypes, opts = parse_header(content_type.encode('ascii')) boundary = opts.get('boundary') if not boundary or not cgi.valid_boundary(boundary): raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary) # Content-Length should contain the length of the body we are about # to receive. try: content_length = int(META.get('HTTP_CONTENT_LENGTH', META.get('CONTENT_LENGTH', 0))) except (ValueError, TypeError): content_length = 0 if content_length < 0: # This means we shouldn't continue...raise an error. raise MultiPartParserError("Invalid content length: %r" % content_length) if isinstance(boundary, six.text_type): boundary = boundary.encode('ascii') self._boundary = boundary self._input_data = input_data # For compatibility with low-level network APIs (with 32-bit integers), # the chunk size should be < 2^31, but still divisible by 4. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size] self._chunk_size = min([2**31-4] + possible_sizes) self._meta = META self._encoding = encoding or settings.DEFAULT_CHARSET self._content_length = content_length self._upload_handlers = upload_handlers def parse(self): """ Parse the POST data and break it into a FILES MultiValueDict and a POST MultiValueDict. Returns a tuple containing the POST and FILES dictionary, respectively. """ # We have to import QueryDict down here to avoid a circular import. from django.http import QueryDict encoding = self._encoding handlers = self._upload_handlers # HTTP spec says that Content-Length >= 0 is valid # handling content-length == 0 before continuing if self._content_length == 0: return QueryDict('', encoding=self._encoding), MultiValueDict() # See if the handler will want to take care of the parsing. # This allows overriding everything if somebody wants it. for handler in handlers: result = handler.handle_raw_input(self._input_data, self._meta, self._content_length, self._boundary, encoding) if result is not None: return result[0], result[1] # Create the data structures to be used later. self._post = QueryDict('', mutable=True) self._files = MultiValueDict() # Instantiate the parser and stream: stream = LazyStream(ChunkIter(self._input_data, self._chunk_size)) # Whether or not to signal a file-completion at the beginning of the loop. old_field_name = None counters = [0] * len(handlers) try: for item_type, meta_data, field_stream in Parser(stream, self._boundary): if old_field_name: # We run this at the beginning of the next loop # since we cannot be sure a file is complete until # we hit the next boundary/part of the multipart content. self.handle_file_complete(old_field_name, counters) old_field_name = None try: disposition = meta_data['content-disposition'][1] field_name = disposition['name'].strip() except (KeyError, IndexError, AttributeError): continue transfer_encoding = meta_data.get('content-transfer-encoding') if transfer_encoding is not None: transfer_encoding = transfer_encoding[0].strip() field_name = force_text(field_name, encoding, errors='replace') if item_type == FIELD: # This is a post field, we can just set it in the post if transfer_encoding == 'base64': raw_data = field_stream.read() try: data = str(raw_data).decode('base64') except: data = raw_data else: data = field_stream.read() self._post.appendlist(field_name, force_text(data, encoding, errors='replace')) elif item_type == FILE: # This is a file, use the handler... file_name = disposition.get('filename') if not file_name: continue file_name = force_text(file_name, encoding, errors='replace') file_name = self.IE_sanitize(unescape_entities(file_name)) content_type = meta_data.get('content-type', ('',))[0].strip() try: charset = meta_data.get('content-type', (0, {}))[1].get('charset', None) except: charset = None try: content_length = int(meta_data.get('content-length')[0]) except (IndexError, TypeError, ValueError): content_length = None counters = [0] * len(handlers) try: for handler in handlers: try: handler.new_file(field_name, file_name, content_type, content_length, charset) except StopFutureHandlers: break for chunk in field_stream: if transfer_encoding == 'base64': # We only special-case base64 transfer encoding # We should always read base64 streams by multiple of 4 over_bytes = len(chunk) % 4 if over_bytes: over_chunk = field_stream.read(4 - over_bytes) chunk += over_chunk try: chunk = base64.b64decode(chunk) except Exception as e: # Since this is only a chunk, any error is an unfixable error. raise MultiPartParserError("Could not decode base64 data: %r" % e) for i, handler in enumerate(handlers): chunk_length = len(chunk) chunk = handler.receive_data_chunk(chunk, counters[i]) counters[i] += chunk_length if chunk is None: # If the chunk received by the handler is None, then don't continue. break except SkipFile: # Just use up the rest of this file... exhaust(field_stream) else: # Handle file upload completions on next iteration. old_field_name = field_name else: # If this is neither a FIELD or a FILE, just exhaust the stream. exhaust(stream) except StopUpload as e: if not e.connection_reset: exhaust(self._input_data) else: # Make sure that the request data is all fed exhaust(self._input_data) # Signal that the upload has completed. for handler in handlers: retval = handler.upload_complete() if retval: break return self._post, self._files def handle_file_complete(self, old_field_name, counters): """ Handle all the signalling that takes place when a file is complete. """ for i, handler in enumerate(self._upload_handlers): file_obj = handler.file_complete(counters[i]) if file_obj: # If it returns a file object, then set the files dict. self._files.appendlist(force_text(old_field_name, self._encoding, errors='replace'), file_obj) break def IE_sanitize(self, filename): """Cleanup filename from Internet Explorer full paths.""" return filename and filename[filename.rfind("\\")+1:].strip() class LazyStream(six.Iterator): """ The LazyStream wrapper allows one to get and "unget" bytes from a stream. Given a producer object (an iterator that yields bytestrings), the LazyStream object will support iteration, reading, and keeping a "look-back" variable in case you need to "unget" some bytes. """ def __init__(self, producer, length=None): """ Every LazyStream must have a producer when instantiated. A producer is an iterable that returns a string each time it is called. """ self._producer = producer self._empty = False self._leftover = b'' self.length = length self.position = 0 self._remaining = length self._unget_history = [] def tell(self): return self.position def read(self, size=None): def parts(): remaining = (size is not None and [size] or [self._remaining])[0] # do the whole thing in one shot if no limit was provided. if remaining is None: yield b''.join(self) return # otherwise do some bookkeeping to return exactly enough # of the stream and stashing any extra content we get from # the producer while remaining != 0: assert remaining > 0, 'remaining bytes to read should never go negative' chunk = next(self) emitting = chunk[:remaining] self.unget(chunk[remaining:]) remaining -= len(emitting) yield emitting out = b''.join(parts()) return out def __next__(self): """ Used when the exact number of bytes to read is unimportant. This procedure just returns whatever is chunk is conveniently returned from the iterator instead. Useful to avoid unnecessary bookkeeping if performance is an issue. """ if self._leftover: output = self._leftover self._leftover = b'' else: output = next(self._producer) self._unget_history = [] self.position += len(output) return output def close(self): """ Used to invalidate/disable this lazy stream. Replaces the producer with an empty list. Any leftover bytes that have already been read will still be reported upon read() and/or next(). """ self._producer = [] def __iter__(self): return self def unget(self, bytes): """ Places bytes back onto the front of the lazy stream. Future calls to read() will return those bytes first. The stream position and thus tell() will be rewound. """ if not bytes: return self._update_unget_history(len(bytes)) self.position -= len(bytes) self._leftover = b''.join([bytes, self._leftover]) def _update_unget_history(self, num_bytes): """ Updates the unget history as a sanity check to see if we've pushed back the same number of bytes in one chunk. If we keep ungetting the same number of bytes many times (here, 50), we're mostly likely in an infinite loop of some sort. This is usually caused by a maliciously-malformed MIME request. """ self._unget_history = [num_bytes] + self._unget_history[:49] number_equal = len([current_number for current_number in self._unget_history if current_number == num_bytes]) if number_equal > 40: raise SuspiciousOperation( "The multipart parser got stuck, which shouldn't happen with" " normal uploaded files. Check for malicious upload activity;" " if there is none, report this to the Django developers." ) class ChunkIter(six.Iterator): """ An iterable that will yield chunks of data. Given a file-like object as the constructor, this object will yield chunks of read operations from that object. """ def __init__(self, flo, chunk_size=64 * 1024): self.flo = flo self.chunk_size = chunk_size def __next__(self): try: data = self.flo.read(self.chunk_size) except InputStreamExhausted: raise StopIteration() if data: return data else: raise StopIteration() def __iter__(self): return self class InterBoundaryIter(six.Iterator): """ A Producer that will iterate over boundaries. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary def __iter__(self): return self def __next__(self): try: return LazyStream(BoundaryIter(self._stream, self._boundary)) except InputStreamExhausted: raise StopIteration() class BoundaryIter(six.Iterator): """ A Producer that is sensitive to boundaries. Will happily yield bytes until a boundary is found. Will yield the bytes before the boundary, throw away the boundary bytes themselves, and push the post-boundary bytes back on the stream. The future calls to next() after locating the boundary will raise a StopIteration exception. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary self._done = False # rollback an additional six bytes because the format is like # this: CRLF<boundary>[--CRLF] self._rollback = len(boundary) + 6 # Try to use mx fast string search if available. Otherwise # use Python find. Wrap the latter for consistency. unused_char = self._stream.read(1) if not unused_char: raise InputStreamExhausted() self._stream.unget(unused_char) try: from mx.TextTools import FS self._fs = FS(boundary).find except ImportError: self._fs = lambda data: data.find(boundary) def __iter__(self): return self def __next__(self): if self._done: raise StopIteration() stream = self._stream rollback = self._rollback bytes_read = 0 chunks = [] for bytes in stream: bytes_read += len(bytes) chunks.append(bytes) if bytes_read > rollback: break if not bytes: break else: self._done = True if not chunks: raise StopIteration() chunk = b''.join(chunks) boundary = self._find_boundary(chunk, len(chunk) < self._rollback) if boundary: end, next = boundary stream.unget(chunk[next:]) self._done = True return chunk[:end] else: # make sure we dont treat a partial boundary (and # its separators) as data if not chunk[:-rollback]:# and len(chunk) >= (len(self._boundary) + 6): # There's nothing left, we should just return and mark as done. self._done = True return chunk else: stream.unget(chunk[-rollback:]) return chunk[:-rollback] def _find_boundary(self, data, eof = False): """ Finds a multipart boundary in data. Should no boundry exist in the data None is returned instead. Otherwise a tuple containing the indices of the following are returned: * the end of current encapsulation * the start of the next encapsulation """ index = self._fs(data) if index < 0: return None else: end = index next = index + len(self._boundary) # backup over CRLF last = max(0, end-1) if data[last:last+1] == b'\n': end -= 1 last = max(0, end-1) if data[last:last+1] == b'\r': end -= 1 return end, next def exhaust(stream_or_iterable): """ Completely exhausts an iterator or stream. Raise a MultiPartParserError if the argument is not a stream or an iterable. """ iterator = None try: iterator = iter(stream_or_iterable) except TypeError: iterator = ChunkIter(stream_or_iterable, 16384) if iterator is None: raise MultiPartParserError('multipartparser.exhaust() was passed a non-iterable or stream parameter') for __ in iterator: pass def parse_boundary_stream(stream, max_header_size): """ Parses one and exactly one stream that encapsulates a boundary. """ # Stream at beginning of header, look for end of header # and parse it if found. The header must fit within one # chunk. chunk = stream.read(max_header_size) # 'find' returns the top of these four bytes, so we'll # need to munch them later to prevent them from polluting # the payload. header_end = chunk.find(b'\r\n\r\n') def _parse_header(line): main_value_pair, params = parse_header(line) try: name, value = main_value_pair.split(':', 1) except: raise ValueError("Invalid header: %r" % line) return name, (value, params) if header_end == -1: # we find no header, so we just mark this fact and pass on # the stream verbatim stream.unget(chunk) return (RAW, {}, stream) header = chunk[:header_end] # here we place any excess chunk back onto the stream, as # well as throwing away the CRLFCRLF bytes from above. stream.unget(chunk[header_end + 4:]) TYPE = RAW outdict = {} # Eliminate blank lines for line in header.split(b'\r\n'): # This terminology ("main value" and "dictionary of # parameters") is from the Python docs. try: name, (value, params) = _parse_header(line) except: continue if name == 'content-disposition': TYPE = FIELD if params.get('filename'): TYPE = FILE outdict[name] = value, params if TYPE == RAW: stream.unget(chunk) return (TYPE, outdict, stream) class Parser(object): def __init__(self, stream, boundary): self._stream = stream self._separator = b'--' + boundary def __iter__(self): boundarystream = InterBoundaryIter(self._stream, self._separator) for sub_stream in boundarystream: # Iterate over each part yield parse_boundary_stream(sub_stream, 1024) def parse_header(line): """ Parse the header into a key-value. Input (line): bytes, output: unicode for key/name, bytes for value which will be decoded later """ plist = _parse_header_params(b';' + line) key = plist.pop(0).lower().decode('ascii') pdict = {} for p in plist: i = p.find(b'=') if i >= 0: name = p[:i].strip().lower().decode('ascii') value = p[i+1:].strip() if len(value) >= 2 and value[:1] == value[-1:] == b'"': value = value[1:-1] value = value.replace(b'\\\\', b'\\').replace(b'\\"', b'"') pdict[name] = value return key, pdict def _parse_header_params(s): plist = [] while s[:1] == b';': s = s[1:] end = s.find(b';') while end > 0 and s.count(b'"', 0, end) % 2: end = s.find(b';', end + 1) if end < 0: end = len(s) f = s[:end] plist.append(f.strip()) s = s[end:] return plist
unknown
codeparrot/codeparrot-clean
from __future__ import unicode_literals from django.contrib.admin.utils import quote from django.core.urlresolvers import reverse from django.template.response import TemplateResponse from django.test import TestCase, override_settings from .models import Action, Person, Car @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF='admin_custom_urls.urls',) class AdminCustomUrlsTest(TestCase): """ Remember that: * The Action model has a CharField PK. * The ModelAdmin for Action customizes the add_view URL, it's '<app name>/<model name>/!add/' """ fixtures = ['users.json', 'actions.json'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def testBasicAddGet(self): """ Ensure GET on the add_view works. """ response = self.client.get('/admin/admin_custom_urls/action/!add/') self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def testAddWithGETArgs(self): """ Ensure GET on the add_view plus specifying a field value in the query string works. """ response = self.client.get('/admin/admin_custom_urls/action/!add/', {'name': 'My Action'}) self.assertEqual(response.status_code, 200) self.assertContains(response, 'value="My Action"') def testBasicAddPost(self): """ Ensure POST on add_view works. """ post_data = { '_popup': '1', "name": 'Action added through a popup', "description": "Description of added action", } response = self.client.post('/admin/admin_custom_urls/action/!add/', post_data) self.assertEqual(response.status_code, 200) self.assertContains(response, 'dismissAddAnotherPopup') self.assertContains(response, 'Action added through a popup') def testAdminUrlsNoClash(self): """ Test that some admin URLs work correctly. """ # Should get the change_view for model instance with PK 'add', not show # the add_view response = self.client.get('/admin/admin_custom_urls/action/add/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') # Ditto, but use reverse() to build the URL url = reverse('admin:%s_action_change' % Action._meta.app_label, args=(quote('add'),)) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') # Should correctly get the change_view for the model instance with the # funny-looking PK (the one wth a 'path/to/html/document.html' value) url = reverse('admin:%s_action_change' % Action._meta.app_label, args=(quote("path/to/html/document.html"),)) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Change action') self.assertContains(response, 'value="path/to/html/document.html"') @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), ROOT_URLCONF='admin_custom_urls.urls',) class CustomRedirects(TestCase): fixtures = ['users.json', 'actions.json'] def setUp(self): self.client.login(username='super', password='secret') def tearDown(self): self.client.logout() def test_post_save_add_redirect(self): """ Ensures that ModelAdmin.response_post_save_add() controls the redirection after the 'Save' button has been pressed when adding a new object. Refs 8001, 18310, 19505. """ post_data = {'name': 'John Doe'} self.assertEqual(Person.objects.count(), 0) response = self.client.post( reverse('admin:admin_custom_urls_person_add'), post_data) persons = Person.objects.all() self.assertEqual(len(persons), 1) self.assertRedirects( response, reverse('admin:admin_custom_urls_person_history', args=[persons[0].pk])) def test_post_save_change_redirect(self): """ Ensures that ModelAdmin.response_post_save_change() controls the redirection after the 'Save' button has been pressed when editing an existing object. Refs 8001, 18310, 19505. """ Person.objects.create(name='John Doe') self.assertEqual(Person.objects.count(), 1) person = Person.objects.all()[0] post_data = {'name': 'Jack Doe'} response = self.client.post( reverse('admin:admin_custom_urls_person_change', args=[person.pk]), post_data) self.assertRedirects( response, reverse('admin:admin_custom_urls_person_delete', args=[person.pk])) def test_post_url_continue(self): """ Ensures that the ModelAdmin.response_add()'s parameter `post_url_continue` controls the redirection after an object has been created. """ post_data = {'name': 'SuperFast', '_continue': '1'} self.assertEqual(Car.objects.count(), 0) response = self.client.post( reverse('admin:admin_custom_urls_car_add'), post_data) cars = Car.objects.all() self.assertEqual(len(cars), 1) self.assertRedirects( response, reverse('admin:admin_custom_urls_car_history', args=[cars[0].pk]))
unknown
codeparrot/codeparrot-clean
"""Test the cloud.iot module.""" from aiohttp import web import pytest from homeassistant.components.cloud import DOMAIN from homeassistant.components.cloud.client import CloudClient from homeassistant.components.cloud.const import PREF_ENABLE_ALEXA, PREF_ENABLE_GOOGLE from homeassistant.core import State from homeassistant.setup import async_setup_component from . import mock_cloud, mock_cloud_prefs from tests.async_mock import AsyncMock, MagicMock, patch from tests.components.alexa import test_smart_home as test_alexa @pytest.fixture def mock_cloud_inst(): """Mock cloud class.""" return MagicMock(subscription_expired=False) async def test_handler_alexa(hass): """Test handler Alexa.""" hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"}) hass.states.async_set("switch.test2", "on", {"friendly_name": "Test switch 2"}) await mock_cloud( hass, { "alexa": { "filter": {"exclude_entities": "switch.test2"}, "entity_config": { "switch.test": { "name": "Config name", "description": "Config description", "display_categories": "LIGHT", } }, } }, ) mock_cloud_prefs(hass) cloud = hass.data["cloud"] resp = await cloud.client.async_alexa_message( test_alexa.get_new_request("Alexa.Discovery", "Discover") ) endpoints = resp["event"]["payload"]["endpoints"] assert len(endpoints) == 1 device = endpoints[0] assert device["description"] == "Config description via Home Assistant" assert device["friendlyName"] == "Config name" assert device["displayCategories"] == ["LIGHT"] assert device["manufacturerName"] == "Home Assistant" async def test_handler_alexa_disabled(hass, mock_cloud_fixture): """Test handler Alexa when user has disabled it.""" mock_cloud_fixture._prefs[PREF_ENABLE_ALEXA] = False cloud = hass.data["cloud"] resp = await cloud.client.async_alexa_message( test_alexa.get_new_request("Alexa.Discovery", "Discover") ) assert resp["event"]["header"]["namespace"] == "Alexa" assert resp["event"]["header"]["name"] == "ErrorResponse" assert resp["event"]["payload"]["type"] == "BRIDGE_UNREACHABLE" async def test_handler_google_actions(hass): """Test handler Google Actions.""" hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"}) hass.states.async_set("switch.test2", "on", {"friendly_name": "Test switch 2"}) hass.states.async_set("group.all_locks", "on", {"friendly_name": "Evil locks"}) await mock_cloud( hass, { "google_actions": { "filter": {"exclude_entities": "switch.test2"}, "entity_config": { "switch.test": { "name": "Config name", "aliases": "Config alias", "room": "living room", } }, } }, ) mock_cloud_prefs(hass) cloud = hass.data["cloud"] reqid = "5711642932632160983" data = {"requestId": reqid, "inputs": [{"intent": "action.devices.SYNC"}]} with patch( "hass_nabucasa.Cloud._decode_claims", return_value={"cognito:username": "myUserName"}, ): await cloud.client.get_google_config() resp = await cloud.client.async_google_message(data) assert resp["requestId"] == reqid payload = resp["payload"] assert payload["agentUserId"] == "myUserName" devices = payload["devices"] assert len(devices) == 1 device = devices[0] assert device["id"] == "switch.test" assert device["name"]["name"] == "Config name" assert device["name"]["nicknames"] == ["Config name", "Config alias"] assert device["type"] == "action.devices.types.SWITCH" assert device["roomHint"] == "living room" async def test_handler_google_actions_disabled(hass, mock_cloud_fixture): """Test handler Google Actions when user has disabled it.""" mock_cloud_fixture._prefs[PREF_ENABLE_GOOGLE] = False with patch("hass_nabucasa.Cloud.start"): assert await async_setup_component(hass, "cloud", {}) reqid = "5711642932632160983" data = {"requestId": reqid, "inputs": [{"intent": "action.devices.SYNC"}]} cloud = hass.data["cloud"] resp = await cloud.client.async_google_message(data) assert resp["requestId"] == reqid assert resp["payload"]["errorCode"] == "deviceTurnedOff" async def test_webhook_msg(hass, caplog): """Test webhook msg.""" with patch("hass_nabucasa.Cloud.start"): setup = await async_setup_component(hass, "cloud", {"cloud": {}}) assert setup cloud = hass.data["cloud"] await cloud.client.prefs.async_initialize() await cloud.client.prefs.async_update( cloudhooks={ "mock-webhook-id": { "webhook_id": "mock-webhook-id", "cloudhook_id": "mock-cloud-id", }, "no-longere-existing": { "webhook_id": "no-longere-existing", "cloudhook_id": "mock-nonexisting-id", }, } ) received = [] async def handler(hass, webhook_id, request): """Handle a webhook.""" received.append(request) return web.json_response({"from": "handler"}) hass.components.webhook.async_register("test", "Test", "mock-webhook-id", handler) response = await cloud.client.async_webhook_message( { "cloudhook_id": "mock-cloud-id", "body": '{"hello": "world"}', "headers": {"content-type": "application/json"}, "method": "POST", "query": None, } ) assert response == { "status": 200, "body": '{"from": "handler"}', "headers": {"Content-Type": "application/json"}, } assert len(received) == 1 assert await received[0].json() == {"hello": "world"} # Non existing webhook caplog.clear() response = await cloud.client.async_webhook_message( { "cloudhook_id": "mock-nonexisting-id", "body": '{"nonexisting": "payload"}', "headers": {"content-type": "application/json"}, "method": "POST", "query": None, } ) assert response == { "status": 200, "body": None, "headers": {"Content-Type": "application/octet-stream"}, } assert ( "Received message for unregistered webhook no-longere-existing from cloud" in caplog.text ) assert '{"nonexisting": "payload"}' in caplog.text async def test_google_config_expose_entity(hass, mock_cloud_setup, mock_cloud_login): """Test Google config exposing entity method uses latest config.""" cloud_client = hass.data[DOMAIN].client state = State("light.kitchen", "on") gconf = await cloud_client.get_google_config() assert gconf.should_expose(state) await cloud_client.prefs.async_update_google_entity_config( entity_id="light.kitchen", should_expose=False ) assert not gconf.should_expose(state) async def test_google_config_should_2fa(hass, mock_cloud_setup, mock_cloud_login): """Test Google config disabling 2FA method uses latest config.""" cloud_client = hass.data[DOMAIN].client gconf = await cloud_client.get_google_config() state = State("light.kitchen", "on") assert gconf.should_2fa(state) await cloud_client.prefs.async_update_google_entity_config( entity_id="light.kitchen", disable_2fa=True ) assert not gconf.should_2fa(state) async def test_set_username(hass): """Test we set username during login.""" prefs = MagicMock( alexa_enabled=False, google_enabled=False, async_set_username=AsyncMock(return_value=None), ) client = CloudClient(hass, prefs, None, {}, {}) client.cloud = MagicMock(is_logged_in=True, username="mock-username") await client.logged_in() assert len(prefs.async_set_username.mock_calls) == 1 assert prefs.async_set_username.mock_calls[0][1][0] == "mock-username"
unknown
codeparrot/codeparrot-clean
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from ansible.utils.debug import debug class Group: ''' a group of ansible hosts ''' #__slots__ = [ 'name', 'hosts', 'vars', 'child_groups', 'parent_groups', 'depth', '_hosts_cache' ] def __init__(self, name=None): self.depth = 0 self.name = name self.hosts = [] self.vars = {} self.child_groups = [] self.parent_groups = [] self._hosts_cache = None #self.clear_hosts_cache() #if self.name is None: # raise Exception("group name is required") def __repr__(self): return self.get_name() def __getstate__(self): return self.serialize() def __setstate__(self, data): return self.deserialize(data) def serialize(self): parent_groups = [] for parent in self.parent_groups: parent_groups.append(parent.serialize()) result = dict( name=self.name, vars=self.vars.copy(), parent_groups=parent_groups, depth=self.depth, ) debug("serializing group, result is: %s" % result) return result def deserialize(self, data): debug("deserializing group, data is: %s" % data) self.__init__() self.name = data.get('name') self.vars = data.get('vars', dict()) parent_groups = data.get('parent_groups', []) for parent_data in parent_groups: g = Group() g.deserialize(parent_data) self.parent_groups.append(g) def get_name(self): return self.name def add_child_group(self, group): if self == group: raise Exception("can't add group to itself") # don't add if it's already there if not group in self.child_groups: self.child_groups.append(group) # update the depth of the child group.depth = max([self.depth+1, group.depth]) # update the depth of the grandchildren group._check_children_depth() # now add self to child's parent_groups list, but only if there # isn't already a group with the same name if not self.name in [g.name for g in group.parent_groups]: group.parent_groups.append(self) self.clear_hosts_cache() def _check_children_depth(self): for group in self.child_groups: group.depth = max([self.depth+1, group.depth]) group._check_children_depth() def add_host(self, host): self.hosts.append(host) host.add_group(self) self.clear_hosts_cache() def set_variable(self, key, value): self.vars[key] = value def clear_hosts_cache(self): self._hosts_cache = None for g in self.parent_groups: g.clear_hosts_cache() def get_hosts(self): if self._hosts_cache is None: self._hosts_cache = self._get_hosts() return self._hosts_cache def _get_hosts(self): hosts = [] seen = {} for kid in self.child_groups: kid_hosts = kid.get_hosts() for kk in kid_hosts: if kk not in seen: seen[kk] = 1 hosts.append(kk) for mine in self.hosts: if mine not in seen: seen[mine] = 1 hosts.append(mine) return hosts def get_vars(self): return self.vars.copy() def _get_ancestors(self): results = {} for g in self.parent_groups: results[g.name] = g results.update(g._get_ancestors()) return results def get_ancestors(self): return self._get_ancestors().values()
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python """ Module contingency_applicator.py deals wit non-boolean contingencies: - ! ---> absolutely required - x ---> absolutely inhibitory - k+ ---> positive stimulation - k- ---> negative stimulation - 0 ---> no effect - ? ---> unknown effect or no effect Contingencies 0 and ? are ignored. - ctype input ---> this is a special kind of contingency - molecules stay as they are but rate changes. Applies contingencies on: - molecules - complexes - reactions - reaction containers In the end contingency application means modification of molecule object (gets additional modification, bond ...). If contingency type is K+ or K- it also means duplication of a reaction and updating the rate for the new one. How rate is updated for K+/K-: - TODO: How to apply cont like A_P+_B; A--B """ from contingency_factory import ContingencyWrapper from rxnconcompiler.molecule.molecule import Molecule from rxnconcompiler.biological_complex.biological_complex import BiologicalComplex class ContingencyApplicator(): """ Applys contingency on - molecules - compelxes - reactions - reaction containers """ def __init__(self, war=None): self.war = war def apply_on_molecule(self, mol, cont, side = 'L'): """ Applys contingency on molecule. Side - indicates whether molecule belong to left or right substrate complex. It is important when we have homodimer states: indicates which domain is used. """ if (cont.state.type == 'Association' or cont.state.type == "Intraprotein") and cont.ctype == 'x': #mol.binding_sites.append(cont.state) mol.add_binding_site(cont.state, side) elif cont.state.type == 'Covalent Modification' and cont.ctype == '!': mol.add_modification(cont.state) elif cont.state.type == 'Covalent Modification' and cont.ctype == 'x': mol.add_modification_site(cont.state) elif cont.state.type == 'Relocalisation': mol.localisation = cont.state if cont.ctype == '!': cont.state.loc = True def add_molecule_to_complex(self, mols, cont, component, compl, reaction): """ mols - molecules that are present in complex and in contingency e.g. Complex: A, B, C; Cont: ! A--X ---> [A] cont - Contingency object, e.g. ! A--X component - the other component from contingency - one to be added e.g. X compl - complex reaction - reaction in question """ #print 'add_molecule_to_complex' #print mols, cont, component, compl # check whether contingency state in not equal to product state add_partner = True for state in mols[0].binding_sites: if state == cont.state: dom_cont = cont.state.get_component(mols[0].name).domain dom_side = state.get_component(mols[0].name).domain if dom_side == dom_cont: add_partner = False # check conflicts between contingency and to_change # (state that changes in the reaction) for comp_cont in cont.state.components: for comp_tochange in reaction.to_change.components: if comp_cont.exact_compare(comp_tochange): add_partner = False # check whether domain is not occupied new_mols = [] for mol in mols: occupied_doms = mol.get_domains('binding', True) if component.domain not in occupied_doms: new_mols.append(mol) mols = new_mols if not mols: add_partner = False if self.war: self.war.not_applied_contingencies.append(reaction) if add_partner: mols[0].binding_partners.append(cont.state) mol_ob = Molecule(component.name) mol_ob.binding_partners.append(cont.state) compl.molecules.append(mol_ob) def apply_positive_intraprotein(self, reaction, cont): """ it requires to set the binding_partners for the Intraprotein """ component = cont.state.components[0] left = reaction.get_substrate_complex('L') right = reaction.get_substrate_complex('R') left_right = reaction.get_substrate_complex('LR') if right.has_molecule(component.name) and not cont.state == reaction.to_change: side = right.side mol = right.get_molecules(component.name, component.cid) new_mols = [] occupied_doms = mol[0].get_domains('binding', True) if component.domain not in occupied_doms: new_mols.append(mol) if new_mols: mol[0].binding_partners.append(cont.state) def apply_positive_association(self, reaction, cont): """ it requires either - adding a new molecule to a complex - or incorporating two substrate complexes into one and not just editing existing molecules in a complex. It also needs to deal with a situation that there is already one complex. """ component1 = cont.state.components[0] component2 = cont.state.components[1] # situation when we need to join complexes left = reaction.get_substrate_complex('L') right = reaction.get_substrate_complex('R') left_right = reaction.get_substrate_complex('LR') if left_right: mols1 = left_right.get_molecules(component1.name, component1.cid) mols2 = left_right.get_molecules(component2.name, component2.cid) if mols1 and mols2: # what to do when two molecules are already in? # e.g. A.B + C ! A--B #print "PROBLEM", mols1, mols2 pass if mols1: self.add_molecule_to_complex(mols1, cont, component2, left_right, reaction) elif mols2: self.add_molecule_to_complex(mols2, cont, component1, left_right, reaction) elif left and right: # TODO: Refactor make a function to check this condition. # A--B, A and B present in substrates if ((left.has_molecule(component1.name) and right.has_molecule(component2.name))\ or (left.has_molecule(component2.name) and right.has_molecule(component1.name)))\ and not cont.state == reaction.to_change: if component1.name in [reaction.left_reactant.name, reaction.right_reactant.name] \ and component2.name in [reaction.left_reactant.name, reaction.right_reactant.name]: # if A--B, A and B present in substrates but if reaction creates A and B # we don't join. We want then A reaction.join_substrate_complexes(cont.state) # here one of mols from contingency is present in both complexes # but it was added because of previously applayed contingency so we dont want to join. else: if component1.name == reaction.left_reactant.name \ or component2.name == reaction.left_reactant.name: self._add_components_to_complex(left, component1, component2, cont, reaction) else: self._add_components_to_complex(right, component1, component2, cont, reaction) # a molecule needs to be added to complexes # or complexes are already joined: else: for compl in reaction.substrat_complexes: self._add_components_to_complex(compl, component1, component2, cont, reaction) def _add_components_to_complex(self, compl, component1, component2, cont, reaction): """ Helper function. Checks which component is already in the complex and adds the second one. What to do when both are already present??? (Not decided yet). """ mols1 = compl.get_molecules(component1.name, component1.cid) mols2 = compl.get_molecules(component2.name, component2.cid) if mols1 and mols2: # what to do when two molecules are already in? # e.g. A.B + C ! A--B #print "PROBLEM", mols1, mols2 pass if mols1: self.add_molecule_to_complex(mols1, cont, component2, compl, reaction) elif mols2: self.add_molecule_to_complex(mols2, cont, component1, compl, reaction) def apply_on_complex(self, compl, cont): """ Positive association won't get here. """ if cont.state.type == 'Association': # only negative associations get here. side = compl.side for component in cont.state.components: mols = compl.get_molecules(component.name, component.cid) if mols: self.apply_on_molecule(mols[0], cont, side) else: component = cont.state.components[0] mols = compl.get_molecules(component.name, component.cid) if mols: self.apply_on_molecule(mols[0], cont) def apply_on_reaction(self, reaction, cont): """ Gets reaction and x or ! contingency. For ! contingencies with input state creates additional substrate complex. For other states applays contingency on substrate complexes. """ for compl in reaction.substrat_complexes: self.apply_on_complex(compl, cont) def apply_input_on_container(self, container, cont): """ Applys all input contingencies. Input contingency is applied by changing reaction rate (adding a local function). Rate depend on: - contingency type: different functions for !, x and K - whether reaction is reversible or irreversible (for reversible reaction kr always looks like for K even when its ! or x) Different rate function types: - k1*k_Input ---> function for ! [Input] - k1*(1-k_Input) ---> function for x [Input] - k1_1*(1-k_Input)+k1_2*k_Input ---> for K+/K- and all reversed reactions (complex must be able to dissociate even when input is not present an more) """ # establish new ids for rates - num1, num2 highest_subrate = container.highest_subrate # int if highest_subrate == 0: num1 = '%s_1' % container.rid num2 = '%s_2' % container.rid else: num1 = '%s_%s' % (container.rid, str(highest_subrate + 1)) num2 = '%s_%s' % (container.rid, str(highest_subrate + 2)) if cont.ctype in ['x', '!']: for reaction in container: if reaction.definition['Reversibility'] == 'reversible': # we will have two rates here (because of reverse reaction). reaction.rate.update_function(cont, False, num1, num2) else: # just multiply old rate by input rate. # We don't need new rate numbers here. # Because it is still one rate. rate_id = reaction.rate.get_ids()[0] reaction.rate.update_function(cont, False, rate_id, None) elif 'k' in cont.ctype: # here input rate is a switch between two rates. for reaction in container: reaction.rate.update_function(cont, True, num1, num2) def get_rate_ids(self, reaction, container, subrate, keep_old=False): """ When applying K+/K- contingency rates need to be updated. This function returns a list of new ids which will be used for updating. e.g. ['1', None] ['3_5', '3_6'] """ # TODO: Does this function belongs here? single_id = lambda container, old_id, subrate: '%s_%s' % (container.rid, str(int(old_id.split('_')[1]) + subrate)) # Trys to keep old id if possible if keep_old: if subrate == 0: return ['%s_1' % container.rid, None] else: old_ids = reaction.rate.get_ids() if len(old_ids) == 1: return [old_ids[0], None] else: return old_ids else: if subrate == 0: return ['%s_2' % container.rid, None] else: old_ids = reaction.rate.get_ids() if len(old_ids) == 1: return [single_id(container, old_ids[0], subrate), None] else: return [single_id(container, old_ids[0], subrate), single_id(container, old_ids[1], subrate)] def apply_on_container(self, container, cont): """ Applys a contingency on a container. Top level function. It is called first and directs tasks to other functions. --- If contingency contains Input state: apply_input_on_container --- If ctype x or ! (no Input): apply_on_reaction --- If contingency state is Association then: apply_positive_association --- If ctype is K+ or K- (no Input): clone all the reactions in the container for each reaction (now two) apply one ! and one x (it is done like in previous step). Updates rate: reaction.rate.update_name Only normal contingencies are applied here. """ # TODO: some ugly stuff here - refactor. # emptying container and adding them again to get consistent ids. # Remove some iterations. # Input contingencies are handled by adding function to reaction rate. if cont.state.type == 'Input': self.apply_input_on_container(container, cont) elif cont.ctype in ['x', '!']: for reaction in container: if cont.state.type == 'Association' and cont.ctype == '!': self.apply_positive_association(reaction, cont) elif cont.state.type == "Intraprotein" and cont.ctype == '!': self.apply_positive_intraprotein(reaction,cont) else: self.apply_on_reaction(reaction, cont) elif 'k' in cont.ctype: #rate_dict = self.prepare_rates_dict() temp = [] pos_cont = ContingencyWrapper(cont, 'positive').get_contingency() neg_cont = ContingencyWrapper(cont, 'negative').get_contingency() subrate = container.highest_subrate for reaction in container: temp.append(reaction.clone()) temp2 = [] #print 'Len:', len(container) for reaction in container: #print 'Reaction in orig container:', reaction.substrat_complexes[0].molecules[0].modifications, reaction.substrat_complexes[0].molecules[0].modification_sites #print 'Mod before cloning', reaction.substrat_complexes[0].molecules[0].modifications #print 'Mod site before cloning', reaction.substrat_complexes[0].molecules[0].modification_sites reaction = reaction.clone() #print 'Mod after cloning', reaction.substrat_complexes[0].molecules[0].modifications #print 'Mod site after cloning', reaction.substrat_complexes[0].molecules[0].modification_sites if cont.state.type == 'Association': self.apply_positive_association(reaction, pos_cont) else: ############### BUG self.apply_on_reaction(reaction, pos_cont) #print 'After applying:', reaction.substrat_complexes[0].molecules[0].modifications, reaction.substrat_complexes[0].molecules[0].modification_sites new_rate_ids = self.get_rate_ids(reaction, container, subrate, True) reaction.rate.update_name(new_rate_ids[0], new_rate_ids[1]) temp2.append(reaction) #for reaction in temp2: # print 'Reaction in temp2:', reaction.substrat_complexes[0].molecules[0].modifications, reaction.substrat_complexes[0].molecules[0].modification_sites container.empty() for reaction in temp2: container.add_reaction(reaction) for reaction in temp: self.apply_on_reaction(reaction, neg_cont) container.add_reaction(reaction) new_rate_ids = self.get_rate_ids(reaction, container, subrate, False) reaction.rate.update_name(new_rate_ids[0], new_rate_ids[1])
unknown
codeparrot/codeparrot-clean
from __future__ import unicode_literals from django.db import models from breach.helpers import injector from django.utils import timezone class Victim(models.Model): ''' A particular instance of a target for a particular user-victim e.g. dionyziz@gmail.com ''' def attack(self): injector.inject(self) @property def percentage(self): rounds = self.round_set.all() round_details = sorted(list(rounds.values('knownsecret'))) try: return "{:.2f}".format((len(round_details[len(round_details) - 1]['knownsecret']) / self.target.secretlength) * 100) except: return '0' @property def running_time(self): return (timezone.now() - self.attacked_at).total_seconds() def delete(self): self.trashed_at = timezone.now() self.save() def restore(self): self.trashed_at = None self.save() target = models.ForeignKey('breach.Target', null=True, blank=True) snifferendpoint = models.CharField( default='http://127.0.0.1:9000', max_length=255, help_text=("The HTTP endpoint of the adversarial sniffer running on " "the victim's network which is listening for our HTTP " "requests. This endpoint must include the 'http://' " "prefix.") ) sourceip = models.GenericIPAddressField( help_text='Source IP on the local network, e.g. 192.168.10.140' ) trashed_at = models.DateTimeField( blank=True, null=True, help_text=('The datatime of the delete request.') ) interface = models.CharField( default='wlan0', max_length=255, help_text=("Attacking machine's interface that is on the victim's " "network.") ) state = models.CharField( default='discovered', max_length=255, help_text=("The state of the attack. Possible values are" "'discovered', 'completed', 'running', 'paused' ") ) attacked_at = models.DateTimeField( default=timezone.now, max_length=255, help_text=("The start time of the attack") ) realtimeurl = models.CharField( default='http://localhost:3031', max_length=255, help_text=("The realtime module URL that the client should " "communicate with. This URL must include the " "'http://' prefix.") ) calibration_wait = models.FloatField( default=0.0, help_text=('The amount of time in seconds that sniffer should wait ' 'so that Scapy has enough time to lock on low-level network ' 'resources.') ) recordscardinality = models.IntegerField( default=0, help_text=('The amount of expected TLS response records per request. ' 'If 0 then the amount is not known or is expected to ' 'change per request.') )
unknown
codeparrot/codeparrot-clean
# Copyright 2019 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. # ============================================================================== """DataAdapter tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from absl.testing import parameterized import numpy as np from tensorflow.python import keras from tensorflow.python.data.experimental.ops import cardinality from tensorflow.python.data.ops import dataset_ops from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.keras import keras_parameterized from tensorflow.python.keras import testing_utils from tensorflow.python.keras.engine import data_adapter from tensorflow.python.keras.utils import data_utils from tensorflow.python.ops import array_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.platform import test from tensorflow.python.util import nest class DummyArrayLike(object): """Dummy array-like object.""" def __init__(self, data): self.data = data def __len__(self): return len(self.data) def __getitem__(self, key): return self.data[key] @property def shape(self): return self.data.shape @property def dtype(self): return self.data.dtype def fail_on_convert(x, **kwargs): _ = x _ = kwargs raise TypeError('Cannot convert DummyArrayLike to a tensor') ops.register_tensor_conversion_function(DummyArrayLike, fail_on_convert) class DataAdapterTestBase(keras_parameterized.TestCase): def setUp(self): super(DataAdapterTestBase, self).setUp() self.batch_size = 5 self.numpy_input = np.zeros((50, 10)) self.numpy_target = np.ones(50) self.tensor_input = constant_op.constant(2.0, shape=(50, 10)) self.tensor_target = array_ops.ones((50,)) self.arraylike_input = DummyArrayLike(self.numpy_input) self.arraylike_target = DummyArrayLike(self.numpy_target) self.dataset_input = dataset_ops.DatasetV2.from_tensor_slices( (self.numpy_input, self.numpy_target)).shuffle(50).batch( self.batch_size) def generator(): while True: yield (np.zeros((self.batch_size, 10)), np.ones(self.batch_size)) self.generator_input = generator() self.iterator_input = data_utils.threadsafe_generator(generator)() self.sequence_input = TestSequence(batch_size=self.batch_size, feature_shape=10) self.text_input = [['abc']] self.bytes_input = [[b'abc']] self.model = keras.models.Sequential( [keras.layers.Dense(8, input_shape=(10,), activation='softmax')]) class TestSequence(data_utils.Sequence): def __init__(self, batch_size, feature_shape): self.batch_size = batch_size self.feature_shape = feature_shape def __getitem__(self, item): return (np.zeros((self.batch_size, self.feature_shape)), np.ones((self.batch_size,))) def __len__(self): return 10 class TensorLikeDataAdapterTest(DataAdapterTestBase): def setUp(self): super(TensorLikeDataAdapterTest, self).setUp() self.adapter_cls = data_adapter.TensorLikeDataAdapter def test_can_handle_numpy(self): self.assertTrue(self.adapter_cls.can_handle(self.numpy_input)) self.assertTrue( self.adapter_cls.can_handle(self.numpy_input, self.numpy_target)) self.assertFalse(self.adapter_cls.can_handle(self.dataset_input)) self.assertFalse(self.adapter_cls.can_handle(self.generator_input)) self.assertFalse(self.adapter_cls.can_handle(self.sequence_input)) self.assertFalse(self.adapter_cls.can_handle(self.text_input)) self.assertFalse(self.adapter_cls.can_handle(self.bytes_input)) def test_size_numpy(self): adapter = self.adapter_cls( self.numpy_input, self.numpy_target, batch_size=5) self.assertEqual(adapter.get_size(), 10) self.assertFalse(adapter.has_partial_batch()) def test_batch_size_numpy(self): adapter = self.adapter_cls( self.numpy_input, self.numpy_target, batch_size=5) self.assertEqual(adapter.batch_size(), 5) def test_partial_batch_numpy(self): adapter = self.adapter_cls( self.numpy_input, self.numpy_target, batch_size=4) self.assertEqual(adapter.get_size(), 13) # 50/4 self.assertTrue(adapter.has_partial_batch()) self.assertEqual(adapter.partial_batch_size(), 2) def test_epochs(self): num_epochs = 3 adapter = self.adapter_cls( self.numpy_input, self.numpy_target, batch_size=5, epochs=num_epochs) ds_iter = iter(adapter.get_dataset()) num_batches_per_epoch = self.numpy_input.shape[0] // 5 for _ in range(num_batches_per_epoch * num_epochs): next(ds_iter) with self.assertRaises(StopIteration): next(ds_iter) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_training_numpy(self): self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(self.numpy_input, self.numpy_target, batch_size=5) def test_can_handle_pandas(self): try: import pandas as pd # pylint: disable=g-import-not-at-top except ImportError: self.skipTest('Skipping test because pandas is not installed.') self.assertTrue(self.adapter_cls.can_handle(pd.DataFrame(self.numpy_input))) self.assertTrue( self.adapter_cls.can_handle(pd.DataFrame(self.numpy_input)[0])) self.assertTrue( self.adapter_cls.can_handle( pd.DataFrame(self.numpy_input), pd.DataFrame(self.numpy_input)[0])) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_training_pandas(self): try: import pandas as pd # pylint: disable=g-import-not-at-top except ImportError: self.skipTest('Skipping test because pandas is not installed.') input_a = keras.Input(shape=(3,), name='input_a') input_b = keras.Input(shape=(3,), name='input_b') input_c = keras.Input(shape=(1,), name='input_b') x = keras.layers.Dense(4, name='dense_1')(input_a) y = keras.layers.Dense(3, name='dense_2')(input_b) z = keras.layers.Dense(1, name='dense_3')(input_c) model_1 = keras.Model(inputs=input_a, outputs=x) model_2 = keras.Model(inputs=[input_a, input_b], outputs=[x, y]) model_3 = keras.Model(inputs=input_c, outputs=z) model_1.compile(optimizer='rmsprop', loss='mse') model_2.compile(optimizer='rmsprop', loss='mse') input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) input_a_df = pd.DataFrame(input_a_np) input_b_df = pd.DataFrame(input_b_np) output_a_df = pd.DataFrame(np.random.random((10, 4))) output_b_df = pd.DataFrame(np.random.random((10, 3))) model_1.fit(input_a_df, output_a_df) model_2.fit([input_a_df, input_b_df], [output_a_df, output_b_df]) model_1.fit([input_a_df], [output_a_df]) model_1.fit({'input_a': input_a_df}, output_a_df) model_2.fit({'input_a': input_a_df, 'input_b': input_b_df}, [output_a_df, output_b_df]) model_1.evaluate(input_a_df, output_a_df) model_2.evaluate([input_a_df, input_b_df], [output_a_df, output_b_df]) model_1.evaluate([input_a_df], [output_a_df]) model_1.evaluate({'input_a': input_a_df}, output_a_df) model_2.evaluate({'input_a': input_a_df, 'input_b': input_b_df}, [output_a_df, output_b_df]) # Verify predicting on pandas vs numpy returns the same result predict_1_pandas = model_1.predict(input_a_df) predict_2_pandas = model_2.predict([input_a_df, input_b_df]) predict_3_pandas = model_3.predict(input_a_df[0]) predict_1_numpy = model_1.predict(input_a_np) predict_2_numpy = model_2.predict([input_a_np, input_b_np]) predict_3_numpy = model_3.predict(np.asarray(input_a_df[0])) self.assertAllClose(predict_1_numpy, predict_1_pandas) self.assertAllClose(predict_2_numpy, predict_2_pandas) self.assertAllClose(predict_3_numpy, predict_3_pandas) # Extra ways to pass in dataframes model_1.predict([input_a_df]) model_1.predict({'input_a': input_a_df}) model_2.predict({'input_a': input_a_df, 'input_b': input_b_df}) def test_can_handle(self): self.assertTrue(self.adapter_cls.can_handle(self.tensor_input)) self.assertTrue( self.adapter_cls.can_handle(self.tensor_input, self.tensor_target)) self.assertFalse(self.adapter_cls.can_handle(self.arraylike_input)) self.assertFalse( self.adapter_cls.can_handle(self.arraylike_input, self.arraylike_target)) self.assertFalse(self.adapter_cls.can_handle(self.dataset_input)) self.assertFalse(self.adapter_cls.can_handle(self.generator_input)) self.assertFalse(self.adapter_cls.can_handle(self.sequence_input)) self.assertFalse(self.adapter_cls.can_handle(self.text_input)) self.assertFalse(self.adapter_cls.can_handle(self.bytes_input)) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_training(self): self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(self.tensor_input, self.tensor_target, batch_size=5) def test_size(self): adapter = self.adapter_cls( self.tensor_input, self.tensor_target, batch_size=5) self.assertEqual(adapter.get_size(), 10) self.assertFalse(adapter.has_partial_batch()) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_shuffle_correctness(self): num_samples = 100 batch_size = 32 x = np.arange(num_samples) np.random.seed(99) adapter = self.adapter_cls( x, y=None, batch_size=batch_size, shuffle=True, epochs=2) def _get_epoch(ds_iter): ds_data = [] for _ in range(int(math.ceil(num_samples / batch_size))): ds_data.append(next(ds_iter).numpy()) return np.concatenate(ds_data) ds_iter = iter(adapter.get_dataset()) # First epoch. epoch_data = _get_epoch(ds_iter) # Check that shuffling occurred. self.assertNotAllClose(x, epoch_data) # Check that each elements appears, and only once. self.assertAllClose(x, np.sort(epoch_data)) # Second epoch. second_epoch_data = _get_epoch(ds_iter) # Check that shuffling occurred. self.assertNotAllClose(x, second_epoch_data) # Check that shuffling is different across epochs. self.assertNotAllClose(epoch_data, second_epoch_data) # Check that each elements appears, and only once. self.assertAllClose(x, np.sort(second_epoch_data)) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_batch_shuffle_correctness(self): num_samples = 100 batch_size = 6 x = np.arange(num_samples) np.random.seed(99) adapter = self.adapter_cls( x, y=None, batch_size=batch_size, shuffle='batch', epochs=2) def _get_epoch_batches(ds_iter): ds_data = [] for _ in range(int(math.ceil(num_samples / batch_size))): ds_data.append(next(ds_iter)[0].numpy()) return ds_data ds_iter = iter(adapter.get_dataset()) # First epoch. epoch_batch_data = _get_epoch_batches(ds_iter) epoch_data = np.concatenate(epoch_batch_data) def _verify_batch(batch): # Verify that a batch contains only contiguous data, and that it has # been shuffled. shuffled_batch = np.sort(batch) self.assertNotAllClose(batch, shuffled_batch) for i in range(1, len(batch)): self.assertEqual(shuffled_batch[i-1] + 1, shuffled_batch[i]) # Assert that the data within each batch remains contiguous for batch in epoch_batch_data: _verify_batch(batch) # Check that individual batches are unshuffled # Check that shuffling occurred. self.assertNotAllClose(x, epoch_data) # Check that each elements appears, and only once. self.assertAllClose(x, np.sort(epoch_data)) # Second epoch. second_epoch_batch_data = _get_epoch_batches(ds_iter) second_epoch_data = np.concatenate(second_epoch_batch_data) # Assert that the data within each batch remains contiguous for batch in second_epoch_batch_data: _verify_batch(batch) # Check that shuffling occurred. self.assertNotAllClose(x, second_epoch_data) # Check that shuffling is different across epochs. self.assertNotAllClose(epoch_data, second_epoch_data) # Check that each elements appears, and only once. self.assertAllClose(x, np.sort(second_epoch_data)) @parameterized.named_parameters( ('batch_size_5', 5, None, 5), ('batch_size_50', 50, 4, 50), # Sanity check: batch_size takes precedence ('steps_1', None, 1, 50), ('steps_4', None, 4, 13), ) def test_batch_size(self, batch_size_in, steps, batch_size_out): adapter = self.adapter_cls( self.tensor_input, self.tensor_target, batch_size=batch_size_in, steps=steps) self.assertEqual(adapter.batch_size(), batch_size_out) @parameterized.named_parameters( ('batch_size_5', 5, None, 10, 0), ('batch_size_4', 4, None, 13, 2), ('steps_1', None, 1, 1, 0), ('steps_5', None, 5, 5, 0), ('steps_4', None, 4, 4, 11), ) def test_partial_batch( self, batch_size_in, steps, size, partial_batch_size): adapter = self.adapter_cls( self.tensor_input, self.tensor_target, batch_size=batch_size_in, steps=steps) self.assertEqual(adapter.get_size(), size) # 50/steps self.assertEqual(adapter.has_partial_batch(), bool(partial_batch_size)) self.assertEqual(adapter.partial_batch_size(), partial_batch_size or None) class GenericArrayLikeDataAdapterTest(DataAdapterTestBase): def setUp(self): super(GenericArrayLikeDataAdapterTest, self).setUp() self.adapter_cls = data_adapter.GenericArrayLikeDataAdapter def test_can_handle_some_numpy(self): self.assertTrue(self.adapter_cls.can_handle( self.arraylike_input)) self.assertTrue( self.adapter_cls.can_handle(self.arraylike_input, self.arraylike_target)) # Because adapters are mutually exclusive, don't handle cases # where all the data is numpy or an eagertensor self.assertFalse(self.adapter_cls.can_handle(self.numpy_input)) self.assertFalse( self.adapter_cls.can_handle(self.numpy_input, self.numpy_target)) self.assertFalse(self.adapter_cls.can_handle(self.tensor_input)) self.assertFalse( self.adapter_cls.can_handle(self.tensor_input, self.tensor_target)) # But do handle mixes that include generic arraylike data self.assertTrue( self.adapter_cls.can_handle(self.numpy_input, self.arraylike_target)) self.assertTrue( self.adapter_cls.can_handle(self.arraylike_input, self.numpy_target)) self.assertTrue( self.adapter_cls.can_handle(self.arraylike_input, self.tensor_target)) self.assertTrue( self.adapter_cls.can_handle(self.tensor_input, self.arraylike_target)) self.assertFalse(self.adapter_cls.can_handle(self.dataset_input)) self.assertFalse(self.adapter_cls.can_handle(self.generator_input)) self.assertFalse(self.adapter_cls.can_handle(self.sequence_input)) self.assertFalse(self.adapter_cls.can_handle(self.text_input)) self.assertFalse(self.adapter_cls.can_handle(self.bytes_input)) def test_size(self): adapter = self.adapter_cls( self.arraylike_input, self.arraylike_target, batch_size=5) self.assertEqual(adapter.get_size(), 10) self.assertFalse(adapter.has_partial_batch()) def test_epochs(self): num_epochs = 3 adapter = self.adapter_cls( self.arraylike_input, self.numpy_target, batch_size=5, epochs=num_epochs) ds_iter = iter(adapter.get_dataset()) num_batches_per_epoch = self.numpy_input.shape[0] // 5 for _ in range(num_batches_per_epoch * num_epochs): next(ds_iter) with self.assertRaises(StopIteration): next(ds_iter) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_training(self): # First verify that DummyArrayLike can't be converted to a Tensor with self.assertRaises(TypeError): ops.convert_to_tensor_v2_with_dispatch(self.arraylike_input) # Then train on the array like. # It should not be converted to a tensor directly (which would force it into # memory), only the sliced data should be converted. self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(self.arraylike_input, self.arraylike_target, batch_size=5) self.model.fit(self.arraylike_input, self.arraylike_target, shuffle=True, batch_size=5) self.model.fit(self.arraylike_input, self.arraylike_target, shuffle='batch', batch_size=5) self.model.evaluate(self.arraylike_input, self.arraylike_target, batch_size=5) self.model.predict(self.arraylike_input, batch_size=5) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_training_numpy_target(self): self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(self.arraylike_input, self.numpy_target, batch_size=5) self.model.fit(self.arraylike_input, self.numpy_target, shuffle=True, batch_size=5) self.model.fit(self.arraylike_input, self.numpy_target, shuffle='batch', batch_size=5) self.model.evaluate(self.arraylike_input, self.numpy_target, batch_size=5) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_training_tensor_target(self): self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(self.arraylike_input, self.tensor_target, batch_size=5) self.model.fit(self.arraylike_input, self.tensor_target, shuffle=True, batch_size=5) self.model.fit(self.arraylike_input, self.tensor_target, shuffle='batch', batch_size=5) self.model.evaluate(self.arraylike_input, self.tensor_target, batch_size=5) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_shuffle_correctness(self): num_samples = 100 batch_size = 32 x = DummyArrayLike(np.arange(num_samples)) np.random.seed(99) adapter = self.adapter_cls( x, y=None, batch_size=batch_size, shuffle=True, epochs=2) def _get_epoch(ds_iter): ds_data = [] for _ in range(int(math.ceil(num_samples / batch_size))): ds_data.append(next(ds_iter).numpy()) return np.concatenate(ds_data) ds_iter = iter(adapter.get_dataset()) # First epoch. epoch_data = _get_epoch(ds_iter) # Check that shuffling occurred. self.assertNotAllClose(x, epoch_data) # Check that each elements appears, and only once. self.assertAllClose(x, np.sort(epoch_data)) # Second epoch. second_epoch_data = _get_epoch(ds_iter) # Check that shuffling occurred. self.assertNotAllClose(x, second_epoch_data) # Check that shuffling is different across epochs. self.assertNotAllClose(epoch_data, second_epoch_data) # Check that each elements appears, and only once. self.assertAllClose(x, np.sort(second_epoch_data)) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_batch_shuffle_correctness(self): num_samples = 100 batch_size = 6 x = DummyArrayLike(np.arange(num_samples)) np.random.seed(99) adapter = self.adapter_cls( x, y=None, batch_size=batch_size, shuffle='batch', epochs=2) def _get_epoch_batches(ds_iter): ds_data = [] for _ in range(int(math.ceil(num_samples / batch_size))): ds_data.append(next(ds_iter)[0].numpy()) return ds_data ds_iter = iter(adapter.get_dataset()) # First epoch. epoch_batch_data = _get_epoch_batches(ds_iter) epoch_data = np.concatenate(epoch_batch_data) def _verify_batch(batch): # Verify that a batch contains only contiguous data, but that it has # been shuffled. shuffled_batch = np.sort(batch) self.assertNotAllClose(batch, shuffled_batch) for i in range(1, len(batch)): self.assertEqual(shuffled_batch[i-1] + 1, shuffled_batch[i]) # Assert that the data within each batch is shuffled contiguous data for batch in epoch_batch_data: _verify_batch(batch) # Check that individual batches are unshuffled # Check that shuffling occurred. self.assertNotAllClose(x, epoch_data) # Check that each elements appears, and only once. self.assertAllClose(x, np.sort(epoch_data)) # Second epoch. second_epoch_batch_data = _get_epoch_batches(ds_iter) second_epoch_data = np.concatenate(second_epoch_batch_data) # Assert that the data within each batch remains contiguous for batch in second_epoch_batch_data: _verify_batch(batch) # Check that shuffling occurred. self.assertNotAllClose(x, second_epoch_data) # Check that shuffling is different across epochs. self.assertNotAllClose(epoch_data, second_epoch_data) # Check that each elements appears, and only once. self.assertAllClose(x, np.sort(second_epoch_data)) @parameterized.named_parameters( ('batch_size_5', 5, None, 5), ('batch_size_50', 50, 4, 50), # Sanity check: batch_size takes precedence ('steps_1', None, 1, 50), ('steps_4', None, 4, 13), ) def test_batch_size(self, batch_size_in, steps, batch_size_out): adapter = self.adapter_cls( self.arraylike_input, self.arraylike_target, batch_size=batch_size_in, steps=steps) self.assertEqual(adapter.batch_size(), batch_size_out) @parameterized.named_parameters( ('batch_size_5', 5, None, 10, 0), ('batch_size_4', 4, None, 13, 2), ('steps_1', None, 1, 1, 0), ('steps_5', None, 5, 5, 0), ('steps_4', None, 4, 4, 11), ) def test_partial_batch( self, batch_size_in, steps, size, partial_batch_size): adapter = self.adapter_cls( self.arraylike_input, self.arraylike_target, batch_size=batch_size_in, steps=steps) self.assertEqual(adapter.get_size(), size) # 50/steps self.assertEqual(adapter.has_partial_batch(), bool(partial_batch_size)) self.assertEqual(adapter.partial_batch_size(), partial_batch_size or None) class DatasetAdapterTest(DataAdapterTestBase): def setUp(self): super(DatasetAdapterTest, self).setUp() self.adapter_cls = data_adapter.DatasetAdapter def test_can_handle(self): self.assertFalse(self.adapter_cls.can_handle(self.numpy_input)) self.assertFalse(self.adapter_cls.can_handle(self.tensor_input)) self.assertTrue(self.adapter_cls.can_handle(self.dataset_input)) self.assertFalse(self.adapter_cls.can_handle(self.generator_input)) self.assertFalse(self.adapter_cls.can_handle(self.sequence_input)) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_training(self): dataset = self.adapter_cls(self.dataset_input).get_dataset() self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(dataset) def test_size(self): adapter = self.adapter_cls(self.dataset_input) self.assertIsNone(adapter.get_size()) def test_batch_size(self): adapter = self.adapter_cls(self.dataset_input) self.assertIsNone(adapter.batch_size()) def test_partial_batch(self): adapter = self.adapter_cls(self.dataset_input) self.assertFalse(adapter.has_partial_batch()) self.assertIsNone(adapter.partial_batch_size()) def test_invalid_targets_argument(self): with self.assertRaisesRegex(ValueError, r'`y` argument is not supported'): self.adapter_cls(self.dataset_input, y=self.dataset_input) def test_invalid_sample_weights_argument(self): with self.assertRaisesRegex(ValueError, r'`sample_weight` argument is not supported'): self.adapter_cls(self.dataset_input, sample_weights=self.dataset_input) class GeneratorDataAdapterTest(DataAdapterTestBase): def setUp(self): super(GeneratorDataAdapterTest, self).setUp() self.adapter_cls = data_adapter.GeneratorDataAdapter def test_can_handle(self): self.assertFalse(self.adapter_cls.can_handle(self.numpy_input)) self.assertFalse(self.adapter_cls.can_handle(self.tensor_input)) self.assertFalse(self.adapter_cls.can_handle(self.dataset_input)) self.assertTrue(self.adapter_cls.can_handle(self.generator_input)) self.assertFalse(self.adapter_cls.can_handle(self.sequence_input)) self.assertFalse(self.adapter_cls.can_handle(self.text_input)) self.assertFalse(self.adapter_cls.can_handle(self.bytes_input)) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_training(self): self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(self.generator_input, steps_per_epoch=10) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) @testing_utils.run_v2_only @data_utils.dont_use_multiprocessing_pool def test_with_multiprocessing_training(self): self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(self.iterator_input, workers=1, use_multiprocessing=True, max_queue_size=10, steps_per_epoch=10) # Fit twice to ensure there isn't any duplication that prevent the worker # from starting. self.model.fit(self.iterator_input, workers=1, use_multiprocessing=True, max_queue_size=10, steps_per_epoch=10) def test_size(self): adapter = self.adapter_cls(self.generator_input) self.assertIsNone(adapter.get_size()) def test_batch_size(self): adapter = self.adapter_cls(self.generator_input) self.assertEqual(adapter.batch_size(), None) self.assertEqual(adapter.representative_batch_size(), 5) def test_partial_batch(self): adapter = self.adapter_cls(self.generator_input) self.assertFalse(adapter.has_partial_batch()) self.assertIsNone(adapter.partial_batch_size()) def test_invalid_targets_argument(self): with self.assertRaisesRegex(ValueError, r'`y` argument is not supported'): self.adapter_cls(self.generator_input, y=self.generator_input) def test_invalid_sample_weights_argument(self): with self.assertRaisesRegex(ValueError, r'`sample_weight` argument is not supported'): self.adapter_cls( self.generator_input, sample_weights=self.generator_input) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_not_shuffled(self): def generator(): for i in range(10): yield np.ones((1, 1)) * i adapter = self.adapter_cls(generator(), shuffle=True) for i, data in enumerate(adapter.get_dataset()): self.assertEqual(i, data[0].numpy().flatten()) class KerasSequenceAdapterTest(DataAdapterTestBase): def setUp(self): super(KerasSequenceAdapterTest, self).setUp() self.adapter_cls = data_adapter.KerasSequenceAdapter def test_can_handle(self): self.assertFalse(self.adapter_cls.can_handle(self.numpy_input)) self.assertFalse(self.adapter_cls.can_handle(self.tensor_input)) self.assertFalse(self.adapter_cls.can_handle(self.dataset_input)) self.assertFalse(self.adapter_cls.can_handle(self.generator_input)) self.assertTrue(self.adapter_cls.can_handle(self.sequence_input)) self.assertFalse(self.adapter_cls.can_handle(self.text_input)) self.assertFalse(self.adapter_cls.can_handle(self.bytes_input)) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) def test_training(self): self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(self.sequence_input) @keras_parameterized.run_all_keras_modes(always_skip_v1=True) @testing_utils.run_v2_only @data_utils.dont_use_multiprocessing_pool def test_with_multiprocessing_training(self): self.model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', run_eagerly=testing_utils.should_run_eagerly()) self.model.fit(self.sequence_input, workers=1, use_multiprocessing=True, max_queue_size=10, steps_per_epoch=10) # Fit twice to ensure there isn't any duplication that prevent the worker # from starting. self.model.fit(self.sequence_input, workers=1, use_multiprocessing=True, max_queue_size=10, steps_per_epoch=10) def test_size(self): adapter = self.adapter_cls(self.sequence_input) self.assertEqual(adapter.get_size(), 10) def test_batch_size(self): adapter = self.adapter_cls(self.sequence_input) self.assertEqual(adapter.batch_size(), None) self.assertEqual(adapter.representative_batch_size(), 5) def test_partial_batch(self): adapter = self.adapter_cls(self.sequence_input) self.assertFalse(adapter.has_partial_batch()) self.assertIsNone(adapter.partial_batch_size()) def test_invalid_targets_argument(self): with self.assertRaisesRegex(ValueError, r'`y` argument is not supported'): self.adapter_cls(self.sequence_input, y=self.sequence_input) def test_invalid_sample_weights_argument(self): with self.assertRaisesRegex(ValueError, r'`sample_weight` argument is not supported'): self.adapter_cls(self.sequence_input, sample_weights=self.sequence_input) class DataHandlerTest(keras_parameterized.TestCase): def test_finite_dataset_with_steps_per_epoch(self): data = dataset_ops.Dataset.from_tensor_slices([0, 1, 2, 3]).batch(1) # User can choose to only partially consume `Dataset`. data_handler = data_adapter.DataHandler( data, initial_epoch=0, epochs=2, steps_per_epoch=2) self.assertEqual(data_handler.inferred_steps, 2) self.assertFalse(data_handler._adapter.should_recreate_iterator()) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): epoch_data.append(next(iterator).numpy()) returned_data.append(epoch_data) self.assertEqual(returned_data, [[0, 1], [2, 3]]) def test_finite_dataset_without_steps_per_epoch(self): data = dataset_ops.Dataset.from_tensor_slices([0, 1, 2]).batch(1) data_handler = data_adapter.DataHandler(data, initial_epoch=0, epochs=2) self.assertEqual(data_handler.inferred_steps, 3) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): epoch_data.append(next(iterator).numpy()) returned_data.append(epoch_data) self.assertEqual(returned_data, [[0, 1, 2], [0, 1, 2]]) def test_finite_dataset_with_steps_per_epoch_exact_size(self): data = dataset_ops.Dataset.from_tensor_slices([0, 1, 2, 3]).batch(1) # If user specifies exact size of `Dataset` as `steps_per_epoch`, # create a new iterator each epoch. data_handler = data_adapter.DataHandler( data, initial_epoch=0, epochs=2, steps_per_epoch=4) self.assertTrue(data_handler._adapter.should_recreate_iterator()) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): epoch_data.append(next(iterator).numpy()) returned_data.append(epoch_data) self.assertEqual(returned_data, [[0, 1, 2, 3], [0, 1, 2, 3]]) def test_infinite_dataset_with_steps_per_epoch(self): data = dataset_ops.Dataset.from_tensor_slices([0, 1, 2]).batch(1).repeat() data_handler = data_adapter.DataHandler( data, initial_epoch=0, epochs=2, steps_per_epoch=3) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): epoch_data.append(next(iterator).numpy()) returned_data.append(epoch_data) self.assertEqual(returned_data, [[0, 1, 2], [0, 1, 2]]) def test_unknown_cardinality_dataset_with_steps_per_epoch(self): ds = dataset_ops.DatasetV2.from_tensor_slices([0, 1, 2, 3, 4, 5, 6]) filtered_ds = ds.filter(lambda x: x < 4) self.assertEqual( cardinality.cardinality(filtered_ds).numpy(), cardinality.UNKNOWN) # User can choose to only partially consume `Dataset`. data_handler = data_adapter.DataHandler( filtered_ds, initial_epoch=0, epochs=2, steps_per_epoch=2) self.assertFalse(data_handler._adapter.should_recreate_iterator()) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): epoch_data.append(next(iterator)) returned_data.append(epoch_data) returned_data = self.evaluate(returned_data) self.assertEqual(returned_data, [[0, 1], [2, 3]]) self.assertEqual(data_handler.inferred_steps, 2) def test_unknown_cardinality_dataset_without_steps_per_epoch(self): ds = dataset_ops.DatasetV2.from_tensor_slices([0, 1, 2, 3, 4, 5, 6]) filtered_ds = ds.filter(lambda x: x < 4) self.assertEqual( cardinality.cardinality(filtered_ds).numpy(), cardinality.UNKNOWN) data_handler = data_adapter.DataHandler( filtered_ds, initial_epoch=0, epochs=2) self.assertEqual(data_handler.inferred_steps, None) self.assertTrue(data_handler._adapter.should_recreate_iterator()) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] with data_handler.catch_stop_iteration(): for _ in data_handler.steps(): epoch_data.append(next(iterator)) returned_data.append(epoch_data) returned_data = self.evaluate(returned_data) self.assertEqual(returned_data, [[0, 1, 2, 3], [0, 1, 2, 3]]) self.assertEqual(data_handler.inferred_steps, 4) def test_insufficient_data(self): ds = dataset_ops.DatasetV2.from_tensor_slices([0, 1]) ds = ds.filter(lambda *args, **kwargs: True) data_handler = data_adapter.DataHandler( ds, initial_epoch=0, epochs=2, steps_per_epoch=3) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): with data_handler.catch_stop_iteration(): epoch_data.append(next(iterator)) returned_data.append(epoch_data) returned_data = self.evaluate(returned_data) self.assertTrue(data_handler._insufficient_data) self.assertEqual(returned_data, [[0, 1]]) def test_numpy(self): x = np.array([0, 1, 2]) y = np.array([0, 2, 4]) sw = np.array([0, 4, 8]) data_handler = data_adapter.DataHandler( x=x, y=y, sample_weight=sw, batch_size=1, epochs=2) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): epoch_data.append(next(iterator)) returned_data.append(epoch_data) returned_data = self.evaluate(returned_data) self.assertEqual(returned_data, [[(0, 0, 0), (1, 2, 4), (2, 4, 8)], [(0, 0, 0), (1, 2, 4), (2, 4, 8)]]) def test_generator(self): def generator(): for _ in range(2): for step in range(3): yield (ops.convert_to_tensor_v2_with_dispatch([step]),) data_handler = data_adapter.DataHandler( generator(), epochs=2, steps_per_epoch=3) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): epoch_data.append(next(iterator)) returned_data.append(epoch_data) returned_data = self.evaluate(returned_data) self.assertEqual(returned_data, [[([0],), ([1],), ([2],)], [([0],), ([1],), ([2],)]]) def test_composite_tensor(self): st = sparse_tensor.SparseTensor( indices=[[0, 0], [1, 0], [2, 0]], values=[0, 1, 2], dense_shape=[3, 1]) data_handler = data_adapter.DataHandler(st, epochs=2, steps_per_epoch=3) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): epoch_data.append(next(iterator)) returned_data.append(epoch_data) returned_data = self.evaluate( nest.map_structure(sparse_ops.sparse_tensor_to_dense, returned_data)) self.assertEqual(returned_data, [[([0],), ([1],), ([2],)], [([0],), ([1],), ([2],)]]) def test_list_of_scalars(self): data_handler = data_adapter.DataHandler([[0], [1], [2]], epochs=2, steps_per_epoch=3) returned_data = [] for _, iterator in data_handler.enumerate_epochs(): epoch_data = [] for _ in data_handler.steps(): epoch_data.append(next(iterator)) returned_data.append(epoch_data) returned_data = self.evaluate(returned_data) self.assertEqual(returned_data, [[([0],), ([1],), ([2],)], [([0],), ([1],), ([2],)]]) def test_class_weight_user_errors(self): with self.assertRaisesRegex(ValueError, 'to be a dict with keys'): data_adapter.DataHandler( x=[[0], [1], [2]], y=[[2], [1], [0]], batch_size=1, sample_weight=[[1.], [2.], [4.]], class_weight={ 0: 0.5, 1: 1., 3: 1.5 # Skips class `2`. }) with self.assertRaisesRegex(ValueError, 'with a single output'): data_adapter.DataHandler( x=np.ones((10, 1)), y=[np.ones((10, 1)), np.zeros((10, 1))], batch_size=2, class_weight={ 0: 0.5, 1: 1., 2: 1.5 }) @parameterized.named_parameters(('numpy', True), ('dataset', False)) def test_single_x_input_no_tuple_wrapping(self, use_numpy): x = np.ones((10, 1)) if use_numpy: batch_size = 2 else: x = dataset_ops.Dataset.from_tensor_slices(x).batch(2) batch_size = None data_handler = data_adapter.DataHandler(x, batch_size=batch_size) for _, iterator in data_handler.enumerate_epochs(): for _ in data_handler.steps(): # Check that single x input is not wrapped in a tuple. self.assertIsInstance(next(iterator), ops.Tensor) class TestValidationSplit(keras_parameterized.TestCase): @parameterized.named_parameters(('numpy_arrays', True), ('tensors', False)) def test_validation_split_unshuffled(self, use_numpy): if use_numpy: x = np.array([0, 1, 2, 3, 4]) y = np.array([0, 2, 4, 6, 8]) sw = np.array([0, 4, 8, 12, 16]) else: x = ops.convert_to_tensor_v2_with_dispatch([0, 1, 2, 3, 4]) y = ops.convert_to_tensor_v2_with_dispatch([0, 2, 4, 6, 8]) sw = ops.convert_to_tensor_v2_with_dispatch([0, 4, 8, 12, 16]) (train_x, train_y, train_sw), (val_x, val_y, val_sw) = ( data_adapter.train_validation_split((x, y, sw), validation_split=0.2)) if use_numpy: train_x = ops.convert_to_tensor_v2_with_dispatch(train_x) train_y = ops.convert_to_tensor_v2_with_dispatch(train_y) train_sw = ops.convert_to_tensor_v2_with_dispatch(train_sw) val_x = ops.convert_to_tensor_v2_with_dispatch(val_x) val_y = ops.convert_to_tensor_v2_with_dispatch(val_y) val_sw = ops.convert_to_tensor_v2_with_dispatch(val_sw) self.assertEqual(train_x.numpy().tolist(), [0, 1, 2, 3]) self.assertEqual(train_y.numpy().tolist(), [0, 2, 4, 6]) self.assertEqual(train_sw.numpy().tolist(), [0, 4, 8, 12]) self.assertEqual(val_x.numpy().tolist(), [4]) self.assertEqual(val_y.numpy().tolist(), [8]) self.assertEqual(val_sw.numpy().tolist(), [16]) def test_validation_split_user_error(self): with self.assertRaisesRegex(ValueError, 'is only supported for Tensors'): data_adapter.train_validation_split( lambda: np.ones((10, 1)), validation_split=0.2) def test_validation_split_examples_too_few(self): with self.assertRaisesRegex(ValueError, 'not sufficient to split it'): data_adapter.train_validation_split( np.ones((1, 10)), validation_split=0.2) def test_validation_split_none(self): train_sw, val_sw = data_adapter.train_validation_split( None, validation_split=0.2) self.assertIsNone(train_sw) self.assertIsNone(val_sw) (_, train_sw), (_, val_sw) = data_adapter.train_validation_split( (np.ones((10, 1)), None), validation_split=0.2) self.assertIsNone(train_sw) self.assertIsNone(val_sw) class ListsOfScalarsDataAdapterTest(DataAdapterTestBase): def setUp(self): super(ListsOfScalarsDataAdapterTest, self).setUp() self.adapter_cls = data_adapter.ListsOfScalarsDataAdapter def test_can_list_inputs(self): self.assertTrue(self.adapter_cls.can_handle(self.text_input)) self.assertTrue(self.adapter_cls.can_handle(self.bytes_input)) self.assertFalse(self.adapter_cls.can_handle(self.numpy_input)) self.assertFalse(self.adapter_cls.can_handle(self.tensor_input)) self.assertFalse(self.adapter_cls.can_handle(self.dataset_input)) self.assertFalse(self.adapter_cls.can_handle(self.generator_input)) self.assertFalse(self.adapter_cls.can_handle(self.sequence_input)) class TestUtils(keras_parameterized.TestCase): def test_expand_1d_sparse_tensors_untouched(self): st = sparse_tensor.SparseTensor( indices=[[0], [10]], values=[1, 2], dense_shape=[10]) st = data_adapter.expand_1d(st) self.assertEqual(st.shape.rank, 1) if __name__ == '__main__': ops.enable_eager_execution() test.main()
unknown
codeparrot/codeparrot-clean
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import asn1 import hashlib import os # This file implements very minimal certificate and OCSP generation. It's # designed to test revocation checking. def RandomNumber(length_in_bytes): '''RandomNumber returns a random number of length 8*|length_in_bytes| bits''' rand = os.urandom(length_in_bytes) n = 0 for x in rand: n <<= 8 n |= ord(x) return n def ModExp(n, e, p): '''ModExp returns n^e mod p''' r = 1 while e != 0: if e & 1: r = (r*n) % p e >>= 1 n = (n*n) % p return r # PKCS1v15_SHA1_PREFIX is the ASN.1 prefix for a SHA1 signature. PKCS1v15_SHA1_PREFIX = '3021300906052b0e03021a05000414'.decode('hex') class RSA(object): def __init__(self, modulus, e, d): self.m = modulus self.e = e self.d = d self.modlen = 0 m = modulus while m != 0: self.modlen += 1 m >>= 8 def Sign(self, message): digest = hashlib.sha1(message).digest() prefix = PKCS1v15_SHA1_PREFIX em = ['\xff'] * (self.modlen - 1 - len(prefix) - len(digest)) em[0] = '\x00' em[1] = '\x01' em += "\x00" + prefix + digest n = 0 for x in em: n <<= 8 n |= ord(x) s = ModExp(n, self.d, self.m) out = [] while s != 0: out.append(s & 0xff) s >>= 8 out.reverse() return '\x00' * (self.modlen - len(out)) + asn1.ToBytes(out) def ToDER(self): return asn1.ToDER(asn1.SEQUENCE([self.m, self.e])) def Name(cn = None, c = None, o = None): names = asn1.SEQUENCE([]) if cn is not None: names.children.append( asn1.SET([ asn1.SEQUENCE([ COMMON_NAME, cn, ]) ]) ) if c is not None: names.children.append( asn1.SET([ asn1.SEQUENCE([ COUNTRY, c, ]) ]) ) if o is not None: names.children.append( asn1.SET([ asn1.SEQUENCE([ ORGANIZATION, o, ]) ]) ) return names # The private key and root certificate name are hard coded here: # This is the private key KEY = RSA(0x00a71998f2930bfe73d031a87f133d2f378eeeeed52a77e44d0fc9ff6f07ff32cbf3da999de4ed65832afcb0807f98787506539d258a0ce3c2c77967653099a9034a9b115a876c39a8c4e4ed4acd0c64095946fb39eeeb47a0704dbb018acf48c3a1c4b895fc409fb4a340a986b1afc45519ab9eca47c30185c771c64aa5ecf07d, 3, 0x6f6665f70cb2a9a28acbc5aa0cd374cfb49f49e371a542de0a86aa4a0554cc87f7e71113edf399021ca875aaffbafaf8aee268c3b15ded2c84fb9a4375bbc6011d841e57833bc6f998d25daf6fa7f166b233e3e54a4bae7a5aaaba21431324967d5ff3e1d4f413827994262115ca54396e7068d0afa7af787a5782bc7040e6d3) # And the same thing in PEM format KEY_PEM = '''-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQCnGZjykwv+c9AxqH8TPS83ju7u1Sp35E0Pyf9vB/8yy/PamZ3k 7WWDKvywgH+YeHUGU50ligzjwsd5Z2UwmakDSpsRWodsOajE5O1KzQxkCVlG+znu 60egcE27AYrPSMOhxLiV/ECftKNAqYaxr8RVGaueykfDAYXHccZKpezwfQIBAwKB gG9mZfcMsqmiisvFqgzTdM+0n0njcaVC3gqGqkoFVMyH9+cRE+3zmQIcqHWq/7r6 +K7iaMOxXe0shPuaQ3W7xgEdhB5XgzvG+ZjSXa9vp/FmsjPj5UpLrnpaqrohQxMk ln1f8+HU9BOCeZQmIRXKVDlucGjQr6eveHpXgrxwQObTAkEA2wBAfuduw5G0/VfN Wx66D5fbPccfYFqLM5LuTimLmNqzK2gIKXckB2sm44gJZ6wVlumaB1CSNug2LNYx 3cAjUwJBAMNUo1hbI8ugqqwI9kpxv9+2Heea4BlnXbS6tYF8pvkHMoliuxNbXmmB u4zNB5iZ6V0ZZ4nvtUNo2cGr/h/Lcu8CQQCSACr/RPSCYSNTj948vya1D+d+hL+V kbIiYfQ0G7Jl5yIc8AVw+hgE8hntBVuacrkPRmaviwwkms7IjsvpKsI3AkEAgjhs 5ZIX3RXHHVtO3EvVP86+mmdAEO+TzdHOVlMZ+1ohsOx8t5I+8QEnszNaZbvw6Lua W/UjgkXmgR1UFTJMnwJBAKErmAw21/g3SST0a4wlyaGT/MbXL8Ouwnb5IOKQVe55 CZdeVeSh6cJ4hAcQKfr2s1JaZTJFIBPGKAif5HqpydA= -----END RSA PRIVATE KEY----- ''' # Root certificate CN ISSUER_CN = "Testing CA" # All certificates are issued under this policy OID, in the Google arc: CERT_POLICY_OID = asn1.OID([1, 3, 6, 1, 4, 1, 11129, 2, 4, 1]) # These result in the following root certificate: # -----BEGIN CERTIFICATE----- # MIIB0TCCATqgAwIBAgIBATANBgkqhkiG9w0BAQUFADAVMRMwEQYDVQQDEwpUZXN0aW5nIENBMB4X # DTEwMDEwMTA2MDAwMFoXDTMyMTIwMTA2MDAwMFowFTETMBEGA1UEAxMKVGVzdGluZyBDQTCBnTAN # BgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEApxmY8pML/nPQMah/Ez0vN47u7tUqd+RND8n/bwf/Msvz # 2pmd5O1lgyr8sIB/mHh1BlOdJYoM48LHeWdlMJmpA0qbEVqHbDmoxOTtSs0MZAlZRvs57utHoHBN # uwGKz0jDocS4lfxAn7SjQKmGsa/EVRmrnspHwwGFx3HGSqXs8H0CAQOjMzAxMBIGA1UdEwEB/wQI # MAYBAf8CAQAwGwYDVR0gAQEABBEwDzANBgsrBgEEAdZ5AgHODzANBgkqhkiG9w0BAQUFAAOBgQA/ # STb40A6D+93jMfLGQzXc997IsaJZdoPt7tYa8PqGJBL62EiTj+erd/H5pDZx/2/bcpOG4m9J56yg # wOohbllw2TM+oeEd8syzV6X+1SIPnGI56JRrm3UXcHYx1Rq5loM9WKAiz/WmIWmskljsEQ7+542p # q0pkHjs8nuXovSkUYA== # -----END CERTIFICATE----- # If you update any of the above, you can generate a new root with the # following line: # print DERToPEM(MakeCertificate(ISSUER_CN, ISSUER_CN, 1, KEY, KEY, None)) # Various OIDs AIA_OCSP = asn1.OID([1, 3, 6, 1, 5, 5, 7, 48, 1]) AUTHORITY_INFORMATION_ACCESS = asn1.OID([1, 3, 6, 1, 5, 5, 7, 1, 1]) BASIC_CONSTRAINTS = asn1.OID([2, 5, 29, 19]) CERT_POLICIES = asn1.OID([2, 5, 29, 32]) COMMON_NAME = asn1.OID([2, 5, 4, 3]) COUNTRY = asn1.OID([2, 5, 4, 6]) HASH_SHA1 = asn1.OID([1, 3, 14, 3, 2, 26]) OCSP_TYPE_BASIC = asn1.OID([1, 3, 6, 1, 5, 5, 7, 48, 1, 1]) ORGANIZATION = asn1.OID([2, 5, 4, 10]) PUBLIC_KEY_RSA = asn1.OID([1, 2, 840, 113549, 1, 1, 1]) SHA1_WITH_RSA_ENCRYPTION = asn1.OID([1, 2, 840, 113549, 1, 1, 5]) def MakeCertificate( issuer_cn, subject_cn, serial, pubkey, privkey, ocsp_url = None): '''MakeCertificate returns a DER encoded certificate, signed by privkey.''' extensions = asn1.SEQUENCE([]) # Default subject name fields c = "XX" o = "Testing Org" if issuer_cn == subject_cn: # Root certificate. c = None o = None extensions.children.append( asn1.SEQUENCE([ basic_constraints, True, asn1.OCTETSTRING(asn1.ToDER(asn1.SEQUENCE([ True, # IsCA 0, # Path len ]))), ])) if ocsp_url is not None: extensions.children.append( asn1.SEQUENCE([ AUTHORITY_INFORMATION_ACCESS, False, asn1.OCTETSTRING(asn1.ToDER(asn1.SEQUENCE([ asn1.SEQUENCE([ AIA_OCSP, asn1.Raw(asn1.TagAndLength(0x86, len(ocsp_url)) + ocsp_url), ]), ]))), ])) extensions.children.append( asn1.SEQUENCE([ CERT_POLICIES, False, asn1.OCTETSTRING(asn1.ToDER(asn1.SEQUENCE([ asn1.SEQUENCE([ # PolicyInformation CERT_POLICY_OID, ]), ]))), ]) ) tbsCert = asn1.ToDER(asn1.SEQUENCE([ asn1.Explicit(0, 2), # Version serial, asn1.SEQUENCE([SHA1_WITH_RSA_ENCRYPTION, None]), # SignatureAlgorithm Name(cn = issuer_cn), # Issuer asn1.SEQUENCE([ # Validity asn1.UTCTime("100101060000Z"), # NotBefore asn1.UTCTime("321201060000Z"), # NotAfter ]), Name(cn = subject_cn, c = c, o = o), # Subject asn1.SEQUENCE([ # SubjectPublicKeyInfo asn1.SEQUENCE([ # Algorithm PUBLIC_KEY_RSA, None, ]), asn1.BitString(asn1.ToDER(pubkey)), ]), asn1.Explicit(3, extensions), ])) return asn1.ToDER(asn1.SEQUENCE([ asn1.Raw(tbsCert), asn1.SEQUENCE([ SHA1_WITH_RSA_ENCRYPTION, None, ]), asn1.BitString(privkey.Sign(tbsCert)), ])) def MakeOCSPResponse(issuer_cn, issuer_key, serial, ocsp_state): # https://tools.ietf.org/html/rfc2560 issuer_name_hash = asn1.OCTETSTRING( hashlib.sha1(asn1.ToDER(Name(cn = issuer_cn))).digest()) issuer_key_hash = asn1.OCTETSTRING( hashlib.sha1(asn1.ToDER(issuer_key)).digest()) cert_status = None if ocsp_state == OCSP_STATE_REVOKED: cert_status = asn1.Explicit(1, asn1.GeneralizedTime("20100101060000Z")) elif ocsp_state == OCSP_STATE_UNKNOWN: cert_status = asn1.Raw(asn1.TagAndLength(0x80 | 2, 0)) elif ocsp_state == OCSP_STATE_GOOD: cert_status = asn1.Raw(asn1.TagAndLength(0x80 | 0, 0)) else: raise ValueError('Bad OCSP state: ' + str(ocsp_state)) basic_resp_data_der = asn1.ToDER(asn1.SEQUENCE([ asn1.Explicit(2, issuer_key_hash), asn1.GeneralizedTime("20100101060000Z"), # producedAt asn1.SEQUENCE([ asn1.SEQUENCE([ # SingleResponse asn1.SEQUENCE([ # CertID asn1.SEQUENCE([ # hashAlgorithm HASH_SHA1, None, ]), issuer_name_hash, issuer_key_hash, serial, ]), cert_status, asn1.GeneralizedTime("20100101060000Z"), # thisUpdate asn1.Explicit(0, asn1.GeneralizedTime("20300101060000Z")), # nextUpdate ]), ]), ])) basic_resp = asn1.SEQUENCE([ asn1.Raw(basic_resp_data_der), asn1.SEQUENCE([ SHA1_WITH_RSA_ENCRYPTION, None, ]), asn1.BitString(issuer_key.Sign(basic_resp_data_der)), ]) resp = asn1.SEQUENCE([ asn1.ENUMERATED(0), asn1.Explicit(0, asn1.SEQUENCE([ OCSP_TYPE_BASIC, asn1.OCTETSTRING(asn1.ToDER(basic_resp)), ])) ]) return asn1.ToDER(resp) def DERToPEM(der): pem = '-----BEGIN CERTIFICATE-----\n' pem += der.encode('base64') pem += '-----END CERTIFICATE-----\n' return pem OCSP_STATE_GOOD = 1 OCSP_STATE_REVOKED = 2 OCSP_STATE_INVALID = 3 OCSP_STATE_UNAUTHORIZED = 4 OCSP_STATE_UNKNOWN = 5 # unauthorizedDER is an OCSPResponse with a status of 6: # SEQUENCE { ENUM(6) } unauthorizedDER = '30030a0106'.decode('hex') def GenerateCertKeyAndOCSP(subject = "127.0.0.1", ocsp_url = "http://127.0.0.1", ocsp_state = OCSP_STATE_GOOD, serial = 0): '''GenerateCertKeyAndOCSP returns a (cert_and_key_pem, ocsp_der) where: * cert_and_key_pem contains a certificate and private key in PEM format with the given subject common name and OCSP URL. * ocsp_der contains a DER encoded OCSP response or None if ocsp_url is None''' if serial == 0: serial = RandomNumber(16) cert_der = MakeCertificate(ISSUER_CN, bytes(subject), serial, KEY, KEY, bytes(ocsp_url)) cert_pem = DERToPEM(cert_der) ocsp_der = None if ocsp_url is not None: if ocsp_state == OCSP_STATE_UNAUTHORIZED: ocsp_der = unauthorizedDER elif ocsp_state == OCSP_STATE_INVALID: ocsp_der = '3' else: ocsp_der = MakeOCSPResponse(ISSUER_CN, KEY, serial, ocsp_state) return (cert_pem + KEY_PEM, ocsp_der)
unknown
codeparrot/codeparrot-clean
# coding: utf-8 # pylint: disable=too-many-arguments, too-many-locals """Definition of various recurrent neural network cells.""" from __future__ import print_function import bisect import random import numpy as np from ..io import DataIter, DataBatch, DataDesc from .. import ndarray def encode_sentences(sentences, vocab=None, invalid_label=-1, invalid_key='\n', start_label=0): """Encode sentences and (optionally) build a mapping from string tokens to integer indices. Unknown keys will be added to vocabulary. Parameters ---------- sentences : list of list of str A list of sentences to encode. Each sentence should be a list of string tokens. vocab : None or dict of str -> int Optional input Vocabulary invalid_label : int, default -1 Index for invalid token, like <end-of-sentence> invalid_key : str, default '\\n' Key for invalid token. Use '\\n' for end of sentence by default. start_label : int lowest index. Returns ------- result : list of list of int encoded sentences vocab : dict of str -> int result vocabulary """ idx = start_label if vocab is None: vocab = {invalid_key: invalid_label} new_vocab = True else: new_vocab = False res = [] for sent in sentences: coded = [] for word in sent: if word not in vocab: assert new_vocab, "Unknown token %s"%word if idx == invalid_label: idx += 1 vocab[word] = idx idx += 1 coded.append(vocab[word]) res.append(coded) return res, vocab class BucketSentenceIter(DataIter): """Simple bucketing iterator for language model. The label at each sequence step is the following token in the sequence. Parameters ---------- sentences : list of list of int Encoded sentences. batch_size : int Batch size of the data. invalid_label : int, optional Key for invalid label, e.g. <end-of-sentence>. The default is -1. dtype : str, optional Data type of the encoding. The default data type is 'float32'. buckets : list of int, optional Size of the data buckets. Automatically generated if None. data_name : str, optional Name of the data. The default name is 'data'. label_name : str, optional Name of the label. The default name is 'softmax_label'. layout : str, optional Format of data and label. 'NT' means (batch_size, length) and 'TN' means (length, batch_size). """ def __init__(self, sentences, batch_size, buckets=None, invalid_label=-1, data_name='data', label_name='softmax_label', dtype='float32', layout='NT'): super(BucketSentenceIter, self).__init__() if not buckets: buckets = [i for i, j in enumerate(np.bincount([len(s) for s in sentences])) if j >= batch_size] buckets.sort() ndiscard = 0 self.data = [[] for _ in buckets] for i, sent in enumerate(sentences): buck = bisect.bisect_left(buckets, len(sent)) if buck == len(buckets): ndiscard += 1 continue buff = np.full((buckets[buck],), invalid_label, dtype=dtype) buff[:len(sent)] = sent self.data[buck].append(buff) self.data = [np.asarray(i, dtype=dtype) for i in self.data] print("WARNING: discarded %d sentences longer than the largest bucket."%ndiscard) self.batch_size = batch_size self.buckets = buckets self.data_name = data_name self.label_name = label_name self.dtype = dtype self.invalid_label = invalid_label self.nddata = [] self.ndlabel = [] self.major_axis = layout.find('N') self.layout = layout self.default_bucket_key = max(buckets) if self.major_axis == 0: self.provide_data = [DataDesc( name=self.data_name, shape=(batch_size, self.default_bucket_key), layout=self.layout)] self.provide_label = [DataDesc( name=self.label_name, shape=(batch_size, self.default_bucket_key), layout=self.layout)] elif self.major_axis == 1: self.provide_data = [DataDesc( name=self.data_name, shape=(self.default_bucket_key, batch_size), layout=self.layout)] self.provide_label = [DataDesc( name=self.label_name, shape=(self.default_bucket_key, batch_size), layout=self.layout)] else: raise ValueError("Invalid layout %s: Must by NT (batch major) or TN (time major)") self.idx = [] for i, buck in enumerate(self.data): self.idx.extend([(i, j) for j in range(0, len(buck) - batch_size + 1, batch_size)]) self.curr_idx = 0 self.reset() def reset(self): """Resets the iterator to the beginning of the data.""" self.curr_idx = 0 random.shuffle(self.idx) for buck in self.data: np.random.shuffle(buck) self.nddata = [] self.ndlabel = [] for buck in self.data: label = np.empty_like(buck) label[:, :-1] = buck[:, 1:] label[:, -1] = self.invalid_label self.nddata.append(ndarray.array(buck, dtype=self.dtype)) self.ndlabel.append(ndarray.array(label, dtype=self.dtype)) def next(self): """Returns the next batch of data.""" if self.curr_idx == len(self.idx): raise StopIteration i, j = self.idx[self.curr_idx] self.curr_idx += 1 if self.major_axis == 1: data = self.nddata[i][j:j+self.batch_size].T label = self.ndlabel[i][j:j+self.batch_size].T else: data = self.nddata[i][j:j+self.batch_size] label = self.ndlabel[i][j:j+self.batch_size] return DataBatch([data], [label], pad=0, bucket_key=self.buckets[i], provide_data=[DataDesc( name=self.data_name, shape=data.shape, layout=self.layout)], provide_label=[DataDesc( name=self.label_name, shape=label.shape, layout=self.layout)])
unknown
codeparrot/codeparrot-clean
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.energy', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## wifi-mode.h (module 'wifi'): ns3::WifiCodeRate [enumeration] module.add_enum('WifiCodeRate', ['WIFI_CODE_RATE_UNDEFINED', 'WIFI_CODE_RATE_3_4', 'WIFI_CODE_RATE_2_3', 'WIFI_CODE_RATE_1_2', 'WIFI_CODE_RATE_5_6'], import_from_module='ns.wifi') ## wifi-preamble.h (module 'wifi'): ns3::WifiPreamble [enumeration] module.add_enum('WifiPreamble', ['WIFI_PREAMBLE_LONG', 'WIFI_PREAMBLE_SHORT', 'WIFI_PREAMBLE_HT_MF', 'WIFI_PREAMBLE_HT_GF'], import_from_module='ns.wifi') ## wifi-phy-standard.h (module 'wifi'): ns3::WifiPhyStandard [enumeration] module.add_enum('WifiPhyStandard', ['WIFI_PHY_STANDARD_80211a', 'WIFI_PHY_STANDARD_80211b', 'WIFI_PHY_STANDARD_80211g', 'WIFI_PHY_STANDARD_80211_10MHZ', 'WIFI_PHY_STANDARD_80211_5MHZ', 'WIFI_PHY_STANDARD_holland', 'WIFI_PHY_STANDARD_80211n_2_4GHZ', 'WIFI_PHY_STANDARD_80211n_5GHZ'], import_from_module='ns.wifi') ## wifi-mode.h (module 'wifi'): ns3::WifiModulationClass [enumeration] module.add_enum('WifiModulationClass', ['WIFI_MOD_CLASS_UNKNOWN', 'WIFI_MOD_CLASS_IR', 'WIFI_MOD_CLASS_FHSS', 'WIFI_MOD_CLASS_DSSS', 'WIFI_MOD_CLASS_ERP_PBCC', 'WIFI_MOD_CLASS_DSSS_OFDM', 'WIFI_MOD_CLASS_ERP_OFDM', 'WIFI_MOD_CLASS_OFDM', 'WIFI_MOD_CLASS_HT'], import_from_module='ns.wifi') ## 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') ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer [class] module.add_class('DeviceEnergyModelContainer') ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper [class] module.add_class('DeviceEnergyModelHelper', allow_subclassing=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper [class] module.add_class('EnergySourceHelper', allow_subclassing=True) ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## 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') ## rv-battery-model-helper.h (module 'energy'): ns3::RvBatteryModelHelper [class] module.add_class('RvBatteryModelHelper', parent=root_module['ns3::EnergySourceHelper']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## traced-value.h (module 'core'): ns3::TracedValue<double> [class] module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['double']) ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## wifi-mode.h (module 'wifi'): ns3::WifiMode [class] module.add_class('WifiMode', import_from_module='ns.wifi') ## wifi-mode.h (module 'wifi'): ns3::WifiModeFactory [class] module.add_class('WifiModeFactory', import_from_module='ns.wifi') ## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener [class] module.add_class('WifiPhyListener', allow_subclassing=True, import_from_module='ns.wifi') ## wifi-radio-energy-model-helper.h (module 'energy'): ns3::WifiRadioEnergyModelHelper [class] module.add_class('WifiRadioEnergyModelHelper', parent=root_module['ns3::DeviceEnergyModelHelper']) ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiRadioEnergyModelPhyListener [class] module.add_class('WifiRadioEnergyModelPhyListener', parent=root_module['ns3::WifiPhyListener']) ## wifi-tx-vector.h (module 'wifi'): ns3::WifiTxVector [class] module.add_class('WifiTxVector', import_from_module='ns.wifi') ## 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') ## basic-energy-source-helper.h (module 'energy'): ns3::BasicEnergySourceHelper [class] module.add_class('BasicEnergySourceHelper', parent=root_module['ns3::EnergySourceHelper']) ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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')) ## 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> >']) ## traced-value.h (module 'core'): ns3::TracedValue<ns3::Time> [class] module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['ns3::Time']) ## traced-value.h (module 'core'): ns3::TracedValue<ns3::Time> [class] root_module['ns3::TracedValue< ns3::Time >'].implicitly_converts_to(root_module['ns3::Time']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## wifi-phy.h (module 'wifi'): ns3::WifiPhy [class] module.add_class('WifiPhy', import_from_module='ns.wifi', parent=root_module['ns3::Object']) ## wifi-phy.h (module 'wifi'): ns3::WifiPhy::State [enumeration] module.add_enum('State', ['IDLE', 'CCA_BUSY', 'TX', 'RX', 'SWITCHING'], outer_class=root_module['ns3::WifiPhy'], import_from_module='ns.wifi') ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## boolean.h (module 'core'): ns3::BooleanChecker [class] module.add_class('BooleanChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## boolean.h (module 'core'): ns3::BooleanValue [class] module.add_class('BooleanValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel [class] module.add_class('DeviceEnergyModel', parent=root_module['ns3::Object']) ## double.h (module 'core'): ns3::DoubleValue [class] module.add_class('DoubleValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## energy-source.h (module 'energy'): ns3::EnergySource [class] module.add_class('EnergySource', parent=root_module['ns3::Object']) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer [class] module.add_class('EnergySourceContainer', parent=root_module['ns3::Object']) ## enum.h (module 'core'): ns3::EnumChecker [class] module.add_class('EnumChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## enum.h (module 'core'): ns3::EnumValue [class] module.add_class('EnumValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## 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> >']) ## integer.h (module 'core'): ns3::IntegerValue [class] module.add_class('IntegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## li-ion-energy-source.h (module 'energy'): ns3::LiIonEnergySource [class] module.add_class('LiIonEnergySource', parent=root_module['ns3::EnergySource']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## rv-battery-model.h (module 'energy'): ns3::RvBatteryModel [class] module.add_class('RvBatteryModel', parent=root_module['ns3::EnergySource']) ## simple-device-energy-model.h (module 'energy'): ns3::SimpleDeviceEnergyModel [class] module.add_class('SimpleDeviceEnergyModel', parent=root_module['ns3::DeviceEnergyModel']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## uinteger.h (module 'core'): ns3::UintegerValue [class] module.add_class('UintegerValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker [class] module.add_class('WifiModeChecker', import_from_module='ns.wifi', parent=root_module['ns3::AttributeChecker']) ## wifi-mode.h (module 'wifi'): ns3::WifiModeValue [class] module.add_class('WifiModeValue', import_from_module='ns.wifi', parent=root_module['ns3::AttributeValue']) ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiRadioEnergyModel [class] module.add_class('WifiRadioEnergyModel', parent=root_module['ns3::DeviceEnergyModel']) ## 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']) ## basic-energy-source.h (module 'energy'): ns3::BasicEnergySource [class] module.add_class('BasicEnergySource', parent=root_module['ns3::EnergySource']) module.add_container('ns3::WifiModeList', 'ns3::WifiMode', container_type=u'vector') typehandlers.add_type_alias(u'std::vector< unsigned char, std::allocator< unsigned char > >', u'ns3::WifiMcsList') typehandlers.add_type_alias(u'std::vector< unsigned char, std::allocator< unsigned char > >*', u'ns3::WifiMcsList*') typehandlers.add_type_alias(u'std::vector< unsigned char, std::allocator< unsigned char > >&', u'ns3::WifiMcsList&') typehandlers.add_type_alias(u'std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >', u'ns3::WifiModeList') typehandlers.add_type_alias(u'std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >*', u'ns3::WifiModeList*') typehandlers.add_type_alias(u'std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > >&', u'ns3::WifiModeList&') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >', u'ns3::WifiModeListIterator') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >*', u'ns3::WifiModeListIterator*') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< ns3::WifiMode const *, std::vector< ns3::WifiMode, std::allocator< ns3::WifiMode > > >&', u'ns3::WifiModeListIterator&') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char, std::allocator< unsigned char > > >', u'ns3::WifiMcsListIterator') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char, std::allocator< unsigned char > > >*', u'ns3::WifiMcsListIterator*') typehandlers.add_type_alias(u'__gnu_cxx::__normal_iterator< unsigned char const *, std::vector< unsigned char, std::allocator< unsigned char > > >&', u'ns3::WifiMcsListIterator&') ## 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 internal nested_module = module.add_cpp_namespace('internal') register_types_ns3_internal(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_types_ns3_internal(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_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_Ns3DeviceEnergyModelContainer_methods(root_module, root_module['ns3::DeviceEnergyModelContainer']) register_Ns3DeviceEnergyModelHelper_methods(root_module, root_module['ns3::DeviceEnergyModelHelper']) register_Ns3EnergySourceHelper_methods(root_module, root_module['ns3::EnergySourceHelper']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3RvBatteryModelHelper_methods(root_module, root_module['ns3::RvBatteryModelHelper']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TracedValue__Double_methods(root_module, root_module['ns3::TracedValue< double >']) 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_Ns3WifiMode_methods(root_module, root_module['ns3::WifiMode']) register_Ns3WifiModeFactory_methods(root_module, root_module['ns3::WifiModeFactory']) register_Ns3WifiPhyListener_methods(root_module, root_module['ns3::WifiPhyListener']) register_Ns3WifiRadioEnergyModelHelper_methods(root_module, root_module['ns3::WifiRadioEnergyModelHelper']) register_Ns3WifiRadioEnergyModelPhyListener_methods(root_module, root_module['ns3::WifiRadioEnergyModelPhyListener']) register_Ns3WifiTxVector_methods(root_module, root_module['ns3::WifiTxVector']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3BasicEnergySourceHelper_methods(root_module, root_module['ns3::BasicEnergySourceHelper']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3TracedValue__Ns3Time_methods(root_module, root_module['ns3::TracedValue< ns3::Time >']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3WifiPhy_methods(root_module, root_module['ns3::WifiPhy']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3BooleanChecker_methods(root_module, root_module['ns3::BooleanChecker']) register_Ns3BooleanValue_methods(root_module, root_module['ns3::BooleanValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3DeviceEnergyModel_methods(root_module, root_module['ns3::DeviceEnergyModel']) register_Ns3DoubleValue_methods(root_module, root_module['ns3::DoubleValue']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EnergySource_methods(root_module, root_module['ns3::EnergySource']) register_Ns3EnergySourceContainer_methods(root_module, root_module['ns3::EnergySourceContainer']) register_Ns3EnumChecker_methods(root_module, root_module['ns3::EnumChecker']) register_Ns3EnumValue_methods(root_module, root_module['ns3::EnumValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3IntegerValue_methods(root_module, root_module['ns3::IntegerValue']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3LiIonEnergySource_methods(root_module, root_module['ns3::LiIonEnergySource']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3RvBatteryModel_methods(root_module, root_module['ns3::RvBatteryModel']) register_Ns3SimpleDeviceEnergyModel_methods(root_module, root_module['ns3::SimpleDeviceEnergyModel']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3UintegerValue_methods(root_module, root_module['ns3::UintegerValue']) register_Ns3WifiModeChecker_methods(root_module, root_module['ns3::WifiModeChecker']) register_Ns3WifiModeValue_methods(root_module, root_module['ns3::WifiModeValue']) register_Ns3WifiRadioEnergyModel_methods(root_module, root_module['ns3::WifiRadioEnergyModel']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3BasicEnergySource_methods(root_module, root_module['ns3::BasicEnergySource']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): 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 adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3DeviceEnergyModelContainer_methods(root_module, cls): ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'arg0')]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer() [constructor] cls.add_constructor([]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::Ptr<ns3::DeviceEnergyModel> model) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(std::string modelName) [constructor] cls.add_constructor([param('std::string', 'modelName')]) ## device-energy-model-container.h (module 'energy'): ns3::DeviceEnergyModelContainer::DeviceEnergyModelContainer(ns3::DeviceEnergyModelContainer const & a, ns3::DeviceEnergyModelContainer const & b) [constructor] cls.add_constructor([param('ns3::DeviceEnergyModelContainer const &', 'a'), param('ns3::DeviceEnergyModelContainer const &', 'b')]) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::DeviceEnergyModelContainer container) [member function] cls.add_method('Add', 'void', [param('ns3::DeviceEnergyModelContainer', 'container')]) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(ns3::Ptr<ns3::DeviceEnergyModel> model) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::DeviceEnergyModel >', 'model')]) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Add(std::string modelName) [member function] cls.add_method('Add', 'void', [param('std::string', 'modelName')]) ## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >', [], is_const=True) ## device-energy-model-container.h (module 'energy'): void ns3::DeviceEnergyModelContainer::Clear() [member function] cls.add_method('Clear', 'void', []) ## device-energy-model-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::DeviceEnergyModel>*,std::vector<ns3::Ptr<ns3::DeviceEnergyModel>, std::allocator<ns3::Ptr<ns3::DeviceEnergyModel> > > > ns3::DeviceEnergyModelContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::DeviceEnergyModel > const, std::vector< ns3::Ptr< ns3::DeviceEnergyModel > > >', [], is_const=True) ## device-energy-model-container.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::DeviceEnergyModel >', [param('uint32_t', 'i')], is_const=True) ## device-energy-model-container.h (module 'energy'): uint32_t ns3::DeviceEnergyModelContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3DeviceEnergyModelHelper_methods(root_module, cls): ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper() [constructor] cls.add_constructor([]) ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelHelper::DeviceEnergyModelHelper(ns3::DeviceEnergyModelHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeviceEnergyModelHelper const &', 'arg0')]) ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function] cls.add_method('Install', 'ns3::DeviceEnergyModelContainer', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::DeviceEnergyModelHelper::Install(ns3::NetDeviceContainer deviceContainer, ns3::EnergySourceContainer sourceContainer) const [member function] cls.add_method('Install', 'ns3::DeviceEnergyModelContainer', [param('ns3::NetDeviceContainer', 'deviceContainer'), param('ns3::EnergySourceContainer', 'sourceContainer')], is_const=True) ## energy-model-helper.h (module 'energy'): void ns3::DeviceEnergyModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_pure_virtual=True, is_virtual=True) ## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::DeviceEnergyModelHelper::DoInstall(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::DeviceEnergyModel >', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3EnergySourceHelper_methods(root_module, cls): ## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper() [constructor] cls.add_constructor([]) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceHelper::EnergySourceHelper(ns3::EnergySourceHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnergySourceHelper const &', 'arg0')]) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::EnergySourceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'ns3::EnergySourceContainer', [param('ns3::NodeContainer', 'c')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'ns3::EnergySourceContainer', [param('std::string', 'nodeName')], is_const=True) ## energy-model-helper.h (module 'energy'): ns3::EnergySourceContainer ns3::EnergySourceHelper::InstallAll() const [member function] cls.add_method('InstallAll', 'ns3::EnergySourceContainer', [], is_const=True) ## energy-model-helper.h (module 'energy'): void ns3::EnergySourceHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_pure_virtual=True, is_virtual=True) ## energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergySourceHelper::DoInstall(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::EnergySource >', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_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_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3RvBatteryModelHelper_methods(root_module, cls): ## rv-battery-model-helper.h (module 'energy'): ns3::RvBatteryModelHelper::RvBatteryModelHelper(ns3::RvBatteryModelHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::RvBatteryModelHelper const &', 'arg0')]) ## rv-battery-model-helper.h (module 'energy'): ns3::RvBatteryModelHelper::RvBatteryModelHelper() [constructor] cls.add_constructor([]) ## rv-battery-model-helper.h (module 'energy'): void ns3::RvBatteryModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_virtual=True) ## rv-battery-model-helper.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::RvBatteryModelHelper::DoInstall(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::EnergySource >', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TracedValue__Double_methods(root_module, cls): ## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue() [constructor] cls.add_constructor([]) ## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue(ns3::TracedValue<double> const & o) [copy constructor] cls.add_constructor([param('ns3::TracedValue< double > const &', 'o')]) ## traced-value.h (module 'core'): ns3::TracedValue<double>::TracedValue(double const & v) [constructor] cls.add_constructor([param('double const &', 'v')]) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::Connect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Connect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::ConnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('ConnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::Disconnect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Disconnect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::DisconnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('DisconnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): double ns3::TracedValue<double>::Get() const [member function] cls.add_method('Get', 'double', [], is_const=True) ## traced-value.h (module 'core'): void ns3::TracedValue<double>::Set(double const & v) [member function] cls.add_method('Set', 'void', [param('double const &', 'v')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3WifiMode_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode(ns3::WifiMode const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiMode const &', 'arg0')]) ## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode() [constructor] cls.add_constructor([]) ## wifi-mode.h (module 'wifi'): ns3::WifiMode::WifiMode(std::string name) [constructor] cls.add_constructor([param('std::string', 'name')]) ## wifi-mode.h (module 'wifi'): uint32_t ns3::WifiMode::GetBandwidth() const [member function] cls.add_method('GetBandwidth', 'uint32_t', [], is_const=True) ## wifi-mode.h (module 'wifi'): ns3::WifiCodeRate ns3::WifiMode::GetCodeRate() const [member function] cls.add_method('GetCodeRate', 'ns3::WifiCodeRate', [], is_const=True) ## wifi-mode.h (module 'wifi'): uint8_t ns3::WifiMode::GetConstellationSize() const [member function] cls.add_method('GetConstellationSize', 'uint8_t', [], is_const=True) ## wifi-mode.h (module 'wifi'): uint64_t ns3::WifiMode::GetDataRate() const [member function] cls.add_method('GetDataRate', 'uint64_t', [], is_const=True) ## wifi-mode.h (module 'wifi'): ns3::WifiModulationClass ns3::WifiMode::GetModulationClass() const [member function] cls.add_method('GetModulationClass', 'ns3::WifiModulationClass', [], is_const=True) ## wifi-mode.h (module 'wifi'): uint64_t ns3::WifiMode::GetPhyRate() const [member function] cls.add_method('GetPhyRate', 'uint64_t', [], is_const=True) ## wifi-mode.h (module 'wifi'): uint32_t ns3::WifiMode::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## wifi-mode.h (module 'wifi'): std::string ns3::WifiMode::GetUniqueName() const [member function] cls.add_method('GetUniqueName', 'std::string', [], is_const=True) ## wifi-mode.h (module 'wifi'): bool ns3::WifiMode::IsMandatory() const [member function] cls.add_method('IsMandatory', 'bool', [], is_const=True) return def register_Ns3WifiModeFactory_methods(root_module, cls): ## wifi-mode.h (module 'wifi'): ns3::WifiModeFactory::WifiModeFactory(ns3::WifiModeFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiModeFactory const &', 'arg0')]) ## wifi-mode.h (module 'wifi'): static ns3::WifiMode ns3::WifiModeFactory::CreateWifiMode(std::string uniqueName, ns3::WifiModulationClass modClass, bool isMandatory, uint32_t bandwidth, uint32_t dataRate, ns3::WifiCodeRate codingRate, uint8_t constellationSize) [member function] cls.add_method('CreateWifiMode', 'ns3::WifiMode', [param('std::string', 'uniqueName'), param('ns3::WifiModulationClass', 'modClass'), param('bool', 'isMandatory'), param('uint32_t', 'bandwidth'), param('uint32_t', 'dataRate'), param('ns3::WifiCodeRate', 'codingRate'), param('uint8_t', 'constellationSize')], is_static=True) return def register_Ns3WifiPhyListener_methods(root_module, cls): ## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener::WifiPhyListener() [constructor] cls.add_constructor([]) ## wifi-phy.h (module 'wifi'): ns3::WifiPhyListener::WifiPhyListener(ns3::WifiPhyListener const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiPhyListener const &', 'arg0')]) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyMaybeCcaBusyStart(ns3::Time duration) [member function] cls.add_method('NotifyMaybeCcaBusyStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxEndError() [member function] cls.add_method('NotifyRxEndError', 'void', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxEndOk() [member function] cls.add_method('NotifyRxEndOk', 'void', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyRxStart(ns3::Time duration) [member function] cls.add_method('NotifyRxStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifySwitchingStart(ns3::Time duration) [member function] cls.add_method('NotifySwitchingStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhyListener::NotifyTxStart(ns3::Time duration) [member function] cls.add_method('NotifyTxStart', 'void', [param('ns3::Time', 'duration')], is_pure_virtual=True, is_virtual=True) return def register_Ns3WifiRadioEnergyModelHelper_methods(root_module, cls): ## wifi-radio-energy-model-helper.h (module 'energy'): ns3::WifiRadioEnergyModelHelper::WifiRadioEnergyModelHelper(ns3::WifiRadioEnergyModelHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiRadioEnergyModelHelper const &', 'arg0')]) ## wifi-radio-energy-model-helper.h (module 'energy'): ns3::WifiRadioEnergyModelHelper::WifiRadioEnergyModelHelper() [constructor] cls.add_constructor([]) ## wifi-radio-energy-model-helper.h (module 'energy'): void ns3::WifiRadioEnergyModelHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_virtual=True) ## wifi-radio-energy-model-helper.h (module 'energy'): void ns3::WifiRadioEnergyModelHelper::SetDepletionCallback(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('SetDepletionCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## wifi-radio-energy-model-helper.h (module 'energy'): ns3::Ptr<ns3::DeviceEnergyModel> ns3::WifiRadioEnergyModelHelper::DoInstall(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<ns3::EnergySource> source) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::DeviceEnergyModel >', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::EnergySource >', 'source')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3WifiRadioEnergyModelPhyListener_methods(root_module, cls): ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiRadioEnergyModelPhyListener::WifiRadioEnergyModelPhyListener(ns3::WifiRadioEnergyModelPhyListener const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiRadioEnergyModelPhyListener const &', 'arg0')]) ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiRadioEnergyModelPhyListener::WifiRadioEnergyModelPhyListener() [constructor] cls.add_constructor([]) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModelPhyListener::NotifyMaybeCcaBusyStart(ns3::Time duration) [member function] cls.add_method('NotifyMaybeCcaBusyStart', 'void', [param('ns3::Time', 'duration')], is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModelPhyListener::NotifyRxEndError() [member function] cls.add_method('NotifyRxEndError', 'void', [], is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModelPhyListener::NotifyRxEndOk() [member function] cls.add_method('NotifyRxEndOk', 'void', [], is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModelPhyListener::NotifyRxStart(ns3::Time duration) [member function] cls.add_method('NotifyRxStart', 'void', [param('ns3::Time', 'duration')], is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModelPhyListener::NotifySwitchingStart(ns3::Time duration) [member function] cls.add_method('NotifySwitchingStart', 'void', [param('ns3::Time', 'duration')], is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModelPhyListener::NotifyTxStart(ns3::Time duration) [member function] cls.add_method('NotifyTxStart', 'void', [param('ns3::Time', 'duration')], is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModelPhyListener::SetChangeStateCallback(ns3::Callback<void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('SetChangeStateCallback', 'void', [param('ns3::Callback< void, int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) return def register_Ns3WifiTxVector_methods(root_module, cls): cls.add_output_stream_operator() ## wifi-tx-vector.h (module 'wifi'): ns3::WifiTxVector::WifiTxVector(ns3::WifiTxVector const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiTxVector const &', 'arg0')]) ## wifi-tx-vector.h (module 'wifi'): ns3::WifiTxVector::WifiTxVector() [constructor] cls.add_constructor([]) ## wifi-tx-vector.h (module 'wifi'): ns3::WifiTxVector::WifiTxVector(ns3::WifiMode mode, uint8_t powerLevel, uint8_t retries, bool shortGuardInterval, uint8_t nss, uint8_t ness, bool stbc) [constructor] cls.add_constructor([param('ns3::WifiMode', 'mode'), param('uint8_t', 'powerLevel'), param('uint8_t', 'retries'), param('bool', 'shortGuardInterval'), param('uint8_t', 'nss'), param('uint8_t', 'ness'), param('bool', 'stbc')]) ## wifi-tx-vector.h (module 'wifi'): ns3::WifiMode ns3::WifiTxVector::GetMode() const [member function] cls.add_method('GetMode', 'ns3::WifiMode', [], is_const=True) ## wifi-tx-vector.h (module 'wifi'): uint8_t ns3::WifiTxVector::GetNess() const [member function] cls.add_method('GetNess', 'uint8_t', [], is_const=True) ## wifi-tx-vector.h (module 'wifi'): uint8_t ns3::WifiTxVector::GetNss() const [member function] cls.add_method('GetNss', 'uint8_t', [], is_const=True) ## wifi-tx-vector.h (module 'wifi'): uint8_t ns3::WifiTxVector::GetRetries() const [member function] cls.add_method('GetRetries', 'uint8_t', [], is_const=True) ## wifi-tx-vector.h (module 'wifi'): uint8_t ns3::WifiTxVector::GetTxPowerLevel() const [member function] cls.add_method('GetTxPowerLevel', 'uint8_t', [], is_const=True) ## wifi-tx-vector.h (module 'wifi'): bool ns3::WifiTxVector::IsShortGuardInterval() const [member function] cls.add_method('IsShortGuardInterval', 'bool', [], is_const=True) ## wifi-tx-vector.h (module 'wifi'): bool ns3::WifiTxVector::IsStbc() const [member function] cls.add_method('IsStbc', 'bool', [], is_const=True) ## wifi-tx-vector.h (module 'wifi'): void ns3::WifiTxVector::SetMode(ns3::WifiMode mode) [member function] cls.add_method('SetMode', 'void', [param('ns3::WifiMode', 'mode')]) ## wifi-tx-vector.h (module 'wifi'): void ns3::WifiTxVector::SetNess(uint8_t ness) [member function] cls.add_method('SetNess', 'void', [param('uint8_t', 'ness')]) ## wifi-tx-vector.h (module 'wifi'): void ns3::WifiTxVector::SetNss(uint8_t nss) [member function] cls.add_method('SetNss', 'void', [param('uint8_t', 'nss')]) ## wifi-tx-vector.h (module 'wifi'): void ns3::WifiTxVector::SetRetries(uint8_t retries) [member function] cls.add_method('SetRetries', 'void', [param('uint8_t', 'retries')]) ## wifi-tx-vector.h (module 'wifi'): void ns3::WifiTxVector::SetShortGuardInterval(bool guardinterval) [member function] cls.add_method('SetShortGuardInterval', 'void', [param('bool', 'guardinterval')]) ## wifi-tx-vector.h (module 'wifi'): void ns3::WifiTxVector::SetStbc(bool stbc) [member function] cls.add_method('SetStbc', 'void', [param('bool', 'stbc')]) ## wifi-tx-vector.h (module 'wifi'): void ns3::WifiTxVector::SetTxPowerLevel(uint8_t powerlevel) [member function] cls.add_method('SetTxPowerLevel', 'void', [param('uint8_t', 'powerlevel')]) 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_Ns3BasicEnergySourceHelper_methods(root_module, cls): ## basic-energy-source-helper.h (module 'energy'): ns3::BasicEnergySourceHelper::BasicEnergySourceHelper(ns3::BasicEnergySourceHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::BasicEnergySourceHelper const &', 'arg0')]) ## basic-energy-source-helper.h (module 'energy'): ns3::BasicEnergySourceHelper::BasicEnergySourceHelper() [constructor] cls.add_constructor([]) ## basic-energy-source-helper.h (module 'energy'): void ns3::BasicEnergySourceHelper::Set(std::string name, ns3::AttributeValue const & v) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'v')], is_virtual=True) ## basic-energy-source-helper.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::BasicEnergySourceHelper::DoInstall(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('DoInstall', 'ns3::Ptr< ns3::EnergySource >', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): 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__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__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_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(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): 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 & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TracedValue__Ns3Time_methods(root_module, cls): ## traced-value.h (module 'core'): ns3::TracedValue<ns3::Time>::TracedValue() [constructor] cls.add_constructor([]) ## traced-value.h (module 'core'): ns3::TracedValue<ns3::Time>::TracedValue(ns3::TracedValue<ns3::Time> const & o) [copy constructor] cls.add_constructor([param('ns3::TracedValue< ns3::Time > const &', 'o')]) ## traced-value.h (module 'core'): ns3::TracedValue<ns3::Time>::TracedValue(ns3::Time const & v) [constructor] cls.add_constructor([param('ns3::Time const &', 'v')]) ## traced-value.h (module 'core'): void ns3::TracedValue<ns3::Time>::Connect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Connect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<ns3::Time>::ConnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('ConnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): void ns3::TracedValue<ns3::Time>::Disconnect(ns3::CallbackBase const & cb, std::basic_string<char,std::char_traits<char>,std::allocator<char> > path) [member function] cls.add_method('Disconnect', 'void', [param('ns3::CallbackBase const &', 'cb'), param('std::string', 'path')]) ## traced-value.h (module 'core'): void ns3::TracedValue<ns3::Time>::DisconnectWithoutContext(ns3::CallbackBase const & cb) [member function] cls.add_method('DisconnectWithoutContext', 'void', [param('ns3::CallbackBase const &', 'cb')]) ## traced-value.h (module 'core'): ns3::Time ns3::TracedValue<ns3::Time>::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## traced-value.h (module 'core'): void ns3::TracedValue<ns3::Time>::Set(ns3::Time const & v) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'v')]) 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_Ns3WifiPhy_methods(root_module, cls): ## wifi-phy.h (module 'wifi'): ns3::WifiPhy::WifiPhy(ns3::WifiPhy const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiPhy const &', 'arg0')]) ## wifi-phy.h (module 'wifi'): ns3::WifiPhy::WifiPhy() [constructor] cls.add_constructor([]) ## wifi-phy.h (module 'wifi'): int64_t ns3::WifiPhy::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::CalculateSnr(ns3::WifiMode txMode, double ber) const [member function] cls.add_method('CalculateSnr', 'double', [param('ns3::WifiMode', 'txMode'), param('double', 'ber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): static ns3::Time ns3::WifiPhy::CalculateTxDuration(uint32_t size, ns3::WifiTxVector txvector, ns3::WifiPreamble preamble) [member function] cls.add_method('CalculateTxDuration', 'ns3::Time', [param('uint32_t', 'size'), param('ns3::WifiTxVector', 'txvector'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::ConfigureStandard(ns3::WifiPhyStandard standard) [member function] cls.add_method('ConfigureStandard', 'void', [param('ns3::WifiPhyStandard', 'standard')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetBssMembershipSelector(uint32_t selector) const [member function] cls.add_method('GetBssMembershipSelector', 'uint32_t', [param('uint32_t', 'selector')], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): ns3::Ptr<ns3::WifiChannel> ns3::WifiPhy::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::WifiChannel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::GetChannelBonding() const [member function] cls.add_method('GetChannelBonding', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): uint16_t ns3::WifiPhy::GetChannelNumber() const [member function] cls.add_method('GetChannelNumber', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetDelayUntilIdle() [member function] cls.add_method('GetDelayUntilIdle', 'ns3::Time', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate11Mbps() [member function] cls.add_method('GetDsssRate11Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate1Mbps() [member function] cls.add_method('GetDsssRate1Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate2Mbps() [member function] cls.add_method('GetDsssRate2Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetDsssRate5_5Mbps() [member function] cls.add_method('GetDsssRate5_5Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate12Mbps() [member function] cls.add_method('GetErpOfdmRate12Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate18Mbps() [member function] cls.add_method('GetErpOfdmRate18Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate24Mbps() [member function] cls.add_method('GetErpOfdmRate24Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate36Mbps() [member function] cls.add_method('GetErpOfdmRate36Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate48Mbps() [member function] cls.add_method('GetErpOfdmRate48Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate54Mbps() [member function] cls.add_method('GetErpOfdmRate54Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate6Mbps() [member function] cls.add_method('GetErpOfdmRate6Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetErpOfdmRate9Mbps() [member function] cls.add_method('GetErpOfdmRate9Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetFrequency() const [member function] cls.add_method('GetFrequency', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::GetGreenfield() const [member function] cls.add_method('GetGreenfield', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::GetGuardInterval() const [member function] cls.add_method('GetGuardInterval', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetLastRxStartTime() const [member function] cls.add_method('GetLastRxStartTime', 'ns3::Time', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::GetLdpc() const [member function] cls.add_method('GetLdpc', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetMFPlcpHeaderMode(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function] cls.add_method('GetMFPlcpHeaderMode', 'ns3::WifiMode', [param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## wifi-phy.h (module 'wifi'): uint8_t ns3::WifiPhy::GetMcs(uint8_t mcs) const [member function] cls.add_method('GetMcs', 'uint8_t', [param('uint8_t', 'mcs')], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): ns3::WifiModeList ns3::WifiPhy::GetMembershipSelectorModes(uint32_t selector) [member function] cls.add_method('GetMembershipSelectorModes', 'ns3::WifiModeList', [param('uint32_t', 'selector')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): ns3::WifiMode ns3::WifiPhy::GetMode(uint32_t mode) const [member function] cls.add_method('GetMode', 'ns3::WifiMode', [param('uint32_t', 'mode')], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNBssMembershipSelectors() const [member function] cls.add_method('GetNBssMembershipSelectors', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): uint8_t ns3::WifiPhy::GetNMcs() const [member function] cls.add_method('GetNMcs', 'uint8_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNModes() const [member function] cls.add_method('GetNModes', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNTxPower() const [member function] cls.add_method('GetNTxPower', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNumberOfReceiveAntennas() const [member function] cls.add_method('GetNumberOfReceiveAntennas', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::GetNumberOfTransmitAntennas() const [member function] cls.add_method('GetNumberOfTransmitAntennas', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate108MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate108MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate120MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate120MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate121_5MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate121_5MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12Mbps() [member function] cls.add_method('GetOfdmRate12Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate12MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate12MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate12MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate135MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate135MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate135MbpsBW40MHzShGi() [member function] cls.add_method('GetOfdmRate135MbpsBW40MHzShGi', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate13MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate13MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate13_5MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate13_5MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate13_5MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate13_5MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate14_4MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate14_4MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate150MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate150MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate15MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate15MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18Mbps() [member function] cls.add_method('GetOfdmRate18Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate18MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate18MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate19_5MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate19_5MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate1_5MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate1_5MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate21_7MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate21_7MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24Mbps() [member function] cls.add_method('GetOfdmRate24Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate24MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate24MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate26MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate26MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate27MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate27MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate27MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate27MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate28_9MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate28_9MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate2_25MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate2_25MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate30MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate30MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate36Mbps() [member function] cls.add_method('GetOfdmRate36Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate39MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate39MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate3MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate3MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate3MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate40_5MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate40_5MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate43_3MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate43_3MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate45MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate45MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate48Mbps() [member function] cls.add_method('GetOfdmRate48Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate4_5MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate4_5MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate4_5MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate52MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate52MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate54Mbps() [member function] cls.add_method('GetOfdmRate54Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate54MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate54MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate57_8MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate57_8MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate58_5MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate58_5MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate60MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate60MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate65MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate65MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate65MbpsBW20MHzShGi() [member function] cls.add_method('GetOfdmRate65MbpsBW20MHzShGi', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6Mbps() [member function] cls.add_method('GetOfdmRate6Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate6MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate6MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate6_5MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate6_5MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate72_2MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate72_2MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate7_2MbpsBW20MHz() [member function] cls.add_method('GetOfdmRate7_2MbpsBW20MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate81MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate81MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate90MbpsBW40MHz() [member function] cls.add_method('GetOfdmRate90MbpsBW40MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9Mbps() [member function] cls.add_method('GetOfdmRate9Mbps', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW10MHz() [member function] cls.add_method('GetOfdmRate9MbpsBW10MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetOfdmRate9MbpsBW5MHz() [member function] cls.add_method('GetOfdmRate9MbpsBW5MHz', 'ns3::WifiMode', [], is_static=True) ## wifi-phy.h (module 'wifi'): static double ns3::WifiPhy::GetPayloadDurationMicroSeconds(uint32_t size, ns3::WifiTxVector txvector) [member function] cls.add_method('GetPayloadDurationMicroSeconds', 'double', [param('uint32_t', 'size'), param('ns3::WifiTxVector', 'txvector')], is_static=True) ## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpHeaderDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function] cls.add_method('GetPlcpHeaderDurationMicroSeconds', 'uint32_t', [param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## wifi-phy.h (module 'wifi'): static ns3::WifiMode ns3::WifiPhy::GetPlcpHeaderMode(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function] cls.add_method('GetPlcpHeaderMode', 'ns3::WifiMode', [param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpHtSigHeaderDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function] cls.add_method('GetPlcpHtSigHeaderDurationMicroSeconds', 'uint32_t', [param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpHtTrainingSymbolDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble, ns3::WifiTxVector txvector) [member function] cls.add_method('GetPlcpHtTrainingSymbolDurationMicroSeconds', 'uint32_t', [param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble'), param('ns3::WifiTxVector', 'txvector')], is_static=True) ## wifi-phy.h (module 'wifi'): static uint32_t ns3::WifiPhy::GetPlcpPreambleDurationMicroSeconds(ns3::WifiMode payloadMode, ns3::WifiPreamble preamble) [member function] cls.add_method('GetPlcpPreambleDurationMicroSeconds', 'uint32_t', [param('ns3::WifiMode', 'payloadMode'), param('ns3::WifiPreamble', 'preamble')], is_static=True) ## wifi-phy.h (module 'wifi'): ns3::Time ns3::WifiPhy::GetStateDuration() [member function] cls.add_method('GetStateDuration', 'ns3::Time', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::GetStbc() const [member function] cls.add_method('GetStbc', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::GetTxPowerEnd() const [member function] cls.add_method('GetTxPowerEnd', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): double ns3::WifiPhy::GetTxPowerStart() const [member function] cls.add_method('GetTxPowerStart', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): static ns3::TypeId ns3::WifiPhy::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsModeSupported(ns3::WifiMode mode) const [member function] cls.add_method('IsModeSupported', 'bool', [param('ns3::WifiMode', 'mode')], is_pure_virtual=True, is_const=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateBusy() [member function] cls.add_method('IsStateBusy', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateCcaBusy() [member function] cls.add_method('IsStateCcaBusy', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateIdle() [member function] cls.add_method('IsStateIdle', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateRx() [member function] cls.add_method('IsStateRx', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateSwitching() [member function] cls.add_method('IsStateSwitching', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): bool ns3::WifiPhy::IsStateTx() [member function] cls.add_method('IsStateTx', 'bool', [], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): ns3::WifiMode ns3::WifiPhy::McsToWifiMode(uint8_t mcs) [member function] cls.add_method('McsToWifiMode', 'ns3::WifiMode', [param('uint8_t', 'mcs')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyMonitorSniffRx(ns3::Ptr<const ns3::Packet> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble, double signalDbm, double noiseDbm) [member function] cls.add_method('NotifyMonitorSniffRx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble'), param('double', 'signalDbm'), param('double', 'noiseDbm')]) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyMonitorSniffTx(ns3::Ptr<const ns3::Packet> packet, uint16_t channelFreqMhz, uint16_t channelNumber, uint32_t rate, bool isShortPreamble, uint8_t txPower) [member function] cls.add_method('NotifyMonitorSniffTx', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'channelFreqMhz'), param('uint16_t', 'channelNumber'), param('uint32_t', 'rate'), param('bool', 'isShortPreamble'), param('uint8_t', 'txPower')]) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxBegin(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyRxBegin', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxDrop(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyRxDrop', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyRxEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyRxEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxBegin(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyTxBegin', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxDrop(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyTxDrop', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::NotifyTxEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('NotifyTxEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::RegisterListener(ns3::WifiPhyListener * listener) [member function] cls.add_method('RegisterListener', 'void', [param('ns3::WifiPhyListener *', 'listener')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SendPacket(ns3::Ptr<const ns3::Packet> packet, ns3::WifiMode mode, ns3::WifiPreamble preamble, ns3::WifiTxVector txvector) [member function] cls.add_method('SendPacket', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet'), param('ns3::WifiMode', 'mode'), param('ns3::WifiPreamble', 'preamble'), param('ns3::WifiTxVector', 'txvector')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetChannelBonding(bool channelbonding) [member function] cls.add_method('SetChannelBonding', 'void', [param('bool', 'channelbonding')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetChannelNumber(uint16_t id) [member function] cls.add_method('SetChannelNumber', 'void', [param('uint16_t', 'id')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetFrequency(uint32_t freq) [member function] cls.add_method('SetFrequency', 'void', [param('uint32_t', 'freq')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetGreenfield(bool greenfield) [member function] cls.add_method('SetGreenfield', 'void', [param('bool', 'greenfield')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetGuardInterval(bool guardInterval) [member function] cls.add_method('SetGuardInterval', 'void', [param('bool', 'guardInterval')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetLdpc(bool ldpc) [member function] cls.add_method('SetLdpc', 'void', [param('bool', 'ldpc')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetNumberOfReceiveAntennas(uint32_t rx) [member function] cls.add_method('SetNumberOfReceiveAntennas', 'void', [param('uint32_t', 'rx')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetNumberOfTransmitAntennas(uint32_t tx) [member function] cls.add_method('SetNumberOfTransmitAntennas', 'void', [param('uint32_t', 'tx')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetReceiveErrorCallback(ns3::Callback<void,ns3::Ptr<const ns3::Packet>,double,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('SetReceiveErrorCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, double, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetReceiveOkCallback(ns3::Callback<void,ns3::Ptr<ns3::Packet>,double,ns3::WifiMode,ns3::WifiPreamble,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('SetReceiveOkCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, double, ns3::WifiMode, ns3::WifiPreamble, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): void ns3::WifiPhy::SetStbc(bool stbc) [member function] cls.add_method('SetStbc', 'void', [param('bool', 'stbc')], is_pure_virtual=True, is_virtual=True) ## wifi-phy.h (module 'wifi'): uint32_t ns3::WifiPhy::WifiModeToMcs(ns3::WifiMode mode) [member function] cls.add_method('WifiModeToMcs', 'uint32_t', [param('ns3::WifiMode', 'mode')], is_pure_virtual=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_Ns3BooleanChecker_methods(root_module, cls): ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanChecker::BooleanChecker(ns3::BooleanChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanChecker const &', 'arg0')]) return def register_Ns3BooleanValue_methods(root_module, cls): cls.add_output_stream_operator() ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(ns3::BooleanValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::BooleanValue const &', 'arg0')]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue() [constructor] cls.add_constructor([]) ## boolean.h (module 'core'): ns3::BooleanValue::BooleanValue(bool value) [constructor] cls.add_constructor([param('bool', 'value')]) ## boolean.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::BooleanValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## boolean.h (module 'core'): bool ns3::BooleanValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## boolean.h (module 'core'): bool ns3::BooleanValue::Get() const [member function] cls.add_method('Get', 'bool', [], is_const=True) ## boolean.h (module 'core'): std::string ns3::BooleanValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## boolean.h (module 'core'): void ns3::BooleanValue::Set(bool value) [member function] cls.add_method('Set', 'void', [param('bool', 'value')]) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3DeviceEnergyModel_methods(root_module, cls): ## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel::DeviceEnergyModel(ns3::DeviceEnergyModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::DeviceEnergyModel const &', 'arg0')]) ## device-energy-model.h (module 'energy'): ns3::DeviceEnergyModel::DeviceEnergyModel() [constructor] cls.add_constructor([]) ## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::ChangeState(int newState) [member function] cls.add_method('ChangeState', 'void', [param('int', 'newState')], is_pure_virtual=True, is_virtual=True) ## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::GetCurrentA() const [member function] cls.add_method('GetCurrentA', 'double', [], is_const=True) ## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::GetTotalEnergyConsumption() const [member function] cls.add_method('GetTotalEnergyConsumption', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## device-energy-model.h (module 'energy'): static ns3::TypeId ns3::DeviceEnergyModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::HandleEnergyDepletion() [member function] cls.add_method('HandleEnergyDepletion', 'void', [], is_pure_virtual=True, is_virtual=True) ## device-energy-model.h (module 'energy'): void ns3::DeviceEnergyModel::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function] cls.add_method('SetEnergySource', 'void', [param('ns3::Ptr< ns3::EnergySource >', 'source')], is_pure_virtual=True, is_virtual=True) ## device-energy-model.h (module 'energy'): double ns3::DeviceEnergyModel::DoGetCurrentA() const [member function] cls.add_method('DoGetCurrentA', 'double', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3DoubleValue_methods(root_module, cls): ## double.h (module 'core'): ns3::DoubleValue::DoubleValue() [constructor] cls.add_constructor([]) ## double.h (module 'core'): ns3::DoubleValue::DoubleValue(ns3::DoubleValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DoubleValue const &', 'arg0')]) ## double.h (module 'core'): ns3::DoubleValue::DoubleValue(double const & value) [constructor] cls.add_constructor([param('double const &', 'value')]) ## double.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::DoubleValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## double.h (module 'core'): bool ns3::DoubleValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## double.h (module 'core'): double ns3::DoubleValue::Get() const [member function] cls.add_method('Get', 'double', [], is_const=True) ## double.h (module 'core'): std::string ns3::DoubleValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## double.h (module 'core'): void ns3::DoubleValue::Set(double const & value) [member function] cls.add_method('Set', 'void', [param('double const &', 'value')]) return def register_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_Ns3EnergySource_methods(root_module, cls): ## energy-source.h (module 'energy'): ns3::EnergySource::EnergySource(ns3::EnergySource const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnergySource const &', 'arg0')]) ## energy-source.h (module 'energy'): ns3::EnergySource::EnergySource() [constructor] cls.add_constructor([]) ## energy-source.h (module 'energy'): void ns3::EnergySource::AppendDeviceEnergyModel(ns3::Ptr<ns3::DeviceEnergyModel> deviceEnergyModelPtr) [member function] cls.add_method('AppendDeviceEnergyModel', 'void', [param('ns3::Ptr< ns3::DeviceEnergyModel >', 'deviceEnergyModelPtr')]) ## energy-source.h (module 'energy'): void ns3::EnergySource::DisposeDeviceModels() [member function] cls.add_method('DisposeDeviceModels', 'void', []) ## energy-source.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::EnergySource::FindDeviceEnergyModels(ns3::TypeId tid) [member function] cls.add_method('FindDeviceEnergyModels', 'ns3::DeviceEnergyModelContainer', [param('ns3::TypeId', 'tid')]) ## energy-source.h (module 'energy'): ns3::DeviceEnergyModelContainer ns3::EnergySource::FindDeviceEnergyModels(std::string name) [member function] cls.add_method('FindDeviceEnergyModels', 'ns3::DeviceEnergyModelContainer', [param('std::string', 'name')]) ## energy-source.h (module 'energy'): double ns3::EnergySource::GetEnergyFraction() [member function] cls.add_method('GetEnergyFraction', 'double', [], is_pure_virtual=True, is_virtual=True) ## energy-source.h (module 'energy'): double ns3::EnergySource::GetInitialEnergy() const [member function] cls.add_method('GetInitialEnergy', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## energy-source.h (module 'energy'): ns3::Ptr<ns3::Node> ns3::EnergySource::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## energy-source.h (module 'energy'): double ns3::EnergySource::GetRemainingEnergy() [member function] cls.add_method('GetRemainingEnergy', 'double', [], is_pure_virtual=True, is_virtual=True) ## energy-source.h (module 'energy'): double ns3::EnergySource::GetSupplyVoltage() const [member function] cls.add_method('GetSupplyVoltage', 'double', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## energy-source.h (module 'energy'): static ns3::TypeId ns3::EnergySource::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## energy-source.h (module 'energy'): void ns3::EnergySource::InitializeDeviceModels() [member function] cls.add_method('InitializeDeviceModels', 'void', []) ## energy-source.h (module 'energy'): void ns3::EnergySource::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## energy-source.h (module 'energy'): void ns3::EnergySource::UpdateEnergySource() [member function] cls.add_method('UpdateEnergySource', 'void', [], is_pure_virtual=True, is_virtual=True) ## energy-source.h (module 'energy'): void ns3::EnergySource::BreakDeviceEnergyModelRefCycle() [member function] cls.add_method('BreakDeviceEnergyModelRefCycle', 'void', [], visibility='protected') ## energy-source.h (module 'energy'): double ns3::EnergySource::CalculateTotalCurrent() [member function] cls.add_method('CalculateTotalCurrent', 'double', [], visibility='protected') ## energy-source.h (module 'energy'): void ns3::EnergySource::NotifyEnergyDrained() [member function] cls.add_method('NotifyEnergyDrained', 'void', [], visibility='protected') ## energy-source.h (module 'energy'): void ns3::EnergySource::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EnergySourceContainer_methods(root_module, cls): ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::EnergySourceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnergySourceContainer const &', 'arg0')]) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer() [constructor] cls.add_constructor([]) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::Ptr<ns3::EnergySource> source) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EnergySource >', 'source')]) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(std::string sourceName) [constructor] cls.add_constructor([param('std::string', 'sourceName')]) ## energy-source-container.h (module 'energy'): ns3::EnergySourceContainer::EnergySourceContainer(ns3::EnergySourceContainer const & a, ns3::EnergySourceContainer const & b) [constructor] cls.add_constructor([param('ns3::EnergySourceContainer const &', 'a'), param('ns3::EnergySourceContainer const &', 'b')]) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(ns3::EnergySourceContainer container) [member function] cls.add_method('Add', 'void', [param('ns3::EnergySourceContainer', 'container')]) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(ns3::Ptr<ns3::EnergySource> source) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::EnergySource >', 'source')]) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::Add(std::string sourceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'sourceName')]) ## energy-source-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::EnergySource>*,std::vector<ns3::Ptr<ns3::EnergySource>, std::allocator<ns3::Ptr<ns3::EnergySource> > > > ns3::EnergySourceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::EnergySource > const, std::vector< ns3::Ptr< ns3::EnergySource > > >', [], is_const=True) ## energy-source-container.h (module 'energy'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::EnergySource>*,std::vector<ns3::Ptr<ns3::EnergySource>, std::allocator<ns3::Ptr<ns3::EnergySource> > > > ns3::EnergySourceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::EnergySource > const, std::vector< ns3::Ptr< ns3::EnergySource > > >', [], is_const=True) ## energy-source-container.h (module 'energy'): ns3::Ptr<ns3::EnergySource> ns3::EnergySourceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::EnergySource >', [param('uint32_t', 'i')], is_const=True) ## energy-source-container.h (module 'energy'): uint32_t ns3::EnergySourceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## energy-source-container.h (module 'energy'): static ns3::TypeId ns3::EnergySourceContainer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## energy-source-container.h (module 'energy'): void ns3::EnergySourceContainer::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='private', is_virtual=True) return def register_Ns3EnumChecker_methods(root_module, cls): ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')]) ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor] cls.add_constructor([]) ## enum.h (module 'core'): void ns3::EnumChecker::Add(int v, std::string name) [member function] cls.add_method('Add', 'void', [param('int', 'v'), param('std::string', 'name')]) ## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int v, std::string name) [member function] cls.add_method('AddDefault', 'void', [param('int', 'v'), param('std::string', 'name')]) ## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')], is_const=True, is_virtual=True) ## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_const=True, is_virtual=True) return def register_Ns3EnumValue_methods(root_module, cls): ## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EnumValue const &', 'arg0')]) ## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor] cls.add_constructor([]) ## enum.h (module 'core'): ns3::EnumValue::EnumValue(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## enum.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EnumValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function] cls.add_method('Get', 'int', [], is_const=True) ## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## enum.h (module 'core'): void ns3::EnumValue::Set(int v) [member function] cls.add_method('Set', 'void', [param('int', 'v')]) 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_Ns3IntegerValue_methods(root_module, cls): ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor] cls.add_constructor([]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')]) ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor] cls.add_constructor([param('int64_t const &', 'value')]) ## integer.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::IntegerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## integer.h (module 'core'): bool ns3::IntegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function] cls.add_method('Get', 'int64_t', [], is_const=True) ## integer.h (module 'core'): std::string ns3::IntegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function] cls.add_method('Set', 'void', [param('int64_t const &', 'value')]) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3LiIonEnergySource_methods(root_module, cls): ## li-ion-energy-source.h (module 'energy'): ns3::LiIonEnergySource::LiIonEnergySource(ns3::LiIonEnergySource const & arg0) [copy constructor] cls.add_constructor([param('ns3::LiIonEnergySource const &', 'arg0')]) ## li-ion-energy-source.h (module 'energy'): ns3::LiIonEnergySource::LiIonEnergySource() [constructor] cls.add_constructor([]) ## li-ion-energy-source.h (module 'energy'): void ns3::LiIonEnergySource::DecreaseRemainingEnergy(double energyJ) [member function] cls.add_method('DecreaseRemainingEnergy', 'void', [param('double', 'energyJ')], is_virtual=True) ## li-ion-energy-source.h (module 'energy'): double ns3::LiIonEnergySource::GetEnergyFraction() [member function] cls.add_method('GetEnergyFraction', 'double', [], is_virtual=True) ## li-ion-energy-source.h (module 'energy'): ns3::Time ns3::LiIonEnergySource::GetEnergyUpdateInterval() const [member function] cls.add_method('GetEnergyUpdateInterval', 'ns3::Time', [], is_const=True) ## li-ion-energy-source.h (module 'energy'): double ns3::LiIonEnergySource::GetInitialEnergy() const [member function] cls.add_method('GetInitialEnergy', 'double', [], is_const=True, is_virtual=True) ## li-ion-energy-source.h (module 'energy'): double ns3::LiIonEnergySource::GetRemainingEnergy() [member function] cls.add_method('GetRemainingEnergy', 'double', [], is_virtual=True) ## li-ion-energy-source.h (module 'energy'): double ns3::LiIonEnergySource::GetSupplyVoltage() const [member function] cls.add_method('GetSupplyVoltage', 'double', [], is_const=True, is_virtual=True) ## li-ion-energy-source.h (module 'energy'): static ns3::TypeId ns3::LiIonEnergySource::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## li-ion-energy-source.h (module 'energy'): void ns3::LiIonEnergySource::IncreaseRemainingEnergy(double energyJ) [member function] cls.add_method('IncreaseRemainingEnergy', 'void', [param('double', 'energyJ')], is_virtual=True) ## li-ion-energy-source.h (module 'energy'): void ns3::LiIonEnergySource::SetEnergyUpdateInterval(ns3::Time interval) [member function] cls.add_method('SetEnergyUpdateInterval', 'void', [param('ns3::Time', 'interval')]) ## li-ion-energy-source.h (module 'energy'): void ns3::LiIonEnergySource::SetInitialEnergy(double initialEnergyJ) [member function] cls.add_method('SetInitialEnergy', 'void', [param('double', 'initialEnergyJ')]) ## li-ion-energy-source.h (module 'energy'): void ns3::LiIonEnergySource::SetInitialSupplyVoltage(double supplyVoltageV) [member function] cls.add_method('SetInitialSupplyVoltage', 'void', [param('double', 'supplyVoltageV')]) ## li-ion-energy-source.h (module 'energy'): void ns3::LiIonEnergySource::UpdateEnergySource() [member function] cls.add_method('UpdateEnergySource', 'void', [], is_virtual=True) ## li-ion-energy-source.h (module 'energy'): void ns3::LiIonEnergySource::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## li-ion-energy-source.h (module 'energy'): void ns3::LiIonEnergySource::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='private', is_virtual=True) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) return def register_Ns3RvBatteryModel_methods(root_module, cls): ## rv-battery-model.h (module 'energy'): ns3::RvBatteryModel::RvBatteryModel(ns3::RvBatteryModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RvBatteryModel const &', 'arg0')]) ## rv-battery-model.h (module 'energy'): ns3::RvBatteryModel::RvBatteryModel() [constructor] cls.add_constructor([]) ## rv-battery-model.h (module 'energy'): double ns3::RvBatteryModel::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## rv-battery-model.h (module 'energy'): double ns3::RvBatteryModel::GetBatteryLevel() [member function] cls.add_method('GetBatteryLevel', 'double', []) ## rv-battery-model.h (module 'energy'): double ns3::RvBatteryModel::GetBeta() const [member function] cls.add_method('GetBeta', 'double', [], is_const=True) ## rv-battery-model.h (module 'energy'): double ns3::RvBatteryModel::GetCutoffVoltage() const [member function] cls.add_method('GetCutoffVoltage', 'double', [], is_const=True) ## rv-battery-model.h (module 'energy'): double ns3::RvBatteryModel::GetEnergyFraction() [member function] cls.add_method('GetEnergyFraction', 'double', [], is_virtual=True) ## rv-battery-model.h (module 'energy'): double ns3::RvBatteryModel::GetInitialEnergy() const [member function] cls.add_method('GetInitialEnergy', 'double', [], is_const=True, is_virtual=True) ## rv-battery-model.h (module 'energy'): ns3::Time ns3::RvBatteryModel::GetLifetime() const [member function] cls.add_method('GetLifetime', 'ns3::Time', [], is_const=True) ## rv-battery-model.h (module 'energy'): int ns3::RvBatteryModel::GetNumOfTerms() const [member function] cls.add_method('GetNumOfTerms', 'int', [], is_const=True) ## rv-battery-model.h (module 'energy'): double ns3::RvBatteryModel::GetOpenCircuitVoltage() const [member function] cls.add_method('GetOpenCircuitVoltage', 'double', [], is_const=True) ## rv-battery-model.h (module 'energy'): double ns3::RvBatteryModel::GetRemainingEnergy() [member function] cls.add_method('GetRemainingEnergy', 'double', [], is_virtual=True) ## rv-battery-model.h (module 'energy'): ns3::Time ns3::RvBatteryModel::GetSamplingInterval() const [member function] cls.add_method('GetSamplingInterval', 'ns3::Time', [], is_const=True) ## rv-battery-model.h (module 'energy'): double ns3::RvBatteryModel::GetSupplyVoltage() const [member function] cls.add_method('GetSupplyVoltage', 'double', [], is_const=True, is_virtual=True) ## rv-battery-model.h (module 'energy'): static ns3::TypeId ns3::RvBatteryModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## rv-battery-model.h (module 'energy'): void ns3::RvBatteryModel::SetAlpha(double alpha) [member function] cls.add_method('SetAlpha', 'void', [param('double', 'alpha')]) ## rv-battery-model.h (module 'energy'): void ns3::RvBatteryModel::SetBeta(double beta) [member function] cls.add_method('SetBeta', 'void', [param('double', 'beta')]) ## rv-battery-model.h (module 'energy'): void ns3::RvBatteryModel::SetCutoffVoltage(double voltage) [member function] cls.add_method('SetCutoffVoltage', 'void', [param('double', 'voltage')]) ## rv-battery-model.h (module 'energy'): void ns3::RvBatteryModel::SetNumOfTerms(int num) [member function] cls.add_method('SetNumOfTerms', 'void', [param('int', 'num')]) ## rv-battery-model.h (module 'energy'): void ns3::RvBatteryModel::SetOpenCircuitVoltage(double voltage) [member function] cls.add_method('SetOpenCircuitVoltage', 'void', [param('double', 'voltage')]) ## rv-battery-model.h (module 'energy'): void ns3::RvBatteryModel::SetSamplingInterval(ns3::Time interval) [member function] cls.add_method('SetSamplingInterval', 'void', [param('ns3::Time', 'interval')]) ## rv-battery-model.h (module 'energy'): void ns3::RvBatteryModel::UpdateEnergySource() [member function] cls.add_method('UpdateEnergySource', 'void', [], is_virtual=True) ## rv-battery-model.h (module 'energy'): void ns3::RvBatteryModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## rv-battery-model.h (module 'energy'): void ns3::RvBatteryModel::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='private', is_virtual=True) return def register_Ns3SimpleDeviceEnergyModel_methods(root_module, cls): ## simple-device-energy-model.h (module 'energy'): ns3::SimpleDeviceEnergyModel::SimpleDeviceEnergyModel(ns3::SimpleDeviceEnergyModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SimpleDeviceEnergyModel const &', 'arg0')]) ## simple-device-energy-model.h (module 'energy'): ns3::SimpleDeviceEnergyModel::SimpleDeviceEnergyModel() [constructor] cls.add_constructor([]) ## simple-device-energy-model.h (module 'energy'): void ns3::SimpleDeviceEnergyModel::ChangeState(int newState) [member function] cls.add_method('ChangeState', 'void', [param('int', 'newState')], is_virtual=True) ## simple-device-energy-model.h (module 'energy'): ns3::Ptr<ns3::Node> ns3::SimpleDeviceEnergyModel::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## simple-device-energy-model.h (module 'energy'): double ns3::SimpleDeviceEnergyModel::GetTotalEnergyConsumption() const [member function] cls.add_method('GetTotalEnergyConsumption', 'double', [], is_const=True, is_virtual=True) ## simple-device-energy-model.h (module 'energy'): static ns3::TypeId ns3::SimpleDeviceEnergyModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## simple-device-energy-model.h (module 'energy'): void ns3::SimpleDeviceEnergyModel::HandleEnergyDepletion() [member function] cls.add_method('HandleEnergyDepletion', 'void', [], is_virtual=True) ## simple-device-energy-model.h (module 'energy'): void ns3::SimpleDeviceEnergyModel::SetCurrentA(double current) [member function] cls.add_method('SetCurrentA', 'void', [param('double', 'current')]) ## simple-device-energy-model.h (module 'energy'): void ns3::SimpleDeviceEnergyModel::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function] cls.add_method('SetEnergySource', 'void', [param('ns3::Ptr< ns3::EnergySource >', 'source')], is_virtual=True) ## simple-device-energy-model.h (module 'energy'): void ns3::SimpleDeviceEnergyModel::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## simple-device-energy-model.h (module 'energy'): void ns3::SimpleDeviceEnergyModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## simple-device-energy-model.h (module 'energy'): double ns3::SimpleDeviceEnergyModel::DoGetCurrentA() const [member function] cls.add_method('DoGetCurrentA', 'double', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3UintegerValue_methods(root_module, cls): ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor] cls.add_constructor([]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')]) ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor] cls.add_constructor([param('uint64_t const &', 'value')]) ## uinteger.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::UintegerValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function] cls.add_method('Get', 'uint64_t', [], is_const=True) ## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function] cls.add_method('Set', 'void', [param('uint64_t const &', 'value')]) return def register_Ns3WifiModeChecker_methods(root_module, cls): ## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker::WifiModeChecker() [constructor] cls.add_constructor([]) ## wifi-mode.h (module 'wifi'): ns3::WifiModeChecker::WifiModeChecker(ns3::WifiModeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiModeChecker const &', 'arg0')]) return def register_Ns3WifiModeValue_methods(root_module, cls): ## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue() [constructor] cls.add_constructor([]) ## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue(ns3::WifiModeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiModeValue const &', 'arg0')]) ## wifi-mode.h (module 'wifi'): ns3::WifiModeValue::WifiModeValue(ns3::WifiMode const & value) [constructor] cls.add_constructor([param('ns3::WifiMode const &', 'value')]) ## wifi-mode.h (module 'wifi'): ns3::Ptr<ns3::AttributeValue> ns3::WifiModeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## wifi-mode.h (module 'wifi'): bool ns3::WifiModeValue::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) ## wifi-mode.h (module 'wifi'): ns3::WifiMode ns3::WifiModeValue::Get() const [member function] cls.add_method('Get', 'ns3::WifiMode', [], is_const=True) ## wifi-mode.h (module 'wifi'): std::string ns3::WifiModeValue::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) ## wifi-mode.h (module 'wifi'): void ns3::WifiModeValue::Set(ns3::WifiMode const & value) [member function] cls.add_method('Set', 'void', [param('ns3::WifiMode const &', 'value')]) return def register_Ns3WifiRadioEnergyModel_methods(root_module, cls): ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiRadioEnergyModel::WifiRadioEnergyModel(ns3::WifiRadioEnergyModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::WifiRadioEnergyModel const &', 'arg0')]) ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiRadioEnergyModel::WifiRadioEnergyModel() [constructor] cls.add_constructor([]) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::ChangeState(int newState) [member function] cls.add_method('ChangeState', 'void', [param('int', 'newState')], is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): double ns3::WifiRadioEnergyModel::GetCcaBusyCurrentA() const [member function] cls.add_method('GetCcaBusyCurrentA', 'double', [], is_const=True) ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiPhy::State ns3::WifiRadioEnergyModel::GetCurrentState() const [member function] cls.add_method('GetCurrentState', 'ns3::WifiPhy::State', [], is_const=True) ## wifi-radio-energy-model.h (module 'energy'): double ns3::WifiRadioEnergyModel::GetIdleCurrentA() const [member function] cls.add_method('GetIdleCurrentA', 'double', [], is_const=True) ## wifi-radio-energy-model.h (module 'energy'): ns3::WifiRadioEnergyModelPhyListener * ns3::WifiRadioEnergyModel::GetPhyListener() [member function] cls.add_method('GetPhyListener', 'ns3::WifiRadioEnergyModelPhyListener *', []) ## wifi-radio-energy-model.h (module 'energy'): double ns3::WifiRadioEnergyModel::GetRxCurrentA() const [member function] cls.add_method('GetRxCurrentA', 'double', [], is_const=True) ## wifi-radio-energy-model.h (module 'energy'): double ns3::WifiRadioEnergyModel::GetSwitchingCurrentA() const [member function] cls.add_method('GetSwitchingCurrentA', 'double', [], is_const=True) ## wifi-radio-energy-model.h (module 'energy'): double ns3::WifiRadioEnergyModel::GetTotalEnergyConsumption() const [member function] cls.add_method('GetTotalEnergyConsumption', 'double', [], is_const=True, is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): double ns3::WifiRadioEnergyModel::GetTxCurrentA() const [member function] cls.add_method('GetTxCurrentA', 'double', [], is_const=True) ## wifi-radio-energy-model.h (module 'energy'): static ns3::TypeId ns3::WifiRadioEnergyModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::HandleEnergyDepletion() [member function] cls.add_method('HandleEnergyDepletion', 'void', [], is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::SetCcaBusyCurrentA(double ccaBusyCurrentA) [member function] cls.add_method('SetCcaBusyCurrentA', 'void', [param('double', 'ccaBusyCurrentA')]) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::SetEnergyDepletionCallback(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('SetEnergyDepletionCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::SetEnergySource(ns3::Ptr<ns3::EnergySource> source) [member function] cls.add_method('SetEnergySource', 'void', [param('ns3::Ptr< ns3::EnergySource >', 'source')], is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::SetIdleCurrentA(double idleCurrentA) [member function] cls.add_method('SetIdleCurrentA', 'void', [param('double', 'idleCurrentA')]) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::SetRxCurrentA(double rxCurrentA) [member function] cls.add_method('SetRxCurrentA', 'void', [param('double', 'rxCurrentA')]) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::SetSwitchingCurrentA(double switchingCurrentA) [member function] cls.add_method('SetSwitchingCurrentA', 'void', [param('double', 'switchingCurrentA')]) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::SetTxCurrentA(double txCurrentA) [member function] cls.add_method('SetTxCurrentA', 'void', [param('double', 'txCurrentA')]) ## wifi-radio-energy-model.h (module 'energy'): void ns3::WifiRadioEnergyModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## wifi-radio-energy-model.h (module 'energy'): double ns3::WifiRadioEnergyModel::DoGetCurrentA() const [member function] cls.add_method('DoGetCurrentA', 'double', [], is_const=True, visibility='private', is_virtual=True) 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_Ns3BasicEnergySource_methods(root_module, cls): ## basic-energy-source.h (module 'energy'): ns3::BasicEnergySource::BasicEnergySource(ns3::BasicEnergySource const & arg0) [copy constructor] cls.add_constructor([param('ns3::BasicEnergySource const &', 'arg0')]) ## basic-energy-source.h (module 'energy'): ns3::BasicEnergySource::BasicEnergySource() [constructor] cls.add_constructor([]) ## basic-energy-source.h (module 'energy'): double ns3::BasicEnergySource::GetEnergyFraction() [member function] cls.add_method('GetEnergyFraction', 'double', [], is_virtual=True) ## basic-energy-source.h (module 'energy'): ns3::Time ns3::BasicEnergySource::GetEnergyUpdateInterval() const [member function] cls.add_method('GetEnergyUpdateInterval', 'ns3::Time', [], is_const=True) ## basic-energy-source.h (module 'energy'): double ns3::BasicEnergySource::GetInitialEnergy() const [member function] cls.add_method('GetInitialEnergy', 'double', [], is_const=True, is_virtual=True) ## basic-energy-source.h (module 'energy'): double ns3::BasicEnergySource::GetRemainingEnergy() [member function] cls.add_method('GetRemainingEnergy', 'double', [], is_virtual=True) ## basic-energy-source.h (module 'energy'): double ns3::BasicEnergySource::GetSupplyVoltage() const [member function] cls.add_method('GetSupplyVoltage', 'double', [], is_const=True, is_virtual=True) ## basic-energy-source.h (module 'energy'): static ns3::TypeId ns3::BasicEnergySource::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## basic-energy-source.h (module 'energy'): void ns3::BasicEnergySource::SetEnergyUpdateInterval(ns3::Time interval) [member function] cls.add_method('SetEnergyUpdateInterval', 'void', [param('ns3::Time', 'interval')]) ## basic-energy-source.h (module 'energy'): void ns3::BasicEnergySource::SetInitialEnergy(double initialEnergyJ) [member function] cls.add_method('SetInitialEnergy', 'void', [param('double', 'initialEnergyJ')]) ## basic-energy-source.h (module 'energy'): void ns3::BasicEnergySource::SetSupplyVoltage(double supplyVoltageV) [member function] cls.add_method('SetSupplyVoltage', 'void', [param('double', 'supplyVoltageV')]) ## basic-energy-source.h (module 'energy'): void ns3::BasicEnergySource::UpdateEnergySource() [member function] cls.add_method('UpdateEnergySource', 'void', [], is_virtual=True) ## basic-energy-source.h (module 'energy'): void ns3::BasicEnergySource::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## basic-energy-source.h (module 'energy'): void ns3::BasicEnergySource::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='private', is_virtual=True) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) register_functions_ns3_internal(module.get_submodule('internal'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def register_functions_ns3_internal(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
unknown
codeparrot/codeparrot-clean
""" The OGRGeometry is a wrapper for using the OGR Geometry class (see http://www.gdal.org/ogr/classOGRGeometry.html). OGRGeometry may be instantiated when reading geometries from OGR Data Sources (e.g. SHP files), or when given OGC WKT (a string). While the 'full' API is not present yet, the API is "pythonic" unlike the traditional and "next-generation" OGR Python bindings. One major advantage OGR Geometries have over their GEOS counterparts is support for spatial reference systems and their transformation. Example: >>> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, SpatialReference >>> wkt1, wkt2 = 'POINT(-90 30)', 'POLYGON((0 0, 5 0, 5 5, 0 5)' >>> pnt = OGRGeometry(wkt1) >>> print pnt POINT (-90 30) >>> mpnt = OGRGeometry(OGRGeomType('MultiPoint'), SpatialReference('WGS84')) >>> mpnt.add(wkt1) >>> mpnt.add(wkt1) >>> print mpnt MULTIPOINT (-90 30,-90 30) >>> print mpnt.srs.name WGS 84 >>> print mpnt.srs.proj +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs >>> mpnt.transform_to(SpatialReference('NAD27')) >>> print mpnt.proj +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs >>> print mpnt MULTIPOINT (-89.999930378602485 29.999797886557641,-89.999930378602485 29.999797886557641) The OGRGeomType class is to make it easy to specify an OGR geometry type: >>> from django.contrib.gis.gdal import OGRGeomType >>> gt1 = OGRGeomType(3) # Using an integer for the type >>> gt2 = OGRGeomType('Polygon') # Using a string >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive >>> print gt1 == 3, gt1 == 'Polygon' # Equivalence works w/non-OGRGeomType objects True """ # Python library requisites. import sys from binascii import a2b_hex from ctypes import byref, string_at, c_char_p, c_double, c_ubyte, c_void_p # Getting GDAL prerequisites from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope from django.contrib.gis.gdal.error import OGRException, OGRIndexError, SRSException from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.libgdal import GEOJSON, GDAL_VERSION from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform # Getting the ctypes prototype functions that interface w/the GDAL C library. from django.contrib.gis.gdal.prototypes import geom as capi, srs as srs_api # For recognizing geometry input. from django.contrib.gis.geometry.regex import hex_regex, wkt_regex, json_regex # For more information, see the OGR C API source code: # http://www.gdal.org/ogr/ogr__api_8h.html # # The OGR_G_* routines are relevant here. #### OGRGeometry Class #### class OGRGeometry(GDALBase): "Generally encapsulates an OGR geometry." def __init__(self, geom_input, srs=None): "Initializes Geometry on either WKT or an OGR pointer as input." str_instance = isinstance(geom_input, basestring) # If HEX, unpack input to to a binary buffer. if str_instance and hex_regex.match(geom_input): geom_input = buffer(a2b_hex(geom_input.upper())) str_instance = False # Constructing the geometry, if str_instance: # Checking if unicode if isinstance(geom_input, unicode): # Encoding to ASCII, WKT or HEX doesn't need any more. geom_input = geom_input.encode('ascii') wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m.group('srid'): # If there's EWKT, set the SRS w/value of the SRID. srs = int(wkt_m.group('srid')) if wkt_m.group('type').upper() == 'LINEARRING': # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See http://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num) capi.import_wkt(g, byref(c_char_p(wkt_m.group('wkt')))) else: g = capi.from_wkt(byref(c_char_p(wkt_m.group('wkt'))), None, byref(c_void_p())) elif json_m: if GEOJSON: g = capi.from_json(geom_input) else: raise NotImplementedError('GeoJSON input only supported on GDAL 1.5+.') else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). ogr_t = OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) elif isinstance(geom_input, buffer): # WKB was passed in g = capi.from_wkb(str(geom_input), None, byref(c_void_p()), len(geom_input)) elif isinstance(geom_input, OGRGeomType): # OGRGeomType was passed in, an empty geometry will be created. g = capi.create_geom(geom_input.num) elif isinstance(geom_input, self.ptr_type): # OGR pointer (c_void_p) was the input. g = geom_input else: raise OGRException('Invalid input type for OGR Geometry construction: %s' % type(geom_input)) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: raise OGRException('Cannot create OGR Geometry from input: %s' % str(geom_input)) self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. if bool(srs): self.srs = srs # Setting the class depending upon the OGR Geometry Type self.__class__ = GEO_CLASSES[self.geom_type.num] def __del__(self): "Deletes this Geometry." if self._ptr: capi.destroy_geom(self._ptr) # Pickle routines def __getstate__(self): srs = self.srs if srs: srs = srs.wkt else: srs = None return str(self.wkb), srs def __setstate__(self, state): wkb, srs = state ptr = capi.from_wkb(wkb, None, byref(c_void_p()), len(wkb)) if not ptr: raise OGRException('Invalid OGRGeometry loaded from pickled state.') self.ptr = ptr self.srs = srs @classmethod def from_bbox(cls, bbox): "Constructs a Polygon from a bounding box (4-tuple)." x0, y0, x1, y1 = bbox return OGRGeometry( 'POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' % ( x0, y0, x0, y1, x1, y1, x1, y0, x0, y0) ) ### Geometry set-like operations ### # g = g1 | g2 def __or__(self, other): "Returns the union of the two geometries." return self.union(other) # g = g1 & g2 def __and__(self, other): "Returns the intersection of this Geometry and the other." return self.intersection(other) # g = g1 - g2 def __sub__(self, other): "Return the difference this Geometry and the other." return self.difference(other) # g = g1 ^ g2 def __xor__(self, other): "Return the symmetric difference of this Geometry and the other." return self.sym_difference(other) def __eq__(self, other): "Is this Geometry equal to the other?" if isinstance(other, OGRGeometry): return self.equals(other) else: return False def __ne__(self, other): "Tests for inequality." return not (self == other) def __str__(self): "WKT is used for the string representation." return self.wkt #### Geometry Properties #### @property def dimension(self): "Returns 0 for points, 1 for lines, and 2 for surfaces." return capi.get_dims(self.ptr) def _get_coord_dim(self): "Returns the coordinate dimension of the Geometry." if isinstance(self, GeometryCollection) and GDAL_VERSION < (1, 5, 2): # On GDAL versions prior to 1.5.2, there exists a bug in which # the coordinate dimension of geometry collections is always 2: # http://trac.osgeo.org/gdal/ticket/2334 # Here we workaround by returning the coordinate dimension of the # first geometry in the collection instead. if len(self): return capi.get_coord_dim(capi.get_geom_ref(self.ptr, 0)) return capi.get_coord_dim(self.ptr) def _set_coord_dim(self, dim): "Sets the coordinate dimension of this Geometry." if not dim in (2, 3): raise ValueError('Geometry dimension must be either 2 or 3') capi.set_coord_dim(self.ptr, dim) coord_dim = property(_get_coord_dim, _set_coord_dim) @property def geom_count(self): "The number of elements in this Geometry." return capi.get_geom_count(self.ptr) @property def point_count(self): "Returns the number of Points in this Geometry." return capi.get_point_count(self.ptr) @property def num_points(self): "Alias for `point_count` (same name method in GEOS API.)" return self.point_count @property def num_coords(self): "Alais for `point_count`." return self.point_count @property def geom_type(self): "Returns the Type for this Geometry." return OGRGeomType(capi.get_geom_type(self.ptr)) @property def geom_name(self): "Returns the Name of this Geometry." return capi.get_geom_name(self.ptr) @property def area(self): "Returns the area for a LinearRing, Polygon, or MultiPolygon; 0 otherwise." return capi.get_area(self.ptr) @property def envelope(self): "Returns the envelope for this Geometry." # TODO: Fix Envelope() for Point geometries. return Envelope(capi.get_envelope(self.ptr, byref(OGREnvelope()))) @property def extent(self): "Returns the envelope as a 4-tuple, instead of as an Envelope object." return self.envelope.tuple #### SpatialReference-related Properties #### # The SRS property def _get_srs(self): "Returns the Spatial Reference for this Geometry." try: srs_ptr = capi.get_geom_srs(self.ptr) return SpatialReference(srs_api.clone_srs(srs_ptr)) except SRSException: return None def _set_srs(self, srs): "Sets the SpatialReference for this geometry." # Do not have to clone the `SpatialReference` object pointer because # when it is assigned to this `OGRGeometry` it's internal OGR # reference count is incremented, and will likewise be released # (decremented) when this geometry's destructor is called. if isinstance(srs, SpatialReference): srs_ptr = srs.ptr elif isinstance(srs, (int, long, basestring)): sr = SpatialReference(srs) srs_ptr = sr.ptr else: raise TypeError('Cannot assign spatial reference with object of type: %s' % type(srs)) capi.assign_srs(self.ptr, srs_ptr) srs = property(_get_srs, _set_srs) # The SRID property def _get_srid(self): srs = self.srs if srs: return srs.srid return None def _set_srid(self, srid): if isinstance(srid, (int, long)): self.srs = srid else: raise TypeError('SRID must be set with an integer.') srid = property(_get_srid, _set_srid) #### Output Methods #### @property def geos(self): "Returns a GEOSGeometry object from this OGRGeometry." from django.contrib.gis.geos import GEOSGeometry return GEOSGeometry(self.wkb, self.srid) @property def gml(self): "Returns the GML representation of the Geometry." return capi.to_gml(self.ptr) @property def hex(self): "Returns the hexadecimal representation of the WKB (a string)." return str(self.wkb).encode('hex').upper() #return b2a_hex(self.wkb).upper() @property def json(self): """ Returns the GeoJSON representation of this Geometry (requires GDAL 1.5+). """ if GEOJSON: return capi.to_json(self.ptr) else: raise NotImplementedError('GeoJSON output only supported on GDAL 1.5+.') geojson = json @property def kml(self): "Returns the KML representation of the Geometry." if GEOJSON: return capi.to_kml(self.ptr, None) else: raise NotImplementedError('KML output only supported on GDAL 1.5+.') @property def wkb_size(self): "Returns the size of the WKB buffer." return capi.get_wkbsize(self.ptr) @property def wkb(self): "Returns the WKB representation of the Geometry." if sys.byteorder == 'little': byteorder = 1 # wkbNDR (from ogr_core.h) else: byteorder = 0 # wkbXDR sz = self.wkb_size # Creating the unsigned character buffer, and passing it in by reference. buf = (c_ubyte * sz)() wkb = capi.to_wkb(self.ptr, byteorder, byref(buf)) # Returning a buffer of the string at the pointer. return buffer(string_at(buf, sz)) @property def wkt(self): "Returns the WKT representation of the Geometry." return capi.to_wkt(self.ptr, byref(c_char_p())) @property def ewkt(self): "Returns the EWKT representation of the Geometry." srs = self.srs if srs and srs.srid: return 'SRID=%s;%s' % (srs.srid, self.wkt) else: return self.wkt #### Geometry Methods #### def clone(self): "Clones this OGR Geometry." return OGRGeometry(capi.clone_geom(self.ptr), self.srs) def close_rings(self): """ If there are any rings within this geometry that have not been closed, this routine will do so by adding the starting point at the end. """ # Closing the open rings. capi.geom_close_rings(self.ptr) def transform(self, coord_trans, clone=False): """ Transforms this geometry to a different spatial reference system. May take a CoordTransform object, a SpatialReference object, string WKT or PROJ.4, and/or an integer SRID. By default nothing is returned and the geometry is transformed in-place. However, if the `clone` keyword is set, then a transformed clone of this geometry will be returned. """ if clone: klone = self.clone() klone.transform(coord_trans) return klone # Have to get the coordinate dimension of the original geometry # so it can be used to reset the transformed geometry's dimension # afterwards. This is done because of GDAL bug (in versions prior # to 1.7) that turns geometries 3D after transformation, see: # http://trac.osgeo.org/gdal/changeset/17792 if GDAL_VERSION < (1, 7): orig_dim = self.coord_dim # Depending on the input type, use the appropriate OGR routine # to perform the transformation. if isinstance(coord_trans, CoordTransform): capi.geom_transform(self.ptr, coord_trans.ptr) elif isinstance(coord_trans, SpatialReference): capi.geom_transform_to(self.ptr, coord_trans.ptr) elif isinstance(coord_trans, (int, long, basestring)): sr = SpatialReference(coord_trans) capi.geom_transform_to(self.ptr, sr.ptr) else: raise TypeError('Transform only accepts CoordTransform, ' 'SpatialReference, string, and integer objects.') # Setting with original dimension, see comment above. if GDAL_VERSION < (1, 7): if isinstance(self, GeometryCollection): # With geometry collections have to set dimension on # each internal geometry reference, as the collection # dimension isn't affected. for i in xrange(len(self)): internal_ptr = capi.get_geom_ref(self.ptr, i) if orig_dim != capi.get_coord_dim(internal_ptr): capi.set_coord_dim(internal_ptr, orig_dim) else: if self.coord_dim != orig_dim: self.coord_dim = orig_dim def transform_to(self, srs): "For backwards-compatibility." self.transform(srs) #### Topology Methods #### def _topology(self, func, other): """A generalized function for topology operations, takes a GDAL function and the other geometry to perform the operation on.""" if not isinstance(other, OGRGeometry): raise TypeError('Must use another OGRGeometry object for topology operations!') # Returning the output of the given function with the other geometry's # pointer. return func(self.ptr, other.ptr) def intersects(self, other): "Returns True if this geometry intersects with the other." return self._topology(capi.ogr_intersects, other) def equals(self, other): "Returns True if this geometry is equivalent to the other." return self._topology(capi.ogr_equals, other) def disjoint(self, other): "Returns True if this geometry and the other are spatially disjoint." return self._topology(capi.ogr_disjoint, other) def touches(self, other): "Returns True if this geometry touches the other." return self._topology(capi.ogr_touches, other) def crosses(self, other): "Returns True if this geometry crosses the other." return self._topology(capi.ogr_crosses, other) def within(self, other): "Returns True if this geometry is within the other." return self._topology(capi.ogr_within, other) def contains(self, other): "Returns True if this geometry contains the other." return self._topology(capi.ogr_contains, other) def overlaps(self, other): "Returns True if this geometry overlaps the other." return self._topology(capi.ogr_overlaps, other) #### Geometry-generation Methods #### def _geomgen(self, gen_func, other=None): "A helper routine for the OGR routines that generate geometries." if isinstance(other, OGRGeometry): return OGRGeometry(gen_func(self.ptr, other.ptr), self.srs) else: return OGRGeometry(gen_func(self.ptr), self.srs) @property def boundary(self): "Returns the boundary of this geometry." return self._geomgen(capi.get_boundary) @property def convex_hull(self): """ Returns the smallest convex Polygon that contains all the points in this Geometry. """ return self._geomgen(capi.geom_convex_hull) def difference(self, other): """ Returns a new geometry consisting of the region which is the difference of this geometry and the other. """ return self._geomgen(capi.geom_diff, other) def intersection(self, other): """ Returns a new geometry consisting of the region of intersection of this geometry and the other. """ return self._geomgen(capi.geom_intersection, other) def sym_difference(self, other): """ Returns a new geometry which is the symmetric difference of this geometry and the other. """ return self._geomgen(capi.geom_sym_diff, other) def union(self, other): """ Returns a new geometry consisting of the region which is the union of this geometry and the other. """ return self._geomgen(capi.geom_union, other) # The subclasses for OGR Geometry. class Point(OGRGeometry): @property def x(self): "Returns the X coordinate for this Point." return capi.getx(self.ptr, 0) @property def y(self): "Returns the Y coordinate for this Point." return capi.gety(self.ptr, 0) @property def z(self): "Returns the Z coordinate for this Point." if self.coord_dim == 3: return capi.getz(self.ptr, 0) @property def tuple(self): "Returns the tuple of this point." if self.coord_dim == 2: return (self.x, self.y) elif self.coord_dim == 3: return (self.x, self.y, self.z) coords = tuple class LineString(OGRGeometry): def __getitem__(self, index): "Returns the Point at the given index." if index >= 0 and index < self.point_count: x, y, z = c_double(), c_double(), c_double() capi.get_point(self.ptr, index, byref(x), byref(y), byref(z)) dim = self.coord_dim if dim == 1: return (x.value,) elif dim == 2: return (x.value, y.value) elif dim == 3: return (x.value, y.value, z.value) else: raise OGRIndexError('index out of range: %s' % str(index)) def __iter__(self): "Iterates over each point in the LineString." for i in xrange(self.point_count): yield self[i] def __len__(self): "The length returns the number of points in the LineString." return self.point_count @property def tuple(self): "Returns the tuple representation of this LineString." return tuple([self[i] for i in xrange(len(self))]) coords = tuple def _listarr(self, func): """ Internal routine that returns a sequence (list) corresponding with the given function. """ return [func(self.ptr, i) for i in xrange(len(self))] @property def x(self): "Returns the X coordinates in a list." return self._listarr(capi.getx) @property def y(self): "Returns the Y coordinates in a list." return self._listarr(capi.gety) @property def z(self): "Returns the Z coordinates in a list." if self.coord_dim == 3: return self._listarr(capi.getz) # LinearRings are used in Polygons. class LinearRing(LineString): pass class Polygon(OGRGeometry): def __len__(self): "The number of interior rings in this Polygon." return self.geom_count def __iter__(self): "Iterates through each ring in the Polygon." for i in xrange(self.geom_count): yield self[i] def __getitem__(self, index): "Gets the ring at the specified index." if index < 0 or index >= self.geom_count: raise OGRIndexError('index out of range: %s' % index) else: return OGRGeometry(capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs) # Polygon Properties @property def shell(self): "Returns the shell of this Polygon." return self[0] # First ring is the shell exterior_ring = shell @property def tuple(self): "Returns a tuple of LinearRing coordinate tuples." return tuple([self[i].tuple for i in xrange(self.geom_count)]) coords = tuple @property def point_count(self): "The number of Points in this Polygon." # Summing up the number of points in each ring of the Polygon. return sum([self[i].point_count for i in xrange(self.geom_count)]) @property def centroid(self): "Returns the centroid (a Point) of this Polygon." # The centroid is a Point, create a geometry for this. p = OGRGeometry(OGRGeomType('Point')) capi.get_centroid(self.ptr, p.ptr) return p # Geometry Collection base class. class GeometryCollection(OGRGeometry): "The Geometry Collection class." def __getitem__(self, index): "Gets the Geometry at the specified index." if index < 0 or index >= self.geom_count: raise OGRIndexError('index out of range: %s' % index) else: return OGRGeometry(capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs) def __iter__(self): "Iterates over each Geometry." for i in xrange(self.geom_count): yield self[i] def __len__(self): "The number of geometries in this Geometry Collection." return self.geom_count def add(self, geom): "Add the geometry to this Geometry Collection." if isinstance(geom, OGRGeometry): if isinstance(geom, self.__class__): for g in geom: capi.add_geom(self.ptr, g.ptr) else: capi.add_geom(self.ptr, geom.ptr) elif isinstance(geom, basestring): tmp = OGRGeometry(geom) capi.add_geom(self.ptr, tmp.ptr) else: raise OGRException('Must add an OGRGeometry.') @property def point_count(self): "The number of Points in this Geometry Collection." # Summing up the number of points in each geometry in this collection return sum([self[i].point_count for i in xrange(self.geom_count)]) @property def tuple(self): "Returns a tuple representation of this Geometry Collection." return tuple([self[i].tuple for i in xrange(self.geom_count)]) coords = tuple # Multiple Geometry types. class MultiPoint(GeometryCollection): pass class MultiLineString(GeometryCollection): pass class MultiPolygon(GeometryCollection): pass # Class mapping dictionary (using the OGRwkbGeometryType as the key) GEO_CLASSES = {1 : Point, 2 : LineString, 3 : Polygon, 4 : MultiPoint, 5 : MultiLineString, 6 : MultiPolygon, 7 : GeometryCollection, 101: LinearRing, 1 + OGRGeomType.wkb25bit : Point, 2 + OGRGeomType.wkb25bit : LineString, 3 + OGRGeomType.wkb25bit : Polygon, 4 + OGRGeomType.wkb25bit : MultiPoint, 5 + OGRGeomType.wkb25bit : MultiLineString, 6 + OGRGeomType.wkb25bit : MultiPolygon, 7 + OGRGeomType.wkb25bit : GeometryCollection, }
unknown
codeparrot/codeparrot-clean
########################################################## # THIS IS A GENERATED FILE -- DO NOT MODIFY. # IF YOU WISH TO MODIFY THIS SUITE, MODIFY THE CORRESPONDING MATRIX SUITE MAPPING FILE # AND REGENERATE THE MATRIX SUITES. # # matrix suite mapping file: buildscripts/resmokeconfig/matrix_suites/mappings/multiversion_sanity_check_last_continuous_new_old_new.yml # regenerate matrix suites: buildscripts/resmoke.py generate-matrix-suites ########################################################## executor: archive: hooks: - RunDBCheckInBackground - CheckReplDBHashInBackground - ValidateCollectionsInBackground - CheckReplDBHash - CheckReplOplogs - ValidateCollections config: shell_options: eval: globalThis.testingReplication = true; global_vars: TestData: enableOTELTracing: false fixture: class: ReplicaSetFixture mixed_bin_versions: new_old_new mongod_options: set_parameters: enableTestCommands: 1 num_nodes: 3 old_bin_version: last_continuous hooks: - class: RunDBCheckInBackground - class: CheckReplDBHashInBackground - class: ValidateCollectionsInBackground - class: CheckReplOplogs - class: CheckReplDBHash - class: ValidateCollections - class: CleanEveryN n: 20 matrix_suite: true selector: exclude_files: - jstests/core/txns/abort_expired_transaction.js - jstests/core/txns/abort_transaction_thread_does_not_block_on_locks.js - jstests/core/txns/kill_op_on_txn_expiry.js - jstests/core/**/set_param1.js - jstests/core/query/awaitdata_getmore_cmd.js - jstests/core/administrative/current_op/currentop.js - jstests/core/administrative/fsync/fsync.js - jstests/core/txns/prepare_conflict.js - jstests/core/txns/prepare_conflict_aggregation_behavior.js - jstests/core/timeseries/write/timeseries_update_multi.js exclude_with_any_tags: - assumes_standalone_mongod - requires_profiling include_with_any_tags: - multiversion_sanity_check roots: - jstests/core/**/*.js - jstests/fle2/**/*.js - src/mongo/db/modules/*/jstests/fle2/**/*.js test_kind: js_test
unknown
github
https://github.com/mongodb/mongo
buildscripts/resmokeconfig/matrix_suites/generated_suites/multiversion_sanity_check_last_continuous_new_old_new.yml
#!/usr/bin/env python # -*- coding: utf-8 -*- # phppo2pypo unit tests # Author: Wil Clouser <wclouser@mozilla.com> # Date: 2009-12-03 from translate.tools import phppo2pypo from translate.storage import po from translate.convert import test_convert from translate.misc import wStringIO class TestPhpPo2PyPo: def test_single_po(self): inputfile = """ # This user comment refers to: %1$s #. This developer comment does too: %1$s #: some/path.php:111 #, php-format msgid "I have %2$s apples and %1$s oranges" msgstr "I have %2$s apples and %1$s oranges" """ outputfile = wStringIO.StringIO() phppo2pypo.convertphp2py(inputfile, outputfile) output = outputfile.getvalue() assert "refers to: {0}" in output assert "does too: {0}" in output assert 'msgid "I have {1} apples and {0} oranges"' in output assert 'msgstr "I have {1} apples and {0} oranges"' in output def test_plural_po(self): inputfile = """ #. This developer comment refers to %1$s #: some/path.php:111 #, php-format msgid "I have %1$s apple" msgid_plural "I have %1$s apples" msgstr[0] "I have %1$s apple" msgstr[1] "I have %1$s apples" """ outputfile = wStringIO.StringIO() phppo2pypo.convertphp2py(inputfile, outputfile) output = outputfile.getvalue() assert 'msgid "I have {0} apple"' in output assert 'msgid_plural "I have {0} apples"' in output assert 'msgstr[0] "I have {0} apple"' in output assert 'msgstr[1] "I have {0} apples"' in output class TestPhpPo2PyPoCommand(test_convert.TestConvertCommand, TestPhpPo2PyPo): """Tests running actual phppo2pypo commands on files""" convertmodule = phppo2pypo defaultoptions = {}
unknown
codeparrot/codeparrot-clean
# Copyright 2025 The HuggingFace Team. 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 typing import TYPE_CHECKING from ...utils import _LazyModule from ...utils.import_utils import define_import_structure if TYPE_CHECKING: from .configuration_aimv2 import * from .modeling_aimv2 import * else: import sys _file = globals()["__file__"] sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
python
github
https://github.com/huggingface/transformers
src/transformers/models/aimv2/__init__.py
import { test } from '../../test'; export default test({ get props() { return { todos: [ { description: 'implement keyed each blocks' }, { description: 'implement client-side hydration' } ] }; }, html: ` <p>1: implement keyed each blocks</p> <p>2: implement client-side hydration</p> `, test({ assert, component, target }) { const [p1, p2] = target.querySelectorAll('p'); component.todos = [component.todos[1]]; assert.htmlEqual(target.innerHTML, '<p>1: implement client-side hydration</p>'); const [p3] = target.querySelectorAll('p'); assert.ok(!target.contains(p1), 'first `<p>` element should be removed'); assert.equal(p2, p3, 'second `<p>` element should be retained'); } });
javascript
github
https://github.com/sveltejs/svelte
packages/svelte/tests/runtime-legacy/samples/each-block-keyed-object-identity/_config.js
# # Copyright (C) 2013,2014,2015,2016 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo 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. # # ESPResSo is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from functools import update_wrapper class ThereCanOnlyBeOne(BaseException): def __init__(self, cls): self._cls = cls def __str__(self): return "There can only be one instance of '{}' at any time.".format(self._cls) def highlander(klass): klass.highlander_created = False def cls_init(self, *args, **kwargs): "__init__ method by the highlander decorator." if self.__class__.highlander_created: raise ThereCanOnlyBeOne(self.__class__) self.__class__.highlander_created = True def cls_init_call_orig(self, *args, **kwargs): if self.__class__.highlander_created: raise ThereCanOnlyBeOne(self.__class__) self.__class__.highlander_created = True self.__class__.__init_orig__(self, *args, **kwargs) # override the __init__ method of the class to store the bool # "highlander_created" if hasattr(klass, '__init__'): klass.__init_orig__ = klass.__init__ klass.__init__ = cls_init_call_orig update_wrapper(cls_init_call_orig, klass.__init_orig__) else: klass.__init__ = cls_init # override the __del__ method of the class def cls_del(self): "__del__ method by the highlander decorator." self.__class__.highlander_created = False def cls_del_call_orig(self): cls_del(self) self.__class__.__del_orig__(self) if hasattr(klass, '__del__'): klass.__del_orig__ = klass.__del__ klass.__del__ = cls_del_call_orig update_wrapper(cls_del_call_orig, klass.__del_orig__) else: klass.__del__ = cls_del return klass
unknown
codeparrot/codeparrot-clean
# Copyright: (c) 2018, Pluribus Networks # 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 from units.compat.mock import patch from ansible.modules.network.netvisor import pn_vrouter_ospf6 from units.modules.utils import set_module_args from .nvos_module import TestNvosModule class TestVrouterOSPF6Module(TestNvosModule): module = pn_vrouter_ospf6 def setUp(self): self.mock_run_nvos_commands = patch('ansible.modules.network.netvisor.pn_vrouter_ospf6.run_cli') self.run_nvos_commands = self.mock_run_nvos_commands.start() self.mock_run_check_cli = patch('ansible.modules.network.netvisor.pn_vrouter_ospf6.check_cli') self.run_check_cli = self.mock_run_check_cli.start() def tearDown(self): self.mock_run_nvos_commands.stop() self.mock_run_check_cli.stop() def run_cli_patch(self, module, cli, state_map): if state_map['present'] == 'vrouter-ospf6-add': results = dict( changed=True, cli_cmd=cli ) elif state_map['absent'] == 'vrouter-ospf6-remove': results = dict( changed=True, cli_cmd=cli ) module.exit_json(**results) def load_fixtures(self, commands=None, state=None, transport='cli'): self.run_nvos_commands.side_effect = self.run_cli_patch if state == 'present': self.run_check_cli.return_value = True, False if state == 'absent': self.run_check_cli.return_value = True, True def test_vrouter_ospf6_add(self): set_module_args({'pn_cliswitch': 'sw01', 'pn_vrouter_name': 'foo-vrouter', 'pn_nic': 'eth0.4092', 'pn_ospf6_area': '0.0.0.0', 'state': 'present'}) result = self.execute_module(changed=True, state='present') expected_cmd = ' switch sw01 vrouter-ospf6-add vrouter-name foo-vrouter nic eth0.4092 ospf6-area 0.0.0.0 ' self.assertEqual(result['cli_cmd'], expected_cmd) def test_vrouter_ospf6_remove(self): set_module_args({'pn_cliswitch': 'sw01', 'pn_vrouter_name': 'foo-vrouter', 'pn_nic': 'eth0.4092', 'state': 'absent'}) result = self.execute_module(changed=True, state='absent') expected_cmd = ' switch sw01 vrouter-ospf6-remove vrouter-name foo-vrouter nic eth0.4092' self.assertEqual(result['cli_cmd'], expected_cmd)
unknown
codeparrot/codeparrot-clean
/* Copyright 2021 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. ==============================================================================*/ #ifndef TENSORFLOW_C_EXPERIMENTAL_OPS_GEN_COMMON_VIEW_UTIL_H_ #define TENSORFLOW_C_EXPERIMENTAL_OPS_GEN_COMMON_VIEW_UTIL_H_ #include <vector> #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace generator { std::string Call(const std::string& function, std::vector<std::string> arguments); std::string Call(const std::string& object, const std::string& method, std::vector<std::string> arguments, const char* oper = "->"); std::string Quoted(const std::string& s); } // namespace generator } // namespace tensorflow #endif // TENSORFLOW_C_EXPERIMENTAL_OPS_GEN_COMMON_VIEW_UTIL_H_
c
github
https://github.com/tensorflow/tensorflow
tensorflow/c/experimental/ops/gen/common/view_util.h
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Uploads files to Google Storage content addressed.""" import hashlib import optparse import os import Queue import re import stat import sys import threading import time from download_from_google_storage import check_bucket_permissions from download_from_google_storage import get_sha1 from download_from_google_storage import Gsutil from download_from_google_storage import printer_worker from download_from_google_storage import GSUTIL_DEFAULT_PATH USAGE_STRING = """%prog [options] target [target2 ...]. Target is the file intended to be uploaded to Google Storage. If target is "-", then a list of files will be taken from standard input This script will generate a file (original filename).sha1 containing the sha1 sum of the uploaded file. It is recommended that the .sha1 file is checked into the repository, the original file removed from the repository, and a hook added to the DEPS file to call download_from_google_storage.py. Example usages -------------- Scan the current directory and upload all files larger than 1MB: find . -name .svn -prune -o -size +1000k -type f -print0 | %prog -0 -b bkt - (Replace "bkt" with the name of a writable bucket.) """ def get_md5(filename): md5_calculator = hashlib.md5() with open(filename, 'rb') as f: while True: chunk = f.read(1024*1024) if not chunk: break md5_calculator.update(chunk) return md5_calculator.hexdigest() def get_md5_cached(filename): """Don't calculate the MD5 if we can find a .md5 file.""" # See if we can find an existing MD5 sum stored in a file. if os.path.exists('%s.md5' % filename): with open('%s.md5' % filename, 'rb') as f: md5_match = re.search('([a-z0-9]{32})', f.read()) if md5_match: return md5_match.group(1) else: md5_hash = get_md5(filename) with open('%s.md5' % filename, 'wb') as f: f.write(md5_hash) return md5_hash def _upload_worker( thread_num, upload_queue, base_url, gsutil, md5_lock, force, use_md5, stdout_queue, ret_codes): while True: filename, sha1_sum = upload_queue.get() if not filename: break file_url = '%s/%s' % (base_url, sha1_sum) if gsutil.check_call('ls', file_url)[0] == 0 and not force: # File exists, check MD5 hash. _, out, _ = gsutil.check_call('ls', '-L', file_url) etag_match = re.search('ETag:\s+([a-z0-9]{32})', out) if etag_match: remote_md5 = etag_match.group(1) # Calculate the MD5 checksum to match it to Google Storage's ETag. with md5_lock: if use_md5: local_md5 = get_md5_cached(filename) else: local_md5 = get_md5(filename) if local_md5 == remote_md5: stdout_queue.put( '%d> File %s already exists and MD5 matches, upload skipped' % (thread_num, filename)) continue stdout_queue.put('%d> Uploading %s...' % ( thread_num, filename)) code, _, err = gsutil.check_call('cp', filename, file_url) if code != 0: ret_codes.put( (code, 'Encountered error on uploading %s to %s\n%s' % (filename, file_url, err))) continue # Mark executable files with the header "x-goog-meta-executable: 1" which # the download script will check for to preserve the executable bit. if not sys.platform.startswith('win'): if os.stat(filename).st_mode & stat.S_IEXEC: code, _, err = gsutil.check_call('setmeta', '-h', 'x-goog-meta-executable:1', file_url) if code: ret_codes.put( (code, 'Encountered error on setting metadata on %s\n%s' % (file_url, err))) def get_targets(args, parser, use_null_terminator): if not args: parser.error('Missing target.') if len(args) == 1 and args[0] == '-': # Take stdin as a newline or null seperated list of files. if use_null_terminator: return sys.stdin.read().split('\0') else: return sys.stdin.read().splitlines() else: return args def upload_to_google_storage( input_filenames, base_url, gsutil, force, use_md5, num_threads, skip_hashing): # We only want one MD5 calculation happening at a time to avoid HD thrashing. md5_lock = threading.Lock() # Start up all the worker threads plus the printer thread. all_threads = [] ret_codes = Queue.Queue() ret_codes.put((0, None)) upload_queue = Queue.Queue() upload_timer = time.time() stdout_queue = Queue.Queue() printer_thread = threading.Thread(target=printer_worker, args=[stdout_queue]) printer_thread.daemon = True printer_thread.start() for thread_num in range(num_threads): t = threading.Thread( target=_upload_worker, args=[thread_num, upload_queue, base_url, gsutil, md5_lock, force, use_md5, stdout_queue, ret_codes]) t.daemon = True t.start() all_threads.append(t) # We want to hash everything in a single thread since its faster. # The bottleneck is in disk IO, not CPU. hashing_start = time.time() for filename in input_filenames: if not os.path.exists(filename): stdout_queue.put('Main> Error: %s not found, skipping.' % filename) continue if os.path.exists('%s.sha1' % filename) and skip_hashing: stdout_queue.put( 'Main> Found hash for %s, sha1 calculation skipped.' % filename) with open(filename + '.sha1', 'rb') as f: sha1_file = f.read(1024) if not re.match('^([a-z0-9]{40})$', sha1_file): print >> sys.stderr, 'Invalid sha1 hash file %s.sha1' % filename return 1 upload_queue.put((filename, sha1_file)) continue stdout_queue.put('Main> Calculating hash for %s...' % filename) sha1_sum = get_sha1(filename) with open(filename + '.sha1', 'wb') as f: f.write(sha1_sum) stdout_queue.put('Main> Done calculating hash for %s.' % filename) upload_queue.put((filename, sha1_sum)) hashing_duration = time.time() - hashing_start # Wait for everything to finish. for _ in all_threads: upload_queue.put((None, None)) # To mark the end of the work queue. for t in all_threads: t.join() stdout_queue.put(None) printer_thread.join() # Print timing information. print 'Hashing %s files took %1f seconds' % ( len(input_filenames), hashing_duration) print 'Uploading took %1f seconds' % (time.time() - upload_timer) # See if we ran into any errors. max_ret_code = 0 for ret_code, message in ret_codes.queue: max_ret_code = max(ret_code, max_ret_code) if message: print >> sys.stderr, message if not max_ret_code: print 'Success!' return max_ret_code def main(args): parser = optparse.OptionParser(USAGE_STRING) parser.add_option('-b', '--bucket', help='Google Storage bucket to upload to.') parser.add_option('-e', '--boto', help='Specify a custom boto file.') parser.add_option('-f', '--force', action='store_true', help='Force upload even if remote file exists.') parser.add_option('-g', '--gsutil_path', default=GSUTIL_DEFAULT_PATH, help='Path to the gsutil script.') parser.add_option('-m', '--use_md5', action='store_true', help='Generate MD5 files when scanning, and don\'t check ' 'the MD5 checksum if a .md5 file is found.') parser.add_option('-t', '--num_threads', default=1, type='int', help='Number of uploader threads to run.') parser.add_option('-s', '--skip_hashing', action='store_true', help='Skip hashing if .sha1 file exists.') parser.add_option('-0', '--use_null_terminator', action='store_true', help='Use \\0 instead of \\n when parsing ' 'the file list from stdin. This is useful if the input ' 'is coming from "find ... -print0".') (options, args) = parser.parse_args() # Enumerate our inputs. input_filenames = get_targets(args, parser, options.use_null_terminator) # Make sure we can find a working instance of gsutil. if os.path.exists(GSUTIL_DEFAULT_PATH): gsutil = Gsutil(GSUTIL_DEFAULT_PATH, boto_path=options.boto) else: gsutil = None for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(path) and 'gsutil' in os.listdir(path): gsutil = Gsutil(os.path.join(path, 'gsutil'), boto_path=options.boto) if not gsutil: parser.error('gsutil not found in %s, bad depot_tools checkout?' % GSUTIL_DEFAULT_PATH) base_url = 'gs://%s' % options.bucket # Check we have a valid bucket with valid permissions. code = check_bucket_permissions(base_url, gsutil) if code: return code return upload_to_google_storage( input_filenames, base_url, gsutil, options.force, options.use_md5, options.num_threads, options.skip_hashing) if __name__ == '__main__': sys.exit(main(sys.argv))
unknown
codeparrot/codeparrot-clean
""" Tests for Version Based App Upgrade Middleware """ from datetime import datetime from unittest import mock import ddt from django.core.cache import caches from django.http import HttpRequest, HttpResponse from pytz import UTC from lms.djangoapps.mobile_api.middleware import AppVersionUpgrade from lms.djangoapps.mobile_api.models import AppVersionConfig from openedx.core.djangolib.testing.utils import CacheIsolationTestCase @ddt.ddt class TestAppVersionUpgradeMiddleware(CacheIsolationTestCase): """ Tests for version based app upgrade middleware """ ENABLED_CACHES = ['default'] def setUp(self): super().setUp() self.middleware = AppVersionUpgrade() self.set_app_version_config() def set_app_version_config(self): """ Creates configuration data for platform versions """ AppVersionConfig(platform="iOS", version="1.1.1", expire_at=None, enabled=True).save() AppVersionConfig( platform="iOS", version="2.2.2", expire_at=datetime(2014, 1, 1, tzinfo=UTC), enabled=True ).save() AppVersionConfig( platform="iOS", version="4.4.4", expire_at=datetime(9000, 1, 1, tzinfo=UTC), enabled=True ).save() AppVersionConfig(platform="iOS", version="6.6.6", expire_at=None, enabled=True).save() AppVersionConfig(platform="Android", version="1.1.1", expire_at=None, enabled=True).save() AppVersionConfig( platform="Android", version="2.2.2", expire_at=datetime(2014, 1, 1, tzinfo=UTC), enabled=True ).save() AppVersionConfig( platform="Android", version="4.4.4", expire_at=datetime(5000, 1, 1, tzinfo=UTC), enabled=True ).save() AppVersionConfig(platform="Android", version="8.8.8", expire_at=None, enabled=True).save() def process_middleware(self, user_agent, cache_get_many_calls_for_request=1): """ Helper function that makes calls to middle process_request and process_response """ fake_request = HttpRequest() fake_request.META['HTTP_USER_AGENT'] = user_agent with mock.patch.object(caches['default'], 'get_many', wraps=caches['default'].get_many) as mocked_code: request_response = self.middleware.process_request(fake_request) assert cache_get_many_calls_for_request == mocked_code.call_count with mock.patch.object(caches['default'], 'get_many', wraps=caches['default'].get_many) as mocked_code: processed_response = self.middleware.process_response(fake_request, request_response or HttpResponse()) assert 0 == mocked_code.call_count return request_response, processed_response @ddt.data( ("Mozilla/5.0 (Linux; Android 5.1; Nexus 5 Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) " "Version/4.0 Chrome/47.0.2526.100 Mobile Safari/537.36 edX/org.edx.mobile/2.0.0"), ("Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) " "Mobile/13C75 edX/org.edx.mobile/2.2.1"), ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 " "Safari/537.36"), ) def test_non_mobile_app_requests(self, user_agent): with self.assertNumQueries(0): request_response, processed_response = self.process_middleware(user_agent, 0) assert request_response is None assert 200 == processed_response.status_code assert AppVersionUpgrade.LATEST_VERSION_HEADER not in processed_response assert AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER not in processed_response @ddt.data( "edX/org.edx.mobile (6.6.6; OS Version 9.2 (Build 13C75))", "edX/org.edx.mobile (7.7.7; OS Version 9.2 (Build 13C75))", "Dalvik/2.1.0 (Linux; U; Android 5.1; Nexus 5 Build/LMY47I) edX/org.edx.mobile/8.8.8", "Dalvik/2.1.0 (Linux; U; Android 5.1; Nexus 5 Build/LMY47I) edX/org.edx.mobile/9.9.9", ) def test_no_update(self, user_agent): with self.assertNumQueries(2): request_response, processed_response = self.process_middleware(user_agent) assert request_response is None assert 200 == processed_response.status_code assert AppVersionUpgrade.LATEST_VERSION_HEADER not in processed_response assert AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER not in processed_response with self.assertNumQueries(0): self.process_middleware(user_agent) @ddt.data( ("edX/org.edx.mobile (5.1.1; OS Version 9.2 (Build 13C75))", "6.6.6"), ("edX/org.edx.mobile (5.1.1.RC; OS Version 9.2 (Build 13C75))", "6.6.6"), ("Dalvik/2.1.0 (Linux; U; Android 5.1; Nexus 5 Build/LMY47I) edX/org.edx.mobile/5.1.1", "8.8.8"), ("Dalvik/2.1.0 (Linux; U; Android 5.1; Nexus 5 Build/LMY47I) edX/org.edx.mobile/5.1.1.RC", "8.8.8"), ) @ddt.unpack def test_new_version_available(self, user_agent, latest_version): with self.assertNumQueries(2): request_response, processed_response = self.process_middleware(user_agent) assert request_response is None assert 200 == processed_response.status_code assert latest_version == processed_response[AppVersionUpgrade.LATEST_VERSION_HEADER] assert AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER not in processed_response with self.assertNumQueries(0): self.process_middleware(user_agent) @ddt.data( ("edX/org.edx.mobile (1.0.1; OS Version 9.2 (Build 13C75))", "6.6.6"), ("edX/org.edx.mobile (1.1.1; OS Version 9.2 (Build 13C75))", "6.6.6"), ("edX/org.edx.mobile (2.0.5.RC; OS Version 9.2 (Build 13C75))", "6.6.6"), ("edX/org.edx.mobile (2.2.2; OS Version 9.2 (Build 13C75))", "6.6.6"), ("Dalvik/2.1.0 (Linux; U; Android 5.1; Nexus 5 Build/LMY47I) edX/org.edx.mobile/1.0.1", "8.8.8"), ("Dalvik/2.1.0 (Linux; U; Android 5.1; Nexus 5 Build/LMY47I) edX/org.edx.mobile/1.1.1", "8.8.8"), ("Dalvik/2.1.0 (Linux; U; Android 5.1; Nexus 5 Build/LMY47I) edX/org.edx.mobile/2.0.5.RC", "8.8.8"), ("Dalvik/2.1.0 (Linux; U; Android 5.1; Nexus 5 Build/LMY47I) edX/org.edx.mobile/2.2.2", "8.8.8"), ) @ddt.unpack def test_version_update_required(self, user_agent, latest_version): with self.assertNumQueries(2): request_response, processed_response = self.process_middleware(user_agent) assert request_response is not None assert 426 == processed_response.status_code assert latest_version == processed_response[AppVersionUpgrade.LATEST_VERSION_HEADER] with self.assertNumQueries(0): self.process_middleware(user_agent) @ddt.data( ("edX/org.edx.mobile (4.4.4; OS Version 9.2 (Build 13C75))", "6.6.6", '9000-01-01T00:00:00+00:00'), ( "Dalvik/2.1.0 (Linux; U; Android 5.1; Nexus 5 Build/LMY47I) edX/org.edx.mobile/4.4.4", "8.8.8", '5000-01-01T00:00:00+00:00', ), ) @ddt.unpack def test_version_update_available_with_deadline(self, user_agent, latest_version, upgrade_date): with self.assertNumQueries(2): request_response, processed_response = self.process_middleware(user_agent) assert request_response is None assert 200 == processed_response.status_code assert latest_version == processed_response[AppVersionUpgrade.LATEST_VERSION_HEADER] assert upgrade_date == processed_response[AppVersionUpgrade.LAST_SUPPORTED_DATE_HEADER] with self.assertNumQueries(0): self.process_middleware(user_agent)
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env bash set -eux # Ensure that when a non-distro 'distro' package is in PYTHONPATH, we fallback # to our bundled one. new_pythonpath="$OUTPUT_DIR/pythonpath" mkdir -p "$new_pythonpath/distro" touch "$new_pythonpath/distro/__init__.py" export PYTHONPATH="$new_pythonpath:$PYTHONPATH" # Sanity test to make sure the above worked set +e distro_id_fail="$(python -c 'import distro; distro.id' 2>&1)" set -e grep -q "AttributeError:.*has no attribute 'id'" <<< "$distro_id_fail" # ansible.module_utils.common.sys_info imports distro, and itself gets imported # in DataLoader, so all we have to do to test the fallback is run `ansible`. ansirun="$(ansible -i ../../inventory -a "echo \$PYTHONPATH" localhost)" grep -q "$new_pythonpath" <<< "$ansirun" rm -rf "$new_pythonpath"
unknown
github
https://github.com/ansible/ansible
test/integration/targets/module_utils_distro/runme.sh
/*============================================================================== Copyright (c) 2010-2011 Bryce Lelbach Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_DETAIL_SORTED_HPP #define BOOST_DETAIL_SORTED_HPP #include <iterator> #include <functional> namespace boost { namespace detail { template<class Iterator, class Comp> inline Iterator is_sorted_until (Iterator first, Iterator last, Comp c) { if (first == last) return last; Iterator it = first; ++it; for (; it != last; first = it, ++it) if (c(*it, *first)) return it; return it; } template<class Iterator> inline Iterator is_sorted_until (Iterator first, Iterator last) { typedef typename std::iterator_traits<Iterator>::value_type value_type; typedef std::less<value_type> c; return ::boost::detail::is_sorted_until(first, last, c()); } template<class Iterator, class Comp> inline bool is_sorted (Iterator first, Iterator last, Comp c) { return ::boost::detail::is_sorted_until(first, last, c) == last; } template<class Iterator> inline bool is_sorted (Iterator first, Iterator last) { return ::boost::detail::is_sorted_until(first, last) == last; } } // detail } // boost #endif // BOOST_DETAIL_SORTED_HPP
unknown
github
https://github.com/mysql/mysql-server
extra/boost/boost_1_87_0/boost/detail/is_sorted.hpp
from __future__ import print_function, division from sympy import (sympify, diff, sin, cos, Matrix, Symbol, integrate, trigsimp, Function, symbols) from sympy.core.basic import S from sympy.core.compatibility import reduce from .vector import Vector, _check_vector from .frame import CoordinateSym, _check_frame from .dyadic import Dyadic from .printing import vprint, vsprint, vpprint, vlatex, init_vprinting from sympy.utilities.iterables import iterable __all__ = ['cross', 'dot', 'express', 'time_derivative', 'outer', 'kinematic_equations', 'get_motion_params', 'partial_velocity', 'dynamicsymbols', 'vprint', 'vsprint', 'vpprint', 'vlatex', 'init_vprinting'] def cross(vec1, vec2): """Cross product convenience wrapper for Vector.cross(): \n""" if not isinstance(vec1, (Vector, Dyadic)): raise TypeError('Cross product is between two vectors') return vec1 ^ vec2 cross.__doc__ += Vector.cross.__doc__ def dot(vec1, vec2): """Dot product convenience wrapper for Vector.dot(): \n""" if not isinstance(vec1, (Vector, Dyadic)): raise TypeError('Dot product is between two vectors') return vec1 & vec2 dot.__doc__ += Vector.dot.__doc__ def express(expr, frame, frame2=None, variables=False): """ Global function for 'express' functionality. Re-expresses a Vector, scalar(sympyfiable) or Dyadic in given frame. Refer to the local methods of Vector and Dyadic for details. If 'variables' is True, then the coordinate variables (CoordinateSym instances) of other frames present in the vector/scalar field or dyadic expression are also substituted in terms of the base scalars of this frame. Parameters ========== expr : Vector/Dyadic/scalar(sympyfiable) The expression to re-express in ReferenceFrame 'frame' frame: ReferenceFrame The reference frame to express expr in frame2 : ReferenceFrame The other frame required for re-expression(only for Dyadic expr) variables : boolean Specifies whether to substitute the coordinate variables present in expr, in terms of those of frame Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer, dynamicsymbols >>> N = ReferenceFrame('N') >>> q = dynamicsymbols('q') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> d = outer(N.x, N.x) >>> from sympy.physics.vector import express >>> express(d, B, N) cos(q)*(B.x|N.x) - sin(q)*(B.y|N.x) >>> express(B.x, N) cos(q)*N.x + sin(q)*N.y >>> express(N[0], B, variables=True) B_x*cos(q(t)) - B_y*sin(q(t)) """ _check_frame(frame) if expr == 0: return expr if isinstance(expr, Vector): #Given expr is a Vector if variables: #If variables attribute is True, substitute #the coordinate variables in the Vector frame_list = [x[-1] for x in expr.args] subs_dict = {} for f in frame_list: subs_dict.update(f.variable_map(frame)) expr = expr.subs(subs_dict) #Re-express in this frame outvec = Vector([]) for i, v in enumerate(expr.args): if v[1] != frame: temp = frame.dcm(v[1]) * v[0] if Vector.simp: temp = temp.applyfunc(lambda x: trigsimp(x, method='fu')) outvec += Vector([(temp, frame)]) else: outvec += Vector([v]) return outvec if isinstance(expr, Dyadic): if frame2 is None: frame2 = frame _check_frame(frame2) ol = Dyadic(0) for i, v in enumerate(expr.args): ol += express(v[0], frame, variables=variables) * \ (express(v[1], frame, variables=variables) | express(v[2], frame2, variables=variables)) return ol else: if variables: #Given expr is a scalar field frame_set = set([]) expr = sympify(expr) #Subsitute all the coordinate variables for x in expr.free_symbols: if isinstance(x, CoordinateSym)and x.frame != frame: frame_set.add(x.frame) subs_dict = {} for f in frame_set: subs_dict.update(f.variable_map(frame)) return expr.subs(subs_dict) return expr def time_derivative(expr, frame, order=1): """ Calculate the time derivative of a vector/scalar field function or dyadic expression in given frame. References ========== http://en.wikipedia.org/wiki/Rotating_reference_frame#Time_derivatives_in_the_two_frames Parameters ========== expr : Vector/Dyadic/sympifyable The expression whose time derivative is to be calculated frame : ReferenceFrame The reference frame to calculate the time derivative in order : integer The order of the derivative to be calculated Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dynamicsymbols >>> from sympy import Symbol >>> q1 = Symbol('q1') >>> u1 = dynamicsymbols('u1') >>> N = ReferenceFrame('N') >>> A = N.orientnew('A', 'Axis', [q1, N.x]) >>> v = u1 * N.x >>> A.set_ang_vel(N, 10*A.x) >>> from sympy.physics.vector import time_derivative >>> time_derivative(v, N) u1'*N.x >>> time_derivative(u1*A[0], N) N_x*Derivative(u1(t), t) >>> B = N.orientnew('B', 'Axis', [u1, N.z]) >>> from sympy.physics.vector import outer >>> d = outer(N.x, N.x) >>> time_derivative(d, B) - u1'*(N.y|N.x) - u1'*(N.x|N.y) """ t = dynamicsymbols._t _check_frame(frame) if order == 0: return expr if order % 1 != 0 or order < 0: raise ValueError("Unsupported value of order entered") if isinstance(expr, Vector): outvec = Vector(0) for i, v in enumerate(expr.args): if v[1] == frame: outvec += Vector([(express(v[0], frame, variables=True).diff(t), frame)]) else: outvec += time_derivative(Vector([v]), v[1]) + \ (v[1].ang_vel_in(frame) ^ Vector([v])) return time_derivative(outvec, frame, order - 1) if isinstance(expr, Dyadic): ol = Dyadic(0) for i, v in enumerate(expr.args): ol += (v[0].diff(t) * (v[1] | v[2])) ol += (v[0] * (time_derivative(v[1], frame) | v[2])) ol += (v[0] * (v[1] | time_derivative(v[2], frame))) return time_derivative(ol, frame, order - 1) else: return diff(express(expr, frame, variables=True), t, order) def outer(vec1, vec2): """Outer product convenience wrapper for Vector.outer():\n""" if not isinstance(vec1, Vector): raise TypeError('Outer product is between two Vectors') return vec1 | vec2 outer.__doc__ += Vector.outer.__doc__ def kinematic_equations(speeds, coords, rot_type, rot_order=''): """Gives equations relating the qdot's to u's for a rotation type. Supply rotation type and order as in orient. Speeds are assumed to be body-fixed; if we are defining the orientation of B in A using by rot_type, the angular velocity of B in A is assumed to be in the form: speed[0]*B.x + speed[1]*B.y + speed[2]*B.z Parameters ========== speeds : list of length 3 The body fixed angular velocity measure numbers. coords : list of length 3 or 4 The coordinates used to define the orientation of the two frames. rot_type : str The type of rotation used to create the equations. Body, Space, or Quaternion only rot_order : str If applicable, the order of a series of rotations. Examples ======== >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import kinematic_equations, vprint >>> u1, u2, u3 = dynamicsymbols('u1 u2 u3') >>> q1, q2, q3 = dynamicsymbols('q1 q2 q3') >>> vprint(kinematic_equations([u1,u2,u3], [q1,q2,q3], 'body', '313'), ... order=None) [-(u1*sin(q3) + u2*cos(q3))/sin(q2) + q1', -u1*cos(q3) + u2*sin(q3) + q2', (u1*sin(q3) + u2*cos(q3))*cos(q2)/sin(q2) - u3 + q3'] """ # Code below is checking and sanitizing input approved_orders = ('123', '231', '312', '132', '213', '321', '121', '131', '212', '232', '313', '323', '1', '2', '3', '') rot_order = str(rot_order).upper() # Now we need to make sure XYZ = 123 rot_type = rot_type.upper() rot_order = [i.replace('X', '1') for i in rot_order] rot_order = [i.replace('Y', '2') for i in rot_order] rot_order = [i.replace('Z', '3') for i in rot_order] rot_order = ''.join(rot_order) if not isinstance(speeds, (list, tuple)): raise TypeError('Need to supply speeds in a list') if len(speeds) != 3: raise TypeError('Need to supply 3 body-fixed speeds') if not isinstance(coords, (list, tuple)): raise TypeError('Need to supply coordinates in a list') if rot_type.lower() in ['body', 'space']: if rot_order not in approved_orders: raise ValueError('Not an acceptable rotation order') if len(coords) != 3: raise ValueError('Need 3 coordinates for body or space') # Actual hard-coded kinematic differential equations q1, q2, q3 = coords q1d, q2d, q3d = [diff(i, dynamicsymbols._t) for i in coords] w1, w2, w3 = speeds s1, s2, s3 = [sin(q1), sin(q2), sin(q3)] c1, c2, c3 = [cos(q1), cos(q2), cos(q3)] if rot_type.lower() == 'body': if rot_order == '123': return [q1d - (w1 * c3 - w2 * s3) / c2, q2d - w1 * s3 - w2 * c3, q3d - (-w1 * c3 + w2 * s3) * s2 / c2 - w3] if rot_order == '231': return [q1d - (w2 * c3 - w3 * s3) / c2, q2d - w2 * s3 - w3 * c3, q3d - w1 - (- w2 * c3 + w3 * s3) * s2 / c2] if rot_order == '312': return [q1d - (-w1 * s3 + w3 * c3) / c2, q2d - w1 * c3 - w3 * s3, q3d - (w1 * s3 - w3 * c3) * s2 / c2 - w2] if rot_order == '132': return [q1d - (w1 * c3 + w3 * s3) / c2, q2d + w1 * s3 - w3 * c3, q3d - (w1 * c3 + w3 * s3) * s2 / c2 - w2] if rot_order == '213': return [q1d - (w1 * s3 + w2 * c3) / c2, q2d - w1 * c3 + w2 * s3, q3d - (w1 * s3 + w2 * c3) * s2 / c2 - w3] if rot_order == '321': return [q1d - (w2 * s3 + w3 * c3) / c2, q2d - w2 * c3 + w3 * s3, q3d - w1 - (w2 * s3 + w3 * c3) * s2 / c2] if rot_order == '121': return [q1d - (w2 * s3 + w3 * c3) / s2, q2d - w2 * c3 + w3 * s3, q3d - w1 + (w2 * s3 + w3 * c3) * c2 / s2] if rot_order == '131': return [q1d - (-w2 * c3 + w3 * s3) / s2, q2d - w2 * s3 - w3 * c3, q3d - w1 - (w2 * c3 - w3 * s3) * c2 / s2] if rot_order == '212': return [q1d - (w1 * s3 - w3 * c3) / s2, q2d - w1 * c3 - w3 * s3, q3d - (-w1 * s3 + w3 * c3) * c2 / s2 - w2] if rot_order == '232': return [q1d - (w1 * c3 + w3 * s3) / s2, q2d + w1 * s3 - w3 * c3, q3d + (w1 * c3 + w3 * s3) * c2 / s2 - w2] if rot_order == '313': return [q1d - (w1 * s3 + w2 * c3) / s2, q2d - w1 * c3 + w2 * s3, q3d + (w1 * s3 + w2 * c3) * c2 / s2 - w3] if rot_order == '323': return [q1d - (-w1 * c3 + w2 * s3) / s2, q2d - w1 * s3 - w2 * c3, q3d - (w1 * c3 - w2 * s3) * c2 / s2 - w3] if rot_type.lower() == 'space': if rot_order == '123': return [q1d - w1 - (w2 * s1 + w3 * c1) * s2 / c2, q2d - w2 * c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / c2] if rot_order == '231': return [q1d - (w1 * c1 + w3 * s1) * s2 / c2 - w2, q2d + w1 * s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / c2] if rot_order == '312': return [q1d - (w1 * s1 + w2 * c1) * s2 / c2 - w3, q2d - w1 * c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / c2] if rot_order == '132': return [q1d - w1 - (-w2 * c1 + w3 * s1) * s2 / c2, q2d - w2 * s1 - w3 * c1, q3d - (w2 * c1 - w3 * s1) / c2] if rot_order == '213': return [q1d - (w1 * s1 - w3 * c1) * s2 / c2 - w2, q2d - w1 * c1 - w3 * s1, q3d - (-w1 * s1 + w3 * c1) / c2] if rot_order == '321': return [q1d - (-w1 * c1 + w2 * s1) * s2 / c2 - w3, q2d - w1 * s1 - w2 * c1, q3d - (w1 * c1 - w2 * s1) / c2] if rot_order == '121': return [q1d - w1 + (w2 * s1 + w3 * c1) * c2 / s2, q2d - w2 * c1 + w3 * s1, q3d - (w2 * s1 + w3 * c1) / s2] if rot_order == '131': return [q1d - w1 - (w2 * c1 - w3 * s1) * c2 / s2, q2d - w2 * s1 - w3 * c1, q3d - (-w2 * c1 + w3 * s1) / s2] if rot_order == '212': return [q1d - (-w1 * s1 + w3 * c1) * c2 / s2 - w2, q2d - w1 * c1 - w3 * s1, q3d - (w1 * s1 - w3 * c1) / s2] if rot_order == '232': return [q1d + (w1 * c1 + w3 * s1) * c2 / s2 - w2, q2d + w1 * s1 - w3 * c1, q3d - (w1 * c1 + w3 * s1) / s2] if rot_order == '313': return [q1d + (w1 * s1 + w2 * c1) * c2 / s2 - w3, q2d - w1 * c1 + w2 * s1, q3d - (w1 * s1 + w2 * c1) / s2] if rot_order == '323': return [q1d - (w1 * c1 - w2 * s1) * c2 / s2 - w3, q2d - w1 * s1 - w2 * c1, q3d - (-w1 * c1 + w2 * s1) / s2] elif rot_type.lower() == 'quaternion': if rot_order != '': raise ValueError('Cannot have rotation order for quaternion') if len(coords) != 4: raise ValueError('Need 4 coordinates for quaternion') # Actual hard-coded kinematic differential equations e0, e1, e2, e3 = coords w = Matrix(speeds + [0]) E = Matrix([[e0, -e3, e2, e1], [e3, e0, -e1, e2], [-e2, e1, e0, e3], [-e1, -e2, -e3, e0]]) edots = Matrix([diff(i, dynamicsymbols._t) for i in [e1, e2, e3, e0]]) return list(edots.T - 0.5 * w.T * E.T) else: raise ValueError('Not an approved rotation type for this function') def get_motion_params(frame, **kwargs): """ Returns the three motion parameters - (acceleration, velocity, and position) as vectorial functions of time in the given frame. If a higher order differential function is provided, the lower order functions are used as boundary conditions. For example, given the acceleration, the velocity and position parameters are taken as boundary conditions. The values of time at which the boundary conditions are specified are taken from timevalue1(for position boundary condition) and timevalue2(for velocity boundary condition). If any of the boundary conditions are not provided, they are taken to be zero by default (zero vectors, in case of vectorial inputs). If the boundary conditions are also functions of time, they are converted to constants by substituting the time values in the dynamicsymbols._t time Symbol. This function can also be used for calculating rotational motion parameters. Have a look at the Parameters and Examples for more clarity. Parameters ========== frame : ReferenceFrame The frame to express the motion parameters in acceleration : Vector Acceleration of the object/frame as a function of time velocity : Vector Velocity as function of time or as boundary condition of velocity at time = timevalue1 position : Vector Velocity as function of time or as boundary condition of velocity at time = timevalue1 timevalue1 : sympyfiable Value of time for position boundary condition timevalue2 : sympyfiable Value of time for velocity boundary condition Examples ======== >>> from sympy.physics.vector import ReferenceFrame, get_motion_params, dynamicsymbols >>> from sympy import symbols >>> R = ReferenceFrame('R') >>> v1, v2, v3 = dynamicsymbols('v1 v2 v3') >>> v = v1*R.x + v2*R.y + v3*R.z >>> get_motion_params(R, position = v) (v1''*R.x + v2''*R.y + v3''*R.z, v1'*R.x + v2'*R.y + v3'*R.z, v1*R.x + v2*R.y + v3*R.z) >>> a, b, c = symbols('a b c') >>> v = a*R.x + b*R.y + c*R.z >>> get_motion_params(R, velocity = v) (0, a*R.x + b*R.y + c*R.z, a*t*R.x + b*t*R.y + c*t*R.z) >>> parameters = get_motion_params(R, acceleration = v) >>> parameters[1] a*t*R.x + b*t*R.y + c*t*R.z >>> parameters[2] a*t**2/2*R.x + b*t**2/2*R.y + c*t**2/2*R.z """ ##Helper functions def _process_vector_differential(vectdiff, condition, \ variable, ordinate, frame): """ Helper function for get_motion methods. Finds derivative of vectdiff wrt variable, and its integral using the specified boundary condition at value of variable = ordinate. Returns a tuple of - (derivative, function and integral) wrt vectdiff """ #Make sure boundary condition is independent of 'variable' if condition != 0: condition = express(condition, frame, variables=True) #Special case of vectdiff == 0 if vectdiff == Vector(0): return (0, 0, condition) #Express vectdiff completely in condition's frame to give vectdiff1 vectdiff1 = express(vectdiff, frame) #Find derivative of vectdiff vectdiff2 = time_derivative(vectdiff, frame) #Integrate and use boundary condition vectdiff0 = Vector(0) lims = (variable, ordinate, variable) for dim in frame: function1 = vectdiff1.dot(dim) abscissa = dim.dot(condition).subs({variable : ordinate}) # Indefinite integral of 'function1' wrt 'variable', using # the given initial condition (ordinate, abscissa). vectdiff0 += (integrate(function1, lims) + abscissa) * dim #Return tuple return (vectdiff2, vectdiff, vectdiff0) ##Function body _check_frame(frame) #Decide mode of operation based on user's input if 'acceleration' in kwargs: mode = 2 elif 'velocity' in kwargs: mode = 1 else: mode = 0 #All the possible parameters in kwargs #Not all are required for every case #If not specified, set to default values(may or may not be used in #calculations) conditions = ['acceleration', 'velocity', 'position', 'timevalue', 'timevalue1', 'timevalue2'] for i, x in enumerate(conditions): if x not in kwargs: if i < 3: kwargs[x] = Vector(0) else: kwargs[x] = S(0) elif i < 3: _check_vector(kwargs[x]) else: kwargs[x] = sympify(kwargs[x]) if mode == 2: vel = _process_vector_differential(kwargs['acceleration'], kwargs['velocity'], dynamicsymbols._t, kwargs['timevalue2'], frame)[2] pos = _process_vector_differential(vel, kwargs['position'], dynamicsymbols._t, kwargs['timevalue1'], frame)[2] return (kwargs['acceleration'], vel, pos) elif mode == 1: return _process_vector_differential(kwargs['velocity'], kwargs['position'], dynamicsymbols._t, kwargs['timevalue1'], frame) else: vel = time_derivative(kwargs['position'], frame) acc = time_derivative(vel, frame) return (acc, vel, kwargs['position']) def partial_velocity(vel_list, u_list, frame): """Returns a list of partial velocities. For a list of velocity or angular velocity vectors the partial derivatives with respect to the supplied generalized speeds are computed, in the specified ReferenceFrame. The output is a list of lists. The outer list has a number of elements equal to the number of supplied velocity vectors. The inner lists are, for each velocity vector, the partial derivatives of that velocity vector with respect to the generalized speeds supplied. Parameters ========== vel_list : list List of velocities of Point's and angular velocities of ReferenceFrame's u_list : list List of independent generalized speeds. frame : ReferenceFrame The ReferenceFrame the partial derivatives are going to be taken in. Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import partial_velocity >>> u = dynamicsymbols('u') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, u * N.x) >>> vel_list = [P.vel(N)] >>> u_list = [u] >>> partial_velocity(vel_list, u_list, N) [[N.x]] """ if not iterable(vel_list): raise TypeError('Provide velocities in an iterable') if not iterable(u_list): raise TypeError('Provide speeds in an iterable') list_of_pvlists = [] for i in vel_list: pvlist = [] for j in u_list: vel = i.diff(j, frame) pvlist += [vel] list_of_pvlists += [pvlist] return list_of_pvlists def dynamicsymbols(names, level=0): """Uses symbols and Function for functions of time. Creates a SymPy UndefinedFunction, which is then initialized as a function of a variable, the default being Symbol('t'). Parameters ========== names : str Names of the dynamic symbols you want to create; works the same way as inputs to symbols level : int Level of differentiation of the returned function; d/dt once of t, twice of t, etc. Examples ======== >>> from sympy.physics.vector import dynamicsymbols >>> from sympy import diff, Symbol >>> q1 = dynamicsymbols('q1') >>> q1 q1(t) >>> diff(q1, Symbol('t')) Derivative(q1(t), t) """ esses = symbols(names, cls=Function) t = dynamicsymbols._t if iterable(esses): esses = [reduce(diff, [t] * level, e(t)) for e in esses] return esses else: return reduce(diff, [t] * level, esses(t)) dynamicsymbols._t = Symbol('t') dynamicsymbols._str = '\''
unknown
codeparrot/codeparrot-clean
# Copyright 2020 Google # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from functools import lru_cache from typing import Dict import numpy as np import recirq from recirq.qaoa.classical_angle_optimization import OptimizationResult, \ optimize_instance_interp_heuristic from recirq.qaoa.experiments.problem_generation_tasks import ProblemGenerationTaskT, \ DEFAULT_BASE_DIR as DEFAULT_PROBLEM_GENERATION_BASE_DIR from recirq.qaoa.problems import HardwareGridProblem, ThreeRegularProblem, SKProblem EXPERIMENT_NAME = 'qaoa-precomputation' DEFAULT_BASE_DIR = os.path.expanduser(f'~/cirq-results/{EXPERIMENT_NAME}') @recirq.json_serializable_dataclass(namespace='recirq.qaoa', registry=recirq.Registry, frozen=True) class AnglePrecomputationTask: """Pre-compute optimized angles classically for a given problem. See Also: :py:func:`precompute_angles` Attributes: dataset_id: A unique identifier for this dataset. generation_task: The input task which specifies the problem. p: QAOA depth hyperparameter p. The number of parameters is 2*p. """ dataset_id: str generation_task: ProblemGenerationTaskT p: int @property def fn(self): parent_fn = self.generation_task.fn return (f'{self.dataset_id}/' f'from-{parent_fn}/' f'p-{self.p}') @lru_cache() def _get_optima(in_task: ProblemGenerationTaskT, problem_generation_base_dir, p_max: int = 5) \ -> Dict[int, OptimizationResult]: """Helper function to get optimal parameters for a given instance of a given device's problem, subselected on a given number of qubits. This function is annotated with lru_cache so you can call it once for each p-value without re-doing the (expensive) optimization. optimize_instance_interp_heuristic uses low-p-values to bootstrap guesses for high-p-values, so it just does the optimization for everything up to p_max. This is the meat of `generate_problems` to get the optimal parameters for a given (device, instance, n_qubit, p) specification which are all the relevant parameters. """ data = recirq.load(in_task, base_dir=problem_generation_base_dir) problem = data['problem'] if isinstance(problem, HardwareGridProblem): param_guess = [np.pi / 8, -np.pi / 8] elif isinstance(problem, ThreeRegularProblem): param_guess = [np.pi / 8, -np.pi / 8] elif isinstance(problem, SKProblem): n = problem.graph.number_of_nodes() param_guess = [ np.arccos(np.sqrt((1 + np.sqrt((n - 2) / (n - 1))) / 2)), -np.pi / 8 ] else: raise ValueError("Unknown problem type: {}".format(problem)) optima = optimize_instance_interp_heuristic( graph=problem.graph, p_max=p_max, param_guess_at_p1=param_guess, verbose=True, ) return {op.p: op for op in optima} def precompute_angles(task: AnglePrecomputationTask, base_dir=None, problem_generation_base_dir=None): """Execute a :py:func:`AnglePrecomputationTask` task.""" if base_dir is None: base_dir = DEFAULT_BASE_DIR if problem_generation_base_dir is None: problem_generation_base_dir = DEFAULT_PROBLEM_GENERATION_BASE_DIR if recirq.exists(task, base_dir=base_dir): print(f"{task.fn} already exists. Skipping.") return optimum = _get_optima( in_task=task.generation_task, problem_generation_base_dir=problem_generation_base_dir, )[task.p] recirq.save(task=task, data={ 'optimum': optimum, }, base_dir=base_dir) print(f"{task.fn} complete.")
unknown
codeparrot/codeparrot-clean
"""Tests for distutils.msvc9compiler.""" import sys import unittest import os from distutils.errors import DistutilsPlatformError from distutils.tests import support from test.support import run_unittest # A manifest with the only assembly reference being the msvcrt assembly, so # should have the assembly completely stripped. Note that although the # assembly has a <security> reference the assembly is removed - that is # currently a "feature", not a bug :) _MANIFEST_WITH_ONLY_MSVC_REFERENCE = """\ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"> </requestedExecutionLevel> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="XXXX"> </assemblyIdentity> </dependentAssembly> </dependency> </assembly> """ # A manifest with references to assemblies other than msvcrt. When processed, # this assembly should be returned with just the msvcrt part removed. _MANIFEST_WITH_MULTIPLE_REFERENCES = """\ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"> </requestedExecutionLevel> </requestedPrivileges> </security> </trustInfo> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="XXXX"> </assemblyIdentity> </dependentAssembly> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="XXXX"></assemblyIdentity> </dependentAssembly> </dependency> </assembly> """ _CLEANED_MANIFEST = """\ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"> </requestedExecutionLevel> </requestedPrivileges> </security> </trustInfo> <dependency> </dependency> <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.VC90.MFC" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="XXXX"></assemblyIdentity> </dependentAssembly> </dependency> </assembly>""" if sys.platform=="win32": from distutils.msvccompiler import get_build_version if get_build_version()>=8.0: SKIP_MESSAGE = None else: SKIP_MESSAGE = "These tests are only for MSVC8.0 or above" else: SKIP_MESSAGE = "These tests are only for win32" @unittest.skipUnless(SKIP_MESSAGE is None, SKIP_MESSAGE) class msvc9compilerTestCase(support.TempdirManager, unittest.TestCase): def test_no_compiler(self): # makes sure query_vcvarsall raises # a DistutilsPlatformError if the compiler # is not found from distutils.msvc9compiler import query_vcvarsall def _find_vcvarsall(version): return None from distutils import msvc9compiler old_find_vcvarsall = msvc9compiler.find_vcvarsall msvc9compiler.find_vcvarsall = _find_vcvarsall try: self.assertRaises(DistutilsPlatformError, query_vcvarsall, 'wont find this version') finally: msvc9compiler.find_vcvarsall = old_find_vcvarsall def test_reg_class(self): from distutils.msvc9compiler import Reg self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx') # looking for values that should exist on all # windows registeries versions. path = r'Control Panel\Desktop' v = Reg.get_value(path, 'dragfullwindows') self.assertIn(v, ('0', '1', '2')) import winreg HKCU = winreg.HKEY_CURRENT_USER keys = Reg.read_keys(HKCU, 'xxxx') self.assertEqual(keys, None) keys = Reg.read_keys(HKCU, r'Control Panel') self.assertIn('Desktop', keys) def test_remove_visual_c_ref(self): from distutils.msvc9compiler import MSVCCompiler tempdir = self.mkdtemp() manifest = os.path.join(tempdir, 'manifest') f = open(manifest, 'w') try: f.write(_MANIFEST_WITH_MULTIPLE_REFERENCES) finally: f.close() compiler = MSVCCompiler() compiler._remove_visual_c_ref(manifest) # see what we got f = open(manifest) try: # removing trailing spaces content = '\n'.join([line.rstrip() for line in f.readlines()]) finally: f.close() # makes sure the manifest was properly cleaned self.assertEqual(content, _CLEANED_MANIFEST) def test_remove_entire_manifest(self): from distutils.msvc9compiler import MSVCCompiler tempdir = self.mkdtemp() manifest = os.path.join(tempdir, 'manifest') f = open(manifest, 'w') try: f.write(_MANIFEST_WITH_ONLY_MSVC_REFERENCE) finally: f.close() compiler = MSVCCompiler() got = compiler._remove_visual_c_ref(manifest) self.assertIsNone(got) def test_suite(): return unittest.makeSuite(msvc9compilerTestCase) if __name__ == "__main__": run_unittest(test_suite())
unknown
codeparrot/codeparrot-clean
#-*- coding: ISO-8859-1 -*- # pysqlite2/test/userfunctions.py: tests for user-defined functions and # aggregates. # # Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. import unittest import sqlite3 as sqlite def func_returntext(): return "foo" def func_returnunicode(): return u"bar" def func_returnint(): return 42 def func_returnfloat(): return 3.14 def func_returnnull(): return None def func_returnblob(): return buffer("blob") def func_returnlonglong(): return 1<<31 def func_raiseexception(): 5 // 0 def func_isstring(v): return type(v) is unicode def func_isint(v): return type(v) is int def func_isfloat(v): return type(v) is float def func_isnone(v): return type(v) is type(None) def func_isblob(v): return type(v) is buffer def func_islonglong(v): return isinstance(v, (int, long)) and v >= 1<<31 class AggrNoStep: def __init__(self): pass def finalize(self): return 1 class AggrNoFinalize: def __init__(self): pass def step(self, x): pass class AggrExceptionInInit: def __init__(self): 5 // 0 def step(self, x): pass def finalize(self): pass class AggrExceptionInStep: def __init__(self): pass def step(self, x): 5 // 0 def finalize(self): return 42 class AggrExceptionInFinalize: def __init__(self): pass def step(self, x): pass def finalize(self): 5 // 0 class AggrCheckType: def __init__(self): self.val = None def step(self, whichType, val): theType = {"str": unicode, "int": int, "float": float, "None": type(None), "blob": buffer} self.val = int(theType[whichType] is type(val)) def finalize(self): return self.val class AggrSum: def __init__(self): self.val = 0.0 def step(self, val): self.val += val def finalize(self): return self.val class FunctionTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") self.con.create_function("returntext", 0, func_returntext) self.con.create_function("returnunicode", 0, func_returnunicode) self.con.create_function("returnint", 0, func_returnint) self.con.create_function("returnfloat", 0, func_returnfloat) self.con.create_function("returnnull", 0, func_returnnull) self.con.create_function("returnblob", 0, func_returnblob) self.con.create_function("returnlonglong", 0, func_returnlonglong) self.con.create_function("raiseexception", 0, func_raiseexception) self.con.create_function("isstring", 1, func_isstring) self.con.create_function("isint", 1, func_isint) self.con.create_function("isfloat", 1, func_isfloat) self.con.create_function("isnone", 1, func_isnone) self.con.create_function("isblob", 1, func_isblob) self.con.create_function("islonglong", 1, func_islonglong) def tearDown(self): self.con.close() def CheckFuncErrorOnCreate(self): try: self.con.create_function("bla", -100, lambda x: 2*x) self.fail("should have raised an OperationalError") except sqlite.OperationalError: pass def CheckFuncRefCount(self): def getfunc(): def f(): return 1 return f f = getfunc() globals()["foo"] = f # self.con.create_function("reftest", 0, getfunc()) self.con.create_function("reftest", 0, f) cur = self.con.cursor() cur.execute("select reftest()") def CheckFuncReturnText(self): cur = self.con.cursor() cur.execute("select returntext()") val = cur.fetchone()[0] self.assertEqual(type(val), unicode) self.assertEqual(val, "foo") def CheckFuncReturnUnicode(self): cur = self.con.cursor() cur.execute("select returnunicode()") val = cur.fetchone()[0] self.assertEqual(type(val), unicode) self.assertEqual(val, u"bar") def CheckFuncReturnInt(self): cur = self.con.cursor() cur.execute("select returnint()") val = cur.fetchone()[0] self.assertEqual(type(val), int) self.assertEqual(val, 42) def CheckFuncReturnFloat(self): cur = self.con.cursor() cur.execute("select returnfloat()") val = cur.fetchone()[0] self.assertEqual(type(val), float) if val < 3.139 or val > 3.141: self.fail("wrong value") def CheckFuncReturnNull(self): cur = self.con.cursor() cur.execute("select returnnull()") val = cur.fetchone()[0] self.assertEqual(type(val), type(None)) self.assertEqual(val, None) def CheckFuncReturnBlob(self): cur = self.con.cursor() cur.execute("select returnblob()") val = cur.fetchone()[0] self.assertEqual(type(val), buffer) self.assertEqual(val, buffer("blob")) def CheckFuncReturnLongLong(self): cur = self.con.cursor() cur.execute("select returnlonglong()") val = cur.fetchone()[0] self.assertEqual(val, 1<<31) def CheckFuncException(self): cur = self.con.cursor() try: cur.execute("select raiseexception()") cur.fetchone() self.fail("should have raised OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], 'user-defined function raised exception') def CheckParamString(self): cur = self.con.cursor() cur.execute("select isstring(?)", ("foo",)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckParamInt(self): cur = self.con.cursor() cur.execute("select isint(?)", (42,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckParamFloat(self): cur = self.con.cursor() cur.execute("select isfloat(?)", (3.14,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckParamNone(self): cur = self.con.cursor() cur.execute("select isnone(?)", (None,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckParamBlob(self): cur = self.con.cursor() cur.execute("select isblob(?)", (buffer("blob"),)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckParamLongLong(self): cur = self.con.cursor() cur.execute("select islonglong(?)", (1<<42,)) val = cur.fetchone()[0] self.assertEqual(val, 1) class AggregateTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") cur = self.con.cursor() cur.execute(""" create table test( t text, i integer, f float, n, b blob ) """) cur.execute("insert into test(t, i, f, n, b) values (?, ?, ?, ?, ?)", ("foo", 5, 3.14, None, buffer("blob"),)) self.con.create_aggregate("nostep", 1, AggrNoStep) self.con.create_aggregate("nofinalize", 1, AggrNoFinalize) self.con.create_aggregate("excInit", 1, AggrExceptionInInit) self.con.create_aggregate("excStep", 1, AggrExceptionInStep) self.con.create_aggregate("excFinalize", 1, AggrExceptionInFinalize) self.con.create_aggregate("checkType", 2, AggrCheckType) self.con.create_aggregate("mysum", 1, AggrSum) def tearDown(self): #self.cur.close() #self.con.close() pass def CheckAggrErrorOnCreate(self): try: self.con.create_function("bla", -100, AggrSum) self.fail("should have raised an OperationalError") except sqlite.OperationalError: pass def CheckAggrNoStep(self): cur = self.con.cursor() try: cur.execute("select nostep(t) from test") self.fail("should have raised an AttributeError") except AttributeError, e: self.assertEqual(e.args[0], "AggrNoStep instance has no attribute 'step'") def CheckAggrNoFinalize(self): cur = self.con.cursor() try: cur.execute("select nofinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrExceptionInInit(self): cur = self.con.cursor() try: cur.execute("select excInit(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], "user-defined aggregate's '__init__' method raised error") def CheckAggrExceptionInStep(self): cur = self.con.cursor() try: cur.execute("select excStep(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], "user-defined aggregate's 'step' method raised error") def CheckAggrExceptionInFinalize(self): cur = self.con.cursor() try: cur.execute("select excFinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrCheckParamStr(self): cur = self.con.cursor() cur.execute("select checkType('str', ?)", ("foo",)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckParamInt(self): cur = self.con.cursor() cur.execute("select checkType('int', ?)", (42,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckParamFloat(self): cur = self.con.cursor() cur.execute("select checkType('float', ?)", (3.14,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckParamNone(self): cur = self.con.cursor() cur.execute("select checkType('None', ?)", (None,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckParamBlob(self): cur = self.con.cursor() cur.execute("select checkType('blob', ?)", (buffer("blob"),)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckAggrSum(self): cur = self.con.cursor() cur.execute("delete from test") cur.executemany("insert into test(i) values (?)", [(10,), (20,), (30,)]) cur.execute("select mysum(i) from test") val = cur.fetchone()[0] self.assertEqual(val, 60) def authorizer_cb(action, arg1, arg2, dbname, source): if action != sqlite.SQLITE_SELECT: return sqlite.SQLITE_DENY if arg2 == 'c2' or arg1 == 't2': return sqlite.SQLITE_DENY return sqlite.SQLITE_OK class AuthorizerTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") self.con.executescript(""" create table t1 (c1, c2); create table t2 (c1, c2); insert into t1 (c1, c2) values (1, 2); insert into t2 (c1, c2) values (4, 5); """) # For our security test: self.con.execute("select c2 from t2") self.con.set_authorizer(authorizer_cb) def tearDown(self): pass def CheckTableAccess(self): try: self.con.execute("select * from t2") except sqlite.DatabaseError, e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return self.fail("should have raised an exception due to missing privileges") def CheckColumnAccess(self): try: self.con.execute("select c2 from t1") except sqlite.DatabaseError, e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return self.fail("should have raised an exception due to missing privileges") def suite(): function_suite = unittest.makeSuite(FunctionTests, "Check") aggregate_suite = unittest.makeSuite(AggregateTests, "Check") authorizer_suite = unittest.makeSuite(AuthorizerTests, "Check") return unittest.TestSuite((function_suite, aggregate_suite, authorizer_suite)) def test(): runner = unittest.TextTestRunner() runner.run(suite()) if __name__ == "__main__": test()
unknown
codeparrot/codeparrot-clean
from __future__ import unicode_literals from django.core.urlresolvers import NoReverseMatch from django.contrib.auth.views import logout from django.shortcuts import resolve_url from django.test import TestCase from .models import UnimportantThing class ResolveUrlTests(TestCase): """ Tests for the ``resolve_url`` function. """ urls = 'resolve_url.urls' def test_url_path(self): """ Tests that passing a URL path to ``resolve_url`` will result in the same url. """ self.assertEqual('/something/', resolve_url('/something/')) def test_full_url(self): """ Tests that passing a full URL to ``resolve_url`` will result in the same url. """ url = 'http://example.com/' self.assertEqual(url, resolve_url(url)) def test_model(self): """ Tests that passing a model to ``resolve_url`` will result in ``get_absolute_url`` being called on that model instance. """ m = UnimportantThing(importance=1) self.assertEqual(m.get_absolute_url(), resolve_url(m)) def test_view_function(self): """ Tests that passing a view name to ``resolve_url`` will result in the URL path mapping to that view name. """ resolved_url = resolve_url(logout) self.assertEqual('/accounts/logout/', resolved_url) def test_valid_view_name(self): """ Tests that passing a view function to ``resolve_url`` will result in the URL path mapping to that view. """ resolved_url = resolve_url('django.contrib.auth.views.logout') self.assertEqual('/accounts/logout/', resolved_url) def test_domain(self): """ Tests that passing a domain to ``resolve_url`` returns the same domain. """ self.assertEqual(resolve_url('example.com'), 'example.com') def test_non_view_callable_raises_no_reverse_match(self): """ Tests that passing a non-view callable into ``resolve_url`` raises a ``NoReverseMatch`` exception. """ with self.assertRaises(NoReverseMatch): resolve_url(lambda: 'asdf')
unknown
codeparrot/codeparrot-clean
// Copyright IBM Corp. 2016, 2025 // SPDX-License-Identifier: BUSL-1.1 package audit import ( "testing" "time" "github.com/stretchr/testify/require" ) // TestOptions_withFormat exercises withFormat option to ensure it performs as expected. func TestOptions_withFormat(t *testing.T) { t.Parallel() tests := map[string]struct { Value string IsErrorExpected bool ExpectedErrorMessage string ExpectedValue format }{ "empty": { Value: "", IsErrorExpected: false, ExpectedValue: format(""), }, "whitespace": { Value: " ", IsErrorExpected: false, ExpectedValue: format(""), }, "invalid-test": { Value: "test", IsErrorExpected: true, ExpectedErrorMessage: "invalid format \"test\": invalid internal parameter", }, "valid-json": { Value: "json", IsErrorExpected: false, ExpectedValue: jsonFormat, }, "valid-jsonx": { Value: "jsonx", IsErrorExpected: false, ExpectedValue: jsonxFormat, }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts := &options{} applyOption := withFormat(tc.Value) err := applyOption(opts) switch { case tc.IsErrorExpected: require.Error(t, err) require.EqualError(t, err, tc.ExpectedErrorMessage) default: require.NoError(t, err) require.Equal(t, tc.ExpectedValue, opts.withFormat) } }) } } // TestOptions_withSubtype exercises withSubtype option to ensure it performs as expected. func TestOptions_withSubtype(t *testing.T) { t.Parallel() tests := map[string]struct { Value string IsErrorExpected bool ExpectedErrorMessage string ExpectedValue subtype }{ "empty": { Value: "", IsErrorExpected: true, ExpectedErrorMessage: "subtype cannot be empty", }, "whitespace": { Value: " ", IsErrorExpected: true, ExpectedErrorMessage: "subtype cannot be empty", }, "valid": { Value: "AuditResponse", IsErrorExpected: false, ExpectedValue: ResponseType, }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts := &options{} applyOption := withSubtype(tc.Value) err := applyOption(opts) switch { case tc.IsErrorExpected: require.Error(t, err) require.EqualError(t, err, tc.ExpectedErrorMessage) default: require.NoError(t, err) require.Equal(t, tc.ExpectedValue, opts.withSubtype) } }) } } // TestOptions_withNow exercises withNow option to ensure it performs as expected. func TestOptions_withNow(t *testing.T) { t.Parallel() tests := map[string]struct { Value time.Time IsErrorExpected bool ExpectedErrorMessage string ExpectedValue time.Time }{ "default-time": { Value: time.Time{}, IsErrorExpected: true, ExpectedErrorMessage: "cannot specify 'now' to be the zero time instant", }, "valid-time": { Value: time.Date(2023, time.July, 4, 12, 3, 0, 0, time.Local), IsErrorExpected: false, ExpectedValue: time.Date(2023, time.July, 4, 12, 3, 0, 0, time.Local), }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts := &options{} applyOption := withNow(tc.Value) err := applyOption(opts) switch { case tc.IsErrorExpected: require.Error(t, err) require.EqualError(t, err, tc.ExpectedErrorMessage) default: require.NoError(t, err) require.Equal(t, tc.ExpectedValue, opts.withNow) } }) } } // TestOptions_withID exercises withID option to ensure it performs as expected. func TestOptions_withID(t *testing.T) { t.Parallel() tests := map[string]struct { Value string IsErrorExpected bool ExpectedErrorMessage string ExpectedValue string }{ "empty": { Value: "", IsErrorExpected: true, ExpectedErrorMessage: "id cannot be empty", }, "whitespace": { Value: " ", IsErrorExpected: true, ExpectedErrorMessage: "id cannot be empty", }, "valid": { Value: "test", IsErrorExpected: false, ExpectedValue: "test", }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts := &options{} applyOption := withID(tc.Value) err := applyOption(opts) switch { case tc.IsErrorExpected: require.Error(t, err) require.EqualError(t, err, tc.ExpectedErrorMessage) default: require.NoError(t, err) require.Equal(t, tc.ExpectedValue, opts.withID) } }) } } // TestOptions_withPrefix exercises withPrefix option to ensure it performs as expected. func TestOptions_withPrefix(t *testing.T) { t.Parallel() tests := map[string]struct { Value string IsErrorExpected bool ExpectedErrorMessage string ExpectedValue string }{ "empty": { Value: "", IsErrorExpected: false, ExpectedValue: "", }, "whitespace": { Value: " ", IsErrorExpected: false, ExpectedValue: " ", }, "valid": { Value: "test", IsErrorExpected: false, ExpectedValue: "test", }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts := &options{} applyOption := withPrefix(tc.Value) err := applyOption(opts) switch { case tc.IsErrorExpected: require.Error(t, err) require.EqualError(t, err, tc.ExpectedErrorMessage) default: require.NoError(t, err) require.Equal(t, tc.ExpectedValue, opts.withPrefix) } }) } } // TestOptions_withRaw exercises withRaw option to ensure it performs as expected. func TestOptions_withRaw(t *testing.T) { t.Parallel() tests := map[string]struct { Value bool ExpectedValue bool }{ "true": { Value: true, ExpectedValue: true, }, "false": { Value: false, ExpectedValue: false, }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts := &options{} applyOption := withRaw(tc.Value) err := applyOption(opts) require.NoError(t, err) require.Equal(t, tc.ExpectedValue, opts.withRaw) }) } } // TestOptions_withElision exercises withElision option to ensure it performs as expected. func TestOptions_withElision(t *testing.T) { t.Parallel() tests := map[string]struct { Value bool ExpectedValue bool }{ "true": { Value: true, ExpectedValue: true, }, "false": { Value: false, ExpectedValue: false, }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts := &options{} applyOption := withElision(tc.Value) err := applyOption(opts) require.NoError(t, err) require.Equal(t, tc.ExpectedValue, opts.withElision) }) } } // TestOptions_withHMACAccessor exercises withHMACAccessor option to ensure it performs as expected. func TestOptions_withHMACAccessor(t *testing.T) { t.Parallel() tests := map[string]struct { Value bool ExpectedValue bool }{ "true": { Value: true, ExpectedValue: true, }, "false": { Value: false, ExpectedValue: false, }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts := &options{} applyOption := withHMACAccessor(tc.Value) err := applyOption(opts) require.NoError(t, err) require.Equal(t, tc.ExpectedValue, opts.withHMACAccessor) }) } } // TestOptions_withOmitTime exercises withOmitTime option to ensure it performs as expected. func TestOptions_withOmitTime(t *testing.T) { t.Parallel() tests := map[string]struct { Value bool ExpectedValue bool }{ "true": { Value: true, ExpectedValue: true, }, "false": { Value: false, ExpectedValue: false, }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts := &options{} applyOption := withOmitTime(tc.Value) err := applyOption(opts) require.NoError(t, err) require.Equal(t, tc.ExpectedValue, opts.withOmitTime) }) } } // TestOptions_Default exercises getDefaultOptions to assert the default values. func TestOptions_Default(t *testing.T) { t.Parallel() opts := getDefaultOptions() require.NotNil(t, opts) require.True(t, time.Now().After(opts.withNow)) require.False(t, opts.withNow.IsZero()) } // TestOptions_Opts exercises GetOpts with various option values. func TestOptions_Opts(t *testing.T) { t.Parallel() tests := map[string]struct { opts []option IsErrorExpected bool ExpectedErrorMessage string ExpectedID string ExpectedSubtype subtype ExpectedFormat format IsNowExpected bool ExpectedNow time.Time }{ "nil-options": { opts: nil, IsErrorExpected: false, IsNowExpected: true, ExpectedFormat: jsonFormat, }, "empty-options": { opts: []option{}, IsErrorExpected: false, IsNowExpected: true, ExpectedFormat: jsonFormat, }, "with-multiple-valid-id": { opts: []option{ withID("qwerty"), withID("juan"), }, IsErrorExpected: false, ExpectedID: "juan", IsNowExpected: true, ExpectedFormat: jsonFormat, }, "with-multiple-valid-subtype": { opts: []option{ withSubtype("AuditRequest"), withSubtype("AuditResponse"), }, IsErrorExpected: false, ExpectedSubtype: ResponseType, IsNowExpected: true, ExpectedFormat: jsonFormat, }, "with-multiple-valid-format": { opts: []option{ withFormat("json"), withFormat("jsonx"), }, IsErrorExpected: false, ExpectedFormat: jsonxFormat, IsNowExpected: true, }, "with-multiple-valid-now": { opts: []option{ withNow(time.Date(2023, time.July, 4, 12, 3, 0, 0, time.Local)), withNow(time.Date(2023, time.July, 4, 13, 3, 0, 0, time.Local)), }, IsErrorExpected: false, ExpectedNow: time.Date(2023, time.July, 4, 13, 3, 0, 0, time.Local), IsNowExpected: false, ExpectedFormat: jsonFormat, }, "with-multiple-valid-then-invalid-now": { opts: []option{ withNow(time.Date(2023, time.July, 4, 12, 3, 0, 0, time.Local)), withNow(time.Time{}), }, IsErrorExpected: true, ExpectedErrorMessage: "cannot specify 'now' to be the zero time instant", ExpectedFormat: jsonFormat, }, "with-multiple-valid-options": { opts: []option{ withID("qwerty"), withSubtype("AuditRequest"), withFormat("json"), withNow(time.Date(2023, time.July, 4, 12, 3, 0, 0, time.Local)), }, IsErrorExpected: false, ExpectedID: "qwerty", ExpectedSubtype: RequestType, ExpectedFormat: jsonFormat, ExpectedNow: time.Date(2023, time.July, 4, 12, 3, 0, 0, time.Local), }, } for name, tc := range tests { name := name tc := tc t.Run(name, func(t *testing.T) { t.Parallel() opts, err := getOpts(tc.opts...) switch { case tc.IsErrorExpected: require.Error(t, err) require.EqualError(t, err, tc.ExpectedErrorMessage) default: require.NotNil(t, opts) require.NoError(t, err) require.Equal(t, tc.ExpectedID, opts.withID) require.Equal(t, tc.ExpectedSubtype, opts.withSubtype) require.Equal(t, tc.ExpectedFormat, opts.withFormat) switch { case tc.IsNowExpected: require.True(t, time.Now().After(opts.withNow)) require.False(t, opts.withNow.IsZero()) default: require.Equal(t, tc.ExpectedNow, opts.withNow) } } }) } }
go
github
https://github.com/hashicorp/vault
audit/options_test.go
import pdb; import sys; import linecache def qdebug(options = None, expanded = None, typeformats = None, individualformats = None, watchers = None): class QDebug: def __init__(self, options = None, expanded = None, typeformats = None, individualformats = None, watchers = None): self.options = options self.expandedINames = expanded self.typeformats = typeformats self.individualformats = individualformats self.watchers = watchers self.buffer = "" if self.options == "listmodules": self.handleListModules() elif self.options == "listsymbols": self.handleListSymbols(expanded) else: self.handleListVars() def put(self, value): #sys.stdout.write(value) self.buffer += value def putField(self, name, value): self.put('%s="%s",' % (name, value)) def putItemCount(self, count): self.put('value="<%s items>",' % count) def putEllipsis(self): self.put('{name="<incomplete>",value="",type="",numchild="0"},') def cleanType(self, type): t = str(type) if t.startswith("<type '") and t.endswith("'>"): t = t[7:-2] if t.startswith("<class '") and t.endswith("'>"): t = t[8:-2] return t def putType(self, type, priority = 0): self.putField("type", self.cleanType(type)) def putAddress(self, addr): self.put('addr="%s",' % cleanAddress(addr)) def putNumChild(self, numchild): self.put('numchild="%s",' % numchild) def putValue(self, value, encoding = None, priority = 0): self.putField("value", value) def putName(self, name): self.put('name="%s",' % name) def isExpanded(self, iname): #self.warn("IS EXPANDED: %s in %s" % (iname, self.expandedINames)) if iname.startswith("None"): raise "Illegal iname '%s'" % iname #self.warn(" --> %s" % (iname in self.expandedINames)) return iname in self.expandedINames def isExpandedIName(self, iname): return iname in self.expandedINames def itemFormat(self, item): format = self.formats.get(str(cleanAddress(item.value.address))) if format is None: format = self.typeformats.get(stripClassTag(str(item.value.type))) return format def dumpFrame(self, frame): for var in frame.f_locals.keys(): if var == "__file__": continue #if var == "__name__": # continue if var == "__package__": continue if var == "qdebug": continue if var != '__builtins__': value = frame.f_locals[var] self.dumpValue(value, var, "local.%s" % var) def dumpValue(self, value, name, iname): t = type(value) tt = self.cleanType(t) if tt == "module" or tt == "function": return if str(value).startswith("<class '"): return # FIXME: Should we? if str(value).startswith("<enum-item "): return self.put("{") self.putField("iname", iname) self.putName(name) self.putType(tt) if tt == "NoneType": self.putValue("None") self.putNumChild(0) elif tt == "list" or tt == "tuple": self.putItemCount(len(value)) #self.putValue(value) self.put("children=[") for i in xrange(len(value)): self.dumpValue(value[i], str(i), "%s.%d" % (iname, i)) self.put("]") elif tt == "str": v = value self.putValue(v.encode('hex')) self.putField("valueencoded", 6) self.putNumChild(0) elif tt == "unicode": v = value self.putValue(v.encode('hex')) self.putField("valueencoded", 6) self.putNumChild(0) elif tt == "buffer": v = str(value) self.putValue(v.encode('hex')) self.putField("valueencoded", 6) self.putNumChild(0) elif tt == "xrange": b = iter(value).next() e = b + len(value) self.putValue("(%d, %d)" % (b, e)) self.putNumChild(0) elif tt == "dict": self.putItemCount(len(value)) self.putField("childnumchild", 2) self.put("children=[") i = 0 for (k, v) in value.iteritems(): self.put("{") self.putType(" ") self.putValue("%s: %s" % (k, v)) if self.isExpanded(iname): self.put("children=[") self.dumpValue(k, "key", "%s.%d.k" % (iname, i)) self.dumpValue(v, "value", "%s.%d.v" % (iname, i)) self.put("]") self.put("},") i += 1 self.put("]") elif tt == "class": pass elif tt == "module": pass elif tt == "function": pass elif str(value).startswith("<enum-item "): # FIXME: Having enums always shown like this is not nice. self.putValue(str(value)[11:-1]) self.putNumChild(0) else: v = str(value) p = v.find(" object at ") if p > 1: v = "@" + v[p + 11:-1] self.putValue(v) if self.isExpanded(iname): self.put("children=[") for child in dir(value): if child == "__dict__": continue if child == "__doc__": continue if child == "__module__": continue attr = getattr(value, child) if callable(attr): continue try: self.dumpValue(attr, child, "%s.%s" % (iname, child)) except: pass self.put("],") self.put("},") def warn(self, msg): self.putField("warning", msg) def handleListVars(self): # Trigger error to get a backtrace. frame = None #self.warn("frame: %s" % frame) try: raise ZeroDivisionError except ZeroDivisionError: frame = sys.exc_info()[2].tb_frame.f_back limit = 30 n = 0 isActive = False while frame is not None and n < limit: #self.warn("frame: %s" % frame.f_locals.keys()) lineno = frame.f_lineno code = frame.f_code filename = code.co_filename name = code.co_name if isActive: linecache.checkcache(filename) line = linecache.getline(filename, lineno, frame.f_globals) self.dumpFrame(frame) if name == "<module>": isActive = False if name == "trace_dispatch": isActive = True frame = frame.f_back n = n + 1 #sys.stdout.flush() def handleListModules(self): self.put("modules=["); for name in sys.modules: self.put("{") self.putName(name) self.putValue(sys.modules[name]) self.put("},") self.put("]") #sys.stdout.flush() def handleListSymbols(self, module): #self.put("symbols=%s" % dir(sys.modules[module])) self.put("symbols=["); for name in sys.modules: self.put("{") self.putName(name) #self.putValue(sys.modules[name]) self.put("},") self.put("]") #sys.stdout.flush() d = QDebug(options, expanded, typeformats, individualformats, watchers) #print d.buffer sys.stdout.write(d.buffer) sys.stdout.flush()
unknown
codeparrot/codeparrot-clean
from tastypie.resources import ModelResource from apps.survey.models import Profile, SurveyUser, Survey from apps.survey.survey import parse_specification from apps.survey.spec import Question, Branch, Else from pickle import loads from inspect import isclass class EpiwebModelResource(ModelResource): class Meta: default_format = 'application/json' include_resource_uri = False allowed_methods = ['get'] def xmlify_spec(spec): p = parse_specification(spec) def a(s): return str(s) def t(tag, s): return a('<%s>\n' % tag) + a(s) + a('</%s>\n' % tag) def xo(options): return reduce(lambda s,o: s+t('option', t('code', o[0]) + t('text', o[1])) , options, '') def xs(f): if not f: return '' if isinstance(f, str): return f + '\n' if isinstance(f, list) or isinstance(f, tuple): return xs(f[0]) + xs(f[1:]) elif isinstance(f, Else): return t('else', f.rules) elif isinstance(f, Branch): # Process condition here!!! return t('branch', t('condition', f.condition) + t('rules', f.rules)) elif isclass(f) and issubclass(f, Question): x = t('type', f.type) x += t('question', f.question) if 'options' in dir(f): x += xo(f.options) return t('item', x) else: t('unknown', type(f)) xml = t('survey', xs(p.rules)) return xml ## EIP resources class GetUserProfile(EpiwebModelResource): """Takes global_id Returns name, a_uids, code, report_ts """ class Meta: resource_name = 'GetUserProfile' queryset = Profile.objects.all() # queryset = Profile.objects.filter(user__global_id="193807d8-4a30-4601-9bc5-bc59db1696cd") filtering = ['user__global_id'] # fields = ['data'] def dehydrate(self, bundle): id = bundle.data['id'] return loads(str(bundle.data['data'])) class GetReportSurvey(ModelResource): """Takes language int Returns survey in XML format """ class Meta: resource_name = 'GetReportSurvey' queryset = Survey.objects.all() fields = ['specification'] def dehydrate(self, bundle): spec = bundle.data['specification'] xml = xmlify_spec(spec) return xml # return str(parse_specification(bundle.data['specification'])) class Report(ModelResource): """Takes uid and reportS Returns status """ class Meta: queryset = SurveyUser.objects.all() allowed_methods = ['put']
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- """ flask.debughelpers ~~~~~~~~~~~~~~~~~~ Various helpers to make the development experience better. 1 :copyright: (c) 2014 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from ._compat import implements_to_string class UnexpectedUnicodeError(AssertionError, UnicodeError): """Raised in places where we want some better error reporting for unexpected unicode or binary data. """ @implements_to_string class DebugFilesKeyError(KeyError, AssertionError): """Raised from request.files during debugging. The idea is that it can provide a better error message than just a generic KeyError/BadRequest. """ def __init__(self, request, key): form_matches = request.form.getlist(key) buf = ['You tried to access the file "%s" in the request.files ' 'dictionary but it does not exist. The mimetype for the request ' 'is "%s" instead of "multipart/form-data" which means that no ' 'file contents were transmitted. To fix this error you should ' 'provide enctype="multipart/form-data" in your form.' % (key, request.mimetype)] if form_matches: buf.append('\n\nThe browser instead transmitted some file names. ' 'This was submitted: %s' % ', '.join('"%s"' % x for x in form_matches)) self.msg = ''.join(buf) def __str__(self): return self.msg class FormDataRoutingRedirect(AssertionError): """This exception is raised by Flask in debug mode if it detects a redirect caused by the routing system when the request method is not GET, HEAD or OPTIONS. Reasoning: form data will be dropped. """ def __init__(self, request): exc = request.routing_exception buf = ['A request was sent to this URL (%s) but a redirect was ' 'issued automatically by the routing system to "%s".' % (request.url, exc.new_url)] # In case just a slash was appended we can be extra helpful if request.base_url + '/' == exc.new_url.split('?')[0]: buf.append(' The URL was defined with a trailing slash so ' 'Flask will automatically redirect to the URL ' 'with the trailing slash if it was accessed ' 'without one.') buf.append(' Make sure to directly send your %s-request to this URL ' 'since we can\'t make browsers or HTTP clients redirect ' 'with form data reliably or without user interaction.' % request.method) buf.append('\n\nNote: this exception is only raised in debug mode') AssertionError.__init__(self, ''.join(buf).encode('utf-8')) def attach_enctype_error_multidict(request): """Since Flask 0.8 we're monkeypatching the files object in case a request is detected that does not use multipart form data but the files object is accessed. """ oldcls = request.files.__class__ class newcls(oldcls): def __getitem__(self, key): try: return oldcls.__getitem__(self, key) except KeyError: if key not in request.form: raise raise DebugFilesKeyError(request, key) newcls.__name__ = oldcls.__name__ newcls.__module__ = oldcls.__module__ request.files.__class__ = newcls
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python """ @package ion.agents.platform.rsn.simulator.oms_simulator_server @file ion/agents/platform/rsn/simulator/oms_simulator_server.py @author Carlos Rueda @brief OMS simulator XML/RPC server. Program intended to be run outside of pyon. USAGE: $ bin/python ion/agents/platform/rsn/simulator/oms_simulator_server.py ... 2012-09-27 21:15:51,335 INFO MainThread oms_simulator :107 <module> Listening on localhost:7700 2012-09-27 21:15:51,335 INFO MainThread oms_simulator :108 <module> Enter ^D to exit """ import os __author__ = 'Carlos Rueda' __license__ = 'Apache 2.0' import sys sys.path.append('.') from mi.platform.rsn.simulator.logger import Logger log = Logger.get_logger() import logging from mi.platform.rsn.simulator.oms_simulator import CIOMSSimulator from mi.platform.util.network_util import NetworkUtil from SimpleXMLRPCServer import SimpleXMLRPCServer from threading import Thread import time class CIOMSSimulatorWithExit(CIOMSSimulator): """ Adds some special methods for coordination from integration tests: x_exit_simulator: to exit the simulator process. x_exit_inactivity: to make the simulator shutdown itself after a period of inactivity. """ def __init__(self, oss): """ @param oss CIOMSSimulatorServer """ CIOMSSimulator.__init__(self) self._oss = oss # for inactivity checking self._last_activity = time.time() self._inactivity_period = None def x_exit_simulator(self): log.info("x_exit_simulator called. event_generator=%s; %s listeners registered", self._event_generator, len(self._reg_event_listeners)) if self._event_generator: self._event_generator.stop() self._event_generator = None def call_exit(): self._oss.shutdown_server() time.sleep(4) quit() Thread(target=call_exit).start() return "Will exit in a couple of secs" def x_exit_inactivity(self, inactivity_period): if self._inactivity_period is None: # first call. self._inactivity_period = inactivity_period check_idle = Thread(target=self._check_inactivity) check_idle.setDaemon(True) check_idle.start() log.info("started check_inactivity thread: inactivity_period=%.1f", inactivity_period) else: self._inactivity_period = inactivity_period log.info("updated inactivity_period=%.1f", inactivity_period) def _enter(self): self._last_activity = time.time() super(CIOMSSimulatorWithExit, self)._enter() def _check_inactivity(self): ip = self._inactivity_period warn_per = 30 if ip >= 60 else 10 if ip >= 30 else 5 while self._oss._running: inactive = time.time() - self._last_activity if inactive >= self._inactivity_period: log.warn("%.1f secs of inactivity. Exiting...", inactive) self._oss.shutdown_server() quit() elif inactive >= warn_per and int(inactive) % warn_per == 0: log.warn("%.1f secs of inactivity", inactive) time.sleep(0.5) class CIOMSSimulatorServer(object): """ Dispatches an CIOMSSimulator with a SimpleXMLRPCServer. Intended to be run outside of pyon. """ def __init__(self, host, port, inactivity_period=None): """ Creates a SimpleXMLRPCServer and starts a Thread where serve_forever is called on the server. @param host Hostname for the service @param port Port for the service """ self._running = True self._sim = CIOMSSimulatorWithExit(self) if log.isEnabledFor(logging.DEBUG): ser = NetworkUtil.serialize_network_definition(self._sim._ndef) log.debug("network serialization:\n %s" % ser.replace('\n', '\n ')) log.debug("network.get_map() = %s\n" % self._sim.config.get_platform_map()) self._server = SimpleXMLRPCServer((host, port), allow_none=True) actual_port = self._server.socket.getsockname()[1] uri = "http://%s:%s/" % (host, actual_port) # write the URI to a file for launching process to see it: with open("logs/rsn_oms_simulator.yml", 'w') as f: f.write("rsn_oms_simulator_uri=%s\n" % uri) self._server.register_introspection_functions() self._server.register_instance(self._sim, allow_dotted_names=True) log.info("Methods:\n\t%s", "\n\t".join(self._server.system_listMethods())) self._check_pyon() runnable = Thread(target=self._server.serve_forever) runnable.setDaemon(True) runnable.start() log.info("OMS simulator xmlrpc server listening on %s" % uri) if inactivity_period: self._sim.x_exit_inactivity(inactivity_period) def shutdown_server(self): self._running = False if self._sim: log.info("RSN OMS simulator exiting...") self._sim = None self._server.shutdown() self._server = None def wait_until_shutdown(self): while self._running: time.sleep(1) self.shutdown_server() @staticmethod def _check_pyon(): """ Prints a warning message if pyon is detected. """ if 'pyon' in sys.modules: m = "!! WARNING: pyon in sys.modules !!" s = "!" * len(m) sys.stderr.write("\n%s\n%s\n%s\n\n" % (s, m, s)) # Main program if __name__ == "__main__": # pragma: no cover DEFAULT_HOST = 'localhost' DEFAULT_PORT = 7700 import argparse import signal parser = argparse.ArgumentParser(description="OMS Simulator server") parser.add_argument("-H", "--host", help="host (default: %s)" % DEFAULT_HOST, default=DEFAULT_HOST) parser.add_argument("-P", "--port", help="port (default: %s)" % DEFAULT_PORT, default=DEFAULT_PORT) parser.add_argument("-i", "--inactivity", help="inactivity period check in secs (no check by default)") opts = parser.parse_args() host = opts.host port = int(opts.port) inactivity_period = int(opts.inactivity) if opts.inactivity else None oss = CIOMSSimulatorServer(host, port, inactivity_period) def handler(signum, frame): log.info("\n--SIGINT--") oss.shutdown_server() quit() signal.signal(signal.SIGINT, handler) oss.wait_until_shutdown()
unknown
codeparrot/codeparrot-clean
import { Comment, type VNode, type VNodeProps, closeBlock, createVNode, currentBlock, isBlockTreeEnabled, isSameVNodeType, normalizeVNode, openBlock, } from '../vnode' import { ShapeFlags, isArray, isFunction, toNumber } from '@vue/shared' import { type ComponentInternalInstance, handleSetupResult } from '../component' import type { Slots } from '../componentSlots' import { type ElementNamespace, MoveType, type RendererElement, type RendererInternals, type RendererNode, type SetupRenderEffectFn, queuePostRenderEffect, } from '../renderer' import { queuePostFlushCb } from '../scheduler' import { filterSingleRoot, updateHOCHostEl } from '../componentRenderUtils' import { assertNumber, popWarningContext, pushWarningContext, warn, } from '../warning' import { ErrorCodes, handleError } from '../errorHandling' import { NULL_DYNAMIC_COMPONENT } from '../helpers/resolveAssets' export interface SuspenseProps { onResolve?: () => void onPending?: () => void onFallback?: () => void timeout?: string | number /** * Allow suspense to be captured by parent suspense * * @default false */ suspensible?: boolean } export const isSuspense = (type: any): boolean => type.__isSuspense // incrementing unique id for every pending branch let suspenseId = 0 /** * For testing only */ export const resetSuspenseId = (): number => (suspenseId = 0) // Suspense exposes a component-like API, and is treated like a component // in the compiler, but internally it's a special built-in type that hooks // directly into the renderer. export const SuspenseImpl = { name: 'Suspense', // In order to make Suspense tree-shakable, we need to avoid importing it // directly in the renderer. The renderer checks for the __isSuspense flag // on a vnode's type and calls the `process` method, passing in renderer // internals. __isSuspense: true, process( n1: VNode | null, n2: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, // platform-specific impl passed from renderer rendererInternals: RendererInternals, ): void { if (n1 == null) { mountSuspense( n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, rendererInternals, ) } else { // #8678 if the current suspense needs to be patched and parentSuspense has // not been resolved. this means that both the current suspense and parentSuspense // need to be patched. because parentSuspense's pendingBranch includes the // current suspense, it will be processed twice: // 1. current patch // 2. mounting along with the pendingBranch of parentSuspense // it is necessary to skip the current patch to avoid multiple mounts // of inner components. if ( parentSuspense && parentSuspense.deps > 0 && !n1.suspense!.isInFallback ) { n2.suspense = n1.suspense! n2.suspense.vnode = n2 n2.el = n1.el return } patchSuspense( n1, n2, container, anchor, parentComponent, namespace, slotScopeIds, optimized, rendererInternals, ) } }, hydrate: hydrateSuspense as typeof hydrateSuspense, normalize: normalizeSuspenseChildren as typeof normalizeSuspenseChildren, } // Force-casted public typing for h and TSX props inference export const Suspense = (__FEATURE_SUSPENSE__ ? SuspenseImpl : null) as unknown as { __isSuspense: true new (): { $props: VNodeProps & SuspenseProps $slots: { default(): VNode[] fallback(): VNode[] } } } function triggerEvent( vnode: VNode, name: 'onResolve' | 'onPending' | 'onFallback', ) { const eventListener = vnode.props && vnode.props[name] if (isFunction(eventListener)) { eventListener() } } function mountSuspense( vnode: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, rendererInternals: RendererInternals, ) { const { p: patch, o: { createElement }, } = rendererInternals const hiddenContainer = createElement('div') const suspense = (vnode.suspense = createSuspenseBoundary( vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, namespace, slotScopeIds, optimized, rendererInternals, )) // start mounting the content subtree in an off-dom container patch( null, (suspense.pendingBranch = vnode.ssContent!), hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds, ) // now check if we have encountered any async deps if (suspense.deps > 0) { // has async // invoke @fallback event triggerEvent(vnode, 'onPending') triggerEvent(vnode, 'onFallback') // mount the fallback tree patch( null, vnode.ssFallback!, container, anchor, parentComponent, null, // fallback tree will not have suspense context namespace, slotScopeIds, ) setActiveBranch(suspense, vnode.ssFallback!) } else { // Suspense has no async deps. Just resolve. suspense.resolve(false, true) } } function patchSuspense( n1: VNode, n2: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, { p: patch, um: unmount, o: { createElement } }: RendererInternals, ) { const suspense = (n2.suspense = n1.suspense)! suspense.vnode = n2 n2.el = n1.el const newBranch = n2.ssContent! const newFallback = n2.ssFallback! const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense if (pendingBranch) { suspense.pendingBranch = newBranch if (isSameVNodeType(pendingBranch, newBranch)) { // same root type but content may have changed. patch( pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds, optimized, ) if (suspense.deps <= 0) { suspense.resolve() } else if (isInFallback) { // It's possible that the app is in hydrating state when patching the // suspense instance. If someone updates the dependency during component // setup in children of suspense boundary, that would be problemtic // because we aren't actually showing a fallback content when // patchSuspense is called. In such case, patch of fallback content // should be no op if (!isHydrating) { patch( activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context namespace, slotScopeIds, optimized, ) setActiveBranch(suspense, newFallback) } } } else { // toggled before pending tree is resolved // increment pending ID. this is used to invalidate async callbacks suspense.pendingId = suspenseId++ if (isHydrating) { // if toggled before hydration is finished, the current DOM tree is // no longer valid. set it as the active branch so it will be unmounted // when resolved suspense.isHydrating = false suspense.activeBranch = pendingBranch } else { unmount(pendingBranch, parentComponent, suspense) } // reset suspense state suspense.deps = 0 // discard effects from pending branch suspense.effects.length = 0 // discard previous container suspense.hiddenContainer = createElement('div') if (isInFallback) { // already in fallback state patch( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds, optimized, ) if (suspense.deps <= 0) { suspense.resolve() } else { patch( activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context namespace, slotScopeIds, optimized, ) setActiveBranch(suspense, newFallback) } } else if (activeBranch && isSameVNodeType(activeBranch, newBranch)) { // toggled "back" to current active branch patch( activeBranch, newBranch, container, anchor, parentComponent, suspense, namespace, slotScopeIds, optimized, ) // force resolve suspense.resolve(true) } else { // switched to a 3rd branch patch( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds, optimized, ) if (suspense.deps <= 0) { suspense.resolve() } } } } else { if (activeBranch && isSameVNodeType(activeBranch, newBranch)) { // root did not change, just normal patch patch( activeBranch, newBranch, container, anchor, parentComponent, suspense, namespace, slotScopeIds, optimized, ) setActiveBranch(suspense, newBranch) } else { // root node toggled // invoke @pending event triggerEvent(n2, 'onPending') // mount pending branch in off-dom container suspense.pendingBranch = newBranch if (newBranch.shapeFlag & ShapeFlags.COMPONENT_KEPT_ALIVE) { suspense.pendingId = newBranch.component!.suspenseId! } else { suspense.pendingId = suspenseId++ } patch( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, namespace, slotScopeIds, optimized, ) if (suspense.deps <= 0) { // incoming branch has no async deps, resolve now. suspense.resolve() } else { const { timeout, pendingId } = suspense if (timeout > 0) { setTimeout(() => { if (suspense.pendingId === pendingId) { suspense.fallback(newFallback) } }, timeout) } else if (timeout === 0) { suspense.fallback(newFallback) } } } } } export interface SuspenseBoundary { vnode: VNode<RendererNode, RendererElement, SuspenseProps> parent: SuspenseBoundary | null parentComponent: ComponentInternalInstance | null namespace: ElementNamespace container: RendererElement hiddenContainer: RendererElement activeBranch: VNode | null pendingBranch: VNode | null deps: number pendingId: number timeout: number isInFallback: boolean isHydrating: boolean isUnmounted: boolean effects: Function[] resolve(force?: boolean, sync?: boolean): void fallback(fallbackVNode: VNode): void move( container: RendererElement, anchor: RendererNode | null, type: MoveType, ): void next(): RendererNode | null registerDep( instance: ComponentInternalInstance, setupRenderEffect: SetupRenderEffectFn, optimized: boolean, ): void unmount(parentSuspense: SuspenseBoundary | null, doRemove?: boolean): void } let hasWarned = false function createSuspenseBoundary( vnode: VNode, parentSuspense: SuspenseBoundary | null, parentComponent: ComponentInternalInstance | null, container: RendererElement, hiddenContainer: RendererElement, anchor: RendererNode | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, rendererInternals: RendererInternals, isHydrating = false, ): SuspenseBoundary { /* v8 ignore start */ if (__DEV__ && !__TEST__ && !hasWarned) { hasWarned = true // @ts-expect-error `console.info` cannot be null error // eslint-disable-next-line no-console console[console.info ? 'info' : 'log']( `<Suspense> is an experimental feature and its API will likely change.`, ) } /* v8 ignore stop */ const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove }, } = rendererInternals // if set `suspensible: true`, set the current suspense as a dep of parent suspense let parentSuspenseId: number | undefined const isSuspensible = isVNodeSuspensible(vnode) if (isSuspensible) { if (parentSuspense && parentSuspense.pendingBranch) { parentSuspenseId = parentSuspense.pendingId parentSuspense.deps++ } } const timeout = vnode.props ? toNumber(vnode.props.timeout) : undefined if (__DEV__) { assertNumber(timeout, `Suspense timeout`) } const initialAnchor = anchor const suspense: SuspenseBoundary = { vnode, parent: parentSuspense, parentComponent, namespace, container, hiddenContainer, deps: 0, pendingId: suspenseId++, timeout: typeof timeout === 'number' ? timeout : -1, activeBranch: null, pendingBranch: null, isInFallback: !isHydrating, isHydrating, isUnmounted: false, effects: [], resolve(resume = false, sync = false) { if (__DEV__) { if (!resume && !suspense.pendingBranch) { throw new Error( `suspense.resolve() is called without a pending branch.`, ) } if (suspense.isUnmounted) { throw new Error( `suspense.resolve() is called on an already unmounted suspense boundary.`, ) } } const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container, isInFallback, } = suspense // if there's a transition happening we need to wait it to finish. let delayEnter: boolean | null = false if (suspense.isHydrating) { suspense.isHydrating = false } else if (!resume) { delayEnter = activeBranch && pendingBranch!.transition && pendingBranch!.transition.mode === 'out-in' if (delayEnter) { activeBranch!.transition!.afterLeave = () => { if (pendingId === suspense.pendingId) { move( pendingBranch!, container, anchor === initialAnchor ? next(activeBranch!) : anchor, MoveType.ENTER, ) queuePostFlushCb(effects) // clear el reference from fallback vnode to allow GC after transition if (isInFallback && vnode.ssFallback) { vnode.ssFallback.el = null } } } } // unmount current active tree if (activeBranch) { // if the fallback tree was mounted, it may have been moved // as part of a parent suspense. get the latest anchor for insertion // #8105 if `delayEnter` is true, it means that the mounting of // `activeBranch` will be delayed. if the branch switches before // transition completes, both `activeBranch` and `pendingBranch` may // coexist in the `hiddenContainer`. This could result in // `next(activeBranch!)` obtaining an incorrect anchor // (got `pendingBranch.el`). // Therefore, after the mounting of activeBranch is completed, // it is necessary to get the latest anchor. if (parentNode(activeBranch.el!) === container) { anchor = next(activeBranch) } unmount(activeBranch, parentComponent, suspense, true) // clear el reference from fallback vnode to allow GC if (!delayEnter && isInFallback && vnode.ssFallback) { queuePostRenderEffect(() => (vnode.ssFallback!.el = null), suspense) } } if (!delayEnter) { // move content from off-dom container to actual container move(pendingBranch!, container, anchor, MoveType.ENTER) } } setActiveBranch(suspense, pendingBranch!) suspense.pendingBranch = null suspense.isInFallback = false // flush buffered effects // check if there is a pending parent suspense let parent = suspense.parent let hasUnresolvedAncestor = false while (parent) { if (parent.pendingBranch) { // found a pending parent suspense, merge buffered post jobs // into that parent parent.effects.push(...effects) hasUnresolvedAncestor = true break } parent = parent.parent } // no pending parent suspense nor transition, flush all jobs if (!hasUnresolvedAncestor && !delayEnter) { queuePostFlushCb(effects) } suspense.effects = [] // resolve parent suspense if all async deps are resolved if (isSuspensible) { if ( parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId ) { parentSuspense.deps-- if (parentSuspense.deps === 0 && !sync) { parentSuspense.resolve() } } } // invoke @resolve event triggerEvent(vnode, 'onResolve') }, fallback(fallbackVNode) { if (!suspense.pendingBranch) { return } const { vnode, activeBranch, parentComponent, container, namespace } = suspense // invoke @fallback event triggerEvent(vnode, 'onFallback') const anchor = next(activeBranch!) const mountFallback = () => { if (!suspense.isInFallback) { return } // mount the fallback tree patch( null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context namespace, slotScopeIds, optimized, ) setActiveBranch(suspense, fallbackVNode) } const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in' if (delayEnter) { activeBranch!.transition!.afterLeave = mountFallback } suspense.isInFallback = true // unmount current active branch unmount( activeBranch!, parentComponent, null, // no suspense so unmount hooks fire now true, // shouldRemove ) if (!delayEnter) { mountFallback() } }, move(container, anchor, type) { suspense.activeBranch && move(suspense.activeBranch, container, anchor, type) suspense.container = container }, next() { return suspense.activeBranch && next(suspense.activeBranch) }, registerDep(instance, setupRenderEffect, optimized) { const isInPendingSuspense = !!suspense.pendingBranch if (isInPendingSuspense) { suspense.deps++ } const hydratedEl = instance.vnode.el instance .asyncDep!.catch(err => { handleError(err, instance, ErrorCodes.SETUP_FUNCTION) }) .then(asyncSetupResult => { // retry when the setup() promise resolves. // component may have been unmounted before resolve. if ( instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId ) { return } // retry from this component instance.asyncResolved = true const { vnode } = instance if (__DEV__) { pushWarningContext(vnode) } handleSetupResult(instance, asyncSetupResult, false) if (hydratedEl) { // vnode may have been replaced if an update happened before the // async dep is resolved. vnode.el = hydratedEl } const placeholder = !hydratedEl && instance.subTree.el setupRenderEffect( instance, vnode, // component may have been moved before resolve. // if this is not a hydration, instance.subTree will be the comment // placeholder. parentNode(hydratedEl || instance.subTree.el!)!, // anchor will not be used if this is hydration, so only need to // consider the comment placeholder case. hydratedEl ? null : next(instance.subTree), suspense, namespace, optimized, ) if (placeholder) { // clean up placeholder reference vnode.placeholder = null remove(placeholder) } updateHOCHostEl(instance, vnode.el) if (__DEV__) { popWarningContext() } // only decrease deps count if suspense is not already resolved if (isInPendingSuspense && --suspense.deps === 0) { suspense.resolve() } }) }, unmount(parentSuspense, doRemove) { suspense.isUnmounted = true if (suspense.activeBranch) { unmount( suspense.activeBranch, parentComponent, parentSuspense, doRemove, ) } if (suspense.pendingBranch) { unmount( suspense.pendingBranch, parentComponent, parentSuspense, doRemove, ) } }, } return suspense } function hydrateSuspense( node: Node, vnode: VNode, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, rendererInternals: RendererInternals, hydrateNode: ( node: Node, vnode: VNode, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, slotScopeIds: string[] | null, optimized: boolean, ) => Node | null, ): Node | null { const suspense = (vnode.suspense = createSuspenseBoundary( vnode, parentSuspense, parentComponent, node.parentNode!, // eslint-disable-next-line no-restricted-globals document.createElement('div'), null, namespace, slotScopeIds, optimized, rendererInternals, true /* hydrating */, )) // there are two possible scenarios for server-rendered suspense: // - success: ssr content should be fully resolved // - failure: ssr content should be the fallback branch. // however, on the client we don't really know if it has failed or not // attempt to hydrate the DOM assuming it has succeeded, but we still // need to construct a suspense boundary first const result = hydrateNode( node, (suspense.pendingBranch = vnode.ssContent!), parentComponent, suspense, slotScopeIds, optimized, ) if (suspense.deps === 0) { suspense.resolve(false, true) } return result } function normalizeSuspenseChildren(vnode: VNode): void { const { shapeFlag, children } = vnode const isSlotChildren = shapeFlag & ShapeFlags.SLOTS_CHILDREN vnode.ssContent = normalizeSuspenseSlot( isSlotChildren ? (children as Slots).default : children, ) vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot((children as Slots).fallback) : createVNode(Comment) } function normalizeSuspenseSlot(s: any) { let block: VNode[] | null | undefined if (isFunction(s)) { const trackBlock = isBlockTreeEnabled && s._c if (trackBlock) { // disableTracking: false // allow block tracking for compiled slots // (see ./componentRenderContext.ts) s._d = false openBlock() } s = s() if (trackBlock) { s._d = true block = currentBlock closeBlock() } } if (isArray(s)) { const singleChild = filterSingleRoot(s) if ( __DEV__ && !singleChild && s.filter(child => child !== NULL_DYNAMIC_COMPONENT).length > 0 ) { warn(`<Suspense> slots expect a single root node.`) } s = singleChild } s = normalizeVNode(s) if (block && !s.dynamicChildren) { s.dynamicChildren = block.filter(c => c !== s) } return s } export function queueEffectWithSuspense( fn: Function | Function[], suspense: SuspenseBoundary | null, ): void { if (suspense && suspense.pendingBranch) { if (isArray(fn)) { suspense.effects.push(...fn) } else { suspense.effects.push(fn) } } else { queuePostFlushCb(fn) } } function setActiveBranch(suspense: SuspenseBoundary, branch: VNode) { suspense.activeBranch = branch const { vnode, parentComponent } = suspense let el = branch.el // if branch has no el after patch, it's a HOC wrapping async components // drill and locate the placeholder comment node while (!el && branch.component) { branch = branch.component.subTree el = branch.el } vnode.el = el // in case suspense is the root node of a component, // recursively update the HOC el if (parentComponent && parentComponent.subTree === vnode) { parentComponent.vnode.el = el updateHOCHostEl(parentComponent, el) } } function isVNodeSuspensible(vnode: VNode) { const suspensible = vnode.props && vnode.props.suspensible return suspensible != null && suspensible !== false }
typescript
github
https://github.com/vuejs/core
packages/runtime-core/src/components/Suspense.ts
# -*- coding: utf-8 -*- # # gPodder - A media aggregator and podcast client # Copyright (c) 2005-2010 Thomas Perl and the gPodder Team # # gPodder 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. # # gPodder 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 gtk import gpodder _ = gpodder.gettext N_ = gpodder.ngettext from gpodder import util from gpodder.gtkui.interface.common import BuilderWidget from gpodder.gtkui.interface.common import Orientation from gpodder.gtkui.frmntl.portrait import FremantleRotation import hildon class gPodderPreferences(BuilderWidget): UPDATE_INTERVALS = ( (0, _('manually')), (20, N_('every %d minute', 'every %d minutes', 20) % 20), (60, _('hourly')), (60*6, N_('every %d hour', 'every %d hours', 6) % 6), (60*24, _('daily')), ) DOWNLOAD_METHODS = ( ('never', _('Show episode list')), ('queue', _('Add to download list')), # ('wifi', _('Download when on Wi-Fi')), ('always', _('Download immediately')), ) AUDIO_PLAYERS = ( ('default', _('Media Player')), ('panucci', _('Panucci')), ) VIDEO_PLAYERS = ( ('default', _('Media Player')), ('mplayer', _('MPlayer')), ) def new(self): self.main_window.connect('destroy', lambda w, self: self.callback_finished(), self) self.wiki_button = self.main_window.add_button(_('User manual'), 1) self.wiki_button.connect('clicked', self.on_wiki_activate) self.about_button = self.main_window.add_button(_('About'), 2) self.about_button.connect('clicked', self.on_itemAbout_activate) self.touch_selector_orientation = hildon.TouchSelector(text=True) for caption in FremantleRotation.MODE_CAPTIONS: self.touch_selector_orientation.append_text(caption) self.touch_selector_orientation.set_active(0, self._config.rotation_mode) self.picker_orientation.set_selector(self.touch_selector_orientation) if not self._config.auto_update_feeds: self._config.auto_update_frequency = 0 # Create a mapping from minute values to touch selector indices minute_index_mapping = dict((b, a) for a, b in enumerate(x[0] for x in self.UPDATE_INTERVALS)) self.touch_selector_interval = hildon.TouchSelector(text=True) for value, caption in self.UPDATE_INTERVALS: self.touch_selector_interval.append_text(caption) interval = self._config.auto_update_frequency if interval in minute_index_mapping: self._custom_interval = 0 self.touch_selector_interval.set_active(0, minute_index_mapping[interval]) else: self._custom_interval = self._config.auto_update_frequency self.touch_selector_interval.append_text(_('every %d minutes') % interval) self.touch_selector_interval.set_active(0, len(self.UPDATE_INTERVALS)) self.picker_interval.set_selector(self.touch_selector_interval) # Create a mapping from download methods to touch selector indices download_method_mapping = dict((b, a) for a, b in enumerate(x[0] for x in self.DOWNLOAD_METHODS)) self.touch_selector_download = hildon.TouchSelector(text=True) for value, caption in self.DOWNLOAD_METHODS: self.touch_selector_download.append_text(caption) if self._config.auto_download not in (x[0] for x in self.DOWNLOAD_METHODS): self._config.auto_download = self.DOWNLOAD_METHODS[0][0] self.touch_selector_download.set_active(0, download_method_mapping[self._config.auto_download]) self.picker_download.set_selector(self.touch_selector_download) # Create a mapping from audio players to touch selector indices audio_player_mapping = dict((b, a) for a, b in enumerate(x[0] for x in self.AUDIO_PLAYERS)) self.touch_selector_audio_player = hildon.TouchSelector(text=True) for value, caption in self.AUDIO_PLAYERS: self.touch_selector_audio_player.append_text(caption) if self._config.player not in (x[0] for x in self.AUDIO_PLAYERS): self._config.player = self.AUDIO_PLAYERS[0][0] self.touch_selector_audio_player.set_active(0, audio_player_mapping[self._config.player]) self.picker_audio_player.set_selector(self.touch_selector_audio_player) # Create a mapping from video players to touch selector indices video_player_mapping = dict((b, a) for a, b in enumerate(x[0] for x in self.VIDEO_PLAYERS)) self.touch_selector_video_player = hildon.TouchSelector(text=True) for value, caption in self.VIDEO_PLAYERS: self.touch_selector_video_player.append_text(caption) if self._config.videoplayer not in (x[0] for x in self.VIDEO_PLAYERS): self._config.videoplayer = self.VIDEO_PLAYERS[0][0] self.touch_selector_video_player.set_active(0, video_player_mapping[self._config.videoplayer]) self.picker_video_player.set_selector(self.touch_selector_video_player) self.update_button_mygpo() # Fix the styling and layout of the picker buttons for button in (self.picker_orientation, \ self.picker_interval, \ self.picker_download, \ self.picker_audio_player, \ self.picker_video_player, \ self.button_mygpo): # Work around Maemo bug #4718 button.set_name('HildonButton-finger') # Fix alignment problems (Maemo bug #6205) button.set_alignment(.0, .5, 1., 0.) child = button.get_child() child.set_padding(0, 0, 12, 0) self.check_feed_update_skipping = hildon.CheckButton(gtk.HILDON_SIZE_FINGER_HEIGHT) self.check_feed_update_skipping.set_label(_('Enable feed update heuristics')) self._config.connect_gtk_togglebutton('feed_update_skipping', self.check_feed_update_skipping) self.pannable_vbox.add(self.check_feed_update_skipping) self.pannable_vbox.reorder_child(self.check_feed_update_skipping, 6) self.check_view_all_episodes = hildon.CheckButton(gtk.HILDON_SIZE_FINGER_HEIGHT) self.check_view_all_episodes.set_label(_('Show "All episodes" view')) self._config.connect_gtk_togglebutton('podcast_list_view_all', self.check_view_all_episodes) self.pannable_vbox.add(self.check_view_all_episodes) self.pannable_vbox.reorder_child(self.check_view_all_episodes, 2) self.gPodderPreferences.show_all() def on_window_orientation_changed(self, orientation): if orientation == Orientation.PORTRAIT: self.wiki_button.hide() self.about_button.hide() else: self.wiki_button.show() self.about_button.show() def on_picker_orientation_value_changed(self, *args): self._config.rotation_mode = self.touch_selector_orientation.get_active(0) def on_picker_interval_value_changed(self, *args): active_index = self.touch_selector_interval.get_active(0) if active_index < len(self.UPDATE_INTERVALS): new_frequency = self.UPDATE_INTERVALS[active_index][0] else: new_frequency = self._custom_interval if new_frequency == 0: self._config.auto_update_feeds = False self._config.auto_update_frequency = new_frequency if new_frequency > 0: self._config.auto_update_feeds = True def on_picker_download_value_changed(self, *args): active_index = self.touch_selector_download.get_active(0) new_value = self.DOWNLOAD_METHODS[active_index][0] self._config.auto_download = new_value def on_picker_audio_player_value_changed(self, *args): active_index = self.touch_selector_audio_player.get_active(0) new_value = self.AUDIO_PLAYERS[active_index][0] self._config.player = new_value def on_picker_video_player_value_changed(self, *args): active_index = self.touch_selector_video_player.get_active(0) new_value = self.VIDEO_PLAYERS[active_index][0] self._config.videoplayer = new_value def update_button_mygpo(self): if self._config.mygpo_username: self.button_mygpo.set_value(self._config.mygpo_username) else: self.button_mygpo.set_value(_('Not logged in')) def on_button_mygpo_clicked(self, button): self.mygpo_login() self.update_button_mygpo()
unknown
codeparrot/codeparrot-clean
# frozen_string_literal: true module Bundler; end require_relative "vendor/tsort/lib/tsort"
ruby
github
https://github.com/ruby/ruby
lib/bundler/vendored_tsort.rb
# -*- coding: utf-8 -*- ############################################################################## # # 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 _, models class WizardUpdateChartsAccounts(models.TransientModel): _inherit = 'wizard.update.charts.accounts' def _is_different_tax_code(self, tax_code, tax_code_template, mapping_tax_codes): notes = super(WizardUpdateChartsAccounts, self)._is_different_tax_code( tax_code, tax_code_template, mapping_tax_codes) if tax_code.mod340 != tax_code_template.mod340: notes += _("The 340 model field is different.\n") return notes def _prepare_tax_code_vals(self, tax_code_template, mapping_tax_codes): res = super(WizardUpdateChartsAccounts, self)._prepare_tax_code_vals( tax_code_template, mapping_tax_codes) res['mod340'] = tax_code_template.mod340 return res def _is_different_tax(self, tax, tax_template, mapping_taxes, mapping_tax_codes, mapping_accounts): notes = super(WizardUpdateChartsAccounts, self)._is_different_tax( tax, tax_template, mapping_taxes, mapping_tax_codes, mapping_accounts) if tax.is_340_reserve_charge != tax_template.is_340_reserve_charge: notes += _("The field is 340 reverse charge is different.\n") return notes def _prepare_tax_vals(self, tax_template, mapping_tax_codes, mapping_taxes): res = super(WizardUpdateChartsAccounts, self)._prepare_tax_vals( tax_template, mapping_tax_codes, mapping_taxes) res['is_340_reserve_charge'] = tax_template.is_340_reserve_charge return res
unknown
codeparrot/codeparrot-clean
import cv2 import numpy as np import os import sys import ntpath import time from . import util, html from subprocess import Popen, PIPE if sys.version_info[0] == 2: VisdomExceptionBase = Exception else: VisdomExceptionBase = ConnectionError def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256): """Save images to the disk. Parameters: webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details) visuals (OrderedDict) -- an ordered dictionary that stores (name, images (either tensor or numpy) ) pairs image_path (str) -- the string is used to create image paths aspect_ratio (float) -- the aspect ratio of saved images width (int) -- the images will be resized to width x width This function will save images stored in 'visuals' to the HTML file specified by 'webpage'. """ image_dir = webpage.get_image_dir() short_path = ntpath.basename(image_path[0]) name = os.path.splitext(short_path)[0] webpage.add_header(name) ims, txts, links = [], [], [] for label, im_data in visuals.items(): im = util.tensor2im(im_data) image_name = '%s_%s.png' % (name, label) save_path = os.path.join(image_dir, image_name) util.save_image(im, save_path, aspect_ratio=aspect_ratio) ims.append(image_name) txts.append(label) links.append(image_name) webpage.add_images(ims, txts, links, width=width) def save_videos(webpage, visuals, width=256): """Save videos to the disk. Parameters: webpage (the HTML class) -- the HTML webpage class that stores these videos (see html.py for more details) visuals (OrderedDict) -- an ordered dictionary that stores (name, video (either tensor or numpy) ) pairs save_dir (str) -- the string is used to create video paths aspect_ratio (float) -- the aspect ratio of saved images width (int) -- the images will be resized to width x width This function will save videos stored in 'visuals' to the HTML file specified by 'webpage'. """ video_dir = webpage.get_video_dir() webpage.add_header('videos') vids, txts, links = [], [], [] for label, vid_data in sorted(visuals.items()): video_name = f'{label}.webm' video_path = os.path.join(video_dir, video_name) frame_height, frame_width = vid_data.shape[-2:] video = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'vp80'), 25, (frame_width, frame_height)) for i in range(vid_data.shape[0]): frame = util.tensor2im(vid_data[i:i+1]) if frame.shape[-1] == 4: # render png frame = util.render_png(frame, background='checker') frame = frame[:, :, ::-1] # RGB -> BGR video.write(frame) video.release() cv2.destroyAllWindows() print("You may see an OpenCV 'vp80 not supported' error message despite the video saving correctly. Please ignore it.") vids.append(video_name) txts.append(label) links.append(video_name) webpage.add_videos(vids, txts, links, width=width) class Visualizer(): """This class includes several functions that can display/save images and print/save logging information. It uses a Python library 'visdom' for display, and a Python library 'dominate' (wrapped in 'HTML') for creating HTML files with images. """ def __init__(self, opt): """Initialize the Visualizer class Parameters: opt -- stores all the experiment flags; needs to be a subclass of BaseOptions Step 1: Cache the training/test options Step 2: connect to a visdom server Step 3: create an HTML object for saveing HTML filters Step 4: create a logging file to store training losses """ self.opt = opt # cache the option self.display_id = opt.display_id self.use_html = opt.isTrain and not opt.no_html self.win_size = opt.display_winsize self.name = opt.name self.port = opt.display_port self.saved = False if self.display_id > 0: # connect to a visdom server given <display_port> and <display_server> import visdom self.ncols = opt.display_ncols self.vis = visdom.Visdom(server=opt.display_server, port=opt.display_port, env=opt.display_env) if not self.vis.check_connection(): self.create_visdom_connections() if self.use_html: # create an HTML object at <checkpoints_dir>/web/; images will be saved under <checkpoints_dir>/web/images/ self.web_dir = os.path.join(opt.checkpoints_dir, opt.name, 'web') self.img_dir = os.path.join(self.web_dir, 'images') print('create web directory %s...' % self.web_dir) util.mkdirs([self.web_dir, self.img_dir]) # create a logging file to store training losses self.log_name = os.path.join(opt.checkpoints_dir, opt.name, 'loss_log.txt') with open(self.log_name, "a") as log_file: now = time.strftime("%c") log_file.write('================ Training Loss (%s) ================\n' % now) def reset(self): """Reset the self.saved status""" self.saved = False def create_visdom_connections(self): """If the program could not connect to Visdom server, this function will start a new server at port < self.port > """ cmd = sys.executable + ' -m visdom.server -p %d &>/dev/null &' % self.port print('\n\nCould not connect to Visdom server. \n Trying to start a server....') print('Command: %s' % cmd) Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) def display_current_results(self, visuals, epoch, save_result): """Display current results on visdom; save current results to an HTML file. Parameters: visuals (OrderedDict) - - dictionary of images to display or save epoch (int) - - the current epoch save_result (bool) - - if save the current results to an HTML file """ if self.display_id > 0: # show images in the browser using visdom ncols = self.ncols if ncols > 0: # show all the images in one visdom panel ncols = min(ncols, len(visuals)) h, w = next(iter(visuals.values())).shape[:2] table_css = """<style> table {border-collapse: separate; border-spacing: 4px; white-space: nowrap; text-align: center} table td {width: % dpx; height: % dpx; padding: 4px; outline: 4px solid black} </style>""" % (w, h) # create a table css # create a table of images. title = self.name label_html = '' label_html_row = '' images = [] idx = 0 for label, image in visuals.items(): image_numpy = util.tensor2im(image) label_html_row += '<td>%s</td>' % label images.append(image_numpy.transpose([2, 0, 1])) idx += 1 if idx % ncols == 0: label_html += '<tr>%s</tr>' % label_html_row label_html_row = '' white_image = np.ones_like(image_numpy.transpose([2, 0, 1])) * 255 while idx % ncols != 0: images.append(white_image) label_html_row += '<td></td>' idx += 1 if label_html_row != '': label_html += '<tr>%s</tr>' % label_html_row try: self.vis.images(images, nrow=ncols, win=self.display_id + 1, padding=2, opts=dict(title=title + ' images')) label_html = '<table>%s</table>' % label_html self.vis.text(table_css + label_html, win=self.display_id + 2, opts=dict(title=title + ' labels')) except VisdomExceptionBase: self.create_visdom_connections() else: # show each image in a separate visdom panel; idx = 1 try: for label, image in visuals.items(): image_numpy = util.tensor2im(image) self.vis.image(image_numpy.transpose([2, 0, 1]), opts=dict(title=label), win=self.display_id + idx) idx += 1 except VisdomExceptionBase: self.create_visdom_connections() if self.use_html and (save_result or not self.saved): # save images to an HTML file if they haven't been saved. self.saved = True # save images to the disk for label, image in visuals.items(): image_numpy = util.tensor2im(image) img_path = os.path.join(self.img_dir, 'epoch%.3d_%s.png' % (epoch, label)) util.save_image(image_numpy, img_path) # update website webpage = html.HTML(self.web_dir, 'Experiment name = %s' % self.name, refresh=1) for n in range(epoch, 0, -1): label = list(visuals.keys())[0] img_path = 'epoch%.3d_%s.png' % (n, label) if not os.path.exists(os.path.join(webpage.img_dir, img_path)): continue webpage.add_header('epoch [%d]' % n) ims, txts, links = [], [], [] for label, image_numpy in visuals.items(): img_path = 'epoch%.3d_%s.png' % (n, label) ims.append(img_path) txts.append(label) links.append(img_path) webpage.add_images(ims, txts, links, width=self.win_size) webpage.save() def plot_current_losses(self, epoch, counter_ratio, losses): """display the current losses on visdom display: dictionary of error labels and values Parameters: epoch (int) -- current epoch counter_ratio (float) -- progress (percentage) in the current epoch, between 0 to 1 losses (OrderedDict) -- training losses stored in the format of (name, float) pairs """ if not hasattr(self, 'plot_data'): self.plot_data = {'X': [], 'Y': [], 'legend': list(losses.keys())} self.plot_data['X'].append(epoch + counter_ratio) self.plot_data['Y'].append([losses[k] for k in self.plot_data['legend']]) try: self.vis.line( X=np.stack([np.array(self.plot_data['X'])] * len(self.plot_data['legend']), 1), Y=np.array(self.plot_data['Y']), opts={ 'title': self.name + ' loss over time', 'legend': self.plot_data['legend'], 'xlabel': 'epoch', 'ylabel': 'loss'}, win=self.display_id) except VisdomExceptionBase: self.create_visdom_connections() # losses: same format as |losses| of plot_current_losses def print_current_losses(self, epoch, iters, losses, t_comp, t_data): """print current losses on console; also save the losses to the disk Parameters: epoch (int) -- current epoch iters (int) -- current training iteration during this epoch (reset to 0 at the end of every epoch) losses (OrderedDict) -- training losses stored in the format of (name, float) pairs t_comp (float) -- computational time per data point (normalized by batch_size) t_data (float) -- data loading time per data point (normalized by batch_size) """ message = '(epoch: %d, iters: %d, time: %.3f, data: %.3f) ' % (epoch, iters, t_comp, t_data) for k, v in losses.items(): message += '%s: %.3f ' % (k, v) print(message) # print the message with open(self.log_name, "a") as log_file: log_file.write('%s\n' % message) # save the message
unknown
codeparrot/codeparrot-clean
// Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: BUSL-1.1 package addrs import ( "fmt" ) // InputVariable is the address of an input variable. type InputVariable struct { referenceable Name string } func (v InputVariable) String() string { return "var." + v.Name } func (v InputVariable) UniqueKey() UniqueKey { return v // A InputVariable is its own UniqueKey } func (v InputVariable) uniqueKeySigil() {} // Absolute converts the receiver into an absolute address within the given // module instance. func (v InputVariable) Absolute(m ModuleInstance) AbsInputVariableInstance { return AbsInputVariableInstance{ Module: m, Variable: v, } } func (v InputVariable) InModule(module Module) ConfigInputVariable { return ConfigInputVariable{ Module: module, Variable: v, } } // AbsInputVariableInstance is the address of an input variable within a // particular module instance. type AbsInputVariableInstance struct { Module ModuleInstance Variable InputVariable } var _ Checkable = AbsInputVariableInstance{} // InputVariable returns the absolute address of the input variable of the // given name inside the receiving module instance. func (m ModuleInstance) InputVariable(name string) AbsInputVariableInstance { return AbsInputVariableInstance{ Module: m, Variable: InputVariable{ Name: name, }, } } func (v AbsInputVariableInstance) String() string { if len(v.Module) == 0 { return v.Variable.String() } return fmt.Sprintf("%s.%s", v.Module.String(), v.Variable.String()) } func (v AbsInputVariableInstance) UniqueKey() UniqueKey { return absInputVariableInstanceUniqueKey(v.String()) } func (v AbsInputVariableInstance) checkableSigil() {} func (v AbsInputVariableInstance) CheckRule(typ CheckRuleType, i int) CheckRule { return CheckRule{ Container: v, Type: typ, Index: i, } } // ModuleInstance returns the module instance portion of the address. func (v AbsInputVariableInstance) ModuleInstance() ModuleInstance { return v.Module } func (v AbsInputVariableInstance) ConfigCheckable() ConfigCheckable { return ConfigInputVariable{ Module: v.Module.Module(), Variable: v.Variable, } } func (v AbsInputVariableInstance) CheckableKind() CheckableKind { return CheckableInputVariable } type ConfigInputVariable struct { Module Module Variable InputVariable } var _ ConfigCheckable = ConfigInputVariable{} func (v ConfigInputVariable) UniqueKey() UniqueKey { return configInputVariableUniqueKey(v.String()) } func (v ConfigInputVariable) configCheckableSigil() {} func (v ConfigInputVariable) CheckableKind() CheckableKind { return CheckableInputVariable } func (v ConfigInputVariable) String() string { if len(v.Module) == 0 { return v.Variable.String() } return fmt.Sprintf("%s.%s", v.Module.String(), v.Variable.String()) } type configInputVariableUniqueKey string func (k configInputVariableUniqueKey) uniqueKeySigil() {} type absInputVariableInstanceUniqueKey string func (k absInputVariableInstanceUniqueKey) uniqueKeySigil() {}
go
github
https://github.com/hashicorp/terraform
internal/addrs/input_variable.go
antora: extensions: site: title: Spring Boot content: sources: [] asciidoc: sourcemap: true attributes: chomp: all hide-uri-scheme: '@' javadoc-location: xref:api:java/ page-pagination: '' page-stackoverflow-url: https://stackoverflow.com/tags/spring-boot tabs-sync-option: '@' extensions: urls: latest_version_segment: '' runtime: log: failure_level: warn
unknown
github
https://github.com/spring-projects/spring-boot
buildSrc/src/main/resources/org/springframework/boot/build/antora/antora-playbook-template.yml
# Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com) # # MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # from __future__ import unicode_literals """ Utilities for using modules """ import webnotes, os, conf transfer_types = ['Role', 'Print Format','DocType','Page','DocType Mapper', 'GL Mapper','Search Criteria', 'Patch', 'Report'] lower_case_files_for = ['DocType', 'Page', 'Search Criteria', 'Report', "Workflow", 'Module Def', 'Desktop Item', 'Workflow State', 'Workflow Action'] code_fields_dict = { 'Page':[('script', 'js'), ('content', 'html'), ('style', 'css'), ('static_content', 'html'), ('server_code', 'py')], 'DocType':[('server_code_core', 'py'), ('client_script_core', 'js')], 'Search Criteria':[('report_script', 'js'), ('server_script', 'py'), ('custom_query', 'sql')], 'Patch':[('patch_code', 'py')], 'Stylesheet':['stylesheet', 'css'], 'Page Template':['template', 'html'], 'Control Panel':[('startup_code', 'js'), ('startup_css', 'css')] } def scrub(txt): return txt.replace(' ','_').replace('-', '_').replace('/', '_').lower() def scrub_dt_dn(dt, dn): """Returns in lowercase and code friendly names of doctype and name for certain types""" ndt, ndn = dt, dn if dt in lower_case_files_for: ndt, ndn = scrub(dt), scrub(dn) return ndt, ndn def get_module_path(module): """Returns path of the given module""" m = scrub(module) app_path = os.path.dirname(conf.__file__) if m in ('core'): return os.path.join(app_path, 'lib', 'core') else: return os.path.join(app_path, 'app', m) def get_doc_path(module, doctype, name): dt, dn = scrub_dt_dn(doctype, name) return os.path.join(get_module_path(module), dt, dn) def reload_doc(module, dt=None, dn=None, force=True): from webnotes.modules.import_file import import_files return import_files(module, dt, dn, force) def export_doc(doctype, name, module=None): """write out a doc""" from webnotes.modules.export_file import write_document_file import webnotes.model.doc if not module: module = webnotes.conn.get_value(doctype, name, 'module') write_document_file(webnotes.model.doc.get(doctype, name), module) def get_doctype_module(doctype): return webnotes.conn.get_value('DocType', doctype, 'module')
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # # Copyright 2017 F5 Networks Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public Liccense 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 os import json import sys import pytest from nose.plugins.skip import SkipTest if sys.version_info < (2, 7): raise SkipTest("F5 Ansible modules require Python >= 2.7") from ansible.compat.tests import unittest from ansible.compat.tests.mock import patch, Mock from ansible.module_utils import basic from ansible.module_utils._text import to_bytes from ansible.module_utils.f5_utils import AnsibleF5Client from ansible.module_utils.f5_utils import F5ModuleError try: from library.bigip_monitor_tcp_echo import Parameters from library.bigip_monitor_tcp_echo import ModuleManager from library.bigip_monitor_tcp_echo import ArgumentSpec except ImportError: try: from ansible.modules.network.f5.bigip_monitor_tcp_echo import Parameters from ansible.modules.network.f5.bigip_monitor_tcp_echo import ModuleManager from ansible.modules.network.f5.bigip_monitor_tcp_echo import ArgumentSpec from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError except ImportError: raise SkipTest("F5 Ansible modules require the f5-sdk Python library") fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def set_module_args(args): args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) basic._ANSIBLE_ARGS = to_bytes(args) def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except Exception: pass fixture_data[path] = data return data class TestParameters(unittest.TestCase): def test_module_parameters(self): args = dict( name='foo', parent='parent', ip='10.10.10.10', interval=20, timeout=30, time_until_up=60, partition='Common' ) p = Parameters(args) assert p.name == 'foo' assert p.parent == '/Common/parent' assert p.ip == '10.10.10.10' assert p.type == 'tcp_echo' assert p.destination == '10.10.10.10' assert p.interval == 20 assert p.timeout == 30 assert p.time_until_up == 60 def test_module_parameters_ints_as_strings(self): args = dict( name='foo', parent='parent', ip='10.10.10.10', interval='20', timeout='30', time_until_up='60', partition='Common' ) p = Parameters(args) assert p.name == 'foo' assert p.parent == '/Common/parent' assert p.ip == '10.10.10.10' assert p.type == 'tcp_echo' assert p.destination == '10.10.10.10' assert p.interval == 20 assert p.timeout == 30 assert p.time_until_up == 60 def test_api_parameters(self): args = dict( name='foo', defaultsFrom='/Common/parent', destination='10.10.10.10', interval=20, timeout=30, timeUntilUp=60 ) p = Parameters(args) assert p.name == 'foo' assert p.parent == '/Common/parent' assert p.ip == '10.10.10.10' assert p.type == 'tcp_echo' assert p.destination == '10.10.10.10' assert p.interval == 20 assert p.timeout == 30 assert p.time_until_up == 60 @patch('ansible.module_utils.f5_utils.AnsibleF5Client._get_mgmt_root', return_value=True) class TestManagerEcho(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() def test_create_monitor(self, *args): set_module_args(dict( name='foo', ip='10.10.10.10', interval=20, timeout=30, time_until_up=60, server='localhost', password='password', user='admin' )) client = AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) # Override methods in the specific type of manager mm = ModuleManager(client) mm.exists = Mock(side_effect=[False, True]) mm.create_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True def test_create_monitor_idempotent(self, *args): set_module_args(dict( name='foo', ip='10.10.10.10', interval=20, timeout=30, time_until_up=60, server='localhost', password='password', user='admin' )) current = Parameters(load_fixture('load_ltm_monitor_tcp_echo.json')) client = AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) # Override methods in the specific type of manager mm = ModuleManager(client) mm.exists = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=current) results = mm.exec_module() assert results['changed'] is False def test_update_interval(self, *args): set_module_args(dict( name='foo', interval=10, server='localhost', password='password', user='admin' )) current = Parameters(load_fixture('load_ltm_monitor_tcp_echo.json')) client = AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) # Override methods in the specific type of manager mm = ModuleManager(client) mm.exists = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=current) mm.update_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True assert results['interval'] == 10 def test_update_interval_larger_than_existing_timeout(self, *args): set_module_args(dict( name='foo', interval=30, server='localhost', password='password', user='admin' )) current = Parameters(load_fixture('load_ltm_monitor_tcp_echo.json')) client = AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) # Override methods in the specific type of manager mm = ModuleManager(client) mm.exists = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=current) mm.update_on_device = Mock(return_value=True) with pytest.raises(F5ModuleError) as ex: mm.exec_module() assert "must be less than" in str(ex) def test_update_interval_larger_than_new_timeout(self, *args): set_module_args(dict( name='foo', interval=10, timeout=5, server='localhost', password='password', user='admin' )) current = Parameters(load_fixture('load_ltm_monitor_tcp_echo.json')) client = AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) # Override methods in the specific type of manager mm = ModuleManager(client) mm.exists = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=current) mm.update_on_device = Mock(return_value=True) with pytest.raises(F5ModuleError) as ex: mm.exec_module() assert "must be less than" in str(ex) def test_update_timeout(self, *args): set_module_args(dict( name='foo', timeout=300, server='localhost', password='password', user='admin' )) current = Parameters(load_fixture('load_ltm_monitor_tcp_echo.json')) client = AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) # Override methods in the specific type of manager mm = ModuleManager(client) mm.exists = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=current) mm.update_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True assert results['timeout'] == 300 def test_update_time_until_up(self, *args): set_module_args(dict( name='foo', time_until_up=300, server='localhost', password='password', user='admin' )) current = Parameters(load_fixture('load_ltm_monitor_tcp_echo.json')) client = AnsibleF5Client( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode, f5_product_name=self.spec.f5_product_name ) # Override methods in the specific type of manager mm = ModuleManager(client) mm.exists = Mock(return_value=True) mm.read_current_from_device = Mock(return_value=current) mm.update_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True assert results['time_until_up'] == 300
unknown
codeparrot/codeparrot-clean
/* * Copyright (C) 2008 The Guava Authors * * 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. */ package com.google.common.collect.testing; import static java.util.Arrays.asList; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.ListIterator; import java.util.Set; /** * A method supported by implementations of the {@link Iterator} or {@link ListIterator} interface. * * <p>This enum is GWT compatible. * * @author Chris Povirk */ @GwtCompatible public enum IteratorFeature { /** Support for {@link Iterator#remove()}. */ SUPPORTS_REMOVE, /** * Support for {@link ListIterator#add(Object)}; ignored for plain {@link Iterator} * implementations. */ SUPPORTS_ADD, /** * Support for {@link ListIterator#set(Object)}; ignored for plain {@link Iterator} * implementations. */ SUPPORTS_SET; /** * A set containing none of the optional features of the {@link Iterator} or {@link ListIterator} * interfaces. */ public static final Set<IteratorFeature> UNMODIFIABLE = emptySet(); /** * A set containing all of the optional features of the {@link Iterator} and {@link ListIterator} * interfaces. */ public static final Set<IteratorFeature> MODIFIABLE = unmodifiableSet(new LinkedHashSet<>(asList(values()))); }
java
github
https://github.com/google/guava
android/guava-testlib/src/com/google/common/collect/testing/IteratorFeature.java
function Component(x = 'default', y = [{}]) { return [x, y]; } export const FIXTURE_ENTRYPOINT = { fn: Component, params: ['TodoAdd'], isComponent: 'TodoAdd', };
javascript
github
https://github.com/facebook/react
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-param-assignment-pattern.js
#!/usr/bin/env bash # Copyright IBM Corp. 2016, 2025 # SPDX-License-Identifier: BUSL-1.1 set -eou pipefail fail() { echo "$1" 1>&2 exit 1 } [[ -z "$VAULT_ADDR" ]] && fail "VAULT_ADDR env variable has not been set" [[ -z "$VAULT_INSTALL_DIR" ]] && fail "VAULT_INSTALL_DIR env variable has not been set" [[ -z "$VAULT_TOKEN" ]] && fail "VAULT_TOKEN env variable has not been set" binpath=${VAULT_INSTALL_DIR}/vault test -x "$binpath" || fail "unable to locate vault binary at $binpath" eval "$binpath" operator step-down
unknown
github
https://github.com/hashicorp/vault
enos/modules/vault_step_down/scripts/operator-step-down.sh
#!/usr/bin/env python ''' extra DMA mapping tables from a stm32 datasheet This assumes a csv file extracted from the datasheet using tablula: https://github.com/tabulapdf/tabula ''' import sys, csv, os def parse_dma_table(fname, table): dma_num = 1 csvt = csv.reader(open(fname,'rb')) i = 0 last_channel = -1 for row in csvt: if len(row) > 1 and row[1].startswith('Channel '): row = row[1:] if not row[0].startswith('Channel '): continue channel = int(row[0].split(' ')[1]) if channel < last_channel: dma_num += 1 last_channel = channel for stream in range(8): s = row[stream+1] s = s.replace('_\r', '_') s = s.replace('\r_', '_') if s == '-': continue keys = s.split() for k in keys: brace = k.find('(') if brace != -1: k = k[:brace] if k not in table: table[k] = [] table[k] += [(dma_num, stream, channel)] def error(str): '''show an error and exit''' print("Error: " + str) sys.exit(1) def check_full_table(table): '''check the table is not missing rows or columns we should have at least one entry in every row and one entry in every colum of each dma table ''' stream_mask = [0,0] channel_mask = [0,0] for k in table: for v in table[k]: (engine,stream,channel) = v if engine > 2 or engine < 1: error("Bad entry for %s: %s" % (k, v)) stream_mask[engine-1] |= 1<<stream channel_mask[engine-1] |= 1<<channel for i in range(2): for c in range(8): if not ((1<<c) & channel_mask[i]): error("Missing channel %u for dma table %u" % (c, i)) if not ((1<<c) & stream_mask[i]): error("Missing stream %u for dma table %u" % (c, i)) table = {} if len(sys.argv) != 2: print("Error: expected a CSV files and output file") sys.exit(1) parse_dma_table(sys.argv[1], table) check_full_table(table) sys.stdout.write("DMA_Map = {\n"); sys.stdout.write('\t# format is (DMA_TABLE, StreamNum, Channel)\n') sys.stdout.write('\t# extracted from %s\n' % os.path.basename(sys.argv[1])) for k in sorted(table.iterkeys()): s = '"%s"' % k sys.stdout.write('\t%-10s\t:\t[' % s) for i in range(len(table[k])): sys.stdout.write("(%u,%u,%u)" % (table[k][i][0], table[k][i][1], table[k][i][2])) if i < len(table[k])-1: sys.stdout.write(",") sys.stdout.write("],\n") sys.stdout.write("}\n");
unknown
codeparrot/codeparrot-clean
/* * Copyright (C) 2011 The Guava Authors * * 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. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.Byte.toUnsignedInt; import static java.lang.Math.max; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.hash.BloomFilterStrategies.LockFreeBitArray; import com.google.common.math.DoubleMath; import com.google.common.primitives.SignedBytes; import com.google.common.primitives.UnsignedBytes; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.InlineMe; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.Serializable; import java.math.RoundingMode; import java.util.Objects; import java.util.stream.Collector; import org.jspecify.annotations.Nullable; /** * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test * with one-sided error: if it claims that an element is contained in it, this might be in error, * but if it claims that an element is <i>not</i> contained in it, then this is definitely true. * * <p>If you are unfamiliar with Bloom filters, this nice <a * href="http://llimllib.github.io/bloomfilter-tutorial/">tutorial</a> may help you understand how * they work. * * <p>The false positive probability ({@code FPP}) of a Bloom filter is defined as the probability * that {@linkplain #mightContain(Object)} will erroneously return {@code true} for an object that * has not actually been put in the {@code BloomFilter}. * * <p>Bloom filters are serializable. They also support a more compact serial representation via the * {@link #writeTo} and {@link #readFrom} methods. Both serialized forms will continue to be * supported by future versions of this library. However, serial forms generated by newer versions * of the code may not be readable by older versions of the code (e.g., a serialized Bloom filter * generated today may <i>not</i> be readable by a binary that was compiled 6 months ago). * * <p>As of Guava 23.0, this class is thread-safe and lock-free. It internally uses atomics and * compare-and-swap to ensure correctness when multiple threads are used to access it. * * @param <T> the type of instances that the {@code BloomFilter} accepts * @author Dimitris Andreou * @author Kevin Bourrillion * @since 11.0 (thread-safe since 23.0) */ @Beta public final class BloomFilter<T extends @Nullable Object> implements Predicate<T>, Serializable { /** * A strategy to translate T instances, to {@code numHashFunctions} bit indexes. * * <p>Implementations should be collections of pure functions (i.e. stateless). */ interface Strategy extends Serializable { /** * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element. * * <p>Returns whether any bits changed as a result of this operation. */ <T extends @Nullable Object> boolean put( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits); /** * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element; * returns {@code true} if and only if all selected bits are set. */ <T extends @Nullable Object> boolean mightContain( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits); /** * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. Only * values in the [-128, 127] range are valid for the compact serial form. Non-negative values * are reserved for enums defined in BloomFilterStrategies; negative values are reserved for any * custom, stateful strategy we may define (e.g. any kind of strategy that would depend on user * input). */ int ordinal(); } /** The bit set of the BloomFilter (not necessarily power of 2!) */ private final LockFreeBitArray bits; /** Number of hashes per element */ private final int numHashFunctions; /** The funnel to translate Ts to bytes */ private final Funnel<? super T> funnel; /** The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. */ private final Strategy strategy; /** Natural logarithm of 2, used to optimize calculations in Bloom filter sizing. */ private static final double LOG_TWO = Math.log(2); /** Square of the natural logarithm of 2, reused to optimize the bit size calculation. */ private static final double SQUARED_LOG_TWO = LOG_TWO * LOG_TWO; /** Creates a BloomFilter. */ private BloomFilter( LockFreeBitArray bits, int numHashFunctions, Funnel<? super T> funnel, Strategy strategy) { checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions); checkArgument( numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions); this.bits = checkNotNull(bits); this.numHashFunctions = numHashFunctions; this.funnel = checkNotNull(funnel); this.strategy = checkNotNull(strategy); } /** * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to * this instance but shares no mutable state. * * @since 12.0 */ public BloomFilter<T> copy() { return new BloomFilter<>(bits.copy(), numHashFunctions, funnel, strategy); } /** * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, {@code * false} if this is <i>definitely</i> not the case. */ public boolean mightContain(@ParametricNullness T object) { return strategy.mightContain(object, funnel, numHashFunctions, bits); } /** * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #mightContain} * instead. */ @InlineMe(replacement = "this.mightContain(input)") @Deprecated @Override public boolean apply(@ParametricNullness T input) { return mightContain(input); } /** * @deprecated Provided only to satisfy the {@link java.util.function.Predicate} interface; use * {@link #mightContain} instead. * @since 21.0 */ @InlineMe(replacement = "this.mightContain(input)") @Deprecated @Override public boolean test(@ParametricNullness T input) { return mightContain(input); } /** * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of {@link * #mightContain(Object)} with the same element will always return {@code true}. * * @return true if the Bloom filter's bits changed as a result of this operation. If the bits * changed, this is <i>definitely</i> the first time {@code object} has been added to the * filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} has * been added to the filter. Note that {@code put(t)} always returns the <i>opposite</i> * result to what {@code mightContain(t)} would have returned at the time it is called. * @since 12.0 (present in 11.0 with {@code void} return type}) */ @CanIgnoreReturnValue public boolean put(@ParametricNullness T object) { return strategy.put(object, funnel, numHashFunctions, bits); } /** * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return {@code * true} for an object that has not actually been put in the {@code BloomFilter}. * * <p>Ideally, this number should be close to the {@code fpp} parameter passed in {@linkplain * #create(Funnel, int, double)}, or smaller. If it is significantly higher, it is usually the * case that too many elements (more than expected) have been put in the {@code BloomFilter}, * degenerating it. * * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) */ public double expectedFpp() { return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); } /** * Returns an estimate for the total number of distinct elements that have been added to this * Bloom filter. This approximation is reasonably accurate if it does not exceed the value of * {@code expectedInsertions} that was used when constructing the filter. * * @since 22.0 */ public long approximateElementCount() { long bitSize = bits.bitSize(); long bitCount = bits.bitCount(); /* * Each insertion is expected to reduce the # of clear bits by a factor of * `numHashFunctions/bitSize`. So, after n insertions, expected bitCount is `bitSize * (1 - (1 - * numHashFunctions/bitSize)^n)`. Solving that for n, and approximating `ln x` as `x - 1` when x * is close to 1 (why?), gives the following formula. */ double fractionOfBitsSet = (double) bitCount / bitSize; return DoubleMath.roundToLong( -Math.log1p(-fractionOfBitsSet) * bitSize / numHashFunctions, RoundingMode.HALF_UP); } /** Returns the number of bits in the underlying bit array. */ @VisibleForTesting long bitSize() { return bits.bitSize(); } /** * Determines whether a given Bloom filter is compatible with this Bloom filter. For two Bloom * filters to be compatible, they must: * * <ul> * <li>not be the same instance * <li>have the same number of hash functions * <li>have the same bit size * <li>have the same strategy * <li>have equal funnels * </ul> * * @param that The Bloom filter to check for compatibility. * @since 15.0 */ public boolean isCompatible(BloomFilter<T> that) { checkNotNull(that); return this != that && this.numHashFunctions == that.numHashFunctions && this.bitSize() == that.bitSize() && this.strategy.equals(that.strategy) && this.funnel.equals(that.funnel); } /** * Combines this Bloom filter with another Bloom filter by performing a bitwise OR of the * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the Bloom * filters are appropriately sized to avoid saturating them. * * @param that The Bloom filter to combine this Bloom filter with. It is not mutated. * @throws IllegalArgumentException if {@code isCompatible(that) == false} * @since 15.0 */ public void putAll(BloomFilter<T> that) { checkNotNull(that); checkArgument(this != that, "Cannot combine a BloomFilter with itself."); checkArgument( this.numHashFunctions == that.numHashFunctions, "BloomFilters must have the same number of hash functions (%s != %s)", this.numHashFunctions, that.numHashFunctions); checkArgument( this.bitSize() == that.bitSize(), "BloomFilters must have the same size underlying bit arrays (%s != %s)", this.bitSize(), that.bitSize()); checkArgument( this.strategy.equals(that.strategy), "BloomFilters must have equal strategies (%s != %s)", this.strategy, that.strategy); checkArgument( this.funnel.equals(that.funnel), "BloomFilters must have equal funnels (%s != %s)", this.funnel, that.funnel); this.bits.putAll(that.bits); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof BloomFilter) { BloomFilter<?> that = (BloomFilter<?>) object; return this.numHashFunctions == that.numHashFunctions && this.funnel.equals(that.funnel) && this.bits.equals(that.bits) && this.strategy.equals(that.strategy); } return false; } @Override public int hashCode() { return Objects.hash(numHashFunctions, funnel, strategy, bits); } /** * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link * BloomFilter} with false positive probability 3%. * * <p>Note that if the {@code Collector} receives significantly more elements than specified, the * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive * probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @return a {@code Collector} generating a {@code BloomFilter} of the received elements * @since 23.0 (but only since 33.4.0 in the Android flavor) */ public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter( Funnel<? super T> funnel, long expectedInsertions) { return toBloomFilter(funnel, expectedInsertions, 0.03); } /** * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link * BloomFilter} with the specified expected false positive probability. * * <p>Note that if the {@code Collector} receives significantly more elements than specified, the * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive * probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code Collector} generating a {@code BloomFilter} of the received elements * @since 23.0 (but only since 33.4.0 in the Android flavor) */ public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter( Funnel<? super T> funnel, long expectedInsertions, double fpp) { checkNotNull(funnel); checkArgument( expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); return Collector.of( () -> BloomFilter.create(funnel, expectedInsertions, fpp), BloomFilter::put, (bf1, bf2) -> { bf1.putAll(bf2); return bf1; }, Collector.Characteristics.UNORDERED, Collector.Characteristics.CONCURRENT); } /** * Creates a {@link BloomFilter} with the expected number of insertions and expected false * positive probability. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code BloomFilter} */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, int expectedInsertions, double fpp) { return create(funnel, (long) expectedInsertions, fpp); } /** * Creates a {@link BloomFilter} with the expected number of insertions and expected false * positive probability. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code BloomFilter} * @since 19.0 */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, long expectedInsertions, double fpp) { return create(funnel, expectedInsertions, fpp, BloomFilterStrategies.MURMUR128_MITZ_64); } @VisibleForTesting static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) { checkNotNull(funnel); checkArgument( expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); checkNotNull(strategy); if (expectedInsertions == 0) { expectedInsertions = 1; } /* * TODO(user): Put a warning in the javadoc about tiny fpp values, since the resulting size * is proportional to -log(p), but there is not much of a point after all, e.g. * optimalM(1000, 0.0000000000000001) = 76680 which is less than 10kb. Who cares! */ long numBits = optimalNumOfBits(expectedInsertions, fpp); int numHashFunctions = optimalNumOfHashFunctions(fpp); try { return new BloomFilter<>(new LockFreeBitArray(numBits), numHashFunctions, funnel, strategy); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e); } } /** * Creates a {@link BloomFilter} with the expected number of insertions and a default expected * false positive probability of 3%. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @return a {@code BloomFilter} */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, int expectedInsertions) { return create(funnel, (long) expectedInsertions); } /** * Creates a {@link BloomFilter} with the expected number of insertions and a default expected * false positive probability of 3%. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @return a {@code BloomFilter} * @since 19.0 */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, long expectedInsertions) { return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions } // Cheat sheet: // // m: total bits // n: expected insertions // b: m/n, bits per insertion // p: expected false positive probability // // 1) Optimal k = b * ln2 // 2) p = (1 - e ^ (-kn/m))^k // 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b // 4) For optimal k: m = -nlnp / ((ln2) ^ 2) /** * Computes the optimal number of hash functions (k) for a given false positive probability (p). * * <p>See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. * * @param p desired false positive probability (must be between 0 and 1, exclusive) */ @VisibleForTesting static int optimalNumOfHashFunctions(double p) { // -log(p) / log(2), ensuring the result is rounded to avoid truncation. return max(1, (int) Math.round(-Math.log(p) / LOG_TWO)); } /** * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified * expected insertions, the required false positive probability. * * <p>See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the * formula. * * @param n expected insertions (must be positive) * @param p false positive rate (must be 0 < p < 1) */ @VisibleForTesting static long optimalNumOfBits(long n, double p) { if (p == 0) { p = Double.MIN_VALUE; } return (long) (-n * Math.log(p) / SQUARED_LOG_TWO); } private Object writeReplace() { return new SerialForm<T>(this); } private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } private static final class SerialForm<T extends @Nullable Object> implements Serializable { final long[] data; final int numHashFunctions; final Funnel<? super T> funnel; final Strategy strategy; SerialForm(BloomFilter<T> bf) { this.data = LockFreeBitArray.toPlainArray(bf.bits.data); this.numHashFunctions = bf.numHashFunctions; this.funnel = bf.funnel; this.strategy = bf.strategy; } Object readResolve() { return new BloomFilter<T>(new LockFreeBitArray(data), numHashFunctions, funnel, strategy); } private static final long serialVersionUID = 1; } /** * Writes this {@code BloomFilter} to an output stream, with a custom format (not Java * serialization). This has been measured to save at least 400 bytes compared to regular * serialization. * * <p>Use {@linkplain #readFrom(InputStream, Funnel)} to reconstruct the written BloomFilter. */ public void writeTo(OutputStream out) throws IOException { // Serial form: // 1 signed byte for the strategy // 1 unsigned byte for the number of hash functions // 1 big endian int, the number of longs in our bitset // N big endian longs of our bitset DataOutputStream dout = new DataOutputStream(out); dout.writeByte(SignedBytes.checkedCast(strategy.ordinal())); dout.writeByte(UnsignedBytes.checkedCast(numHashFunctions)); // note: checked at the c'tor dout.writeInt(bits.data.length()); for (int i = 0; i < bits.data.length(); i++) { dout.writeLong(bits.data.get(i)); } } /** * Reads a byte stream, which was written by {@linkplain #writeTo(OutputStream)}, into a {@code * BloomFilter}. * * <p>The {@code Funnel} to be used is not encoded in the stream, so it must be provided here. * <b>Warning:</b> the funnel provided <b>must</b> behave identically to the one used to populate * the original Bloom filter! * * @throws IOException if the InputStream throws an {@code IOException}, or if its data does not * appear to be a BloomFilter serialized using the {@linkplain #writeTo(OutputStream)} method. */ @SuppressWarnings("CatchingUnchecked") // sneaky checked exception public static <T extends @Nullable Object> BloomFilter<T> readFrom( InputStream in, Funnel<? super T> funnel) throws IOException { checkNotNull(in, "InputStream"); checkNotNull(funnel, "Funnel"); int strategyOrdinal = -1; int numHashFunctions = -1; int dataLength = -1; try { DataInputStream din = new DataInputStream(in); // currently this assumes there is no negative ordinal; will have to be updated if we // add non-stateless strategies (for which we've reserved negative ordinals; see // Strategy.ordinal()). strategyOrdinal = din.readByte(); numHashFunctions = toUnsignedInt(din.readByte()); dataLength = din.readInt(); /* * We document in BloomFilterStrategies that we must not change the ordering, and we have a * test that verifies that we don't do so. */ @SuppressWarnings("EnumOrdinal") Strategy strategy = BloomFilterStrategies.values()[strategyOrdinal]; LockFreeBitArray dataArray = new LockFreeBitArray(Math.multiplyExact(dataLength, 64L)); for (int i = 0; i < dataLength; i++) { dataArray.putData(i, din.readLong()); } return new BloomFilter<>(dataArray, numHashFunctions, funnel, strategy); } catch (IOException e) { throw e; } catch (Exception e) { // sneaky checked exception String message = "Unable to deserialize BloomFilter from InputStream." + " strategyOrdinal: " + strategyOrdinal + " numHashFunctions: " + numHashFunctions + " dataLength: " + dataLength; throw new IOException(message, e); } } private static final long serialVersionUID = 0xcafebabe; }
java
github
https://github.com/google/guava
guava/src/com/google/common/hash/BloomFilter.java
-- -- Test foreign-data wrapper file_fdw. -- -- directory paths are passed to us in environment variables \getenv abs_srcdir PG_ABS_SRCDIR -- Clean up in case a prior regression run failed SET client_min_messages TO 'warning'; DROP ROLE IF EXISTS regress_file_fdw_superuser, regress_file_fdw_user, regress_no_priv_user; RESET client_min_messages; CREATE ROLE regress_file_fdw_superuser LOGIN SUPERUSER; -- is a superuser CREATE ROLE regress_file_fdw_user LOGIN; -- has priv and user mapping CREATE ROLE regress_no_priv_user LOGIN; -- has priv but no user mapping -- Install file_fdw CREATE EXTENSION file_fdw; -- create function to filter unstable results of EXPLAIN CREATE FUNCTION explain_filter(text) RETURNS setof text LANGUAGE plpgsql AS $$ declare ln text; begin for ln in execute $1 loop -- Remove the path portion of foreign file names ln := regexp_replace(ln, 'Foreign File: .*/([a-z.]+)$', 'Foreign File: .../\1'); return next ln; end loop; end; $$; -- regress_file_fdw_superuser owns fdw-related objects SET ROLE regress_file_fdw_superuser; CREATE SERVER file_server FOREIGN DATA WRAPPER file_fdw; -- privilege tests SET ROLE regress_file_fdw_user; CREATE FOREIGN DATA WRAPPER file_fdw2 HANDLER file_fdw_handler VALIDATOR file_fdw_validator; -- ERROR CREATE SERVER file_server2 FOREIGN DATA WRAPPER file_fdw; -- ERROR CREATE USER MAPPING FOR regress_file_fdw_user SERVER file_server; -- ERROR SET ROLE regress_file_fdw_superuser; GRANT USAGE ON FOREIGN SERVER file_server TO regress_file_fdw_user; SET ROLE regress_file_fdw_user; CREATE USER MAPPING FOR regress_file_fdw_user SERVER file_server; -- create user mappings and grant privilege to test users SET ROLE regress_file_fdw_superuser; CREATE USER MAPPING FOR regress_file_fdw_superuser SERVER file_server; CREATE USER MAPPING FOR regress_no_priv_user SERVER file_server; -- validator tests CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (foo 'bar'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS ("a=b" 'true'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'xml'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', quote ':'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', escape ':'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'binary', header 'true'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'binary', quote ':'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'binary', escape ':'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter 'a'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', escape '-'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', quote '-', null '=-='); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', delimiter '-', null '=-='); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', delimiter '-', quote '-'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', delimiter '---'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', quote '---'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', escape '---'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter '\'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter '.'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter '1'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter 'a'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', delimiter ' '); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', null ' '); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (on_error 'unsupported'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'binary', on_error 'ignore'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (log_verbosity 'unsupported'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (reject_limit '1'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (on_error 'ignore', reject_limit '0'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (header '-1'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (header '2.5'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (header 'unsupported'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server; -- ERROR \set filename :abs_srcdir '/data/agg.data' CREATE FOREIGN TABLE agg_text ( a int2 CHECK (a >= 0), b float4 ) SERVER file_server OPTIONS (format 'text', filename :'filename', delimiter ' ', null '\N'); GRANT SELECT ON agg_text TO regress_file_fdw_user; \set filename :abs_srcdir '/data/agg.csv' CREATE FOREIGN TABLE agg_csv ( a int2, b float4 ) SERVER file_server OPTIONS (format 'csv', filename :'filename', header 'true', delimiter ';', quote '@', escape '"', null ''); ALTER FOREIGN TABLE agg_csv ADD CHECK (a >= 0); \set filename :abs_srcdir '/data/agg.bad' CREATE FOREIGN TABLE agg_bad ( a int2, b float4 ) SERVER file_server OPTIONS (format 'csv', filename :'filename', header 'true', delimiter ';', quote '@', escape '"', null ''); ALTER FOREIGN TABLE agg_bad ADD CHECK (a >= 0); -- test header matching \set filename :abs_srcdir '/data/list1.csv' CREATE FOREIGN TABLE header_match ("1" int, foo text) SERVER file_server OPTIONS (format 'csv', filename :'filename', delimiter ',', header 'match'); SELECT * FROM header_match; CREATE FOREIGN TABLE header_doesnt_match (a int, foo text) SERVER file_server OPTIONS (format 'csv', filename :'filename', delimiter ',', header 'match'); SELECT * FROM header_doesnt_match; -- ERROR -- test multi-line header \set filename :abs_srcdir '/data/multiline_header.csv' CREATE FOREIGN TABLE multi_header (a int, b text) SERVER file_server OPTIONS (format 'csv', filename :'filename', header '2'); SELECT * FROM multi_header ORDER BY a; CREATE FOREIGN TABLE multi_header_skip (a int, b text) SERVER file_server OPTIONS (format 'csv', filename :'filename', header '5'); SELECT count(*) FROM multi_header_skip; -- per-column options tests \set filename :abs_srcdir '/data/text.csv' CREATE FOREIGN TABLE text_csv ( word1 text OPTIONS (force_not_null 'true'), word2 text OPTIONS (force_not_null 'off'), word3 text OPTIONS (force_null 'true'), word4 text OPTIONS (force_null 'off') ) SERVER file_server OPTIONS (format 'text', filename :'filename', null 'NULL'); SELECT * FROM text_csv; -- ERROR ALTER FOREIGN TABLE text_csv OPTIONS (SET format 'csv'); \pset null _null_ SELECT * FROM text_csv; -- force_not_null and force_null can be used together on the same column ALTER FOREIGN TABLE text_csv ALTER COLUMN word1 OPTIONS (force_null 'true'); ALTER FOREIGN TABLE text_csv ALTER COLUMN word3 OPTIONS (force_not_null 'true'); -- force_not_null is not allowed to be specified at any foreign object level: ALTER FOREIGN DATA WRAPPER file_fdw OPTIONS (ADD force_not_null '*'); -- ERROR ALTER SERVER file_server OPTIONS (ADD force_not_null '*'); -- ERROR CREATE USER MAPPING FOR public SERVER file_server OPTIONS (force_not_null '*'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (force_not_null '*'); -- ERROR -- force_null is not allowed to be specified at any foreign object level: ALTER FOREIGN DATA WRAPPER file_fdw OPTIONS (ADD force_null '*'); -- ERROR ALTER SERVER file_server OPTIONS (ADD force_null '*'); -- ERROR CREATE USER MAPPING FOR public SERVER file_server OPTIONS (force_null '*'); -- ERROR CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (force_null '*'); -- ERROR -- basic query tests SELECT * FROM agg_text WHERE b > 10.0 ORDER BY a; SELECT * FROM agg_csv ORDER BY a; SELECT * FROM agg_csv c JOIN agg_text t ON (t.a = c.a) ORDER BY c.a; -- error context report tests SELECT * FROM agg_bad; -- ERROR -- on_error, log_verbosity and reject_limit tests ALTER FOREIGN TABLE agg_bad OPTIONS (ADD on_error 'ignore'); SELECT * FROM agg_bad; ALTER FOREIGN TABLE agg_bad OPTIONS (ADD log_verbosity 'silent'); SELECT * FROM agg_bad; ALTER FOREIGN TABLE agg_bad OPTIONS (ADD reject_limit '1'); -- ERROR SELECT * FROM agg_bad; ALTER FOREIGN TABLE agg_bad OPTIONS (SET reject_limit '2'); SELECT * FROM agg_bad; ANALYZE agg_bad; -- misc query tests \t on SELECT explain_filter('EXPLAIN (VERBOSE, COSTS FALSE) SELECT * FROM agg_csv'); \t off PREPARE st(int) AS SELECT * FROM agg_csv WHERE a = $1; EXECUTE st(100); EXECUTE st(100); DEALLOCATE st; -- tableoid SELECT tableoid::regclass, b FROM agg_csv; -- updates aren't supported INSERT INTO agg_csv VALUES(1,2.0); UPDATE agg_csv SET a = 1; DELETE FROM agg_csv WHERE a = 100; TRUNCATE agg_csv; -- but this should be allowed SELECT * FROM agg_csv FOR UPDATE; -- copy from isn't supported either COPY agg_csv FROM STDIN; 12 3.4 \. -- constraint exclusion tests \t on SELECT explain_filter('EXPLAIN (VERBOSE, COSTS FALSE) SELECT * FROM agg_csv WHERE a < 0'); \t off SELECT * FROM agg_csv WHERE a < 0; SET constraint_exclusion = 'on'; \t on SELECT explain_filter('EXPLAIN (VERBOSE, COSTS FALSE) SELECT * FROM agg_csv WHERE a < 0'); \t off SELECT * FROM agg_csv WHERE a < 0; RESET constraint_exclusion; -- table inheritance tests CREATE TABLE agg (a int2, b float4); ALTER FOREIGN TABLE agg_csv INHERIT agg; SELECT tableoid::regclass, * FROM agg; SELECT tableoid::regclass, * FROM agg_csv; SELECT tableoid::regclass, * FROM ONLY agg; -- updates aren't supported UPDATE agg SET a = 1; DELETE FROM agg WHERE a = 100; -- but this should be allowed SELECT tableoid::regclass, * FROM agg FOR UPDATE; ALTER FOREIGN TABLE agg_csv NO INHERIT agg; DROP TABLE agg; -- declarative partitioning tests SET ROLE regress_file_fdw_superuser; CREATE TABLE pt (a int, b text) partition by list (a); \set filename :abs_srcdir '/data/list1.csv' CREATE FOREIGN TABLE p1 partition of pt for values in (1) SERVER file_server OPTIONS (format 'csv', filename :'filename', delimiter ','); CREATE TABLE p2 partition of pt for values in (2); SELECT tableoid::regclass, * FROM pt; SELECT tableoid::regclass, * FROM p1; SELECT tableoid::regclass, * FROM p2; \set filename :abs_srcdir '/data/list2.bad' COPY pt FROM :'filename' with (format 'csv', delimiter ','); -- ERROR \set filename :abs_srcdir '/data/list2.csv' COPY pt FROM :'filename' with (format 'csv', delimiter ','); SELECT tableoid::regclass, * FROM pt; SELECT tableoid::regclass, * FROM p1; SELECT tableoid::regclass, * FROM p2; INSERT INTO pt VALUES (1, 'xyzzy'); -- ERROR INSERT INTO pt VALUES (2, 'xyzzy'); UPDATE pt set a = 1 where a = 2; -- ERROR SELECT tableoid::regclass, * FROM pt; SELECT tableoid::regclass, * FROM p1; SELECT tableoid::regclass, * FROM p2; -- Test DELETE/UPDATE/MERGE on a partitioned table when all partitions -- are excluded and only the dummy root result relation remains. The -- operation is a no-op but should not fail regardless of whether the -- foreign child was processed (pruning off) or not (pruning on). DROP TABLE p2; SET enable_partition_pruning TO off; DELETE FROM pt WHERE false; UPDATE pt SET b = 'x' WHERE false; MERGE INTO pt t USING (VALUES (1, 'x'::text)) AS s(a, b) ON false WHEN MATCHED THEN UPDATE SET b = s.b; SET enable_partition_pruning TO on; DELETE FROM pt WHERE false; UPDATE pt SET b = 'x' WHERE false; MERGE INTO pt t USING (VALUES (1, 'x'::text)) AS s(a, b) ON false WHEN MATCHED THEN UPDATE SET b = s.b; DROP TABLE pt; -- generated column tests \set filename :abs_srcdir '/data/list1.csv' CREATE FOREIGN TABLE gft1 (a int, b text, c text GENERATED ALWAYS AS ('foo') STORED) SERVER file_server OPTIONS (format 'csv', filename :'filename', delimiter ','); SELECT a, c FROM gft1; DROP FOREIGN TABLE gft1; -- copy default tests \set filename :abs_srcdir '/data/copy_default.csv' CREATE FOREIGN TABLE copy_default ( id integer, text_value text not null default 'test', ts_value timestamp without time zone not null default '2022-07-05' ) SERVER file_server OPTIONS (format 'csv', filename :'filename', default '\D'); SELECT id, text_value, ts_value FROM copy_default; DROP FOREIGN TABLE copy_default; -- privilege tests SET ROLE regress_file_fdw_superuser; SELECT * FROM agg_text ORDER BY a; SET ROLE regress_file_fdw_user; SELECT * FROM agg_text ORDER BY a; SET ROLE regress_no_priv_user; SELECT * FROM agg_text ORDER BY a; -- ERROR SET ROLE regress_file_fdw_user; \t on SELECT explain_filter('EXPLAIN (VERBOSE, COSTS FALSE) SELECT * FROM agg_text WHERE a > 0'); \t off -- file FDW allows foreign tables to be accessed without user mapping DROP USER MAPPING FOR regress_file_fdw_user SERVER file_server; SELECT * FROM agg_text ORDER BY a; -- privilege tests for object SET ROLE regress_file_fdw_superuser; ALTER FOREIGN TABLE agg_text OWNER TO regress_file_fdw_user; ALTER FOREIGN TABLE agg_text OPTIONS (SET format 'text'); SET ROLE regress_file_fdw_user; ALTER FOREIGN TABLE agg_text OPTIONS (SET format 'text'); SET ROLE regress_file_fdw_superuser; -- cleanup RESET ROLE; DROP EXTENSION file_fdw CASCADE; DROP ROLE regress_file_fdw_superuser, regress_file_fdw_user, regress_no_priv_user;
sql
github
https://github.com/postgres/postgres
contrib/file_fdw/sql/file_fdw.sql
""" Fantasm: A taskqueue-based Finite State Machine for App Engine Python Docs and examples: http://code.google.com/p/fantasm/ Copyright 2010 VendAsta Technologies 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. """ import time import logging import simplejson from google.appengine.ext import deferred, webapp, db from google.appengine.api.capabilities import CapabilitySet from fantasm import config, constants from fantasm.fsm import FSM from fantasm.utils import NoOpQueue from fantasm.constants import NON_CONTEXT_PARAMS, STATE_PARAM, EVENT_PARAM, INSTANCE_NAME_PARAM, TASK_NAME_PARAM, \ RETRY_COUNT_PARAM, STARTED_AT_PARAM, IMMEDIATE_MODE_PARAM, MESSAGES_PARAM, \ HTTP_REQUEST_HEADER_PREFIX from fantasm.exceptions import UnknownMachineError, RequiredServicesUnavailableRuntimeError, FSMRuntimeError from fantasm.models import _FantasmTaskSemaphore, Encoder, _FantasmFanIn from fantasm.lock import RunOnceSemaphore REQUIRED_SERVICES = ('memcache', 'datastore_v3', 'taskqueue') class TemporaryStateObject(dict): """ A simple object that is passed throughout a machine dispatch that can hold temporary in-flight data. """ pass def getMachineNameFromRequest(request): """ Returns the machine name embedded in the request. @param request: an HttpRequest @return: the machineName (as a string) """ path = request.path # strip off the mount-point currentConfig = config.currentConfiguration() mountPoint = currentConfig.rootUrl # e.g., '/fantasm/' if not path.startswith(mountPoint): raise FSMRuntimeError("rootUrl '%s' must match app.yaml mapping." % mountPoint) path = path[len(mountPoint):] # split on '/', the second item will be the machine name parts = path.split('/') return parts[1] # 0-based index def getMachineConfig(request): """ Returns the machine configuration specified by a URI in a HttpReuest @param request: an HttpRequest @return: a config._machineConfig instance """ # parse out the machine-name from the path {mount-point}/fsm/{machine-name}/startState/event/endState/ # NOTE: /startState/event/endState/ is optional machineName = getMachineNameFromRequest(request) # load the configuration, lookup the machine-specific configuration # FIXME: sort out a module level cache for the configuration - it must be sensitive to YAML file changes # for developer-time experience currentConfig = config.currentConfiguration() try: machineConfig = currentConfig.machines[machineName] return machineConfig except KeyError: raise UnknownMachineError(machineName) class FSMLogHandler(webapp.RequestHandler): """ The handler used for logging """ def post(self): """ Runs the serialized function """ deferred.run(self.request.body) class FSMFanInCleanupHandler(webapp.RequestHandler): """ The handler used for logging """ def post(self): """ Runs the serialized function """ q = _FantasmFanIn.all().filter('workIndex =', self.request.POST[constants.WORK_INDEX_PARAM]) db.delete(q) class FSMGraphvizHandler(webapp.RequestHandler): """ The hander to output graphviz diagram of the finite state machine. """ def get(self): """ Handles the GET request. """ from fantasm.utils import outputMachineConfig machineConfig = getMachineConfig(self.request) content = outputMachineConfig(machineConfig, skipStateNames=[self.request.GET.get('skipStateName')]) if self.request.GET.get('type', 'png') == 'png': self.response.out.write( """ <html> <head></head> <body onload="javascript:document.forms.chartform.submit();"> <form id='chartform' action='http://chart.apis.google.com/chart' method='POST'> <input type="hidden" name="cht" value="gv:dot" /> <input type="hidden" name="chl" value='%(chl)s' /> <input type="submit" value="Generate GraphViz .png" /> </form> </body> """ % {'chl': content.replace('\n', ' ')}) else: self.response.out.write(content) _fsm = None def getCurrentFSM(): """ Returns the current FSM singleton. """ # W0603: 32:currentConfiguration: Using the global statement global _fsm # pylint: disable-msg=W0603 # always reload the FSM for dev_appserver to grab recent dev changes if _fsm and not constants.DEV_APPSERVER: return _fsm currentConfig = config.currentConfiguration() _fsm = FSM(currentConfig=currentConfig) return _fsm class FSMHandler(webapp.RequestHandler): """ The main worker handler, used to process queued machine events. """ def get(self): """ Handles the GET request. """ self.get_or_post(method='GET') def post(self): """ Handles the POST request. """ self.get_or_post(method='POST') def initialize(self, request, response): """Initializes this request handler with the given Request and Response.""" super(FSMHandler, self).initialize(request, response) # pylint: disable-msg=W0201 # - this is the preferred location to initialize the handler in the webapp framework self.fsm = None def handle_exception(self, exception, debug_mode): # pylint: disable-msg=C0103 """ Delegates logging to the FSMContext logger """ self.error(500) logger = logging if self.fsm: logger = self.fsm.logger logger.exception("FSMHandler caught Exception") if debug_mode: import traceback, sys, cgi lines = ''.join(traceback.format_exception(*sys.exc_info())) self.response.clear() self.response.out.write('<pre>%s</pre>' % (cgi.escape(lines, quote=True))) def get_or_post(self, method='POST'): """ Handles the GET/POST request. FIXME: this is getting a touch long """ # ensure that we have our services for the next 30s (length of a single request) unavailable = set() for service in REQUIRED_SERVICES: if not CapabilitySet(service).is_enabled(): unavailable.add(service) if unavailable: raise RequiredServicesUnavailableRuntimeError(unavailable) # the case of headers is inconsistent on dev_appserver and appengine # ie 'X-AppEngine-TaskRetryCount' vs. 'X-AppEngine-Taskretrycount' lowerCaseHeaders = dict([(key.lower(), value) for key, value in self.request.headers.items()]) taskName = lowerCaseHeaders.get('x-appengine-taskname') retryCount = int(lowerCaseHeaders.get('x-appengine-taskretrycount', 0)) # Taskqueue can invoke multiple tasks of the same name occassionally. Here, we'll use # a datastore transaction as a semaphore to determine if we should actually execute this or not. if taskName: semaphoreKey = '%s--%s' % (taskName, retryCount) semaphore = RunOnceSemaphore(semaphoreKey, None) if not semaphore.writeRunOnceSemaphore(payload='fantasm')[0]: # we can simply return here, this is a duplicate fired task logging.info('A duplicate task "%s" has been queued by taskqueue infrastructure. Ignoring.', taskName) self.response.status_code = 200 return # pull out X-Fantasm-* headers headers = None for key, value in self.request.headers.items(): if key.startswith(HTTP_REQUEST_HEADER_PREFIX): headers = headers or {} if ',' in value: headers[key] = [v.strip() for v in value.split(',')] else: headers[key] = value.strip() requestData = {'POST': self.request.POST, 'GET': self.request.GET}[method] method = requestData.get('method') or method machineName = getMachineNameFromRequest(self.request) # get the incoming instance name, if any instanceName = requestData.get(INSTANCE_NAME_PARAM) # get the incoming state, if any fsmState = requestData.get(STATE_PARAM) # get the incoming event, if any fsmEvent = requestData.get(EVENT_PARAM) assert (fsmState and instanceName) or True # if we have a state, we should have an instanceName assert (fsmState and fsmEvent) or True # if we have a state, we should have an event obj = TemporaryStateObject() # make a copy, add the data fsm = getCurrentFSM().createFSMInstance(machineName, currentStateName=fsmState, instanceName=instanceName, method=method, obj=obj, headers=headers) # in "immediate mode" we try to execute as much as possible in the current request # for the time being, this does not include things like fork/spawn/contuniuations/fan-in immediateMode = IMMEDIATE_MODE_PARAM in requestData.keys() if immediateMode: obj[IMMEDIATE_MODE_PARAM] = immediateMode obj[MESSAGES_PARAM] = [] fsm.Queue = NoOpQueue # don't queue anything else # pylint: disable-msg=W0201 # - initialized outside of ctor is ok in this case self.fsm = fsm # used for logging in handle_exception # pull all the data off the url and stuff into the context for key, value in requestData.items(): if key in NON_CONTEXT_PARAMS: continue # these are special, don't put them in the data # deal with ...a=1&a=2&a=3... value = requestData.get(key) valueList = requestData.getall(key) if len(valueList) > 1: value = valueList if key.endswith('[]'): key = key[:-2] value = [value] if key in fsm.contextTypes.keys(): fsm.putTypedValue(key, value) else: fsm[key] = value if not (fsmState or fsmEvent): # just queue up a task to run the initial state transition using retries fsm[STARTED_AT_PARAM] = time.time() # initialize the fsm, which returns the 'pseudo-init' event fsmEvent = fsm.initialize() else: # add the retry counter into the machine context from the header obj[RETRY_COUNT_PARAM] = retryCount # add the actual task name to the context obj[TASK_NAME_PARAM] = taskName # dispatch and return the next event fsmEvent = fsm.dispatch(fsmEvent, obj) # loop and execute until there are no more events - any exceptions # will make it out to the user in the response - useful for debugging if immediateMode: while fsmEvent: fsmEvent = fsm.dispatch(fsmEvent, obj) self.response.headers['Content-Type'] = 'application/json' data = { 'obj' : obj, 'context': fsm, } self.response.out.write(simplejson.dumps(data, cls=Encoder))
unknown
codeparrot/codeparrot-clean
""" Model used by Video module for Branding configuration. Includes: BrandingInfoConfig: A ConfigurationModel for managing how Video Module will use Branding. """ import json from config_models.models import ConfigurationModel from django.core.exceptions import ValidationError from django.db.models import TextField class BrandingInfoConfig(ConfigurationModel): """ Configuration for Branding. Example of configuration that must be stored: { "CN": { "url": "http://www.xuetangx.com", "logo_src": "http://www.xuetangx.com/static/images/logo.png", "logo_tag": "Video hosted by XuetangX.com" } } """ class Meta(ConfigurationModel.Meta): app_label = "branding" configuration = TextField( help_text="JSON data of Configuration for Video Branding." ) def clean(self): """ Validates configuration text field. """ try: json.loads(self.configuration) except ValueError: raise ValidationError('Must be valid JSON string.') @classmethod def get_config(cls): """ Get the Video Branding Configuration. """ info = cls.current() return json.loads(info.configuration) if info.enabled else {} class BrandingApiConfig(ConfigurationModel): """Configure Branding api's Enable or disable api's functionality. When this flag is disabled, the api will return 404. When the flag is enabled, the api will returns the valid reponse. """ class Meta(ConfigurationModel.Meta): app_label = "branding"
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import analytic # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
unknown
codeparrot/codeparrot-clean
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Util; use Composer\IO\IOInterface; use Composer\Config; use Composer\Factory; use Composer\Downloader\TransportException; use Composer\Pcre\Preg; /** * @author Roshan Gautam <roshan.gautam@hotmail.com> */ class GitLab { /** @var IOInterface */ protected $io; /** @var Config */ protected $config; /** @var ProcessExecutor */ protected $process; /** @var HttpDownloader */ protected $httpDownloader; /** * Constructor. * * @param IOInterface $io The IO instance * @param Config $config The composer configuration * @param ProcessExecutor $process Process instance, injectable for mocking * @param HttpDownloader $httpDownloader Remote Filesystem, injectable for mocking */ public function __construct(IOInterface $io, Config $config, ?ProcessExecutor $process = null, ?HttpDownloader $httpDownloader = null) { $this->io = $io; $this->config = $config; $this->process = $process ?: new ProcessExecutor($io); $this->httpDownloader = $httpDownloader ?: Factory::createHttpDownloader($this->io, $config); } /** * Attempts to authorize a GitLab domain via OAuth. * * @param string $originUrl The host this GitLab instance is located at * * @return bool true on success */ public function authorizeOAuth(string $originUrl): bool { // before composer 1.9, origin URLs had no port number in them $bcOriginUrl = Preg::replace('{:\d+}', '', $originUrl); if (!in_array($originUrl, $this->config->get('gitlab-domains'), true) && !in_array($bcOriginUrl, $this->config->get('gitlab-domains'), true)) { return false; } // if available use token from git config if (0 === $this->process->execute(['git', 'config', 'gitlab.accesstoken'], $output)) { $this->io->setAuthentication($originUrl, trim($output), 'oauth2'); return true; } // if available use deploy token from git config if (0 === $this->process->execute(['git', 'config', 'gitlab.deploytoken.user'], $tokenUser) && 0 === $this->process->execute(['git', 'config', 'gitlab.deploytoken.token'], $tokenPassword)) { $this->io->setAuthentication($originUrl, trim($tokenUser), trim($tokenPassword)); return true; } // if available use token from composer config $authTokens = $this->config->get('gitlab-token'); if (isset($authTokens[$originUrl])) { $token = $authTokens[$originUrl]; } if (isset($authTokens[$bcOriginUrl])) { $token = $authTokens[$bcOriginUrl]; } if (isset($token)) { $username = is_array($token) ? $token["username"] : $token; $password = is_array($token) ? $token["token"] : 'private-token'; // Composer expects the GitLab token to be stored as username and 'private-token' or 'gitlab-ci-token' to be stored as password // Detect cases where this is reversed and resolve automatically resolve it if (in_array($username, ['private-token', 'gitlab-ci-token', 'oauth2'], true)) { $this->io->setAuthentication($originUrl, $password, $username); } else { $this->io->setAuthentication($originUrl, $username, $password); } return true; } return false; } /** * Authorizes a GitLab domain interactively via OAuth. * * @param string $scheme Scheme used in the origin URL * @param string $originUrl The host this GitLab instance is located at * @param string $message The reason this authorization is required * * @throws \RuntimeException * @throws TransportException|\Exception * * @return bool true on success */ public function authorizeOAuthInteractively(string $scheme, string $originUrl, ?string $message = null): bool { if ($message) { $this->io->writeError($message); } $localAuthConfig = $this->config->getLocalAuthConfigSource(); $personalAccessTokenLink = $scheme.'://'.$originUrl.'/-/user_settings/personal_access_tokens'; $revokeLink = $scheme.'://'.$originUrl.'/-/user_settings/applications'; $this->io->writeError(sprintf('A token will be created and stored in "%s", your password will never be stored', ($localAuthConfig !== null ? $localAuthConfig->getName() . ' OR ' : '') . $this->config->getAuthConfigSource()->getName())); $this->io->writeError('To revoke access to this token you can visit:'); $this->io->writeError($revokeLink); $this->io->writeError('Alternatively you can setup an personal access token on:'); $this->io->writeError($personalAccessTokenLink); $this->io->writeError('and store it under "gitlab-token" see https://getcomposer.org/doc/articles/authentication-for-private-packages.md#gitlab-token for more details.'); $this->io->writeError('https://getcomposer.org/doc/articles/authentication-for-private-packages.md#gitlab-token'); $this->io->writeError('for more details.'); $storeInLocalAuthConfig = false; if ($localAuthConfig !== null) { $storeInLocalAuthConfig = $this->io->askConfirmation('A local auth config source was found, do you want to store the token there?', true); } $attemptCounter = 0; while ($attemptCounter++ < 5) { try { $response = $this->createToken($scheme, $originUrl); } catch (TransportException $e) { // 401 is bad credentials, // 403 is max login attempts exceeded if (in_array($e->getCode(), [403, 401])) { if (401 === $e->getCode()) { $response = json_decode($e->getResponse(), true); if (isset($response['error']) && $response['error'] === 'invalid_grant') { $this->io->writeError('Bad credentials. If you have two factor authentication enabled you will have to manually create a personal access token'); } else { $this->io->writeError('Bad credentials.'); } } else { $this->io->writeError('Maximum number of login attempts exceeded. Please try again later.'); } $this->io->writeError('You can also manually create a personal access token enabling the "read_api" scope at:'); $this->io->writeError($personalAccessTokenLink); $this->io->writeError('Add it using "composer config --global --auth gitlab-token.'.$originUrl.' <token>"'); continue; } throw $e; } $this->io->setAuthentication($originUrl, $response['access_token'], 'oauth2'); $authConfigSource = $storeInLocalAuthConfig && $localAuthConfig !== null ? $localAuthConfig : $this->config->getAuthConfigSource(); // store value in user config in auth file if (isset($response['expires_in'])) { $authConfigSource->addConfigSetting( 'gitlab-oauth.'.$originUrl, [ 'expires-at' => intval($response['created_at']) + intval($response['expires_in']), 'refresh-token' => $response['refresh_token'], 'token' => $response['access_token'], ] ); } else { $authConfigSource->addConfigSetting('gitlab-oauth.'.$originUrl, $response['access_token']); } return true; } throw new \RuntimeException('Invalid GitLab credentials 5 times in a row, aborting.'); } /** * Authorizes a GitLab domain interactively via OAuth. * * @param string $scheme Scheme used in the origin URL * @param string $originUrl The host this GitLab instance is located at * * @throws \RuntimeException * @throws TransportException|\Exception * * @return bool true on success */ public function authorizeOAuthRefresh(string $scheme, string $originUrl): bool { try { $response = $this->refreshToken($scheme, $originUrl); } catch (TransportException $e) { $this->io->writeError("Couldn't refresh access token: ".$e->getMessage()); return false; } $this->io->setAuthentication($originUrl, $response['access_token'], 'oauth2'); // store value in user config in auth file $this->config->getAuthConfigSource()->addConfigSetting( 'gitlab-oauth.'.$originUrl, [ 'expires-at' => intval($response['created_at']) + intval($response['expires_in']), 'refresh-token' => $response['refresh_token'], 'token' => $response['access_token'], ] ); return true; } /** * @return array{access_token: non-empty-string, refresh_token: non-empty-string, token_type: non-empty-string, expires_in?: positive-int, created_at: positive-int} * * @see https://docs.gitlab.com/ee/api/oauth2.html#resource-owner-password-credentials-flow */ private function createToken(string $scheme, string $originUrl): array { $username = $this->io->ask('Username: '); $password = $this->io->askAndHideAnswer('Password: '); $headers = ['Content-Type: application/x-www-form-urlencoded']; $apiUrl = $originUrl; $data = http_build_query([ 'username' => $username, 'password' => $password, 'grant_type' => 'password', ], '', '&'); $options = [ 'retry-auth-failure' => false, 'http' => [ 'method' => 'POST', 'header' => $headers, 'content' => $data, ], ]; $token = $this->httpDownloader->get($scheme.'://'.$apiUrl.'/oauth/token', $options)->decodeJson(); $this->io->writeError('Token successfully created'); return $token; } /** * Is the OAuth access token expired? * * @return bool true on expired token, false if token is fresh or expiration date is not set */ public function isOAuthExpired(string $originUrl): bool { $authTokens = $this->config->get('gitlab-oauth'); if (isset($authTokens[$originUrl]['expires-at'])) { if ($authTokens[$originUrl]['expires-at'] < time()) { return true; } } return false; } /** * @return array{access_token: non-empty-string, refresh_token: non-empty-string, token_type: non-empty-string, expires_in: positive-int, created_at: positive-int} * * @see https://docs.gitlab.com/ee/api/oauth2.html#resource-owner-password-credentials-flow */ private function refreshToken(string $scheme, string $originUrl): array { $authTokens = $this->config->get('gitlab-oauth'); if (!isset($authTokens[$originUrl]['refresh-token'])) { throw new \RuntimeException('No GitLab refresh token present for '.$originUrl.'.'); } $refreshToken = $authTokens[$originUrl]['refresh-token']; $headers = ['Content-Type: application/x-www-form-urlencoded']; $data = http_build_query([ 'refresh_token' => $refreshToken, 'grant_type' => 'refresh_token', ], '', '&'); $options = [ 'retry-auth-failure' => false, 'http' => [ 'method' => 'POST', 'header' => $headers, 'content' => $data, ], ]; $token = $this->httpDownloader->get($scheme.'://'.$originUrl.'/oauth/token', $options)->decodeJson(); $this->io->writeError('GitLab token successfully refreshed', true, IOInterface::VERY_VERBOSE); $this->io->writeError('To revoke access to this token you can visit '.$scheme.'://'.$originUrl.'/-/user_settings/applications', true, IOInterface::VERY_VERBOSE); return $token; } }
php
github
https://github.com/composer/composer
src/Composer/Util/GitLab.php
/* * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.sockets import io.ktor.network.selector.* import io.ktor.network.sockets.nodejs.* import kotlinx.coroutines.* internal actual suspend fun tcpConnect( selector: SelectorManager, remoteAddress: SocketAddress, socketOptions: SocketOptions.TCPClientSocketOptions ): Socket = suspendCancellableCoroutine { cont -> val socket = nodeNet.createConnection(CreateConnectionOptions(remoteAddress, socketOptions)) SocketContext(socket, remoteAddress, null).initiate(cont) } internal actual suspend fun tcpBind( selector: SelectorManager, localAddress: SocketAddress?, socketOptions: SocketOptions.AcceptorOptions ): ServerSocket = suspendCancellableCoroutine { cont -> val server = nodeNet.createServer(CreateServerOptions {}) ServerSocketContext(server, localAddress, null).initiate(cont) } internal actual suspend fun udpConnect( selector: SelectorManager, remoteAddress: SocketAddress, localAddress: SocketAddress?, options: SocketOptions.UDPSocketOptions ): ConnectedDatagramSocket = error("UDP sockets are unsupported on WASM/JS") internal actual suspend fun udpBind( selector: SelectorManager, localAddress: SocketAddress?, options: SocketOptions.UDPSocketOptions ): BoundDatagramSocket = error("UDP sockets are unsupported on WASM/JS")
kotlin
github
https://github.com/ktorio/ktor
ktor-network/web/src/io/ktor/network/sockets/SocketEngine.web.kt
//// [tests/cases/conformance/async/es5/functionDeclarations/asyncFunctionDeclaration13_es5.ts] //// //// [asyncFunctionDeclaration13_es5.ts] async function foo(): Promise<void> { // Legal to use 'await' in a type context. var v: await; } //// [asyncFunctionDeclaration13_es5.js] "use strict"; function foo() { return __awaiter(this, void 0, void 0, function* () { // Legal to use 'await' in a type context. var v; }); }
javascript
github
https://github.com/microsoft/TypeScript
tests/baselines/reference/asyncFunctionDeclaration13_es5(target=es2015).js
/* * 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. */ package org.apache.hadoop.io.compress; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.io.compress.zstd.ZStandardCompressor; import org.apache.hadoop.io.compress.zstd.ZStandardDecompressor; import org.apache.hadoop.util.NativeCodeLoader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static org.apache.hadoop.fs.CommonConfigurationKeys.IO_COMPRESSION_CODEC_ZSTD_BUFFER_SIZE_DEFAULT; import static org.apache.hadoop.fs.CommonConfigurationKeys.IO_COMPRESSION_CODEC_ZSTD_BUFFER_SIZE_KEY; /** * This class creates zstd compressors/decompressors. */ public class ZStandardCodec implements Configurable, CompressionCodec, DirectDecompressionCodec { private Configuration conf; /** * Set the configuration to be used by this object. * * @param conf the configuration object. */ @Override public void setConf(Configuration conf) { this.conf = conf; } /** * Return the configuration used by this object. * * @return the configuration object used by this object. */ @Override public Configuration getConf() { return conf; } public static void checkNativeCodeLoaded() { if (!NativeCodeLoader.isNativeCodeLoaded() || !NativeCodeLoader.buildSupportsZstd()) { throw new RuntimeException("native zStandard library " + "not available: this version of libhadoop was built " + "without zstd support."); } if (!ZStandardCompressor.isNativeCodeLoaded()) { throw new RuntimeException("native zStandard library not " + "available: ZStandardCompressor has not been loaded."); } if (!ZStandardDecompressor.isNativeCodeLoaded()) { throw new RuntimeException("native zStandard library not " + "available: ZStandardDecompressor has not been loaded."); } } public static boolean isNativeCodeLoaded() { return ZStandardCompressor.isNativeCodeLoaded() && ZStandardDecompressor.isNativeCodeLoaded(); } public static String getLibraryName() { return ZStandardCompressor.getLibraryName(); } public static int getCompressionLevel(Configuration conf) { return conf.getInt( CommonConfigurationKeys.IO_COMPRESSION_CODEC_ZSTD_LEVEL_KEY, CommonConfigurationKeys.IO_COMPRESSION_CODEC_ZSTD_LEVEL_DEFAULT); } public static int getCompressionBufferSize(Configuration conf) { int bufferSize = getBufferSize(conf); return bufferSize == 0 ? ZStandardCompressor.getRecommendedBufferSize() : bufferSize; } public static int getDecompressionBufferSize(Configuration conf) { int bufferSize = getBufferSize(conf); return bufferSize == 0 ? ZStandardDecompressor.getRecommendedBufferSize() : bufferSize; } private static int getBufferSize(Configuration conf) { return conf.getInt(IO_COMPRESSION_CODEC_ZSTD_BUFFER_SIZE_KEY, IO_COMPRESSION_CODEC_ZSTD_BUFFER_SIZE_DEFAULT); } /** * Create a {@link CompressionOutputStream} that will write to the given * {@link OutputStream}. * * @param out the location for the final output stream * @return a stream the user can write uncompressed data to have compressed * @throws IOException raised on errors performing I/O. */ @Override public CompressionOutputStream createOutputStream(OutputStream out) throws IOException { return Util. createOutputStreamWithCodecPool(this, conf, out); } /** * Create a {@link CompressionOutputStream} that will write to the given * {@link OutputStream} with the given {@link Compressor}. * * @param out the location for the final output stream * @param compressor compressor to use * @return a stream the user can write uncompressed data to have compressed * @throws IOException raised on errors performing I/O. */ @Override public CompressionOutputStream createOutputStream(OutputStream out, Compressor compressor) throws IOException { checkNativeCodeLoaded(); return new CompressorStream(out, compressor, getCompressionBufferSize(conf)); } /** * Get the type of {@link Compressor} needed by this {@link CompressionCodec}. * * @return the type of compressor needed by this codec. */ @Override public Class<? extends Compressor> getCompressorType() { checkNativeCodeLoaded(); return ZStandardCompressor.class; } /** * Create a new {@link Compressor} for use by this {@link CompressionCodec}. * * @return a new compressor for use by this codec */ @Override public Compressor createCompressor() { checkNativeCodeLoaded(); return new ZStandardCompressor( getCompressionLevel(conf), getCompressionBufferSize(conf)); } /** * Create a {@link CompressionInputStream} that will read from the given * input stream. * * @param in the stream to read compressed bytes from * @return a stream to read uncompressed bytes from * @throws IOException raised on errors performing I/O. */ @Override public CompressionInputStream createInputStream(InputStream in) throws IOException { return Util. createInputStreamWithCodecPool(this, conf, in); } /** * Create a {@link CompressionInputStream} that will read from the given * {@link InputStream} with the given {@link Decompressor}. * * @param in the stream to read compressed bytes from * @param decompressor decompressor to use * @return a stream to read uncompressed bytes from * @throws IOException raised on errors performing I/O. */ @Override public CompressionInputStream createInputStream(InputStream in, Decompressor decompressor) throws IOException { checkNativeCodeLoaded(); return new DecompressorStream(in, decompressor, getDecompressionBufferSize(conf)); } /** * Get the type of {@link Decompressor} needed by * this {@link CompressionCodec}. * * @return the type of decompressor needed by this codec. */ @Override public Class<? extends Decompressor> getDecompressorType() { checkNativeCodeLoaded(); return ZStandardDecompressor.class; } /** * Create a new {@link Decompressor} for use by this {@link CompressionCodec}. * * @return a new decompressor for use by this codec */ @Override public Decompressor createDecompressor() { checkNativeCodeLoaded(); return new ZStandardDecompressor(getDecompressionBufferSize(conf)); } /** * Get the default filename extension for this kind of compression. * * @return <code>.zst</code>. */ @Override public String getDefaultExtension() { return CodecConstants.ZSTANDARD_CODEC_EXTENSION; } @Override public DirectDecompressor createDirectDecompressor() { return new ZStandardDecompressor.ZStandardDirectDecompressor( getDecompressionBufferSize(conf) ); } }
java
github
https://github.com/apache/hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/ZStandardCodec.java
/* * Copyright (C) Nginx, Inc. * Copyright (C) Valentin V. Bartenev */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #define NGX_HTTP_V2_TABLE_SIZE 4096 static ngx_int_t ngx_http_v2_table_account(ngx_http_v2_connection_t *h2c, size_t size); static ngx_http_v2_header_t ngx_http_v2_static_table[] = { { ngx_string(":authority"), ngx_string("") }, { ngx_string(":method"), ngx_string("GET") }, { ngx_string(":method"), ngx_string("POST") }, { ngx_string(":path"), ngx_string("/") }, { ngx_string(":path"), ngx_string("/index.html") }, { ngx_string(":scheme"), ngx_string("http") }, { ngx_string(":scheme"), ngx_string("https") }, { ngx_string(":status"), ngx_string("200") }, { ngx_string(":status"), ngx_string("204") }, { ngx_string(":status"), ngx_string("206") }, { ngx_string(":status"), ngx_string("304") }, { ngx_string(":status"), ngx_string("400") }, { ngx_string(":status"), ngx_string("404") }, { ngx_string(":status"), ngx_string("500") }, { ngx_string("accept-charset"), ngx_string("") }, { ngx_string("accept-encoding"), ngx_string("gzip, deflate") }, { ngx_string("accept-language"), ngx_string("") }, { ngx_string("accept-ranges"), ngx_string("") }, { ngx_string("accept"), ngx_string("") }, { ngx_string("access-control-allow-origin"), ngx_string("") }, { ngx_string("age"), ngx_string("") }, { ngx_string("allow"), ngx_string("") }, { ngx_string("authorization"), ngx_string("") }, { ngx_string("cache-control"), ngx_string("") }, { ngx_string("content-disposition"), ngx_string("") }, { ngx_string("content-encoding"), ngx_string("") }, { ngx_string("content-language"), ngx_string("") }, { ngx_string("content-length"), ngx_string("") }, { ngx_string("content-location"), ngx_string("") }, { ngx_string("content-range"), ngx_string("") }, { ngx_string("content-type"), ngx_string("") }, { ngx_string("cookie"), ngx_string("") }, { ngx_string("date"), ngx_string("") }, { ngx_string("etag"), ngx_string("") }, { ngx_string("expect"), ngx_string("") }, { ngx_string("expires"), ngx_string("") }, { ngx_string("from"), ngx_string("") }, { ngx_string("host"), ngx_string("") }, { ngx_string("if-match"), ngx_string("") }, { ngx_string("if-modified-since"), ngx_string("") }, { ngx_string("if-none-match"), ngx_string("") }, { ngx_string("if-range"), ngx_string("") }, { ngx_string("if-unmodified-since"), ngx_string("") }, { ngx_string("last-modified"), ngx_string("") }, { ngx_string("link"), ngx_string("") }, { ngx_string("location"), ngx_string("") }, { ngx_string("max-forwards"), ngx_string("") }, { ngx_string("proxy-authenticate"), ngx_string("") }, { ngx_string("proxy-authorization"), ngx_string("") }, { ngx_string("range"), ngx_string("") }, { ngx_string("referer"), ngx_string("") }, { ngx_string("refresh"), ngx_string("") }, { ngx_string("retry-after"), ngx_string("") }, { ngx_string("server"), ngx_string("") }, { ngx_string("set-cookie"), ngx_string("") }, { ngx_string("strict-transport-security"), ngx_string("") }, { ngx_string("transfer-encoding"), ngx_string("") }, { ngx_string("user-agent"), ngx_string("") }, { ngx_string("vary"), ngx_string("") }, { ngx_string("via"), ngx_string("") }, { ngx_string("www-authenticate"), ngx_string("") }, }; #define NGX_HTTP_V2_STATIC_TABLE_ENTRIES \ (sizeof(ngx_http_v2_static_table) \ / sizeof(ngx_http_v2_header_t)) ngx_str_t * ngx_http_v2_get_static_name(ngx_uint_t index) { return &ngx_http_v2_static_table[index - 1].name; } ngx_str_t * ngx_http_v2_get_static_value(ngx_uint_t index) { return &ngx_http_v2_static_table[index - 1].value; } ngx_int_t ngx_http_v2_get_indexed_header(ngx_http_v2_connection_t *h2c, ngx_uint_t index, ngx_uint_t name_only) { u_char *p; size_t rest; ngx_http_v2_header_t *entry; if (index == 0) { ngx_log_error(NGX_LOG_INFO, h2c->connection->log, 0, "client sent invalid hpack table index 0"); return NGX_ERROR; } ngx_log_debug2(NGX_LOG_DEBUG_HTTP, h2c->connection->log, 0, "http2 get indexed %s: %ui", name_only ? "name" : "header", index); index--; if (index < NGX_HTTP_V2_STATIC_TABLE_ENTRIES) { h2c->state.header = ngx_http_v2_static_table[index]; return NGX_OK; } index -= NGX_HTTP_V2_STATIC_TABLE_ENTRIES; if (index < h2c->hpack.added - h2c->hpack.deleted) { index = (h2c->hpack.added - index - 1) % h2c->hpack.allocated; entry = h2c->hpack.entries[index]; p = ngx_pnalloc(h2c->state.pool, entry->name.len + 1); if (p == NULL) { return NGX_ERROR; } h2c->state.header.name.len = entry->name.len; h2c->state.header.name.data = p; rest = h2c->hpack.storage + NGX_HTTP_V2_TABLE_SIZE - entry->name.data; if (entry->name.len > rest) { p = ngx_cpymem(p, entry->name.data, rest); p = ngx_cpymem(p, h2c->hpack.storage, entry->name.len - rest); } else { p = ngx_cpymem(p, entry->name.data, entry->name.len); } *p = '\0'; if (name_only) { return NGX_OK; } p = ngx_pnalloc(h2c->state.pool, entry->value.len + 1); if (p == NULL) { return NGX_ERROR; } h2c->state.header.value.len = entry->value.len; h2c->state.header.value.data = p; rest = h2c->hpack.storage + NGX_HTTP_V2_TABLE_SIZE - entry->value.data; if (entry->value.len > rest) { p = ngx_cpymem(p, entry->value.data, rest); p = ngx_cpymem(p, h2c->hpack.storage, entry->value.len - rest); } else { p = ngx_cpymem(p, entry->value.data, entry->value.len); } *p = '\0'; return NGX_OK; } ngx_log_error(NGX_LOG_INFO, h2c->connection->log, 0, "client sent out of bound hpack table index: %ui", index); return NGX_ERROR; } ngx_int_t ngx_http_v2_add_header(ngx_http_v2_connection_t *h2c, ngx_http_v2_header_t *header) { size_t avail; ngx_uint_t index; ngx_http_v2_header_t *entry, **entries; ngx_log_debug2(NGX_LOG_DEBUG_HTTP, h2c->connection->log, 0, "http2 table add: \"%V: %V\"", &header->name, &header->value); if (h2c->hpack.entries == NULL) { h2c->hpack.allocated = 64; h2c->hpack.size = NGX_HTTP_V2_TABLE_SIZE; h2c->hpack.free = NGX_HTTP_V2_TABLE_SIZE; h2c->hpack.entries = ngx_palloc(h2c->connection->pool, sizeof(ngx_http_v2_header_t *) * h2c->hpack.allocated); if (h2c->hpack.entries == NULL) { return NGX_ERROR; } h2c->hpack.storage = ngx_palloc(h2c->connection->pool, h2c->hpack.free); if (h2c->hpack.storage == NULL) { return NGX_ERROR; } h2c->hpack.pos = h2c->hpack.storage; } if (ngx_http_v2_table_account(h2c, header->name.len + header->value.len) != NGX_OK) { return NGX_OK; } if (h2c->hpack.reused == h2c->hpack.deleted) { entry = ngx_palloc(h2c->connection->pool, sizeof(ngx_http_v2_header_t)); if (entry == NULL) { return NGX_ERROR; } } else { entry = h2c->hpack.entries[h2c->hpack.reused++ % h2c->hpack.allocated]; } avail = h2c->hpack.storage + NGX_HTTP_V2_TABLE_SIZE - h2c->hpack.pos; entry->name.len = header->name.len; entry->name.data = h2c->hpack.pos; if (avail >= header->name.len) { h2c->hpack.pos = ngx_cpymem(h2c->hpack.pos, header->name.data, header->name.len); } else { ngx_memcpy(h2c->hpack.pos, header->name.data, avail); h2c->hpack.pos = ngx_cpymem(h2c->hpack.storage, header->name.data + avail, header->name.len - avail); avail = NGX_HTTP_V2_TABLE_SIZE; } avail -= header->name.len; entry->value.len = header->value.len; entry->value.data = h2c->hpack.pos; if (avail >= header->value.len) { h2c->hpack.pos = ngx_cpymem(h2c->hpack.pos, header->value.data, header->value.len); } else { ngx_memcpy(h2c->hpack.pos, header->value.data, avail); h2c->hpack.pos = ngx_cpymem(h2c->hpack.storage, header->value.data + avail, header->value.len - avail); } if (h2c->hpack.allocated == h2c->hpack.added - h2c->hpack.deleted) { entries = ngx_palloc(h2c->connection->pool, sizeof(ngx_http_v2_header_t *) * (h2c->hpack.allocated + 64)); if (entries == NULL) { return NGX_ERROR; } index = h2c->hpack.deleted % h2c->hpack.allocated; ngx_memcpy(entries, &h2c->hpack.entries[index], (h2c->hpack.allocated - index) * sizeof(ngx_http_v2_header_t *)); ngx_memcpy(&entries[h2c->hpack.allocated - index], h2c->hpack.entries, index * sizeof(ngx_http_v2_header_t *)); (void) ngx_pfree(h2c->connection->pool, h2c->hpack.entries); h2c->hpack.entries = entries; h2c->hpack.added = h2c->hpack.allocated; h2c->hpack.deleted = 0; h2c->hpack.reused = 0; h2c->hpack.allocated += 64; } h2c->hpack.entries[h2c->hpack.added++ % h2c->hpack.allocated] = entry; return NGX_OK; } static ngx_int_t ngx_http_v2_table_account(ngx_http_v2_connection_t *h2c, size_t size) { ngx_http_v2_header_t *entry; size += 32; ngx_log_debug2(NGX_LOG_DEBUG_HTTP, h2c->connection->log, 0, "http2 table account: %uz free:%uz", size, h2c->hpack.free); if (size <= h2c->hpack.free) { h2c->hpack.free -= size; return NGX_OK; } if (size > h2c->hpack.size) { h2c->hpack.deleted = h2c->hpack.added; h2c->hpack.free = h2c->hpack.size; return NGX_DECLINED; } do { entry = h2c->hpack.entries[h2c->hpack.deleted++ % h2c->hpack.allocated]; h2c->hpack.free += 32 + entry->name.len + entry->value.len; } while (size > h2c->hpack.free); h2c->hpack.free -= size; return NGX_OK; } ngx_int_t ngx_http_v2_table_size(ngx_http_v2_connection_t *h2c, size_t size) { ssize_t needed; ngx_http_v2_header_t *entry; if (size > NGX_HTTP_V2_TABLE_SIZE) { ngx_log_error(NGX_LOG_INFO, h2c->connection->log, 0, "client sent invalid table size update: %uz", size); return NGX_ERROR; } ngx_log_debug2(NGX_LOG_DEBUG_HTTP, h2c->connection->log, 0, "http2 new hpack table size: %uz was:%uz", size, h2c->hpack.size); needed = h2c->hpack.size - size; while (needed > (ssize_t) h2c->hpack.free) { entry = h2c->hpack.entries[h2c->hpack.deleted++ % h2c->hpack.allocated]; h2c->hpack.free += 32 + entry->name.len + entry->value.len; } h2c->hpack.size = size; h2c->hpack.free -= needed; return NGX_OK; }
c
github
https://github.com/nginx/nginx
src/http/v2/ngx_http_v2_table.c
# Copyright 2014-2015 MongoDB, 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. """Represent a response from the server.""" class Response(object): __slots__ = ('_data', '_address') def __init__(self, data, address): """Represent a response from the server. :Parameters: - `data`: Raw BSON bytes. - `address`: (host, port) of the source server. """ self._data = data self._address = address @property def data(self): """Server response's raw BSON bytes.""" return self._data @property def address(self): """(host, port) of the source server.""" return self._address class ExhaustResponse(Response): __slots__ = ('_socket_info', '_pool') def __init__(self, data, address, socket_info, pool): """Represent a response to an exhaust cursor's initial query. :Parameters: - `data`: Raw BSON bytes. - `address`: (host, port) of the source server. - `socket_info`: The SocketInfo used for the initial query. - `pool`: The Pool from which the SocketInfo came. """ super(ExhaustResponse, self).__init__(data, address) self._socket_info = socket_info self._pool = pool @property def socket_info(self): """The SocketInfo used for the initial query. The server will send batches on this socket, without waiting for getMores from the client, until the result set is exhausted or there is an error. """ return self._socket_info @property def pool(self): """The Pool from which the SocketInfo came.""" return self._pool
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- import decimal import json import logging import re import arrow import boto3 from boto3.dynamodb.conditions import Key MOVIE_CODE_PATTERN = re.compile("popupSchedule\('.*','.*','(\d\d:\d\d)','\d*','\d*', '(\d*)', '\d*', '\d*',") class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): if o % 1 > 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o) class ScheduleInfo: id = '' raw_data = '' def __init__(self, schedule_id, raw_data, theater_code, date, movie_code, time, created_at=None): self.id = schedule_id self.raw_data = str(raw_data) self.theater_code = theater_code self.date = date self.movie_code = movie_code self.time = time self.created_at = created_at def __repr__(self) -> str: return self.id def is_valid(self): return self.id is not '' def is_imax_schedule(self): return u'아이맥스' in self.raw_data or 'imax' in self.raw_data.lower() def create_schedule_info(theater_code, date, raw_data): schedule_id = '' movie_code = '' time = '' movie_info = MOVIE_CODE_PATTERN.search(raw_data) if movie_info is None: logger.warning('Wrong schedule_info : %s', raw_data) else: time = movie_info.group(1).replace(':', '') movie_code = movie_info.group(2) schedule_id = '{}.{}.{}.{}'.format(theater_code, date, movie_code, time) return ScheduleInfo(schedule_id, raw_data, theater_code, date, movie_code, time) def parse_schedule_info(json_str): data = json.loads(json_str) return ScheduleInfo( schedule_id=data['id'], raw_data=data['raw_data'], theater_code=data['theater_code'], movie_code=data['movie_code'], date=data['date'], time=data['time'], created_at=data['created_at'] ) def save_schedule_list(schedule_list): table = boto3.resource('dynamodb').Table('nightwatch-imax-raw-data') created_at = arrow.utcnow().timestamp expire_at = arrow.utcnow().shift(minutes=+30).timestamp with table.batch_writer(overwrite_by_pkeys=['id', 'created_at']) as batch: for schedule_info in schedule_list: batch.put_item(Item={'id': schedule_info.id, 'created_at': created_at, 'expire_at': expire_at, 'raw_data': schedule_info.raw_data, 'theater_code': schedule_info.theater_code, 'date': schedule_info.date, 'movie_code': schedule_info.movie_code, 'time': schedule_info.time}) logger.debug('Saved : %s', schedule_info.id) def get_latest_schedule_list(minute): table = boto3.resource('dynamodb').Table('nightwatch-imax-raw-data') raw_data = [] created_from = arrow.utcnow().shift(minutes=-minute).timestamp filter_expression = Key('created_at').gte(created_from) response = table.scan( FilterExpression=filter_expression ) for item in response['Items']: data = json.dumps(item, cls=DecimalEncoder) raw_data.append(parse_schedule_info(data)) while 'LastEvaluatedKey' in response: response = table.scan( FilterExpression=filter_expression, ExclusiveStartKey=response['LastEvaluatedKey'] ) for item in response['Items']: data = json.dumps(item, cls=DecimalEncoder) raw_data.append(parse_schedule_info(data)) return raw_data logger = logging.getLogger() logger.setLevel(logging.INFO)
unknown
codeparrot/codeparrot-clean
import unittest from underscore import array as _ from itertools import chain class TestFlatten(unittest.TestCase): def test_flat_list(self): l = [1,2,3,4] flat = list(_.flatten(l)) self.assertEqual(l,flat) def test_flat_generator(self): l = range(0, 10) flat = _.flatten(range(0,10)) self.assertEqual(list(l), list(flat)) def test_single_nest_list(self): l = [1, 2, 3, [4]] flat = list(_.flatten(l)) self.assertEqual([1,2,3,4], flat) l = [[1,2,3], [4,5,6], [7,8,9]] flat = list(_.flatten(l)) self.assertEqual(flat, [1,2,3,4,5,6,7,8,9]) def test_single_nest_generator(self): l = [range(0,3), range(3,6), range(6,9)] flat = list(_.flatten(l)) self.assertEqual(flat, [0,1,2,3,4,5,6,7,8]) l = chain(range(0,3), range(3,6), range(6,9)) flat = list(_.flatten(l)) self.assertEqual(flat, [0,1,2,3,4,5,6,7,8]) def test_deep_nested_list(self): l = [[1,2], [3,4], [[5, 6], 7, 8]] flat = list(_.flatten(l)) self.assertEqual(flat, [1,2,3,4,5,6,7,8]) def test_deep_nested_generator(self): gen = range(0,3) squared_gen = lambda : map(lambda x: x*x, range(0,3)) nested_gen = chain(gen, gen) nested_gen2 = chain(squared_gen(), squared_gen()) deep_nested_generator = chain(nested_gen, nested_gen2) flat = list(_.flatten(deep_nested_generator)) self.assertEqual(flat, [0,1,2,0,1,2,0,1,4,0,1,4]) print(flat) if __name__ == "__main__": unittest.main()
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- """ *************************************************************************** r_li_padsd.py ------------- Date : February 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot fr *************************************************************************** * * * 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. * * * *************************************************************************** """ __author__ = 'Médéric Ribreux' __date__ = 'February 2016' __copyright__ = '(C) 2016, Médéric Ribreux' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from .r_li import checkMovingWindow, configFile def checkParameterValuesBeforeExecuting(alg, parameters, context): return checkMovingWindow(alg, parameters, context) def processCommand(alg, parameters, context, feedback): configFile(alg, parameters, context, feedback)
unknown
codeparrot/codeparrot-clean
/* Copyright 2019 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. ==============================================================================*/ #ifndef TENSORFLOW_CORE_PROFILER_UTILS_EVENT_SPAN_H_ #define TENSORFLOW_CORE_PROFILER_UTILS_EVENT_SPAN_H_ #include "xprof/utils/event_span.h" // from @org_xprof // IWYU pragma: export #endif // TENSORFLOW_CORE_PROFILER_UTILS_EVENT_SPAN_H_
c
github
https://github.com/tensorflow/tensorflow
tensorflow/core/profiler/utils/event_span.h
from pt import ( # noqa: F401 add_test, ao_sparsifier_test, arange_test, as_strided_test, batchnorm_test, binary_inplace_test, binary_test, bmm_test, boolean_test, cat_test, channel_shuffle_test, chunk_test, conv_test, diag_test, embeddingbag_test, fill_test, gather_test, groupnorm_test, hardsigmoid_test, hardswish_test, index_add__test, index_select_test, instancenorm_test, interpolate_test, layernorm_test, linear_test, matmul_test, mm_test, nan_to_num_test, pool_test, remainder_test, softmax_test, split_test, stack_test, sum_test, tensor_to_test, ternary_test, topk_test, where_test, ) import operator_benchmark as op_bench if __name__ == "__main__": op_bench.benchmark_runner.main()
python
github
https://github.com/pytorch/pytorch
benchmarks/operator_benchmark/benchmark_all_other_test.py
"""Tests for scrapy.core.downloader.handlers.http10.HTTP10DownloadHandler.""" from __future__ import annotations from typing import TYPE_CHECKING import pytest from scrapy.core.downloader.handlers.http10 import HTTP10DownloadHandler from scrapy.http import Request from scrapy.utils.defer import deferred_f_from_coro_f from tests.test_downloader_handlers_http_base import TestHttpBase, TestHttpProxyBase if TYPE_CHECKING: from scrapy.core.downloader.handlers import DownloadHandlerProtocol from tests.mockserver.http import MockServer pytestmark = pytest.mark.requires_reactor class HTTP10DownloadHandlerMixin: @property def download_handler_cls(self) -> type[DownloadHandlerProtocol]: return HTTP10DownloadHandler @pytest.mark.filterwarnings("ignore::scrapy.exceptions.ScrapyDeprecationWarning") class TestHttp10(HTTP10DownloadHandlerMixin, TestHttpBase): """HTTP 1.0 test case""" def test_unsupported_scheme(self) -> None: # type: ignore[override] pytest.skip("Check not implemented") @deferred_f_from_coro_f async def test_protocol(self, mockserver: MockServer) -> None: request = Request( mockserver.url("/host", is_secure=self.is_secure), method="GET" ) async with self.get_dh() as download_handler: response = await download_handler.download_request(request) assert response.protocol == "HTTP/1.0" class TestHttps10(TestHttp10): is_secure = True @pytest.mark.filterwarnings("ignore::scrapy.exceptions.ScrapyDeprecationWarning") class TestHttp10Proxy(HTTP10DownloadHandlerMixin, TestHttpProxyBase): @deferred_f_from_coro_f async def test_download_with_proxy_https_timeout(self): pytest.skip("Not implemented") @deferred_f_from_coro_f async def test_download_with_proxy_without_http_scheme(self): pytest.skip("Not implemented")
python
github
https://github.com/scrapy/scrapy
tests/test_downloader_handler_twisted_http10.py
#!/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_compute_disk_facts description: - Gather facts for GCP Disk short_description: Gather facts for GCP Disk version_added: 2.7 author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: filters: description: A list of filter value pairs. Available filters are listed here U(https://cloud.google.com/sdk/gcloud/reference/topic/filters). Each additional filter in the list will act be added as an AND condition (filter1 and filter2) zone: description: - A reference to the zone where the disk resides. required: true extends_documentation_fragment: gcp ''' EXAMPLES = ''' - name: a disk facts gcp_compute_disk_facts: zone: us-central1-a filters: - name = test_object project: test_project auth_kind: service_account service_account_file: "/tmp/auth.pem" ''' RETURN = ''' items: description: List of items returned: always type: complex contains: creation_timestamp: description: - Creation timestamp in RFC3339 text format. returned: success type: str description: description: - An optional description of this resource. Provide this property when you create the resource. returned: success type: str id: description: - The unique identifier for the resource. returned: success type: int last_attach_timestamp: description: - Last attach timestamp in RFC3339 text format. returned: success type: str last_detach_timestamp: description: - Last dettach timestamp in RFC3339 text format. returned: success type: str labels: description: - Labels to apply to this disk. A list of key->value pairs. returned: success type: dict licenses: description: - Any applicable publicly visible licenses. returned: success type: list name: description: - Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. returned: success type: str size_gb: description: - Size of the persistent disk, specified in GB. You can specify this field when creating a persistent disk using the sourceImage or sourceSnapshot parameter, or specify it alone to create an empty persistent disk. - If you specify this field along with sourceImage or sourceSnapshot, the value of sizeGb must not be less than the size of the sourceImage or the size of the snapshot. returned: success type: int users: description: - 'Links to the users of the disk (attached instances) in form: project/zones/zone/instances/instance .' returned: success type: list type: description: - URL of the disk type resource describing which disk type to use to create the disk. Provide this when creating the disk. returned: success type: str source_image: description: - The source image used to create this disk. If the source image is deleted, this field will not be set. - 'To create a disk with one of the public operating system images, specify the image by its family name. For example, specify family/debian-8 to use the latest Debian 8 image: projects/debian-cloud/global/images/family/debian-8 Alternatively, use a specific version of a public operating system image: projects/debian-cloud/global/images/debian-8-jessie-vYYYYMMDD To create a disk with a private image that you created, specify the image name in the following format: global/images/my-private-image You can also specify a private image by its image family, which returns the latest version of the image in that family. Replace the image name with family/family-name: global/images/family/my-private-family .' returned: success type: str zone: description: - A reference to the zone where the disk resides. returned: success type: str source_image_encryption_key: description: - The customer-supplied encryption key of the source image. Required if the source image is protected by a customer-supplied encryption key. returned: success type: complex contains: raw_key: description: - Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. returned: success type: str sha256: description: - The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. returned: success type: str source_image_id: description: - The ID value of the image used to create this disk. This value identifies the exact image that was used to create this persistent disk. For example, if you created the persistent disk from an image that was later deleted and recreated under the same name, the source image ID would identify the exact version of the image that was used. returned: success type: str disk_encryption_key: description: - Encrypts the disk using a customer-supplied encryption key. - After you encrypt a disk with a customer-supplied key, you must provide the same key if you use the disk later (e.g. to create a disk snapshot or an image, or to attach the disk to a virtual machine). - Customer-supplied encryption keys do not protect access to metadata of the disk. - If you do not provide an encryption key when creating the disk, then the disk will be encrypted using an automatically generated key and you do not need to provide a key to use the disk later. returned: success type: complex contains: raw_key: description: - Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. returned: success type: str sha256: description: - The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. returned: success type: str source_snapshot: description: - 'The source snapshot used to create this disk. You can provide this as a partial or full URL to the resource. For example, the following are valid values: * `U(https://www.googleapis.com/compute/v1/projects/project/global/snapshots/snapshot`) * `projects/project/global/snapshots/snapshot` * `global/snapshots/snapshot` .' returned: success type: dict source_snapshot_encryption_key: description: - The customer-supplied encryption key of the source snapshot. Required if the source snapshot is protected by a customer-supplied encryption key. returned: success type: complex contains: raw_key: description: - Specifies a 256-bit customer-supplied encryption key, encoded in RFC 4648 base64 to either encrypt or decrypt this resource. returned: success type: str sha256: description: - The RFC 4648 base64 encoded SHA-256 hash of the customer-supplied encryption key that protects this resource. returned: success type: str source_snapshot_id: description: - The unique ID of the snapshot used to create this disk. This value identifies the exact snapshot that was used to create this persistent disk. For example, if you created the persistent disk from a snapshot that was later deleted and recreated under the same name, the source snapshot ID would identify the exact version of the snapshot that was used. returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest import json ################################################################################ # Main ################################################################################ def main(): module = GcpModule( argument_spec=dict( filters=dict(type='list', elements='str'), zone=dict(required=True, type='str') ) ) if 'scopes' not in module.params: module.params['scopes'] = ['https://www.googleapis.com/auth/compute'] items = fetch_list(module, collection(module), query_options(module.params['filters'])) if items.get('items'): items = items.get('items') else: items = [] return_value = { 'items': items } module.exit_json(**return_value) def collection(module): return "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/disks".format(**module.params) def fetch_list(module, link, query): auth = GcpSession(module, 'compute') response = auth.get(link, params={'filter': query}) return return_if_object(module, response) def query_options(filters): if not filters: return '' if len(filters) == 1: return filters[0] else: queries = [] for f in filters: # For multiple queries, all queries should have () if f[0] != '(' and f[-1] != ')': queries.append("(%s)" % ''.join(f)) else: queries.append(f) return ' '.join(queries) def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) 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', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__": main()
unknown
codeparrot/codeparrot-clean
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. # # SPDX-License-Identifier: curl name: 'dist' 'on': push: branches: - master - '*/ci' pull_request: branches: - master concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} cancel-in-progress: true permissions: {} env: CURL_TEST_MIN: 1450 MAKEFLAGS: -j 5 jobs: maketgz-and-verify-in-tree: name: 'AM in-tree & maketgz' runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false - name: 'remove preinstalled curl libcurl4{-doc}' run: sudo apt-get -o Dpkg::Use-Pty=0 purge curl libcurl4 libcurl4-doc - name: 'autoreconf' run: autoreconf -fi - name: 'configure' run: ./configure --without-ssl --without-libpsl - name: 'make' run: make V=1 - name: 'maketgz' run: SOURCE_DATE_EPOCH=1711526400 ./scripts/maketgz 99.98.97 - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 with: name: 'release-tgz' path: 'curl-99.98.97.tar.gz' retention-days: 1 - name: 'configure build & install' run: | echo "::stop-commands::$(uuidgen)" tar xvf curl-99.98.97.tar.gz pushd curl-99.98.97 ./configure --prefix="$HOME"/temp --enable-option-checking=fatal --enable-werror --without-ssl --without-libpsl make make test-ci make install popd # basic check of the installed files bash scripts/installcheck.sh "$HOME"/temp rm -rf curl-99.98.97 verify-out-of-tree-docs: name: 'AM out-of-tree docs' runs-on: ubuntu-latest timeout-minutes: 10 needs: maketgz-and-verify-in-tree steps: - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: name: 'release-tgz' - name: 'configure build & docs' run: | echo "::stop-commands::$(uuidgen)" tar xvf curl-99.98.97.tar.gz touch curl-99.98.97/docs/{cmdline-opts,libcurl}/Makefile.inc mkdir build pushd build ../curl-99.98.97/configure --enable-option-checking=fatal --enable-werror --without-ssl --without-libpsl make make test-ci popd rm -rf build rm -rf curl-99.98.97 verify-out-of-tree-autotools-debug: name: 'AM out-of-tree (debug)' runs-on: ubuntu-latest timeout-minutes: 10 needs: maketgz-and-verify-in-tree steps: - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: name: 'release-tgz' - name: 'build & install' run: | echo "::stop-commands::$(uuidgen)" tar xvf curl-99.98.97.tar.gz pushd curl-99.98.97 mkdir build pushd build ../configure --prefix="$PWD"/curl-install --enable-option-checking=fatal --enable-werror --without-ssl --enable-debug --without-libpsl make make test-ci make install curl-install/bin/curl --disable --version curl-install/bin/curl --manual | wc -l | grep -v '^ *0$' popd scripts/checksrc-all.pl verify-out-of-tree-autotools: name: 'AM out-of-tree !perl' runs-on: ubuntu-latest timeout-minutes: 10 needs: maketgz-and-verify-in-tree steps: - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: name: 'release-tgz' - name: 'build & install' run: | echo "::stop-commands::$(uuidgen)" tar xvf curl-99.98.97.tar.gz pushd curl-99.98.97 mkdir build pushd build ../configure --prefix="$PWD"/curl-install --enable-option-checking=fatal --enable-werror --without-ssl --without-libpsl ac_cv_path_PERL= make make install curl-install/bin/curl --disable --version curl-install/bin/curl --manual | wc -l | grep -v '^ *0$' popd verify-in-tree-autotools: name: 'AM in-tree !perl' runs-on: ubuntu-latest timeout-minutes: 10 needs: maketgz-and-verify-in-tree steps: - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: name: 'release-tgz' - name: 'build & install' run: | echo "::stop-commands::$(uuidgen)" tar xvf curl-99.98.97.tar.gz pushd curl-99.98.97 ./configure --prefix="$PWD"/curl-install --enable-option-checking=fatal --enable-werror --without-ssl --without-libpsl ac_cv_path_PERL= make make install curl-install/bin/curl --disable --version curl-install/bin/curl --manual | wc -l | grep -v '^ *0$' verify-out-of-tree-cmake: name: 'CM out-of-tree !perl' runs-on: ubuntu-latest timeout-minutes: 5 needs: maketgz-and-verify-in-tree steps: - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: name: 'release-tgz' - name: 'build & install' run: | echo "::stop-commands::$(uuidgen)" tar xvf curl-99.98.97.tar.gz pushd curl-99.98.97 cmake -B build -DCMAKE_INSTALL_PREFIX="$PWD"/curl-install -DCURL_WERROR=ON -DCURL_USE_LIBPSL=OFF -DPERL_EXECUTABLE= cmake --build build cmake --install build export LD_LIBRARY_PATH="$PWD/curl-install/lib:$LD_LIBRARY_PATH" curl-install/bin/curl --disable --version curl-install/bin/curl --manual | wc -l | grep -v '^ *0$' verify-in-tree-cmake: name: 'CM in-tree !perl' runs-on: ubuntu-latest timeout-minutes: 5 needs: maketgz-and-verify-in-tree steps: - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: name: 'release-tgz' - name: 'build & install' run: | echo "::stop-commands::$(uuidgen)" tar xvf curl-99.98.97.tar.gz pushd curl-99.98.97 cmake . -G Ninja -DCMAKE_INSTALL_PREFIX="$PWD"/curl-install -DCURL_WERROR=ON -DCURL_USE_LIBPSL=OFF -DPERL_EXECUTABLE= cmake --build . cmake --install . export LD_LIBRARY_PATH="$PWD/curl-install/lib:$LD_LIBRARY_PATH" curl-install/bin/curl --disable --version curl-install/bin/curl --manual | wc -l | grep -v '^ *0$' missing-files: name: 'missing files' runs-on: ubuntu-slim timeout-minutes: 5 needs: maketgz-and-verify-in-tree steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 with: name: 'release-tgz' - name: 'detect files missing from release tarball' run: .github/scripts/distfiles.sh curl-99.98.97.tar.gz reproducible-releases: name: 'reproducible releases' runs-on: ubuntu-latest timeout-minutes: 10 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false - name: 'remove preinstalled curl libcurl4{-doc}' run: sudo apt-get -o Dpkg::Use-Pty=0 purge curl libcurl4 libcurl4-doc - name: 'generate release tarballs' run: ./scripts/dmaketgz 9.10.11 - name: 'verify release tarballs' run: | mkdir _verify mv curl-9.10.11.tar.gz _verify cd _verify ../scripts/verify-release curl-9.10.11.tar.gz cmake-integration: name: 'CM integration ${{ matrix.image }}' runs-on: ${{ matrix.image }} timeout-minutes: 15 defaults: run: shell: ${{ contains(matrix.image, 'windows') && 'msys2 {0}' || 'bash' }} env: CC: ${{ !contains(matrix.image, 'windows') && 'clang' || '' }} MAKEFLAGS: ${{ contains(matrix.image, 'macos') && '-j 4' || '-j 5' }} MATRIX_IMAGE: '${{ matrix.image }}' TESTOPTS: ${{ contains(matrix.image, 'macos') && '-D_CURL_PREFILL=ON' || '' }} ${{ contains(matrix.image, 'windows') && '-DCMAKE_UNITY_BUILD_BATCH_SIZE=30' || '' }} OLD_CMAKE_VERSION: 3.19.8 OLD_CMAKE_SHA256_LINUX_ARM: 807f5afb2a560e00af9640e496d5673afefc2888bf0ed076412884a5ebb547a1 OLD_CMAKE_SHA256_MACOS_UNI: 0976d23d982af05dcbfb3aa34fcb62ead43bea27f0e3bb95222f2a78161423f2 OLD_CMAKE_SHA256_WIN_INTEL: 2a30877a3d6b50da305b289f4d1c03befdfaeb2edba02a563c681e883d810380 strategy: fail-fast: false matrix: image: [ubuntu-24.04-arm, macos-latest, windows-2022] steps: - uses: msys2/setup-msys2@4f806de0a5a7294ffabaff804b38a9b435a73bda # v2.30.0 if: ${{ contains(matrix.image, 'windows') }} with: msystem: mingw64 release: false update: false cache: false path-type: inherit install: >- mingw-w64-x86_64-zlib mingw-w64-x86_64-zstd mingw-w64-x86_64-libpsl mingw-w64-x86_64-libssh2 mingw-w64-x86_64-nghttp2 mingw-w64-x86_64-openssl - name: 'install prereqs' timeout-minutes: 3 run: | if [[ "${MATRIX_IMAGE}" = *'windows'* ]]; then cd ~ curl --disable --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-connrefused \ --location "https://github.com/Kitware/CMake/releases/download/v${OLD_CMAKE_VERSION}/cmake-${OLD_CMAKE_VERSION}-win64-x64.zip" --output pkg.bin sha256sum pkg.bin && sha256sum pkg.bin | grep -qwF -- "${OLD_CMAKE_SHA256_WIN_INTEL}" && unzip -q pkg.bin && rm -f pkg.bin printf '%s' ~/cmake-"${OLD_CMAKE_VERSION}"-win64-x64/bin/cmake.exe > ~/old-cmake-path.txt elif [[ "${MATRIX_IMAGE}" = *'ubuntu'* ]]; then sudo apt-get -o Dpkg::Use-Pty=0 install libpsl-dev libssl-dev cd ~ curl --disable --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-connrefused \ --location "https://github.com/Kitware/CMake/releases/download/v${OLD_CMAKE_VERSION}/cmake-${OLD_CMAKE_VERSION}-Linux-aarch64.tar.gz" --output pkg.bin sha256sum pkg.bin | tee /dev/stderr | grep -qwF -- "${OLD_CMAKE_SHA256_LINUX_ARM}" && tar -xzf pkg.bin && rm -f pkg.bin printf '%s' ~/cmake-"${OLD_CMAKE_VERSION}"-Linux-aarch64/bin/cmake > ~/old-cmake-path.txt else brew install libpsl openssl cd ~ curl --disable --fail --silent --show-error --connect-timeout 15 --max-time 60 --retry 3 --retry-connrefused \ --location "https://github.com/Kitware/CMake/releases/download/v${OLD_CMAKE_VERSION}/cmake-${OLD_CMAKE_VERSION}-macos-universal.tar.gz" --output pkg.bin sha256sum pkg.bin | tee /dev/stderr | grep -qwF -- "${OLD_CMAKE_SHA256_MACOS_UNI}" && tar -xzf pkg.bin && rm -f pkg.bin printf '%s' ~/cmake-"${OLD_CMAKE_VERSION}"-macos-universal/CMake.app/Contents/bin/cmake > ~/old-cmake-path.txt fi - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: persist-credentials: false - name: 'via ExternalProject' if: ${{ !contains(matrix.image, 'ubuntu') }} run: ./tests/cmake/test.sh ExternalProject ${TESTOPTS} - name: 'via FetchContent' run: ./tests/cmake/test.sh FetchContent ${TESTOPTS} -DCURL_USE_OPENSSL=ON - name: 'via add_subdirectory' run: ./tests/cmake/test.sh add_subdirectory ${TESTOPTS} -DCURL_USE_OPENSSL=ON - name: 'via find_package' run: ./tests/cmake/test.sh find_package ${TESTOPTS} -DCURL_USE_OPENSSL=ON - name: 'via ExternalProject (old cmake)' if: ${{ contains(matrix.image, 'ubuntu') }} run: | export TEST_CMAKE_CONSUMER; TEST_CMAKE_CONSUMER="$(cat ~/old-cmake-path.txt)" if [[ "${MATRIX_IMAGE}" = *'macos'* ]]; then export CFLAGS='-arch arm64' fi if [[ "${MATRIX_IMAGE}" = *'windows'* ]]; then export TEST_CMAKE_GENERATOR='MSYS Makefiles' export TEST_CMAKE_FLAGS='-DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc' fi ./tests/cmake/test.sh ExternalProject ${TESTOPTS} - name: 'via add_subdirectory OpenSSL (old cmake)' run: | export TEST_CMAKE_CONSUMER; TEST_CMAKE_CONSUMER="$(cat ~/old-cmake-path.txt)" if [[ "${MATRIX_IMAGE}" = *'macos'* ]]; then export CFLAGS='-arch arm64' export TEST_CMAKE_FLAGS='-DCURL_USE_LIBPSL=OFF' # auto-detection does not work with old-cmake fi if [[ "${MATRIX_IMAGE}" = *'windows'* ]]; then export TEST_CMAKE_GENERATOR='MSYS Makefiles' export TEST_CMAKE_FLAGS='-DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc -DOPENSSL_ROOT_DIR=C:/msys64/mingw64' fi ./tests/cmake/test.sh add_subdirectory ${TESTOPTS} -DCURL_USE_OPENSSL=ON - name: 'via find_package OpenSSL (old cmake)' run: | export TEST_CMAKE_CONSUMER; TEST_CMAKE_CONSUMER="$(cat ~/old-cmake-path.txt)" if [[ "${MATRIX_IMAGE}" = *'macos'* ]]; then export CFLAGS='-arch arm64' export TEST_CMAKE_FLAGS='-DCURL_USE_LIBPSL=OFF' # auto-detection does not work with old-cmake fi if [[ "${MATRIX_IMAGE}" = *'windows'* ]]; then export TEST_CMAKE_GENERATOR='MSYS Makefiles' export TEST_CMAKE_FLAGS='-DCMAKE_C_COMPILER=x86_64-w64-mingw32-gcc -DOPENSSL_ROOT_DIR=C:/msys64/mingw64' fi ./tests/cmake/test.sh find_package ${TESTOPTS} -DCURL_USE_OPENSSL=ON
unknown
github
https://github.com/curl/curl
.github/workflows/distcheck.yml
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !compiler_bootstrap package strconv import "internal/bytealg" // index returns the index of the first instance of c in s, or -1 if missing. func index(s string, c byte) int { return bytealg.IndexByteString(s, c) }
go
github
https://github.com/golang/go
src/strconv/bytealg.go
# =========================================================================== # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # =========================================================================== from Python.Test import DelegateTest, PublicDelegate from Python.Test import StringDelegate, ObjectDelegate from Python.Test import BoolDelegate import sys, os, string, unittest, types import Python.Test as Test import System class DelegateTests(unittest.TestCase): """Test CLR delegate support.""" def testDelegateStandardAttrs(self): """Test standard delegate attributes.""" self.failUnless(PublicDelegate.__name__ == 'PublicDelegate') self.failUnless(PublicDelegate.__module__ == 'Python.Test') self.failUnless(type(PublicDelegate.__dict__) == types.DictProxyType) self.failUnless(PublicDelegate.__doc__ == None) def testGlobalDelegateVisibility(self): """Test visibility of module-level delegates.""" from Python.Test import PublicDelegate self.failUnless(PublicDelegate.__name__ == 'PublicDelegate') self.failUnless(Test.PublicDelegate.__name__ == 'PublicDelegate') def test(): from Python.Test import InternalDelegate self.failUnlessRaises(ImportError, test) def test(): i = Test.InternalDelegate self.failUnlessRaises(AttributeError, test) def testNestedDelegateVisibility(self): """Test visibility of nested delegates.""" ob = DelegateTest.PublicDelegate self.failUnless(ob.__name__ == 'PublicDelegate') ob = DelegateTest.ProtectedDelegate self.failUnless(ob.__name__ == 'ProtectedDelegate') def test(): ob = DelegateTest.InternalDelegate self.failUnlessRaises(AttributeError, test) def test(): ob = DelegateTest.PrivateDelegate self.failUnlessRaises(AttributeError, test) def testDelegateFromFunction(self): """Test delegate implemented with a Python function.""" def sayhello(): return "hello" d = StringDelegate(sayhello) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(d) == "hello") self.failUnless(d() == "hello") ob.stringDelegate = d self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") def testDelegateFromMethod(self): """Test delegate implemented with a Python instance method.""" class Hello: def sayhello(self): return "hello" inst = Hello() d = StringDelegate(inst.sayhello) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(d) == "hello") self.failUnless(d() == "hello") ob.stringDelegate = d self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") def testDelegateFromUnboundMethod(self): """Test failure mode for unbound methods.""" class Hello: def sayhello(self): return "hello" def test(): d = StringDelegate(Hello.sayhello) d() self.failUnlessRaises(TypeError, test) def testDelegateFromStaticMethod(self): """Test delegate implemented with a Python static method.""" class Hello: def sayhello(): return "hello" sayhello = staticmethod(sayhello) d = StringDelegate(Hello.sayhello) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(d) == "hello") self.failUnless(d() == "hello") ob.stringDelegate = d self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") inst = Hello() d = StringDelegate(inst.sayhello) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(d) == "hello") self.failUnless(d() == "hello") ob.stringDelegate = d self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") def testDelegateFromClassMethod(self): """Test delegate implemented with a Python class method.""" class Hello: def sayhello(self): return "hello" sayhello = classmethod(sayhello) d = StringDelegate(Hello.sayhello) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(d) == "hello") self.failUnless(d() == "hello") ob.stringDelegate = d self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") inst = Hello() d = StringDelegate(inst.sayhello) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(d) == "hello") self.failUnless(d() == "hello") ob.stringDelegate = d self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") def testDelegateFromCallable(self): """Test delegate implemented with a Python callable object.""" class Hello: def __call__(self): return "hello" inst = Hello() d = StringDelegate(inst) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(d) == "hello") self.failUnless(d() == "hello") ob.stringDelegate = d self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") def testDelegateFromManagedInstanceMethod(self): """Test delegate implemented with a managed instance method.""" ob = DelegateTest() d = StringDelegate(ob.SayHello) self.failUnless(ob.CallStringDelegate(d) == "hello") self.failUnless(d() == "hello") ob.stringDelegate = d self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") def testDelegateFromManagedStaticMethod(self): """Test delegate implemented with a managed static method.""" d = StringDelegate(DelegateTest.StaticSayHello) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(d) == "hello") self.failUnless(d() == "hello") ob.stringDelegate = d self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") def testDelegateFromDelegate(self): """Test delegate implemented with another delegate.""" def sayhello(): return "hello" d1 = StringDelegate(sayhello) d2 = StringDelegate(d1) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(d2) == "hello") self.failUnless(d2() == "hello") ob.stringDelegate = d2 self.failUnless(ob.CallStringDelegate(ob.stringDelegate) == "hello") self.failUnless(ob.stringDelegate() == "hello") def testDelegateWithInvalidArgs(self): """Test delegate instantiation with invalid (non-callable) args.""" def test(): d = StringDelegate(None) self.failUnlessRaises(TypeError, test) def test(): d = StringDelegate("spam") self.failUnlessRaises(TypeError, test) def test(): d = StringDelegate(1) self.failUnlessRaises(TypeError, test) def testMulticastDelegate(self): """Test multicast delegates.""" class Multi: def __init__(self): self.value = 0 def count(self): self.value += 1 return 'ok' inst = Multi() d1 = StringDelegate(inst.count) d2 = StringDelegate(inst.count) md = System.Delegate.Combine(d1, d2) ob = DelegateTest() self.failUnless(ob.CallStringDelegate(md) == "ok") self.failUnless(inst.value == 2) self.failUnless(md() == "ok") self.failUnless(inst.value == 4) def testSubclassDelegateFails(self): """Test that subclassing of a delegate type fails.""" def test(): class Boom(PublicDelegate): pass self.failUnlessRaises(TypeError, test) def testDelegateEquality(self): """Test delegate equality.""" def sayhello(): return "hello" d = StringDelegate(sayhello) ob = DelegateTest() ob.stringDelegate = d self.failUnless(ob.stringDelegate == d) def testBoolDelegate(self): """Test boolean delegate.""" def always_so_negative(): return 0 d = BoolDelegate(always_so_negative) ob = DelegateTest() ob.CallBoolDelegate(d) self.failUnless(not d()) self.failUnless(not ob.CallBoolDelegate(d)) # test async delegates # test multicast delegates # test explicit op_ # test sig mismatch, both on managed and Python side # test return wrong type def test_suite(): return unittest.makeSuite(DelegateTests) def main(): unittest.TextTestRunner().run(test_suite()) if __name__ == '__main__': main()
unknown
codeparrot/codeparrot-clean
# Copyright 2016 Cisco Systems, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import unittest from yabgp.common import constants as bgp_cons from yabgp.message.attribute.nlri.evpn import EVPN class TestEVPN(unittest.TestCase): def test_parse_mac_ip_adv(self): data_hex = b'\x02\x25\x00\x01\xac\x11\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' \ b'\x00\x00\x00\x6c\x30\x00\x11\x22\x33\x44\x55\x20\x0b\x0b\x0b\x01\x00\x00\x00' data_list = [{ 'type': bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT, 'value': { 'rd': '172.17.0.3:2', 'mac': '00-11-22-33-44-55', 'eth_tag_id': 108, 'esi': 0, 'ip': '11.11.11.1', 'label': [0]} }] self.assertEqual(data_list, EVPN.parse(data_hex)) def test_construct_mac_ip_adv(self): data_hex = b'\x02\x25\x00\x01\xac\x11\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' \ b'\x00\x00\x00\x6c\x30\x00\x11\x22\x33\x44\x55\x20\x0b\x0b\x0b\x01\x00\x00\x00' data_list = [{ 'type': bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT, 'value': { 'rd': '172.17.0.3:2', 'mac': '00-11-22-33-44-55', 'eth_tag_id': 108, 'esi': 0, 'ip': '11.11.11.1', 'label': [0]} }] self.assertEqual(data_hex, EVPN.construct(data_list)) def test_parse_eth_auto_dis(self): data_hex = b'\x01\x19\x00\x01\x01\x01\x01\x01\x80\x63\x00\x00\x00' \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x64\x00\x00\xa1' data_list = [{ 'type': bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY, 'value': { 'rd': '1.1.1.1:32867', 'esi': 0, 'eth_tag_id': 100, 'label': [10] } }] self.assertEqual(data_list, EVPN.parse(data_hex)) def test_construct_eth_auto_dis(self): data_hex = b'\x01\x19\x00\x01\x01\x01\x01\x01\x80\x63\x00\x00\x00' \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x64\x00\x00\xa1' data_list = [{ 'type': bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY, 'value': { 'rd': '1.1.1.1:32867', 'esi': 0, 'eth_tag_id': 100, 'label': [10] } }] self.assertEqual(data_hex, EVPN.construct(data_list)) def test_parse_in_mul_eth_tag(self): data_hex = b'\x03\x11\x00\x01\xac\x10\x00\x01\x17\x10\x00\x00\x00\x64\x20\xc0\xa8\x00\x01' data_list = [{ 'type': bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG, 'value': { 'rd': '172.16.0.1:5904', 'eth_tag_id': 100, 'ip': '192.168.0.1' } }] self.assertEqual(data_list, EVPN.parse(data_hex)) def test_construct_in_mul_eth_tag(self): data_hex = b'\x03\x11\x00\x01\xac\x10\x00\x01\x17\x10\x00\x00\x00\x64\x20\xc0\xa8\x00\x01' data_list = [{ 'type': bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG, 'value': { 'rd': '172.16.0.1:5904', 'eth_tag_id': 100, 'ip': '192.168.0.1' } }] self.assertEqual(data_hex, EVPN.construct(data_list)) def test_parse_eth_segment(self): data_hex = b'\x04\x17\x00\x01\xac\x10\x00\x01\x17\x10\x00\x00' \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x20\xc0\xa8\x00\x01' data_list = [{ 'type': bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT, 'value': { 'rd': '172.16.0.1:5904', 'esi': 0, 'ip': '192.168.0.1' } }] self.assertEqual(data_list, EVPN.parse(data_hex)) def test_construct_eth_segment(self): data_hex = b'\x04\x17\x00\x01\xac\x10\x00\x01\x17\x10\x00\x00' \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x20\xc0\xa8\x00\x01' data_list = [{ 'type': bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT, 'value': { 'rd': '172.16.0.1:5904', 'esi': 0, 'ip': '192.168.0.1' } }] self.assertEqual(data_hex, EVPN.construct(data_list)) def test_parse_ip_route_prefix_v4(self): data_hex = b'\x05\x22\x00\x02\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' \ b'\x00\x00\x00\x01\x18\x01\x01\x01\x00\x01\x01\x01\x01\x00\x00\xa1' data_list = [{ 'type': 5, 'value': { 'esi': 0, 'eth_tag_id': 1, 'gateway': '1.1.1.1', 'label': [10], 'prefix': '1.1.1.0/24', 'rd': '65536:2'}}] self.assertEqual(data_list, EVPN.parse(data_hex)) def test_construct_ip_route_prefix_v4(self): data_hex = b'\x05\x22\x00\x02\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' \ b'\x00\x00\x00\x01\x18\x01\x01\x01\x00\x01\x01\x01\x01\x00\x00\xa1' data_list = [{ 'type': 5, 'value': { 'esi': 0, 'eth_tag_id': 1, 'gateway': '1.1.1.1', 'label': [10], 'prefix': '1.1.1.0/24', 'rd': '65536:2'}}] self.assertEqual(data_hex, EVPN.construct(data_list)) def test_parse_ip_route_prefix_v6(self): data_hex = b'\x05' \ b'\x3a' \ b'\x00\x02\x00\x01\x00\x00\x00\x02' \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' \ b'\x00\x00\x00\x01' \ b'\x40' \ b'\x20\x01\x32\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01' \ b'\x20\x01\x32\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01' \ b'\x00\x00\xa1' data_list = [{ 'type': 5, 'value': { 'esi': 0, 'eth_tag_id': 1, 'gateway': '2001:3232::1', 'label': [10], 'prefix': '2001:3232::1/64', 'rd': '65536:2'}}] self.assertEqual(data_list, EVPN.parse(data_hex)) def test_construct_ip_route_prefix_v6(self): data_hex = b'\x05' \ b'\x3a' \ b'\x00\x02\x00\x01\x00\x00\x00\x02' \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' \ b'\x00\x00\x00\x01' \ b'\x40' \ b'\x20\x01\x32\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01' \ b'\x20\x01\x32\x32\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01' \ b'\x00\x00\xa1' data_list = [{ 'type': 5, 'value': { 'esi': 0, 'eth_tag_id': 1, 'gateway': '2001:3232::1', 'label': [10], 'prefix': '2001:3232::1/64', 'rd': '65536:2'}}] self.assertEqual(data_hex, EVPN.construct(data_list)) if __name__ == '__main__': unittest.main()
unknown
codeparrot/codeparrot-clean
# SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause) %YAML 1.2 --- $id: http://devicetree.org/schemas/interrupt-controller/intel,ce4100-lapic.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# title: Intel Local Advanced Programmable Interrupt Controller (LAPIC) maintainers: - Rahul Tanwar <rtanwar@maxlinear.com> description: | Intel's Advanced Programmable Interrupt Controller (APIC) is a family of interrupt controllers. The APIC is a split architecture design, with a local component (LAPIC) integrated into the processor itself and an external I/O APIC. Local APIC (lapic) receives interrupts from the processor's interrupt pins, from internal sources and from an external I/O APIC (ioapic). And it sends these to the processor core for handling. See [1] Chapter 8 for more details. Many of the Intel's generic devices like hpet, ioapic, lapic have the ce4100 name in their compatible property names because they first appeared in CE4100 SoC. This schema defines bindings for local APIC interrupt controller. [1] https://pdos.csail.mit.edu/6.828/2008/readings/ia32/IA32-3A.pdf properties: compatible: const: intel,ce4100-lapic reg: maxItems: 1 interrupt-controller: true '#interrupt-cells': const: 2 intel,virtual-wire-mode: description: Intel defines a few possible interrupt delivery modes. With respect to boot/init time, mainly two interrupt delivery modes are possible. PIC Mode - Legacy external 8259 compliant PIC interrupt controller. Virtual Wire Mode - use lapic as virtual wire interrupt delivery mode. For ACPI or MPS spec compliant systems, it is figured out by some read only bit field/s available in their respective defined data structures. For OF based systems, it is by default set to PIC mode. But if this optional boolean property is set, then the interrupt delivery mode is configured to virtual wire compatibility mode. type: boolean required: - compatible - reg - interrupt-controller - '#interrupt-cells' additionalProperties: false examples: - | lapic0: interrupt-controller@fee00000 { compatible = "intel,ce4100-lapic"; reg = <0xfee00000 0x1000>; interrupt-controller; #interrupt-cells = <2>; intel,virtual-wire-mode; };
unknown
github
https://github.com/torvalds/linux
Documentation/devicetree/bindings/interrupt-controller/intel,ce4100-lapic.yaml
# # Copyright (c) 2008-2011 Camptocamp. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of Camptocamp 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 <COPYRIGHT HOLDER> 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. # """Paster Commands, for use with paster in your MapFish project The command(s) listed here are for use with Paste to enable easy creation of various MapFish files. Currently available commands: mf-controller, mf-model """ import os import sys from ConfigParser import ConfigParser, NoOptionError from paste.script.command import Command, BadCommand from paste.script.filemaker import FileOp from tempita import paste_script_template_renderer import pylons.util as util __all__ = ['MapFishControllerCommand', 'MapFishModelCommand', 'MapFishLayerCommand'] def can_import(name): """Attempt to __import__ the specified package/module, returning True when succeeding, otherwise False""" try: __import__(name) return True except ImportError: return False def validateName(name): """Validate that the name for the layer isn't present on the path already""" if not name: # This happens when the name is an existing directory raise BadCommand('Please give the name of a layer.') # 'setup' is a valid controller name, but when paster controller is ran # from the root directory of a project, importing setup will import the # project's setup.py causing a sys.exit(). Blame relative imports if name != 'setup' and can_import(name): raise BadCommand( "\n\nA module named '%s' is already present in your " "PYTHON_PATH.\nChoosing a conflicting name will likely cause " "import problems in\nyour controller at some point. It's " "suggested that you choose an\nalternate name, and if you'd " "like that name to be accessible as\n'%s', add a route " "to your projects config/routing.py file similar\nto:\n" " map.connect('%s', controller='my_%s')" \ % (name, name, name, name)) return True class MapFishControllerCommand(Command): """Create a MapFish controller and accompanying functional test The MapFishController command will create the standard controller template file and associated functional test. Example usage:: yourproj% paster mf-controller foos Creating yourproj/yourproj/controllers/foos.py Creating yourproj/yourproj/tests/functional/test_foos.py If you'd like to have controllers underneath a directory, just include the path as the controller name and the necessary directories will be created for you:: yourproj% paster mf-controller admin/foos Creating yourproj/controllers/admin Creating yourproj/yourproj/controllers/admin/foos.py Creating yourproj/yourproj/tests/functional/test_admin_foos.py """ summary = __doc__.splitlines()[0] usage = '\n' + __doc__ min_args = 1 max_args = 1 group_name = 'mapfish' default_verbosity = 3 parser = Command.standard_parser(simulate=True) parser.add_option('--no-test', action='store_true', dest='no_test', help="Don't create the test; just the controller") def command(self): """Main command to create a mapfish controller""" try: # read layers.ini config = ConfigParser() config.read(['layers.ini']) # check passed layer is in layers.ini sectionName = self.args[0] if not config.has_section(sectionName): raise BadCommand( 'There is no layer section named %s in layers.ini' % \ sectionName) # get layer parameters singular = config.get(sectionName, 'singular') plural = config.get(sectionName, 'plural') epsg = config.get(sectionName, 'epsg') fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: singularName, singularDirectory = \ fileOp.parse_path_name_args(singular) pluralName, pluralDirectory = \ fileOp.parse_path_name_args(plural) except Exception, e: raise BadCommand('No egg_info directory was found') # check the name isn't the same as the package basePkg = fileOp.find_dir('controllers', True)[0] if basePkg.lower() == pluralName.lower(): raise BadCommand( 'Your controller name should not be the same as ' 'the package name %s' % basePkg) # validate the name name = pluralName.replace('-', '_') validateName(name) # set test file name fullName = os.path.join(pluralDirectory, name) if not fullName.startswith(os.sep): fullName = os.sep + fullName testName = fullName.replace(os.sep, '_')[1:] # set template vars modName = name fullModName = os.path.join(pluralDirectory, name) contrClass = util.class_name_from_module_name(name) modelClass = util.class_name_from_module_name(singularName) # setup the controller fileOp.template_vars.update( {'modName': modName, 'fullModName': fullModName, 'singularName': singularName, 'pluralName': pluralName, 'contrClass': contrClass, 'modelClass': modelClass, 'basePkg': basePkg}) fileOp.copy_file(template='controller.py_tmpl', dest=os.path.join('controllers', pluralDirectory), filename=name, template_renderer=paste_script_template_renderer) if not self.options.no_test: fileOp.copy_file(template='test_controller.py_tmpl', dest=os.path.join('tests', 'functional'), filename='test_' + testName, template_renderer=paste_script_template_renderer) resource_command = ("\nTo create the appropriate RESTful mapping, " "add a map statement to your\n") resource_command += ("config/routing.py file in the CUSTOM ROUTES section " "like this:\n\n") resource_command += ('map.connect("/%s/count", controller="%s", ' 'action="count")\n' % (pluralName, pluralName)) resource_command += 'map.resource("%s", "%s")\n' % \ (singularName, pluralName) print resource_command except BadCommand, e: raise BadCommand('An error occurred. %s' % e) except: msg = str(sys.exc_info()[1]) raise BadCommand('An unknown error occurred. %s' % msg) class MapFishModelCommand(Command): """Create a MapFish model The MapFishModel command will create the standard model template file. Example usage:: yourproj% paster mf-model foos Creating yourproj/yourproj/model/foos.py If you'd like to have models underneath a directory, just include the path as the model name and the necessary directories will be created for you:: yourproj% paster mf-model admin/foos Creating yourproj/model/admin Creating yourproj/yourproj/model/admin/foos.py """ summary = __doc__.splitlines()[0] usage = '\n' + __doc__ min_args = 1 max_args = 1 group_name = 'mapfish' default_verbosity = 3 parser = Command.standard_parser(simulate=True) def command(self): """Main command to create mapfish model""" try: # read layers.ini config = ConfigParser() config.read(['layers.ini']) # check passed layer is in layers.ini sectionName = self.args[0] if not config.has_section(sectionName): raise BadCommand( 'There is no layer section named %s in layers.ini' % \ sectionName) # get layer parameters singular = config.get(sectionName, 'singular') plural = config.get(sectionName, 'plural') table = config.get(sectionName, 'table') epsg = config.get(sectionName, 'epsg') geomColName = config.get(sectionName, 'geomcolumn') if config.has_option(sectionName, 'schema'): schema = config.get(sectionName, 'schema') else: schema = None # get geometry type if not config.has_option(sectionName, 'geomtype'): geomtype = 'Geometry' else: raw_geomtype = config.get(sectionName, 'geomtype') # check if the value is valid (geometries supported by GeoAlchemy) valid_types = ['Geometry', 'Point', 'Curve', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection'] if raw_geomtype in valid_types: geomtype = raw_geomtype else: raise BadCommand('Geometry type "%s" is unknown, valid values are: %s' % (raw_geomtype, valid_types)) fileOp = FileOp(source_dir=os.path.join( os.path.dirname(__file__), 'templates')) try: singularName, singularDirectory = \ fileOp.parse_path_name_args(singular) pluralName, pluralDirectory = \ fileOp.parse_path_name_args(plural) except: raise BadCommand('No egg_info directory was found') # check the name isn't the same as the package basePkg = fileOp.find_dir('model', True)[0] if basePkg.lower() == pluralName.lower(): raise BadCommand( 'Your model name should not be the same as ' 'the package name %s' % basePkg) # validate the name name = pluralName.replace('-', '_') validateName(name) # set template vars modelClass = util.class_name_from_module_name(singularName) # setup the model fileOp.template_vars.update( {'modelClass': modelClass, 'table': table, 'epsg': epsg, 'geomColName': geomColName, 'geomType': geomtype, 'basePkg': basePkg, 'schema': schema}) fileOp.copy_file(template='model.py_tmpl', dest=os.path.join('model', pluralDirectory), filename=name, template_renderer=paste_script_template_renderer) except BadCommand, e: raise BadCommand('An error occurred. %s' % e) except: msg = str(sys.exc_info()[1]) raise BadCommand('An unknown error occurred. %s' % msg) class MapFishLayerCommand(Command): """Create a MapFish layer (controller + model). The MapFishLayer command will create the standard controller and model template files. It combines the MapFishController and MapFishModel commands. Example usage:: yourproj% paster mf-layer foos Creating yourproj/yourproj/controllers/foos.py Creating yourproj/yourproj/tests/functional/test_foos.py Creating yourproj/yourproj/model/foos.py If you'd like to have controllers and models underneath a directory, just include the path as the controller name and the necessary directories will be created for you:: yourproj% paster mf-layer admin/foos Creating yourproj/controllers/admin Creating yourproj/yourproj/controllers/admin/foos.py Creating yourproj/yourproj/tests/functional/test_admin_foos.py Creating yourproj/model/admin Creating yourproj/yourproj/model/admin/foos.py """ summary = __doc__.splitlines()[0] usage = '\n' + __doc__ min_args = 1 max_args = 1 group_name = 'mapfish' default_verbosity = 3 parser = Command.standard_parser(simulate=True) parser.add_option('--no-test', action='store_true', dest='no_test', help="Don't create the test; just the controller") def run(self, args): try: contrCmd = MapFishControllerCommand('mf-controller') contrCmd.run(args) modelCmd = MapFishModelCommand('mf-model') modelCmd.run(args) except BadCommand, e: raise BadCommand('An error occurred. %s' % e) except: msg = str(sys.exc_info()[1]) raise BadCommand('An unknown error occurred. %s' % msg)
unknown
codeparrot/codeparrot-clean
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Test cases for twisted.protocols.stateful """ from twisted.trial.unittest import TestCase from twisted.protocols.test import test_basic from twisted.protocols.stateful import StatefulProtocol from struct import pack, unpack, calcsize class MyInt32StringReceiver(StatefulProtocol): """ A stateful Int32StringReceiver. """ MAX_LENGTH = 99999 structFormat = "!I" prefixLength = calcsize(structFormat) def getInitialState(self): return self._getHeader, 4 def lengthLimitExceeded(self, length): self.transport.loseConnection() def _getHeader(self, msg): length, = unpack("!i", msg) if length > self.MAX_LENGTH: self.lengthLimitExceeded(length) return return self._getString, length def _getString(self, msg): self.stringReceived(msg) return self._getHeader, 4 def stringReceived(self, msg): """ Override this. """ raise NotImplementedError def sendString(self, data): """ Send an int32-prefixed string to the other end of the connection. """ self.transport.write(pack(self.structFormat, len(data)) + data) class TestInt32(MyInt32StringReceiver): def connectionMade(self): self.received = [] def stringReceived(self, s): self.received.append(s) MAX_LENGTH = 50 closed = 0 def connectionLost(self, reason): self.closed = 1 class Int32TestCase(TestCase, test_basic.IntNTestCaseMixin): protocol = TestInt32 strings = ["a", "b" * 16] illegalStrings = ["\x10\x00\x00\x00aaaaaa"] partialStrings = ["\x00\x00\x00", "hello there", ""] def test_bigReceive(self): r = self.getProtocol() big = "" for s in self.strings * 4: big += pack("!i", len(s)) + s r.dataReceived(big) self.assertEqual(r.received, self.strings * 4)
unknown
codeparrot/codeparrot-clean
"""This module contains general utility code that is used throughout the library. For users of this library, the C{L{log}} function is probably the most interesting. """ __all__ = ['log', 'appendArgs', 'toBase64', 'fromBase64'] import binascii import sys import urlparse from urllib import urlencode elementtree_modules = [ 'lxml.etree', 'xml.etree.cElementTree', 'xml.etree.ElementTree', 'cElementTree', 'elementtree.ElementTree', ] def importElementTree(module_names=None): """Find a working ElementTree implementation, trying the standard places that such a thing might show up. >>> ElementTree = importElementTree() @param module_names: The names of modules to try to use as ElementTree. Defaults to C{L{elementtree_modules}} @returns: An ElementTree module """ if module_names is None: module_names = elementtree_modules for mod_name in module_names: try: ElementTree = __import__(mod_name, None, None, ['unused']) except ImportError: pass else: # Make sure it can actually parse XML try: ElementTree.XML('<unused/>') except (SystemExit, MemoryError, AssertionError): raise except: why = sys.exc_info()[1] log('Not using ElementTree library %r because it failed to ' 'parse a trivial document: %s' % (mod_name, why)) else: return ElementTree else: raise def log(message, level=0): """Handle a log message from the OpenID library. This implementation writes the string it to C{sys.stderr}, followed by a newline. Currently, the library does not use the second parameter to this function, but that may change in the future. To install your own logging hook:: from openid import oidutil def myLoggingFunction(message, level): ... oidutil.log = myLoggingFunction @param message: A string containing a debugging message from the OpenID library @type message: str @param level: The severity of the log message. This parameter is currently unused, but in the future, the library may indicate more important information with a higher level value. @type level: int or None @returns: Nothing. """ sys.stderr.write(message) sys.stderr.write('\n') def appendArgs(url, args): """Append query arguments to a HTTP(s) URL. If the URL already has query arguemtns, these arguments will be added, and the existing arguments will be preserved. Duplicate arguments will not be detected or collapsed (both will appear in the output). @param url: The url to which the arguments will be appended @type url: str @param args: The query arguments to add to the URL. If a dictionary is passed, the items will be sorted before appending them to the URL. If a sequence of pairs is passed, the order of the sequence will be preserved. @type args: A dictionary from string to string, or a sequence of pairs of strings. @returns: The URL with the parameters added @rtype: str """ if hasattr(args, 'items'): args = args.items() args.sort() else: args = list(args) if len(args) == 0: return url if '?' in url: sep = '&' else: sep = '?' # Map unicode to UTF-8 if present. Do not make any assumptions # about the encodings of plain bytes (str). i = 0 for k, v in args: if type(k) is not str: k = k.encode('UTF-8') if type(v) is not str: v = v.encode('UTF-8') args[i] = (k, v) i += 1 return '%s%s%s' % (url, sep, urlencode(args)) def toBase64(s): """Represent string s as base64, omitting newlines""" return binascii.b2a_base64(s)[:-1] def fromBase64(s): try: return binascii.a2b_base64(s) except binascii.Error, why: # Convert to a common exception type raise ValueError(why[0]) def isAbsoluteHTTPURL(url): """Does this URL look like a http or https URL that has a host? @param url: The url to check @type url: str @return: Whether the URL looks OK @rtype: bool """ parts = urlparse.urlparse(url) return parts[0] in ['http', 'https'] and parts[1] class Symbol(object): """This class implements an object that compares equal to others of the same type that have the same name. These are distict from str or unicode objects. """ def __init__(self, name): self.name = name def __eq__(self, other): return type(self) is type(other) and self.name == other.name def __ne__(self, other): return not (self == other) def __hash__(self): return hash((self.__class__, self.name)) def __repr__(self): return '<Symbol %s>' % (self.name,)
unknown
codeparrot/codeparrot-clean
// Copyright 2022 The etcd Authors // // 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. package common import ( "context" "os" "strings" "testing" "time" "github.com/stretchr/testify/require" clientv3 "go.etcd.io/etcd/client/v3" "go.etcd.io/etcd/tests/v3/framework/config" "go.etcd.io/etcd/tests/v3/framework/testutils" ) func TestAlarm(t *testing.T) { testRunner.BeforeTest(t) ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) defer cancel() clus := testRunner.NewCluster(ctx, t, config.WithClusterSize(1), config.WithQuotaBackendBytes(int64(13*os.Getpagesize())), ) defer clus.Close() cc := testutils.MustClient(clus.Client()) testutils.ExecuteUntil(ctx, t, func() { // test small put still works smallbuf := strings.Repeat("a", 64) _, err := cc.Put(ctx, "1st_test", smallbuf, config.PutOptions{}) require.NoErrorf(t, err, "alarmTest: put kv error") // write some chunks to fill up the database buf := strings.Repeat("b", os.Getpagesize()) for { if _, err = cc.Put(ctx, "2nd_test", buf, config.PutOptions{}); err != nil { require.ErrorContains(t, err, "etcdserver: mvcc: database space exceeded") break } } // quota alarm should now be on alarmResp, err := cc.AlarmList(ctx) require.NoErrorf(t, err, "alarmTest: Alarm error") // check that Put is rejected when alarm is on if _, err = cc.Put(ctx, "3rd_test", smallbuf, config.PutOptions{}); err != nil { require.ErrorContains(t, err, "etcdserver: mvcc: database space exceeded") } // get latest revision to compact sresp, err := cc.Status(ctx) require.NoErrorf(t, err, "get endpoint status error") var rvs int64 for _, resp := range sresp { if resp != nil && resp.Header != nil { rvs = resp.Header.Revision break } } // make some space _, err = cc.Compact(ctx, rvs, config.CompactOption{Physical: true, Timeout: 10 * time.Second}) require.NoErrorf(t, err, "alarmTest: Compact error") err = cc.Defragment(ctx, config.DefragOption{Timeout: 10 * time.Second}) require.NoErrorf(t, err, "alarmTest: defrag error") // turn off alarm for _, alarm := range alarmResp.Alarms { alarmMember := &clientv3.AlarmMember{ MemberID: alarm.MemberID, Alarm: alarm.Alarm, } _, err = cc.AlarmDisarm(ctx, alarmMember) require.NoErrorf(t, err, "alarmTest: Alarm error") } // put one more key below quota _, err = cc.Put(ctx, "4th_test", smallbuf, config.PutOptions{}) require.NoError(t, err) }) } func TestAlarmlistOnMemberRestart(t *testing.T) { testRunner.BeforeTest(t) ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) defer cancel() clus := testRunner.NewCluster(ctx, t, config.WithClusterSize(1), config.WithQuotaBackendBytes(int64(13*os.Getpagesize())), config.WithSnapshotCount(5), ) defer clus.Close() cc := testutils.MustClient(clus.Client()) testutils.ExecuteUntil(ctx, t, func() { for i := 0; i < 6; i++ { _, err := cc.AlarmList(ctx) require.NoError(t, err) } clus.Members()[0].Stop() err := clus.Members()[0].Start(ctx) require.NoErrorf(t, err, "failed to start etcdserver") }) }
go
github
https://github.com/etcd-io/etcd
tests/common/alarm_test.go
"""Converts Illumina SampleSheet CSV files to the run_info.yaml input file. This allows running the analysis pipeline without Galaxy, using CSV input files from Illumina SampleSheet or Genesifter. """ import os import csv import itertools import difflib import glob import yaml from bcbio.illumina import flowcell from bcbio import utils # ## Create samplesheets def from_flowcell(run_folder, lane_details, out_dir=None): """Convert a flowcell into a samplesheet for demultiplexing. """ fcid = os.path.basename(run_folder) if out_dir is None: out_dir = run_folder out_file = os.path.join(out_dir, "%s.csv" % fcid) with open(out_file, "w") as out_handle: writer = csv.writer(out_handle) writer.writerow(["FCID", "Lane", "Sample_ID", "SampleRef", "Index", "Description", "Control", "Recipe", "Operator", "SampleProject"]) for ldetail in lane_details: writer.writerow(_lane_detail_to_ss(fcid, ldetail)) return out_file def _lane_detail_to_ss(fcid, ldetail): """Convert information about a lane into Illumina samplesheet output. """ return [fcid, ldetail["lane"], ldetail["name"], ldetail["genome_build"], ldetail["bc_index"], ldetail["description"], "N", "", "", ldetail["project_name"]] # ## Use samplesheets to create YAML files def _organize_lanes(info_iter, barcode_ids): """Organize flat lane information into nested YAML structure. """ all_lanes = [] for (fcid, lane, sampleref), info in itertools.groupby(info_iter, lambda x: (x[0], x[1], x[1])): info = list(info) cur_lane = dict(flowcell_id=fcid, lane=lane, genome_build=info[0][3], analysis="Standard") if not _has_barcode(info): cur_lane["description"] = info[0][1] else: # barcoded sample cur_lane["description"] = "Barcoded lane %s" % lane multiplex = [] for (_, _, sample_id, _, bc_seq) in info: bc_type, bc_id = barcode_ids[bc_seq] multiplex.append(dict(barcode_type=bc_type, barcode_id=bc_id, sequence=bc_seq, name=sample_id)) cur_lane["multiplex"] = multiplex all_lanes.append(cur_lane) return all_lanes def _has_barcode(sample): if sample[0][4]: return True def _generate_barcode_ids(info_iter): """Create unique barcode IDs assigned to sequences """ bc_type = "SampleSheet" barcodes = list(set([x[-1] for x in info_iter])) barcodes.sort() barcode_ids = {} for i, bc in enumerate(barcodes): barcode_ids[bc] = (bc_type, i+1) return barcode_ids def _read_input_csv(in_file): """Parse useful details from SampleSheet CSV file. """ with open(in_file, "rU") as in_handle: reader = csv.reader(in_handle) reader.next() # header for line in reader: if line: # empty lines (fc_id, lane, sample_id, genome, barcode) = line[:5] yield fc_id, lane, sample_id, genome, barcode def _get_flowcell_id(in_file, require_single=True): """Retrieve the unique flowcell id represented in the SampleSheet. """ fc_ids = set([x[0] for x in _read_input_csv(in_file)]) if require_single and len(fc_ids) > 1: raise ValueError("There are several FCIDs in the same samplesheet file: %s" % in_file) else: return fc_ids def csv2yaml(in_file, out_file=None): """Convert a CSV SampleSheet to YAML run_info format. """ if out_file is None: out_file = "%s.yaml" % os.path.splitext(in_file)[0] barcode_ids = _generate_barcode_ids(_read_input_csv(in_file)) lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids) with open(out_file, "w") as out_handle: out_handle.write(yaml.safe_dump(lanes, default_flow_style=False)) return out_file def run_has_samplesheet(fc_dir, config, require_single=True): """Checks if there's a suitable SampleSheet.csv present for the run """ fc_name, _ = flowcell.parse_dirname(fc_dir) sheet_dirs = config.get("samplesheet_directories", []) fcid_sheet = {} for ss_dir in (s for s in sheet_dirs if os.path.exists(s)): with utils.chdir(ss_dir): for ss in glob.glob("*.csv"): fc_ids = _get_flowcell_id(ss, require_single) for fcid in fc_ids: if fcid: fcid_sheet[fcid] = os.path.join(ss_dir, ss) # difflib handles human errors while entering data on the SampleSheet. # Only one best candidate is returned (if any). 0.85 cutoff allows for # maximum of 2 mismatches in fcid potential_fcids = difflib.get_close_matches(fc_name, fcid_sheet.keys(), 1, 0.85) if len(potential_fcids) > 0 and fcid_sheet.has_key(potential_fcids[0]): return fcid_sheet[potential_fcids[0]] else: return None
unknown
codeparrot/codeparrot-clean
prompt_template = """Given the following question and context, return YES if the context is relevant to the question and NO if it isn't. > Question: {question} > Context: >>> {context} >>> > Relevant (YES / NO):""" # noqa: E501
python
github
https://github.com/langchain-ai/langchain
libs/langchain/langchain_classic/retrievers/document_compressors/chain_filter_prompt.py
def npartitions(n): """ Calculate the partition function P(n), i.e. the number of ways that n can be written as a sum of positive integers. P(n) is computed using a straightforward implementation of the Hardy-Ramanujan-Rademacher formula, described e.g. at http://mathworld.wolfram.com/PartitionFunctionP.html The speed is decent up to n = 10**5 or so. The function has been tested to give the correct result for n = 10**6. """ n = int(n) if n < 0: return 0 if n <= 5: return [1, 1, 2, 3, 5, 7][n] from sympy.core.numbers import gcd from sympy.numerics import Float from sympy.numerics.functions import pi_float, sqrt, exp, log, cos def frac(x): return x - int(x) def D(n, j): pi = pi_float() a = sqrt(Float(2)/3) * pi / j b = Float(n) - Float(1)/24 c = sqrt(b) expa = exp(a*c) iexpa = Float(1)/expa ch = (expa + iexpa)*0.5 sh = (expa - iexpa)*0.5 return sqrt(j) / (2*sqrt(2)*b*pi) * (a*ch-sh/c) def A(n, j): if j == 1: return Float(1) s = Float(0) pi = pi_float() for h in xrange(1, j): if gcd(h,j) == 1: s += cos((g(h,j)-2*h*n)*pi/j) return s def g(h, j): if j < 3: return Float(0) s = Float(0) for k in xrange(1, j): s += k*(frac(h*Float(k)/j)-0.5) return s # estimate number of digits in p(n) pdigits = int((pi_float()*sqrt(2.0*n/3)-log(4*n))/log(10)+1) Float.store() Float.setdps(pdigits*1.1 + 10) s = Float(0) M = max(6, int(0.24*sqrt(n)+4)) for q in xrange(1, M): s += A(n,q) * D(n,q) p = int(s + 0.5) Float.revert() return p
unknown
codeparrot/codeparrot-clean