repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
UWPCE-PythonCert/IntroPython2016
students/baumel/session_02/grid_printer.py
3
2166
"""this is a lab to create grid patterns""" #first version simple print statement def grid_printer(): print('+ - - - - + - - - - +') print('| | |') print('| | |') print('| | |') print('| | |') print('+ - - - - + - - - - +') print('| | |') print('| | |') print('| | |') print('| | |') print('+ - - - - + - - - - +') #version 2 using values as print objects def print_grid(n): sides = "|" apex = "+ " topBottom = "- " top = apex+topBottom*n+apex+topBottom*n+apex wall = sides+" "*(n)+" " count = n print(top) wallMaker(n) print(top) wallMaker(n) print(top) #top helper method def topMaker(n, squares): apex = "+ " lines = "- " top = ((apex+lines*n)*squares)+apex print(top) #wall making helper method def wallMaker(n, squares): count = n sides = "|" wall = sides+" "*(n)+" " #loops through to make enough walls while count !=0: print(wall*(squares+1)) count -= 1 #main grid making method def print_grid2(squares, size): counter = squares #loop to print the boxes while counter != 0: topMaker(size,squares) wallMaker(size,squares) counter -=1 topMaker(size, squares) def main(): squares = eval(input("How many squares would you like? ")) size = eval(input("what size squares would you like? ")) if squares <= 0 or size <= 0: print("INVALID ENTRY. BOTH VALUES MUST BE GREATER THAN 0!") keepGoing = input("Would you like to try again (y/n)? ") again(keepGoing) else: print_grid2(squares, size) keepGoing = input("Would you like to make another grid (y/n)? ") again(keepGoing) def again(keepGoing): if keepGoing.lower() == 'y': main() elif keepGoing.lower() == 'n': print('Thanks, see ya later') else: again(input("Please enter (y/n)? ")) main() #print_grid2(3,4) #print() #print_grid2(5,3) #print() #print_grid2(2,6) #print() #print_grid2(9,1)
unlicense
mollstam/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Python-2.7.10/Lib/idlelib/IdleHistory.py
122
4052
"Implement Idle Shell history mechanism with History class" from idlelib.configHandler import idleConf class History: ''' Implement Idle Shell history mechanism. store - Store source statement (called from PyShell.resetoutput). fetch - Fetch stored statement matching prefix already entered. history_next - Bound to <<history-next>> event (default Alt-N). history_prev - Bound to <<history-prev>> event (default Alt-P). ''' def __init__(self, text): '''Initialize data attributes and bind event methods. .text - Idle wrapper of tk Text widget, with .bell(). .history - source statements, possibly with multiple lines. .prefix - source already entered at prompt; filters history list. .pointer - index into history. .cyclic - wrap around history list (or not). ''' self.text = text self.history = [] self.prefix = None self.pointer = None self.cyclic = idleConf.GetOption("main", "History", "cyclic", 1, "bool") text.bind("<<history-previous>>", self.history_prev) text.bind("<<history-next>>", self.history_next) def history_next(self, event): "Fetch later statement; start with ealiest if cyclic." self.fetch(reverse=False) return "break" def history_prev(self, event): "Fetch earlier statement; start with most recent." self.fetch(reverse=True) return "break" def fetch(self, reverse): '''Fetch statememt and replace current line in text widget. Set prefix and pointer as needed for successive fetches. Reset them to None, None when returning to the start line. Sound bell when return to start line or cannot leave a line because cyclic is False. ''' nhist = len(self.history) pointer = self.pointer prefix = self.prefix if pointer is not None and prefix is not None: if self.text.compare("insert", "!=", "end-1c") or \ self.text.get("iomark", "end-1c") != self.history[pointer]: pointer = prefix = None self.text.mark_set("insert", "end-1c") # != after cursor move if pointer is None or prefix is None: prefix = self.text.get("iomark", "end-1c") if reverse: pointer = nhist # will be decremented else: if self.cyclic: pointer = -1 # will be incremented else: # abort history_next self.text.bell() return nprefix = len(prefix) while 1: pointer += -1 if reverse else 1 if pointer < 0 or pointer >= nhist: self.text.bell() if not self.cyclic and pointer < 0: # abort history_prev return else: if self.text.get("iomark", "end-1c") != prefix: self.text.delete("iomark", "end-1c") self.text.insert("iomark", prefix) pointer = prefix = None break item = self.history[pointer] if item[:nprefix] == prefix and len(item) > nprefix: self.text.delete("iomark", "end-1c") self.text.insert("iomark", item) break self.text.see("insert") self.text.tag_remove("sel", "1.0", "end") self.pointer = pointer self.prefix = prefix def store(self, source): "Store Shell input statement into history list." source = source.strip() if len(source) > 2: # avoid duplicates try: self.history.remove(source) except ValueError: pass self.history.append(source) self.pointer = None self.prefix = None if __name__ == "__main__": from unittest import main main('idlelib.idle_test.test_idlehistory', verbosity=2, exit=False)
mit
rush-skills/ZeroNet
src/lib/PySocks/socks.py
23
27442
""" SocksiPy - Python SOCKS module. Version 1.5.3 Copyright 2006 Dan-Haim. 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 Dan Haim nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY DAN HAIM "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 DAN HAIM OR HIS 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, 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 DAMANGE. This module provides a standard socket-like interface for Python for tunneling connections through SOCKS proxies. =============================================================================== Minor modifications made by Christopher Gilbert (http://motomastyle.com/) for use in PyLoris (http://pyloris.sourceforge.net/) Minor modifications made by Mario Vilas (http://breakingcode.wordpress.com/) mainly to merge bug fixes found in Sourceforge Modifications made by Anorov (https://github.com/Anorov) -Forked and renamed to PySocks -Fixed issue with HTTP proxy failure checking (same bug that was in the old ___recvall() method) -Included SocksiPyHandler (sockshandler.py), to be used as a urllib2 handler, courtesy of e000 (https://github.com/e000): https://gist.github.com/869791#file_socksipyhandler.py -Re-styled code to make it readable -Aliased PROXY_TYPE_SOCKS5 -> SOCKS5 etc. -Improved exception handling and output -Removed irritating use of sequence indexes, replaced with tuple unpacked variables -Fixed up Python 3 bytestring handling - chr(0x03).encode() -> b"\x03" -Other general fixes -Added clarification that the HTTP proxy connection method only supports CONNECT-style tunneling HTTP proxies -Various small bug fixes """ __version__ = "1.5.3" import socket import struct from errno import EOPNOTSUPP, EINVAL, EAGAIN from io import BytesIO from os import SEEK_CUR from collections import Callable PROXY_TYPE_SOCKS4 = SOCKS4 = 1 PROXY_TYPE_SOCKS5 = SOCKS5 = 2 PROXY_TYPE_HTTP = HTTP = 3 PROXY_TYPES = {"SOCKS4": SOCKS4, "SOCKS5": SOCKS5, "HTTP": HTTP} PRINTABLE_PROXY_TYPES = dict(zip(PROXY_TYPES.values(), PROXY_TYPES.keys())) _orgsocket = _orig_socket = socket.socket class ProxyError(IOError): """ socket_err contains original socket.error exception. """ def __init__(self, msg, socket_err=None): self.msg = msg self.socket_err = socket_err if socket_err: self.msg += ": {0}".format(socket_err) def __str__(self): return self.msg class GeneralProxyError(ProxyError): pass class ProxyConnectionError(ProxyError): pass class SOCKS5AuthError(ProxyError): pass class SOCKS5Error(ProxyError): pass class SOCKS4Error(ProxyError): pass class HTTPError(ProxyError): pass SOCKS4_ERRORS = { 0x5B: "Request rejected or failed", 0x5C: "Request rejected because SOCKS server cannot connect to identd on the client", 0x5D: "Request rejected because the client program and identd report different user-ids" } SOCKS5_ERRORS = { 0x01: "General SOCKS server failure", 0x02: "Connection not allowed by ruleset", 0x03: "Network unreachable", 0x04: "Host unreachable", 0x05: "Connection refused", 0x06: "TTL expired", 0x07: "Command not supported, or protocol error", 0x08: "Address type not supported" } DEFAULT_PORTS = { SOCKS4: 1080, SOCKS5: 1080, HTTP: 8080 } def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): """ set_default_proxy(proxy_type, addr[, port[, rdns[, username, password]]]) Sets a default proxy which all further socksocket objects will use, unless explicitly changed. All parameters are as for socket.set_proxy(). """ socksocket.default_proxy = (proxy_type, addr, port, rdns, username.encode() if username else None, password.encode() if password else None) setdefaultproxy = set_default_proxy def get_default_proxy(): """ Returns the default proxy, set by set_default_proxy. """ return socksocket.default_proxy getdefaultproxy = get_default_proxy def wrap_module(module): """ Attempts to replace a module's socket library with a SOCKS socket. Must set a default proxy using set_default_proxy(...) first. This will only work on modules that import socket directly into the namespace; most of the Python Standard Library falls into this category. """ if socksocket.default_proxy: module.socket.socket = socksocket else: raise GeneralProxyError("No default proxy specified") wrapmodule = wrap_module def create_connection(dest_pair, proxy_type=None, proxy_addr=None, proxy_port=None, proxy_username=None, proxy_password=None, timeout=None, source_address=None): """create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object Like socket.create_connection(), but connects to proxy before returning the socket object. dest_pair - 2-tuple of (IP/hostname, port). **proxy_args - Same args passed to socksocket.set_proxy() if present. timeout - Optional socket timeout value, in seconds. source_address - tuple (host, port) for the socket to bind to as its source address before connecting (only for compatibility) """ sock = socksocket() if isinstance(timeout, (int, float)): sock.settimeout(timeout) if proxy_type is not None: sock.set_proxy(proxy_type, proxy_addr, proxy_port, proxy_username, proxy_password) sock.connect(dest_pair) return sock class _BaseSocket(socket.socket): """Allows Python 2's "delegated" methods such as send() to be overridden """ def __init__(self, *pos, **kw): _orig_socket.__init__(self, *pos, **kw) self._savedmethods = dict() for name in self._savenames: self._savedmethods[name] = getattr(self, name) delattr(self, name) # Allows normal overriding mechanism to work _savenames = list() def _makemethod(name): return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw) for name in ("sendto", "send", "recvfrom", "recv"): method = getattr(_BaseSocket, name, None) # Determine if the method is not defined the usual way # as a function in the class. # Python 2 uses __slots__, so there are descriptors for each method, # but they are not functions. if not isinstance(method, Callable): _BaseSocket._savenames.append(name) setattr(_BaseSocket, name, _makemethod(name)) class socksocket(_BaseSocket): """socksocket([family[, type[, proto]]]) -> socket object Open a SOCKS enabled socket. The parameters are the same as those of the standard socket init. In order for SOCKS to work, you must specify family=AF_INET and proto=0. The "type" argument must be either SOCK_STREAM or SOCK_DGRAM. """ default_proxy = None def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, _sock=None): if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM): msg = "Socket type must be stream or datagram, not {!r}" raise ValueError(msg.format(type)) _BaseSocket.__init__(self, family, type, proto, _sock) self._proxyconn = None # TCP connection to keep UDP relay alive if self.default_proxy: self.proxy = self.default_proxy else: self.proxy = (None, None, None, None, None, None) self.proxy_sockname = None self.proxy_peername = None def _readall(self, file, count): """ Receive EXACTLY the number of bytes requested from the file object. Blocks until the required number of bytes have been received. """ data = b"" while len(data) < count: d = file.read(count - len(data)) if not d: raise GeneralProxyError("Connection closed unexpectedly") data += d return data def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None): """set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxy_type - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The port of the server. Defaults to 1080 for SOCKS servers and 8080 for HTTP proxy servers. rdns - Should DNS queries be performed on the remote side (rather than the local side). The default is True. Note: This has no effect with SOCKS4 servers. username - Username to authenticate with to the server. The default is no authentication. password - Password to authenticate with to the server. Only relevant when username is also provided. """ self.proxy = (proxy_type, addr, port, rdns, username.encode() if username else None, password.encode() if password else None) setproxy = set_proxy def bind(self, *pos, **kw): """ Implements proxy connection for UDP sockets, which happens during the bind() phase. """ proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy if not proxy_type or self.type != socket.SOCK_DGRAM: return _orig_socket.bind(self, *pos, **kw) if self._proxyconn: raise socket.error(EINVAL, "Socket already bound to an address") if proxy_type != SOCKS5: msg = "UDP only supported by SOCKS5 proxy type" raise socket.error(EOPNOTSUPP, msg) _BaseSocket.bind(self, *pos, **kw) # Need to specify actual local port because # some relays drop packets if a port of zero is specified. # Avoid specifying host address in case of NAT though. _, port = self.getsockname() dst = ("0", port) self._proxyconn = _orig_socket() proxy = self._proxy_addr() self._proxyconn.connect(proxy) UDP_ASSOCIATE = b"\x03" _, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst) # The relay is most likely on the same host as the SOCKS proxy, # but some proxies return a private IP address (10.x.y.z) host, _ = proxy _, port = relay _BaseSocket.connect(self, (host, port)) self.proxy_sockname = ("0.0.0.0", 0) # Unknown def sendto(self, bytes, *args, **kwargs): if self.type != socket.SOCK_DGRAM: return _BaseSocket.sendto(self, bytes, *args, **kwargs) if not self._proxyconn: self.bind(("", 0)) address = args[-1] flags = args[:-1] header = BytesIO() RSV = b"\x00\x00" header.write(RSV) STANDALONE = b"\x00" header.write(STANDALONE) self._write_SOCKS5_address(address, header) sent = _BaseSocket.send(self, header.getvalue() + bytes, *flags, **kwargs) return sent - header.tell() def send(self, bytes, flags=0, **kwargs): if self.type == socket.SOCK_DGRAM: return self.sendto(bytes, flags, self.proxy_peername, **kwargs) else: return _BaseSocket.send(self, bytes, flags, **kwargs) def recvfrom(self, bufsize, flags=0): if self.type != socket.SOCK_DGRAM: return _BaseSocket.recvfrom(self, bufsize, flags) if not self._proxyconn: self.bind(("", 0)) buf = BytesIO(_BaseSocket.recv(self, bufsize, flags)) buf.seek(+2, SEEK_CUR) frag = buf.read(1) if ord(frag): raise NotImplementedError("Received UDP packet fragment") fromhost, fromport = self._read_SOCKS5_address(buf) if self.proxy_peername: peerhost, peerport = self.proxy_peername if fromhost != peerhost or peerport not in (0, fromport): raise socket.error(EAGAIN, "Packet filtered") return (buf.read(), (fromhost, fromport)) def recv(self, *pos, **kw): bytes, _ = self.recvfrom(*pos, **kw) return bytes def close(self): if self._proxyconn: self._proxyconn.close() return _BaseSocket.close(self) def get_proxy_sockname(self): """ Returns the bound IP address and port number at the proxy. """ return self.proxy_sockname getproxysockname = get_proxy_sockname def get_proxy_peername(self): """ Returns the IP and port number of the proxy. """ return _BaseSocket.getpeername(self) getproxypeername = get_proxy_peername def get_peername(self): """ Returns the IP address and port number of the destination machine (note: get_proxy_peername returns the proxy) """ return self.proxy_peername getpeername = get_peername def _negotiate_SOCKS5(self, *dest_addr): """ Negotiates a stream connection through a SOCKS5 server. """ CONNECT = b"\x01" self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(self, CONNECT, dest_addr) def _SOCKS5_request(self, conn, cmd, dst): """ Send SOCKS5 request with given command (CMD field) and address (DST field). Returns resolved DST address that was used. """ proxy_type, addr, port, rdns, username, password = self.proxy writer = conn.makefile("wb") reader = conn.makefile("rb", 0) # buffering=0 renamed in Python 3 try: # First we'll send the authentication packages we support. if username and password: # The username/password details were supplied to the # set_proxy method so we support the USERNAME/PASSWORD # authentication (in addition to the standard none). writer.write(b"\x05\x02\x00\x02") else: # No username/password were entered, therefore we # only support connections with no authentication. writer.write(b"\x05\x01\x00") # We'll receive the server's response to determine which # method was selected writer.flush() chosen_auth = self._readall(reader, 2) if chosen_auth[0:1] != b"\x05": # Note: string[i:i+1] is used because indexing of a bytestring # via bytestring[i] yields an integer in Python 3 raise GeneralProxyError("SOCKS5 proxy server sent invalid data") # Check the chosen authentication method if chosen_auth[1:2] == b"\x02": # Okay, we need to perform a basic username/password # authentication. writer.write(b"\x01" + chr(len(username)).encode() + username + chr(len(password)).encode() + password) writer.flush() auth_status = self._readall(reader, 2) if auth_status[0:1] != b"\x01": # Bad response raise GeneralProxyError("SOCKS5 proxy server sent invalid data") if auth_status[1:2] != b"\x00": # Authentication failed raise SOCKS5AuthError("SOCKS5 authentication failed") # Otherwise, authentication succeeded # No authentication is required if 0x00 elif chosen_auth[1:2] != b"\x00": # Reaching here is always bad if chosen_auth[1:2] == b"\xFF": raise SOCKS5AuthError("All offered SOCKS5 authentication methods were rejected") else: raise GeneralProxyError("SOCKS5 proxy server sent invalid data") # Now we can request the actual connection writer.write(b"\x05" + cmd + b"\x00") resolved = self._write_SOCKS5_address(dst, writer) writer.flush() # Get the response resp = self._readall(reader, 3) if resp[0:1] != b"\x05": raise GeneralProxyError("SOCKS5 proxy server sent invalid data") status = ord(resp[1:2]) if status != 0x00: # Connection failed: server returned an error error = SOCKS5_ERRORS.get(status, "Unknown error") raise SOCKS5Error("{0:#04x}: {1}".format(status, error)) # Get the bound address/port bnd = self._read_SOCKS5_address(reader) return (resolved, bnd) finally: reader.close() writer.close() def _write_SOCKS5_address(self, addr, file): """ Return the host and port packed for the SOCKS5 protocol, and the resolved address as a tuple object. """ host, port = addr proxy_type, _, _, rdns, username, password = self.proxy # If the given destination address is an IP address, we'll # use the IPv4 address request even if remote resolving was specified. try: addr_bytes = socket.inet_aton(host) file.write(b"\x01" + addr_bytes) host = socket.inet_ntoa(addr_bytes) except socket.error: # Well it's not an IP number, so it's probably a DNS name. if rdns: # Resolve remotely host_bytes = host.encode('idna') file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes) else: # Resolve locally addr_bytes = socket.inet_aton(socket.gethostbyname(host)) file.write(b"\x01" + addr_bytes) host = socket.inet_ntoa(addr_bytes) file.write(struct.pack(">H", port)) return host, port def _read_SOCKS5_address(self, file): atyp = self._readall(file, 1) if atyp == b"\x01": addr = socket.inet_ntoa(self._readall(file, 4)) elif atyp == b"\x03": length = self._readall(file, 1) addr = self._readall(file, ord(length)) else: raise GeneralProxyError("SOCKS5 proxy server sent invalid data") port = struct.unpack(">H", self._readall(file, 2))[0] return addr, port def _negotiate_SOCKS4(self, dest_addr, dest_port): """ Negotiates a connection through a SOCKS4 server. """ proxy_type, addr, port, rdns, username, password = self.proxy writer = self.makefile("wb") reader = self.makefile("rb", 0) # buffering=0 renamed in Python 3 try: # Check if the destination address provided is an IP address remote_resolve = False try: addr_bytes = socket.inet_aton(dest_addr) except socket.error: # It's a DNS name. Check where it should be resolved. if rdns: addr_bytes = b"\x00\x00\x00\x01" remote_resolve = True else: addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr)) # Construct the request packet writer.write(struct.pack(">BBH", 0x04, 0x01, dest_port)) writer.write(addr_bytes) # The username parameter is considered userid for SOCKS4 if username: writer.write(username) writer.write(b"\x00") # DNS name if remote resolving is required # NOTE: This is actually an extension to the SOCKS4 protocol # called SOCKS4A and may not be supported in all cases. if remote_resolve: writer.write(dest_addr.encode('idna') + b"\x00") writer.flush() # Get the response from the server resp = self._readall(reader, 8) if resp[0:1] != b"\x00": # Bad data raise GeneralProxyError("SOCKS4 proxy server sent invalid data") status = ord(resp[1:2]) if status != 0x5A: # Connection failed: server returned an error error = SOCKS4_ERRORS.get(status, "Unknown error") raise SOCKS4Error("{0:#04x}: {1}".format(status, error)) # Get the bound address/port self.proxy_sockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0]) if remote_resolve: self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port else: self.proxy_peername = dest_addr, dest_port finally: reader.close() writer.close() def _negotiate_HTTP(self, dest_addr, dest_port): """ Negotiates a connection through an HTTP server. NOTE: This currently only supports HTTP CONNECT-style proxies. """ proxy_type, addr, port, rdns, username, password = self.proxy # If we need to resolve locally, we do this now addr = dest_addr if rdns else socket.gethostbyname(dest_addr) self.sendall(b"CONNECT " + addr.encode('idna') + b":" + str(dest_port).encode() + b" HTTP/1.1\r\n" + b"Host: " + dest_addr.encode('idna') + b"\r\n\r\n") # We just need the first line to check if the connection was successful fobj = self.makefile() status_line = fobj.readline() fobj.close() if not status_line: raise GeneralProxyError("Connection closed unexpectedly") try: proto, status_code, status_msg = status_line.split(" ", 2) except ValueError: raise GeneralProxyError("HTTP proxy server sent invalid response") if not proto.startswith("HTTP/"): raise GeneralProxyError("Proxy server does not appear to be an HTTP proxy") try: status_code = int(status_code) except ValueError: raise HTTPError("HTTP proxy server did not return a valid HTTP status") if status_code != 200: error = "{0}: {1}".format(status_code, status_msg) if status_code in (400, 403, 405): # It's likely that the HTTP proxy server does not support the CONNECT tunneling method error += ("\n[*] Note: The HTTP proxy server may not be supported by PySocks" " (must be a CONNECT tunnel proxy)") raise HTTPError(error) self.proxy_sockname = (b"0.0.0.0", 0) self.proxy_peername = addr, dest_port _proxy_negotiators = { SOCKS4: _negotiate_SOCKS4, SOCKS5: _negotiate_SOCKS5, HTTP: _negotiate_HTTP } def connect(self, dest_pair): """ Connects to the specified destination through a proxy. Uses the same API as socket's connect(). To select the proxy server, use set_proxy(). dest_pair - 2-tuple of (IP/hostname, port). """ dest_addr, dest_port = dest_pair if self.type == socket.SOCK_DGRAM: if not self._proxyconn: self.bind(("", 0)) dest_addr = socket.gethostbyname(dest_addr) # If the host address is INADDR_ANY or similar, reset the peer # address so that packets are received from any peer if dest_addr == "0.0.0.0" and not dest_port: self.proxy_peername = None else: self.proxy_peername = (dest_addr, dest_port) return proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy # Do a minimal input check first if (not isinstance(dest_pair, (list, tuple)) or len(dest_pair) != 2 or not dest_addr or not isinstance(dest_port, int)): raise GeneralProxyError("Invalid destination-connection (host, port) pair") if proxy_type is None: # Treat like regular socket object self.proxy_peername = dest_pair _BaseSocket.connect(self, (dest_addr, dest_port)) return proxy_addr = self._proxy_addr() try: # Initial connection to proxy server _BaseSocket.connect(self, proxy_addr) except socket.error as error: # Error while connecting to proxy self.close() proxy_addr, proxy_port = proxy_addr proxy_server = "{0}:{1}".format(proxy_addr, proxy_port) printable_type = PRINTABLE_PROXY_TYPES[proxy_type] msg = "Error connecting to {0} proxy {1}".format(printable_type, proxy_server) raise ProxyConnectionError(msg, error) else: # Connected to proxy server, now negotiate try: # Calls negotiate_{SOCKS4, SOCKS5, HTTP} negotiate = self._proxy_negotiators[proxy_type] negotiate(self, dest_addr, dest_port) except socket.error as error: # Wrap socket errors self.close() raise GeneralProxyError("Socket error", error) except ProxyError: # Protocol error while negotiating with proxy self.close() raise def _proxy_addr(self): """ Return proxy address to connect to as tuple object """ proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy proxy_port = proxy_port or DEFAULT_PORTS.get(proxy_type) if not proxy_port: raise GeneralProxyError("Invalid proxy type") return proxy_addr, proxy_port
gpl-2.0
andymg/androguard
androguard/core/bytecode.py
37
24731
# This file is part of Androguard. # # Copyright (C) 2012/2013, Anthony Desnos <desnos at t0t0.fr> # 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 hashlib from xml.sax.saxutils import escape from struct import unpack, pack import textwrap import json from androconf import warning, error, CONF, enable_colors, remove_colors, save_colors, color_range def disable_print_colors(): colors = save_colors() remove_colors() return colors def enable_print_colors(colors): enable_colors(colors) # Handle exit message def Exit( msg ): warning("Error : " + msg) raise("oops") def Warning( msg ): warning(msg) def _PrintBanner() : print_fct = CONF["PRINT_FCT"] print_fct("*" * 75 + "\n") def _PrintSubBanner(title=None) : print_fct = CONF["PRINT_FCT"] if title == None : print_fct("#" * 20 + "\n") else : print_fct("#" * 10 + " " + title + "\n") def _PrintNote(note, tab=0) : print_fct = CONF["PRINT_FCT"] note_color = CONF["COLORS"]["NOTE"] normal_color = CONF["COLORS"]["NORMAL"] print_fct("\t" * tab + "%s# %s%s" % (note_color, note, normal_color) + "\n") # Print arg into a correct format def _Print(name, arg) : buff = name + " " if type(arg).__name__ == 'int' : buff += "0x%x" % arg elif type(arg).__name__ == 'long' : buff += "0x%x" % arg elif type(arg).__name__ == 'str' : buff += "%s" % arg elif isinstance(arg, SV) : buff += "0x%x" % arg.get_value() elif isinstance(arg, SVs) : buff += arg.get_value().__str__() print buff def PrettyShowEx(exceptions): if len(exceptions) > 0: CONF["PRINT_FCT"]("Exceptions:\n") for i in exceptions: CONF["PRINT_FCT"]("\t%s%s%s\n" % (CONF["COLORS"]["EXCEPTION"], i.show_buff(), CONF["COLORS"]["NORMAL"])) def _PrintXRef(tag, items): print_fct = CONF["PRINT_FCT"] for i in items: print_fct("%s: %s %s %s %s\n" % (tag, i[0].get_class_name(), i[0].get_name(), i[0].get_descriptor(), ' '.join("%x" % j.get_idx() for j in i[1]))) def _PrintDRef(tag, items): print_fct = CONF["PRINT_FCT"] for i in items: print_fct("%s: %s %s %s %s\n" % (tag, i[0].get_class_name(), i[0].get_name(), i[0].get_descriptor(), ' '.join("%x" % j for j in i[1]))) def _PrintDefault(msg): print_fct = CONF["PRINT_FCT"] print_fct(msg) def PrettyShow(m_a, basic_blocks, notes={}): idx = 0 nb = 0 offset_color = CONF["COLORS"]["OFFSET"] offset_addr_color = CONF["COLORS"]["OFFSET_ADDR"] instruction_name_color = CONF["COLORS"]["INSTRUCTION_NAME"] branch_false_color = CONF["COLORS"]["BRANCH_FALSE"] branch_true_color = CONF["COLORS"]["BRANCH_TRUE"] branch_color = CONF["COLORS"]["BRANCH"] exception_color = CONF["COLORS"]["EXCEPTION"] bb_color = CONF["COLORS"]["BB"] normal_color = CONF["COLORS"]["NORMAL"] print_fct = CONF["PRINT_FCT"] colors = CONF["COLORS"]["OUTPUT"] for i in basic_blocks: print_fct("%s%s%s : \n" % (bb_color, i.get_name(), normal_color)) instructions = i.get_instructions() for ins in instructions: if nb in notes: for note in notes[nb]: _PrintNote(note, 1) print_fct("\t%s%-3d%s(%s%08x%s) " % (offset_color, nb, normal_color, offset_addr_color, idx, normal_color)) print_fct("%s%-20s%s" % (instruction_name_color, ins.get_name(), normal_color)) operands = ins.get_operands() print_fct("%s" % ", ".join(m_a.get_vm().colorize_operands(operands, colors))) op_value = ins.get_op_value() if ins == instructions[-1] and i.childs: print_fct(" ") # packed/sparse-switch if (op_value == 0x2b or op_value == 0x2c) and len(i.childs) > 1: values = i.get_special_ins(idx).get_values() print_fct("%s[ D:%s%s " % (branch_false_color, i.childs[0][2].get_name(), branch_color)) print_fct(' '.join("%d:%s" % (values[j], i.childs[j + 1][2].get_name()) for j in range(0, len(i.childs) - 1)) + " ]%s" % normal_color) else: if len(i.childs) == 2: print_fct("%s[ %s%s " % (branch_false_color, i.childs[0][2].get_name(), branch_true_color)) print_fct(' '.join("%s" % c[2].get_name() for c in i.childs[1:]) + " ]%s" % normal_color) else: print_fct("%s[ " % branch_color + ' '.join("%s" % c[2].get_name() for c in i.childs) + " ]%s" % normal_color) idx += ins.get_length() nb += 1 print_fct("\n") if i.get_exception_analysis(): print_fct("\t%s%s%s\n" % (exception_color, i.exception_analysis.show_buff(), normal_color)) print_fct("\n") def method2dot(mx, colors={}): """ Export analysis method to dot format @param mx : MethodAnalysis object @param colors : MethodAnalysis object @rtype : dot format buffer (it is a subgraph (dict)) """ colors = colors or {"true_branch": "green", "false_branch": "red", "default_branch": "purple", "jump_branch": "blue", "bg_idx": "lightgray", "idx": "blue", "bg_start_idx": "yellow", "bg_instruction": "lightgray", "instruction_name": "black", "instructions_operands": "yellow", "raw": "red", "string": "red", "literal": "green", "offset": "#4000FF", "method": "#DF3A01", "field": "#088A08", "type": "#0000FF", "registers_range": ("#999933", "#6666FF") } node_tpl = "\nstruct_%s [label=<\n<TABLE BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"3\">\n%s</TABLE>>];\n" label_tpl = "<TR><TD ALIGN=\"LEFT\" BGCOLOR=\"%s\"> <FONT FACE=\"Times-Bold\" color=\"%s\">%x</FONT> </TD><TD ALIGN=\"LEFT\" BGCOLOR=\"%s\"> <FONT FACE=\"Times-Bold\" color=\"%s\">%s </FONT> %s </TD></TR>\n" link_tpl = "<TR><TD PORT=\"%s\"></TD></TR>\n" edges_html = "" blocks_html = "" method = mx.get_method() sha256 = hashlib.sha256("%s%s%s" % (mx.get_method().get_class_name(), mx.get_method().get_name(), mx.get_method().get_descriptor())).hexdigest() registers = {} if method.get_code(): for DVMBasicMethodBlock in mx.basic_blocks.gets(): for DVMBasicMethodBlockInstruction in DVMBasicMethodBlock.get_instructions(): operands = DVMBasicMethodBlockInstruction.get_operands(0) for register in operands: if register[0] == 0: if register[1] not in registers: registers[register[1]] = 0 registers[register[1]] += 1 # for i in range(method.get_code().get_registers_size()): # registers[i] = 0 if registers: registers_colors = color_range(colors["registers_range"][0], colors["registers_range"][1], len(registers)) for i in registers: registers[i] = registers_colors.pop(0) new_links = [] for DVMBasicMethodBlock in mx.basic_blocks.gets(): ins_idx = DVMBasicMethodBlock.start block_id = hashlib.md5(sha256 + DVMBasicMethodBlock.get_name()).hexdigest() content = link_tpl % 'header' for DVMBasicMethodBlockInstruction in DVMBasicMethodBlock.get_instructions(): if DVMBasicMethodBlockInstruction.get_op_value() == 0x2b or DVMBasicMethodBlockInstruction.get_op_value() == 0x2c: new_links.append((DVMBasicMethodBlock, ins_idx, DVMBasicMethodBlockInstruction.get_ref_off() * 2 + ins_idx)) elif DVMBasicMethodBlockInstruction.get_op_value() == 0x26: new_links.append((DVMBasicMethodBlock, ins_idx, DVMBasicMethodBlockInstruction.get_ref_off() * 2 + ins_idx)) operands = DVMBasicMethodBlockInstruction.get_operands(ins_idx) output = ", ".join(mx.get_vm().get_operand_html(i, registers, colors, escape, textwrap.wrap) for i in operands) formatted_operands = DVMBasicMethodBlockInstruction.get_formatted_operands() if formatted_operands: output += " ; %s" % str(formatted_operands) bg_idx = colors["bg_idx"] if ins_idx == 0 and "bg_start_idx" in colors: bg_idx = colors["bg_start_idx"] content += label_tpl % (bg_idx, colors["idx"], ins_idx, colors["bg_instruction"], colors["instruction_name"], DVMBasicMethodBlockInstruction.get_name(), output) ins_idx += DVMBasicMethodBlockInstruction.get_length() last_instru = DVMBasicMethodBlockInstruction # all blocks from one method parsed # updating dot HTML content content += link_tpl % 'tail' blocks_html += node_tpl % (block_id, content) # Block edges color treatment (conditional branchs colors) val = colors["true_branch"] if len(DVMBasicMethodBlock.childs) > 1: val = colors["false_branch"] elif len(DVMBasicMethodBlock.childs) == 1: val = colors["jump_branch"] values = None if (last_instru.get_op_value() == 0x2b or last_instru.get_op_value() == 0x2c) and len(DVMBasicMethodBlock.childs) > 1: val = colors["default_branch"] values = ["default"] values.extend(DVMBasicMethodBlock.get_special_ins(ins_idx - last_instru.get_length()).get_values()) # updating dot edges for DVMBasicMethodBlockChild in DVMBasicMethodBlock.childs: label_edge = "" if values: label_edge = values.pop(0) child_id = hashlib.md5(sha256 + DVMBasicMethodBlockChild[-1].get_name()).hexdigest() edges_html += "struct_%s:tail -> struct_%s:header [color=\"%s\", label=\"%s\"];\n" % (block_id, child_id, val, label_edge) # color switch if val == colors["false_branch"]: val = colors["true_branch"] elif val == colors["default_branch"]: val = colors["true_branch"] exception_analysis = DVMBasicMethodBlock.get_exception_analysis() if exception_analysis: for exception_elem in exception_analysis.exceptions: exception_block = exception_elem[-1] if exception_block: exception_id = hashlib.md5(sha256 + exception_block.get_name()).hexdigest() edges_html += "struct_%s:tail -> struct_%s:header [color=\"%s\", label=\"%s\"];\n" % (block_id, exception_id, "black", exception_elem[0]) for link in new_links: DVMBasicMethodBlock = link[0] DVMBasicMethodBlockChild = mx.basic_blocks.get_basic_block(link[2]) if DVMBasicMethodBlockChild: block_id = hashlib.md5(sha256 + DVMBasicMethodBlock.get_name()).hexdigest() child_id = hashlib.md5(sha256 + DVMBasicMethodBlockChild.get_name()).hexdigest() edges_html += "struct_%s:tail -> struct_%s:header [color=\"%s\", label=\"data(0x%x) to @0x%x\", style=\"dashed\"];\n" % (block_id, child_id, "yellow", link[1], link[2]) method_label = method.get_class_name() + "." + method.get_name() + "->" + method.get_descriptor() method_information = method.get_information() if method_information: method_label += "\\nLocal registers v%d ... v%d" % (method_information["registers"][0], method_information["registers"][1]) if "params" in method_information: for register, rtype in method_information["params"]: method_label += "\\nparam v%d = %s" % (register, rtype) method_label += "\\nreturn = %s" % (method_information["return"]) return {'name': method_label, 'nodes': blocks_html, 'edges': edges_html} def method2format(output, _format="png", mx=None, raw=None): """ Export method to a specific file format @param output : output filename @param _format : format type (png, jpg ...) (default : png) @param mx : specify the MethodAnalysis object @param raw : use directly a dot raw buffer if None """ try: import pydot except ImportError: error("module pydot not found") buff = "digraph {\n" buff += "graph [rankdir=TB]\n" buff += "node [shape=plaintext]\n" if raw: data = raw else: data = method2dot(mx) # subgraphs cluster buff += "subgraph cluster_" + hashlib.md5(output).hexdigest() + " {\nlabel=\"%s\"\n" % data['name'] buff += data['nodes'] buff += "}\n" # subgraphs edges buff += data['edges'] buff += "}\n" d = pydot.graph_from_dot_data(buff) if d: getattr(d, "write_" + _format.lower())(output) def method2png(output, mx, raw=False): """ Export method to a png file format :param output: output filename :type output: string :param mx: specify the MethodAnalysis object :type mx: :class:`MethodAnalysis` object :param raw: use directly a dot raw buffer :type raw: string """ buff = raw if raw == False: buff = method2dot(mx) method2format(output, "png", mx, buff) def method2jpg(output, mx, raw=False): """ Export method to a jpg file format :param output: output filename :type output: string :param mx: specify the MethodAnalysis object :type mx: :class:`MethodAnalysis` object :param raw: use directly a dot raw buffer (optional) :type raw: string """ buff = raw if raw == False: buff = method2dot(mx) method2format(output, "jpg", mx, buff) def vm2json(vm): d = {} d["name"] = "root" d["children"] = [] for _class in vm.get_classes(): c_class = {} c_class["name"] = _class.get_name() c_class["children"] = [] for method in _class.get_methods(): c_method = {} c_method["name"] = method.get_name() c_method["children"] = [] c_class["children"].append(c_method) d["children"].append(c_class) return json.dumps(d) class TmpBlock: def __init__(self, name): self.name = name def get_name(self): return self.name def method2json(mx, directed_graph=False): if directed_graph: return method2json_direct(mx) return method2json_undirect(mx) def method2json_undirect(mx): d = {} reports = [] d["reports"] = reports for DVMBasicMethodBlock in mx.basic_blocks.gets(): cblock = {} cblock["BasicBlockId"] = DVMBasicMethodBlock.get_name() cblock["registers"] = mx.get_method().get_code().get_registers_size() cblock["instructions"] = [] ins_idx = DVMBasicMethodBlock.start for DVMBasicMethodBlockInstruction in DVMBasicMethodBlock.get_instructions(): c_ins = {} c_ins["idx"] = ins_idx c_ins["name"] = DVMBasicMethodBlockInstruction.get_name() c_ins["operands"] = DVMBasicMethodBlockInstruction.get_operands(ins_idx) cblock["instructions"].append(c_ins) ins_idx += DVMBasicMethodBlockInstruction.get_length() cblock["Edge"] = [] for DVMBasicMethodBlockChild in DVMBasicMethodBlock.childs: cblock["Edge"].append(DVMBasicMethodBlockChild[-1].get_name()) reports.append(cblock) return json.dumps(d) def method2json_direct(mx): d = {} reports = [] d["reports"] = reports hooks = {} l = [] for DVMBasicMethodBlock in mx.basic_blocks.gets(): for index, DVMBasicMethodBlockChild in enumerate(DVMBasicMethodBlock.childs): if DVMBasicMethodBlock.get_name() == DVMBasicMethodBlockChild[-1].get_name(): preblock = TmpBlock(DVMBasicMethodBlock.get_name() + "-pre") cnblock = {} cnblock["BasicBlockId"] = DVMBasicMethodBlock.get_name() + "-pre" cnblock["start"] = DVMBasicMethodBlock.start cnblock["notes"] = [] cnblock["Edge"] = [DVMBasicMethodBlock.get_name()] cnblock["registers"] = 0 cnblock["instructions"] = [] cnblock["info_bb"] = 0 l.append(cnblock) for parent in DVMBasicMethodBlock.fathers: hooks[parent[-1].get_name()] = [] hooks[parent[-1].get_name()].append(preblock) for idx, child in enumerate(parent[-1].childs): if child[-1].get_name() == DVMBasicMethodBlock.get_name(): hooks[parent[-1].get_name()].append(child[-1]) for DVMBasicMethodBlock in mx.basic_blocks.gets(): cblock = {} cblock["BasicBlockId"] = DVMBasicMethodBlock.get_name() cblock["start"] = DVMBasicMethodBlock.start cblock["notes"] = DVMBasicMethodBlock.get_notes() cblock["registers"] = mx.get_method().get_code().get_registers_size() cblock["instructions"] = [] ins_idx = DVMBasicMethodBlock.start last_instru = None for DVMBasicMethodBlockInstruction in DVMBasicMethodBlock.get_instructions(): c_ins = {} c_ins["idx"] = ins_idx c_ins["name"] = DVMBasicMethodBlockInstruction.get_name() c_ins["operands"] = DVMBasicMethodBlockInstruction.get_operands(ins_idx) c_ins["formatted_operands"] = DVMBasicMethodBlockInstruction.get_formatted_operands() cblock["instructions"].append(c_ins) if (DVMBasicMethodBlockInstruction.get_op_value() == 0x2b or DVMBasicMethodBlockInstruction.get_op_value() == 0x2c): values = DVMBasicMethodBlock.get_special_ins(ins_idx) cblock["info_next"] = values.get_values() ins_idx += DVMBasicMethodBlockInstruction.get_length() last_instru = DVMBasicMethodBlockInstruction cblock["info_bb"] = 0 if DVMBasicMethodBlock.childs: if len(DVMBasicMethodBlock.childs) > 1: cblock["info_bb"] = 1 if (last_instru.get_op_value() == 0x2b or last_instru.get_op_value() == 0x2c): cblock["info_bb"] = 2 cblock["Edge"] = [] for DVMBasicMethodBlockChild in DVMBasicMethodBlock.childs: ok = False if DVMBasicMethodBlock.get_name() in hooks: if DVMBasicMethodBlockChild[-1] in hooks[DVMBasicMethodBlock.get_name()]: ok = True cblock["Edge"].append(hooks[DVMBasicMethodBlock.get_name()][0].get_name()) if not ok: cblock["Edge"].append(DVMBasicMethodBlockChild[-1].get_name()) exception_analysis = DVMBasicMethodBlock.get_exception_analysis() if exception_analysis: cblock["Exceptions"] = exception_analysis.get() reports.append(cblock) reports.extend(l) return json.dumps(d) class SV: def __init__(self, size, buff): self.__size = size self.__value = unpack(self.__size, buff)[0] def _get(self): return pack(self.__size, self.__value) def __str__(self) : return "0x%x" % self.__value def __int__(self) : return self.__value def get_value_buff(self) : return self._get() def get_value(self) : return self.__value def set_value(self, attr) : self.__value = attr class SVs : def __init__(self, size, ntuple, buff) : self.__size = size self.__value = ntuple._make( unpack( self.__size, buff ) ) def _get(self) : l = [] for i in self.__value._fields : l.append( getattr( self.__value, i ) ) return pack( self.__size, *l) def _export(self) : return [ x for x in self.__value._fields ] def get_value_buff(self) : return self._get() def get_value(self) : return self.__value def set_value(self, attr) : self.__value = self.__value._replace( **attr ) def __str__(self) : return self.__value.__str__() def object_to_str(obj) : if isinstance(obj, str) : return obj elif isinstance(obj, bool) : return "" elif isinstance(obj, int) : return pack("<L", obj) elif obj == None : return "" else : #print type(obj), obj return obj.get_raw() class MethodBC(object) : def show(self, value) : getattr(self, "show_" + value)() class BuffHandle: def __init__(self, buff): self.__buff = buff self.__idx = 0 def size(self): return len(self.__buff) def set_idx(self, idx): self.__idx = idx def get_idx(self): return self.__idx def readNullString(self, size): data = self.read(size) return data def read_b(self, size) : return self.__buff[ self.__idx : self.__idx + size ] def read_at(self, offset, size): return self.__buff[ offset : offset + size ] def read(self, size) : if isinstance(size, SV) : size = size.value buff = self.__buff[ self.__idx : self.__idx + size ] self.__idx += size return buff def end(self) : return self.__idx == len(self.__buff) class Buff : def __init__(self, offset, buff) : self.offset = offset self.buff = buff self.size = len(buff) class _Bytecode(object): def __init__(self, buff): try : import psyco psyco.full() except ImportError: pass self.__buff = buff self.__idx = 0 def read(self, size) : if isinstance(size, SV) : size = size.value buff = self.__buff[ self.__idx : self.__idx + size ] self.__idx += size return buff def readat(self, off) : if isinstance(off, SV) : off = off.value return self.__buff[ off : ] def read_b(self, size) : return self.__buff[ self.__idx : self.__idx + size ] def set_idx(self, idx) : self.__idx = idx def get_idx(self) : return self.__idx def add_idx(self, idx) : self.__idx += idx def register(self, type_register, fct) : self.__registers[ type_register ].append( fct ) def get_buff(self) : return self.__buff def length_buff(self) : return len( self.__buff ) def set_buff(self, buff) : self.__buff = buff def save(self, filename) : fd = open(filename, "w") buff = self._save() fd.write( buff ) fd.close() def FormatClassToJava(input) : """ Transoform a typical xml format class into java format :param input: the input class name :rtype: string """ return "L" + input.replace(".", "/") + ";" def FormatClassToPython(input) : i = input[:-1] i = i.replace("/", "_") i = i.replace("$", "_") return i def FormatNameToPython(input) : i = input.replace("<", "") i = i.replace(">", "") i = i.replace("$", "_") return i def FormatDescriptorToPython(input) : i = input.replace("/", "_") i = i.replace(";", "") i = i.replace("[", "") i = i.replace("(", "") i = i.replace(")", "") i = i.replace(" ", "") i = i.replace("$", "") return i class Node: def __init__(self, n, s): self.id = n self.title = s self.children = []
apache-2.0
n0trax/ansible
lib/ansible/modules/network/junos/junos_config.py
11
13176
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = """ --- module: junos_config version_added: "2.1" author: "Peter Sprygada (@privateip)" short_description: Manage configuration on devices running Juniper JUNOS description: - This module provides an implementation for working with the active configuration running on Juniper JUNOS devices. It provides a set of arguments for loading configuration, performing rollback operations and zeroing the active configuration on the device. extends_documentation_fragment: junos options: lines: description: - This argument takes a list of C(set) or C(delete) configuration lines to push into the remote device. Each line must start with either C(set) or C(delete). This argument is mutually exclusive with the I(src) argument. required: false default: null src: description: - The I(src) argument provides a path to the configuration file to load into the remote system. The path can either be a full system path to the configuration file if the value starts with / or relative to the root of the implemented role or playbook. This argument is mutually exclusive with the I(lines) argument. required: false default: null version_added: "2.2" src_format: description: - The I(src_format) argument specifies the format of the configuration found int I(src). If the I(src_format) argument is not provided, the module will attempt to determine the format of the configuration file specified in I(src). required: false default: null choices: ['xml', 'set', 'text', 'json'] version_added: "2.2" rollback: description: - The C(rollback) argument instructs the module to rollback the current configuration to the identifier specified in the argument. If the specified rollback identifier does not exist on the remote device, the module will fail. To rollback to the most recent commit, set the C(rollback) argument to 0. required: false default: null zeroize: description: - The C(zeroize) argument is used to completely sanitize the remote device configuration back to initial defaults. This argument will effectively remove all current configuration statements on the remote device. required: false default: null confirm: description: - The C(confirm) argument will configure a time out value for the commit to be confirmed before it is automatically rolled back. If the C(confirm) argument is set to False, this argument is silently ignored. If the value for this argument is set to 0, the commit is confirmed immediately. required: false default: 0 comment: description: - The C(comment) argument specifies a text string to be used when committing the configuration. If the C(confirm) argument is set to False, this argument is silently ignored. required: false default: configured by junos_config replace: description: - The C(replace) argument will instruct the remote device to replace the current configuration hierarchy with the one specified in the corresponding hierarchy of the source configuration loaded from this module. - Note this argument should be considered deprecated. To achieve the equivalent, set the I(update) argument to C(replace). This argument will be removed in a future release. The C(replace) and C(update) argument is mutually exclusive. required: false choices: ['yes', 'no'] default: false backup: description: - This argument will cause the module to create a full backup of the current C(running-config) from the remote device before any changes are made. The backup file is written to the C(backup) folder in the playbook root directory. If the directory does not exist, it is created. required: false default: no choices: ['yes', 'no'] version_added: "2.2" update: description: - This argument will decide how to load the configuration data particulary when the candidate configuration and loaded configuration contain conflicting statements. Following are accepted values. C(merge) combines the data in the loaded configuration with the candidate configuration. If statements in the loaded configuration conflict with statements in the candidate configuration, the loaded statements replace the candidate ones. C(override) discards the entire candidate configuration and replaces it with the loaded configuration. C(replace) substitutes each hierarchy level in the loaded configuration for the corresponding level. required: false default: merge choices: ['merge', 'override', 'replace'] version_added: "2.3" confirm_commit: description: - This argument will execute commit operation on remote device. It can be used to confirm a previous commit. required: false default: no choices: ['yes', 'no'] version_added: "2.4" requirements: - ncclient (>=v0.5.2) notes: - This module requires the netconf system service be enabled on the remote device being managed. - Loading JSON-formatted configuration I(json) is supported starting in Junos OS Release 16.1 onwards. - Tested against vSRX JUNOS version 15.1X49-D15.4, vqfx-10000 JUNOS Version 15.1X53-D60.4. """ EXAMPLES = """ - name: load configure file into device junos_config: src: srx.cfg comment: update config provider: "{{ netconf }}" - name: load configure lines into device junos_config: lines: - set interfaces ge-0/0/1 unit 0 description "Test interface" - set vlans vlan01 description "Test vlan" comment: update config provider: "{{ netconf }}" - name: rollback the configuration to id 10 junos_config: rollback: 10 provider: "{{ netconf }}" - name: zero out the current configuration junos_config: zeroize: yes provider: "{{ netconf }}" - name: confirm a previous commit junos_config: confirm_commit: yes provider: "{{ netconf }}" """ RETURN = """ backup_path: description: The full path to the backup file returned: when backup is yes type: string sample: /playbooks/ansible/backup/config.2016-07-16@22:28:34 """ import re import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.junos import get_diff, load_config, get_configuration from ansible.module_utils.junos import commit_configuration, discard_changes, locked_config from ansible.module_utils.junos import junos_argument_spec from ansible.module_utils.junos import check_args as junos_check_args from ansible.module_utils.netconf import send_request from ansible.module_utils.six import string_types from ansible.module_utils._text import to_native try: from lxml.etree import Element, fromstring except ImportError: from xml.etree.ElementTree import Element, fromstring try: from lxml.etree import ParseError except ImportError: try: from xml.etree.ElementTree import ParseError except ImportError: # for Python < 2.7 from xml.parsers.expat import ExpatError ParseError = ExpatError USE_PERSISTENT_CONNECTION = True DEFAULT_COMMENT = 'configured by junos_config' def check_args(module, warnings): junos_check_args(module, warnings) if module.params['replace'] is not None: module.fail_json(msg='argument replace is deprecated, use update') def zeroize(ele): return send_request(ele, Element('request-system-zeroize')) def rollback(ele): return get_diff(ele) def guess_format(config): try: json.loads(config) return 'json' except ValueError: pass try: fromstring(config) return 'xml' except ParseError: pass if config.startswith('set') or config.startswith('delete'): return 'set' return 'text' def filter_delete_statements(module, candidate): reply = get_configuration(module, format='set') match = reply.find('.//configuration-set') if match is None: # Could not find configuration-set in reply, perhaps device does not support it? return candidate config = to_native(match.text, encoding='latin-1') modified_candidate = candidate[:] for index, line in reversed(list(enumerate(candidate))): if line.startswith('delete'): newline = re.sub('^delete', 'set', line) if newline not in config: del modified_candidate[index] return modified_candidate def configure_device(module, warnings, candidate): kwargs = {} config_format = None if module.params['src']: config_format = module.params['src_format'] or guess_format(str(candidate)) if config_format == 'set': kwargs.update({'format': 'text', 'action': 'set'}) else: kwargs.update({'format': config_format, 'action': module.params['update']}) if isinstance(candidate, string_types): candidate = candidate.split('\n') # this is done to filter out `delete ...` statements which map to # nothing in the config as that will cause an exception to be raised if any((module.params['lines'], config_format == 'set')): candidate = filter_delete_statements(module, candidate) kwargs['format'] = 'text' kwargs['action'] = 'set' return load_config(module, candidate, warnings, **kwargs) def main(): """ main entry point for module execution """ argument_spec = dict( lines=dict(type='list'), src=dict(type='path'), src_format=dict(choices=['xml', 'text', 'set', 'json']), # update operations update=dict(default='merge', choices=['merge', 'override', 'replace', 'update']), # deprecated replace in Ansible 2.3 replace=dict(type='bool'), confirm=dict(default=0, type='int'), comment=dict(default=DEFAULT_COMMENT), confirm_commit=dict(type='bool', default=False), # config operations backup=dict(type='bool', default=False), rollback=dict(type='int'), zeroize=dict(default=False, type='bool'), ) argument_spec.update(junos_argument_spec) mutually_exclusive = [('lines', 'src', 'rollback', 'zeroize')] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() check_args(module, warnings) candidate = module.params['lines'] or module.params['src'] commit = not module.check_mode result = {'changed': False, 'warnings': warnings} if module.params['backup']: for conf_format in ['set', 'text']: reply = get_configuration(module, format=conf_format) match = reply.find('.//configuration-%s' % conf_format) if match is not None: break else: module.fail_json(msg='unable to retrieve device configuration') result['__backup__'] = match.text.strip() if module.params['rollback']: if commit: diff = rollback(module) if module._diff: result['diff'] = {'prepared': diff} result['changed'] = True elif module.params['zeroize']: if commit: zeroize(module) result['changed'] = True else: if candidate: with locked_config(module): diff = configure_device(module, warnings, candidate) if diff: if commit: kwargs = { 'comment': module.params['comment'] } if module.params['confirm'] > 0: kwargs.update({ 'confirm': True, 'confirm_timeout': module.params['confirm'] }) commit_configuration(module, **kwargs) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} elif module.params['confirm_commit']: with locked_config(module): # confirm a previous commit commit_configuration(module) result['changed'] = True module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
simbha/mAngE-Gin
lib/django/contrib/gis/geoip/prototypes.py
93
3944
from ctypes import c_char_p, c_float, c_int, string_at, Structure, POINTER from django.contrib.gis.geoip.libgeoip import lgeoip, free #### GeoIP C Structure definitions #### class GeoIPRecord(Structure): _fields_ = [('country_code', c_char_p), ('country_code3', c_char_p), ('country_name', c_char_p), ('region', c_char_p), ('city', c_char_p), ('postal_code', c_char_p), ('latitude', c_float), ('longitude', c_float), # TODO: In 1.4.6 this changed from `int dma_code;` to # `union {int metro_code; int dma_code;};`. Change # to a `ctypes.Union` in to accommodate in future when # pre-1.4.6 versions are no longer distributed. ('dma_code', c_int), ('area_code', c_int), ('charset', c_int), ('continent_code', c_char_p), ] geoip_char_fields = [name for name, ctype in GeoIPRecord._fields_ if ctype is c_char_p] GEOIP_DEFAULT_ENCODING = 'iso-8859-1' geoip_encodings = { 0: 'iso-8859-1', 1: 'utf8', } class GeoIPTag(Structure): pass RECTYPE = POINTER(GeoIPRecord) DBTYPE = POINTER(GeoIPTag) #### ctypes function prototypes #### # GeoIP_lib_version appeared in version 1.4.7. if hasattr(lgeoip, 'GeoIP_lib_version'): GeoIP_lib_version = lgeoip.GeoIP_lib_version GeoIP_lib_version.argtypes = None GeoIP_lib_version.restype = c_char_p else: GeoIP_lib_version = None # For freeing memory allocated within a record GeoIPRecord_delete = lgeoip.GeoIPRecord_delete GeoIPRecord_delete.argtypes = [RECTYPE] GeoIPRecord_delete.restype = None # For retrieving records by name or address. def check_record(result, func, cargs): if result: # Checking the pointer to the C structure, if valid pull out elements # into a dictionary. rec = result.contents record = dict((fld, getattr(rec, fld)) for fld, ctype in rec._fields_) # Now converting the strings to unicode using the proper encoding. encoding = geoip_encodings[record['charset']] for char_field in geoip_char_fields: if record[char_field]: record[char_field] = record[char_field].decode(encoding) # Free the memory allocated for the struct & return. GeoIPRecord_delete(result) return record else: return None def record_output(func): func.argtypes = [DBTYPE, c_char_p] func.restype = RECTYPE func.errcheck = check_record return func GeoIP_record_by_addr = record_output(lgeoip.GeoIP_record_by_addr) GeoIP_record_by_name = record_output(lgeoip.GeoIP_record_by_name) # For opening & closing GeoIP database files. GeoIP_open = lgeoip.GeoIP_open GeoIP_open.restype = DBTYPE GeoIP_delete = lgeoip.GeoIP_delete GeoIP_delete.argtypes = [DBTYPE] GeoIP_delete.restype = None # This is so the string pointer can be freed within Python. class geoip_char_p(c_char_p): pass def check_string(result, func, cargs): if result: s = string_at(result) free(result) else: s = '' return s.decode(GEOIP_DEFAULT_ENCODING) GeoIP_database_info = lgeoip.GeoIP_database_info GeoIP_database_info.restype = geoip_char_p GeoIP_database_info.errcheck = check_string # String output routines. def string_output(func): def _err_check(result, func, cargs): if result: return result.decode(GEOIP_DEFAULT_ENCODING) return result func.restype = c_char_p func.errcheck = _err_check return func GeoIP_country_code_by_addr = string_output(lgeoip.GeoIP_country_code_by_addr) GeoIP_country_code_by_name = string_output(lgeoip.GeoIP_country_code_by_name) GeoIP_country_name_by_addr = string_output(lgeoip.GeoIP_country_name_by_addr) GeoIP_country_name_by_name = string_output(lgeoip.GeoIP_country_name_by_name)
mit
vrv/tensorflow
tensorflow/contrib/learn/python/learn/preprocessing/categorical_vocabulary.py
94
4204
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Categorical vocabulary classes to map categories to indexes. Can be used for categorical variables, sparse variables and words. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import six class CategoricalVocabulary(object): """Categorical variables vocabulary class. Accumulates and provides mapping from classes to indexes. Can be easily used for words. """ def __init__(self, unknown_token="<UNK>", support_reverse=True): self._unknown_token = unknown_token self._mapping = {unknown_token: 0} self._support_reverse = support_reverse if support_reverse: self._reverse_mapping = [unknown_token] self._freq = collections.defaultdict(int) self._freeze = False def __len__(self): """Returns total count of mappings. Including unknown token.""" return len(self._mapping) def freeze(self, freeze=True): """Freezes the vocabulary, after which new words return unknown token id. Args: freeze: True to freeze, False to unfreeze. """ self._freeze = freeze def get(self, category): """Returns word's id in the vocabulary. If category is new, creates a new id for it. Args: category: string or integer to lookup in vocabulary. Returns: interger, id in the vocabulary. """ if category not in self._mapping: if self._freeze: return 0 self._mapping[category] = len(self._mapping) if self._support_reverse: self._reverse_mapping.append(category) return self._mapping[category] def add(self, category, count=1): """Adds count of the category to the frequency table. Args: category: string or integer, category to add frequency to. count: optional integer, how many to add. """ category_id = self.get(category) if category_id <= 0: return self._freq[category] += count def trim(self, min_frequency, max_frequency=-1): """Trims vocabulary for minimum frequency. Remaps ids from 1..n in sort frequency order. where n - number of elements left. Args: min_frequency: minimum frequency to keep. max_frequency: optional, maximum frequency to keep. Useful to remove very frequent categories (like stop words). """ # Sort by alphabet then reversed frequency. self._freq = sorted( sorted( six.iteritems(self._freq), key=lambda x: (isinstance(x[0], str), x[0])), key=lambda x: x[1], reverse=True) self._mapping = {self._unknown_token: 0} if self._support_reverse: self._reverse_mapping = [self._unknown_token] idx = 1 for category, count in self._freq: if max_frequency > 0 and count >= max_frequency: continue if count <= min_frequency: break self._mapping[category] = idx idx += 1 if self._support_reverse: self._reverse_mapping.append(category) self._freq = dict(self._freq[:idx - 1]) def reverse(self, class_id): """Given class id reverse to original class name. Args: class_id: Id of the class. Returns: Class name. Raises: ValueError: if this vocabulary wasn't initalized with support_reverse. """ if not self._support_reverse: raise ValueError("This vocabulary wasn't initalized with " "support_reverse to support reverse() function.") return self._reverse_mapping[class_id]
apache-2.0
nstockton/mapperproxy-mume
mapper/sockets/fakesocket.py
1
1829
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Future Modules: from __future__ import annotations # Built-in Modules: import logging import time from typing import Any, Dict, List, Union logger: logging.Logger = logging.getLogger(__name__) class FakeSocketEmpty(Exception): pass class FakeSocket(object): def __init__(self, *args: Any, **kwargs: Any) -> None: self.inboundBuffer: Union[bytes, None] = None self.timeout: Union[float, None] = None def gettimeout(self) -> Union[float, None]: return self.timeout def settimeout(self, timeout: Union[float, None]) -> None: self.timeout = None if timeout is None else float(timeout) def getblocking(self) -> bool: return self.gettimeout() is None def setblocking(self, flag: bool) -> None: self.settimeout(None if flag else 0.0) def connect(self, *args: Any) -> None: # pragma: no cover pass def setsockopt(self, *args: Any) -> None: # pragma: no cover pass def getpeercert(self, *args: Any) -> Dict[str, List[List[str]]]: return {"subject": [["commonName", "mume.org"]]} def shutdown(self, *args: Any) -> None: # pragma: no cover pass def close(self, *args: Any) -> None: # pragma: no cover pass def send(self, data: bytes, flags: int = 0) -> int: if data == b"quit": self.inboundBuffer = b"" return len(data) def sendall(self, data: bytes, flags: int = 0) -> None: self.send(data, flags) def recv(self, buffersize: int, flags: int = 0) -> bytes: # Simulate some lag. time.sleep(0.005) if isinstance(self.inboundBuffer, bytes): inboundBuffer: bytes = self.inboundBuffer self.inboundBuffer = None return inboundBuffer raise FakeSocketEmpty()
mpl-2.0
Fireblend/scikit-learn
examples/decomposition/plot_ica_blind_source_separation.py
349
2228
""" ===================================== Blind source separation using FastICA ===================================== An example of estimating sources from noisy data. :ref:`ICA` is used to estimate sources given noisy measurements. Imagine 3 instruments playing simultaneously and 3 microphones recording the mixed signals. ICA is used to recover the sources ie. what is played by each instrument. Importantly, PCA fails at recovering our `instruments` since the related signals reflect non-Gaussian processes. """ print(__doc__) import numpy as np import matplotlib.pyplot as plt from scipy import signal from sklearn.decomposition import FastICA, PCA ############################################################################### # Generate sample data np.random.seed(0) n_samples = 2000 time = np.linspace(0, 8, n_samples) s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal s3 = signal.sawtooth(2 * np.pi * time) # Signal 3: saw tooth signal S = np.c_[s1, s2, s3] S += 0.2 * np.random.normal(size=S.shape) # Add noise S /= S.std(axis=0) # Standardize data # Mix data A = np.array([[1, 1, 1], [0.5, 2, 1.0], [1.5, 1.0, 2.0]]) # Mixing matrix X = np.dot(S, A.T) # Generate observations # Compute ICA ica = FastICA(n_components=3) S_ = ica.fit_transform(X) # Reconstruct signals A_ = ica.mixing_ # Get estimated mixing matrix # We can `prove` that the ICA model applies by reverting the unmixing. assert np.allclose(X, np.dot(S_, A_.T) + ica.mean_) # For comparison, compute PCA pca = PCA(n_components=3) H = pca.fit_transform(X) # Reconstruct signals based on orthogonal components ############################################################################### # Plot results plt.figure() models = [X, S, S_, H] names = ['Observations (mixed signal)', 'True Sources', 'ICA recovered signals', 'PCA recovered signals'] colors = ['red', 'steelblue', 'orange'] for ii, (model, name) in enumerate(zip(models, names), 1): plt.subplot(4, 1, ii) plt.title(name) for sig, color in zip(model.T, colors): plt.plot(sig, color=color) plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.46) plt.show()
bsd-3-clause
formath/mxnet
example/profiler/profiler_matmul.py
25
2489
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import print_function import mxnet as mx import argparse import os, sys import time import numpy as np def parse_args(): parser = argparse.ArgumentParser(description='Set network parameters for benchmark test.') parser.add_argument('--profile_filename', type=str, default='profile_matmul_20iter.json') parser.add_argument('--iter_num', type=int, default=100) parser.add_argument('--begin_profiling_iter', type=int, default=50) parser.add_argument('--end_profiling_iter', type=int, default=70) return parser.parse_args() args = parse_args() if __name__ == '__main__': mx.profiler.profiler_set_config(mode='symbolic', filename=args.profile_filename) print('profile file save to {0}'.format(args.profile_filename)) A = mx.sym.Variable('A') B = mx.sym.Variable('B') C = mx.symbol.dot(A, B) executor = C.simple_bind(mx.gpu(1), 'write', A=(4096, 4096), B=(4096, 4096)) a = mx.random.uniform(-1.0, 1.0, shape=(4096, 4096)) b = mx.random.uniform(-1.0, 1.0, shape=(4096, 4096)) a.copyto(executor.arg_dict['A']) b.copyto(executor.arg_dict['B']) flag = False print("execution begin") for i in range(args.iter_num): if i == args.begin_profiling_iter: t0 = time.clock() mx.profiler.profiler_set_state('run') if i == args.end_profiling_iter: t1 = time.clock() mx.profiler.profiler_set_state('stop') executor.forward() c = executor.outputs[0] c.wait_to_read() print("execution end") duration = t1 - t0 print('duration: {0}s'.format(duration)) print(' {0}ms/operator'.format(duration*1000/args.iter_num))
apache-2.0
mmcdermo/helpinghand
server/venv/lib/python2.7/site-packages/django/contrib/comments/__init__.py
112
3485
import warnings from django.conf import settings from django.core import urlresolvers from django.core.exceptions import ImproperlyConfigured from django.contrib.comments.models import Comment from django.contrib.comments.forms import CommentForm from django.utils.importlib import import_module warnings.warn("django.contrib.comments is deprecated and will be removed before Django 1.8.", PendingDeprecationWarning) DEFAULT_COMMENTS_APP = 'django.contrib.comments' def get_comment_app(): """ Get the comment app (i.e. "django.contrib.comments") as defined in the settings """ # Make sure the app's in INSTALLED_APPS comments_app = get_comment_app_name() if comments_app not in settings.INSTALLED_APPS: raise ImproperlyConfigured("The COMMENTS_APP (%r) "\ "must be in INSTALLED_APPS" % settings.COMMENTS_APP) # Try to import the package try: package = import_module(comments_app) except ImportError as e: raise ImproperlyConfigured("The COMMENTS_APP setting refers to "\ "a non-existing package. (%s)" % e) return package def get_comment_app_name(): """ Returns the name of the comment app (either the setting value, if it exists, or the default). """ return getattr(settings, 'COMMENTS_APP', DEFAULT_COMMENTS_APP) def get_model(): """ Returns the comment model class. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_model"): return get_comment_app().get_model() else: return Comment def get_form(): """ Returns the comment ModelForm class. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_form"): return get_comment_app().get_form() else: return CommentForm def get_form_target(): """ Returns the target URL for the comment form submission view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_form_target"): return get_comment_app().get_form_target() else: return urlresolvers.reverse("django.contrib.comments.views.comments.post_comment") def get_flag_url(comment): """ Get the URL for the "flag this comment" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_flag_url"): return get_comment_app().get_flag_url(comment) else: return urlresolvers.reverse("django.contrib.comments.views.moderation.flag", args=(comment.id,)) def get_delete_url(comment): """ Get the URL for the "delete this comment" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_delete_url"): return get_comment_app().get_delete_url(comment) else: return urlresolvers.reverse("django.contrib.comments.views.moderation.delete", args=(comment.id,)) def get_approve_url(comment): """ Get the URL for the "approve this comment from moderation" view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP and hasattr(get_comment_app(), "get_approve_url"): return get_comment_app().get_approve_url(comment) else: return urlresolvers.reverse("django.contrib.comments.views.moderation.approve", args=(comment.id,))
mit
venicegeo/eventkit-cloud
eventkit_cloud/auth/tests/test_views.py
1
6563
# -*- coding: utf-8 -*- import json import logging import urllib.request, urllib.parse, urllib.error from django.conf import settings from django.contrib.auth.models import User, Group from django.urls import reverse from django.test import Client, override_settings from django.test import TestCase from mock import patch, Mock, MagicMock from eventkit_cloud.auth.models import OAuth from eventkit_cloud.auth.views import callback, oauth import base64 logger = logging.getLogger(__name__) @override_settings(OAUTH_AUTHORIZATION_URL="http://remote.dev/authorize") class TestAuthViews(TestCase): def setUp(self): self.client = Client() @patch('eventkit_cloud.auth.views.login') @patch('eventkit_cloud.auth.views.fetch_user_from_token') @patch('eventkit_cloud.auth.views.request_access_token') def test_callback(self, mock_get_token, mock_get_user, mock_login): oauth_name = "provider" with self.settings(OAUTH_NAME=oauth_name): example_token = "token" request = Mock(GET={'code': "1234"}) group, created = Group.objects.get_or_create(name='TestDefaultExportExtentGroup') with patch('eventkit_cloud.jobs.signals.Group') as mock_group: mock_group.objects.get.return_value = group user = User.objects.create(username="test", email="test@email.com") OAuth.objects.create(user=user, identification="test_ident", commonname="test_common") mock_get_token.return_value = example_token mock_get_user.return_value = None response = callback(request) self.assertEqual(response.status_code, 401) mock_get_token.return_value = example_token mock_get_user.return_value = user response = callback(request) mock_login.assert_called_once_with(request, user, backend='django.contrib.auth.backends.ModelBackend') self.assertRedirects(response, '/dashboard', fetch_redirect_response=False) mock_login.reset_mock() example_state = base64.b64encode("/status/12345".encode()) request = Mock(GET={'code': "1234", 'state': example_state}) mock_get_token.return_value = example_token mock_get_user.return_value = user response = callback(request) mock_login.assert_called_once_with(request, user, backend='django.contrib.auth.backends.ModelBackend') self.assertRedirects(response, base64.b64decode(example_state).decode(), fetch_redirect_response=False) def test_oauth(self): # Test GET to ensure a provider name is returned for dynamically naming oauth login. oauth_name = "provider" client_id = "name" redirect_uri = "http://test.dev/callback" response_type = "code" scope = "profile" authorization_url = "http://remote.dev/authorize" referer = "/status/12345" with self.settings(OAUTH_NAME=oauth_name): response = self.client.get(reverse('oauth'),{'query':'name'}) return_name = response.json().get('name') self.assertEqual(return_name, oauth_name) self.assertEqual(response.status_code, 200) # Test post to ensure that a valid redirect is returned. with self.settings(OAUTH_CLIENT_ID=client_id, OAUTH_REDIRECT_URI=redirect_uri, OAUTH_RESPONSE_TYPE=response_type, OAUTH_SCOPE=scope, OAUTH_NAME=oauth_name): response = self.client.post(reverse('oauth')) params = urllib.parse.urlencode(( ('client_id', client_id), ('redirect_uri', redirect_uri), ('response_type', response_type), ('scope', scope) )) self.assertRedirects(response, '{url}?{params}'.format(url=authorization_url.rstrip('/'), params=params), fetch_redirect_response=False) mock_request = MagicMock() mock_request.META = {'HTTP_REFERER': referer} mock_request.GET = {'query': None} response = oauth(mock_request) params = urllib.parse.urlencode(( ('client_id', client_id), ('redirect_uri', redirect_uri), ('response_type', response_type), ('scope', scope), ('state', base64.b64encode(referer.encode())) )) self.assertRedirects(response, '{url}?{params}'.format(url=authorization_url.rstrip('/'), params=params), fetch_redirect_response=False) @patch('eventkit_cloud.auth.views.fetch_user_from_token') @patch('eventkit_cloud.auth.views.request_access_token') def test_logout(self, mock_access_token, mock_fetch_user): # Test logout ensure logout of django, and redirect to login if OAUTH URL not provided example_auth_code = 'code' example_token = 'token' logout_url = "http://remote.dev/logout" group, created = Group.objects.get_or_create(name='TestDefaultExportExtentGroup') with patch('eventkit_cloud.jobs.signals.Group') as mock_group: mock_group.objects.get.return_value = group user = User.objects.create(username="test", password="password", email="test@email.com") OAuth.objects.create(user=user, identification="test_ident", commonname="test_common") mock_access_token.return_value = example_token mock_fetch_user.return_value = user #test without logout url with self.settings(OAUTH_LOGOUT_URL=None): self.client.get(reverse('callback'), params={'code': example_auth_code}, follow=True) response = self.client.get(reverse('logout'), follow=True) self.assertRedirects(response, reverse('login'), fetch_redirect_response=False) #test with logout url with self.settings(OAUTH_LOGOUT_URL=logout_url): self.client.login(username='test', password='password') self.client.get(reverse('callback'), params={'code': example_auth_code}, follow=True) response = self.client.get(reverse('logout')) self.assertEqual(response.json().get('OAUTH_LOGOUT_URL'), settings.OAUTH_LOGOUT_URL)
bsd-3-clause
DoubleNegativeVisualEffects/gaffer
python/GafferUI/PlugValueWidget.py
2
15985
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import re import fnmatch import IECore import Gaffer import GafferUI ## \todo Potential optimisation. # Currently every PlugValueWidget instance connects to the various plug signals # on the node, and tests to see if the plug is of interest when signalled. When many # PlugValueWidgets are instantiated for a node this might prove a little slow. In this # eventuality perhaps we can optimise things by having CompoundPlugValueWidget be # responsible for updating only the correct child, so the children don't need to be # connected themselves. PlugValueWidget would need to maintain the ability to do things # itself when used alone, but this might give a good speedup for the most common case. class PlugValueWidget( GafferUI.Widget ) : def __init__( self, topLevelWidget, plug, **kw ) : GafferUI.Widget.__init__( self, topLevelWidget, **kw ) # we don't want to call _updateFromPlug yet because the derived # classes haven't constructed yet. they can call it themselves # upon completing construction. self.__setPlugInternal( plug, callUpdateFromPlug=False ) self.__popupMenuConnections = [] self.__readOnly = False self.__dragEnterConnection = self.dragEnterSignal().connect( Gaffer.WeakMethod( self.__dragEnter ) ) self.__dragLeaveConnection = self.dragLeaveSignal().connect( Gaffer.WeakMethod( self.__dragLeave ) ) self.__dropConnection = self.dropSignal().connect( Gaffer.WeakMethod( self.__drop ) ) ## Note that it is acceptable to pass None to setPlug() (and to the constructor) # and that derived classes should be implemented to cope with this eventuality. def setPlug( self, plug ) : self.__setPlugInternal( plug, callUpdateFromPlug=True ) def getPlug( self ) : return self.__plug ## By default, PlugValueWidgets operate in the main context held by the script node # for the script the plug belongs to. This function allows an alternative context # to be provided, making it possible to view a plug at a custom frame (or with any # other context modification). def setContext( self, context ) : assert( isinstance( context, Gaffer.Context ) ) if context is self.__context : return self.__context = context self.__updateContextConnection() self._updateFromPlug() def getContext( self ) : return self.__context ## This method allows editing of the plug value # to be disabled for this ui. Note that even when getReadOnly() # is False, the ui may not allow editing due to the plug # itself being read only for other reasons. def setReadOnly( self, readOnly ) : assert( isinstance( readOnly, bool ) ) if readOnly == self.__readOnly : return self.__readOnly = readOnly self._updateFromPlug() def getReadOnly( self ) : return self.__readOnly ## Should be reimplemented to return True if this widget includes # some sort of labelling for the plug. This is used to prevent # extra labels being created in the NodeUI when they're not necessary. def hasLabel( self ) : return False ## Implemented to return a tooltip containing the plug name and description. def getToolTip( self ) : result = GafferUI.Widget.getToolTip( self ) if result : return result plug = self.getPlug() if plug is None : return "" input = plug.getInput() inputText = "" if input is not None : inputText = " &lt;- " + input.relativeName( input.commonAncestor( plug, Gaffer.GraphComponent.staticTypeId() ) ) result = "<h3>" + plug.relativeName( plug.node() ) + inputText + "</h3>" description = GafferUI.Metadata.plugDescription( plug ) if description : result += "\n\n" + description return result ## Must be implemented by subclasses so that the widget reflects the current # status of the plug. To temporarily suspend calls to this function, use # Gaffer.BlockedConnection( self._plugConnections() ). def _updateFromPlug( self ) : raise NotImplementedError def _plugConnections( self ) : return [ self.__plugDirtiedConnection, self.__plugInputChangedConnection, self.__plugFlagsChangedConnection ] ## Returns True if the plug value is editable as far as this ui is concerned # - that plug.settable() is True and self.getReadOnly() is False. def _editable( self ) : plug = self.getPlug() if plug is None : return False if hasattr(plug, 'settable') and not plug.settable(): return False if self.__readOnly : return False return True ## Adds a useful popup menu to the specified widget, providing useful functions that # operate on the plug. The menu is populated with the result of _popupMenuDefinition(), # and may also be customised by external code using the popupMenuSignal(). def _addPopupMenu( self, widget = None, buttons = GafferUI.ButtonEvent.Buttons.Right ) : if widget is None : widget = self # it's unclear under what circumstances we get given a right-click vs a context menu event, # but we try to cover all our bases by connecting to both. self.__popupMenuConnections.append( widget.buttonPressSignal().connect( IECore.curry( Gaffer.WeakMethod( self.__buttonPress ), buttonMask = buttons ) ) ) if buttons & GafferUI.ButtonEvent.Buttons.Right : self.__popupMenuConnections.append( widget.contextMenuSignal().connect( IECore.curry( Gaffer.WeakMethod( self.__contextMenu ) ) ) ) ## Returns a definition for the popup menu - this is called each time the menu is displayed # to allow for dynamic menus. Subclasses may override this method to customise the menu, but # should call the base class implementation first. def _popupMenuDefinition( self ) : menuDefinition = IECore.MenuDefinition() if self.getPlug().getInput() is not None : menuDefinition.append( "/Edit input...", { "command" : Gaffer.WeakMethod( self.__editInput ) } ) menuDefinition.append( "/EditInputDivider", { "divider" : True } ) menuDefinition.append( "/Remove input", { "command" : Gaffer.WeakMethod( self.__removeInput ) } ) if hasattr( self.getPlug(), "defaultValue" ) and self.getPlug().direction() == Gaffer.Plug.Direction.In : menuDefinition.append( "/Default", { "command" : IECore.curry( Gaffer.WeakMethod( self.__setValue ), self.getPlug().defaultValue() ), "active" : self._editable() } ) self.popupMenuSignal()( menuDefinition, self ) return menuDefinition __popupMenuSignal = Gaffer.Signal2() ## This signal is emitted whenever a popup menu for a plug is about # to be shown. This provides an opportunity to customise the menu from # external code. The signature for slots is ( menuDefinition, plugValueWidget ), # and slots should just modify the menu definition in place. @classmethod def popupMenuSignal( cls ) : return cls.__popupMenuSignal ## Returns a PlugValueWidget suitable for representing the specified plug. If # useTypeOnly is True, then custom registrations made by registerCreator() will # be ignored and only the plug type will be taken into account in creating a # PlugValueWidget. @classmethod def create( cls, plug, useTypeOnly=False ) : # first try to create one using a creator registered for the specific plug if not useTypeOnly : node = plug.node() if node is not None : plugPath = plug.relativeName( node ) nodeHierarchy = IECore.RunTimeTyped.baseTypeIds( node.typeId() ) for nodeTypeId in [ node.typeId() ] + nodeHierarchy : creators = cls.__nodeTypesToCreators.get( nodeTypeId, None ) if creators : for creator in creators : if creator.plugPathMatcher.match( plugPath ) : if creator.creator is not None : return creator.creator( plug, **(creator.creatorKeywordArgs) ) else : return None # if that failed, then just create something based on the type of the plug typeId = plug.typeId() for plugTypeId in [ plug.typeId() ] + IECore.RunTimeTyped.baseTypeIds( plug.typeId() ) : if plugTypeId in cls.__plugTypesToCreators : creator = cls.__plugTypesToCreators[plugTypeId] if creator is not None : return creator( plug ) else : return None return None ## Registers a PlugValueWidget type for a specific Plug type. Note # that the registerCreator function below provides the # opportunity to further customise the type of Widget used for specific # plug instances based on the node type and plug name. @classmethod def registerType( cls, plugTypeId, creator ) : cls.__plugTypesToCreators[plugTypeId] = creator ## Registers a function to create a PlugWidget. None may be passed as creator, to # disable the creation of uis for specific plugs. @classmethod def registerCreator( cls, nodeTypeId, plugPath, creator, **creatorKeywordArgs ) : if isinstance( plugPath, basestring ) : plugPath = re.compile( fnmatch.translate( plugPath ) ) else : assert( type( plugPath ) is type( re.compile( "" ) ) ) creators = cls.__nodeTypesToCreators.setdefault( nodeTypeId, [] ) creator = IECore.Struct( plugPathMatcher = plugPath, creator = creator, creatorKeywordArgs = creatorKeywordArgs, ) creators.insert( 0, creator ) __plugTypesToCreators = {} __nodeTypesToCreators = {} def __plugDirtied( self, plug ) : if plug.isSame( self.__plug ) : self._updateFromPlug() def __plugInputChanged( self, plug ) : if plug.isSame( self.__plug ) : self.__updateContextConnection() self._updateFromPlug() def __plugFlagsChanged( self, plug ) : if plug.isSame( self.__plug ) : self._updateFromPlug() def __contextChanged( self, context, key ) : self._updateFromPlug() def __setPlugInternal( self, plug, callUpdateFromPlug ) : self.__plug = plug context = self.__fallbackContext if self.__plug is not None : self.__plugDirtiedConnection = plug.node().plugDirtiedSignal().connect( Gaffer.WeakMethod( self.__plugDirtied ) ) self.__plugInputChangedConnection = plug.node().plugInputChangedSignal().connect( Gaffer.WeakMethod( self.__plugInputChanged ) ) self.__plugFlagsChangedConnection = plug.node().plugFlagsChangedSignal().connect( Gaffer.WeakMethod( self.__plugFlagsChanged ) ) scriptNode = self.__plug.ancestor( Gaffer.ScriptNode.staticTypeId() ) if scriptNode is not None : context = scriptNode.context() else : self.__plugDirtiedConnection = None self.__plugInputChangedConnection = None self.__plugFlagsChangedConnection = None self.__context = context self.__updateContextConnection() if callUpdateFromPlug : self._updateFromPlug() def __updateContextConnection( self ) : # we only want to be notified of context changes if we have a plug and that # plug has an incoming connection. otherwise context changes are irrelevant # and we'd just be slowing things down by asking for notifications. context = self.__context plug = self.getPlug() if plug is None or plug.getInput() is None : context = None if context is not None : self.__contextChangedConnection = context.changedSignal().connect( Gaffer.WeakMethod( self.__contextChanged ) ) else : self.__contextChangedConnection = None # we use this when the plug being viewed doesn't have a ScriptNode ancestor # to provide a context. __fallbackContext = Gaffer.Context() def __buttonPress( self, widget, event, buttonMask ) : if event.buttons & buttonMask : return self.__contextMenu() return False def __contextMenu( self, *unused ) : if self.getPlug() is None : return False menuDefinition = self._popupMenuDefinition() if not len( menuDefinition.items() ) : return False title = self.getPlug().relativeName( self.getPlug().node() ) title = ".".join( [ IECore.CamelCase.join( IECore.CamelCase.split( x ) ) for x in title.split( "." ) ] ) self.__popupMenu = GafferUI.Menu( menuDefinition, title = title ) self.__popupMenu.popup() return True def __setValue( self, value ) : with Gaffer.UndoContext( self.getPlug().ancestor( Gaffer.ScriptNode.staticTypeId() ) ) : self.getPlug().setValue( value ) def __editInput( self ) : GafferUI.NodeEditor.acquire( self.getPlug().getInput().node() ) def __removeInput( self ) : with Gaffer.UndoContext( self.getPlug().ancestor( Gaffer.ScriptNode.staticTypeId() ) ) : self.getPlug().setInput( None ) # drag and drop stuff def __dragEnter( self, widget, event ) : if self.getReadOnly() : return False if isinstance( event.data, Gaffer.Plug ) : if self.getPlug().acceptsInput( event.data ) : self.setHighlighted( True ) return True elif hasattr( self.getPlug(), "setValue" ) and self._dropValue( event ) is not None : if self.getPlug().settable() : self.setHighlighted( True ) return True return False def __dragLeave( self, widget, event ) : self.setHighlighted( False ) def __drop( self, widget, event ) : self.setHighlighted( False ) with Gaffer.UndoContext( self.getPlug().node().scriptNode() ) : if isinstance( event.data, Gaffer.Plug ) : self.getPlug().setInput( event.data ) else : self.getPlug().setValue( self._dropValue( event ) ) return True ## Called from a dragEnter slot to see if the drag data can # be converted to a value suitable for a plug.setValue() call. # If this returns a non-None value then the drag will be accepted # and plug.setValue() will be called in the drop event. May be # reimplemented by derived classes to provide conversions of the # drag data to the type needed for setValue(). def _dropValue( self, dragDropEvent ) : if hasattr( self.getPlug(), "defaultValue" ) : plugValueType = type( self.getPlug().defaultValue() ) if isinstance( dragDropEvent.data, plugValueType ) : return dragDropEvent.data elif isinstance( dragDropEvent.data, IECore.Data ) and hasattr( dragDropEvent.data, "value" ) : if isinstance( dragDropEvent.data.value, plugValueType ) : return dragDropEvent.data.value else : with IECore.IgnoredExceptions( Exception ) : return plugValueType( dragDropEvent.data.value ) return None
bsd-3-clause
mkobos/tree_crawler
concurrent_tree_crawler/common/threads/rw_lock.py
1
4057
import threading #import time ##DEBUG #import logging ##DEBUG __author__ = "Mateusz Kobos" """ This code is a derivative of the code from ActiveState Code service at the address: http://code.activestate.com/recipes/577803-reader-writer-lock-with-priority-for-writers and is licensed under the MIT license. """ class RWLock: """Synchronization object used in a solution of so-called second readers-writers problem. In this problem, many readers can simultaneously access a share, and a writer has an exclusive access to this share. Additionally, the following constraints should be met: - no reader should be kept waiting if the share is currently opened for reading unless a writer is also waiting for the share, - no writer should be kept waiting for the share longer than absolutely necessary. The implementation is based on [1, secs. 4.2.2, 4.2.6, 4.2.7] with a modification -- adding an additional lock (C{self.__readers_queue}) -- in accordance with [2]. Sources: 1. A.B. Downey: "The little book of semaphores", Version 2.1.5, 2008 2. P.J. Courtois, F. Heymans, D.L. Parnas: "Concurrent Control with 'Readers' and 'Writers'", Communications of the ACM, 1971 (via [3]) 3. http://en.wikipedia.org/wiki/Readers-writers_problem """ def __init__(self): self.__read_switch = _LightSwitch() self.__write_switch = _LightSwitch() self.__no_readers = threading.Lock() self.__no_writers = threading.Lock() self.__readers_queue = threading.Lock() """A lock giving an even higher priority to the writer in certain cases (see [2] for a discussion)""" def reader_acquire(self): ##DEBUG #logging.info("thread={}: reader_acquire: BEGIN".format(threading.current_thread().name)) self.__readers_queue.acquire() #logging.info("thread={}: reader_acquire: after readers_queue.acquire()".format(threading.current_thread().name)) self.__no_readers.acquire() #logging.info("thread={}: reader_acquire: after no_readers.acquire()".format(threading.current_thread().name)) self.__read_switch.acquire(self.__no_writers) #logging.info("thread={}: reader_acquire: after read_switch.acquire(self.__no_writers)".format(threading.current_thread().name)) self.__no_readers.release() #logging.info("thread={}: reader_acquire: after no_readers.release()".format(threading.current_thread().name)) self.__readers_queue.release() ##DEBUG #logging.info("thread={}: reader_acquire: END".format(threading.current_thread().name)) def reader_release(self): ##DEBUG #logging.info("thread={}: reader_release: BEGIN".format(threading.current_thread().name)) self.__read_switch.release(self.__no_writers) ##DEBUG #logging.info("thread={}: reader_release: END".format(threading.current_thread().name)) def writer_acquire(self): ##DEBUG #logging.info("thread={}: writer_acquire: BEGIN".format(threading.current_thread().name)) self.__write_switch.acquire(self.__no_readers) #logging.info("thread={}: writer_acquire: after write_switch.acquire(self.__no_readers)".format(threading.current_thread().name)) self.__no_writers.acquire() ##DEBUG #logging.info("thread={}: writer_acquire: END".format(threading.current_thread().name)) def writer_release(self): ##DEBUG #logging.info("thread={}: writer_release: BEGIN".format(threading.current_thread().name)) self.__no_writers.release() self.__write_switch.release(self.__no_readers) ##DEBUG #logging.info("{} thread={}: writer_release: END".format(threading.current_thread().name)) class _LightSwitch: """An auxiliary "light switch"-like object. The first thread turns on the "switch", the last one turns it off (see [1, sec. 4.2.2] for details).""" def __init__(self): self.__counter = 0 self.__mutex = threading.Lock() def acquire(self, lock): self.__mutex.acquire() self.__counter += 1 if self.__counter == 1: lock.acquire() self.__mutex.release() def release(self, lock): self.__mutex.acquire() self.__counter -= 1 if self.__counter == 0: lock.release() self.__mutex.release()
mit
thjashin/tensorflow
tensorflow/python/framework/framework_lib.py
61
3985
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=unused-import,g-bad-import-order """Classes and functions for building TensorFlow graphs. ## Core graph data structures @@Graph @@Operation @@Tensor ## Tensor types @@DType @@as_dtype ## Utility functions @@device @@container @@name_scope @@control_dependencies @@convert_to_tensor @@convert_to_tensor_or_indexed_slices @@convert_to_tensor_or_sparse_tensor @@get_default_graph @@reset_default_graph @@import_graph_def @@load_file_system_library @@load_op_library ## Graph collections @@add_to_collection @@get_collection @@get_collection_ref @@GraphKeys ## Defining new operations @@RegisterGradient @@NotDifferentiable @@NoGradient @@TensorShape @@Dimension @@op_scope @@get_seed ## For libraries building on TensorFlow @@register_tensor_conversion_function """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # Classes used when building a Graph. from tensorflow.python.framework.device import DeviceSpec from tensorflow.python.framework.ops import Graph from tensorflow.python.framework.ops import Operation from tensorflow.python.framework.ops import Tensor from tensorflow.python.framework.ops import IndexedSlices from tensorflow.python.framework.sparse_tensor import SparseTensor from tensorflow.python.framework.sparse_tensor import SparseTensorValue # Utilities used when building a Graph. from tensorflow.python.framework.ops import device from tensorflow.python.framework.ops import container from tensorflow.python.framework.ops import name_scope from tensorflow.python.framework.ops import op_scope from tensorflow.python.framework.ops import control_dependencies from tensorflow.python.framework.ops import get_default_graph from tensorflow.python.framework.ops import reset_default_graph from tensorflow.python.framework.ops import GraphKeys from tensorflow.python.framework.ops import add_to_collection from tensorflow.python.framework.ops import get_collection from tensorflow.python.framework.ops import get_collection_ref from tensorflow.python.framework.ops import convert_to_tensor from tensorflow.python.framework.ops import convert_to_tensor_or_indexed_slices from tensorflow.python.framework.random_seed import get_seed from tensorflow.python.framework.random_seed import set_random_seed from tensorflow.python.framework.sparse_tensor import convert_to_tensor_or_sparse_tensor from tensorflow.python.framework.subscribe import subscribe from tensorflow.python.framework.importer import import_graph_def # Needed when you defined a new Op in C++. from tensorflow.python.framework.ops import RegisterGradient from tensorflow.python.framework.ops import NotDifferentiable from tensorflow.python.framework.ops import NoGradient from tensorflow.python.framework.ops import RegisterShape from tensorflow.python.framework.tensor_shape import Dimension from tensorflow.python.framework.tensor_shape import TensorShape # Needed when interfacing tensorflow to new array libraries from tensorflow.python.framework.ops import register_tensor_conversion_function # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.python.framework.dtypes import * # Load a TensorFlow plugin from tensorflow.python.framework.load_library import * # pylint: enable=wildcard-import
apache-2.0
systembugtj/electron
tools/coffee2asar.py
150
1520
#!/usr/bin/env python import os import shutil import subprocess import sys import tempfile SOURCE_ROOT = os.path.dirname(os.path.dirname(__file__)) def main(): archive = sys.argv[1] coffee_source_files = sys.argv[2:] output_dir = tempfile.mkdtemp() compile_coffee(coffee_source_files, output_dir) call_asar(archive, output_dir) shutil.rmtree(output_dir) def compile_coffee(coffee_source_files, output_dir): for source_file in coffee_source_files: output_filename = os.path.splitext(source_file)[0] + '.js' output_path = os.path.join(output_dir, output_filename) call_compile_coffee(source_file, output_path) def call_compile_coffee(source_file, output_filename): compile_coffee = os.path.join(SOURCE_ROOT, 'tools', 'compile-coffee.py') subprocess.check_call([sys.executable, compile_coffee, source_file, output_filename]) def call_asar(archive, output_dir): js_dir = os.path.join(output_dir, 'atom') asar = os.path.join(SOURCE_ROOT, 'node_modules', 'asar', 'bin', 'asar') subprocess.check_call([find_node(), asar, 'pack', js_dir, archive]) def find_node(): WINDOWS_NODE_PATHs = [ 'C:/Program Files (x86)/nodejs', 'C:/Program Files/nodejs', ] + os.environ['PATH'].split(os.pathsep) if sys.platform in ['win32', 'cygwin']: for path in WINDOWS_NODE_PATHs: full_path = os.path.join(path, 'node.exe') if os.path.exists(full_path): return full_path return 'node' if __name__ == '__main__': sys.exit(main())
mit
aevitas/pyREtic
Decompilers/unpyc/__init__.py
3
1727
#!/usr/bin/python # [The "BSD licence"] # Copyright (c) 2008-2009 Dmitri Kornev # 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. # * The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Dmitri Kornev 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. ''' Package with core functions for parsing, disassembling and decompiling pyc files. ''' __version__ = '0.8.1' __all__ = ['opcodes_std', 'parse', 'disasm', 'text', 'decompile', 'ast', 'application', 'gui']
gpl-3.0
romain-dartigues/ansible
lib/ansible/modules/network/cloudengine/ce_command.py
22
7712
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ --- module: ce_command version_added: "2.3" author: "JackyGao2016 (@JackyGao2016)" short_description: Run arbitrary command on HUAWEI CloudEngine devices. description: - Sends an arbitrary command to an HUAWEI CloudEngine node and returns the results read from the device. The ce_command module includes an argument that will cause the module to wait for a specific condition before returning or timing out if the condition is not met. options: commands: description: - The commands to send to the remote HUAWEI CloudEngine device over the configured provider. The resulting output from the command is returned. If the I(wait_for) argument is provided, the module is not returned until the condition is satisfied or the number of I(retries) has been exceeded. required: true wait_for: description: - Specifies what to evaluate from the output of the command and what conditionals to apply. This argument will cause the task to wait for a particular conditional to be true before moving forward. If the conditional is not true by the configured retries, the task fails. See examples. match: description: - The I(match) argument is used in conjunction with the I(wait_for) argument to specify the match policy. Valid values are C(all) or C(any). If the value is set to C(all) then all conditionals in the I(wait_for) must be satisfied. If the value is set to C(any) then only one of the values must be satisfied. default: all retries: description: - Specifies the number of retries a command should by tried before it is considered failed. The command is run on the target device every retry and evaluated against the I(wait_for) conditionals. default: 10 interval: description: - Configures the interval in seconds to wait between retries of the command. If the command does not pass the specified conditional, the interval indicates how to long to wait before trying the command again. default: 1 """ EXAMPLES = """ # Note: examples below use the following provider dict to handle # transport and authentication to the node. - name: CloudEngine command test hosts: cloudengine connection: local gather_facts: no vars: cli: host: "{{ inventory_hostname }}" port: "{{ ansible_ssh_port }}" username: "{{ username }}" password: "{{ password }}" transport: cli tasks: - name: "Run display version on remote devices" ce_command: commands: display version provider: "{{ cli }}" - name: "Run display version and check to see if output contains HUAWEI" ce_command: commands: display version wait_for: result[0] contains HUAWEI provider: "{{ cli }}" - name: "Run multiple commands on remote nodes" ce_command: commands: - display version - display device provider: "{{ cli }}" - name: "Run multiple commands and evaluate the output" ce_command: commands: - display version - display device wait_for: - result[0] contains HUAWEI - result[1] contains Device provider: "{{ cli }}" """ RETURN = """ stdout: description: the set of responses from the commands returned: always type: list sample: ['...', '...'] stdout_lines: description: The value of stdout split into a list returned: always type: list sample: [['...', '...'], ['...'], ['...']] failed_conditions: description: the conditionals that failed returned: failed type: list sample: ['...', '...'] """ import time import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.cloudengine.ce import ce_argument_spec, check_args from ansible.module_utils.network.cloudengine.ce import run_commands from ansible.module_utils.network.common.parsing import Conditional from ansible.module_utils.network.common.utils import ComplexList from ansible.module_utils.six import string_types from ansible.module_utils._text import to_native def to_lines(stdout): lines = list() for item in stdout: if isinstance(item, string_types): item = str(item).split('\n') lines.append(item) return lines def parse_commands(module, warnings): transform = ComplexList(dict( command=dict(key=True), output=dict(), prompt=dict(), response=dict() ), module) commands = transform(module.params['commands']) for _, item in enumerate(commands): if module.check_mode and not item['command'].startswith('dis'): warnings.append( 'Only display commands are supported when using check_mode, not ' 'executing %s' % item['command'] ) return commands def to_cli(obj): cmd = obj['command'] return cmd def main(): """entry point for module execution """ argument_spec = dict( # { command: <str>, output: <str>, prompt: <str>, response: <str> } commands=dict(type='list', required=True), wait_for=dict(type='list'), match=dict(default='all', choices=['any', 'all']), retries=dict(default=10, type='int'), interval=dict(default=1, type='int') ) argument_spec.update(ce_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) result = {'changed': False} warnings = list() check_args(module, warnings) commands = parse_commands(module, warnings) result['warnings'] = warnings wait_for = module.params['wait_for'] or list() try: conditionals = [Conditional(c) for c in wait_for] except AttributeError as exc: module.fail_json(msg=to_native(exc), exception=traceback.format_exc()) retries = module.params['retries'] interval = module.params['interval'] match = module.params['match'] while retries > 0: responses = run_commands(module, commands) for item in list(conditionals): if item(responses): if match == 'any': conditionals = list() break conditionals.remove(item) if not conditionals: break time.sleep(interval) retries -= 1 if conditionals: failed_conditions = [item.raw for item in conditionals] msg = 'One or more conditional statements have not been satisfied' module.fail_json(msg=msg, failed_conditions=failed_conditions) result.update({ 'stdout': responses, 'stdout_lines': to_lines(responses) }) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
tchernomax/ansible
lib/ansible/modules/cloud/cloudstack/cs_network.py
37
18141
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017, René Moser <mail@renemoser.net> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cs_network short_description: Manages networks on Apache CloudStack based clouds. description: - Create, update, restart and delete networks. version_added: '2.0' author: "René Moser (@resmo)" options: name: description: - Name (case sensitive) of the network. required: true display_text: description: - Display text of the network. - If not specified, C(name) will be used as C(display_text). network_offering: description: - Name of the offering for the network. - Required if C(state=present). start_ip: description: - The beginning IPv4 address of the network belongs to. - Only considered on create. end_ip: description: - The ending IPv4 address of the network belongs to. - If not specified, value of C(start_ip) is used. - Only considered on create. gateway: description: - The gateway of the network. - Required for shared networks and isolated networks when it belongs to a VPC. - Only considered on create. netmask: description: - The netmask of the network. - Required for shared networks and isolated networks when it belongs to a VPC. - Only considered on create. start_ipv6: description: - The beginning IPv6 address of the network belongs to. - Only considered on create. end_ipv6: description: - The ending IPv6 address of the network belongs to. - If not specified, value of C(start_ipv6) is used. - Only considered on create. cidr_ipv6: description: - CIDR of IPv6 network, must be at least /64. - Only considered on create. gateway_ipv6: description: - The gateway of the IPv6 network. - Required for shared networks. - Only considered on create. vlan: description: - The ID or VID of the network. vpc: description: - Name of the VPC of the network. isolated_pvlan: description: - The isolated private VLAN for this network. clean_up: description: - Cleanup old network elements. - Only considered on C(state=restarted). default: no type: bool acl_type: description: - Access control type for the VPC network tier. - Only considered on create. default: account choices: [ account, domain ] acl: description: - The name of the access control list for the VPC network tier. version_added: "2.5" subdomain_access: description: - Defines whether to allow subdomains to use networks dedicated to their parent domain(s). - Should be used with C(acl_type=domain). - Only considered on create. type: bool version_added: "2.5" network_domain: description: - The network domain. state: description: - State of the network. default: present choices: [ present, absent, restarted ] zone: description: - Name of the zone in which the network should be deployed. - If not set, default zone is used. project: description: - Name of the project the network to be deployed in. domain: description: - Domain the network is related to. account: description: - Account the network is related to. poll_async: description: - Poll async jobs until job has finished. default: yes type: bool extends_documentation_fragment: cloudstack ''' EXAMPLES = ''' - name: Create a network local_action: module: cs_network name: my network zone: gva-01 network_offering: DefaultIsolatedNetworkOfferingWithSourceNatService network_domain: example.com - name: Create a VPC tier local_action: module: cs_network name: my VPC tier 1 zone: gva-01 vpc: my VPC network_offering: DefaultIsolatedNetworkOfferingForVpcNetworks gateway: 10.43.0.1 netmask: 255.255.255.0 acl: my web acl - name: Update a network local_action: module: cs_network name: my network display_text: network of domain example.local network_domain: example.local - name: Restart a network with clean up local_action: module: cs_network name: my network clean_up: yes state: restared - name: Remove a network local_action: module: cs_network name: my network state: absent ''' RETURN = ''' --- id: description: UUID of the network. returned: success type: string sample: 04589590-ac63-4ffc-93f5-b698b8ac38b6 name: description: Name of the network. returned: success type: string sample: web project display_text: description: Display text of the network. returned: success type: string sample: web project dns1: description: IP address of the 1st nameserver. returned: success type: string sample: 1.2.3.4 dns2: description: IP address of the 2nd nameserver. returned: success type: string sample: 1.2.3.4 cidr: description: IPv4 network CIDR. returned: success type: string sample: 10.101.64.0/24 gateway: description: IPv4 gateway. returned: success type: string sample: 10.101.64.1 netmask: description: IPv4 netmask. returned: success type: string sample: 255.255.255.0 cidr_ipv6: description: IPv6 network CIDR. returned: success type: string sample: 2001:db8::/64 gateway_ipv6: description: IPv6 gateway. returned: success type: string sample: 2001:db8::1 zone: description: Name of zone. returned: success type: string sample: ch-gva-2 domain: description: Domain the network is related to. returned: success type: string sample: ROOT account: description: Account the network is related to. returned: success type: string sample: example account project: description: Name of project. returned: success type: string sample: Production tags: description: List of resource tags associated with the network. returned: success type: dict sample: '[ { "key": "foo", "value": "bar" } ]' acl_type: description: Access type of the VPC network tier (Domain, Account). returned: success type: string sample: Account acl: description: Name of the access control list for the VPC network tier. returned: success type: string sample: My ACL version_added: "2.5" acl_id: description: ID of the access control list for the VPC network tier. returned: success type: string sample: dfafcd55-0510-4b8c-b6c5-b8cedb4cfd88 version_added: "2.5" broadcast_domain_type: description: Broadcast domain type of the network. returned: success type: string sample: Vlan type: description: Type of the network. returned: success type: string sample: Isolated traffic_type: description: Traffic type of the network. returned: success type: string sample: Guest state: description: State of the network (Allocated, Implemented, Setup). returned: success type: string sample: Allocated is_persistent: description: Whether the network is persistent or not. returned: success type: boolean sample: false network_domain: description: The network domain returned: success type: string sample: example.local network_offering: description: The network offering name. returned: success type: string sample: DefaultIsolatedNetworkOfferingWithSourceNatService network_offering_display_text: description: The network offering display text. returned: success type: string sample: Offering for Isolated Vpc networks with Source Nat service enabled version_added: "2.5" network_offering_conserve_mode: description: Whether the network offering has IP conserve mode enabled or not. returned: success type: bool sample: false version_added: "2.5" network_offering_availability: description: The availability of the network offering the network is created from returned: success type: string sample: Optional version_added: "2.5" is_system: description: Whether the network is system related or not. returned: success type: bool sample: false version_added: "2.5" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.cloudstack import ( AnsibleCloudStack, cs_argument_spec, cs_required_together, ) class AnsibleCloudStackNetwork(AnsibleCloudStack): def __init__(self, module): super(AnsibleCloudStackNetwork, self).__init__(module) self.returns = { 'networkdomain': 'network_domain', 'networkofferingname': 'network_offering', 'networkofferingdisplaytext': 'network_offering_display_text', 'networkofferingconservemode': 'network_offering_conserve_mode', 'networkofferingavailability': 'network_offering_availability', 'aclid': 'acl_id', 'issystem': 'is_system', 'ispersistent': 'is_persistent', 'acltype': 'acl_type', 'type': 'type', 'traffictype': 'traffic_type', 'ip6gateway': 'gateway_ipv6', 'ip6cidr': 'cidr_ipv6', 'gateway': 'gateway', 'cidr': 'cidr', 'netmask': 'netmask', 'broadcastdomaintype': 'broadcast_domain_type', 'dns1': 'dns1', 'dns2': 'dns2', } self.network = None def get_network_acl(self, key=None, acl_id=None): if acl_id is not None: args = { 'id': acl_id, 'vpcid': self.get_vpc(key='id'), } else: acl_name = self.module.params.get('acl') if not acl_name: return args = { 'name': acl_name, 'vpcid': self.get_vpc(key='id'), } network_acls = self.query_api('listNetworkACLLists', **args) if network_acls: acl = network_acls['networkacllist'][0] return self._get_by_key(key, acl) def get_network_offering(self, key=None): network_offering = self.module.params.get('network_offering') if not network_offering: self.module.fail_json(msg="missing required arguments: network_offering") args = { 'zoneid': self.get_zone(key='id'), 'fetch_list': True, } network_offerings = self.query_api('listNetworkOfferings', **args) if network_offerings: for no in network_offerings: if network_offering in [no['name'], no['displaytext'], no['id']]: return self._get_by_key(key, no) self.module.fail_json(msg="Network offering '%s' not found" % network_offering) def _get_args(self): args = { 'name': self.module.params.get('name'), 'displaytext': self.get_or_fallback('display_text', 'name'), 'networkdomain': self.module.params.get('network_domain'), 'networkofferingid': self.get_network_offering(key='id') } return args def get_network(self, refresh=False): if not self.network or refresh: network = self.module.params.get('name') args = { 'zoneid': self.get_zone(key='id'), 'projectid': self.get_project(key='id'), 'account': self.get_account(key='name'), 'domainid': self.get_domain(key='id'), 'vpcid': self.get_vpc(key='id'), 'fetch_list': True, } networks = self.query_api('listNetworks', **args) if networks: for n in networks: if network in [n['name'], n['displaytext'], n['id']]: self.network = n self.network['acl'] = self.get_network_acl(key='name', acl_id=n.get('aclid')) break return self.network def present_network(self): if self.module.params.get('acl') is not None and self.module.params.get('vpc') is None: self.module.fail_json(msg="Missing required params: vpc") network = self.get_network() if not network: network = self.create_network(network) else: network = self.update_network(network) return network def update_network(self, network): args = self._get_args() args['id'] = network['id'] if self.has_changed(args, network): self.result['changed'] = True if not self.module.check_mode: network = self.query_api('updateNetwork', **args) poll_async = self.module.params.get('poll_async') if network and poll_async: network = self.poll_job(network, 'network') # Skip ACL check if the network is not a VPC tier if network.get('aclid') != self.get_network_acl(key='id'): self.result['changed'] = True if not self.module.check_mode: args = { 'aclid': self.get_network_acl(key='id'), 'networkid': network['id'], } network = self.query_api('replaceNetworkACLList', **args) if self.module.params.get('poll_async'): self.poll_job(network, 'networkacllist') network = self.get_network(refresh=True) return network def create_network(self, network): self.result['changed'] = True args = self._get_args() args.update({ 'acltype': self.module.params.get('acl_type'), 'aclid': self.get_network_acl(key='id'), 'zoneid': self.get_zone(key='id'), 'projectid': self.get_project(key='id'), 'account': self.get_account(key='name'), 'domainid': self.get_domain(key='id'), 'startip': self.module.params.get('start_ip'), 'endip': self.get_or_fallback('end_ip', 'start_ip'), 'netmask': self.module.params.get('netmask'), 'gateway': self.module.params.get('gateway'), 'startipv6': self.module.params.get('start_ipv6'), 'endipv6': self.get_or_fallback('end_ipv6', 'start_ipv6'), 'ip6cidr': self.module.params.get('cidr_ipv6'), 'ip6gateway': self.module.params.get('gateway_ipv6'), 'vlan': self.module.params.get('vlan'), 'isolatedpvlan': self.module.params.get('isolated_pvlan'), 'subdomainaccess': self.module.params.get('subdomain_access'), 'vpcid': self.get_vpc(key='id') }) if not self.module.check_mode: res = self.query_api('createNetwork', **args) network = res['network'] return network def restart_network(self): network = self.get_network() if not network: self.module.fail_json(msg="No network named '%s' found." % self.module.params('name')) # Restarting only available for these states if network['state'].lower() in ['implemented', 'setup']: self.result['changed'] = True args = { 'id': network['id'], 'cleanup': self.module.params.get('clean_up') } if not self.module.check_mode: network = self.query_api('restartNetwork', **args) poll_async = self.module.params.get('poll_async') if network and poll_async: network = self.poll_job(network, 'network') return network def absent_network(self): network = self.get_network() if network: self.result['changed'] = True args = { 'id': network['id'] } if not self.module.check_mode: res = self.query_api('deleteNetwork', **args) poll_async = self.module.params.get('poll_async') if res and poll_async: self.poll_job(res, 'network') return network def get_result(self, network): super(AnsibleCloudStackNetwork, self).get_result(network) if network: self.result['acl'] = self.get_network_acl(key='name', acl_id=network.get('aclid')) return self.result def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name=dict(required=True), display_text=dict(), network_offering=dict(), zone=dict(), start_ip=dict(), end_ip=dict(), gateway=dict(), netmask=dict(), start_ipv6=dict(), end_ipv6=dict(), cidr_ipv6=dict(), gateway_ipv6=dict(), vlan=dict(), vpc=dict(), isolated_pvlan=dict(), clean_up=dict(type='bool', default=False), network_domain=dict(), subdomain_access=dict(type='bool'), state=dict(choices=['present', 'absent', 'restarted'], default='present'), acl=dict(), acl_type=dict(choices=['account', 'domain']), project=dict(), domain=dict(), account=dict(), poll_async=dict(type='bool', default=True), )) required_together = cs_required_together() required_together.extend([ ['netmask', 'gateway'], ]) module = AnsibleModule( argument_spec=argument_spec, required_together=required_together, supports_check_mode=True ) acs_network = AnsibleCloudStackNetwork(module) state = module.params.get('state') if state == 'absent': network = acs_network.absent_network() elif state == 'restarted': network = acs_network.restart_network() else: network = acs_network.present_network() result = acs_network.get_result(network) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
jjmleiro/hue
desktop/core/ext-py/Django-1.6.10/django/contrib/comments/views/moderation.py
210
5204
from __future__ import absolute_import from django import template from django.conf import settings from django.contrib import comments from django.contrib.auth.decorators import login_required, permission_required from django.contrib.comments import signals from django.contrib.comments.views.utils import next_redirect, confirmation_view from django.shortcuts import get_object_or_404, render_to_response from django.views.decorators.csrf import csrf_protect @csrf_protect @login_required def flag(request, comment_id, next=None): """ Flags a comment. Confirmation on GET, action on POST. Templates: :template:`comments/flag.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Flag on POST if request.method == 'POST': perform_flag(request, comment) return next_redirect(request, fallback=next or 'comments-flag-done', c=comment.pk) # Render a form on GET else: return render_to_response('comments/flag.html', {'comment': comment, "next": next}, template.RequestContext(request) ) @csrf_protect @permission_required("comments.can_moderate") def delete(request, comment_id, next=None): """ Deletes a comment. Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: :template:`comments/delete.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Delete on POST if request.method == 'POST': # Flag the comment as deleted instead of actually deleting it. perform_delete(request, comment) return next_redirect(request, fallback=next or 'comments-delete-done', c=comment.pk) # Render a form on GET else: return render_to_response('comments/delete.html', {'comment': comment, "next": next}, template.RequestContext(request) ) @csrf_protect @permission_required("comments.can_moderate") def approve(request, comment_id, next=None): """ Approve a comment (that is, mark it as public and non-removed). Confirmation on GET, action on POST. Requires the "can moderate comments" permission. Templates: :template:`comments/approve.html`, Context: comment the `comments.comment` object for approval """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) # Delete on POST if request.method == 'POST': # Flag the comment as approved. perform_approve(request, comment) return next_redirect(request, fallback=next or 'comments-approve-done', c=comment.pk) # Render a form on GET else: return render_to_response('comments/approve.html', {'comment': comment, "next": next}, template.RequestContext(request) ) # The following functions actually perform the various flag/aprove/delete # actions. They've been broken out into separate functions to that they # may be called from admin actions. def perform_flag(request, comment): """ Actually perform the flagging of a comment from a request. """ flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.SUGGEST_REMOVAL ) signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) def perform_delete(request, comment): flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.MODERATOR_DELETION ) comment.is_removed = True comment.save() signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) def perform_approve(request, comment): flag, created = comments.models.CommentFlag.objects.get_or_create( comment = comment, user = request.user, flag = comments.models.CommentFlag.MODERATOR_APPROVAL, ) comment.is_removed = False comment.is_public = True comment.save() signals.comment_was_flagged.send( sender = comment.__class__, comment = comment, flag = flag, created = created, request = request, ) # Confirmation views. flag_done = confirmation_view( template = "comments/flagged.html", doc = 'Displays a "comment was flagged" success page.' ) delete_done = confirmation_view( template = "comments/deleted.html", doc = 'Displays a "comment was deleted" success page.' ) approve_done = confirmation_view( template = "comments/approved.html", doc = 'Displays a "comment was approved" success page.' )
apache-2.0
akusok/website-ibc
wibc/modules/add_website.py
1
2369
# -*- coding: utf-8 -*- """Converts images, returns all information. Created on Mon Sep 16 14:58:13 2013 @author: akusoka1 """ from wibc.config.wibc_config import cf import os from PIL import Image import hashlib def add_website(imglist, out_folder): """ imglist -- list of images with paths out_folder -- folder for the given website with processed images """ # creating image folder os.makedirs(out_folder) # start gathering output ws = {} ws['img_present'] = len(imglist) ws['img_count'] = 0 ws['folder'] = out_folder ws['images'] = [] # processing images img_index = 0 # for saving new images for img_raw in imglist: # try to open, check file size try: if os.stat(img_raw).st_size < cf._min_size: #print "image too small" continue # if opened successfully == proper image img_obj = Image.open(img_raw).convert('RGB') except IOError: #print "error opening ", img_raw continue except: print "Unknown image opening/converting exception" continue img = {} # new image record img['true_size'] = img_obj.size img['true_name'] = img_raw img['sha1'] = hashlib.sha1(open(img_raw, 'r').read()).hexdigest() # check image dimensions, resize if needed maxs = cf._max_dim (x, y) = img_obj.size if (x > maxs) and (x >= y): y = int(y * (float(maxs) / x)) x = maxs img_obj = img_obj.resize((x, y), Image.ANTIALIAS) elif y > maxs: x = int(x * (float(maxs) / y)) y = maxs img_obj = img_obj.resize((x, y), Image.ANTIALIAS) img['new_size'] = img_obj.size # saving preprocessed image img_new = os.path.join(out_folder, "%d.jpg" % img_index) try: img_obj.save(img_new, 'JPEG', quality=cf._jpeg_quality) except: print "Error saving image" continue img['new_name'] = img_new img_index += 1 # appending image data to output ws['images'].append(img.copy()) ws['img_count'] += 1 return ws
gpl-2.0
cyc805/FTRerouting
src/mobility/bindings/modulegen__gcc_LP64.py
12
300893
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.mobility', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## box.h (module 'mobility'): ns3::Box [class] module.add_class('Box') ## box.h (module 'mobility'): ns3::Box::Side [enumeration] module.add_enum('Side', ['RIGHT', 'LEFT', 'TOP', 'BOTTOM', 'UP', 'DOWN'], outer_class=root_module['ns3::Box']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper [class] module.add_class('ConstantVelocityHelper') ## 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') ## mobility-helper.h (module 'mobility'): ns3::MobilityHelper [class] module.add_class('MobilityHelper') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## ns2-mobility-helper.h (module 'mobility'): ns3::Ns2MobilityHelper [class] module.add_class('Ns2MobilityHelper') ## 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') ## rectangle.h (module 'mobility'): ns3::Rectangle [class] module.add_class('Rectangle') ## rectangle.h (module 'mobility'): ns3::Rectangle::Side [enumeration] module.add_enum('Side', ['RIGHT', 'LEFT', 'TOP', 'BOTTOM'], outer_class=root_module['ns3::Rectangle']) ## 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-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## 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']) ## vector.h (module 'core'): ns3::Vector2D [class] module.add_class('Vector2D', import_from_module='ns.core') ## vector.h (module 'core'): ns3::Vector3D [class] module.add_class('Vector3D', import_from_module='ns.core') ## waypoint.h (module 'mobility'): ns3::Waypoint [class] module.add_class('Waypoint') ## 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') ## 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']) ## position-allocator.h (module 'mobility'): ns3::PositionAllocator [class] module.add_class('PositionAllocator', parent=root_module['ns3::Object']) ## position-allocator.h (module 'mobility'): ns3::RandomBoxPositionAllocator [class] module.add_class('RandomBoxPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## position-allocator.h (module 'mobility'): ns3::RandomDiscPositionAllocator [class] module.add_class('RandomDiscPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## position-allocator.h (module 'mobility'): ns3::RandomRectanglePositionAllocator [class] module.add_class('RandomRectanglePositionAllocator', parent=root_module['ns3::PositionAllocator']) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream [class] module.add_class('RandomVariableStream', import_from_module='ns.core', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable [class] module.add_class('SequentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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', ['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> >']) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable [class] module.add_class('TriangularRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## position-allocator.h (module 'mobility'): ns3::UniformDiscPositionAllocator [class] module.add_class('UniformDiscPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable [class] module.add_class('UniformRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable [class] module.add_class('WeibullRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable [class] module.add_class('ZetaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable [class] module.add_class('ZipfRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## 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> >']) ## box.h (module 'mobility'): ns3::BoxChecker [class] module.add_class('BoxChecker', parent=root_module['ns3::AttributeChecker']) ## box.h (module 'mobility'): ns3::BoxValue [class] module.add_class('BoxValue', 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']) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable [class] module.add_class('ConstantRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable [class] module.add_class('DeterministicRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable [class] module.add_class('EmpiricalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable [class] module.add_class('ErlangRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable [class] module.add_class('ExponentialRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable [class] module.add_class('GammaRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator [class] module.add_class('GridPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator::LayoutType [enumeration] module.add_enum('LayoutType', ['ROW_FIRST', 'COLUMN_FIRST'], outer_class=root_module['ns3::GridPositionAllocator']) ## 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']) ## position-allocator.h (module 'mobility'): ns3::ListPositionAllocator [class] module.add_class('ListPositionAllocator', parent=root_module['ns3::PositionAllocator']) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable [class] module.add_class('LogNormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## mobility-model.h (module 'mobility'): ns3::MobilityModel [class] module.add_class('MobilityModel', parent=root_module['ns3::Object']) ## 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') ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable [class] module.add_class('NormalRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable [class] module.add_class('ParetoRandomVariable', import_from_module='ns.core', parent=root_module['ns3::RandomVariableStream']) ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::RandomDirection2dMobilityModel [class] module.add_class('RandomDirection2dMobilityModel', parent=root_module['ns3::MobilityModel']) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::RandomWalk2dMobilityModel [class] module.add_class('RandomWalk2dMobilityModel', parent=root_module['ns3::MobilityModel']) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::RandomWalk2dMobilityModel::Mode [enumeration] module.add_enum('Mode', ['MODE_DISTANCE', 'MODE_TIME'], outer_class=root_module['ns3::RandomWalk2dMobilityModel']) ## random-waypoint-mobility-model.h (module 'mobility'): ns3::RandomWaypointMobilityModel [class] module.add_class('RandomWaypointMobilityModel', parent=root_module['ns3::MobilityModel']) ## rectangle.h (module 'mobility'): ns3::RectangleChecker [class] module.add_class('RectangleChecker', parent=root_module['ns3::AttributeChecker']) ## rectangle.h (module 'mobility'): ns3::RectangleValue [class] module.add_class('RectangleValue', parent=root_module['ns3::AttributeValue']) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::SteadyStateRandomWaypointMobilityModel [class] module.add_class('SteadyStateRandomWaypointMobilityModel', parent=root_module['ns3::MobilityModel']) ## 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']) ## vector.h (module 'core'): ns3::Vector2DChecker [class] module.add_class('Vector2DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector2DValue [class] module.add_class('Vector2DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector3DChecker [class] module.add_class('Vector3DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector3DValue [class] module.add_class('Vector3DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## waypoint.h (module 'mobility'): ns3::WaypointChecker [class] module.add_class('WaypointChecker', parent=root_module['ns3::AttributeChecker']) ## waypoint-mobility-model.h (module 'mobility'): ns3::WaypointMobilityModel [class] module.add_class('WaypointMobilityModel', parent=root_module['ns3::MobilityModel']) ## waypoint.h (module 'mobility'): ns3::WaypointValue [class] module.add_class('WaypointValue', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::ConstantAccelerationMobilityModel [class] module.add_class('ConstantAccelerationMobilityModel', parent=root_module['ns3::MobilityModel']) ## constant-position-mobility-model.h (module 'mobility'): ns3::ConstantPositionMobilityModel [class] module.add_class('ConstantPositionMobilityModel', parent=root_module['ns3::MobilityModel']) ## constant-velocity-mobility-model.h (module 'mobility'): ns3::ConstantVelocityMobilityModel [class] module.add_class('ConstantVelocityMobilityModel', parent=root_module['ns3::MobilityModel']) ## gauss-markov-mobility-model.h (module 'mobility'): ns3::GaussMarkovMobilityModel [class] module.add_class('GaussMarkovMobilityModel', parent=root_module['ns3::MobilityModel']) ## hierarchical-mobility-model.h (module 'mobility'): ns3::HierarchicalMobilityModel [class] module.add_class('HierarchicalMobilityModel', parent=root_module['ns3::MobilityModel']) typehandlers.add_type_alias('ns3::Vector3DValue', 'ns3::VectorValue') typehandlers.add_type_alias('ns3::Vector3DValue*', 'ns3::VectorValue*') typehandlers.add_type_alias('ns3::Vector3DValue&', 'ns3::VectorValue&') module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue') typehandlers.add_type_alias('ns3::Vector3D', 'ns3::Vector') typehandlers.add_type_alias('ns3::Vector3D*', 'ns3::Vector*') typehandlers.add_type_alias('ns3::Vector3D&', 'ns3::Vector&') module.add_typedef(root_module['ns3::Vector3D'], 'Vector') typehandlers.add_type_alias('ns3::Vector3DChecker', 'ns3::VectorChecker') typehandlers.add_type_alias('ns3::Vector3DChecker*', 'ns3::VectorChecker*') typehandlers.add_type_alias('ns3::Vector3DChecker&', 'ns3::VectorChecker&') module.add_typedef(root_module['ns3::Vector3DChecker'], 'VectorChecker') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias('uint32_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *', 'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) **', 'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias('uint64_t ( * ) ( char const *, size_t ) *&', 'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Box_methods(root_module, root_module['ns3::Box']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3ConstantVelocityHelper_methods(root_module, root_module['ns3::ConstantVelocityHelper']) 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_Ns3MobilityHelper_methods(root_module, root_module['ns3::MobilityHelper']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3Ns2MobilityHelper_methods(root_module, root_module['ns3::Ns2MobilityHelper']) 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_Ns3Rectangle_methods(root_module, root_module['ns3::Rectangle']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D']) register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D']) register_Ns3Waypoint_methods(root_module, root_module['ns3::Waypoint']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PositionAllocator_methods(root_module, root_module['ns3::PositionAllocator']) register_Ns3RandomBoxPositionAllocator_methods(root_module, root_module['ns3::RandomBoxPositionAllocator']) register_Ns3RandomDiscPositionAllocator_methods(root_module, root_module['ns3::RandomDiscPositionAllocator']) register_Ns3RandomRectanglePositionAllocator_methods(root_module, root_module['ns3::RandomRectanglePositionAllocator']) register_Ns3RandomVariableStream_methods(root_module, root_module['ns3::RandomVariableStream']) register_Ns3SequentialRandomVariable_methods(root_module, root_module['ns3::SequentialRandomVariable']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) 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_Ns3TriangularRandomVariable_methods(root_module, root_module['ns3::TriangularRandomVariable']) register_Ns3UniformDiscPositionAllocator_methods(root_module, root_module['ns3::UniformDiscPositionAllocator']) register_Ns3UniformRandomVariable_methods(root_module, root_module['ns3::UniformRandomVariable']) register_Ns3WeibullRandomVariable_methods(root_module, root_module['ns3::WeibullRandomVariable']) register_Ns3ZetaRandomVariable_methods(root_module, root_module['ns3::ZetaRandomVariable']) register_Ns3ZipfRandomVariable_methods(root_module, root_module['ns3::ZipfRandomVariable']) register_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_Ns3BoxChecker_methods(root_module, root_module['ns3::BoxChecker']) register_Ns3BoxValue_methods(root_module, root_module['ns3::BoxValue']) 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_Ns3ConstantRandomVariable_methods(root_module, root_module['ns3::ConstantRandomVariable']) register_Ns3DeterministicRandomVariable_methods(root_module, root_module['ns3::DeterministicRandomVariable']) register_Ns3EmpiricalRandomVariable_methods(root_module, root_module['ns3::EmpiricalRandomVariable']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3ErlangRandomVariable_methods(root_module, root_module['ns3::ErlangRandomVariable']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3ExponentialRandomVariable_methods(root_module, root_module['ns3::ExponentialRandomVariable']) register_Ns3GammaRandomVariable_methods(root_module, root_module['ns3::GammaRandomVariable']) register_Ns3GridPositionAllocator_methods(root_module, root_module['ns3::GridPositionAllocator']) 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_Ns3ListPositionAllocator_methods(root_module, root_module['ns3::ListPositionAllocator']) register_Ns3LogNormalRandomVariable_methods(root_module, root_module['ns3::LogNormalRandomVariable']) register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3NormalRandomVariable_methods(root_module, root_module['ns3::NormalRandomVariable']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3ParetoRandomVariable_methods(root_module, root_module['ns3::ParetoRandomVariable']) register_Ns3RandomDirection2dMobilityModel_methods(root_module, root_module['ns3::RandomDirection2dMobilityModel']) register_Ns3RandomWalk2dMobilityModel_methods(root_module, root_module['ns3::RandomWalk2dMobilityModel']) register_Ns3RandomWaypointMobilityModel_methods(root_module, root_module['ns3::RandomWaypointMobilityModel']) register_Ns3RectangleChecker_methods(root_module, root_module['ns3::RectangleChecker']) register_Ns3RectangleValue_methods(root_module, root_module['ns3::RectangleValue']) register_Ns3SteadyStateRandomWaypointMobilityModel_methods(root_module, root_module['ns3::SteadyStateRandomWaypointMobilityModel']) 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_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker']) register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue']) register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker']) register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue']) register_Ns3WaypointChecker_methods(root_module, root_module['ns3::WaypointChecker']) register_Ns3WaypointMobilityModel_methods(root_module, root_module['ns3::WaypointMobilityModel']) register_Ns3WaypointValue_methods(root_module, root_module['ns3::WaypointValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3ConstantAccelerationMobilityModel_methods(root_module, root_module['ns3::ConstantAccelerationMobilityModel']) register_Ns3ConstantPositionMobilityModel_methods(root_module, root_module['ns3::ConstantPositionMobilityModel']) register_Ns3ConstantVelocityMobilityModel_methods(root_module, root_module['ns3::ConstantVelocityMobilityModel']) register_Ns3GaussMarkovMobilityModel_methods(root_module, root_module['ns3::GaussMarkovMobilityModel']) register_Ns3HierarchicalMobilityModel_methods(root_module, root_module['ns3::HierarchicalMobilityModel']) 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_Ns3Box_methods(root_module, cls): cls.add_output_stream_operator() ## box.h (module 'mobility'): ns3::Box::Box(ns3::Box const & arg0) [copy constructor] cls.add_constructor([param('ns3::Box const &', 'arg0')]) ## box.h (module 'mobility'): ns3::Box::Box(double _xMin, double _xMax, double _yMin, double _yMax, double _zMin, double _zMax) [constructor] cls.add_constructor([param('double', '_xMin'), param('double', '_xMax'), param('double', '_yMin'), param('double', '_yMax'), param('double', '_zMin'), param('double', '_zMax')]) ## box.h (module 'mobility'): ns3::Box::Box() [constructor] cls.add_constructor([]) ## box.h (module 'mobility'): ns3::Vector ns3::Box::CalculateIntersection(ns3::Vector const & current, ns3::Vector const & speed) const [member function] cls.add_method('CalculateIntersection', 'ns3::Vector', [param('ns3::Vector const &', 'current'), param('ns3::Vector const &', 'speed')], is_const=True) ## box.h (module 'mobility'): ns3::Box::Side ns3::Box::GetClosestSide(ns3::Vector const & position) const [member function] cls.add_method('GetClosestSide', 'ns3::Box::Side', [param('ns3::Vector const &', 'position')], is_const=True) ## box.h (module 'mobility'): bool ns3::Box::IsInside(ns3::Vector const & position) const [member function] cls.add_method('IsInside', 'bool', [param('ns3::Vector const &', 'position')], is_const=True) ## box.h (module 'mobility'): ns3::Box::xMax [variable] cls.add_instance_attribute('xMax', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::xMin [variable] cls.add_instance_attribute('xMin', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::yMax [variable] cls.add_instance_attribute('yMax', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::yMin [variable] cls.add_instance_attribute('yMin', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::zMax [variable] cls.add_instance_attribute('zMax', 'double', is_const=False) ## box.h (module 'mobility'): ns3::Box::zMin [variable] cls.add_instance_attribute('zMin', 'double', 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_Ns3ConstantVelocityHelper_methods(root_module, cls): ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper::ConstantVelocityHelper(ns3::ConstantVelocityHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantVelocityHelper const &', 'arg0')]) ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper::ConstantVelocityHelper() [constructor] cls.add_constructor([]) ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper::ConstantVelocityHelper(ns3::Vector const & position) [constructor] cls.add_constructor([param('ns3::Vector const &', 'position')]) ## constant-velocity-helper.h (module 'mobility'): ns3::ConstantVelocityHelper::ConstantVelocityHelper(ns3::Vector const & position, ns3::Vector const & vel) [constructor] cls.add_constructor([param('ns3::Vector const &', 'position'), param('ns3::Vector const &', 'vel')]) ## constant-velocity-helper.h (module 'mobility'): ns3::Vector ns3::ConstantVelocityHelper::GetCurrentPosition() const [member function] cls.add_method('GetCurrentPosition', 'ns3::Vector', [], is_const=True) ## constant-velocity-helper.h (module 'mobility'): ns3::Vector ns3::ConstantVelocityHelper::GetVelocity() const [member function] cls.add_method('GetVelocity', 'ns3::Vector', [], is_const=True) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::Pause() [member function] cls.add_method('Pause', 'void', []) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::SetPosition(ns3::Vector const & position) [member function] cls.add_method('SetPosition', 'void', [param('ns3::Vector const &', 'position')]) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::SetVelocity(ns3::Vector const & vel) [member function] cls.add_method('SetVelocity', 'void', [param('ns3::Vector const &', 'vel')]) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::Unpause() [member function] cls.add_method('Unpause', 'void', []) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::Update() const [member function] cls.add_method('Update', 'void', [], is_const=True) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::UpdateWithBounds(ns3::Rectangle const & rectangle) const [member function] cls.add_method('UpdateWithBounds', 'void', [param('ns3::Rectangle const &', 'rectangle')], is_const=True) ## constant-velocity-helper.h (module 'mobility'): void ns3::ConstantVelocityHelper::UpdateWithBounds(ns3::Box const & bounds) const [member function] cls.add_method('UpdateWithBounds', 'void', [param('ns3::Box const &', 'bounds')], is_const=True) return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::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() [member function] cls.add_method('IsIpv4MappedAddress', 'bool', []) ## 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_Ns3MobilityHelper_methods(root_module, cls): ## mobility-helper.h (module 'mobility'): ns3::MobilityHelper::MobilityHelper(ns3::MobilityHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::MobilityHelper const &', 'arg0')]) ## mobility-helper.h (module 'mobility'): ns3::MobilityHelper::MobilityHelper() [constructor] cls.add_constructor([]) ## mobility-helper.h (module 'mobility'): int64_t ns3::MobilityHelper::AssignStreams(ns3::NodeContainer c, int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('ns3::NodeContainer', 'c'), param('int64_t', 'stream')]) ## mobility-helper.h (module 'mobility'): static void ns3::MobilityHelper::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid')], is_static=True) ## mobility-helper.h (module 'mobility'): static void ns3::MobilityHelper::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')], is_static=True) ## mobility-helper.h (module 'mobility'): static void ns3::MobilityHelper::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiAll', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_static=True) ## mobility-helper.h (module 'mobility'): std::string ns3::MobilityHelper::GetMobilityModelType() const [member function] cls.add_method('GetMobilityModelType', 'std::string', [], is_const=True) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'void', [param('std::string', 'nodeName')], is_const=True) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::Install(ns3::NodeContainer container) const [member function] cls.add_method('Install', 'void', [param('ns3::NodeContainer', 'container')], is_const=True) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::InstallAll() [member function] cls.add_method('InstallAll', 'void', []) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::PopReferenceMobilityModel() [member function] cls.add_method('PopReferenceMobilityModel', 'void', []) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::PushReferenceMobilityModel(ns3::Ptr<ns3::Object> reference) [member function] cls.add_method('PushReferenceMobilityModel', 'void', [param('ns3::Ptr< ns3::Object >', 'reference')]) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::PushReferenceMobilityModel(std::string referenceName) [member function] cls.add_method('PushReferenceMobilityModel', 'void', [param('std::string', 'referenceName')]) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::SetMobilityModel(std::string type, std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue(), std::string n8="", ns3::AttributeValue const & v8=ns3::EmptyAttributeValue(), std::string n9="", ns3::AttributeValue const & v9=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetMobilityModel', 'void', [param('std::string', 'type'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n8', default_value='""'), param('ns3::AttributeValue const &', 'v8', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n9', default_value='""'), param('ns3::AttributeValue const &', 'v9', default_value='ns3::EmptyAttributeValue()')]) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::SetPositionAllocator(ns3::Ptr<ns3::PositionAllocator> allocator) [member function] cls.add_method('SetPositionAllocator', 'void', [param('ns3::Ptr< ns3::PositionAllocator >', 'allocator')]) ## mobility-helper.h (module 'mobility'): void ns3::MobilityHelper::SetPositionAllocator(std::string type, std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue(), std::string n5="", ns3::AttributeValue const & v5=ns3::EmptyAttributeValue(), std::string n6="", ns3::AttributeValue const & v6=ns3::EmptyAttributeValue(), std::string n7="", ns3::AttributeValue const & v7=ns3::EmptyAttributeValue(), std::string n8="", ns3::AttributeValue const & v8=ns3::EmptyAttributeValue(), std::string n9="", ns3::AttributeValue const & v9=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetPositionAllocator', 'void', [param('std::string', 'type'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n5', default_value='""'), param('ns3::AttributeValue const &', 'v5', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n6', default_value='""'), param('ns3::AttributeValue const &', 'v6', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n7', default_value='""'), param('ns3::AttributeValue const &', 'v7', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n8', default_value='""'), param('ns3::AttributeValue const &', 'v8', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n9', default_value='""'), param('ns3::AttributeValue const &', 'v9', default_value='ns3::EmptyAttributeValue()')]) 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_Ns3Ns2MobilityHelper_methods(root_module, cls): ## ns2-mobility-helper.h (module 'mobility'): ns3::Ns2MobilityHelper::Ns2MobilityHelper(ns3::Ns2MobilityHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ns2MobilityHelper const &', 'arg0')]) ## ns2-mobility-helper.h (module 'mobility'): ns3::Ns2MobilityHelper::Ns2MobilityHelper(std::string filename) [constructor] cls.add_constructor([param('std::string', 'filename')]) ## ns2-mobility-helper.h (module 'mobility'): void ns3::Ns2MobilityHelper::Install() const [member function] cls.add_method('Install', 'void', [], 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_Ns3Rectangle_methods(root_module, cls): cls.add_output_stream_operator() ## rectangle.h (module 'mobility'): ns3::Rectangle::Rectangle(ns3::Rectangle const & arg0) [copy constructor] cls.add_constructor([param('ns3::Rectangle const &', 'arg0')]) ## rectangle.h (module 'mobility'): ns3::Rectangle::Rectangle(double _xMin, double _xMax, double _yMin, double _yMax) [constructor] cls.add_constructor([param('double', '_xMin'), param('double', '_xMax'), param('double', '_yMin'), param('double', '_yMax')]) ## rectangle.h (module 'mobility'): ns3::Rectangle::Rectangle() [constructor] cls.add_constructor([]) ## rectangle.h (module 'mobility'): ns3::Vector ns3::Rectangle::CalculateIntersection(ns3::Vector const & current, ns3::Vector const & speed) const [member function] cls.add_method('CalculateIntersection', 'ns3::Vector', [param('ns3::Vector const &', 'current'), param('ns3::Vector const &', 'speed')], is_const=True) ## rectangle.h (module 'mobility'): ns3::Rectangle::Side ns3::Rectangle::GetClosestSide(ns3::Vector const & position) const [member function] cls.add_method('GetClosestSide', 'ns3::Rectangle::Side', [param('ns3::Vector const &', 'position')], is_const=True) ## rectangle.h (module 'mobility'): bool ns3::Rectangle::IsInside(ns3::Vector const & position) const [member function] cls.add_method('IsInside', 'bool', [param('ns3::Vector const &', 'position')], is_const=True) ## rectangle.h (module 'mobility'): ns3::Rectangle::xMax [variable] cls.add_instance_attribute('xMax', 'double', is_const=False) ## rectangle.h (module 'mobility'): ns3::Rectangle::xMin [variable] cls.add_instance_attribute('xMin', 'double', is_const=False) ## rectangle.h (module 'mobility'): ns3::Rectangle::yMax [variable] cls.add_instance_attribute('yMax', 'double', is_const=False) ## rectangle.h (module 'mobility'): ns3::Rectangle::yMin [variable] cls.add_instance_attribute('yMin', 'double', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_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_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_Ns3Vector2D_methods(root_module, cls): cls.add_output_stream_operator() ## vector.h (module 'core'): ns3::Vector2D::Vector2D(ns3::Vector2D const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2D const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2D::Vector2D(double _x, double _y) [constructor] cls.add_constructor([param('double', '_x'), param('double', '_y')]) ## vector.h (module 'core'): ns3::Vector2D::Vector2D() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2D::x [variable] cls.add_instance_attribute('x', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector2D::y [variable] cls.add_instance_attribute('y', 'double', is_const=False) return def register_Ns3Vector3D_methods(root_module, cls): cls.add_output_stream_operator() ## vector.h (module 'core'): ns3::Vector3D::Vector3D(ns3::Vector3D const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3D const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3D::Vector3D(double _x, double _y, double _z) [constructor] cls.add_constructor([param('double', '_x'), param('double', '_y'), param('double', '_z')]) ## vector.h (module 'core'): ns3::Vector3D::Vector3D() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3D::x [variable] cls.add_instance_attribute('x', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector3D::y [variable] cls.add_instance_attribute('y', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector3D::z [variable] cls.add_instance_attribute('z', 'double', is_const=False) return def register_Ns3Waypoint_methods(root_module, cls): cls.add_output_stream_operator() ## waypoint.h (module 'mobility'): ns3::Waypoint::Waypoint(ns3::Waypoint const & arg0) [copy constructor] cls.add_constructor([param('ns3::Waypoint const &', 'arg0')]) ## waypoint.h (module 'mobility'): ns3::Waypoint::Waypoint(ns3::Time const & waypointTime, ns3::Vector const & waypointPosition) [constructor] cls.add_constructor([param('ns3::Time const &', 'waypointTime'), param('ns3::Vector const &', 'waypointPosition')]) ## waypoint.h (module 'mobility'): ns3::Waypoint::Waypoint() [constructor] cls.add_constructor([]) ## waypoint.h (module 'mobility'): ns3::Waypoint::position [variable] cls.add_instance_attribute('position', 'ns3::Vector', is_const=False) ## waypoint.h (module 'mobility'): ns3::Waypoint::time [variable] cls.add_instance_attribute('time', 'ns3::Time', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) return def register_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_Ns3PositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::PositionAllocator::PositionAllocator(ns3::PositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::PositionAllocator::PositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::PositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::PositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::PositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3RandomBoxPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::RandomBoxPositionAllocator::RandomBoxPositionAllocator(ns3::RandomBoxPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomBoxPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::RandomBoxPositionAllocator::RandomBoxPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::RandomBoxPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::RandomBoxPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::RandomBoxPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::RandomBoxPositionAllocator::SetX(ns3::Ptr<ns3::RandomVariableStream> x) [member function] cls.add_method('SetX', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'x')]) ## position-allocator.h (module 'mobility'): void ns3::RandomBoxPositionAllocator::SetY(ns3::Ptr<ns3::RandomVariableStream> y) [member function] cls.add_method('SetY', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'y')]) ## position-allocator.h (module 'mobility'): void ns3::RandomBoxPositionAllocator::SetZ(ns3::Ptr<ns3::RandomVariableStream> z) [member function] cls.add_method('SetZ', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'z')]) return def register_Ns3RandomDiscPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::RandomDiscPositionAllocator::RandomDiscPositionAllocator(ns3::RandomDiscPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomDiscPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::RandomDiscPositionAllocator::RandomDiscPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::RandomDiscPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::RandomDiscPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::RandomDiscPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::RandomDiscPositionAllocator::SetRho(ns3::Ptr<ns3::RandomVariableStream> rho) [member function] cls.add_method('SetRho', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'rho')]) ## position-allocator.h (module 'mobility'): void ns3::RandomDiscPositionAllocator::SetTheta(ns3::Ptr<ns3::RandomVariableStream> theta) [member function] cls.add_method('SetTheta', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'theta')]) ## position-allocator.h (module 'mobility'): void ns3::RandomDiscPositionAllocator::SetX(double x) [member function] cls.add_method('SetX', 'void', [param('double', 'x')]) ## position-allocator.h (module 'mobility'): void ns3::RandomDiscPositionAllocator::SetY(double y) [member function] cls.add_method('SetY', 'void', [param('double', 'y')]) return def register_Ns3RandomRectanglePositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::RandomRectanglePositionAllocator::RandomRectanglePositionAllocator(ns3::RandomRectanglePositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomRectanglePositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::RandomRectanglePositionAllocator::RandomRectanglePositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::RandomRectanglePositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::RandomRectanglePositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::RandomRectanglePositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::RandomRectanglePositionAllocator::SetX(ns3::Ptr<ns3::RandomVariableStream> x) [member function] cls.add_method('SetX', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'x')]) ## position-allocator.h (module 'mobility'): void ns3::RandomRectanglePositionAllocator::SetY(ns3::Ptr<ns3::RandomVariableStream> y) [member function] cls.add_method('SetY', 'void', [param('ns3::Ptr< ns3::RandomVariableStream >', 'y')]) return def register_Ns3RandomVariableStream_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::RandomVariableStream::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::RandomVariableStream::RandomVariableStream() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetStream(int64_t stream) [member function] cls.add_method('SetStream', 'void', [param('int64_t', 'stream')]) ## random-variable-stream.h (module 'core'): int64_t ns3::RandomVariableStream::GetStream() const [member function] cls.add_method('GetStream', 'int64_t', [], is_const=True) ## random-variable-stream.h (module 'core'): void ns3::RandomVariableStream::SetAntithetic(bool isAntithetic) [member function] cls.add_method('SetAntithetic', 'void', [param('bool', 'isAntithetic')]) ## random-variable-stream.h (module 'core'): bool ns3::RandomVariableStream::IsAntithetic() const [member function] cls.add_method('IsAntithetic', 'bool', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::RandomVariableStream::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::RandomVariableStream::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_pure_virtual=True, is_virtual=True) ## random-variable-stream.h (module 'core'): ns3::RngStream * ns3::RandomVariableStream::Peek() const [member function] cls.add_method('Peek', 'ns3::RngStream *', [], is_const=True, visibility='protected') return def register_Ns3SequentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::SequentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::SequentialRandomVariable::SequentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): ns3::Ptr<ns3::RandomVariableStream> ns3::SequentialRandomVariable::GetIncrement() const [member function] cls.add_method('GetIncrement', 'ns3::Ptr< ns3::RandomVariableStream >', [], is_const=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetConsecutive() const [member function] cls.add_method('GetConsecutive', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::SequentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::SequentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [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__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__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('ns3::Time const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::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'): 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'): 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'): 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_Ns3TriangularRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::TriangularRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::TriangularRandomVariable::TriangularRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue(double mean, double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger(uint32_t mean, uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::TriangularRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::TriangularRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3UniformDiscPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::UniformDiscPositionAllocator::UniformDiscPositionAllocator(ns3::UniformDiscPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::UniformDiscPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::UniformDiscPositionAllocator::UniformDiscPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::UniformDiscPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::UniformDiscPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::UniformDiscPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::UniformDiscPositionAllocator::SetRho(double rho) [member function] cls.add_method('SetRho', 'void', [param('double', 'rho')]) ## position-allocator.h (module 'mobility'): void ns3::UniformDiscPositionAllocator::SetX(double x) [member function] cls.add_method('SetX', 'void', [param('double', 'x')]) ## position-allocator.h (module 'mobility'): void ns3::UniformDiscPositionAllocator::SetY(double y) [member function] cls.add_method('SetY', 'void', [param('double', 'y')]) return def register_Ns3UniformRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::UniformRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::UniformRandomVariable::UniformRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMin() const [member function] cls.add_method('GetMin', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetMax() const [member function] cls.add_method('GetMax', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue(double min, double max) [member function] cls.add_method('GetValue', 'double', [param('double', 'min'), param('double', 'max')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger(uint32_t min, uint32_t max) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'min'), param('uint32_t', 'max')]) ## random-variable-stream.h (module 'core'): double ns3::UniformRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::UniformRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3WeibullRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::WeibullRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::WeibullRandomVariable::WeibullRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetScale() const [member function] cls.add_method('GetScale', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue(double scale, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'scale'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger(uint32_t scale, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'scale'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::WeibullRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::WeibullRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZetaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZetaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZetaRandomVariable::ZetaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue(double alpha) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger(uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZetaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZetaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ZipfRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ZipfRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ZipfRandomVariable::ZipfRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue(uint32_t n, double alpha) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'n'), param('double', 'alpha')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger(uint32_t n, uint32_t alpha) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'n'), param('uint32_t', 'alpha')]) ## random-variable-stream.h (module 'core'): double ns3::ZipfRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ZipfRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_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_Ns3BoxChecker_methods(root_module, cls): ## box.h (module 'mobility'): ns3::BoxChecker::BoxChecker() [constructor] cls.add_constructor([]) ## box.h (module 'mobility'): ns3::BoxChecker::BoxChecker(ns3::BoxChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::BoxChecker const &', 'arg0')]) return def register_Ns3BoxValue_methods(root_module, cls): ## box.h (module 'mobility'): ns3::BoxValue::BoxValue() [constructor] cls.add_constructor([]) ## box.h (module 'mobility'): ns3::BoxValue::BoxValue(ns3::BoxValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::BoxValue const &', 'arg0')]) ## box.h (module 'mobility'): ns3::BoxValue::BoxValue(ns3::Box const & value) [constructor] cls.add_constructor([param('ns3::Box const &', 'value')]) ## box.h (module 'mobility'): ns3::Ptr<ns3::AttributeValue> ns3::BoxValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## box.h (module 'mobility'): bool ns3::BoxValue::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) ## box.h (module 'mobility'): ns3::Box ns3::BoxValue::Get() const [member function] cls.add_method('Get', 'ns3::Box', [], is_const=True) ## box.h (module 'mobility'): std::string ns3::BoxValue::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) ## box.h (module 'mobility'): void ns3::BoxValue::Set(ns3::Box const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Box const &', '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_Ns3ConstantRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ConstantRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ConstantRandomVariable::ConstantRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetConstant() const [member function] cls.add_method('GetConstant', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue(double constant) [member function] cls.add_method('GetValue', 'double', [param('double', 'constant')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger(uint32_t constant) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'constant')]) ## random-variable-stream.h (module 'core'): double ns3::ConstantRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ConstantRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3DeterministicRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::DeterministicRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::DeterministicRandomVariable::DeterministicRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::DeterministicRandomVariable::SetValueArray(double * values, uint64_t length) [member function] cls.add_method('SetValueArray', 'void', [param('double *', 'values'), param('uint64_t', 'length')]) ## random-variable-stream.h (module 'core'): double ns3::DeterministicRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::DeterministicRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3EmpiricalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::EmpiricalRandomVariable::EmpiricalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::CDF(double v, double c) [member function] cls.add_method('CDF', 'void', [param('double', 'v'), param('double', 'c')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::EmpiricalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::EmpiricalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): double ns3::EmpiricalRandomVariable::Interpolate(double arg0, double arg1, double arg2, double arg3, double arg4) [member function] cls.add_method('Interpolate', 'double', [param('double', 'arg0'), param('double', 'arg1'), param('double', 'arg2'), param('double', 'arg3'), param('double', 'arg4')], visibility='private', is_virtual=True) ## random-variable-stream.h (module 'core'): void ns3::EmpiricalRandomVariable::Validate() [member function] cls.add_method('Validate', 'void', [], visibility='private', is_virtual=True) return def register_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_Ns3ErlangRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ErlangRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ErlangRandomVariable::ErlangRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetK() const [member function] cls.add_method('GetK', 'uint32_t', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetLambda() const [member function] cls.add_method('GetLambda', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue(uint32_t k, double lambda) [member function] cls.add_method('GetValue', 'double', [param('uint32_t', 'k'), param('double', 'lambda')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger(uint32_t k, uint32_t lambda) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'k'), param('uint32_t', 'lambda')]) ## random-variable-stream.h (module 'core'): double ns3::ErlangRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ErlangRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3ExponentialRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ExponentialRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ExponentialRandomVariable::ExponentialRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue(double mean, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger(uint32_t mean, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ExponentialRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ExponentialRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3GammaRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::GammaRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::GammaRandomVariable::GammaRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetAlpha() const [member function] cls.add_method('GetAlpha', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetBeta() const [member function] cls.add_method('GetBeta', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue(double alpha, double beta) [member function] cls.add_method('GetValue', 'double', [param('double', 'alpha'), param('double', 'beta')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger(uint32_t alpha, uint32_t beta) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'alpha'), param('uint32_t', 'beta')]) ## random-variable-stream.h (module 'core'): double ns3::GammaRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::GammaRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3GridPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator::GridPositionAllocator(ns3::GridPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::GridPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator::GridPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): int64_t ns3::GridPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): double ns3::GridPositionAllocator::GetDeltaX() const [member function] cls.add_method('GetDeltaX', 'double', [], is_const=True) ## position-allocator.h (module 'mobility'): double ns3::GridPositionAllocator::GetDeltaY() const [member function] cls.add_method('GetDeltaY', 'double', [], is_const=True) ## position-allocator.h (module 'mobility'): ns3::GridPositionAllocator::LayoutType ns3::GridPositionAllocator::GetLayoutType() const [member function] cls.add_method('GetLayoutType', 'ns3::GridPositionAllocator::LayoutType', [], is_const=True) ## position-allocator.h (module 'mobility'): double ns3::GridPositionAllocator::GetMinX() const [member function] cls.add_method('GetMinX', 'double', [], is_const=True) ## position-allocator.h (module 'mobility'): double ns3::GridPositionAllocator::GetMinY() const [member function] cls.add_method('GetMinY', 'double', [], is_const=True) ## position-allocator.h (module 'mobility'): uint32_t ns3::GridPositionAllocator::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::GridPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::GridPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetDeltaX(double deltaX) [member function] cls.add_method('SetDeltaX', 'void', [param('double', 'deltaX')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetDeltaY(double deltaY) [member function] cls.add_method('SetDeltaY', 'void', [param('double', 'deltaY')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetLayoutType(ns3::GridPositionAllocator::LayoutType layoutType) [member function] cls.add_method('SetLayoutType', 'void', [param('ns3::GridPositionAllocator::LayoutType', 'layoutType')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetMinX(double xMin) [member function] cls.add_method('SetMinX', 'void', [param('double', 'xMin')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetMinY(double yMin) [member function] cls.add_method('SetMinY', 'void', [param('double', 'yMin')]) ## position-allocator.h (module 'mobility'): void ns3::GridPositionAllocator::SetN(uint32_t n) [member function] cls.add_method('SetN', 'void', [param('uint32_t', 'n')]) 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_Ns3ListPositionAllocator_methods(root_module, cls): ## position-allocator.h (module 'mobility'): ns3::ListPositionAllocator::ListPositionAllocator(ns3::ListPositionAllocator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ListPositionAllocator const &', 'arg0')]) ## position-allocator.h (module 'mobility'): ns3::ListPositionAllocator::ListPositionAllocator() [constructor] cls.add_constructor([]) ## position-allocator.h (module 'mobility'): void ns3::ListPositionAllocator::Add(ns3::Vector v) [member function] cls.add_method('Add', 'void', [param('ns3::Vector', 'v')]) ## position-allocator.h (module 'mobility'): int64_t ns3::ListPositionAllocator::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_virtual=True) ## position-allocator.h (module 'mobility'): ns3::Vector ns3::ListPositionAllocator::GetNext() const [member function] cls.add_method('GetNext', 'ns3::Vector', [], is_const=True, is_virtual=True) ## position-allocator.h (module 'mobility'): static ns3::TypeId ns3::ListPositionAllocator::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3LogNormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::LogNormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::LogNormalRandomVariable::LogNormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetMu() const [member function] cls.add_method('GetMu', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetSigma() const [member function] cls.add_method('GetSigma', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue(double mu, double sigma) [member function] cls.add_method('GetValue', 'double', [param('double', 'mu'), param('double', 'sigma')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger(uint32_t mu, uint32_t sigma) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mu'), param('uint32_t', 'sigma')]) ## random-variable-stream.h (module 'core'): double ns3::LogNormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::LogNormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3MobilityModel_methods(root_module, cls): ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel(ns3::MobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::MobilityModel const &', 'arg0')]) ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel() [constructor] cls.add_constructor([]) ## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::AssignStreams(int64_t stream) [member function] cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')]) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr<const ns3::MobilityModel> position) const [member function] cls.add_method('GetDistanceFrom', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'position')], is_const=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetPosition() const [member function] cls.add_method('GetPosition', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetRelativeSpeed(ns3::Ptr<const ns3::MobilityModel> other) const [member function] cls.add_method('GetRelativeSpeed', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'other')], is_const=True) ## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function] cls.add_method('GetVelocity', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function] cls.add_method('SetPosition', 'void', [param('ns3::Vector const &', 'position')]) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function] cls.add_method('NotifyCourseChange', 'void', [], is_const=True, visibility='protected') ## mobility-model.h (module 'mobility'): int64_t ns3::MobilityModel::DoAssignStreams(int64_t start) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'start')], visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_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_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_Ns3NormalRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::INFINITE_VALUE [variable] cls.add_static_attribute('INFINITE_VALUE', 'double const', is_const=True) ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::NormalRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::NormalRandomVariable::NormalRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetVariance() const [member function] cls.add_method('GetVariance', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue(double mean, double variance, double bound=ns3::NormalRandomVariable::INFINITE_VALUE) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'variance'), param('double', 'bound', default_value='ns3::NormalRandomVariable::INFINITE_VALUE')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger(uint32_t mean, uint32_t variance, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'variance'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::NormalRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::NormalRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3ParetoRandomVariable_methods(root_module, cls): ## random-variable-stream.h (module 'core'): static ns3::TypeId ns3::ParetoRandomVariable::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-variable-stream.h (module 'core'): ns3::ParetoRandomVariable::ParetoRandomVariable() [constructor] cls.add_constructor([]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetMean() const [member function] cls.add_method('GetMean', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetShape() const [member function] cls.add_method('GetShape', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetBound() const [member function] cls.add_method('GetBound', 'double', [], is_const=True) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue(double mean, double shape, double bound) [member function] cls.add_method('GetValue', 'double', [param('double', 'mean'), param('double', 'shape'), param('double', 'bound')]) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger(uint32_t mean, uint32_t shape, uint32_t bound) [member function] cls.add_method('GetInteger', 'uint32_t', [param('uint32_t', 'mean'), param('uint32_t', 'shape'), param('uint32_t', 'bound')]) ## random-variable-stream.h (module 'core'): double ns3::ParetoRandomVariable::GetValue() [member function] cls.add_method('GetValue', 'double', [], is_virtual=True) ## random-variable-stream.h (module 'core'): uint32_t ns3::ParetoRandomVariable::GetInteger() [member function] cls.add_method('GetInteger', 'uint32_t', [], is_virtual=True) return def register_Ns3RandomDirection2dMobilityModel_methods(root_module, cls): ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::RandomDirection2dMobilityModel::RandomDirection2dMobilityModel(ns3::RandomDirection2dMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomDirection2dMobilityModel const &', 'arg0')]) ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::RandomDirection2dMobilityModel::RandomDirection2dMobilityModel() [constructor] cls.add_constructor([]) ## random-direction-2d-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::RandomDirection2dMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-direction-2d-mobility-model.h (module 'mobility'): int64_t ns3::RandomDirection2dMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): void ns3::RandomDirection2dMobilityModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomDirection2dMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomDirection2dMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): void ns3::RandomDirection2dMobilityModel::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='private', is_virtual=True) ## random-direction-2d-mobility-model.h (module 'mobility'): void ns3::RandomDirection2dMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3RandomWalk2dMobilityModel_methods(root_module, cls): ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::RandomWalk2dMobilityModel::RandomWalk2dMobilityModel() [constructor] cls.add_constructor([]) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::RandomWalk2dMobilityModel::RandomWalk2dMobilityModel(ns3::RandomWalk2dMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomWalk2dMobilityModel const &', 'arg0')]) ## random-walk-2d-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::RandomWalk2dMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-walk-2d-mobility-model.h (module 'mobility'): int64_t ns3::RandomWalk2dMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): void ns3::RandomWalk2dMobilityModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomWalk2dMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomWalk2dMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): void ns3::RandomWalk2dMobilityModel::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='private', is_virtual=True) ## random-walk-2d-mobility-model.h (module 'mobility'): void ns3::RandomWalk2dMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3RandomWaypointMobilityModel_methods(root_module, cls): ## random-waypoint-mobility-model.h (module 'mobility'): ns3::RandomWaypointMobilityModel::RandomWaypointMobilityModel() [constructor] cls.add_constructor([]) ## random-waypoint-mobility-model.h (module 'mobility'): ns3::RandomWaypointMobilityModel::RandomWaypointMobilityModel(ns3::RandomWaypointMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::RandomWaypointMobilityModel const &', 'arg0')]) ## random-waypoint-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::RandomWaypointMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## random-waypoint-mobility-model.h (module 'mobility'): void ns3::RandomWaypointMobilityModel::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## random-waypoint-mobility-model.h (module 'mobility'): int64_t ns3::RandomWaypointMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## random-waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomWaypointMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::RandomWaypointMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## random-waypoint-mobility-model.h (module 'mobility'): void ns3::RandomWaypointMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3RectangleChecker_methods(root_module, cls): ## rectangle.h (module 'mobility'): ns3::RectangleChecker::RectangleChecker() [constructor] cls.add_constructor([]) ## rectangle.h (module 'mobility'): ns3::RectangleChecker::RectangleChecker(ns3::RectangleChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::RectangleChecker const &', 'arg0')]) return def register_Ns3RectangleValue_methods(root_module, cls): ## rectangle.h (module 'mobility'): ns3::RectangleValue::RectangleValue() [constructor] cls.add_constructor([]) ## rectangle.h (module 'mobility'): ns3::RectangleValue::RectangleValue(ns3::RectangleValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::RectangleValue const &', 'arg0')]) ## rectangle.h (module 'mobility'): ns3::RectangleValue::RectangleValue(ns3::Rectangle const & value) [constructor] cls.add_constructor([param('ns3::Rectangle const &', 'value')]) ## rectangle.h (module 'mobility'): ns3::Ptr<ns3::AttributeValue> ns3::RectangleValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## rectangle.h (module 'mobility'): bool ns3::RectangleValue::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) ## rectangle.h (module 'mobility'): ns3::Rectangle ns3::RectangleValue::Get() const [member function] cls.add_method('Get', 'ns3::Rectangle', [], is_const=True) ## rectangle.h (module 'mobility'): std::string ns3::RectangleValue::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) ## rectangle.h (module 'mobility'): void ns3::RectangleValue::Set(ns3::Rectangle const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Rectangle const &', 'value')]) return def register_Ns3SteadyStateRandomWaypointMobilityModel_methods(root_module, cls): ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::SteadyStateRandomWaypointMobilityModel::SteadyStateRandomWaypointMobilityModel(ns3::SteadyStateRandomWaypointMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::SteadyStateRandomWaypointMobilityModel const &', 'arg0')]) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::SteadyStateRandomWaypointMobilityModel::SteadyStateRandomWaypointMobilityModel() [constructor] cls.add_constructor([]) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::SteadyStateRandomWaypointMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): void ns3::SteadyStateRandomWaypointMobilityModel::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): int64_t ns3::SteadyStateRandomWaypointMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::SteadyStateRandomWaypointMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::SteadyStateRandomWaypointMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## steady-state-random-waypoint-mobility-model.h (module 'mobility'): void ns3::SteadyStateRandomWaypointMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], 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_Ns3Vector2DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')]) return def register_Ns3Vector2DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor] cls.add_constructor([param('ns3::Vector2D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector2DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector2DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector2D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector2DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector2D const &', 'value')]) return def register_Ns3Vector3DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')]) return def register_Ns3Vector3DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor] cls.add_constructor([param('ns3::Vector3D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector3DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector3DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector3D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector3DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector3D const &', 'value')]) return def register_Ns3WaypointChecker_methods(root_module, cls): ## waypoint.h (module 'mobility'): ns3::WaypointChecker::WaypointChecker() [constructor] cls.add_constructor([]) ## waypoint.h (module 'mobility'): ns3::WaypointChecker::WaypointChecker(ns3::WaypointChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::WaypointChecker const &', 'arg0')]) return def register_Ns3WaypointMobilityModel_methods(root_module, cls): ## waypoint-mobility-model.h (module 'mobility'): ns3::WaypointMobilityModel::WaypointMobilityModel(ns3::WaypointMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::WaypointMobilityModel const &', 'arg0')]) ## waypoint-mobility-model.h (module 'mobility'): ns3::WaypointMobilityModel::WaypointMobilityModel() [constructor] cls.add_constructor([]) ## waypoint-mobility-model.h (module 'mobility'): void ns3::WaypointMobilityModel::AddWaypoint(ns3::Waypoint const & waypoint) [member function] cls.add_method('AddWaypoint', 'void', [param('ns3::Waypoint const &', 'waypoint')]) ## waypoint-mobility-model.h (module 'mobility'): void ns3::WaypointMobilityModel::EndMobility() [member function] cls.add_method('EndMobility', 'void', []) ## waypoint-mobility-model.h (module 'mobility'): ns3::Waypoint ns3::WaypointMobilityModel::GetNextWaypoint() const [member function] cls.add_method('GetNextWaypoint', 'ns3::Waypoint', [], is_const=True) ## waypoint-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::WaypointMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## waypoint-mobility-model.h (module 'mobility'): uint32_t ns3::WaypointMobilityModel::WaypointsLeft() const [member function] cls.add_method('WaypointsLeft', 'uint32_t', [], is_const=True) ## waypoint-mobility-model.h (module 'mobility'): void ns3::WaypointMobilityModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::WaypointMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## waypoint-mobility-model.h (module 'mobility'): ns3::Vector ns3::WaypointMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## waypoint-mobility-model.h (module 'mobility'): void ns3::WaypointMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3WaypointValue_methods(root_module, cls): ## waypoint.h (module 'mobility'): ns3::WaypointValue::WaypointValue() [constructor] cls.add_constructor([]) ## waypoint.h (module 'mobility'): ns3::WaypointValue::WaypointValue(ns3::WaypointValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::WaypointValue const &', 'arg0')]) ## waypoint.h (module 'mobility'): ns3::WaypointValue::WaypointValue(ns3::Waypoint const & value) [constructor] cls.add_constructor([param('ns3::Waypoint const &', 'value')]) ## waypoint.h (module 'mobility'): ns3::Ptr<ns3::AttributeValue> ns3::WaypointValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## waypoint.h (module 'mobility'): bool ns3::WaypointValue::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) ## waypoint.h (module 'mobility'): ns3::Waypoint ns3::WaypointValue::Get() const [member function] cls.add_method('Get', 'ns3::Waypoint', [], is_const=True) ## waypoint.h (module 'mobility'): std::string ns3::WaypointValue::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) ## waypoint.h (module 'mobility'): void ns3::WaypointValue::Set(ns3::Waypoint const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Waypoint const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3ConstantAccelerationMobilityModel_methods(root_module, cls): ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::ConstantAccelerationMobilityModel::ConstantAccelerationMobilityModel(ns3::ConstantAccelerationMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantAccelerationMobilityModel const &', 'arg0')]) ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::ConstantAccelerationMobilityModel::ConstantAccelerationMobilityModel() [constructor] cls.add_constructor([]) ## constant-acceleration-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::ConstantAccelerationMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## constant-acceleration-mobility-model.h (module 'mobility'): void ns3::ConstantAccelerationMobilityModel::SetVelocityAndAcceleration(ns3::Vector const & velocity, ns3::Vector const & acceleration) [member function] cls.add_method('SetVelocityAndAcceleration', 'void', [param('ns3::Vector const &', 'velocity'), param('ns3::Vector const &', 'acceleration')]) ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantAccelerationMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-acceleration-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantAccelerationMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-acceleration-mobility-model.h (module 'mobility'): void ns3::ConstantAccelerationMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3ConstantPositionMobilityModel_methods(root_module, cls): ## constant-position-mobility-model.h (module 'mobility'): ns3::ConstantPositionMobilityModel::ConstantPositionMobilityModel(ns3::ConstantPositionMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantPositionMobilityModel const &', 'arg0')]) ## constant-position-mobility-model.h (module 'mobility'): ns3::ConstantPositionMobilityModel::ConstantPositionMobilityModel() [constructor] cls.add_constructor([]) ## constant-position-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::ConstantPositionMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## constant-position-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantPositionMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-position-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantPositionMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-position-mobility-model.h (module 'mobility'): void ns3::ConstantPositionMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3ConstantVelocityMobilityModel_methods(root_module, cls): ## constant-velocity-mobility-model.h (module 'mobility'): ns3::ConstantVelocityMobilityModel::ConstantVelocityMobilityModel(ns3::ConstantVelocityMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::ConstantVelocityMobilityModel const &', 'arg0')]) ## constant-velocity-mobility-model.h (module 'mobility'): ns3::ConstantVelocityMobilityModel::ConstantVelocityMobilityModel() [constructor] cls.add_constructor([]) ## constant-velocity-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::ConstantVelocityMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## constant-velocity-mobility-model.h (module 'mobility'): void ns3::ConstantVelocityMobilityModel::SetVelocity(ns3::Vector const & speed) [member function] cls.add_method('SetVelocity', 'void', [param('ns3::Vector const &', 'speed')]) ## constant-velocity-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantVelocityMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-velocity-mobility-model.h (module 'mobility'): ns3::Vector ns3::ConstantVelocityMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## constant-velocity-mobility-model.h (module 'mobility'): void ns3::ConstantVelocityMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3GaussMarkovMobilityModel_methods(root_module, cls): ## gauss-markov-mobility-model.h (module 'mobility'): ns3::GaussMarkovMobilityModel::GaussMarkovMobilityModel(ns3::GaussMarkovMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::GaussMarkovMobilityModel const &', 'arg0')]) ## gauss-markov-mobility-model.h (module 'mobility'): ns3::GaussMarkovMobilityModel::GaussMarkovMobilityModel() [constructor] cls.add_constructor([]) ## gauss-markov-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::GaussMarkovMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## gauss-markov-mobility-model.h (module 'mobility'): int64_t ns3::GaussMarkovMobilityModel::DoAssignStreams(int64_t arg0) [member function] cls.add_method('DoAssignStreams', 'int64_t', [param('int64_t', 'arg0')], visibility='private', is_virtual=True) ## gauss-markov-mobility-model.h (module 'mobility'): void ns3::GaussMarkovMobilityModel::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## gauss-markov-mobility-model.h (module 'mobility'): ns3::Vector ns3::GaussMarkovMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## gauss-markov-mobility-model.h (module 'mobility'): ns3::Vector ns3::GaussMarkovMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## gauss-markov-mobility-model.h (module 'mobility'): void ns3::GaussMarkovMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], visibility='private', is_virtual=True) return def register_Ns3HierarchicalMobilityModel_methods(root_module, cls): ## hierarchical-mobility-model.h (module 'mobility'): ns3::HierarchicalMobilityModel::HierarchicalMobilityModel(ns3::HierarchicalMobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::HierarchicalMobilityModel const &', 'arg0')]) ## hierarchical-mobility-model.h (module 'mobility'): ns3::HierarchicalMobilityModel::HierarchicalMobilityModel() [constructor] cls.add_constructor([]) ## hierarchical-mobility-model.h (module 'mobility'): ns3::Ptr<ns3::MobilityModel> ns3::HierarchicalMobilityModel::GetChild() const [member function] cls.add_method('GetChild', 'ns3::Ptr< ns3::MobilityModel >', [], is_const=True) ## hierarchical-mobility-model.h (module 'mobility'): ns3::Ptr<ns3::MobilityModel> ns3::HierarchicalMobilityModel::GetParent() const [member function] cls.add_method('GetParent', 'ns3::Ptr< ns3::MobilityModel >', [], is_const=True) ## hierarchical-mobility-model.h (module 'mobility'): static ns3::TypeId ns3::HierarchicalMobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## hierarchical-mobility-model.h (module 'mobility'): void ns3::HierarchicalMobilityModel::SetChild(ns3::Ptr<ns3::MobilityModel> model) [member function] cls.add_method('SetChild', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'model')]) ## hierarchical-mobility-model.h (module 'mobility'): void ns3::HierarchicalMobilityModel::SetParent(ns3::Ptr<ns3::MobilityModel> model) [member function] cls.add_method('SetParent', 'void', [param('ns3::Ptr< ns3::MobilityModel >', 'model')]) ## hierarchical-mobility-model.h (module 'mobility'): ns3::Vector ns3::HierarchicalMobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## hierarchical-mobility-model.h (module 'mobility'): ns3::Vector ns3::HierarchicalMobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_const=True, visibility='private', is_virtual=True) ## hierarchical-mobility-model.h (module 'mobility'): void ns3::HierarchicalMobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], 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 ## box.h (module 'mobility'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeBoxChecker() [free function] module.add_function('MakeBoxChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## rectangle.h (module 'mobility'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeRectangleChecker() [free function] module.add_function('MakeRectangleChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) ## waypoint.h (module 'mobility'): extern ns3::Ptr<ns3::AttributeChecker const> ns3::MakeWaypointChecker() [free function] module.add_function('MakeWaypointChecker', 'ns3::Ptr< ns3::AttributeChecker const >', []) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
gpl-2.0
Azure/azure-sdk-for-python
sdk/servicefabric/azure-mgmt-servicefabric/azure/mgmt/servicefabric/aio/_service_fabric_management_client.py
1
7781
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import ServiceFabricManagementClientConfiguration from .operations import ClustersOperations from .operations import ClusterVersionsOperations from .operations import Operations from .operations import ApplicationOperations from .operations import ApplicationTypesOperations from .operations import ApplicationTypeVersionsOperations from .operations import ApplicationsOperations from .operations import ServicesOperations from .operations import ManagedClustersOperations from .operations import ManagedclusterOperations from .operations import ManagedClusterVersionsOperations from .operations import NodetypeOperations from .operations import NodeTypesOperations from .. import models class ServiceFabricManagementClient(object): """Service Fabric Management Client. :ivar clusters: ClustersOperations operations :vartype clusters: azure.mgmt.servicefabric.aio.operations.ClustersOperations :ivar cluster_versions: ClusterVersionsOperations operations :vartype cluster_versions: azure.mgmt.servicefabric.aio.operations.ClusterVersionsOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.servicefabric.aio.operations.Operations :ivar application: ApplicationOperations operations :vartype application: azure.mgmt.servicefabric.aio.operations.ApplicationOperations :ivar application_types: ApplicationTypesOperations operations :vartype application_types: azure.mgmt.servicefabric.aio.operations.ApplicationTypesOperations :ivar application_type_versions: ApplicationTypeVersionsOperations operations :vartype application_type_versions: azure.mgmt.servicefabric.aio.operations.ApplicationTypeVersionsOperations :ivar applications: ApplicationsOperations operations :vartype applications: azure.mgmt.servicefabric.aio.operations.ApplicationsOperations :ivar services: ServicesOperations operations :vartype services: azure.mgmt.servicefabric.aio.operations.ServicesOperations :ivar managed_clusters: ManagedClustersOperations operations :vartype managed_clusters: azure.mgmt.servicefabric.aio.operations.ManagedClustersOperations :ivar managedcluster: ManagedclusterOperations operations :vartype managedcluster: azure.mgmt.servicefabric.aio.operations.ManagedclusterOperations :ivar managed_cluster_versions: ManagedClusterVersionsOperations operations :vartype managed_cluster_versions: azure.mgmt.servicefabric.aio.operations.ManagedClusterVersionsOperations :ivar nodetype: NodetypeOperations operations :vartype nodetype: azure.mgmt.servicefabric.aio.operations.NodetypeOperations :ivar node_types: NodeTypesOperations operations :vartype node_types: azure.mgmt.servicefabric.aio.operations.NodeTypesOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: The customer subscription identifier. :type subscription_id: str :param str base_url: Service URL :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: Optional[str] = None, **kwargs: Any ) -> None: if not base_url: base_url = 'https://management.azure.com' self._config = ServiceFabricManagementClientConfiguration(credential, subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) self.clusters = ClustersOperations( self._client, self._config, self._serialize, self._deserialize) self.cluster_versions = ClusterVersionsOperations( self._client, self._config, self._serialize, self._deserialize) self.operations = Operations( self._client, self._config, self._serialize, self._deserialize) self.application = ApplicationOperations( self._client, self._config, self._serialize, self._deserialize) self.application_types = ApplicationTypesOperations( self._client, self._config, self._serialize, self._deserialize) self.application_type_versions = ApplicationTypeVersionsOperations( self._client, self._config, self._serialize, self._deserialize) self.applications = ApplicationsOperations( self._client, self._config, self._serialize, self._deserialize) self.services = ServicesOperations( self._client, self._config, self._serialize, self._deserialize) self.managed_clusters = ManagedClustersOperations( self._client, self._config, self._serialize, self._deserialize) self.managedcluster = ManagedclusterOperations( self._client, self._config, self._serialize, self._deserialize) self.managed_cluster_versions = ManagedClusterVersionsOperations( self._client, self._config, self._serialize, self._deserialize) self.nodetype = NodetypeOperations( self._client, self._config, self._serialize, self._deserialize) self.node_types = NodeTypesOperations( self._client, self._config, self._serialize, self._deserialize) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "ServiceFabricManagementClient": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
mit
romain-dartigues/ansible
test/units/modules/network/f5/test_bigip_cli_alias.py
21
3461
# -*- coding: utf-8 -*- # # Copyright: (c) 2018, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2, 7): pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") from ansible.module_utils.basic import AnsibleModule try: from library.modules.bigip_cli_alias import ApiParameters from library.modules.bigip_cli_alias import ModuleParameters from library.modules.bigip_cli_alias import ModuleManager from library.modules.bigip_cli_alias import ArgumentSpec # In Ansible 2.8, Ansible changed import paths. from test.units.compat import unittest from test.units.compat.mock import Mock from test.units.compat.mock import patch from test.units.modules.utils import set_module_args except ImportError: from ansible.modules.network.f5.bigip_cli_alias import ApiParameters from ansible.modules.network.f5.bigip_cli_alias import ModuleParameters from ansible.modules.network.f5.bigip_cli_alias import ModuleManager from ansible.modules.network.f5.bigip_cli_alias import ArgumentSpec # Ansible 2.8 imports from units.compat import unittest from units.compat.mock import Mock from units.compat.mock import patch from units.modules.utils import set_module_args fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} 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( command='run /util bash', description='another description', scope='shared', ) p = ModuleParameters(params=args) assert p.command == 'run /util bash' assert p.description == 'another description' assert p.scope == 'shared' def test_api_parameters(self): args = load_fixture('load_tm_cli_alias_1.json') p = ApiParameters(params=args) assert p.command == 'run /util bash' assert p.description == 'Run the bash shell' class TestManager(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() def test_create_default_device_group(self, *args): set_module_args( dict( name="foo-group", command='run /util bash', description='another description', scope='shared', state="present", server='localhost', user='admin', password='password' ) ) module = AnsibleModule( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode ) mm = ModuleManager(module=module) # Override methods to force specific logic in the module to happen mm.create_on_device = Mock(return_value=True) mm.exists = Mock(return_value=False) results = mm.exec_module() assert results['changed'] is True
gpl-3.0
ocadotechnology/django-nuit
example_project/example_project/wsgi.py
73
1146
""" WSGI config for test_project project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
apache-2.0
scholrly/neo4django
neo4django/validators.py
3
2412
from django.core import exceptions class ArrayValidator(object): def __call__(self, values): sup = super(ArrayValidator, self) if hasattr(sup, '__call__'): sup.__call__(values) if not getattr(values, '__iter__', False): raise exceptions.ValidationError('Enter a non-string sequence.') validate_array = ArrayValidator() def validate_str(value): try: str(value) except: raise exceptions.ValidationError('Enter a valid str.') def validate_basestring(value): if not isinstance(value, basestring): raise exceptions.ValidationError('Enter a valid str.') def validate_int(value): if not isinstance(value, int): raise exceptions.ValidationError('Enter a valid int.') class ElementValidator(object): """Validates a sequence element by element with a list of validators.""" def __init__(self, validators, message='Invalid sequence of elements.', *args, **kwargs): """ Arguments: validators -- a sequence of callable validators Keyword arguments: message -- the error message to raise if the sequence is invalid """ super(ElementValidator, self).__init__(*args, **kwargs) self.validators = validators self.message = message def __call__(self, values): sup = super(ElementValidator, self) if hasattr(sup, '__call__'): sup.__call__(values) try: for value in values: for validator in self.validators: validator(value) except exceptions.ValidationError: raise exceptions.ValidationError(self.message) class IntArrayValidator(ArrayValidator, ElementValidator): def __init__(self, *args, **kwargs): kwargs.setdefault('message', 'Enter a sequence of valid ints.') super(IntArrayValidator, self).__init__([validate_int], *args, **kwargs) class StringArrayValidator(ArrayValidator, ElementValidator): def __init__(self, *args, **kwargs): kwargs.setdefault('message', 'Enter a sequence of valid strs.') super(StringArrayValidator, self).__init__([validate_basestring], *args, **kwargs) validate_str_array = StringArrayValidator() validate_int_array = IntArrayValidator()
gpl-3.0
40223247/2015cd_midterm-master
static/Brython3.1.1-20150328-091302/Lib/unittest/test/_test_warnings.py
858
2304
# helper module for test_runner.Test_TextTestRunner.test_warnings """ This module has a number of tests that raise different kinds of warnings. When the tests are run, the warnings are caught and their messages are printed to stdout. This module also accepts an arg that is then passed to unittest.main to affect the behavior of warnings. Test_TextTestRunner.test_warnings executes this script with different combinations of warnings args and -W flags and check that the output is correct. See #10535. """ import sys import unittest import warnings def warnfun(): warnings.warn('rw', RuntimeWarning) class TestWarnings(unittest.TestCase): # unittest warnings will be printed at most once per type (max one message # for the fail* methods, and one for the assert* methods) def test_assert(self): self.assertEquals(2+2, 4) self.assertEquals(2*2, 4) self.assertEquals(2**2, 4) def test_fail(self): self.failUnless(1) self.failUnless(True) def test_other_unittest(self): self.assertAlmostEqual(2+2, 4) self.assertNotAlmostEqual(4+4, 2) # these warnings are normally silenced, but they are printed in unittest def test_deprecation(self): warnings.warn('dw', DeprecationWarning) warnings.warn('dw', DeprecationWarning) warnings.warn('dw', DeprecationWarning) def test_import(self): warnings.warn('iw', ImportWarning) warnings.warn('iw', ImportWarning) warnings.warn('iw', ImportWarning) # user warnings should always be printed def test_warning(self): warnings.warn('uw') warnings.warn('uw') warnings.warn('uw') # these warnings come from the same place; they will be printed # only once by default or three times if the 'always' filter is used def test_function(self): warnfun() warnfun() warnfun() if __name__ == '__main__': with warnings.catch_warnings(record=True) as ws: # if an arg is provided pass it to unittest.main as 'warnings' if len(sys.argv) == 2: unittest.main(exit=False, warnings=sys.argv.pop()) else: unittest.main(exit=False) # print all the warning messages collected for w in ws: print(w.message)
agpl-3.0
les69/calvin-base
calvin/calvinsys/web/tests/facebook_test.py
1
1905
import pytest import json from calvin.calvinsys.web.facebook import Facebook, FacebookUser from facebook import GraphAPIError """ Configuration file for automated testing. Change with your credentials file FACEBOOK_CREDENTIALS = $PATHTO/yourcredentials.json The file has to be structured like the following { "access_token": "<user access token>", } """ FACEBOOK_CREDENTIALS = '/home/emirkomo/projects/internship/calvin-base/calvin/calvinsys/web/tests/credentials.json' def test_correct_credentials(): js_content = open(FACEBOOK_CREDENTIALS).read() credentials = json.loads(js_content) fb = Facebook("lol","lol") assert fb.set_credentials(credentials) is True def test_wrong_credentials(): credentials = {'access_token' : 'nonevalue'} fb = Facebook("lol","lol") assert fb.set_credentials(credentials) is False @pytest.mark.slow def test_correct_post_wall(): credentials = json.loads(open(FACEBOOK_CREDENTIALS).read()) fb = FacebookUser(credentials) msg = {'attachment': {'caption': 'caption', 'description': 'description', 'link': '', 'name': 'hi', 'picture': ''}, 'message': 'message_thisshouldwork'} assert fb.fb_user.put_wall_post(msg['message'], msg['attachment']) is not None @pytest.mark.slow def test_wrong_post_wall(): credentials = {'access_token' : 'nonevalue'} fb = FacebookUser(credentials) msg = {'attachment': {'caption': 'caption', 'description': 'description', 'link': '', 'name': 'hi', 'picture': ''}, 'message': 'message_thisshouldwork'} with pytest.raises(GraphAPIError): fb.fb_user.put_wall_post(msg['message'], msg['attachment'])
apache-2.0
IntegerMan/Pi-MFD
PiMFD/Applications/Navigation/Tags/LeisureTagHandling.py
1
8389
# coding=utf-8 """ Handles the "leisure" tag """ from PiMFD.Applications.Navigation.Tags.TagHandling import TagHandler __author__ = 'Matt Eland' class LeisureTagHandler(TagHandler): def get_color(self, entity, value, cs): """ :type cs: PiMFD.UI.ColorScheme.ColorScheme """ if value in ('pitch', 'park', 'golf_course', 'sports_centre', 'adult_gaming_centr', 'amusement_arcade', 'beach_resort', 'bandstand', 'dog_park', 'dance', 'hackerspace', 'ice_rink', 'sports_centre', 'stadium', 'summer_camp'): return cs.map_recreation elif value in ('playground', 'track', 'bird_hide', 'firepit', 'fishing', 'wildlife_hide'): return cs.map_pedestrian elif value in ('garden', 'golf_course', 'miniature_golf', 'nature_reserve'): return cs.map_vegetation elif value in ('swimming_pool', 'marina', 'water_park'): return cs.map_water elif value == 'slipway': return cs.map_structural return super(LeisureTagHandler, self).get_color(entity, value, cs) def get_description_text(self, entity, value): if value == 'adult_gaming_centre': return 'Arcade (Adults Only)' elif value == 'amusement_arcade': return 'Arcade' elif value == 'beach_resort': return 'Beach Resort' elif value == 'bandstand': return 'Bandstand' elif value == 'bird_hide': return 'Bird Hide' elif value == 'dance': return 'Dance' elif value == 'dog_park': return 'Dog Park' elif value == 'firepit': return 'Fire Pit' elif value == 'fishing': return 'Fishing' elif value == 'garden': return 'Garden' elif value == 'golf_course': return 'Golf Course' elif value == 'hackerspace': return 'Hackerspace' elif value == 'ice_rink': return 'Ice Rink' elif value == 'marina': return 'Marina' elif value == 'miniature_golf': return 'Mini-Golf Course' elif value == 'nature_reserve': return 'Nature Reserve' elif value == 'park': return 'Park' elif value == 'pitch': sport = entity.get_tag_value('sport') if sport: sports = {'9pin': 'Bowling Alley (9 Pin)', '10pin': 'Bowling Alley', 'american_football': 'Football Field', 'aikido': 'Aikido Dojo', 'archery': 'Archery Range', 'athletics': 'Athletics Track', 'australian_football': 'Football Field (Aussie Rules)', 'base': 'Base Jumping Area', 'badminton': 'Badminton Court', 'bandy': 'Bandy Rink', 'baseball': 'Baseball Field', 'basketball': 'Orb Dribbling (Basketball Court)', 'beachvolleyball': 'Volleyball Court (Beach)', 'billiards': 'Billiards Parlor', 'bmx': 'BMX Course', 'bobsleigh': 'Bobsleigh Course', 'boules': 'Ball Gaming Course', 'bowls': 'Bowling Area', 'boxing': 'Boxing Match', 'canadian_football': 'Football Field (Canadian)', 'canoe': 'Canoe Course', 'chess': 'Chess', 'cliff_diving': 'Cliff Diving Area', 'climbing': 'Climbing Area', 'climbing_adventure': 'Adventure Climbing', 'cockfighting': 'Rooster Fighting', 'cricket': 'Cricket Pitch', 'croquet': 'Croquet Court', 'curling': 'Curling Rink', 'cycling': 'Biking Course', 'darts': 'Darts', 'diving': 'Diving Area', 'dog_racing': 'Dog Racing', 'equestrian': 'Horse Sports', 'fencing': 'Fencing Match', 'field_hockey': 'Field Hockey', 'football': 'Football', 'free_flying': 'Hangliding / Parasailing', 'gaelic_games': 'Gaelic Games Area', 'golf': 'Golf Course', 'gymnastics': 'Gymnastics', 'handball': 'Handball Court', 'hapkido': 'Hapkido Dojo', 'hockey': 'Hockey Rink', 'horseshoes': 'Horseshoes Court', 'horse_racing': 'Horse Racing', 'ice_hockey': 'Ice Hockey Rink', 'ice_skating': 'Ice Skating Rink', 'ice_stock': 'Bavarian Curling', 'judo': 'Judo Dojo', 'karting': 'Kart Racing', 'kitesurfing': 'Kite Surfing', 'korfball': 'Korfball Court', 'model_aerodrome': 'Radio Controlled Airfield', 'motocross': 'Motocross Racing', 'motor': 'Motorsport Course', 'multi': 'Multi-Sport Area', 'obstacle_course': 'Obstacle Course', 'orienteering': 'Orienteering Course', 'paddle_tennis': 'Paddle Tennis Court', 'paragliding': 'Paragliding Site', 'pelota': 'Ball Games Court', 'racquet': 'Raquetball Court', 'rc_car': 'RC Car Course', 'roller_skating': 'Roller Skating Rink', 'rowing': 'Rowing Course', 'rugby_league': 'Rugby League', 'rugby_union': 'Rugby Union', 'running': 'Running Track', 'safety_training': 'Safety Training', 'sailing': 'Sailing', 'scuba_diving': 'Scuba Diving', 'shooting': 'Shooting Range', 'skating': 'Skating Rink', 'skateboard': 'Skateboard Park', 'skiing': 'Ski Slope', 'soccer': 'Soccer Field', 'surfing': 'Surfing Area', 'swimming': 'Swimming Area', 'table_tennis': 'Ping Pong', 'table_soccer': 'Foosball', 'taekwondo': 'Taekwondo Dojo', 'team_handball': 'Handball Court', 'tennis': 'Tennis Court', 'toboggan': 'Toboggan Run', 'volleyball': 'Volleyball Court', 'water_polo': 'Water Polo', 'water_ski': 'Water Ski', 'weightlifting': 'Weightlifting Area', 'wrestling': 'Wrestling Area' } if value in sports: return sports[value] return 'Sports Area' elif value == 'playground': return 'Playground' elif value == 'slipway': return 'Boat Launch' elif value == 'sports_centre': return 'Sports Center' elif value == 'stadium': return 'Stadium' elif value == 'summer_camp': return 'Summer Camp' elif value == 'swimming_pool': return 'Swimming Pool' elif value == 'track': return 'Track' elif value == 'water_park': return 'Water Park' elif value == 'wildlife_hide': return 'Wildlife Hide' return super(LeisureTagHandler, self).get_description_text(entity, value)
gpl-2.0
CTSRD-SOAAP/chromium-42.0.2311.135
tools/perf/measurements/smoothness_unittest.py
3
7690
# Copyright 2013 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 sys from measurements import smoothness from metrics import power from telemetry import decorators from telemetry.core import exceptions from telemetry.core import wpr_modes from telemetry.page import page from telemetry.unittest_util import options_for_unittests from telemetry.unittest_util import page_test_test_case class FakeTracingController(object): def __init__(self): self.category_filter = None def Start(self, _options, category_filter, _timeout): self.category_filter = category_filter class FakePlatform(object): def __init__(self): self.tracing_controller = FakeTracingController() def CanMonitorPower(self): return False class FakeBrowser(object): def __init__(self): self.platform = FakePlatform() class AnimatedPage(page.Page): def __init__(self, page_set): super(AnimatedPage, self).__init__( url='file://animated_page.html', page_set=page_set, base_dir=page_set.base_dir) def RunPageInteractions(self, action_runner): action_runner.Wait(.2) class FakeTab(object): def __init__(self): self.browser = FakeBrowser() def ExecuteJavaScript(self, js): pass class SmoothnessUnitTest(page_test_test_case.PageTestTestCase): """Smoke test for smoothness measurement Runs smoothness measurement on a simple page and verifies that all metrics were added to the results. The test is purely functional, i.e. it only checks if the metrics are present and non-zero. """ def testSyntheticDelayConfiguration(self): test_page = page.Page('http://dummy', None) test_page.synthetic_delays = { 'cc.BeginMainFrame': { 'target_duration': 0.012 }, 'cc.DrawAndSwap': { 'target_duration': 0.012, 'mode': 'alternating' }, 'gpu.PresentingFrame': { 'target_duration': 0.012 } } tab = FakeTab() measurement = smoothness.Smoothness() measurement.WillStartBrowser(tab.browser.platform) measurement.WillNavigateToPage(test_page, tab) measurement.WillRunActions(test_page, tab) expected_category_filter = set([ 'DELAY(cc.BeginMainFrame;0.012000;static)', 'DELAY(cc.DrawAndSwap;0.012000;alternating)', 'DELAY(gpu.PresentingFrame;0.012000;static)', 'benchmark' ]) tracing_controller = tab.browser.platform.tracing_controller actual_category_filter = ( tracing_controller.category_filter.included_categories) # FIXME: Put blink.console into the expected above and remove these two # remove entries when the blink.console change has rolled into chromium. actual_category_filter.remove('webkit.console') actual_category_filter.remove('blink.console') if expected_category_filter != actual_category_filter: sys.stderr.write("Expected category filter: %s\n" % repr(expected_category_filter)) sys.stderr.write("Actual category filter filter: %s\n" % repr(actual_category_filter)) self.assertEquals(expected_category_filter, actual_category_filter) def setUp(self): self._options = options_for_unittests.GetCopy() self._options.browser_options.wpr_mode = wpr_modes.WPR_OFF def testSmoothness(self): ps = self.CreatePageSetFromFileInUnittestDataDir('scrollable_page.html') measurement = smoothness.Smoothness() results = self.RunMeasurement(measurement, ps, options=self._options) self.assertEquals(0, len(results.failures)) frame_times = results.FindAllPageSpecificValuesNamed('frame_times') self.assertEquals(len(frame_times), 1) self.assertGreater(frame_times[0].GetRepresentativeNumber(), 0) mean_frame_time = results.FindAllPageSpecificValuesNamed('mean_frame_time') self.assertEquals(len(mean_frame_time), 1) self.assertGreater(mean_frame_time[0].GetRepresentativeNumber(), 0) frame_time_discrepancy = results.FindAllPageSpecificValuesNamed( 'frame_time_discrepancy') self.assertEquals(len(frame_time_discrepancy), 1) self.assertGreater(frame_time_discrepancy[0].GetRepresentativeNumber(), 0) percentage_smooth = results.FindAllPageSpecificValuesNamed( 'percentage_smooth') self.assertEquals(len(percentage_smooth), 1) self.assertGreaterEqual(percentage_smooth[0].GetRepresentativeNumber(), 0) mean_input_event_latency = results.FindAllPageSpecificValuesNamed( 'mean_input_event_latency') if mean_input_event_latency: self.assertEquals(len(mean_input_event_latency), 1) self.assertGreater( mean_input_event_latency[0].GetRepresentativeNumber(), 0) @decorators.Enabled('android') # SurfaceFlinger is android-only def testSmoothnessSurfaceFlingerMetricsCalculated(self): ps = self.CreatePageSetFromFileInUnittestDataDir('scrollable_page.html') measurement = smoothness.Smoothness() results = self.RunMeasurement(measurement, ps, options=self._options) self.assertEquals(0, len(results.failures)) avg_surface_fps = results.FindAllPageSpecificValuesNamed('avg_surface_fps') self.assertEquals(1, len(avg_surface_fps)) self.assertGreater(avg_surface_fps[0].GetRepresentativeNumber, 0) jank_count = results.FindAllPageSpecificValuesNamed('jank_count') self.assertEquals(1, len(jank_count)) self.assertGreater(jank_count[0].GetRepresentativeNumber(), -1) max_frame_delay = results.FindAllPageSpecificValuesNamed('max_frame_delay') self.assertEquals(1, len(max_frame_delay)) self.assertGreater(max_frame_delay[0].GetRepresentativeNumber, 0) frame_lengths = results.FindAllPageSpecificValuesNamed('frame_lengths') self.assertEquals(1, len(frame_lengths)) self.assertGreater(frame_lengths[0].GetRepresentativeNumber, 0) @decorators.Disabled('mac', 'chromeos') # http://crbug.com/403903 def testSmoothnessForPageWithNoGesture(self): ps = self.CreateEmptyPageSet() ps.AddUserStory(AnimatedPage(ps)) measurement = smoothness.Smoothness() results = self.RunMeasurement(measurement, ps, options=self._options) self.assertEquals(0, len(results.failures)) percentage_smooth = results.FindAllPageSpecificValuesNamed( 'percentage_smooth') self.assertEquals(len(percentage_smooth), 1) self.assertGreaterEqual(percentage_smooth[0].GetRepresentativeNumber(), 0) def testCleanUpTrace(self): self.TestTracingCleanedUp(smoothness.Smoothness, self._options) def testCleanUpPowerMetric(self): class FailPage(page.Page): def __init__(self, page_set): # pylint: disable=bad-super-call super(FailPage, self).__init__( url='file://blank.html', page_set=page_set, base_dir=page_set.base_dir) def RunPageInteractions(self, _): raise exceptions.IntentionalException class FakePowerMetric(power.PowerMetric): start_called = False stop_called = True def Start(self, _1, _2): self.start_called = True def Stop(self, _1, _2): self.stop_called = True ps = self.CreateEmptyPageSet() ps.AddUserStory(FailPage(ps)) class BuggyMeasurement(smoothness.Smoothness): fake_power = None # Inject fake power metric. def WillStartBrowser(self, platform): self.fake_power = self._power_metric = FakePowerMetric(platform) measurement = BuggyMeasurement() try: self.RunMeasurement(measurement, ps) except exceptions.IntentionalException: pass self.assertTrue(measurement.fake_power.start_called) self.assertTrue(measurement.fake_power.stop_called)
bsd-3-clause
krieger-od/nwjs_chromium_webrtc
build/version.py
50
1895
#!/usr/bin/env python # Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. """Get svn revision of working copy This script tries to get the svn revision as much as it can. It supports both git-svn and svn. It will fail if not in a git-svn or svn repository; in this case the script will return "n/a". This script is a simplified version of lastchange.py which is in Chromium's src/build/util folder. """ import os import subprocess import sys def popen_cmd_and_get_output(cmd, directory): """Return (status, output) of executing cmd in a shell.""" try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=directory, shell=(sys.platform=='win32')) except OSError: # command is apparently either not installed or not executable. return None if not proc: return None for line in proc.stdout: line = line.strip() if not line: continue words = line.split() for index, word in enumerate(words): if word == "Revision:": return words[index+1] # return None if cannot find keyword Revision return None def main(): directory = os.path.dirname(sys.argv[0]); version = popen_cmd_and_get_output(['git', 'svn', 'info'], directory) if version == None: version = popen_cmd_and_get_output(['svn', 'info'], directory) if version == None: print "n/a" return 0 print version return 0 if __name__ == '__main__': sys.exit(main())
bsd-3-clause
steebchen/youtube-dl
youtube_dl/extractor/pornhd.py
16
3635
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, int_or_none, js_to_json, ) class PornHdIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?pornhd\.com/(?:[a-z]{2,4}/)?videos/(?P<id>\d+)(?:/(?P<display_id>.+))?' _TESTS = [{ 'url': 'http://www.pornhd.com/videos/9864/selfie-restroom-masturbation-fun-with-chubby-cutie-hd-porn-video', 'md5': 'c8b964b1f0a4b5f7f28ae3a5c9f86ad5', 'info_dict': { 'id': '9864', 'display_id': 'selfie-restroom-masturbation-fun-with-chubby-cutie-hd-porn-video', 'ext': 'mp4', 'title': 'Restroom selfie masturbation', 'description': 'md5:3748420395e03e31ac96857a8f125b2b', 'thumbnail': r're:^https?://.*\.jpg', 'view_count': int, 'age_limit': 18, } }, { # removed video 'url': 'http://www.pornhd.com/videos/1962/sierra-day-gets-his-cum-all-over-herself-hd-porn-video', 'md5': '956b8ca569f7f4d8ec563e2c41598441', 'info_dict': { 'id': '1962', 'display_id': 'sierra-day-gets-his-cum-all-over-herself-hd-porn-video', 'ext': 'mp4', 'title': 'Sierra loves doing laundry', 'description': 'md5:8ff0523848ac2b8f9b065ba781ccf294', 'thumbnail': r're:^https?://.*\.jpg', 'view_count': int, 'age_limit': 18, }, 'skip': 'Not available anymore', }] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('display_id') webpage = self._download_webpage(url, display_id or video_id) title = self._html_search_regex( [r'<span[^>]+class=["\']video-name["\'][^>]*>([^<]+)', r'<title>(.+?) - .*?[Pp]ornHD.*?</title>'], webpage, 'title') sources = self._parse_json(js_to_json(self._search_regex( r"(?s)sources'?\s*[:=]\s*(\{.+?\})", webpage, 'sources', default='{}')), video_id) if not sources: message = self._html_search_regex( r'(?s)<(div|p)[^>]+class="no-video"[^>]*>(?P<value>.+?)</\1', webpage, 'error message', group='value') raise ExtractorError('%s said: %s' % (self.IE_NAME, message), expected=True) formats = [] for format_id, video_url in sources.items(): if not video_url: continue height = int_or_none(self._search_regex( r'^(\d+)[pP]', format_id, 'height', default=None)) formats.append({ 'url': video_url, 'format_id': format_id, 'height': height, }) self._sort_formats(formats) description = self._html_search_regex( r'<(div|p)[^>]+class="description"[^>]*>(?P<value>[^<]+)</\1', webpage, 'description', fatal=False, group='value') view_count = int_or_none(self._html_search_regex( r'(\d+) views\s*<', webpage, 'view count', fatal=False)) thumbnail = self._search_regex( r"poster'?\s*:\s*([\"'])(?P<url>(?:(?!\1).)+)\1", webpage, 'thumbnail', fatal=False, group='url') return { 'id': video_id, 'display_id': display_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'view_count': view_count, 'formats': formats, 'age_limit': 18, }
unlicense
HyperBaton/ansible
lib/ansible/modules/cloud/amazon/aws_batch_job_queue.py
11
10636
#!/usr/bin/python # Copyright (c) 2017 Jon Meran <jonathan.meran@sonos.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: aws_batch_job_queue short_description: Manage AWS Batch Job Queues description: - This module allows the management of AWS Batch Job Queues. It is idempotent and supports "Check" mode. Use module M(aws_batch_compute_environment) to manage the compute environment, M(aws_batch_job_queue) to manage job queues, M(aws_batch_job_definition) to manage job definitions. version_added: "2.5" author: Jon Meran (@jonmer85) options: job_queue_name: description: - The name for the job queue required: true type: str state: description: - Describes the desired state. default: "present" choices: ["present", "absent"] type: str job_queue_state: description: - The state of the job queue. If the job queue state is ENABLED , it is able to accept jobs. default: "ENABLED" choices: ["ENABLED", "DISABLED"] type: str priority: description: - The priority of the job queue. Job queues with a higher priority (or a lower integer value for the priority parameter) are evaluated first when associated with same compute environment. Priority is determined in ascending order, for example, a job queue with a priority value of 1 is given scheduling preference over a job queue with a priority value of 10. required: true type: int compute_environment_order: description: - The set of compute environments mapped to a job queue and their order relative to each other. The job scheduler uses this parameter to determine which compute environment should execute a given job. Compute environments must be in the VALID state before you can associate them with a job queue. You can associate up to 3 compute environments with a job queue. required: true type: list elements: dict suboptions: order: type: int description: The relative priority of the environment. compute_environment: type: str description: The name of the compute environment. requirements: - boto3 extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' --- - hosts: localhost gather_facts: no vars: state: present tasks: - name: My Batch Job Queue aws_batch_job_queue: job_queue_name: jobQueueName state: present region: us-east-1 job_queue_state: ENABLED priority: 1 compute_environment_order: - order: 1 compute_environment: my_compute_env1 - order: 2 compute_environment: my_compute_env2 register: batch_job_queue_action - name: show results debug: var: batch_job_queue_action ''' RETURN = ''' --- output: description: "returns what action was taken, whether something was changed, invocation and response" returned: always sample: batch_job_queue_action: updated changed: false response: job_queue_arn: "arn:aws:batch:...." job_queue_name: <name> priority: 1 state: DISABLED status: UPDATING status_reason: "JobQueue Healthy" type: dict ''' from ansible.module_utils._text import to_native from ansible.module_utils.aws.batch import AWSConnection, cc, set_api_params from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import ec2_argument_spec, get_aws_connection_info, boto3_conn, HAS_BOTO3 from ansible.module_utils.ec2 import camel_dict_to_snake_dict import re import traceback try: from botocore.exceptions import ClientError, ParamValidationError, MissingParametersError except ImportError: pass # Handled by HAS_BOTO3 # --------------------------------------------------------------------------------------------------- # # Helper Functions & classes # # --------------------------------------------------------------------------------------------------- def validate_params(module, aws): """ Performs basic parameter validation. :param module: :param aws: :return: """ return # --------------------------------------------------------------------------------------------------- # # Batch Job Queue functions # # --------------------------------------------------------------------------------------------------- def get_current_job_queue(module, connection): try: environments = connection.client().describe_job_queues( jobQueues=[module.params['job_queue_name']] ) return environments['jobQueues'][0] if len(environments['jobQueues']) > 0 else None except ClientError: return None def create_job_queue(module, aws): """ Adds a Batch job queue :param module: :param aws: :return: """ client = aws.client('batch') changed = False # set API parameters params = ('job_queue_name', 'priority') api_params = set_api_params(module, params) if module.params['job_queue_state'] is not None: api_params['state'] = module.params['job_queue_state'] api_params['computeEnvironmentOrder'] = get_compute_environment_order_list(module) try: if not module.check_mode: client.create_job_queue(**api_params) changed = True except (ClientError, ParamValidationError, MissingParametersError) as e: module.fail_json(msg='Error creating compute environment: {0}'.format(to_native(e)), exception=traceback.format_exc()) return changed def get_compute_environment_order_list(module): compute_environment_order_list = [] for ceo in module.params['compute_environment_order']: compute_environment_order_list.append(dict(order=ceo['order'], computeEnvironment=ceo['compute_environment'])) return compute_environment_order_list def remove_job_queue(module, aws): """ Remove a Batch job queue :param module: :param aws: :return: """ client = aws.client('batch') changed = False # set API parameters api_params = {'jobQueue': module.params['job_queue_name']} try: if not module.check_mode: client.delete_job_queue(**api_params) changed = True except (ClientError, ParamValidationError, MissingParametersError) as e: module.fail_json(msg='Error removing job queue: {0}'.format(to_native(e)), exception=traceback.format_exc()) return changed def manage_state(module, aws): changed = False current_state = 'absent' state = module.params['state'] job_queue_state = module.params['job_queue_state'] job_queue_name = module.params['job_queue_name'] priority = module.params['priority'] action_taken = 'none' response = None check_mode = module.check_mode # check if the job queue exists current_job_queue = get_current_job_queue(module, aws) if current_job_queue: current_state = 'present' if state == 'present': if current_state == 'present': updates = False # Update Batch Job Queue configuration job_kwargs = {'jobQueue': job_queue_name} # Update configuration if needed if job_queue_state and current_job_queue['state'] != job_queue_state: job_kwargs.update({'state': job_queue_state}) updates = True if priority is not None and current_job_queue['priority'] != priority: job_kwargs.update({'priority': priority}) updates = True new_compute_environment_order_list = get_compute_environment_order_list(module) if new_compute_environment_order_list != current_job_queue['computeEnvironmentOrder']: job_kwargs['computeEnvironmentOrder'] = new_compute_environment_order_list updates = True if updates: try: if not check_mode: aws.client().update_job_queue(**job_kwargs) changed = True action_taken = "updated" except (ParamValidationError, ClientError) as e: module.fail_json(msg="Unable to update job queue: {0}".format(to_native(e)), exception=traceback.format_exc()) else: # Create Job Queue changed = create_job_queue(module, aws) action_taken = 'added' # Describe job queue response = get_current_job_queue(module, aws) if not response: module.fail_json(msg='Unable to get job queue information after creating/updating') else: if current_state == 'present': # remove the Job Queue changed = remove_job_queue(module, aws) action_taken = 'deleted' return dict(changed=changed, batch_job_queue_action=action_taken, response=response) # --------------------------------------------------------------------------------------------------- # # MAIN # # --------------------------------------------------------------------------------------------------- def main(): """ Main entry point. :return dict: changed, batch_job_queue_action, response """ argument_spec = ec2_argument_spec() argument_spec.update( dict( state=dict(required=False, default='present', choices=['present', 'absent']), job_queue_name=dict(required=True), job_queue_state=dict(required=False, default='ENABLED', choices=['ENABLED', 'DISABLED']), priority=dict(type='int', required=True), compute_environment_order=dict(type='list', required=True), region=dict(aliases=['aws_region', 'ec2_region']) ) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) # validate dependencies if not HAS_BOTO3: module.fail_json(msg='boto3 is required for this module.') aws = AWSConnection(module, ['batch']) validate_params(module, aws) results = manage_state(module, aws) module.exit_json(**camel_dict_to_snake_dict(results)) if __name__ == '__main__': main()
gpl-3.0
jld23/saspy
saspy/tests/test_sasmagic.py
2
2323
import unittest from unittest.mock import patch, MagicMock, PropertyMock from saspy.sas_magic import SASMagic from saspy import SASsession class TestSASMagic(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): pass def tearDown(self): pass def test_sas_magic_existing_session(self): # mocked with existing session (mva) # shape: {shell: {user_ns: []}, mva: {submit: func()}} mock = MagicMock() mva = MagicMock() shell = MagicMock() submit = MagicMock(return_value=dict(LOG='log', LST='list')) type(mva).submit = PropertyMock(return_value=submit) type(mock).mva = PropertyMock(return_value=mva) type(shell).user_ns = PropertyMock(return_value=[]) type(mock).shell = PropertyMock(return_value=shell) test_cell = 'proc print data=work.test; run;' SASMagic.SAS(mock, '', test_cell) self.assertEqual(submit.call_count, 1, msg=u'sas code was not submitted') submit.assert_called_with(test_cell) def test_sas_magic_supplied_session(self): # mocked with session option existing in namespace # shape: {shell: {user_ns: [existing_session]}, mva: None} mock = MagicMock() shell = MagicMock() mva = MagicMock(spec=SASsession) submit = MagicMock(return_value=dict(LOG='log', LST='list')) type(mva).submit = PropertyMock(return_value=submit) # existing_session (mva) is in user namespace user_ns = dict(existing_session=mva) type(shell).user_ns = PropertyMock(return_value=user_ns) type(mock).shell = PropertyMock(return_value=shell) # no preset mva type(mock).mva = PropertyMock(return_value=None) test_cell = 'proc datasets; run;' SASMagic.SAS(mock, 'existing_session', test_cell) self.assertEqual(submit.called, True, msg=u'sas code was not submitted') submit.assert_any_call(test_cell) # now test with non-existing session; expect error submit.reset_mock() output = SASMagic.SAS(mock, 'bad_session', test_cell) self.assertEqual(submit.called, False) self.assertIn('Invalid SAS Session', output)
apache-2.0
maohongyuan/kbengine
kbe/res/scripts/common/Lib/threading.py
61
48900
"""Thread module emulating a subset of Java's threading model.""" import sys as _sys import _thread try: from time import monotonic as _time except ImportError: from time import time as _time from traceback import format_exc as _format_exc from _weakrefset import WeakSet from itertools import islice as _islice try: from _collections import deque as _deque except ImportError: from collections import deque as _deque # Note regarding PEP 8 compliant names # This threading model was originally inspired by Java, and inherited # the convention of camelCase function and method names from that # language. Those original names are not in any imminent danger of # being deprecated (even for Py3k),so this module provides them as an # alias for the PEP 8 compliant names # Note that using the new PEP 8 compliant names facilitates substitution # with the multiprocessing module, which doesn't provide the old # Java inspired names. __all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier', 'Timer', 'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size'] # Rename some stuff so "from threading import *" is safe _start_new_thread = _thread.start_new_thread _allocate_lock = _thread.allocate_lock _set_sentinel = _thread._set_sentinel get_ident = _thread.get_ident ThreadError = _thread.error try: _CRLock = _thread.RLock except AttributeError: _CRLock = None TIMEOUT_MAX = _thread.TIMEOUT_MAX del _thread # Support for profile and trace hooks _profile_hook = None _trace_hook = None def setprofile(func): """Set a profile function for all threads started from the threading module. The func will be passed to sys.setprofile() for each thread, before its run() method is called. """ global _profile_hook _profile_hook = func def settrace(func): """Set a trace function for all threads started from the threading module. The func will be passed to sys.settrace() for each thread, before its run() method is called. """ global _trace_hook _trace_hook = func # Synchronization classes Lock = _allocate_lock def RLock(*args, **kwargs): """Factory function that returns a new reentrant lock. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. """ if _CRLock is None: return _PyRLock(*args, **kwargs) return _CRLock(*args, **kwargs) class _RLock: """This class implements reentrant lock objects. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. """ def __init__(self): self._block = _allocate_lock() self._owner = None self._count = 0 def __repr__(self): owner = self._owner try: owner = _active[owner].name except KeyError: pass return "<%s owner=%r count=%d>" % ( self.__class__.__name__, owner, self._count) def acquire(self, blocking=True, timeout=-1): """Acquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case. When invoked with the blocking argument set to true, do the same thing as when called without arguments, and return true. When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true. When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return true if the lock has been acquired, false if the timeout has elapsed. """ me = get_ident() if self._owner == me: self._count += 1 return 1 rc = self._block.acquire(blocking, timeout) if rc: self._owner = me self._count = 1 return rc __enter__ = acquire def release(self): """Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value. """ if self._owner != get_ident(): raise RuntimeError("cannot release un-acquired lock") self._count = count = self._count - 1 if not count: self._owner = None self._block.release() def __exit__(self, t, v, tb): self.release() # Internal methods used by condition variables def _acquire_restore(self, state): self._block.acquire() self._count, self._owner = state def _release_save(self): if self._count == 0: raise RuntimeError("cannot release un-acquired lock") count = self._count self._count = 0 owner = self._owner self._owner = None self._block.release() return (count, owner) def _is_owned(self): return self._owner == get_ident() _PyRLock = _RLock class Condition: """Class that implements a condition variable. A condition variable allows one or more threads to wait until they are notified by another thread. If the lock argument is given and not None, it must be a Lock or RLock object, and it is used as the underlying lock. Otherwise, a new RLock object is created and used as the underlying lock. """ def __init__(self, lock=None): if lock is None: lock = RLock() self._lock = lock # Export the lock's acquire() and release() methods self.acquire = lock.acquire self.release = lock.release # If the lock defines _release_save() and/or _acquire_restore(), # these override the default implementations (which just call # release() and acquire() on the lock). Ditto for _is_owned(). try: self._release_save = lock._release_save except AttributeError: pass try: self._acquire_restore = lock._acquire_restore except AttributeError: pass try: self._is_owned = lock._is_owned except AttributeError: pass self._waiters = _deque() def __enter__(self): return self._lock.__enter__() def __exit__(self, *args): return self._lock.__exit__(*args) def __repr__(self): return "<Condition(%s, %d)>" % (self._lock, len(self._waiters)) def _release_save(self): self._lock.release() # No state to save def _acquire_restore(self, x): self._lock.acquire() # Ignore saved state def _is_owned(self): # Return True if lock is owned by current_thread. # This method is called only if __lock doesn't have _is_owned(). if self._lock.acquire(0): self._lock.release() return False else: return True def wait(self, timeout=None): """Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call for the same condition variable in another thread, or until the optional timeout occurs. Once awakened or timed out, it re-acquires the lock and returns. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). When the underlying lock is an RLock, it is not released using its release() method, since this may not actually unlock the lock when it was acquired multiple times recursively. Instead, an internal interface of the RLock class is used, which really unlocks it even when it has been recursively acquired several times. Another internal interface is then used to restore the recursion level when the lock is reacquired. """ if not self._is_owned(): raise RuntimeError("cannot wait on un-acquired lock") waiter = _allocate_lock() waiter.acquire() self._waiters.append(waiter) saved_state = self._release_save() gotit = False try: # restore state no matter what (e.g., KeyboardInterrupt) if timeout is None: waiter.acquire() gotit = True else: if timeout > 0: gotit = waiter.acquire(True, timeout) else: gotit = waiter.acquire(False) return gotit finally: self._acquire_restore(saved_state) if not gotit: try: self._waiters.remove(waiter) except ValueError: pass def wait_for(self, predicate, timeout=None): """Wait until a condition evaluates to True. predicate should be a callable which result will be interpreted as a boolean value. A timeout may be provided giving the maximum time to wait. """ endtime = None waittime = timeout result = predicate() while not result: if waittime is not None: if endtime is None: endtime = _time() + waittime else: waittime = endtime - _time() if waittime <= 0: break self.wait(waittime) result = predicate() return result def notify(self, n=1): """Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting. """ if not self._is_owned(): raise RuntimeError("cannot notify on un-acquired lock") all_waiters = self._waiters waiters_to_notify = _deque(_islice(all_waiters, n)) if not waiters_to_notify: return for waiter in waiters_to_notify: waiter.release() try: all_waiters.remove(waiter) except ValueError: pass def notify_all(self): """Wake up all threads waiting on this condition. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. """ self.notify(len(self._waiters)) notifyAll = notify_all class Semaphore: """This class implements semaphore objects. Semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. """ # After Tim Peters' semaphore class, but not quite the same (no maximum) def __init__(self, value=1): if value < 0: raise ValueError("semaphore initial value must be >= 0") self._cond = Condition(Lock()) self._value = value def acquire(self, blocking=True, timeout=None): """Acquire a semaphore, decrementing the internal counter by one. When invoked without arguments: if the internal counter is larger than zero on entry, decrement it by one and return immediately. If it is zero on entry, block, waiting until some other thread has called release() to make it larger than zero. This is done with proper interlocking so that if multiple acquire() calls are blocked, release() will wake exactly one of them up. The implementation may pick one at random, so the order in which blocked threads are awakened should not be relied on. There is no return value in this case. When invoked with blocking set to true, do the same thing as when called without arguments, and return true. When invoked with blocking set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true. When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return false. Return true otherwise. """ if not blocking and timeout is not None: raise ValueError("can't specify timeout for non-blocking acquire") rc = False endtime = None with self._cond: while self._value == 0: if not blocking: break if timeout is not None: if endtime is None: endtime = _time() + timeout else: timeout = endtime - _time() if timeout <= 0: break self._cond.wait(timeout) else: self._value -= 1 rc = True return rc __enter__ = acquire def release(self): """Release a semaphore, incrementing the internal counter by one. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. """ with self._cond: self._value += 1 self._cond.notify() def __exit__(self, t, v, tb): self.release() class BoundedSemaphore(Semaphore): """Implements a bounded semaphore. A bounded semaphore checks to make sure its current value doesn't exceed its initial value. If it does, ValueError is raised. In most situations semaphores are used to guard resources with limited capacity. If the semaphore is released too many times it's a sign of a bug. If not given, value defaults to 1. Like regular semaphores, bounded semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. """ def __init__(self, value=1): Semaphore.__init__(self, value) self._initial_value = value def release(self): """Release a semaphore, incrementing the internal counter by one. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. If the number of releases exceeds the number of acquires, raise a ValueError. """ with self._cond: if self._value >= self._initial_value: raise ValueError("Semaphore released too many times") self._value += 1 self._cond.notify() class Event: """Class implementing event objects. Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. The flag is initially false. """ # After Tim Peters' event class (without is_posted()) def __init__(self): self._cond = Condition(Lock()) self._flag = False def _reset_internal_locks(self): # private! called by Thread._reset_internal_locks by _after_fork() self._cond.__init__() def is_set(self): """Return true if and only if the internal flag is true.""" return self._flag isSet = is_set def set(self): """Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all. """ self._cond.acquire() try: self._flag = True self._cond.notify_all() finally: self._cond.release() def clear(self): """Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again. """ self._cond.acquire() try: self._flag = False finally: self._cond.release() def wait(self, timeout=None): """Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out. """ self._cond.acquire() try: signaled = self._flag if not signaled: signaled = self._cond.wait(timeout) return signaled finally: self._cond.release() # A barrier class. Inspired in part by the pthread_barrier_* api and # the CyclicBarrier class from Java. See # http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and # http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ # CyclicBarrier.html # for information. # We maintain two main states, 'filling' and 'draining' enabling the barrier # to be cyclic. Threads are not allowed into it until it has fully drained # since the previous cycle. In addition, a 'resetting' state exists which is # similar to 'draining' except that threads leave with a BrokenBarrierError, # and a 'broken' state in which all threads get the exception. class Barrier: """Implements a Barrier. Useful for synchronizing a fixed number of threads at known synchronization points. Threads block on 'wait()' and are simultaneously once they have all made that call. """ def __init__(self, parties, action=None, timeout=None): """Create a barrier, initialised to 'parties' threads. 'action' is a callable which, when supplied, will be called by one of the threads after they have all entered the barrier and just prior to releasing them all. If a 'timeout' is provided, it is uses as the default for all subsequent 'wait()' calls. """ self._cond = Condition(Lock()) self._action = action self._timeout = timeout self._parties = parties self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken self._count = 0 def wait(self, timeout=None): """Wait for the barrier. When the specified number of threads have started waiting, they are all simultaneously awoken. If an 'action' was provided for the barrier, one of the threads will have executed that callback prior to returning. Returns an individual index number from 0 to 'parties-1'. """ if timeout is None: timeout = self._timeout with self._cond: self._enter() # Block while the barrier drains. index = self._count self._count += 1 try: if index + 1 == self._parties: # We release the barrier self._release() else: # We wait until someone releases us self._wait(timeout) return index finally: self._count -= 1 # Wake up any threads waiting for barrier to drain. self._exit() # Block until the barrier is ready for us, or raise an exception # if it is broken. def _enter(self): while self._state in (-1, 1): # It is draining or resetting, wait until done self._cond.wait() #see if the barrier is in a broken state if self._state < 0: raise BrokenBarrierError assert self._state == 0 # Optionally run the 'action' and release the threads waiting # in the barrier. def _release(self): try: if self._action: self._action() # enter draining state self._state = 1 self._cond.notify_all() except: #an exception during the _action handler. Break and reraise self._break() raise # Wait in the barrier until we are relased. Raise an exception # if the barrier is reset or broken. def _wait(self, timeout): if not self._cond.wait_for(lambda : self._state != 0, timeout): #timed out. Break the barrier self._break() raise BrokenBarrierError if self._state < 0: raise BrokenBarrierError assert self._state == 1 # If we are the last thread to exit the barrier, signal any threads # waiting for the barrier to drain. def _exit(self): if self._count == 0: if self._state in (-1, 1): #resetting or draining self._state = 0 self._cond.notify_all() def reset(self): """Reset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised. """ with self._cond: if self._count > 0: if self._state == 0: #reset the barrier, waking up threads self._state = -1 elif self._state == -2: #was broken, set it to reset state #which clears when the last thread exits self._state = -1 else: self._state = 0 self._cond.notify_all() def abort(self): """Place the barrier into a 'broken' state. Useful in case of error. Any currently waiting threads and threads attempting to 'wait()' will have BrokenBarrierError raised. """ with self._cond: self._break() def _break(self): # An internal error was detected. The barrier is set to # a broken state all parties awakened. self._state = -2 self._cond.notify_all() @property def parties(self): """Return the number of threads required to trip the barrier.""" return self._parties @property def n_waiting(self): """Return the number of threads currently waiting at the barrier.""" # We don't need synchronization here since this is an ephemeral result # anyway. It returns the correct value in the steady state. if self._state == 0: return self._count return 0 @property def broken(self): """Return True if the barrier is in a broken state.""" return self._state == -2 # exception raised by the Barrier class class BrokenBarrierError(RuntimeError): pass # Helper to generate new thread names _counter = 0 def _newname(template="Thread-%d"): global _counter _counter += 1 return template % _counter # Active thread administration _active_limbo_lock = _allocate_lock() _active = {} # maps thread id to Thread object _limbo = {} _dangling = WeakSet() # Main class for threads class Thread: """A class that represents a thread of control. This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. """ __initialized = False # Need to store a reference to sys.exc_info for printing # out exceptions when a thread tries to use a global var. during interp. # shutdown and thus raises an exception about trying to perform some # operation on/with a NoneType __exc_info = _sys.exc_info # Keep sys.exc_clear too to clear the exception just before # allowing .join() to return. #XXX __exc_clear = _sys.exc_clear def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None): """This constructor should always be called with keyword arguments. Arguments are: *group* should be None; reserved for future extension when a ThreadGroup class is implemented. *target* is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called. *name* is the thread name. By default, a unique name is constructed of the form "Thread-N" where N is a small decimal number. *args* is the argument tuple for the target invocation. Defaults to (). *kwargs* is a dictionary of keyword arguments for the target invocation. Defaults to {}. If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. """ assert group is None, "group argument must be None for now" if kwargs is None: kwargs = {} self._target = target self._name = str(name or _newname()) self._args = args self._kwargs = kwargs if daemon is not None: self._daemonic = daemon else: self._daemonic = current_thread().daemon self._ident = None self._tstate_lock = None self._started = Event() self._is_stopped = False self._initialized = True # sys.stderr is not stored in the class like # sys.exc_info since it can be changed between instances self._stderr = _sys.stderr # For debugging and _after_fork() _dangling.add(self) def _reset_internal_locks(self, is_alive): # private! Called by _after_fork() to reset our internal locks as # they may be in an invalid state leading to a deadlock or crash. self._started._reset_internal_locks() if is_alive: self._set_tstate_lock() else: # The thread isn't alive after fork: it doesn't have a tstate # anymore. self._is_stopped = True self._tstate_lock = None def __repr__(self): assert self._initialized, "Thread.__init__() was not called" status = "initial" if self._started.is_set(): status = "started" self.is_alive() # easy way to get ._is_stopped set when appropriate if self._is_stopped: status = "stopped" if self._daemonic: status += " daemon" if self._ident is not None: status += " %s" % self._ident return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status) def start(self): """Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. """ if not self._initialized: raise RuntimeError("thread.__init__() not called") if self._started.is_set(): raise RuntimeError("threads can only be started once") with _active_limbo_lock: _limbo[self] = self try: _start_new_thread(self._bootstrap, ()) except Exception: with _active_limbo_lock: del _limbo[self] raise self._started.wait() def run(self): """Method representing the thread's activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. """ try: if self._target: self._target(*self._args, **self._kwargs) finally: # Avoid a refcycle if the thread is running a function with # an argument that has a member that points to the thread. del self._target, self._args, self._kwargs def _bootstrap(self): # Wrapper around the real bootstrap code that ignores # exceptions during interpreter cleanup. Those typically # happen when a daemon thread wakes up at an unfortunate # moment, finds the world around it destroyed, and raises some # random exception *** while trying to report the exception in # _bootstrap_inner() below ***. Those random exceptions # don't help anybody, and they confuse users, so we suppress # them. We suppress them only when it appears that the world # indeed has already been destroyed, so that exceptions in # _bootstrap_inner() during normal business hours are properly # reported. Also, we only suppress them for daemonic threads; # if a non-daemonic encounters this, something else is wrong. try: self._bootstrap_inner() except: if self._daemonic and _sys is None: return raise def _set_ident(self): self._ident = get_ident() def _set_tstate_lock(self): """ Set a lock object which will be released by the interpreter when the underlying thread state (see pystate.h) gets deleted. """ self._tstate_lock = _set_sentinel() self._tstate_lock.acquire() def _bootstrap_inner(self): try: self._set_ident() self._set_tstate_lock() self._started.set() with _active_limbo_lock: _active[self._ident] = self del _limbo[self] if _trace_hook: _sys.settrace(_trace_hook) if _profile_hook: _sys.setprofile(_profile_hook) try: self.run() except SystemExit: pass except: # If sys.stderr is no more (most likely from interpreter # shutdown) use self._stderr. Otherwise still use sys (as in # _sys) in case sys.stderr was redefined since the creation of # self. if _sys: _sys.stderr.write("Exception in thread %s:\n%s\n" % (self.name, _format_exc())) else: # Do the best job possible w/o a huge amt. of code to # approximate a traceback (code ideas from # Lib/traceback.py) exc_type, exc_value, exc_tb = self._exc_info() try: print(( "Exception in thread " + self.name + " (most likely raised during interpreter shutdown):"), file=self._stderr) print(( "Traceback (most recent call last):"), file=self._stderr) while exc_tb: print(( ' File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)), file=self._stderr) exc_tb = exc_tb.tb_next print(("%s: %s" % (exc_type, exc_value)), file=self._stderr) # Make sure that exc_tb gets deleted since it is a memory # hog; deleting everything else is just for thoroughness finally: del exc_type, exc_value, exc_tb finally: # Prevent a race in # test_threading.test_no_refcycle_through_target when # the exception keeps the target alive past when we # assert that it's dead. #XXX self.__exc_clear() pass finally: with _active_limbo_lock: try: # We don't call self._delete() because it also # grabs _active_limbo_lock. del _active[get_ident()] except: pass def _stop(self): # After calling ._stop(), .is_alive() returns False and .join() returns # immediately. ._tstate_lock must be released before calling ._stop(). # # Normal case: C code at the end of the thread's life # (release_sentinel in _threadmodule.c) releases ._tstate_lock, and # that's detected by our ._wait_for_tstate_lock(), called by .join() # and .is_alive(). Any number of threads _may_ call ._stop() # simultaneously (for example, if multiple threads are blocked in # .join() calls), and they're not serialized. That's harmless - # they'll just make redundant rebindings of ._is_stopped and # ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the # "assert self._is_stopped" in ._wait_for_tstate_lock() always works # (the assert is executed only if ._tstate_lock is None). # # Special case: _main_thread releases ._tstate_lock via this # module's _shutdown() function. lock = self._tstate_lock if lock is not None: assert not lock.locked() self._is_stopped = True self._tstate_lock = None def _delete(self): "Remove current thread from the dict of currently running threads." # Notes about running with _dummy_thread: # # Must take care to not raise an exception if _dummy_thread is being # used (and thus this module is being used as an instance of # dummy_threading). _dummy_thread.get_ident() always returns -1 since # there is only one thread if _dummy_thread is being used. Thus # len(_active) is always <= 1 here, and any Thread instance created # overwrites the (if any) thread currently registered in _active. # # An instance of _MainThread is always created by 'threading'. This # gets overwritten the instant an instance of Thread is created; both # threads return -1 from _dummy_thread.get_ident() and thus have the # same key in the dict. So when the _MainThread instance created by # 'threading' tries to clean itself up when atexit calls this method # it gets a KeyError if another Thread instance was created. # # This all means that KeyError from trying to delete something from # _active if dummy_threading is being used is a red herring. But # since it isn't if dummy_threading is *not* being used then don't # hide the exception. try: with _active_limbo_lock: del _active[get_ident()] # There must not be any python code between the previous line # and after the lock is released. Otherwise a tracing function # could try to acquire the lock again in the same thread, (in # current_thread()), and would block. except KeyError: if 'dummy_threading' not in _sys.modules: raise def join(self, timeout=None): """Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates -- either normally or through an unhandled exception or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened -- if the thread is still alive, the join() call timed out. When the timeout argument is not present or None, the operation will block until the thread terminates. A thread can be join()ed many times. join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception. """ if not self._initialized: raise RuntimeError("Thread.__init__() not called") if not self._started.is_set(): raise RuntimeError("cannot join thread before it is started") if self is current_thread(): raise RuntimeError("cannot join current thread") if timeout is None: self._wait_for_tstate_lock() else: # the behavior of a negative timeout isn't documented, but # historically .join(timeout=x) for x<0 has acted as if timeout=0 self._wait_for_tstate_lock(timeout=max(timeout, 0)) def _wait_for_tstate_lock(self, block=True, timeout=-1): # Issue #18808: wait for the thread state to be gone. # At the end of the thread's life, after all knowledge of the thread # is removed from C data structures, C code releases our _tstate_lock. # This method passes its arguments to _tstate_lock.aquire(). # If the lock is acquired, the C code is done, and self._stop() is # called. That sets ._is_stopped to True, and ._tstate_lock to None. lock = self._tstate_lock if lock is None: # already determined that the C code is done assert self._is_stopped elif lock.acquire(block, timeout): lock.release() self._stop() @property def name(self): """A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. """ assert self._initialized, "Thread.__init__() not called" return self._name @name.setter def name(self, name): assert self._initialized, "Thread.__init__() not called" self._name = str(name) @property def ident(self): """Thread identifier of this thread or None if it has not been started. This is a nonzero integer. See the thread.get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited. """ assert self._initialized, "Thread.__init__() not called" return self._ident def is_alive(self): """Return whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads. """ assert self._initialized, "Thread.__init__() not called" if self._is_stopped or not self._started.is_set(): return False self._wait_for_tstate_lock(False) return not self._is_stopped isAlive = is_alive @property def daemon(self): """A boolean value indicating whether this thread is a daemon thread. This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False. The entire Python program exits when no alive non-daemon threads are left. """ assert self._initialized, "Thread.__init__() not called" return self._daemonic @daemon.setter def daemon(self, daemonic): if not self._initialized: raise RuntimeError("Thread.__init__() not called") if self._started.is_set(): raise RuntimeError("cannot set daemon status of active thread") self._daemonic = daemonic def isDaemon(self): return self.daemon def setDaemon(self, daemonic): self.daemon = daemonic def getName(self): return self.name def setName(self, name): self.name = name # The timer class was contributed by Itamar Shtull-Trauring class Timer(Thread): """Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None) t.start() t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=None, kwargs=None): Thread.__init__(self) self.interval = interval self.function = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self.finished = Event() def cancel(self): """Stop the timer if it hasn't finished yet.""" self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set() # Special thread class to represent the main thread # This is garbage collected through an exit handler class _MainThread(Thread): def __init__(self): Thread.__init__(self, name="MainThread", daemon=False) self._set_tstate_lock() self._started.set() self._set_ident() with _active_limbo_lock: _active[self._ident] = self # Dummy thread class to represent threads not started here. # These aren't garbage collected when they die, nor can they be waited for. # If they invoke anything in threading.py that calls current_thread(), they # leave an entry in the _active dict forever after. # Their purpose is to return *something* from current_thread(). # They are marked as daemon threads so we won't wait for them # when we exit (conform previous semantics). class _DummyThread(Thread): def __init__(self): Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True) self._started.set() self._set_ident() with _active_limbo_lock: _active[self._ident] = self def _stop(self): pass def join(self, timeout=None): assert False, "cannot join a dummy thread" # Global API functions def current_thread(): """Return the current Thread object, corresponding to the caller's thread of control. If the caller's thread of control was not created through the threading module, a dummy thread object with limited functionality is returned. """ try: return _active[get_ident()] except KeyError: return _DummyThread() currentThread = current_thread def active_count(): """Return the number of Thread objects currently alive. The returned count is equal to the length of the list returned by enumerate(). """ with _active_limbo_lock: return len(_active) + len(_limbo) activeCount = active_count def _enumerate(): # Same as enumerate(), but without the lock. Internal use only. return list(_active.values()) + list(_limbo.values()) def enumerate(): """Return a list of all Thread objects currently alive. The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started. """ with _active_limbo_lock: return list(_active.values()) + list(_limbo.values()) from _thread import stack_size # Create the main thread object, # and make it available for the interpreter # (Py_Main) as threading._shutdown. _main_thread = _MainThread() def _shutdown(): # Obscure: other threads may be waiting to join _main_thread. That's # dubious, but some code does it. We can't wait for C code to release # the main thread's tstate_lock - that won't happen until the interpreter # is nearly dead. So we release it here. Note that just calling _stop() # isn't enough: other threads may already be waiting on _tstate_lock. tlock = _main_thread._tstate_lock # The main thread isn't finished yet, so its thread state lock can't have # been released. assert tlock is not None assert tlock.locked() tlock.release() _main_thread._stop() t = _pickSomeNonDaemonThread() while t: t.join() t = _pickSomeNonDaemonThread() _main_thread._delete() def _pickSomeNonDaemonThread(): for t in enumerate(): if not t.daemon and t.is_alive(): return t return None def main_thread(): """Return the main thread object. In normal conditions, the main thread is the thread from which the Python interpreter was started. """ return _main_thread # get thread-local implementation, either from the thread # module, or from the python fallback try: from _thread import _local as local except ImportError: from _threading_local import local def _after_fork(): # This function is called by Python/ceval.c:PyEval_ReInitThreads which # is called from PyOS_AfterFork. Here we cleanup threading module state # that should not exist after a fork. # Reset _active_limbo_lock, in case we forked while the lock was held # by another (non-forked) thread. http://bugs.python.org/issue874900 global _active_limbo_lock, _main_thread _active_limbo_lock = _allocate_lock() # fork() only copied the current thread; clear references to others. new_active = {} current = current_thread() _main_thread = current with _active_limbo_lock: # Dangling thread instances must still have their locks reset, # because someone may join() them. threads = set(_enumerate()) threads.update(_dangling) for thread in threads: # Any lock/condition variable may be currently locked or in an # invalid state, so we reinitialize them. if thread is current: # There is only one active thread. We reset the ident to # its new value since it can have changed. thread._reset_internal_locks(True) ident = get_ident() thread._ident = ident new_active[ident] = thread else: # All the others are already stopped. thread._reset_internal_locks(False) thread._stop() _limbo.clear() _active.clear() _active.update(new_active) assert len(_active) == 1
lgpl-3.0
maurofaccenda/ansible
lib/ansible/modules/cloud/ovirt/ovirt_networks.py
5
9599
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ovirt_networks short_description: Module to manage logical networks in oVirt/RHV version_added: "2.3" author: "Ondra Machacek (@machacekondra)" description: - "Module to manage logical networks in oVirt/RHV" options: name: description: - "Name of the network to manage." required: true state: description: - "Should the network be present or absent" choices: ['present', 'absent'] default: present data_center: description: - "Datacenter name where network reside." description: description: - "Description of the network." comment: description: - "Comment of the network." vlan_tag: description: - "Specify VLAN tag." vm_network: description: - "If I(True) network will be marked as network for VM." - "VM network carries traffic relevant to the virtual machine." mtu: description: - "Maximum transmission unit (MTU) of the network." clusters: description: - "List of dictionaries describing how the network is managed in specific cluster." - "C(name) - Cluster name." - "C(assigned) - I(true) if the network should be assigned to cluster. Default is I(true)." - "C(required) - I(true) if the network must remain operational for all hosts associated with this network." - "C(display) - I(true) if the network should marked as display network." - "C(migration) - I(true) if the network should marked as migration network." - "C(gluster) - I(true) if the network should marked as gluster network." extends_documentation_fragment: ovirt ''' EXAMPLES = ''' # Examples don't contain auth parameter for simplicity, # look at ovirt_auth module to see how to reuse authentication: # Create network - ovirt_networks: data_center: mydatacenter name: mynetwork vlan_tag: 1 vm_network: true # Remove network - ovirt_networks: state: absent name: mynetwork ''' RETURN = ''' id: description: "ID of the managed network" returned: "On success if network is found." type: str sample: 7de90f31-222c-436c-a1ca-7e655bd5b60c network: description: "Dictionary of all the network attributes. Network attributes can be found on your oVirt/RHV instance at following url: https://ovirt.example.com/ovirt-engine/api/model#types/network." returned: "On success if network is found." type: dict ''' import traceback try: import ovirtsdk4.types as otypes except ImportError: pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( BaseModule, check_sdk, check_params, create_connection, equal, ovirt_full_argument_spec, search_by_name, ) class NetworksModule(BaseModule): def build_entity(self): return otypes.Network( name=self._module.params['name'], comment=self._module.params['comment'], description=self._module.params['description'], data_center=otypes.DataCenter( name=self._module.params['data_center'], ) if self._module.params['data_center'] else None, vlan=otypes.Vlan( self._module.params['vlan_tag'], ) if self._module.params['vlan_tag'] else None, usages=[ otypes.NetworkUsage.VM if self._module.params['vm_network'] else None ] if self._module.params['vm_network'] is not None else None, mtu=self._module.params['mtu'], ) def update_check(self, entity): return ( equal(self._module.params.get('comment'), entity.comment) and equal(self._module.params.get('description'), entity.description) and equal(self._module.params.get('vlan_tag'), getattr(entity.vlan, 'id', None)) and equal(self._module.params.get('vm_network'), True if entity.usages else False) and equal(self._module.params.get('mtu'), entity.mtu) ) class ClusterNetworksModule(BaseModule): def __init__(self, network_id, cluster_network, *args, **kwargs): super(ClusterNetworksModule, self).__init__(*args, **kwargs) self._network_id = network_id self._cluster_network = cluster_network def build_entity(self): return otypes.Network( id=self._network_id, name=self._module.params['name'], required=self._cluster_network.get('required'), display=self._cluster_network.get('display'), usages=[ otypes.NetworkUsage(usage) for usage in ['display', 'gluster', 'migration'] if self._cluster_network.get(usage, False) ] if ( self._cluster_network.get('display') is not None or self._cluster_network.get('gluster') is not None or self._cluster_network.get('migration') is not None ) else None, ) def update_check(self, entity): return ( equal(self._cluster_network.get('required'), entity.required) and equal(self._cluster_network.get('display'), entity.display) and equal( sorted([ usage for usage in ['display', 'gluster', 'migration'] if self._cluster_network.get(usage, False) ]), sorted([ str(usage) for usage in getattr(entity, 'usages', []) # VM + MANAGEMENT is part of root network if usage != otypes.NetworkUsage.VM and usage != otypes.NetworkUsage.MANAGEMENT ]), ) ) def main(): argument_spec = ovirt_full_argument_spec( state=dict( choices=['present', 'absent'], default='present', ), data_center=dict(default=None, required=True), name=dict(default=None, required=True), description=dict(default=None), comment=dict(default=None), vlan_tag=dict(default=None, type='int'), vm_network=dict(default=None, type='bool'), mtu=dict(default=None, type='int'), clusters=dict(default=None, type='list'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) check_sdk(module) check_params(module) try: auth = module.params.pop('auth') connection = create_connection(auth) clusters_service = connection.system_service().clusters_service() networks_service = connection.system_service().networks_service() networks_module = NetworksModule( connection=connection, module=module, service=networks_service, ) state = module.params['state'] network = networks_module.search_entity( search_params={ 'name': module.params['name'], 'datacenter': module.params['data_center'], }, ) if state == 'present': ret = networks_module.create(entity=network) # Update clusters networks: if module.params.get('clusters') is not None: for param_cluster in module.params.get('clusters'): cluster = search_by_name(clusters_service, param_cluster.get('name')) if cluster is None: raise Exception("Cluster '%s' was not found." % param_cluster.get('name')) cluster_networks_service = clusters_service.service(cluster.id).networks_service() cluster_networks_module = ClusterNetworksModule( network_id=ret['id'], cluster_network=param_cluster, connection=connection, module=module, service=cluster_networks_service, ) if param_cluster.get('assigned', True): ret = cluster_networks_module.create() else: ret = cluster_networks_module.remove() elif state == 'absent': ret = networks_module.remove(entity=network) module.exit_json(**ret) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None) if __name__ == "__main__": main()
gpl-3.0
tiaotiaolong/vulnerability_platform
struts2/tasks.py
1
2692
#coding=utf-8 from celery import task from struts2 import struts_poc from struts2.models import Info_Struts2 from struts2.views import * import time @task def deal_url(target_url): #for target_url in target_url_list: result=struts_poc.struts_019(target_url) if result[0]==True: struts_019_pic=red_pic_dir struts_019_be=True else: struts_019_pic=green_pic_dir struts_019_be=False struts_target_url=result[2] result=struts_poc.struts_033(target_url) if result[0]==True: struts_033_pic=red_pic_dir struts_033_be=True else: struts_033_pic=green_pic_dir struts_033_be=False result=struts_poc.struts_005(target_url) if result[0]==True: struts_005_pic=red_pic_dir struts_005_be=True else: struts_005_pic=green_pic_dir struts_005_be=False result=struts_poc.struts_016(target_url) if result[0]==True: struts_016_pic=red_pic_dir struts_016_be=True else: struts_016_pic=green_pic_dir struts_016_be=False result=struts_poc.struts_032(target_url) if result[0]==True: struts_032_pic=red_pic_dir struts_032_be=True else: struts_032_pic=green_pic_dir struts_032_be=False result=struts_poc.struts_037(target_url) if result[0]==True: struts_037_pic=red_pic_dir struts_037_be=True else: struts_037_pic=green_pic_dir struts_037_be=False result=struts_poc.struts_045(target_url) if result[0]==True: struts_045_pic=red_pic_dir struts_045_be=True else: struts_045_pic=green_pic_dir struts_045_be=False ip=get_ip_from_domain(target_url) #判断数据库中是否存在 #filterResult=Info_Struts2.objects.filter(target_url=struts_target_url) #if (len(filterResult)==0): #把扫描结果保存到数据库 obj_Info_Struts2=Info_Struts2(target_url=struts_target_url,struts_005=struts_005_be,struts_016=struts_016_be,struts_019=struts_019_be,struts_032=struts_032_be,struts_033=struts_033_be,struts_037=struts_037_be,struts_045=struts_045_be,ip=ip) obj_Info_Struts2.save() """ @task def mon_deal_url(db_start_num,db_task_num): while True: if get_db_rows()>=db_start_num+db_task_num: send_mail() break time.sleep(2) """ @task def mon_deal_url(celerytask_result): while True: result=0 for item in celerytask_result: if item.ready(): result=result+1 if result==len(celerytask_result): send_mail() break time.sleep(2)
gpl-3.0
LLNL/spack
var/spack/repos/builtin/packages/r-dendextend/package.py
5
1169
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RDendextend(RPackage): """dendextend: Extending 'Dendrogram' Functionality in R""" homepage = "https://cloud.r-project.org/package=dendextend" url = "https://cloud.r-project.org/src/contrib/dendextend_1.5.2.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/dendextend" version('1.12.0', sha256='b487fed8c1878a23b9e28394ee11f16a1831b76c90793eb486e6963c7162fa55') version('1.10.0', sha256='88f0fb3362d69144daf4f35d0ea09f32c2df1adf614e040327a42552a8fd3224') version('1.5.2', sha256='8228cf9cfd31ec30038aaa61a35959179bad748582d796999cd9ad78152a5f12') depends_on('r@3.0.0:', type=('build', 'run')) depends_on('r-magrittr@1.0.1:', type=('build', 'run')) depends_on('r-ggplot2', type=('build', 'run')) depends_on('r-fpc', when='@:1.10.0', type=('build', 'run')) depends_on('r-whisker', when='@:1.5.2', type=('build', 'run')) depends_on('r-viridis', type=('build', 'run'))
lgpl-2.1
uannight/reposan
plugin.video.tvalacarta/lib/youtube_dl/extractor/ccc.py
50
2839
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( int_or_none, parse_iso8601, ) class CCCIE(InfoExtractor): IE_NAME = 'media.ccc.de' _VALID_URL = r'https?://(?:www\.)?media\.ccc\.de/v/(?P<id>[^/?#&]+)' _TESTS = [{ 'url': 'https://media.ccc.de/v/30C3_-_5443_-_en_-_saal_g_-_201312281830_-_introduction_to_processor_design_-_byterazor#video', 'md5': '3a1eda8f3a29515d27f5adb967d7e740', 'info_dict': { 'id': '1839', 'ext': 'mp4', 'title': 'Introduction to Processor Design', 'description': 'md5:df55f6d073d4ceae55aae6f2fd98a0ac', 'thumbnail': r're:^https?://.*\.jpg$', 'upload_date': '20131228', 'timestamp': 1388188800, 'duration': 3710, } }, { 'url': 'https://media.ccc.de/v/32c3-7368-shopshifting#download', 'only_matching': True, }] def _real_extract(self, url): display_id = self._match_id(url) webpage = self._download_webpage(url, display_id) event_id = self._search_regex(r"data-id='(\d+)'", webpage, 'event id') event_data = self._download_json('https://media.ccc.de/public/events/%s' % event_id, event_id) formats = [] for recording in event_data.get('recordings', []): recording_url = recording.get('recording_url') if not recording_url: continue language = recording.get('language') folder = recording.get('folder') format_id = None if language: format_id = language if folder: if language: format_id += '-' + folder else: format_id = folder vcodec = 'h264' if 'h264' in folder else ( 'none' if folder in ('mp3', 'opus') else None ) formats.append({ 'format_id': format_id, 'url': recording_url, 'width': int_or_none(recording.get('width')), 'height': int_or_none(recording.get('height')), 'filesize': int_or_none(recording.get('size'), invscale=1024 * 1024), 'language': language, 'vcodec': vcodec, }) self._sort_formats(formats) return { 'id': event_id, 'display_id': display_id, 'title': event_data['title'], 'description': event_data.get('description'), 'thumbnail': event_data.get('thumb_url'), 'timestamp': parse_iso8601(event_data.get('date')), 'duration': int_or_none(event_data.get('length')), 'tags': event_data.get('tags'), 'formats': formats, }
gpl-2.0
sjagoe/cygit2
cygit2/tests/test_config.py
1
1620
# -*- coding: utf-8 -*- # # Copyright 2013 The cygit2 contributors # # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License, version 2, # as published by the Free Software Foundation. # # In addition to the permissions in the GNU General Public License, # the authors give you unlimited permission to link the compiled # version of this file into combinations with other programs, # and to distribute those combinations without any restriction # coming from the use of this file. (The General Public License # restrictions do apply in other respects; for example, they cover # modification of the file, and distribution when not linked into # a combined executable.) # # This file 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; see the file COPYING. If not, write to # the Free Software Foundation, 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301, USA. import unittest from cygit2.tests.fixtures import RepositoryFixture class TestConfig(RepositoryFixture): def test_get_config(self): # Does not raise when getting from repository object self.empty_repo.config def test_get_config_entry(self): config = self.empty_repo.config self.assertTrue(config['core.bare'], True) if __name__ == '__main__': unittest.main()
gpl-2.0
dbaxa/django
django/contrib/gis/db/models/query.py
224
36645
import warnings from django.contrib.gis.db.models import aggregates from django.contrib.gis.db.models.fields import ( GeometryField, LineStringField, PointField, get_srid_info, ) from django.contrib.gis.db.models.lookups import GISLookup from django.contrib.gis.db.models.sql import ( AreaField, DistanceField, GeomField, GMLField, ) from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Area, Distance from django.db import connections from django.db.models.expressions import RawSQL from django.db.models.fields import Field from django.db.models.query import QuerySet from django.utils import six from django.utils.deprecation import ( RemovedInDjango20Warning, RemovedInDjango110Warning, ) class GeoQuerySet(QuerySet): "The Geographic QuerySet." # ### GeoQuerySet Methods ### def area(self, tolerance=0.05, **kwargs): """ Returns the area of the geographic field in an `area` attribute on each element of this GeoQuerySet. """ # Performing setup here rather than in `_spatial_attribute` so that # we can get the units for `AreaField`. procedure_args, geo_field = self._spatial_setup( 'area', field_name=kwargs.get('field_name')) s = {'procedure_args': procedure_args, 'geo_field': geo_field, 'setup': False, } connection = connections[self.db] backend = connection.ops if backend.oracle: s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s' s['procedure_args']['tolerance'] = tolerance s['select_field'] = AreaField('sq_m') # Oracle returns area in units of meters. elif backend.postgis or backend.spatialite: if backend.geography: # Geography fields support area calculation, returns square meters. s['select_field'] = AreaField('sq_m') elif not geo_field.geodetic(connection): # Getting the area units of the geographic field. s['select_field'] = AreaField(Area.unit_attname(geo_field.units_name(connection))) else: # TODO: Do we want to support raw number areas for geodetic fields? raise Exception('Area on geodetic coordinate systems not supported.') return self._spatial_attribute('area', s, **kwargs) def centroid(self, **kwargs): """ Returns the centroid of the geographic field in a `centroid` attribute on each element of this GeoQuerySet. """ return self._geom_attribute('centroid', **kwargs) def collect(self, **kwargs): """ Performs an aggregate collect operation on the given geometry field. This is analogous to a union operation, but much faster because boundaries are not dissolved. """ warnings.warn( "The collect GeoQuerySet method is deprecated. Use the Collect() " "aggregate in an aggregate() or annotate() method.", RemovedInDjango110Warning, stacklevel=2 ) return self._spatial_aggregate(aggregates.Collect, **kwargs) def difference(self, geom, **kwargs): """ Returns the spatial difference of the geographic field in a `difference` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('difference', geom, **kwargs) def distance(self, geom, **kwargs): """ Returns the distance from the given geographic field name to the given geometry in a `distance` attribute on each element of the GeoQuerySet. Keyword Arguments: `spheroid` => If the geometry field is geodetic and PostGIS is the spatial database, then the more accurate spheroid calculation will be used instead of the quicker sphere calculation. `tolerance` => Used only for Oracle. The tolerance is in meters -- a default of 5 centimeters (0.05) is used. """ return self._distance_attribute('distance', geom, **kwargs) def envelope(self, **kwargs): """ Returns a Geometry representing the bounding box of the Geometry field in an `envelope` attribute on each element of the GeoQuerySet. """ return self._geom_attribute('envelope', **kwargs) def extent(self, **kwargs): """ Returns the extent (aggregate) of the features in the GeoQuerySet. The extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax). """ warnings.warn( "The extent GeoQuerySet method is deprecated. Use the Extent() " "aggregate in an aggregate() or annotate() method.", RemovedInDjango110Warning, stacklevel=2 ) return self._spatial_aggregate(aggregates.Extent, **kwargs) def extent3d(self, **kwargs): """ Returns the aggregate extent, in 3D, of the features in the GeoQuerySet. It is returned as a 6-tuple, comprising: (xmin, ymin, zmin, xmax, ymax, zmax). """ warnings.warn( "The extent3d GeoQuerySet method is deprecated. Use the Extent3D() " "aggregate in an aggregate() or annotate() method.", RemovedInDjango110Warning, stacklevel=2 ) return self._spatial_aggregate(aggregates.Extent3D, **kwargs) def force_rhr(self, **kwargs): """ Returns a modified version of the Polygon/MultiPolygon in which all of the vertices follow the Right-Hand-Rule. By default, this is attached as the `force_rhr` attribute on each element of the GeoQuerySet. """ return self._geom_attribute('force_rhr', **kwargs) def geojson(self, precision=8, crs=False, bbox=False, **kwargs): """ Returns a GeoJSON representation of the geometry field in a `geojson` attribute on each element of the GeoQuerySet. The `crs` and `bbox` keywords may be set to True if the user wants the coordinate reference system and the bounding box to be included in the GeoJSON representation of the geometry. """ backend = connections[self.db].ops if not backend.geojson: raise NotImplementedError('Only PostGIS 1.3.4+ and SpatiaLite 3.0+ ' 'support GeoJSON serialization.') if not isinstance(precision, six.integer_types): raise TypeError('Precision keyword must be set with an integer.') options = 0 if crs and bbox: options = 3 elif bbox: options = 1 elif crs: options = 2 s = {'desc': 'GeoJSON', 'procedure_args': {'precision': precision, 'options': options}, 'procedure_fmt': '%(geo_col)s,%(precision)s,%(options)s', } return self._spatial_attribute('geojson', s, **kwargs) def geohash(self, precision=20, **kwargs): """ Returns a GeoHash representation of the given field in a `geohash` attribute on each element of the GeoQuerySet. The `precision` keyword may be used to custom the number of _characters_ used in the output GeoHash, the default is 20. """ s = {'desc': 'GeoHash', 'procedure_args': {'precision': precision}, 'procedure_fmt': '%(geo_col)s,%(precision)s', } return self._spatial_attribute('geohash', s, **kwargs) def gml(self, precision=8, version=2, **kwargs): """ Returns GML representation of the given field in a `gml` attribute on each element of the GeoQuerySet. """ backend = connections[self.db].ops s = {'desc': 'GML', 'procedure_args': {'precision': precision}} if backend.postgis: s['procedure_fmt'] = '%(version)s,%(geo_col)s,%(precision)s' s['procedure_args'] = {'precision': precision, 'version': version} if backend.oracle: s['select_field'] = GMLField() return self._spatial_attribute('gml', s, **kwargs) def intersection(self, geom, **kwargs): """ Returns the spatial intersection of the Geometry field in an `intersection` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('intersection', geom, **kwargs) def kml(self, **kwargs): """ Returns KML representation of the geometry field in a `kml` attribute on each element of this GeoQuerySet. """ s = {'desc': 'KML', 'procedure_fmt': '%(geo_col)s,%(precision)s', 'procedure_args': {'precision': kwargs.pop('precision', 8)}, } return self._spatial_attribute('kml', s, **kwargs) def length(self, **kwargs): """ Returns the length of the geometry field as a `Distance` object stored in a `length` attribute on each element of this GeoQuerySet. """ return self._distance_attribute('length', None, **kwargs) def make_line(self, **kwargs): """ Creates a linestring from all of the PointField geometries in the this GeoQuerySet and returns it. This is a spatial aggregate method, and thus returns a geometry rather than a GeoQuerySet. """ warnings.warn( "The make_line GeoQuerySet method is deprecated. Use the MakeLine() " "aggregate in an aggregate() or annotate() method.", RemovedInDjango110Warning, stacklevel=2 ) return self._spatial_aggregate(aggregates.MakeLine, geo_field_type=PointField, **kwargs) def mem_size(self, **kwargs): """ Returns the memory size (number of bytes) that the geometry field takes in a `mem_size` attribute on each element of this GeoQuerySet. """ return self._spatial_attribute('mem_size', {}, **kwargs) def num_geom(self, **kwargs): """ Returns the number of geometries if the field is a GeometryCollection or Multi* Field in a `num_geom` attribute on each element of this GeoQuerySet; otherwise the sets with None. """ return self._spatial_attribute('num_geom', {}, **kwargs) def num_points(self, **kwargs): """ Returns the number of points in the first linestring in the Geometry field in a `num_points` attribute on each element of this GeoQuerySet; otherwise sets with None. """ return self._spatial_attribute('num_points', {}, **kwargs) def perimeter(self, **kwargs): """ Returns the perimeter of the geometry field as a `Distance` object stored in a `perimeter` attribute on each element of this GeoQuerySet. """ return self._distance_attribute('perimeter', None, **kwargs) def point_on_surface(self, **kwargs): """ Returns a Point geometry guaranteed to lie on the surface of the Geometry field in a `point_on_surface` attribute on each element of this GeoQuerySet; otherwise sets with None. """ return self._geom_attribute('point_on_surface', **kwargs) def reverse_geom(self, **kwargs): """ Reverses the coordinate order of the geometry, and attaches as a `reverse` attribute on each element of this GeoQuerySet. """ s = {'select_field': GeomField()} kwargs.setdefault('model_att', 'reverse_geom') if connections[self.db].ops.oracle: s['geo_field_type'] = LineStringField return self._spatial_attribute('reverse', s, **kwargs) def scale(self, x, y, z=0.0, **kwargs): """ Scales the geometry to a new size by multiplying the ordinates with the given x,y,z scale factors. """ if connections[self.db].ops.spatialite: if z != 0.0: raise NotImplementedError('SpatiaLite does not support 3D scaling.') s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s', 'procedure_args': {'x': x, 'y': y}, 'select_field': GeomField(), } else: s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s', 'procedure_args': {'x': x, 'y': y, 'z': z}, 'select_field': GeomField(), } return self._spatial_attribute('scale', s, **kwargs) def snap_to_grid(self, *args, **kwargs): """ Snap all points of the input geometry to the grid. How the geometry is snapped to the grid depends on how many arguments were given: - 1 argument : A single size to snap both the X and Y grids to. - 2 arguments: X and Y sizes to snap the grid to. - 4 arguments: X, Y sizes and the X, Y origins. """ if False in [isinstance(arg, (float,) + six.integer_types) for arg in args]: raise TypeError('Size argument(s) for the grid must be a float or integer values.') nargs = len(args) if nargs == 1: size = args[0] procedure_fmt = '%(geo_col)s,%(size)s' procedure_args = {'size': size} elif nargs == 2: xsize, ysize = args procedure_fmt = '%(geo_col)s,%(xsize)s,%(ysize)s' procedure_args = {'xsize': xsize, 'ysize': ysize} elif nargs == 4: xsize, ysize, xorigin, yorigin = args procedure_fmt = '%(geo_col)s,%(xorigin)s,%(yorigin)s,%(xsize)s,%(ysize)s' procedure_args = {'xsize': xsize, 'ysize': ysize, 'xorigin': xorigin, 'yorigin': yorigin} else: raise ValueError('Must provide 1, 2, or 4 arguments to `snap_to_grid`.') s = {'procedure_fmt': procedure_fmt, 'procedure_args': procedure_args, 'select_field': GeomField(), } return self._spatial_attribute('snap_to_grid', s, **kwargs) def svg(self, relative=False, precision=8, **kwargs): """ Returns SVG representation of the geographic field in a `svg` attribute on each element of this GeoQuerySet. Keyword Arguments: `relative` => If set to True, this will evaluate the path in terms of relative moves (rather than absolute). `precision` => May be used to set the maximum number of decimal digits used in output (defaults to 8). """ relative = int(bool(relative)) if not isinstance(precision, six.integer_types): raise TypeError('SVG precision keyword argument must be an integer.') s = { 'desc': 'SVG', 'procedure_fmt': '%(geo_col)s,%(rel)s,%(precision)s', 'procedure_args': { 'rel': relative, 'precision': precision, } } return self._spatial_attribute('svg', s, **kwargs) def sym_difference(self, geom, **kwargs): """ Returns the symmetric difference of the geographic field in a `sym_difference` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('sym_difference', geom, **kwargs) def translate(self, x, y, z=0.0, **kwargs): """ Translates the geometry to a new location using the given numeric parameters as offsets. """ if connections[self.db].ops.spatialite: if z != 0.0: raise NotImplementedError('SpatiaLite does not support 3D translation.') s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s', 'procedure_args': {'x': x, 'y': y}, 'select_field': GeomField(), } else: s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s', 'procedure_args': {'x': x, 'y': y, 'z': z}, 'select_field': GeomField(), } return self._spatial_attribute('translate', s, **kwargs) def transform(self, srid=4326, **kwargs): """ Transforms the given geometry field to the given SRID. If no SRID is provided, the transformation will default to using 4326 (WGS84). """ if not isinstance(srid, six.integer_types): raise TypeError('An integer SRID must be provided.') field_name = kwargs.get('field_name') self._spatial_setup('transform', field_name=field_name) self.query.add_context('transformed_srid', srid) return self._clone() def union(self, geom, **kwargs): """ Returns the union of the geographic field with the given Geometry in a `union` attribute on each element of this GeoQuerySet. """ return self._geomset_attribute('union', geom, **kwargs) def unionagg(self, **kwargs): """ Performs an aggregate union on the given geometry field. Returns None if the GeoQuerySet is empty. The `tolerance` keyword is for Oracle backends only. """ warnings.warn( "The unionagg GeoQuerySet method is deprecated. Use the Union() " "aggregate in an aggregate() or annotate() method.", RemovedInDjango110Warning, stacklevel=2 ) return self._spatial_aggregate(aggregates.Union, **kwargs) # ### Private API -- Abstracted DRY routines. ### def _spatial_setup(self, att, desc=None, field_name=None, geo_field_type=None): """ Performs set up for executing the spatial function. """ # Does the spatial backend support this? connection = connections[self.db] func = getattr(connection.ops, att, False) if desc is None: desc = att if not func: raise NotImplementedError('%s stored procedure not available on ' 'the %s backend.' % (desc, connection.ops.name)) # Initializing the procedure arguments. procedure_args = {'function': func} # Is there a geographic field in the model to perform this # operation on? geo_field = self._geo_field(field_name) if not geo_field: raise TypeError('%s output only available on GeometryFields.' % func) # If the `geo_field_type` keyword was used, then enforce that # type limitation. if geo_field_type is not None and not isinstance(geo_field, geo_field_type): raise TypeError('"%s" stored procedures may only be called on %ss.' % (func, geo_field_type.__name__)) # Setting the procedure args. procedure_args['geo_col'] = self._geocol_select(geo_field, field_name) return procedure_args, geo_field def _spatial_aggregate(self, aggregate, field_name=None, geo_field_type=None, tolerance=0.05): """ DRY routine for calling aggregate spatial stored procedures and returning their result to the caller of the function. """ # Getting the field the geographic aggregate will be called on. geo_field = self._geo_field(field_name) if not geo_field: raise TypeError('%s aggregate only available on GeometryFields.' % aggregate.name) # Checking if there are any geo field type limitations on this # aggregate (e.g. ST_Makeline only operates on PointFields). if geo_field_type is not None and not isinstance(geo_field, geo_field_type): raise TypeError('%s aggregate may only be called on %ss.' % (aggregate.name, geo_field_type.__name__)) # Getting the string expression of the field name, as this is the # argument taken by `Aggregate` objects. agg_col = field_name or geo_field.name # Adding any keyword parameters for the Aggregate object. Oracle backends # in particular need an additional `tolerance` parameter. agg_kwargs = {} if connections[self.db].ops.oracle: agg_kwargs['tolerance'] = tolerance # Calling the QuerySet.aggregate, and returning only the value of the aggregate. return self.aggregate(geoagg=aggregate(agg_col, **agg_kwargs))['geoagg'] def _spatial_attribute(self, att, settings, field_name=None, model_att=None): """ DRY routine for calling a spatial stored procedure on a geometry column and attaching its output as an attribute of the model. Arguments: att: The name of the spatial attribute that holds the spatial SQL function to call. settings: Dictonary of internal settings to customize for the spatial procedure. Public Keyword Arguments: field_name: The name of the geographic field to call the spatial function on. May also be a lookup to a geometry field as part of a foreign key relation. model_att: The name of the model attribute to attach the output of the spatial function to. """ warnings.warn( "The %s GeoQuerySet method is deprecated. See GeoDjango Functions " "documentation to find the expression-based replacement." % att, RemovedInDjango20Warning, stacklevel=2 ) # Default settings. settings.setdefault('desc', None) settings.setdefault('geom_args', ()) settings.setdefault('geom_field', None) settings.setdefault('procedure_args', {}) settings.setdefault('procedure_fmt', '%(geo_col)s') settings.setdefault('select_params', []) connection = connections[self.db] # Performing setup for the spatial column, unless told not to. if settings.get('setup', True): default_args, geo_field = self._spatial_setup( att, desc=settings['desc'], field_name=field_name, geo_field_type=settings.get('geo_field_type')) for k, v in six.iteritems(default_args): settings['procedure_args'].setdefault(k, v) else: geo_field = settings['geo_field'] # The attribute to attach to the model. if not isinstance(model_att, six.string_types): model_att = att # Special handling for any argument that is a geometry. for name in settings['geom_args']: # Using the field's get_placeholder() routine to get any needed # transformation SQL. geom = geo_field.get_prep_value(settings['procedure_args'][name]) params = geo_field.get_db_prep_lookup('contains', geom, connection=connection) geom_placeholder = geo_field.get_placeholder(geom, None, connection) # Replacing the procedure format with that of any needed # transformation SQL. old_fmt = '%%(%s)s' % name new_fmt = geom_placeholder % '%%s' settings['procedure_fmt'] = settings['procedure_fmt'].replace(old_fmt, new_fmt) settings['select_params'].extend(params) # Getting the format for the stored procedure. fmt = '%%(function)s(%s)' % settings['procedure_fmt'] # If the result of this function needs to be converted. if settings.get('select_field'): select_field = settings['select_field'] if connection.ops.oracle: select_field.empty_strings_allowed = False else: select_field = Field() # Finally, setting the extra selection attribute with # the format string expanded with the stored procedure # arguments. self.query.add_annotation( RawSQL(fmt % settings['procedure_args'], settings['select_params'], select_field), model_att) return self def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs): """ DRY routine for GeoQuerySet distance attribute routines. """ # Setting up the distance procedure arguments. procedure_args, geo_field = self._spatial_setup(func, field_name=kwargs.get('field_name')) # If geodetic defaulting distance attribute to meters (Oracle and # PostGIS spherical distances return meters). Otherwise, use the # units of the geometry field. connection = connections[self.db] geodetic = geo_field.geodetic(connection) geography = geo_field.geography if geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_field.units_name(connection)) # Shortcut booleans for what distance function we're using and # whether the geometry field is 3D. distance = func == 'distance' length = func == 'length' perimeter = func == 'perimeter' if not (distance or length or perimeter): raise ValueError('Unknown distance function: %s' % func) geom_3d = geo_field.dim == 3 # The field's get_db_prep_lookup() is used to get any # extra distance parameters. Here we set up the # parameters that will be passed in to field's function. lookup_params = [geom or 'POINT (0 0)', 0] # Getting the spatial backend operations. backend = connection.ops # If the spheroid calculation is desired, either by the `spheroid` # keyword or when calculating the length of geodetic field, make # sure the 'spheroid' distance setting string is passed in so we # get the correct spatial stored procedure. if spheroid or (backend.postgis and geodetic and (not geography) and length): lookup_params.append('spheroid') lookup_params = geo_field.get_prep_value(lookup_params) params = geo_field.get_db_prep_lookup('distance_lte', lookup_params, connection=connection) # The `geom_args` flag is set to true if a geometry parameter was # passed in. geom_args = bool(geom) if backend.oracle: if distance: procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s' elif length or perimeter: procedure_fmt = '%(geo_col)s,%(tolerance)s' procedure_args['tolerance'] = tolerance else: # Getting whether this field is in units of degrees since the field may have # been transformed via the `transform` GeoQuerySet method. srid = self.query.get_context('transformed_srid') if srid: u, unit_name, s = get_srid_info(srid, connection) geodetic = unit_name.lower() in geo_field.geodetic_units if geodetic and not connection.features.supports_distance_geodetic: raise ValueError( 'This database does not support linear distance ' 'calculations on geodetic coordinate systems.' ) if distance: if srid: # Setting the `geom_args` flag to false because we want to handle # transformation SQL here, rather than the way done by default # (which will transform to the original SRID of the field rather # than to what was transformed to). geom_args = False procedure_fmt = '%s(%%(geo_col)s, %s)' % (backend.transform, srid) if geom.srid is None or geom.srid == srid: # If the geom parameter srid is None, it is assumed the coordinates # are in the transformed units. A placeholder is used for the # geometry parameter. `GeomFromText` constructor is also needed # to wrap geom placeholder for SpatiaLite. if backend.spatialite: procedure_fmt += ', %s(%%%%s, %s)' % (backend.from_text, srid) else: procedure_fmt += ', %%s' else: # We need to transform the geom to the srid specified in `transform()`, # so wrapping the geometry placeholder in transformation SQL. # SpatiaLite also needs geometry placeholder wrapped in `GeomFromText` # constructor. if backend.spatialite: procedure_fmt += (', %s(%s(%%%%s, %s), %s)' % ( backend.transform, backend.from_text, geom.srid, srid)) else: procedure_fmt += ', %s(%%%%s, %s)' % (backend.transform, srid) else: # `transform()` was not used on this GeoQuerySet. procedure_fmt = '%(geo_col)s,%(geom)s' if not geography and geodetic: # Spherical distance calculation is needed (because the geographic # field is geodetic). However, the PostGIS ST_distance_sphere/spheroid() # procedures may only do queries from point columns to point geometries # some error checking is required. if not backend.geography: if not isinstance(geo_field, PointField): raise ValueError('Spherical distance calculation only supported on PointFields.') if not str(Geometry(six.memoryview(params[0].ewkb)).geom_type) == 'Point': raise ValueError( 'Spherical distance calculation only supported with ' 'Point Geometry parameters' ) # The `function` procedure argument needs to be set differently for # geodetic distance calculations. if spheroid: # Call to distance_spheroid() requires spheroid param as well. procedure_fmt += ",'%(spheroid)s'" procedure_args.update({'function': backend.distance_spheroid, 'spheroid': params[1]}) else: procedure_args.update({'function': backend.distance_sphere}) elif length or perimeter: procedure_fmt = '%(geo_col)s' if not geography and geodetic and length: # There's no `length_sphere`, and `length_spheroid` also # works on 3D geometries. procedure_fmt += ",'%(spheroid)s'" procedure_args.update({'function': backend.length_spheroid, 'spheroid': params[1]}) elif geom_3d and connection.features.supports_3d_functions: # Use 3D variants of perimeter and length routines on supported backends. if perimeter: procedure_args.update({'function': backend.perimeter3d}) elif length: procedure_args.update({'function': backend.length3d}) # Setting up the settings for `_spatial_attribute`. s = {'select_field': DistanceField(dist_att), 'setup': False, 'geo_field': geo_field, 'procedure_args': procedure_args, 'procedure_fmt': procedure_fmt, } if geom_args: s['geom_args'] = ('geom',) s['procedure_args']['geom'] = geom elif geom: # The geometry is passed in as a parameter because we handled # transformation conditions in this routine. s['select_params'] = [backend.Adapter(geom)] return self._spatial_attribute(func, s, **kwargs) def _geom_attribute(self, func, tolerance=0.05, **kwargs): """ DRY routine for setting up a GeoQuerySet method that attaches a Geometry attribute (e.g., `centroid`, `point_on_surface`). """ s = {'select_field': GeomField()} if connections[self.db].ops.oracle: s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s' s['procedure_args'] = {'tolerance': tolerance} return self._spatial_attribute(func, s, **kwargs) def _geomset_attribute(self, func, geom, tolerance=0.05, **kwargs): """ DRY routine for setting up a GeoQuerySet method that attaches a Geometry attribute and takes a Geoemtry parameter. This is used for geometry set-like operations (e.g., intersection, difference, union, sym_difference). """ s = { 'geom_args': ('geom',), 'select_field': GeomField(), 'procedure_fmt': '%(geo_col)s,%(geom)s', 'procedure_args': {'geom': geom}, } if connections[self.db].ops.oracle: s['procedure_fmt'] += ',%(tolerance)s' s['procedure_args']['tolerance'] = tolerance return self._spatial_attribute(func, s, **kwargs) def _geocol_select(self, geo_field, field_name): """ Helper routine for constructing the SQL to select the geographic column. Takes into account if the geographic field is in a ForeignKey relation to the current model. """ compiler = self.query.get_compiler(self.db) opts = self.model._meta if geo_field not in opts.fields: # Is this operation going to be on a related geographic field? # If so, it'll have to be added to the select related information # (e.g., if 'location__point' was given as the field name). # Note: the operation really is defined as "must add select related!" self.query.add_select_related([field_name]) # Call pre_sql_setup() so that compiler.select gets populated. compiler.pre_sql_setup() for col, _, _ in compiler.select: if col.output_field == geo_field: return col.as_sql(compiler, compiler.connection)[0] raise ValueError("%r not in compiler's related_select_cols" % geo_field) elif geo_field not in opts.local_fields: # This geographic field is inherited from another model, so we have to # use the db table for the _parent_ model instead. parent_model = geo_field.model._meta.concrete_model return self._field_column(compiler, geo_field, parent_model._meta.db_table) else: return self._field_column(compiler, geo_field) # Private API utilities, subject to change. def _geo_field(self, field_name=None): """ Returns the first Geometry field encountered or the one specified via the `field_name` keyword. The `field_name` may be a string specifying the geometry field on this GeoQuerySet's model, or a lookup string to a geometry field via a ForeignKey relation. """ if field_name is None: # Incrementing until the first geographic field is found. for field in self.model._meta.fields: if isinstance(field, GeometryField): return field return False else: # Otherwise, check by the given field name -- which may be # a lookup to a _related_ geographic field. return GISLookup._check_geo_field(self.model._meta, field_name) def _field_column(self, compiler, field, table_alias=None, column=None): """ Helper function that returns the database column for the given field. The table and column are returned (quoted) in the proper format, e.g., `"geoapp_city"."point"`. If `table_alias` is not specified, the database table associated with the model of this `GeoQuerySet` will be used. If `column` is specified, it will be used instead of the value in `field.column`. """ if table_alias is None: table_alias = compiler.query.get_meta().db_table return "%s.%s" % (compiler.quote_name_unless_alias(table_alias), compiler.connection.ops.quote_name(column or field.column))
bsd-3-clause
cbeloni/pychronesapp
backend/appengine/config/template_middleware.py
35
2705
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from jinja2.exceptions import TemplateNotFound from tekton import router from tekton.gae.middleware.response import ResponseBase from tekton.gae.middleware import Middleware from config import template class TemplateResponse(ResponseBase): def __init__(self, context=None, template_path=None): """ Class to render template and send it through HTTP response context: the context dict form template rendering template_path: the path for te template. If None it will find the template by convention, according to path """ super(TemplateResponse, self).__init__(context) self.template_path = template_path class TemplateMiddleware(Middleware): def set_up(self): self.dependencies["_render"] = template.render _TMPL_NOT_FOUND_MSG = '''Template not found Looked by convention in /routes/templates directory for: 1) %s 2) %s Create one of the two template files or explicit indicate which one to use on TemplateResponse''' def render_by_convention(fcn, context): template_path = router.to_path(fcn) def try_render(suffix): if template_path == '/': return '/home.html', template.render('/home.html', context) try: template_file = template_path + suffix return template_file, template.render(template_file, context) except TemplateNotFound: return template_file, None template_1, tmpl_rendered = try_render('.html') if tmpl_rendered is None: template_2, tmpl_rendered = try_render('/home.html') if tmpl_rendered is None: raise TemplateNotFound(_TMPL_NOT_FOUND_MSG % (template_1, template_2)) return tmpl_rendered class TemplateWriteMiddleware(Middleware): def set_up(self): fcn_response = self.dependencies['_fcn_response'] fcn = self.dependencies['_fcn'] if isinstance(fcn_response, TemplateResponse): context = fcn_response.context or {} for key in ('_logged_user', '_login_path', '_logout_path'): context[key] = self.dependencies[key] if '_csrf_code' in self.dependencies: context['_csrf_code'] = self.dependencies['_csrf_code'] template_path = fcn_response.template_path if template_path is None: tmpl_rendered = render_by_convention(fcn, context) else: tmpl_rendered = template.render(template_path, context) self.handler.response.write(tmpl_rendered) return True # after response, there is no need to look for more middlewares
mit
Sorsly/subtle
google-cloud-sdk/lib/surface/compute/rolling_updates/rollback.py
3
3333
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """rolling-updates rollback command.""" from apitools.base.py import exceptions as apitools_exceptions from googlecloudsdk.api_lib.compute import rolling_updates_util as updater_util from googlecloudsdk.calliope import base from googlecloudsdk.calliope import exceptions from googlecloudsdk.core import log from googlecloudsdk.core import resources class Rollback(base.Command): """Rolls back an existing update.""" @staticmethod def Args(parser): """Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed. """ parser.add_argument('update', help='Update id.') # TODO(user): Support --async which does not wait for state transition. def Run(self, args): """Run 'rolling-updates rollback'. Args: args: argparse.Namespace, The arguments that this command was invoked with. Raises: HttpException: An http error response was received while executing api request. ToolException: An error other than http error occured while executing the command. """ client = updater_util.GetApiClientInstance() messages = updater_util.GetApiMessages() ref = resources.REGISTRY.Parse( args.update, collection='replicapoolupdater.rollingUpdates') request = messages.ReplicapoolupdaterRollingUpdatesRollbackRequest( project=ref.project, zone=ref.zone, rollingUpdate=ref.rollingUpdate) try: operation = client.rollingUpdates.Rollback(request) operation_ref = resources.REGISTRY.Parse( operation.name, collection='replicapoolupdater.zoneOperations') result = updater_util.WaitForOperation( client, operation_ref, 'Initiating rollback of the update') if result: log.status.write('Initiated rollback of [{0}].\n'.format(ref)) else: raise exceptions.ToolException( 'could not initiate rollback of [{0}]'.format(ref)) except apitools_exceptions.HttpError as error: raise exceptions.HttpException(error) Rollback.detailed_help = { 'brief': 'Rolls back an existing update.', 'DESCRIPTION': """\ Rolls back the update in state ROLLING_FORWARD, ROLLING_BACK or PAUSED \ (fails if the update is in any other state). No-op if invoked in state ROLLED_BACK. Rollback sets the template that the Managed Instance Group \ used before the update was started and gradually restarts back to the \ old template all instances that are running in the new template. """, }
mit
GinnyN/towerofdimensions-django
django/db/models/fields/__init__.py
20
47014
import copy import datetime import decimal import math import warnings from itertools import tee from django.db import connection from django.db.models.query_utils import QueryWrapper from django.conf import settings from django import forms from django.core import exceptions, validators from django.utils.datastructures import DictWrapper from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.functional import curry from django.utils.text import capfirst from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import smart_unicode, force_unicode, smart_str from django.utils.ipv6 import clean_ipv6_address class NOT_PROVIDED: pass # The values to use for "blank" in SelectFields. Will be appended to the start # of most "choices" lists. BLANK_CHOICE_DASH = [("", "---------")] BLANK_CHOICE_NONE = [("", "None")] class FieldDoesNotExist(Exception): pass # A guide to Field parameters: # # * name: The name of the field specifed in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # attname. For example, this gets the primary key value of object "obj": # # getattr(obj, opts.pk.attname) class Field(object): """Base class for all field types""" # Designates whether empty strings fundamentally are allowed at the # database level. empty_strings_allowed = True # These track each time a Field instance is created. Used to retain order. # The auto_creation_counter is used for fields that Django implicitly # creates, creation_counter is used for all user-specified fields. creation_counter = 0 auto_creation_counter = -1 default_validators = [] # Default set of validators default_error_messages = { 'invalid_choice': _(u'Value %r is not a valid choice.'), 'null': _(u'This field cannot be null.'), 'blank': _(u'This field cannot be blank.'), 'unique': _(u'%(model_name)s with this %(field_label)s ' u'already exists.'), } # Generic field type description, usually overriden by subclasses def _description(self): return _(u'Field of type: %(field_type)s') % { 'field_type': self.__class__.__name__ } description = property(_description) def __init__(self, verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text='', db_column=None, db_tablespace=None, auto_created=False, validators=[], error_messages=None): self.name = name self.verbose_name = verbose_name self.primary_key = primary_key self.max_length, self._unique = max_length, unique self.blank, self.null = blank, null # Oracle treats the empty string ('') as null, so coerce the null # option whenever '' is a possible value. if (self.empty_strings_allowed and connection.features.interprets_empty_strings_as_nulls): self.null = True self.rel = rel self.default = default self.editable = editable self.serialize = serialize self.unique_for_date, self.unique_for_month = (unique_for_date, unique_for_month) self.unique_for_year = unique_for_year self._choices = choices or [] self.help_text = help_text self.db_column = db_column self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE self.auto_created = auto_created # Set db_index to True if the field has a relationship and doesn't # explicitly set db_index. self.db_index = db_index # Adjust the appropriate creation counter, and save our local copy. if auto_created: self.creation_counter = Field.auto_creation_counter Field.auto_creation_counter -= 1 else: self.creation_counter = Field.creation_counter Field.creation_counter += 1 self.validators = self.default_validators + validators messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, 'default_error_messages', {})) messages.update(error_messages or {}) self.error_messages = messages def __cmp__(self, other): # This is needed because bisect does not take a comparison function. return cmp(self.creation_counter, other.creation_counter) def __deepcopy__(self, memodict): # We don't have to deepcopy very much here, since most things are not # intended to be altered after initial creation. obj = copy.copy(self) if self.rel: obj.rel = copy.copy(self.rel) memodict[id(self)] = obj return obj def to_python(self, value): """ Converts the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Returns the converted value. Subclasses should override this. """ return value def run_validators(self, value): if value in validators.EMPTY_VALUES: return errors = [] for v in self.validators: try: v(value) except exceptions.ValidationError, e: if hasattr(e, 'code') and e.code in self.error_messages: message = self.error_messages[e.code] if e.params: message = message % e.params errors.append(message) else: errors.extend(e.messages) if errors: raise exceptions.ValidationError(errors) def validate(self, value, model_instance): """ Validates value and throws ValidationError. Subclasses should override this to provide validation logic. """ if not self.editable: # Skip validation for non-editable fields. return if self._choices and value: for option_key, option_value in self.choices: if isinstance(option_value, (list, tuple)): # This is an optgroup, so look inside the group for # options. for optgroup_key, optgroup_value in option_value: if value == optgroup_key: return elif value == option_key: return msg = self.error_messages['invalid_choice'] % value raise exceptions.ValidationError(msg) if value is None and not self.null: raise exceptions.ValidationError(self.error_messages['null']) if not self.blank and value in validators.EMPTY_VALUES: raise exceptions.ValidationError(self.error_messages['blank']) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised. """ value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) return value def db_type(self, connection): """ Returns the database column data type for this field, for the provided connection. """ # The default implementation of this method looks at the # backend-specific DATA_TYPES dictionary, looking up the field by its # "internal type". # # A Field class can implement the get_internal_type() method to specify # which *preexisting* Django Field class it's most similar to -- i.e., # a custom field might be represented by a TEXT column type, which is # the same as the TextField Django field type, which means the custom # field's get_internal_type() returns 'TextField'. # # But the limitation of the get_internal_type() / data_types approach # is that it cannot handle database column types that aren't already # mapped to one of the built-in Django field types. In this case, you # can implement db_type() instead of get_internal_type() to specify # exactly which wacky database column type you want to use. data = DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") try: return (connection.creation.data_types[self.get_internal_type()] % data) except KeyError: return None @property def unique(self): return self._unique or self.primary_key def set_attributes_from_name(self, name): if not self.name: self.name = name self.attname, self.column = self.get_attname_column() if self.verbose_name is None and self.name: self.verbose_name = self.name.replace('_', ' ') def contribute_to_class(self, cls, name): self.set_attributes_from_name(name) self.model = cls cls._meta.add_field(self) if self.choices: setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self)) def get_attname(self): return self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_cache_name(self): return '_%s_cache' % self.name def get_internal_type(self): return self.__class__.__name__ def pre_save(self, model_instance, add): """ Returns field's value just before saving. """ return getattr(model_instance, self.attname) def get_prep_value(self, value): """ Perform preliminary non-db specific value checks and conversions. """ return value def get_db_prep_value(self, value, connection, prepared=False): """Returns field's value prepared for interacting with the database backend. Used by the default implementations of ``get_db_prep_save``and `get_db_prep_lookup``` """ if not prepared: value = self.get_prep_value(value) return value def get_db_prep_save(self, value, connection): """ Returns field's value prepared for saving into a database. """ return self.get_db_prep_value(value, connection=connection, prepared=False) def get_prep_lookup(self, lookup_type, value): """ Perform preliminary non-db specific lookup checks and conversions """ if hasattr(value, 'prepare'): return value.prepare() if hasattr(value, '_prepare'): return value._prepare() if lookup_type in ( 'regex', 'iregex', 'month', 'day', 'week_day', 'search', 'contains', 'icontains', 'iexact', 'startswith', 'istartswith', 'endswith', 'iendswith', 'isnull' ): return value elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'): return self.get_prep_value(value) elif lookup_type in ('range', 'in'): return [self.get_prep_value(v) for v in value] elif lookup_type == 'year': try: return int(value) except ValueError: raise ValueError("The __year lookup type requires an integer " "argument") raise TypeError("Field has invalid lookup: %s" % lookup_type) def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): """ Returns field's value prepared for database lookup. """ if not prepared: value = self.get_prep_lookup(lookup_type, value) if hasattr(value, 'get_compiler'): value = value.get_compiler(connection=connection) if hasattr(value, 'as_sql') or hasattr(value, '_as_sql'): # If the value has a relabel_aliases method, it will need to # be invoked before the final SQL is evaluated if hasattr(value, 'relabel_aliases'): return value if hasattr(value, 'as_sql'): sql, params = value.as_sql() else: sql, params = value._as_sql(connection=connection) return QueryWrapper(('(%s)' % sql), params) if lookup_type in ('regex', 'iregex', 'month', 'day', 'week_day', 'search'): return [value] elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'): return [self.get_db_prep_value(value, connection=connection, prepared=prepared)] elif lookup_type in ('range', 'in'): return [self.get_db_prep_value(v, connection=connection, prepared=prepared) for v in value] elif lookup_type in ('contains', 'icontains'): return ["%%%s%%" % connection.ops.prep_for_like_query(value)] elif lookup_type == 'iexact': return [connection.ops.prep_for_iexact_query(value)] elif lookup_type in ('startswith', 'istartswith'): return ["%s%%" % connection.ops.prep_for_like_query(value)] elif lookup_type in ('endswith', 'iendswith'): return ["%%%s" % connection.ops.prep_for_like_query(value)] elif lookup_type == 'isnull': return [] elif lookup_type == 'year': if self.get_internal_type() == 'DateField': return connection.ops.year_lookup_bounds_for_date_field(value) else: return connection.ops.year_lookup_bounds(value) def has_default(self): """ Returns a boolean of whether this field has a default value. """ return self.default is not NOT_PROVIDED def get_default(self): """ Returns the default value for this field. """ if self.has_default(): if callable(self.default): return self.default() return force_unicode(self.default, strings_only=True) if (not self.empty_strings_allowed or (self.null and not connection.features.interprets_empty_strings_as_nulls)): return None return "" def get_validator_unique_lookup_type(self): return '%s__exact' % self.name def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): """Returns choices with a default blank choices included, for use as SelectField choices for this field.""" first_choice = include_blank and blank_choice or [] if self.choices: return first_choice + list(self.choices) rel_model = self.rel.to if hasattr(self.rel, 'get_related_field'): lst = [(getattr(x, self.rel.get_related_field().attname), smart_unicode(x)) for x in rel_model._default_manager.complex_filter( self.rel.limit_choices_to)] else: lst = [(x._get_pk_val(), smart_unicode(x)) for x in rel_model._default_manager.complex_filter( self.rel.limit_choices_to)] return first_choice + lst def get_choices_default(self): return self.get_choices() def get_flatchoices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH): """ Returns flattened choices with a default blank choice included. """ first_choice = include_blank and blank_choice or [] return first_choice + list(self.flatchoices) def _get_val_from_obj(self, obj): if obj is not None: return getattr(obj, self.attname) else: return self.get_default() def value_to_string(self, obj): """ Returns a string value of this field from the passed obj. This is used by the serialization framework. """ return smart_unicode(self._get_val_from_obj(obj)) def bind(self, fieldmapping, original, bound_field_class): return bound_field_class(self, fieldmapping, original) def _get_choices(self): if hasattr(self._choices, 'next'): choices, self._choices = tee(self._choices) return choices else: return self._choices choices = property(_get_choices) def _get_flatchoices(self): """Flattened version of choices tuple.""" flat = [] for choice, value in self.choices: if isinstance(value, (list, tuple)): flat.extend(value) else: flat.append((choice,value)) return flat flatchoices = property(_get_flatchoices) def save_form_data(self, instance, data): setattr(instance, self.name, data) def formfield(self, form_class=forms.CharField, **kwargs): """ Returns a django.forms.Field instance for this database Field. """ defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Fields with choices get special treatment. include_blank = (self.blank or not (self.has_default() or 'initial' in kwargs)) defaults['choices'] = self.get_choices(include_blank=include_blank) defaults['coerce'] = self.to_python if self.null: defaults['empty_value'] = None form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) return form_class(**defaults) def value_from_object(self, obj): """ Returns the value of this field in the given model instance. """ return getattr(obj, self.attname) def __repr__(self): """ Displays the module, class and name of the field. """ path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__) name = getattr(self, 'name', None) if name is not None: return '<%s: %s>' % (path, name) return '<%s>' % path class AutoField(Field): description = _("Integer") empty_strings_allowed = False default_error_messages = { 'invalid': _(u"'%s' value must be an integer."), } def __init__(self, *args, **kwargs): assert kwargs.get('primary_key', False) is True, \ "%ss must have primary_key=True." % self.__class__.__name__ kwargs['blank'] = True Field.__init__(self, *args, **kwargs) def get_internal_type(self): return "AutoField" def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): msg = self.error_messages['invalid'] % str(value) raise exceptions.ValidationError(msg) def validate(self, value, model_instance): pass def get_prep_value(self, value): if value is None: return None return int(value) def contribute_to_class(self, cls, name): assert not cls._meta.has_auto_field, \ "A model can't have more than one AutoField." super(AutoField, self).contribute_to_class(cls, name) cls._meta.has_auto_field = True cls._meta.auto_field = self def formfield(self, **kwargs): return None class BooleanField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _(u"'%s' value must be either True or False."), } description = _("Boolean (Either True or False)") def __init__(self, *args, **kwargs): kwargs['blank'] = True if 'default' not in kwargs and not kwargs.get('null'): kwargs['default'] = False Field.__init__(self, *args, **kwargs) def get_internal_type(self): return "BooleanField" def to_python(self, value): if value in (True, False): # if value is 1 or 0 than it's equal to True or False, but we want # to return a true bool for semantic reasons. return bool(value) if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False msg = self.error_messages['invalid'] % str(value) raise exceptions.ValidationError(msg) def get_prep_lookup(self, lookup_type, value): # Special-case handling for filters coming from a Web request (e.g. the # admin interface). Only works for scalar values (not lists). If you're # passing in a list, you might as well make things the right type when # constructing the list. if value in ('1', '0'): value = bool(int(value)) return super(BooleanField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): if value is None: return None return bool(value) def formfield(self, **kwargs): # Unlike most fields, BooleanField figures out include_blank from # self.null instead of self.blank. if self.choices: include_blank = (self.null or not (self.has_default() or 'initial' in kwargs)) defaults = {'choices': self.get_choices( include_blank=include_blank)} else: defaults = {'form_class': forms.BooleanField} defaults.update(kwargs) return super(BooleanField, self).formfield(**defaults) class CharField(Field): description = _("String (up to %(max_length)s)") def __init__(self, *args, **kwargs): super(CharField, self).__init__(*args, **kwargs) self.validators.append(validators.MaxLengthValidator(self.max_length)) def get_internal_type(self): return "CharField" def to_python(self, value): if isinstance(value, basestring) or value is None: return value return smart_unicode(value) def get_prep_value(self, value): return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). defaults = {'max_length': self.max_length} defaults.update(kwargs) return super(CharField, self).formfield(**defaults) # TODO: Maybe move this into contrib, because it's specialized. class CommaSeparatedIntegerField(CharField): default_validators = [validators.validate_comma_separated_integer_list] description = _("Comma-separated integers") def formfield(self, **kwargs): defaults = { 'error_messages': { 'invalid': _(u'Enter only digits separated by commas.'), } } defaults.update(kwargs) return super(CommaSeparatedIntegerField, self).formfield(**defaults) class DateField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _(u"'%s' value has an invalid date format. It must be " u"in YYYY-MM-DD format."), 'invalid_date': _(u"'%s' value has the correct format (YYYY-MM-DD) " u"but it is an invalid date."), } description = _("Date (without time)") def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs['editable'] = False kwargs['blank'] = True Field.__init__(self, verbose_name, name, **kwargs) def get_internal_type(self): return "DateField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value value = smart_str(value) try: parsed = parse_date(value) if parsed is not None: return parsed except ValueError: msg = self.error_messages['invalid_date'] % value raise exceptions.ValidationError(msg) msg = self.error_messages['invalid'] % value raise exceptions.ValidationError(msg) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super(DateField, self).pre_save(model_instance, add) def contribute_to_class(self, cls, name): super(DateField,self).contribute_to_class(cls, name) if not self.null: setattr(cls, 'get_next_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)) setattr(cls, 'get_previous_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False)) def get_prep_lookup(self, lookup_type, value): # For "__month", "__day", and "__week_day" lookups, convert the value # to an int so the database backend always sees a consistent type. if lookup_type in ('month', 'day', 'week_day'): return int(value) return super(DateField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.value_to_db_date(value) def value_to_string(self, obj): val = self._get_val_from_obj(obj) return '' if val is None else val.isoformat() def formfield(self, **kwargs): defaults = {'form_class': forms.DateField} defaults.update(kwargs) return super(DateField, self).formfield(**defaults) class DateTimeField(DateField): empty_strings_allowed = False default_error_messages = { 'invalid': _(u"'%s' value has an invalid format. It must be in " u"YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."), 'invalid_date': _(u"'%s' value has the correct format " u"(YYYY-MM-DD) but it is an invalid date."), 'invalid_datetime': _(u"'%s' value has the correct format " u"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " u"but it is an invalid date/time."), } description = _("Date (with time)") # __init__ is inherited from DateField def get_internal_type(self): return "DateTimeField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) if settings.USE_TZ: # For backwards compatibility, interpret naive datetimes in # local time. This won't work during DST change, but we can't # do much about it, so we let the exceptions percolate up the # call stack. warnings.warn(u"DateTimeField received a naive datetime (%s)" u" while time zone support is active." % value, RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value value = smart_str(value) try: parsed = parse_datetime(value) if parsed is not None: return parsed except ValueError: msg = self.error_messages['invalid_datetime'] % value raise exceptions.ValidationError(msg) try: parsed = parse_date(value) if parsed is not None: return datetime.datetime(parsed.year, parsed.month, parsed.day) except ValueError: msg = self.error_messages['invalid_date'] % value raise exceptions.ValidationError(msg) msg = self.error_messages['invalid'] % value raise exceptions.ValidationError(msg) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super(DateTimeField, self).pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO # get_prep_lookup is inherited from DateField def get_prep_value(self, value): value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. warnings.warn(u"DateTimeField received a naive datetime (%s)" u" while time zone support is active." % value, RuntimeWarning) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value def get_db_prep_value(self, value, connection, prepared=False): # Casts datetimes into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.value_to_db_datetime(value) def value_to_string(self, obj): val = self._get_val_from_obj(obj) return '' if val is None else val.isoformat() def formfield(self, **kwargs): defaults = {'form_class': forms.DateTimeField} defaults.update(kwargs) return super(DateTimeField, self).formfield(**defaults) class DecimalField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _(u"'%s' value must be a decimal number."), } description = _("Decimal number") def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs): self.max_digits, self.decimal_places = max_digits, decimal_places Field.__init__(self, verbose_name, name, **kwargs) def get_internal_type(self): return "DecimalField" def to_python(self, value): if value is None: return value try: return decimal.Decimal(value) except decimal.InvalidOperation: msg = self.error_messages['invalid'] % str(value) raise exceptions.ValidationError(msg) def _format(self, value): if isinstance(value, basestring) or value is None: return value else: return self.format_number(value) def format_number(self, value): """ Formats a number into a string with the requisite number of digits and decimal places. """ # Method moved to django.db.backends.util. # # It is preserved because it is used by the oracle backend # (django.db.backends.oracle.query), and also for # backwards-compatibility with any external code which may have used # this method. from django.db.backends import util return util.format_number(value, self.max_digits, self.decimal_places) def get_db_prep_save(self, value, connection): return connection.ops.value_to_db_decimal(self.to_python(value), self.max_digits, self.decimal_places) def get_prep_value(self, value): return self.to_python(value) def formfield(self, **kwargs): defaults = { 'max_digits': self.max_digits, 'decimal_places': self.decimal_places, 'form_class': forms.DecimalField, } defaults.update(kwargs) return super(DecimalField, self).formfield(**defaults) class EmailField(CharField): default_validators = [validators.validate_email] description = _("E-mail address") def __init__(self, *args, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 75) CharField.__init__(self, *args, **kwargs) def formfield(self, **kwargs): # As with CharField, this will cause email validation to be performed # twice. defaults = { 'form_class': forms.EmailField, } defaults.update(kwargs) return super(EmailField, self).formfield(**defaults) class FilePathField(Field): description = _("File path") def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, **kwargs): self.path, self.match, self.recursive = path, match, recursive kwargs['max_length'] = kwargs.get('max_length', 100) Field.__init__(self, verbose_name, name, **kwargs) def formfield(self, **kwargs): defaults = { 'path': self.path, 'match': self.match, 'recursive': self.recursive, 'form_class': forms.FilePathField, } defaults.update(kwargs) return super(FilePathField, self).formfield(**defaults) def get_internal_type(self): return "FilePathField" class FloatField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%s' value must be a float."), } description = _("Floating point number") def get_prep_value(self, value): if value is None: return None return float(value) def get_internal_type(self): return "FloatField" def to_python(self, value): if value is None: return value try: return float(value) except (TypeError, ValueError): msg = self.error_messages['invalid'] % str(value) raise exceptions.ValidationError(msg) def formfield(self, **kwargs): defaults = {'form_class': forms.FloatField} defaults.update(kwargs) return super(FloatField, self).formfield(**defaults) class IntegerField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%s' value must be an integer."), } description = _("Integer") def get_prep_value(self, value): if value is None: return None return int(value) def get_prep_lookup(self, lookup_type, value): if ((lookup_type == 'gte' or lookup_type == 'lt') and isinstance(value, float)): value = math.ceil(value) return super(IntegerField, self).get_prep_lookup(lookup_type, value) def get_internal_type(self): return "IntegerField" def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): msg = self.error_messages['invalid'] % str(value) raise exceptions.ValidationError(msg) def formfield(self, **kwargs): defaults = {'form_class': forms.IntegerField} defaults.update(kwargs) return super(IntegerField, self).formfield(**defaults) class BigIntegerField(IntegerField): empty_strings_allowed = False description = _("Big (8 byte) integer") MAX_BIGINT = 9223372036854775807 def get_internal_type(self): return "BigIntegerField" def formfield(self, **kwargs): defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1, 'max_value': BigIntegerField.MAX_BIGINT} defaults.update(kwargs) return super(BigIntegerField, self).formfield(**defaults) class IPAddressField(Field): empty_strings_allowed = False description = _("IPv4 address") def __init__(self, *args, **kwargs): kwargs['max_length'] = 15 Field.__init__(self, *args, **kwargs) def get_internal_type(self): return "IPAddressField" def formfield(self, **kwargs): defaults = {'form_class': forms.IPAddressField} defaults.update(kwargs) return super(IPAddressField, self).formfield(**defaults) class GenericIPAddressField(Field): empty_strings_allowed = True description = _("IP address") default_error_messages = {} def __init__(self, protocol='both', unpack_ipv4=False, *args, **kwargs): self.unpack_ipv4 = unpack_ipv4 self.default_validators, invalid_error_message = \ validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages['invalid'] = invalid_error_message kwargs['max_length'] = 39 Field.__init__(self, *args, **kwargs) def get_internal_type(self): return "GenericIPAddressField" def to_python(self, value): if value and ':' in value: return clean_ipv6_address(value, self.unpack_ipv4, self.error_messages['invalid']) return value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return value or None def get_prep_value(self, value): if value and ':' in value: try: return clean_ipv6_address(value, self.unpack_ipv4) except exceptions.ValidationError: pass return value def formfield(self, **kwargs): defaults = {'form_class': forms.GenericIPAddressField} defaults.update(kwargs) return super(GenericIPAddressField, self).formfield(**defaults) class NullBooleanField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _("'%s' value must be either None, True or False."), } description = _("Boolean (Either True, False or None)") def __init__(self, *args, **kwargs): kwargs['null'] = True kwargs['blank'] = True Field.__init__(self, *args, **kwargs) def get_internal_type(self): return "NullBooleanField" def to_python(self, value): if value is None: return None if value in (True, False): return bool(value) if value in ('None',): return None if value in ('t', 'True', '1'): return True if value in ('f', 'False', '0'): return False msg = self.error_messages['invalid'] % str(value) raise exceptions.ValidationError(msg) def get_prep_lookup(self, lookup_type, value): # Special-case handling for filters coming from a Web request (e.g. the # admin interface). Only works for scalar values (not lists). If you're # passing in a list, you might as well make things the right type when # constructing the list. if value in ('1', '0'): value = bool(int(value)) return super(NullBooleanField, self).get_prep_lookup(lookup_type, value) def get_prep_value(self, value): if value is None: return None return bool(value) def formfield(self, **kwargs): defaults = { 'form_class': forms.NullBooleanField, 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return super(NullBooleanField, self).formfield(**defaults) class PositiveIntegerField(IntegerField): description = _("Positive integer") def get_internal_type(self): return "PositiveIntegerField" def formfield(self, **kwargs): defaults = {'min_value': 0} defaults.update(kwargs) return super(PositiveIntegerField, self).formfield(**defaults) class PositiveSmallIntegerField(IntegerField): description = _("Positive small integer") def get_internal_type(self): return "PositiveSmallIntegerField" def formfield(self, **kwargs): defaults = {'min_value': 0} defaults.update(kwargs) return super(PositiveSmallIntegerField, self).formfield(**defaults) class SlugField(CharField): description = _("Slug (up to %(max_length)s)") def __init__(self, *args, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 50) # Set db_index=True unless it's been set manually. if 'db_index' not in kwargs: kwargs['db_index'] = True super(SlugField, self).__init__(*args, **kwargs) def get_internal_type(self): return "SlugField" def formfield(self, **kwargs): defaults = {'form_class': forms.SlugField} defaults.update(kwargs) return super(SlugField, self).formfield(**defaults) class SmallIntegerField(IntegerField): description = _("Small integer") def get_internal_type(self): return "SmallIntegerField" class TextField(Field): description = _("Text") def get_internal_type(self): return "TextField" def get_prep_value(self, value): if isinstance(value, basestring) or value is None: return value return smart_unicode(value) def formfield(self, **kwargs): defaults = {'widget': forms.Textarea} defaults.update(kwargs) return super(TextField, self).formfield(**defaults) class TimeField(Field): empty_strings_allowed = False default_error_messages = { 'invalid': _(u"'%s' value has an invalid format. It must be in " u"HH:MM[:ss[.uuuuuu]] format."), 'invalid_time': _(u"'%s' value has the correct format " u"(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."), } description = _("Time") def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs['editable'] = False kwargs['blank'] = True Field.__init__(self, verbose_name, name, **kwargs) def get_internal_type(self): return "TimeField" def to_python(self, value): if value is None: return None if isinstance(value, datetime.time): return value if isinstance(value, datetime.datetime): # Not usually a good idea to pass in a datetime here (it loses # information), but this can be a side-effect of interacting with a # database backend (e.g. Oracle), so we'll be accommodating. return value.time() value = smart_str(value) try: parsed = parse_time(value) if parsed is not None: return parsed except ValueError: msg = self.error_messages['invalid_time'] % value raise exceptions.ValidationError(msg) msg = self.error_messages['invalid'] % value raise exceptions.ValidationError(msg) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now().time() setattr(model_instance, self.attname, value) return value else: return super(TimeField, self).pre_save(model_instance, add) def get_prep_value(self, value): return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts times into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.value_to_db_time(value) def value_to_string(self, obj): val = self._get_val_from_obj(obj) return '' if val is None else val.isoformat() def formfield(self, **kwargs): defaults = {'form_class': forms.TimeField} defaults.update(kwargs) return super(TimeField, self).formfield(**defaults) class URLField(CharField): description = _("URL") def __init__(self, verbose_name=None, name=None, verify_exists=False, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 200) CharField.__init__(self, verbose_name, name, **kwargs) self.validators.append( validators.URLValidator(verify_exists=verify_exists)) def formfield(self, **kwargs): # As with CharField, this will cause URL validation to be performed # twice. defaults = { 'form_class': forms.URLField, } defaults.update(kwargs) return super(URLField, self).formfield(**defaults)
bsd-3-clause
tareqalayan/ansible
lib/ansible/playbook/block.py
14
16214
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleParserError from ansible.playbook.attribute import FieldAttribute from ansible.playbook.base import Base from ansible.playbook.become import Become from ansible.playbook.conditional import Conditional from ansible.playbook.helpers import load_list_of_tasks from ansible.playbook.role import Role from ansible.playbook.taggable import Taggable class Block(Base, Become, Conditional, Taggable): # main block fields containing the task lists _block = FieldAttribute(isa='list', default=[], inherit=False) _rescue = FieldAttribute(isa='list', default=[], inherit=False) _always = FieldAttribute(isa='list', default=[], inherit=False) # other fields _delegate_to = FieldAttribute(isa='string') _delegate_facts = FieldAttribute(isa='bool', default=False) # for future consideration? this would be functionally # similar to the 'else' clause for exceptions # _otherwise = FieldAttribute(isa='list') def __init__(self, play=None, parent_block=None, role=None, task_include=None, use_handlers=False, implicit=False): self._play = play self._role = role self._parent = None self._dep_chain = None self._use_handlers = use_handlers self._implicit = implicit # end of role flag self._eor = False if task_include: self._parent = task_include elif parent_block: self._parent = parent_block super(Block, self).__init__() def __repr__(self): return "BLOCK(uuid=%s)(id=%s)(parent=%s)" % (self._uuid, id(self), self._parent) def __eq__(self, other): '''object comparison based on _uuid''' return self._uuid == other._uuid def __ne__(self, other): '''object comparison based on _uuid''' return self._uuid != other._uuid def get_vars(self): ''' Blocks do not store variables directly, however they may be a member of a role or task include which does, so return those if present. ''' all_vars = self.vars.copy() if self._parent: all_vars.update(self._parent.get_vars()) return all_vars @staticmethod def load(data, play=None, parent_block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None): implicit = not Block.is_block(data) b = Block(play=play, parent_block=parent_block, role=role, task_include=task_include, use_handlers=use_handlers, implicit=implicit) return b.load_data(data, variable_manager=variable_manager, loader=loader) @staticmethod def is_block(ds): is_block = False if isinstance(ds, dict): for attr in ('block', 'rescue', 'always'): if attr in ds: is_block = True break return is_block def preprocess_data(self, ds): ''' If a simple task is given, an implicit block for that single task is created, which goes in the main portion of the block ''' if not Block.is_block(ds): if isinstance(ds, list): return super(Block, self).preprocess_data(dict(block=ds)) else: return super(Block, self).preprocess_data(dict(block=[ds])) return super(Block, self).preprocess_data(ds) def _load_block(self, attr, ds): try: return load_list_of_tasks( ds, play=self._play, block=self, role=self._role, task_include=None, variable_manager=self._variable_manager, loader=self._loader, use_handlers=self._use_handlers, ) except AssertionError as e: raise AnsibleParserError("A malformed block was encountered while loading a block", obj=self._ds, orig_exc=e) def _load_rescue(self, attr, ds): try: return load_list_of_tasks( ds, play=self._play, block=self, role=self._role, task_include=None, variable_manager=self._variable_manager, loader=self._loader, use_handlers=self._use_handlers, ) except AssertionError as e: raise AnsibleParserError("A malformed block was encountered while loading rescue.", obj=self._ds, orig_exc=e) def _load_always(self, attr, ds): try: return load_list_of_tasks( ds, play=self._play, block=self, role=self._role, task_include=None, variable_manager=self._variable_manager, loader=self._loader, use_handlers=self._use_handlers, ) except AssertionError as e: raise AnsibleParserError("A malformed block was encountered while loading always", obj=self._ds, orig_exc=e) def _validate_always(self, attr, name, value): if value and not self.block: raise AnsibleParserError("'%s' keyword cannot be used without 'block'" % name, obj=self._ds) _validate_rescue = _validate_always def get_dep_chain(self): if self._dep_chain is None: if self._parent: return self._parent.get_dep_chain() else: return None else: return self._dep_chain[:] def copy(self, exclude_parent=False, exclude_tasks=False): def _dupe_task_list(task_list, new_block): new_task_list = [] for task in task_list: new_task = task.copy(exclude_parent=True) if task._parent: new_task._parent = task._parent.copy(exclude_tasks=True) if task._parent == new_block: # If task._parent is the same as new_block, just replace it new_task._parent = new_block else: # task may not be a direct child of new_block, search for the correct place to insert new_block cur_obj = new_task._parent while cur_obj._parent and cur_obj._parent != new_block: cur_obj = cur_obj._parent cur_obj._parent = new_block else: new_task._parent = new_block new_task_list.append(new_task) return new_task_list new_me = super(Block, self).copy() new_me._play = self._play new_me._use_handlers = self._use_handlers new_me._eor = self._eor if self._dep_chain is not None: new_me._dep_chain = self._dep_chain[:] new_me._parent = None if self._parent and not exclude_parent: new_me._parent = self._parent.copy(exclude_tasks=True) if not exclude_tasks: new_me.block = _dupe_task_list(self.block or [], new_me) new_me.rescue = _dupe_task_list(self.rescue or [], new_me) new_me.always = _dupe_task_list(self.always or [], new_me) new_me._role = None if self._role: new_me._role = self._role new_me.validate() return new_me def serialize(self): ''' Override of the default serialize method, since when we're serializing a task we don't want to include the attribute list of tasks. ''' data = dict() for attr in self._valid_attrs: if attr not in ('block', 'rescue', 'always'): data[attr] = getattr(self, attr) data['dep_chain'] = self.get_dep_chain() data['eor'] = self._eor if self._role is not None: data['role'] = self._role.serialize() if self._parent is not None: data['parent'] = self._parent.copy(exclude_tasks=True).serialize() data['parent_type'] = self._parent.__class__.__name__ return data def deserialize(self, data): ''' Override of the default deserialize method, to match the above overridden serialize method ''' # import is here to avoid import loops from ansible.playbook.task_include import TaskInclude from ansible.playbook.handler_task_include import HandlerTaskInclude # we don't want the full set of attributes (the task lists), as that # would lead to a serialize/deserialize loop for attr in self._valid_attrs: if attr in data and attr not in ('block', 'rescue', 'always'): setattr(self, attr, data.get(attr)) self._dep_chain = data.get('dep_chain', None) self._eor = data.get('eor', False) # if there was a serialized role, unpack it too role_data = data.get('role') if role_data: r = Role() r.deserialize(role_data) self._role = r parent_data = data.get('parent') if parent_data: parent_type = data.get('parent_type') if parent_type == 'Block': p = Block() elif parent_type == 'TaskInclude': p = TaskInclude() elif parent_type == 'HandlerTaskInclude': p = HandlerTaskInclude() p.deserialize(parent_data) self._parent = p self._dep_chain = self._parent.get_dep_chain() def set_loader(self, loader): self._loader = loader if self._parent: self._parent.set_loader(loader) elif self._role: self._role.set_loader(loader) dep_chain = self.get_dep_chain() if dep_chain: for dep in dep_chain: dep.set_loader(loader) def _get_parent_attribute(self, attr, extend=False, prepend=False): ''' Generic logic to get the attribute or parent attribute for a block value. ''' extend = self._valid_attrs[attr].extend prepend = self._valid_attrs[attr].prepend try: value = self._attributes[attr] # If parent is static, we can grab attrs from the parent # otherwise, defer to the grandparent if getattr(self._parent, 'statically_loaded', True): _parent = self._parent else: _parent = self._parent._parent if _parent and (value is None or extend): try: if getattr(_parent, 'statically_loaded', True): if hasattr(_parent, '_get_parent_attribute'): parent_value = _parent._get_parent_attribute(attr) else: parent_value = _parent._attributes.get(attr, None) if extend: value = self._extend_value(value, parent_value, prepend) else: value = parent_value except AttributeError: pass if self._role and (value is None or extend): try: if hasattr(self._role, '_get_parent_attribute'): parent_value = self._role.get_parent_attribute(attr) else: parent_value = self._role._attributes.get(attr, None) if extend: value = self._extend_value(value, parent_value, prepend) else: value = parent_value dep_chain = self.get_dep_chain() if dep_chain and (value is None or extend): dep_chain.reverse() for dep in dep_chain: if hasattr(dep, '_get_parent_attribute'): dep_value = dep._get_parent_attribute(attr) else: dep_value = dep._attributes.get(attr, None) if extend: value = self._extend_value(value, dep_value, prepend) else: value = dep_value if value is not None and not extend: break except AttributeError: pass if self._play and (value is None or extend): try: play_value = self._play._attributes.get(attr, None) if play_value is not None: if extend: value = self._extend_value(value, play_value, prepend) else: value = play_value except AttributeError: pass except KeyError: pass return value def filter_tagged_tasks(self, play_context, all_vars): ''' Creates a new block, with task lists filtered based on the tags contained within the play_context object. ''' def evaluate_and_append_task(target): tmp_list = [] for task in target: if isinstance(task, Block): tmp_list.append(evaluate_block(task)) elif (task.action == 'meta' or (task.action == 'include' and task.evaluate_tags([], play_context.skip_tags, all_vars=all_vars)) or task.evaluate_tags(play_context.only_tags, play_context.skip_tags, all_vars=all_vars)): tmp_list.append(task) return tmp_list def evaluate_block(block): new_block = self.copy(exclude_tasks=True) new_block.block = evaluate_and_append_task(block.block) new_block.rescue = evaluate_and_append_task(block.rescue) new_block.always = evaluate_and_append_task(block.always) return new_block return evaluate_block(self) def has_tasks(self): return len(self.block) > 0 or len(self.rescue) > 0 or len(self.always) > 0 def get_include_params(self): if self._parent: return self._parent.get_include_params() else: return dict() def all_parents_static(self): ''' Determine if all of the parents of this block were statically loaded or not. Since Task/TaskInclude objects may be in the chain, they simply call their parents all_parents_static() method. Only Block objects in the chain check the statically_loaded value of the parent. ''' from ansible.playbook.task_include import TaskInclude if self._parent: if isinstance(self._parent, TaskInclude) and not self._parent.statically_loaded: return False return self._parent.all_parents_static() return True def get_first_parent_include(self): from ansible.playbook.task_include import TaskInclude if self._parent: if isinstance(self._parent, TaskInclude): return self._parent return self._parent.get_first_parent_include() return None
gpl-3.0
jdsika/TUM_HOly
openrave/sympy/series/residues.py
5
2020
""" This module implements the Residue function and related tools for working with residues. """ from sympy import Wild, sympify, Integer, Add def residue(expr, x, x0): """ Finds the residue of ``expr`` at the point x=x0. The residue is defined as the coefficient of 1/(x-x0) in the power series expansion about x=x0. Examples: >>> from sympy import Symbol, residue, sin >>> x = Symbol("x") >>> residue(1/x, x, 0) 1 >>> residue(1/x**2, x, 0) 0 >>> residue(2/sin(x), x, 0) 2 This function is essential for the Residue Theorem [1]. The current implementation uses series expansion to calculate it. A more general implementation is explained in the section 5.6 of the Bronstein's book [2]. For purely rational functions, the algorithm is much easier. See sections 2.4, 2.5, and 2.7 (this section actually gives an algorithm for computing any Laurent series coefficient for a rational function). The theory in section 2.4 will help to understand why the resultant works in the general algorithm. For the definition of a resultant, see section 1.4 (and any previous sections for more review). [1] http://en.wikipedia.org/wiki/Residue_theorem [2] M. Bronstein: Symbolic Integration I, Springer Verlag (2005) """ from sympy import collect expr = sympify(expr) if x0 != 0: expr = expr.subs(x, x+x0) s = expr.series(x, 0, 0).removeO() # TODO: this sometimes helps, but the series expansion should rather be # fixed, see #1627: if s == 0: s = expr.series(x, 0, 6).removeO() s = collect(s, x) if x0 != 0: s = s.subs(x, x-x0) a = Wild("r", exclude=[x]) c = Wild("c", exclude=[x]) r = s.match(a/(x-x0)+c) if r: return r[a] elif isinstance(s, Add): # TODO: this is to overcome a bug in match (#1626) for t in s.args: r = t.match(a/(x-x0)+c) if r: return r[a] return Integer(0)
mit
franekp/millandict
ankidict/thirdparty/cherrypy/process/wspbus.py
6
16279
"""An implementation of the Web Site Process Bus. This module is completely standalone, depending only on the stdlib. Web Site Process Bus -------------------- A Bus object is used to contain and manage site-wide behavior: daemonization, HTTP server start/stop, process reload, signal handling, drop privileges, PID file management, logging for all of these, and many more. In addition, a Bus object provides a place for each web framework to register code that runs in response to site-wide events (like process start and stop), or which controls or otherwise interacts with the site-wide components mentioned above. For example, a framework which uses file-based templates would add known template filenames to an autoreload component. Ideally, a Bus object will be flexible enough to be useful in a variety of invocation scenarios: 1. The deployer starts a site from the command line via a framework-neutral deployment script; applications from multiple frameworks are mixed in a single site. Command-line arguments and configuration files are used to define site-wide components such as the HTTP server, WSGI component graph, autoreload behavior, signal handling, etc. 2. The deployer starts a site via some other process, such as Apache; applications from multiple frameworks are mixed in a single site. Autoreload and signal handling (from Python at least) are disabled. 3. The deployer starts a site via a framework-specific mechanism; for example, when running tests, exploring tutorials, or deploying single applications from a single framework. The framework controls which site-wide components are enabled as it sees fit. The Bus object in this package uses topic-based publish-subscribe messaging to accomplish all this. A few topic channels are built in ('start', 'stop', 'exit', 'graceful', 'log', and 'main'). Frameworks and site containers are free to define their own. If a message is sent to a channel that has not been defined or has no listeners, there is no effect. In general, there should only ever be a single Bus object per process. Frameworks and site containers share a single Bus object by publishing messages and subscribing listeners. The Bus object works as a finite state machine which models the current state of the process. Bus methods move it from one state to another; those methods then publish to subscribed listeners on the channel for the new state.:: O | V STOPPING --> STOPPED --> EXITING -> X A A | | \___ | | \ | | V V STARTED <-- STARTING """ import atexit import os import sys import threading import time import traceback as _traceback import warnings import operator # Here I save the value of os.getcwd(), which, if I am imported early enough, # will be the directory from which the startup script was run. This is needed # by _do_execv(), to change back to the original directory before execv()ing a # new process. This is a defense against the application having changed the # current working directory (which could make sys.executable "not found" if # sys.executable is a relative-path, and/or cause other problems). _startup_cwd = os.getcwd() class ChannelFailures(Exception): """Exception raised when errors occur in a listener during Bus.publish(). """ delimiter = '\n' def __init__(self, *args, **kwargs): # Don't use 'super' here; Exceptions are old-style in Py2.4 # See https://github.com/cherrypy/cherrypy/issues/959 Exception.__init__(self, *args, **kwargs) self._exceptions = list() def handle_exception(self): """Append the current exception to self.""" self._exceptions.append(sys.exc_info()[1]) def get_instances(self): """Return a list of seen exception instances.""" return self._exceptions[:] def __str__(self): exception_strings = map(repr, self.get_instances()) return self.delimiter.join(exception_strings) __repr__ = __str__ def __bool__(self): return bool(self._exceptions) __nonzero__ = __bool__ # Use a flag to indicate the state of the bus. class _StateEnum(object): class State(object): name = None def __repr__(self): return "states.%s" % self.name def __setattr__(self, key, value): if isinstance(value, self.State): value.name = key object.__setattr__(self, key, value) states = _StateEnum() states.STOPPED = states.State() states.STARTING = states.State() states.STARTED = states.State() states.STOPPING = states.State() states.EXITING = states.State() try: import fcntl except ImportError: max_files = 0 else: try: max_files = os.sysconf('SC_OPEN_MAX') except AttributeError: max_files = 1024 class Bus(object): """Process state-machine and messenger for HTTP site deployment. All listeners for a given channel are guaranteed to be called even if others at the same channel fail. Each failure is logged, but execution proceeds on to the next listener. The only way to stop all processing from inside a listener is to raise SystemExit and stop the whole server. """ states = states state = states.STOPPED execv = False max_cloexec_files = max_files def __init__(self): self.execv = False self.state = states.STOPPED channels = 'start', 'stop', 'exit', 'graceful', 'log', 'main' self.listeners = dict( (channel, set()) for channel in channels ) self._priorities = {} def subscribe(self, channel, callback, priority=None): """Add the given callback at the given channel (if not present).""" if channel not in self.listeners: self.listeners[channel] = set() self.listeners[channel].add(callback) if priority is None: priority = getattr(callback, 'priority', 50) self._priorities[(channel, callback)] = priority def unsubscribe(self, channel, callback): """Discard the given callback (if present).""" listeners = self.listeners.get(channel) if listeners and callback in listeners: listeners.discard(callback) del self._priorities[(channel, callback)] def publish(self, channel, *args, **kwargs): """Return output of all subscribers for the given channel.""" if channel not in self.listeners: return [] exc = ChannelFailures() output = [] raw_items = ( (self._priorities[(channel, listener)], listener) for listener in self.listeners[channel] ) items = sorted(raw_items, key=operator.itemgetter(0)) for priority, listener in items: try: output.append(listener(*args, **kwargs)) except KeyboardInterrupt: raise except SystemExit: e = sys.exc_info()[1] # If we have previous errors ensure the exit code is non-zero if exc and e.code == 0: e.code = 1 raise except: exc.handle_exception() if channel == 'log': # Assume any further messages to 'log' will fail. pass else: self.log("Error in %r listener %r" % (channel, listener), level=40, traceback=True) if exc: raise exc return output def _clean_exit(self): """An atexit handler which asserts the Bus is not running.""" if self.state != states.EXITING: warnings.warn( "The main thread is exiting, but the Bus is in the %r state; " "shutting it down automatically now. You must either call " "bus.block() after start(), or call bus.exit() before the " "main thread exits." % self.state, RuntimeWarning) self.exit() def start(self): """Start all services.""" atexit.register(self._clean_exit) self.state = states.STARTING self.log('Bus STARTING') try: self.publish('start') self.state = states.STARTED self.log('Bus STARTED') except (KeyboardInterrupt, SystemExit): raise except: self.log("Shutting down due to error in start listener:", level=40, traceback=True) e_info = sys.exc_info()[1] try: self.exit() except: # Any stop/exit errors will be logged inside publish(). pass # Re-raise the original error raise e_info def exit(self): """Stop all services and prepare to exit the process.""" exitstate = self.state try: self.stop() self.state = states.EXITING self.log('Bus EXITING') self.publish('exit') # This isn't strictly necessary, but it's better than seeing # "Waiting for child threads to terminate..." and then nothing. self.log('Bus EXITED') except: # This method is often called asynchronously (whether thread, # signal handler, console handler, or atexit handler), so we # can't just let exceptions propagate out unhandled. # Assume it's been logged and just die. os._exit(70) # EX_SOFTWARE if exitstate == states.STARTING: # exit() was called before start() finished, possibly due to # Ctrl-C because a start listener got stuck. In this case, # we could get stuck in a loop where Ctrl-C never exits the # process, so we just call os.exit here. os._exit(70) # EX_SOFTWARE def restart(self): """Restart the process (may close connections). This method does not restart the process from the calling thread; instead, it stops the bus and asks the main thread to call execv. """ self.execv = True self.exit() def graceful(self): """Advise all services to reload.""" self.log('Bus graceful') self.publish('graceful') def block(self, interval=0.1): """Wait for the EXITING state, KeyboardInterrupt or SystemExit. This function is intended to be called only by the main thread. After waiting for the EXITING state, it also waits for all threads to terminate, and then calls os.execv if self.execv is True. This design allows another thread to call bus.restart, yet have the main thread perform the actual execv call (required on some platforms). """ try: self.wait(states.EXITING, interval=interval, channel='main') except (KeyboardInterrupt, IOError): # The time.sleep call might raise # "IOError: [Errno 4] Interrupted function call" on KBInt. self.log('Keyboard Interrupt: shutting down bus') self.exit() except SystemExit: self.log('SystemExit raised: shutting down bus') self.exit() raise # Waiting for ALL child threads to finish is necessary on OS X. # See https://github.com/cherrypy/cherrypy/issues/581. # It's also good to let them all shut down before allowing # the main thread to call atexit handlers. # See https://github.com/cherrypy/cherrypy/issues/751. self.log("Waiting for child threads to terminate...") for t in threading.enumerate(): # Validate the we're not trying to join the MainThread # that will cause a deadlock and the case exist when # implemented as a windows service and in any other case # that another thread executes cherrypy.engine.exit() if ( t != threading.currentThread() and t.isAlive() and not isinstance(t, threading._MainThread) ): # Note that any dummy (external) threads are always daemonic. if hasattr(threading.Thread, "daemon"): # Python 2.6+ d = t.daemon else: d = t.isDaemon() if not d: self.log("Waiting for thread %s." % t.getName()) t.join() if self.execv: self._do_execv() def wait(self, state, interval=0.1, channel=None): """Poll for the given state(s) at intervals; publish to channel.""" if isinstance(state, (tuple, list)): states = state else: states = [state] def _wait(): while self.state not in states: time.sleep(interval) self.publish(channel) # From http://psyco.sourceforge.net/psycoguide/bugs.html: # "The compiled machine code does not include the regular polling # done by Python, meaning that a KeyboardInterrupt will not be # detected before execution comes back to the regular Python # interpreter. Your program cannot be interrupted if caught # into an infinite Psyco-compiled loop." try: sys.modules['psyco'].cannotcompile(_wait) except (KeyError, AttributeError): pass _wait() def _do_execv(self): """Re-execute the current process. This must be called from the main thread, because certain platforms (OS X) don't allow execv to be called in a child thread very well. """ args = sys.argv[:] self.log('Re-spawning %s' % ' '.join(args)) if sys.platform[:4] == 'java': from _systemrestart import SystemRestart raise SystemRestart else: args.insert(0, sys.executable) if sys.platform == 'win32': args = ['"%s"' % arg for arg in args] os.chdir(_startup_cwd) if self.max_cloexec_files: self._set_cloexec() os.execv(sys.executable, args) def _set_cloexec(self): """Set the CLOEXEC flag on all open files (except stdin/out/err). If self.max_cloexec_files is an integer (the default), then on platforms which support it, it represents the max open files setting for the operating system. This function will be called just before the process is restarted via os.execv() to prevent open files from persisting into the new process. Set self.max_cloexec_files to 0 to disable this behavior. """ for fd in range(3, self.max_cloexec_files): # skip stdin/out/err try: flags = fcntl.fcntl(fd, fcntl.F_GETFD) except IOError: continue fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) def stop(self): """Stop all services.""" self.state = states.STOPPING self.log('Bus STOPPING') self.publish('stop') self.state = states.STOPPED self.log('Bus STOPPED') def start_with_callback(self, func, args=None, kwargs=None): """Start 'func' in a new thread T, then start self (and return T).""" if args is None: args = () if kwargs is None: kwargs = {} args = (func,) + args def _callback(func, *a, **kw): self.wait(states.STARTED) func(*a, **kw) t = threading.Thread(target=_callback, args=args, kwargs=kwargs) t.setName('Bus Callback ' + t.getName()) t.start() self.start() return t def log(self, msg="", level=20, traceback=False): """Log the given message. Append the last traceback if requested.""" if traceback: msg += "\n" + "".join(_traceback.format_exception(*sys.exc_info())) self.publish('log', msg, level) bus = Bus()
mit
eduNEXT/edx-platform
lms/djangoapps/discussion/rest_api/tests/test_pagination.py
5
2099
""" Tests for Discussion API pagination support """ from unittest import TestCase from django.test import RequestFactory from lms.djangoapps.discussion.rest_api.pagination import DiscussionAPIPagination from lms.djangoapps.discussion.rest_api.tests.utils import make_paginated_api_response class PaginationSerializerTest(TestCase): """Tests for PaginationSerializer""" def do_case(self, objects, page_num, num_pages, expected): """ Make a dummy request, and assert that get_paginated_data with the given parameters returns the expected result """ request = RequestFactory().get("/test") paginator = DiscussionAPIPagination(request, page_num, num_pages) actual = paginator.get_paginated_response(objects) assert actual.data == expected def test_empty(self): self.do_case( [], 1, 0, make_paginated_api_response( results=[], count=0, num_pages=0, next_link=None, previous_link=None ) ) def test_only_page(self): self.do_case( ["foo"], 1, 1, make_paginated_api_response( results=["foo"], count=0, num_pages=1, next_link=None, previous_link=None ) ) def test_first_of_many(self): self.do_case( ["foo"], 1, 3, make_paginated_api_response( results=["foo"], count=0, num_pages=3, next_link="http://testserver/test?page=2", previous_link=None ) ) def test_last_of_many(self): self.do_case( ["foo"], 3, 3, make_paginated_api_response( results=["foo"], count=0, num_pages=3, next_link=None, previous_link="http://testserver/test?page=2" ) ) def test_middle_of_many(self): self.do_case( ["foo"], 2, 3, make_paginated_api_response( results=["foo"], count=0, num_pages=3, next_link="http://testserver/test?page=3", previous_link="http://testserver/test?page=1" ) )
agpl-3.0
nrwahl2/ansible
lib/ansible/modules/windows/win_psexec.py
2
5275
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2017, Dag Wieers <dag@wieers.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/>. ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: win_psexec version_added: '2.3' short_description: Runs commands (remotely) as another (privileged) user description: - Run commands (remotely) through the PsExec service - Run commands as another (domain) user (with elevated privileges) options: command: description: - The command line to run through PsExec (limited to 260 characters). required: true executable: description: - The location of the PsExec utility (in case it is not located in your PATH). default: psexec.exe hostnames: description: - The hostnames to run the command. - If not provided, the command is run locally. username: description: - The (remote) user to run the command as. - If not provided, the current user is used. password: description: - The password for the (remote) user to run the command as. - This is mandatory in order authenticate yourself. chdir: description: - Run the command from this (remote) directory. nobanner: description: - Do not display the startup banner and copyright message. - This only works for specific versions of the PsExec binary. default: 'no' choices: [ 'no', 'yes' ] version_added: '2.4' noprofile: description: - Run the command without loading the account's profile. default: 'no' choices: [ 'no', 'yes' ] elevated: description: - Run the command with elevated privileges. default: 'no' choices: [ 'no', 'yes' ] interactive: description: - Run the program so that it interacts with the desktop on the remote system. default: 'no' choices: [ 'no', 'yes' ] limited: description: - Run the command as limited user (strips the Administrators group and allows only privileges assigned to the Users group). default: 'no' choices: [ 'no', 'yes' ] system: description: - Run the remote command in the System account. default: 'no' choices: [ 'no', 'yes' ] priority: description: - Used to run the command at a different priority. choices: - background - low - belownormal - abovenormal - high - realtime timeout: description: - The connection timeout in seconds wait: description: - Wait for the application to terminate. - Only use for non-interactive applications. default: 'yes' choices: [ 'no', 'yes' ] notes: - More information related to PsExec is available from U(https://technet.microsoft.com/en-us/sysinternals/bb897553.aspx) requirements: [ psexec ] author: Dag Wieers (@dagwieers) ''' EXAMPLES = r''' - name: Test the PsExec connection to the local system (target node) with your user win_psexec: command: whoami.exe - name: Run regedit.exe locally (on target node) as SYSTEM and interactively win_psexec: command: regedit.exe interactive: yes system: yes - name: Run the setup.exe installer on multiple servers using the Domain Administrator win_psexec: command: E:\setup.exe /i /IACCEPTEULA hostnames: - remote_server1 - remote_server2 username: DOMAIN\Administrator password: some_password priority: high - name: Run PsExec from custom location C:\Program Files\sysinternals\ win_psexec: command: netsh advfirewall set allprofiles state off executable: C:\Program Files\sysinternals\psexec.exe hostnames: [ remote_server ] password: some_password priority: low ''' RETURN = r''' cmd: description: The complete command line used by the module, including PsExec call and additional options. returned: always type: string sample: psexec.exe -nobanner \\remote_server -u "DOMAIN\Administrator" -p "some_password" -accepteula E:\setup.exe rc: description: The return code for the command returned: always type: int sample: 0 stdout: description: The standard output from the command returned: always type: string sample: Success. stderr: description: The error output from the command returned: always type: string sample: Error 15 running E:\setup.exe msg: description: Possible error message on failure returned: failed type: string sample: The 'password' parameter is a required parameter. changed: description: Whether or not any changes were made. returned: always type: bool sample: True '''
gpl-3.0
o5k/openerp-oemedical-v0.1
openerp/addons/purchase_double_validation/__openerp__.py
57
1994
# -*- 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/>. # ############################################################################## { 'name' : 'Double Validation on Purchases', 'version' : '1.1', 'category': 'Purchase Management', 'images' : ['images/purchase_validation.jpeg'], 'depends' : ['base','purchase'], 'author' : 'OpenERP SA', 'description': """ Double-validation for purchases exceeding minimum amount. ========================================================= This module modifies the purchase workflow in order to validate purchases that exceeds minimum amount set by configuration wizard. """, 'website': 'http://www.openerp.com', 'data': [ 'purchase_double_validation_workflow.xml', 'purchase_double_validation_installer.xml', 'purchase_double_validation_view.xml', 'board_purchase_view.xml' ], 'test': [ 'test/purchase_double_validation_demo.yml', 'test/purchase_double_validation_test.yml' ], 'demo': [], 'installable': True, 'auto_install': False } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
skg-net/ansible
lib/ansible/modules/network/panos/panos_pg.py
50
5869
#!/usr/bin/python # -*- coding: utf-8 -*- # # Ansible module to manage PaloAltoNetworks Firewall # (c) 2016, techbizdev <techbizdev@paloaltonetworks.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/>. DOCUMENTATION = ''' --- module: panos_pg short_description: create a security profiles group description: - Create a security profile group author: "Luigi Mori (@jtschichold), Ivan Bojer (@ivanbojer)" version_added: "2.3" requirements: - pan-python options: pg_name: description: - name of the security profile group required: true data_filtering: description: - name of the data filtering profile file_blocking: description: - name of the file blocking profile spyware: description: - name of the spyware profile url_filtering: description: - name of the url filtering profile virus: description: - name of the anti-virus profile vulnerability: description: - name of the vulnerability profile wildfire: description: - name of the wildfire analysis profile commit: description: - commit if changed type: bool default: 'yes' extends_documentation_fragment: panos ''' EXAMPLES = ''' - name: setup security profile group panos_pg: ip_address: "192.168.1.1" password: "admin" username: "admin" pg_name: "pg-default" virus: "default" spyware: "default" vulnerability: "default" ''' RETURN = ''' # Default return values ''' ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native try: import pan.xapi from pan.xapi import PanXapiError HAS_LIB = True except ImportError: HAS_LIB = False _PG_XPATH = "/config/devices/entry[@name='localhost.localdomain']" +\ "/vsys/entry[@name='vsys1']" +\ "/profile-group/entry[@name='%s']" def pg_exists(xapi, pg_name): xapi.get(_PG_XPATH % pg_name) e = xapi.element_root.find('.//entry') if e is None: return False return True def add_pg(xapi, pg_name, data_filtering, file_blocking, spyware, url_filtering, virus, vulnerability, wildfire): if pg_exists(xapi, pg_name): return False exml = [] if data_filtering is not None: exml.append('<data-filtering><member>%s</member></data-filtering>' % data_filtering) if file_blocking is not None: exml.append('<file-blocking><member>%s</member></file-blocking>' % file_blocking) if spyware is not None: exml.append('<spyware><member>%s</member></spyware>' % spyware) if url_filtering is not None: exml.append('<url-filtering><member>%s</member></url-filtering>' % url_filtering) if virus is not None: exml.append('<virus><member>%s</member></virus>' % virus) if vulnerability is not None: exml.append('<vulnerability><member>%s</member></vulnerability>' % vulnerability) if wildfire is not None: exml.append('<wildfire-analysis><member>%s</member></wildfire-analysis>' % wildfire) exml = ''.join(exml) xapi.set(xpath=_PG_XPATH % pg_name, element=exml) return True def main(): argument_spec = dict( ip_address=dict(required=True), password=dict(required=True, no_log=True), username=dict(default='admin'), pg_name=dict(required=True), data_filtering=dict(), file_blocking=dict(), spyware=dict(), url_filtering=dict(), virus=dict(), vulnerability=dict(), wildfire=dict(), commit=dict(type='bool', default=True) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_LIB: module.fail_json(msg='pan-python is required for this module') ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] xapi = pan.xapi.PanXapi( hostname=ip_address, api_username=username, api_password=password ) pg_name = module.params['pg_name'] data_filtering = module.params['data_filtering'] file_blocking = module.params['file_blocking'] spyware = module.params['spyware'] url_filtering = module.params['url_filtering'] virus = module.params['virus'] vulnerability = module.params['vulnerability'] wildfire = module.params['wildfire'] commit = module.params['commit'] try: changed = add_pg(xapi, pg_name, data_filtering, file_blocking, spyware, url_filtering, virus, vulnerability, wildfire) if changed and commit: xapi.commit(cmd="<commit></commit>", sync=True, interval=1) except PanXapiError as exc: module.fail_json(msg=to_native(exc)) module.exit_json(changed=changed, msg="okey dokey") if __name__ == '__main__': main()
gpl-3.0
felixjimenez/django
tests/deprecation/tests.py
57
6162
from __future__ import unicode_literals import warnings from django.test.testcases import SimpleTestCase from django.utils import six from django.utils.deprecation import RenameMethodsBase class RenameManagerMethods(RenameMethodsBase): renamed_methods = ( ('old', 'new', PendingDeprecationWarning), ) class RenameMethodsTests(SimpleTestCase): """ Tests the `RenameMethodsBase` type introduced to rename `get_query_set` to `get_queryset` across the code base following #15363. """ def test_class_definition_warnings(self): """ Ensure a warning is raised upon class definition to suggest renaming the faulty method. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('always') class Manager(six.with_metaclass(RenameManagerMethods)): def old(self): pass self.assertEqual(len(recorded), 1) msg = str(recorded[0].message) self.assertEqual(msg, '`Manager.old` method should be renamed `new`.') def test_get_new_defined(self): """ Ensure `old` complains and not `new` when only `new` is defined. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('ignore') class Manager(six.with_metaclass(RenameManagerMethods)): def new(self): pass warnings.simplefilter('always') manager = Manager() manager.new() self.assertEqual(len(recorded), 0) manager.old() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) self.assertEqual(msg, '`Manager.old` is deprecated, use `new` instead.') def test_get_old_defined(self): """ Ensure `old` complains when only `old` is defined. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('ignore') class Manager(six.with_metaclass(RenameManagerMethods)): def old(self): pass warnings.simplefilter('always') manager = Manager() manager.new() self.assertEqual(len(recorded), 0) manager.old() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) self.assertEqual(msg, '`Manager.old` is deprecated, use `new` instead.') def test_deprecated_subclass_renamed(self): """ Ensure the correct warnings are raised when a class that didn't rename `old` subclass one that did. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('ignore') class Renamed(six.with_metaclass(RenameManagerMethods)): def new(self): pass class Deprecated(Renamed): def old(self): super(Deprecated, self).old() warnings.simplefilter('always') deprecated = Deprecated() deprecated.new() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) self.assertEqual(msg, '`Renamed.old` is deprecated, use `new` instead.') recorded[:] = [] deprecated.old() self.assertEqual(len(recorded), 2) msgs = [str(warning.message) for warning in recorded] self.assertEqual(msgs, [ '`Deprecated.old` is deprecated, use `new` instead.', '`Renamed.old` is deprecated, use `new` instead.', ]) def test_renamed_subclass_deprecated(self): """ Ensure the correct warnings are raised when a class that renamed `old` subclass one that didn't. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('ignore') class Deprecated(six.with_metaclass(RenameManagerMethods)): def old(self): pass class Renamed(Deprecated): def new(self): super(Renamed, self).new() warnings.simplefilter('always') renamed = Renamed() renamed.new() self.assertEqual(len(recorded), 0) renamed.old() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) self.assertEqual(msg, '`Renamed.old` is deprecated, use `new` instead.') def test_deprecated_subclass_renamed_and_mixins(self): """ Ensure the correct warnings are raised when a subclass inherit from a class that renamed `old` and mixins that may or may not have renamed `new`. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('ignore') class Renamed(six.with_metaclass(RenameManagerMethods)): def new(self): pass class RenamedMixin(object): def new(self): super(RenamedMixin, self).new() class DeprecatedMixin(object): def old(self): super(DeprecatedMixin, self).old() class Deprecated(DeprecatedMixin, RenamedMixin, Renamed): pass warnings.simplefilter('always') deprecated = Deprecated() deprecated.new() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) self.assertEqual(msg, '`RenamedMixin.old` is deprecated, use `new` instead.') deprecated.old() self.assertEqual(len(recorded), 2) msgs = [str(warning.message) for warning in recorded] self.assertEqual(msgs, [ '`DeprecatedMixin.old` is deprecated, use `new` instead.', '`RenamedMixin.old` is deprecated, use `new` instead.', ])
bsd-3-clause
maxkoryukov/headphones
lib/unidecode/x028.py
253
5069
data = ( ' ', # 0x00 'a', # 0x01 '1', # 0x02 'b', # 0x03 '\'', # 0x04 'k', # 0x05 '2', # 0x06 'l', # 0x07 '@', # 0x08 'c', # 0x09 'i', # 0x0a 'f', # 0x0b '/', # 0x0c 'm', # 0x0d 's', # 0x0e 'p', # 0x0f '"', # 0x10 'e', # 0x11 '3', # 0x12 'h', # 0x13 '9', # 0x14 'o', # 0x15 '6', # 0x16 'r', # 0x17 '^', # 0x18 'd', # 0x19 'j', # 0x1a 'g', # 0x1b '>', # 0x1c 'n', # 0x1d 't', # 0x1e 'q', # 0x1f ',', # 0x20 '*', # 0x21 '5', # 0x22 '<', # 0x23 '-', # 0x24 'u', # 0x25 '8', # 0x26 'v', # 0x27 '.', # 0x28 '%', # 0x29 '[', # 0x2a '$', # 0x2b '+', # 0x2c 'x', # 0x2d '!', # 0x2e '&', # 0x2f ';', # 0x30 ':', # 0x31 '4', # 0x32 '\\', # 0x33 '0', # 0x34 'z', # 0x35 '7', # 0x36 '(', # 0x37 '_', # 0x38 '?', # 0x39 'w', # 0x3a ']', # 0x3b '#', # 0x3c 'y', # 0x3d ')', # 0x3e '=', # 0x3f '[d7]', # 0x40 '[d17]', # 0x41 '[d27]', # 0x42 '[d127]', # 0x43 '[d37]', # 0x44 '[d137]', # 0x45 '[d237]', # 0x46 '[d1237]', # 0x47 '[d47]', # 0x48 '[d147]', # 0x49 '[d247]', # 0x4a '[d1247]', # 0x4b '[d347]', # 0x4c '[d1347]', # 0x4d '[d2347]', # 0x4e '[d12347]', # 0x4f '[d57]', # 0x50 '[d157]', # 0x51 '[d257]', # 0x52 '[d1257]', # 0x53 '[d357]', # 0x54 '[d1357]', # 0x55 '[d2357]', # 0x56 '[d12357]', # 0x57 '[d457]', # 0x58 '[d1457]', # 0x59 '[d2457]', # 0x5a '[d12457]', # 0x5b '[d3457]', # 0x5c '[d13457]', # 0x5d '[d23457]', # 0x5e '[d123457]', # 0x5f '[d67]', # 0x60 '[d167]', # 0x61 '[d267]', # 0x62 '[d1267]', # 0x63 '[d367]', # 0x64 '[d1367]', # 0x65 '[d2367]', # 0x66 '[d12367]', # 0x67 '[d467]', # 0x68 '[d1467]', # 0x69 '[d2467]', # 0x6a '[d12467]', # 0x6b '[d3467]', # 0x6c '[d13467]', # 0x6d '[d23467]', # 0x6e '[d123467]', # 0x6f '[d567]', # 0x70 '[d1567]', # 0x71 '[d2567]', # 0x72 '[d12567]', # 0x73 '[d3567]', # 0x74 '[d13567]', # 0x75 '[d23567]', # 0x76 '[d123567]', # 0x77 '[d4567]', # 0x78 '[d14567]', # 0x79 '[d24567]', # 0x7a '[d124567]', # 0x7b '[d34567]', # 0x7c '[d134567]', # 0x7d '[d234567]', # 0x7e '[d1234567]', # 0x7f '[d8]', # 0x80 '[d18]', # 0x81 '[d28]', # 0x82 '[d128]', # 0x83 '[d38]', # 0x84 '[d138]', # 0x85 '[d238]', # 0x86 '[d1238]', # 0x87 '[d48]', # 0x88 '[d148]', # 0x89 '[d248]', # 0x8a '[d1248]', # 0x8b '[d348]', # 0x8c '[d1348]', # 0x8d '[d2348]', # 0x8e '[d12348]', # 0x8f '[d58]', # 0x90 '[d158]', # 0x91 '[d258]', # 0x92 '[d1258]', # 0x93 '[d358]', # 0x94 '[d1358]', # 0x95 '[d2358]', # 0x96 '[d12358]', # 0x97 '[d458]', # 0x98 '[d1458]', # 0x99 '[d2458]', # 0x9a '[d12458]', # 0x9b '[d3458]', # 0x9c '[d13458]', # 0x9d '[d23458]', # 0x9e '[d123458]', # 0x9f '[d68]', # 0xa0 '[d168]', # 0xa1 '[d268]', # 0xa2 '[d1268]', # 0xa3 '[d368]', # 0xa4 '[d1368]', # 0xa5 '[d2368]', # 0xa6 '[d12368]', # 0xa7 '[d468]', # 0xa8 '[d1468]', # 0xa9 '[d2468]', # 0xaa '[d12468]', # 0xab '[d3468]', # 0xac '[d13468]', # 0xad '[d23468]', # 0xae '[d123468]', # 0xaf '[d568]', # 0xb0 '[d1568]', # 0xb1 '[d2568]', # 0xb2 '[d12568]', # 0xb3 '[d3568]', # 0xb4 '[d13568]', # 0xb5 '[d23568]', # 0xb6 '[d123568]', # 0xb7 '[d4568]', # 0xb8 '[d14568]', # 0xb9 '[d24568]', # 0xba '[d124568]', # 0xbb '[d34568]', # 0xbc '[d134568]', # 0xbd '[d234568]', # 0xbe '[d1234568]', # 0xbf '[d78]', # 0xc0 '[d178]', # 0xc1 '[d278]', # 0xc2 '[d1278]', # 0xc3 '[d378]', # 0xc4 '[d1378]', # 0xc5 '[d2378]', # 0xc6 '[d12378]', # 0xc7 '[d478]', # 0xc8 '[d1478]', # 0xc9 '[d2478]', # 0xca '[d12478]', # 0xcb '[d3478]', # 0xcc '[d13478]', # 0xcd '[d23478]', # 0xce '[d123478]', # 0xcf '[d578]', # 0xd0 '[d1578]', # 0xd1 '[d2578]', # 0xd2 '[d12578]', # 0xd3 '[d3578]', # 0xd4 '[d13578]', # 0xd5 '[d23578]', # 0xd6 '[d123578]', # 0xd7 '[d4578]', # 0xd8 '[d14578]', # 0xd9 '[d24578]', # 0xda '[d124578]', # 0xdb '[d34578]', # 0xdc '[d134578]', # 0xdd '[d234578]', # 0xde '[d1234578]', # 0xdf '[d678]', # 0xe0 '[d1678]', # 0xe1 '[d2678]', # 0xe2 '[d12678]', # 0xe3 '[d3678]', # 0xe4 '[d13678]', # 0xe5 '[d23678]', # 0xe6 '[d123678]', # 0xe7 '[d4678]', # 0xe8 '[d14678]', # 0xe9 '[d24678]', # 0xea '[d124678]', # 0xeb '[d34678]', # 0xec '[d134678]', # 0xed '[d234678]', # 0xee '[d1234678]', # 0xef '[d5678]', # 0xf0 '[d15678]', # 0xf1 '[d25678]', # 0xf2 '[d125678]', # 0xf3 '[d35678]', # 0xf4 '[d135678]', # 0xf5 '[d235678]', # 0xf6 '[d1235678]', # 0xf7 '[d45678]', # 0xf8 '[d145678]', # 0xf9 '[d245678]', # 0xfa '[d1245678]', # 0xfb '[d345678]', # 0xfc '[d1345678]', # 0xfd '[d2345678]', # 0xfe '[d12345678]', # 0xff )
gpl-3.0
bd808/striker
striker/goals/signals/handlers.py
1
2134
# -*- coding: utf-8 -*- # # Copyright (c) 2016 Wikimedia Foundation and contributors. # All Rights Reserved. # # This file is part of Striker. # # Striker 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. # # Striker 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 Striker. If not, see <http://www.gnu.org/licenses/>. import logging from django.conf import settings from django.contrib.auth.signals import user_logged_in from django.db.models.signals import post_save from django.dispatch import receiver from striker.goals import GOALS logger = logging.getLogger(__name__) def check_goal_phab(user): if user.phabname is not None: user.milestones.recordMilestone(GOALS['ACCOUNT_PHAB']) def check_goal_sul(user): if user.oauthtoken is not None: user.milestones.recordMilestone(GOALS['ACCOUNT_SUL']) @receiver(user_logged_in, dispatch_uid=__name__) def on_user_login(sender, request, user, **kwargs): check_goal_phab(user) check_goal_sul(user) groups = user.groups.values_list('name', flat=True) if settings.TOOLS_TOOL_LABS_GROUP_NAME in groups: user.milestones.recordMilestone(GOALS['TOOL_MEMBER']) for g in groups: if g.startswith('tools.'): user.milestones.recordMilestone(GOALS['TOOL_MAINTAINER']) break @receiver(post_save, sender=settings.AUTH_USER_MODEL, dispatch_uid=__name__) def on_user_save(sender, instance, **kwargs): check_goal_phab(instance) check_goal_sul(instance) @receiver( post_save, sender='tools.DiffusionRepo', dispatch_uid=__name__) def on_diffusion_save(sender, instance, **kwargs): instance.created_by.milestones.recordMilestone(GOALS['TOOL_GIT'])
gpl-3.0
40223136/20150616test1
static/Brython3.1.1-20150328-091302/Lib/site-packages/pygame/version.py
607
1334
## pygame - Python Game Library ## Copyright (C) 2000-2003 Pete Shinners ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Library General Public ## License as published by the Free Software Foundation; either ## version 2 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 ## Library General Public License for more details. ## ## You should have received a copy of the GNU Library General Public ## License along with this library; if not, write to the Free ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ## ## Pete Shinners ## pete@shinners.org """Simply the current installed pygame version. The version information is stored in the regular pygame module as 'pygame.ver'. Keeping the version information also available in a separate module allows you to test the pygame version without importing the main pygame module. The python version information should always compare greater than any previous releases. (hmm, until we get to versions > 10) """ ver = '1.8.0pre' vernum = 1,8,0
gpl-3.0
virtualopensystems/nova
nova/tests/virt/vmwareapi/test_vmops.py
1
39671
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import copy import mock from nova.compute import power_state from nova import context from nova import exception from nova.network import model as network_model from nova import objects from nova.openstack.common import units from nova.openstack.common import uuidutils from nova import test from nova.tests import fake_instance import nova.tests.image.fake from nova.tests.virt.vmwareapi import fake as vmwareapi_fake from nova.tests.virt.vmwareapi import stubs from nova.virt.vmwareapi import constants from nova.virt.vmwareapi import driver from nova.virt.vmwareapi import ds_util from nova.virt.vmwareapi import error_util from nova.virt.vmwareapi import vim_util from nova.virt.vmwareapi import vm_util from nova.virt.vmwareapi import vmops from nova.virt.vmwareapi import vmware_images class VMwareVMOpsSimpleTestCase(test.NoDBTestCase): @mock.patch.object(vm_util, 'get_res_pool_ref') @mock.patch.object(ds_util, 'get_datastore') @mock.patch.object(vmops.VMwareVMOps, 'get_datacenter_ref_and_name') def test_spawn_disk_invalid_disk_size(self, mock_get_datacenter_ref_and_name, mock_get_datastore, mock_get_res_pool_ref): image = { 'id': 'c1c8ce3d-c2e0-4247-890c-ccf5cc1c004c', 'disk_format': 'vmdk', 'size': 999999999 * units.Gi, } self._context = context.RequestContext('fake_user', 'fake_project') instance = fake_instance.fake_instance_obj(self._context, image_ref=nova.tests.image.fake.get_valid_image_id(), uuid='fake_uuid', root_gb=1, node='respool-1001(MyResPoolName)' ) ops = vmops.VMwareVMOps(mock.Mock(), mock.Mock(), mock.Mock()) self.assertRaises(exception.InstanceUnacceptable, ops.spawn, mock.Mock(), instance, image, injected_files=[], admin_password=None, network_info=None, block_device_info=None) class VMwareVMOpsTestCase(test.NoDBTestCase): def setUp(self): super(VMwareVMOpsTestCase, self).setUp() vmwareapi_fake.reset() stubs.set_stubs(self.stubs) self.flags(image_cache_subdirectory_name='vmware_base', my_ip='', flat_injected=True, vnc_enabled=True) self._context = context.RequestContext('fake_user', 'fake_project') self._session = driver.VMwareAPISession() self._virtapi = mock.Mock() self._vmops = vmops.VMwareVCVMOps(self._session, self._virtapi, None) self._image_id = nova.tests.image.fake.get_valid_image_id() self._instance_values = { 'name': 'fake_name', 'uuid': 'fake_uuid', 'vcpus': 1, 'memory_mb': 512, 'image_ref': self._image_id, 'root_gb': 10, 'node': 'respool-1001(MyResPoolName)' } self._instance = fake_instance.fake_instance_obj( self._context, **self._instance_values) fake_ds_ref = vmwareapi_fake.ManagedObjectReference('fake-ds') self._ds = ds_util.Datastore( ref=fake_ds_ref, name='fake_ds', capacity=10 * units.Gi, freespace=10 * units.Gi) self._dc_info = vmops.DcInfo( ref='fake_dc_ref', name='fake_dc', vmFolder='fake_vm_folder') subnet_4 = network_model.Subnet(cidr='192.168.0.1/24', dns=[network_model.IP('192.168.0.1')], gateway= network_model.IP('192.168.0.1'), ips=[ network_model.IP('192.168.0.100')], routes=None) subnet_6 = network_model.Subnet(cidr='dead:beef::1/64', dns=None, gateway= network_model.IP('dead:beef::1'), ips=[network_model.IP( 'dead:beef::dcad:beff:feef:0')], routes=None) network = network_model.Network(id=0, bridge='fa0', label='fake', subnets=[subnet_4, subnet_6], vlan=None, bridge_interface=None, injected=True) self._network_values = { 'id': None, 'address': 'DE:AD:BE:EF:00:00', 'network': network, 'type': None, 'devname': None, 'ovs_interfaceid': None, 'rxtx_cap': 3 } self.network_info = network_model.NetworkInfo([ network_model.VIF(**self._network_values) ]) pure_IPv6_network = network_model.Network(id=0, bridge='fa0', label='fake', subnets=[subnet_6], vlan=None, bridge_interface=None, injected=True) self.pure_IPv6_network_info = network_model.NetworkInfo([ network_model.VIF(id=None, address='DE:AD:BE:EF:00:00', network=pure_IPv6_network, type=None, devname=None, ovs_interfaceid=None, rxtx_cap=3) ]) def test_get_machine_id_str(self): result = vmops.VMwareVMOps._get_machine_id_str(self.network_info) self.assertEqual(result, 'DE:AD:BE:EF:00:00;192.168.0.100;255.255.255.0;' '192.168.0.1;192.168.0.255;192.168.0.1#') result = vmops.VMwareVMOps._get_machine_id_str( self.pure_IPv6_network_info) self.assertEqual('DE:AD:BE:EF:00:00;;;;;#', result) def _setup_create_folder_mocks(self): ops = vmops.VMwareVMOps(mock.Mock(), mock.Mock(), mock.Mock()) base_name = 'folder' ds_name = "datastore" ds_ref = mock.Mock() ds_ref.value = 1 dc_ref = mock.Mock() ops._datastore_dc_mapping[ds_ref.value] = vmops.DcInfo( ref=dc_ref, name='fake-name', vmFolder='fake-folder') path = ds_util.DatastorePath(ds_name, base_name) ds_util.mkdir = mock.Mock() return ds_name, ds_ref, ops, path, dc_ref def test_create_folder_if_missing(self): ds_name, ds_ref, ops, path, dc = self._setup_create_folder_mocks() ops._create_folder_if_missing(ds_name, ds_ref, 'folder') ds_util.mkdir.assert_called_with(ops._session, path, dc) def test_create_folder_if_missing_exception(self): ds_name, ds_ref, ops, path, dc = self._setup_create_folder_mocks() ds_util.mkdir.side_effect = error_util.FileAlreadyExistsException() ops._create_folder_if_missing(ds_name, ds_ref, 'folder') ds_util.mkdir.assert_called_with(ops._session, path, dc) @mock.patch.object(ds_util, 'file_exists', return_value=True) def test_check_if_folder_file_exists_with_existing(self, mock_exists): ops = vmops.VMwareVMOps(mock.Mock(), mock.Mock(), mock.Mock()) ops._create_folder_if_missing = mock.Mock() mock_ds_ref = mock.Mock() ops._check_if_folder_file_exists(mock.Mock(), mock_ds_ref, "datastore", "folder", "some_file") ops._create_folder_if_missing.assert_called_once_with('datastore', mock_ds_ref, 'vmware_base') @mock.patch.object(ds_util, 'file_exists', return_value=False) def test_check_if_folder_file_exists_no_existing(self, mock_exists): ops = vmops.VMwareVMOps(mock.Mock(), mock.Mock(), mock.Mock()) ops._create_folder_if_missing = mock.Mock() mock_ds_ref = mock.Mock() ops._check_if_folder_file_exists(mock.Mock(), mock_ds_ref, "datastore", "folder", "some_file") ops._create_folder_if_missing.assert_called_once_with('datastore', mock_ds_ref, 'vmware_base') def test_get_valid_vms_from_retrieve_result(self): ops = vmops.VMwareVMOps(mock.Mock(), mock.Mock(), mock.Mock()) fake_objects = vmwareapi_fake.FakeRetrieveResult() fake_objects.add_object(vmwareapi_fake.VirtualMachine()) fake_objects.add_object(vmwareapi_fake.VirtualMachine()) fake_objects.add_object(vmwareapi_fake.VirtualMachine()) vms = ops._get_valid_vms_from_retrieve_result(fake_objects) self.assertEqual(3, len(vms)) def test_get_valid_vms_from_retrieve_result_with_invalid(self): ops = vmops.VMwareVMOps(mock.Mock(), mock.Mock(), mock.Mock()) fake_objects = vmwareapi_fake.FakeRetrieveResult() fake_objects.add_object(vmwareapi_fake.VirtualMachine()) invalid_vm1 = vmwareapi_fake.VirtualMachine() invalid_vm1.set('runtime.connectionState', 'orphaned') invalid_vm2 = vmwareapi_fake.VirtualMachine() invalid_vm2.set('runtime.connectionState', 'inaccessible') fake_objects.add_object(invalid_vm1) fake_objects.add_object(invalid_vm2) vms = ops._get_valid_vms_from_retrieve_result(fake_objects) self.assertEqual(1, len(vms)) def test_delete_vm_snapshot(self): def fake_call_method(module, method, *args, **kwargs): self.assertEqual('RemoveSnapshot_Task', method) self.assertEqual(args[0], "fake_vm_snapshot") self.assertEqual(kwargs['removeChildren'], False) self.assertEqual(kwargs['consolidate'], True) return 'fake_remove_snapshot_task' with contextlib.nested( mock.patch.object(self._session, '_wait_for_task'), mock.patch.object(self._session, '_call_method', fake_call_method) ) as (_wait_for_task, _call_method): self._vmops._delete_vm_snapshot(self._instance, "fake_vm_ref", "fake_vm_snapshot") _wait_for_task.assert_has_calls([ mock.call('fake_remove_snapshot_task')]) def test_create_vm_snapshot(self): method_list = ['CreateSnapshot_Task', 'get_dynamic_property'] def fake_call_method(module, method, *args, **kwargs): expected_method = method_list.pop(0) self.assertEqual(expected_method, method) if (expected_method == 'CreateSnapshot_Task'): self.assertEqual(args[0], "fake_vm_ref") self.assertEqual(kwargs['memory'], False) self.assertEqual(kwargs['quiesce'], True) return 'fake_snapshot_task' elif (expected_method == 'get_dynamic_property'): task_info = mock.Mock() task_info.result = "fake_snapshot_ref" self.assertEqual(('fake_snapshot_task', 'Task', 'info'), args) return task_info with contextlib.nested( mock.patch.object(self._session, '_wait_for_task'), mock.patch.object(self._session, '_call_method', fake_call_method) ) as (_wait_for_task, _call_method): snap = self._vmops._create_vm_snapshot(self._instance, "fake_vm_ref") self.assertEqual("fake_snapshot_ref", snap) _wait_for_task.assert_has_calls([ mock.call('fake_snapshot_task')]) def test_update_instance_progress(self): instance = objects.Instance(context=mock.MagicMock(), uuid='fake-uuid') with mock.patch.object(instance, 'save') as mock_save: self._vmops._update_instance_progress(instance._context, instance, 5, 10) mock_save.assert_called_once_with() self.assertEqual(50, instance.progress) @mock.patch('nova.virt.vmwareapi.vm_util.get_vm_ref', return_value='fake_ref') def test_get_info(self, mock_get_vm_ref): props = ['summary.config.numCpu', 'summary.config.memorySizeMB', 'runtime.powerState'] prop_cpu = vmwareapi_fake.Prop(props[0], 4) prop_mem = vmwareapi_fake.Prop(props[1], 128) prop_state = vmwareapi_fake.Prop(props[2], 'poweredOn') prop_list = [prop_state, prop_mem, prop_cpu] obj_content = vmwareapi_fake.ObjectContent(None, prop_list=prop_list) result = vmwareapi_fake.FakeRetrieveResult() result.add_object(obj_content) mock_call_method = mock.Mock(return_value=result) with mock.patch.object(self._session, '_call_method', mock_call_method): info = self._vmops.get_info(self._instance) mock_call_method.assert_called_once_with(vim_util, 'get_object_properties', None, 'fake_ref', 'VirtualMachine', props) mock_get_vm_ref.assert_called_once_with(self._session, self._instance) self.assertEqual(power_state.RUNNING, info['state']) self.assertEqual(128 * 1024, info['max_mem']) self.assertEqual(128 * 1024, info['mem']) self.assertEqual(4, info['num_cpu']) self.assertEqual(0, info['cpu_time']) def _test_get_datacenter_ref_and_name(self, ds_ref_exists=False): instance_ds_ref = mock.Mock() instance_ds_ref.value = "ds-1" _vcvmops = vmops.VMwareVCVMOps(self._session, None, None) if ds_ref_exists: ds_ref = mock.Mock() ds_ref.value = "ds-1" else: ds_ref = None def fake_call_method(module, method, *args, **kwargs): fake_object1 = vmwareapi_fake.FakeRetrieveResult() fake_object1.add_object(vmwareapi_fake.Datacenter( ds_ref=ds_ref)) if not ds_ref: # Token is set for the fake_object1, so it will continue to # fetch the next object. setattr(fake_object1, 'token', 'token-0') if method == "continue_to_get_objects": fake_object2 = vmwareapi_fake.FakeRetrieveResult() fake_object2.add_object(vmwareapi_fake.Datacenter()) return fake_object2 return fake_object1 with mock.patch.object(self._session, '_call_method', side_effect=fake_call_method) as fake_call: dc_info = _vcvmops.get_datacenter_ref_and_name(instance_ds_ref) if ds_ref: self.assertEqual(1, len(_vcvmops._datastore_dc_mapping)) fake_call.assert_called_once_with(vim_util, "get_objects", "Datacenter", ["name", "datastore", "vmFolder"]) self.assertEqual("ha-datacenter", dc_info.name) else: calls = [mock.call(vim_util, "get_objects", "Datacenter", ["name", "datastore", "vmFolder"]), mock.call(vim_util, "continue_to_get_objects", "token-0")] fake_call.assert_has_calls(calls) self.assertIsNone(dc_info) def test_get_datacenter_ref_and_name(self): self._test_get_datacenter_ref_and_name(ds_ref_exists=True) def test_get_datacenter_ref_and_name_with_no_datastore(self): self._test_get_datacenter_ref_and_name() def test_unrescue_power_on(self): self._test_unrescue(True) def test_unrescue_power_off(self): self._test_unrescue(False) def _test_unrescue(self, power_on): self._vmops._volumeops = mock.Mock() vm_rescue_ref = mock.Mock() vm_ref = mock.Mock() args_list = [(vm_ref, 'VirtualMachine', 'config.hardware.device'), (vm_rescue_ref, 'VirtualMachine', 'config.hardware.device')] def fake_call_method(module, method, *args, **kwargs): expected_args = args_list.pop(0) self.assertEqual('get_dynamic_property', method) self.assertEqual(expected_args, args) path = mock.Mock() path_and_type = (path, mock.Mock(), mock.Mock()) r_instance = copy.deepcopy(self._instance) with contextlib.nested( mock.patch.object(vm_util, 'get_vmdk_path_and_adapter_type', return_value=path_and_type), mock.patch.object(vm_util, 'get_vmdk_volume_disk'), mock.patch.object(vm_util, 'power_on_instance'), mock.patch.object(vm_util, 'get_vm_ref', return_value=vm_ref), mock.patch.object(vm_util, 'get_vm_ref_from_name', return_value=vm_rescue_ref), mock.patch.object(self._session, '_call_method', fake_call_method), mock.patch.object(vm_util, 'power_off_instance'), mock.patch.object(self._vmops, '_destroy_instance'), mock.patch.object(copy, 'deepcopy', return_value=r_instance) ) as (_get_vmdk_path_and_adapter_type, _get_vmdk_volume_disk, _power_on_instance, _get_vm_ref, _get_vm_ref_from_name, _call_method, _power_off, _destroy_instance, _deep_copy): self._vmops.unrescue(self._instance, power_on=power_on) _get_vmdk_path_and_adapter_type.assert_called_once_with( None, uuid='fake_uuid') _get_vmdk_volume_disk.assert_called_once_with(None, path=path) if power_on: _power_on_instance.assert_called_once_with(self._session, self._instance, vm_ref=vm_ref) else: self.assertFalse(_power_on_instance.called) _get_vm_ref.assert_called_once_with(self._session, self._instance) _get_vm_ref_from_name.assert_called_once_with(self._session, 'fake_uuid-rescue') _power_off.assert_called_once_with(self._session, r_instance, vm_rescue_ref) _destroy_instance.assert_called_once_with(r_instance, instance_name='fake_uuid-rescue') def _test_finish_migration(self, power_on=True, resize_instance=False): """Tests the finish_migration method on vmops.""" if resize_instance: self._instance.system_metadata = {'old_instance_type_root_gb': '0'} datastore = ds_util.Datastore(ref='fake-ref', name='fake') dc_info = vmops.DcInfo(ref='fake_ref', name='fake', vmFolder='fake_folder') with contextlib.nested( mock.patch.object(self._session, "_call_method", return_value='fake-task'), mock.patch.object(self._vmops, "_update_instance_progress"), mock.patch.object(self._session, "_wait_for_task"), mock.patch.object(vm_util, "get_vm_resize_spec", return_value='fake-spec'), mock.patch.object(ds_util, "get_datastore", return_value=datastore), mock.patch.object(self._vmops, 'get_datacenter_ref_and_name', return_value=dc_info), mock.patch.object(self._vmops, '_extend_virtual_disk'), mock.patch.object(vm_util, "power_on_instance") ) as (fake_call_method, fake_update_instance_progress, fake_wait_for_task, fake_vm_resize_spec, fake_get_datastore, fake_get_datacenter_ref_and_name, fake_extend_virtual_disk, fake_power_on): self._vmops.finish_migration(context=self._context, migration=None, instance=self._instance, disk_info=None, network_info=None, block_device_info=None, resize_instance=resize_instance, image_meta=None, power_on=power_on) if resize_instance: fake_vm_resize_spec.assert_called_once_with( self._session._get_vim().client.factory, self._instance) fake_call_method.assert_has_calls(mock.call( self._session._get_vim(), "ReconfigVM_Task", 'f', spec='fake-spec')) fake_wait_for_task.assert_called_once_with('fake-task') fake_extend_virtual_disk.assert_called_once_with( self._instance, self._instance['root_gb'] * units.Mi, None, dc_info.ref) else: self.assertFalse(fake_vm_resize_spec.called) self.assertFalse(fake_wait_for_task.called) self.assertFalse(fake_extend_virtual_disk.called) if power_on: fake_power_on.assert_called_once_with(self._session, self._instance, vm_ref='f') else: self.assertFalse(fake_power_on.called) fake_update_instance_progress.called_once_with( self._context, self._instance, 4, vmops.RESIZE_TOTAL_STEPS) def test_finish_migration_power_on(self): self._test_finish_migration(power_on=True, resize_instance=False) def test_finish_migration_power_off(self): self._test_finish_migration(power_on=False, resize_instance=False) def test_finish_migration_power_on_resize(self): self._test_finish_migration(power_on=True, resize_instance=True) @mock.patch.object(vm_util, 'associate_vmref_for_instance') @mock.patch.object(vm_util, 'power_on_instance') def _test_finish_revert_migration(self, fake_power_on, fake_associate_vmref, power_on): """Tests the finish_revert_migration method on vmops.""" # setup the test instance in the database self._vmops.finish_revert_migration(self._context, instance=self._instance, network_info=None, block_device_info=None, power_on=power_on) fake_associate_vmref.assert_called_once_with(self._session, self._instance, suffix='-orig') if power_on: fake_power_on.assert_called_once_with(self._session, self._instance) else: self.assertFalse(fake_power_on.called) def test_finish_revert_migration_power_on(self): self._test_finish_revert_migration(power_on=True) def test_finish_revert_migration_power_off(self): self._test_finish_revert_migration(power_on=False) @mock.patch.object(vmops.VMwareVMOps, '_attach_cdrom_to_vm') @mock.patch.object(vmops.VMwareVMOps, '_create_config_drive') def test_configure_config_drive(self, mock_create_config_drive, mock_attach_cdrom_to_vm): injected_files = mock.Mock() admin_password = mock.Mock() vm_ref = mock.Mock() mock_create_config_drive.return_value = "fake_iso_path" self._vmops._configure_config_drive( self._instance, vm_ref, self._dc_info, self._ds, injected_files, admin_password) upload_iso_path = self._ds.build_path("fake_iso_path") mock_create_config_drive.assert_called_once_with(self._instance, injected_files, admin_password, self._ds.name, self._dc_info.name, self._instance.uuid, "Fake-CookieJar") mock_attach_cdrom_to_vm.assert_called_once_with( vm_ref, self._instance, self._ds.ref, str(upload_iso_path)) @mock.patch.object(vmops.LOG, 'debug') @mock.patch('nova.virt.vmwareapi.volumeops.VMwareVolumeOps' '.attach_root_volume') def test_spawn_mask_block_device_info_password(self, mock_attach_root_volume, mock_debug): # Very simple test that just ensures block_device_info auth_password # is masked when logged; the rest of the test just fails out early. data = {'auth_password': 'scrubme'} bdm = [{'connection_info': {'data': data}}] bdi = {'block_device_mapping': bdm} self.password_logged = False # Tests that the parameters to the to_xml method are sanitized for # passwords when logged. def fake_debug(*args, **kwargs): if 'auth_password' in args[0]: self.password_logged = True self.assertNotIn('scrubme', args[0]) mock_debug.side_effect = fake_debug self.flags(flat_injected=False, vnc_enabled=False) mock_attach_root_volume.side_effect = Exception # Call spawn(). We don't care what it does as long as it generates # the log message, which we check below. try: self._vmops.spawn( self._context, self._instance, {}, injected_files=None, admin_password=None, network_info=[], block_device_info=bdi ) except Exception: pass # Check that the relevant log message was generated, and therefore # that we checked it was scrubbed self.assertTrue(self.password_logged) def test_get_ds_browser(self): cache = self._vmops._datastore_browser_mapping ds_browser = mock.Mock() moref = vmwareapi_fake.ManagedObjectReference('datastore-100') self.assertIsNone(cache.get(moref.value)) mock_call_method = mock.Mock(return_value=ds_browser) with mock.patch.object(self._session, '_call_method', mock_call_method): ret = self._vmops._get_ds_browser(moref) mock_call_method.assert_called_once_with(vim_util, 'get_dynamic_property', moref, 'Datastore', 'browser') self.assertIs(ds_browser, ret) self.assertIs(ds_browser, cache.get(moref.value)) def _verify_spawn_method_calls(self, mock_call_method): # TODO(vui): More explicit assertions of spawn() behavior # are waiting on additional refactoring pertaining to image # handling/manipulation. Till then, we continue to assert on the # sequence of VIM operations invoked. expected_methods = ['get_dynamic_property', 'SearchDatastore_Task', 'SearchDatastore_Task', 'CreateVirtualDisk_Task', 'DeleteDatastoreFile_Task', 'MoveDatastoreFile_Task', 'DeleteDatastoreFile_Task', 'SearchDatastore_Task', 'ExtendVirtualDisk_Task', ] recorded_methods = [c[1][1] for c in mock_call_method.mock_calls] self.assertEqual(expected_methods, recorded_methods) @mock.patch('nova.virt.vmwareapi.ds_util.get_datastore') @mock.patch( 'nova.virt.vmwareapi.vmops.VMwareVCVMOps.get_datacenter_ref_and_name') @mock.patch('nova.virt.vmwareapi.vm_util.get_mo_id_from_instance', return_value='fake_node_mo_id') @mock.patch('nova.virt.vmwareapi.vm_util.get_res_pool_ref', return_value='fake_rp_ref') @mock.patch('nova.virt.vmwareapi.vif.get_vif_info', return_value=[]) @mock.patch('nova.utils.is_neutron', return_value=False) @mock.patch('nova.virt.vmwareapi.vm_util.get_vm_create_spec', return_value='fake_create_spec') @mock.patch('nova.virt.vmwareapi.vm_util.create_vm', return_value='fake_vm_ref') @mock.patch('nova.virt.vmwareapi.ds_util.mkdir') @mock.patch('nova.virt.vmwareapi.vmops.VMwareVMOps._set_machine_id') @mock.patch('nova.virt.vmwareapi.vm_util.get_vnc_port', return_value=5900) @mock.patch('nova.virt.vmwareapi.vmops.VMwareVMOps._set_vnc_config') @mock.patch('nova.virt.vmwareapi.vm_util.power_on_instance') @mock.patch('nova.virt.vmwareapi.vm_util.copy_virtual_disk') # TODO(dims): Need to add tests for create_virtual_disk after the # disk/image code in spawn gets refactored def _test_spawn(self, mock_copy_virtual_disk, mock_power_on_instance, mock_set_vnc_config, mock_get_vnc_port, mock_set_machine_id, mock_mkdir, mock_create_vm, mock_get_create_spec, mock_is_neutron, mock_get_vif_info, mock_get_res_pool_ref, mock_get_mo_id_for_instance, mock_get_datacenter_ref_and_name, mock_get_datastore, block_device_info=None, power_on=True): self._vmops._volumeops = mock.Mock() image = { 'id': 'fake-image-d', 'disk_format': 'vmdk', 'size': 1 * units.Gi, } network_info = mock.Mock() mock_get_datastore.return_value = self._ds mock_get_datacenter_ref_and_name.return_value = self._dc_info mock_call_method = mock.Mock(return_value='fake_task') with contextlib.nested( mock.patch.object(self._session, '_wait_for_task'), mock.patch.object(self._session, '_call_method', mock_call_method), mock.patch.object(uuidutils, 'generate_uuid', return_value='tmp-uuid'), mock.patch.object(vmware_images, 'fetch_image') ) as (_wait_for_task, _call_method, _generate_uuid, _fetch_image): self._vmops.spawn(self._context, self._instance, image, injected_files='fake_files', admin_password='password', network_info=network_info, block_device_info=block_device_info, power_on=power_on) mock_is_neutron.assert_called_once_with() expected_mkdir_calls = 3 if block_device_info and len(block_device_info.get( 'block_device_mapping', [])) > 0: # if block_device_info contains key 'block_device_mapping' # with any information, method mkdir wouldn't be called in # method self._vmops.spawn() expected_mkdir_calls = 0 self.assertEqual(expected_mkdir_calls, len(mock_mkdir.mock_calls)) mock_get_vnc_port.assert_called_once_with(self._session) mock_get_mo_id_for_instance.assert_called_once_with(self._instance) mock_get_res_pool_ref.assert_called_once_with( self._session, None, 'fake_node_mo_id') mock_get_vif_info.assert_called_once_with( self._session, None, False, constants.DEFAULT_VIF_MODEL, network_info) mock_get_create_spec.assert_called_once_with( self._session._get_vim().client.factory, self._instance, 'fake_uuid', 'fake_ds', [], 'otherGuest') mock_create_vm.assert_called_once_with( self._session, self._instance, 'fake_vm_folder', 'fake_create_spec', 'fake_rp_ref') mock_set_vnc_config.assert_called_once_with( self._session._get_vim().client.factory, self._instance, 5900) mock_set_machine_id.assert_called_once_with( self._session._get_vim().client.factory, self._instance, network_info) if power_on: mock_power_on_instance.assert_called_once_with( self._session, self._instance, vm_ref='fake_vm_ref') else: self.assertFalse(mock_power_on_instance.called) if block_device_info: root_disk = block_device_info['block_device_mapping'][0] mock_attach = self._vmops._volumeops.attach_root_volume mock_attach.assert_called_once_with( root_disk['connection_info'], self._instance, 'vda', self._ds.ref) self.assertFalse(_wait_for_task.called) self.assertFalse(_fetch_image.called) self.assertFalse(_call_method.called) else: upload_file_name = 'vmware_temp/tmp-uuid/%s/%s-flat.vmdk' % ( self._image_id, self._image_id) _fetch_image.assert_called_once_with( self._context, self._instance, self._session._host_ip, self._dc_info.name, self._ds.name, upload_file_name, cookies='Fake-CookieJar') self.assertTrue(len(_wait_for_task.mock_calls) > 0) self._verify_spawn_method_calls(_call_method) dc_ref = 'fake_dc_ref' source_file = unicode('[fake_ds] vmware_base/%s/%s.vmdk' % (self._image_id, self._image_id)) dest_file = unicode('[fake_ds] vmware_base/%s/%s.%d.vmdk' % (self._image_id, self._image_id, self._instance['root_gb'])) # TODO(dims): add more tests for copy_virtual_disk after # the disk/image code in spawn gets refactored mock_copy_virtual_disk.assert_called_with(self._session, dc_ref, source_file, dest_file, None) def test_spawn(self): self._test_spawn() def test_spawn_no_power_on(self): self._test_spawn(power_on=False) def test_spawn_with_block_device_info(self): block_device_info = { 'block_device_mapping': [{'connection_info': 'fake'}] } self._test_spawn(block_device_info=block_device_info) @mock.patch('nova.virt.vmwareapi.driver.VMwareAPISession._get_vim_object') def test_build_virtual_machine(self, mock_get_vim_object): mock_get_vim_object.return_value = vmwareapi_fake.FakeVim() fake_session = driver.VMwareAPISession() fake_vmops = vmops.VMwareVCVMOps(fake_session, None, None) image_id = nova.tests.image.fake.get_valid_image_id() image = vmware_images.VMwareImage(image_id=image_id) vm_ref = fake_vmops.build_virtual_machine(self._instance, 'fake-instance-name', image, self._dc_info, self._ds, self.network_info) vm = vmwareapi_fake._get_object(vm_ref) # Test basic VM parameters self.assertEqual('fake-instance-name', vm.name) # NOTE(mdbooth): The instanceUuid behaviour below is apparently # deliberate. self.assertEqual('fake-instance-name', vm.get('summary.config.instanceUuid')) self.assertEqual(self._instance_values['vcpus'], vm.get('summary.config.numCpu')) self.assertEqual(self._instance_values['memory_mb'], vm.get('summary.config.memorySizeMB')) # Test NSX config for optval in vm.get('config.extraConfig').OptionValue: if optval.key == 'nvp.vm-uuid': self.assertEqual(self._instance_values['uuid'], optval.value) break else: self.fail('nvp.vm-uuid not found in extraConfig') # Test that the VM is associated with the specified datastore datastores = vm.datastore.ManagedObjectReference self.assertEqual(1, len(datastores)) datastore = vmwareapi_fake._get_object(datastores[0]) self.assertEqual(self._ds.name, datastore.get('summary.name')) # Test that the VM's network is configured as specified devices = vm.get('config.hardware.device').VirtualDevice for device in devices: if device.obj_name != 'ns0:VirtualE1000': continue self.assertEqual(self._network_values['address'], device.macAddress) break else: self.fail('NIC not configured')
apache-2.0
dongjoon-hyun/tensorflow
tensorflow/contrib/slim/__init__.py
101
2359
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Slim is an interface to contrib functions, examples and models. TODO(nsilberman): flesh out documentation. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import,line-too-long,g-importing-member,wildcard-import # TODO(jart): Delete non-slim imports from tensorflow.contrib import losses from tensorflow.contrib import metrics from tensorflow.contrib.framework.python.ops.arg_scope import * from tensorflow.contrib.framework.python.ops.variables import * from tensorflow.contrib.layers.python.layers import * from tensorflow.contrib.layers.python.layers.initializers import * from tensorflow.contrib.layers.python.layers.regularizers import * from tensorflow.contrib.slim.python.slim import evaluation from tensorflow.contrib.slim.python.slim import learning from tensorflow.contrib.slim.python.slim import model_analyzer from tensorflow.contrib.slim.python.slim import queues from tensorflow.contrib.slim.python.slim import summaries from tensorflow.contrib.slim.python.slim.data import data_decoder from tensorflow.contrib.slim.python.slim.data import data_provider from tensorflow.contrib.slim.python.slim.data import dataset from tensorflow.contrib.slim.python.slim.data import dataset_data_provider from tensorflow.contrib.slim.python.slim.data import parallel_reader from tensorflow.contrib.slim.python.slim.data import prefetch_queue from tensorflow.contrib.slim.python.slim.data import tfexample_decoder from tensorflow.python.util.all_util import make_all # pylint: enable=unused-import,line-too-long,g-importing-member,wildcard-import __all__ = make_all(__name__)
apache-2.0
kevthunder/codewave-subl
codewave_core/closing_promp.py
3
5683
import codewave_core.logger as logger import codewave_core.util as util class ClosingPromp(): def __init__(self, codewave,selections): self.codewave = codewave self._typed = None self.nbChanges = 0 self.selections = util.PosCollection(selections) def begin(self): self.started = True self.addCarrets() if self.codewave.editor.canListenToChange(): self.codewave.editor.addChangeListener( self.onChange ) return self def addCarrets(self): self.replacements = list(map(lambda p: p.carretToSel(), self.selections.wrap( self.codewave.brakets + self.codewave.carretChar + self.codewave.brakets + "\n", "\n" + self.codewave.brakets + self.codewave.closeChar + self.codewave.carretChar + self.codewave.brakets ))) self.codewave.editor.applyReplacements(self.replacements) def invalidTyped(self): self._typed = None def onChange(self,ch = None): self.invalidTyped() if self.skipEvent(ch): return self.nbChanges+=1 if self.shouldStop(): self.stop() self.cleanClose() else: self.resume() def skipEvent(self,ch): return ch is not None and isinstance(ch, str) and ch.charCodeAt(0) != 32 def resume(self): pass def shouldStop(self): return self.typed() == False or ' ' in self.typed() def cleanClose(self): replacements = [] selections = self.getSelections() start = None for sel in selections: sel.withEditor(self.codewave.editor) pos = self.whithinOpenBounds(sel) if pos is not None: start = sel elif start is not None: end = self.whithinCloseBounds(sel) if end is not None: res = end.innerText().split(' ')[0] repl = util.Replacement(end.innerStart,end.innerEnd,res) repl.selections = [start] replacements.append(repl) start = None self.codewave.editor.applyReplacements(replacements) def getSelections(self): return self.codewave.editor.getMultiSel() def stop(self): self.started = False if self.codewave.closingPromp == self: self.codewave.closingPromp = None self.codewave.editor.removeChangeListener(self.onChange) def cancel(self): if self.typed() != False: self.cancelSelections(self.getSelections()) self.stop() def cancelSelections(self,selections): replacements = [] start = None for sel in selections: sel.withEditor(self.codewave.editor) pos = self.whithinOpenBounds(sel) if pos is not None: start = pos else: end = self.whithinCloseBounds(sel) if end is not None and start is not None: replacements.append(util.Replacement(start.start,end.end,self.codewave.editor.textSubstr(start.end+1, end.start-1)).selectContent()) start = None self.codewave.editor.applyReplacements(replacements) def typed(self): if self._typed is None: cpos = self.codewave.editor.getCursorPos() innerStart = self.replacements[0].start + len(self.codewave.brakets) if self.codewave.findPrevBraket(cpos.start) == self.replacements[0].start : innerEnd = self.codewave.findNextBraket(innerStart) if innerEnd is not None and innerEnd >= cpos.end: self._typed = self.codewave.editor.textSubstr(innerStart, innerEnd) else: self._typed = False else: self._typed = False return self._typed def whithinOpenBounds(self,pos): for i, repl in enumerate(self.replacements): targetPos = self.startPosAt(i) targetText = self.codewave.brakets + (self.typed() or '') + self.codewave.brakets if targetPos.innerContainsPos(pos) and targetPos.text() == targetText: return targetPos return None def whithinCloseBounds(self,pos): for i, repl in enumerate(self.replacements): targetPos = self.endPosAt(i) targetText = self.codewave.brakets + self.codewave.closeChar + self.typed() + self.codewave.brakets if targetPos.innerContainsPos(pos) and targetPos.text() == targetText: return targetPos return None def startPosAt(self,index): return util.Pos( self.replacements[index].selections[0].start + len(self.typed() or '') * (index*2), self.replacements[index].selections[0].end + len(self.typed() or '') * (index*2 +1) ).wrappedBy(self.codewave.brakets, self.codewave.brakets).withEditor(self.codewave.editor) def endPosAt(self,index): return util.Pos( self.replacements[index].selections[1].start + len(self.typed()) * (index*2 +1), self.replacements[index].selections[1].end + len(self.typed()) * (index*2 +2) ).wrappedBy(self.codewave.brakets + self.codewave.closeChar, self.codewave.brakets).withEditor(self.codewave.editor) class SimulatedClosingPromp(ClosingPromp): def resume(self): self.simulateType() def simulateType(self): targetText = self.codewave.brakets + self.codewave.closeChar + self.typed() + self.codewave.brakets curClose = self.whithinCloseBounds(self.replacements[0].selections[1].copy().applyOffset(len(self.typed()))) if curClose: repl = util.Replacement(curClose.start, curClose.end, targetText) if repl.necessaryFor(self.codewave.editor): self.codewave.editor.applyReplacements([repl]) else: self.stop() def skipEvent(self): return False def getSelections(self): return [ self.codewave.editor.getCursorPos(), self.replacements[0].selections[1] + len(self.typed()) ] def whithinCloseBounds(self,pos): for i, repl in enumerate(self.replacements): targetPos = self.endPosAt(i) next = self.codewave.findNextBraket(targetPos.innerStart) if next is not None: targetPos.moveSuffix(next) if targetPos.innerContainsPos(pos): return targetPos return False def newFor(codewave,selections): if codewave.editor.allowMultiSelection(): return ClosingPromp(codewave,selections) else: return SimulatedClosingPromp(codewave,selections)
gpl-2.0
randynobx/ansible
lib/ansible/modules/network/nxos/nxos_pim_interface.py
39
24286
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: nxos_pim_interface extends_documentation_fragment: nxos version_added: "2.2" short_description: Manages PIM interface configuration. description: - Manages PIM interface configuration settings. author: - Jason Edelman (@jedelman8) notes: - When C(state=default), supported params will be reset to a default state. These include C(dr_prio), C(hello_auth_key), C(hello_interval), C(jp_policy_out), C(jp_policy_in), C(jp_type_in), C(jp_type_out), C(border), C(neighbor_policy), C(neighbor_type). - The C(hello_auth_key) param is not idempotent. - C(hello_auth_key) only supports clear text passwords. - When C(state=absent), pim interface configuration will be set to defaults and pim-sm will be disabled on the interface. - PIM must be enabled on the device to use this module. - This module is for Layer 3 interfaces. options: interface: description: - Full name of the interface such as Ethernet1/33. required: true sparse: description: - Enable/disable sparse-mode on the interface. required: false default: true choices: ['true', 'false'] hello_auth_key: description: - Authentication for hellos on this interface. required: false default: null hello_interval: description: - Hello interval in milliseconds for this interface. required: false default: null choices: ['true', 'false'] jp_policy_out: description: - Policy for join-prune messages (outbound). required: true default: null jp_policy_in: description: - Policy for join-prune messages (inbound). required: false default: null jp_type_out: description: - Type of policy mapped to C(jp_policy_out). required: false default: null choices: ['prefix', 'routemap'] jp_type_in: description: - Type of policy mapped to C(jp_policy_in). required: false default: null choices: ['prefix', 'routemap'] border: description: - Configures interface to be a boundary of a PIM domain. required: false default: null choices: ['true', 'false'] neighbor_policy: description: - Configures a neighbor policy for filtering adjacencies. required: false default: null neighbor_type: description: - Type of policy mapped to neighbor_policy. required: false default: null choices: ['prefix', 'routemap'] state: description: - Manages desired state of the resource. required: false default: present choices: ['present', 'default'] ''' EXAMPLES = ''' # ensure PIM is not running on the interface - nxos_pim_interface: interface: eth1/33 state: absent host: "{{ inventory_hostname }}" username: "{{ un }}" password: "{{ pwd }}" # ensure the interface has pim-sm enabled with the appropriate priority and hello interval - nxos_pim_interface: interface: eth1/33 dr_prio: 10 hello_interval: 40 state: present host: "{{ inventory_hostname }}" username: "{{ un }}" password: "{{ pwd }}" # ensure join-prune policies exist - nxos_pim_interface: interface: eth1/33 jp_policy_in: JPIN jp_policy_out: JPOUT jp_type_in: routemap jp_type_out: routemap host: "{{ inventory_hostname }}" username: "{{ un }}" password: "{{ pwd }}" # ensure defaults are in place - nxos_pim_interface: interface: eth1/33 state: default host: "{{ inventory_hostname }}" username: "{{ un }}" password: "{{ pwd }}" ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: always type: dict sample: {"interface": "eth1/33", "neighbor_policy": "test", "neighbor_type": "routemap", "sparse": true} existing: description: - k/v pairs of existing configuration returned: always type: dict sample: {"border": false, "dr_prio": "1", "hello_interval": "30000", "isauth": false, "jp_bidir": false, "jp_policy_in": "JPIN", "jp_policy_out": "1", "jp_type_in": "routemap", "jp_type_out": null, "neighbor_policy": "test1", "neighbor_type": "prefix", "sparse": true} end_state: description: k/v pairs of configuration after module execution returned: always type: dict sample: {"border": false, "dr_prio": "1", "hello_interval": "30000", "isauth": false, "jp_bidir": false, "jp_policy_in": "JPIN", "jp_policy_out": "1", "jp_type_in": "routemap", "jp_type_out": null, "neighbor_policy": "test", "neighbor_type": "routemap", "sparse": true} updates: description: command sent to the device returned: always type: list sample: ["interface eth1/33", "ip pim neighbor-policy test", "ip pim neighbor-policy test"] changed: description: check to see if a change was made on the device returned: always type: boolean sample: true ''' from ansible.module_utils.nxos import get_config, load_config, run_commands from ansible.module_utils.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleModule import time import re import re def execute_show_command(command, module, command_type='cli_show', text=False): if module.params['transport'] == 'cli': if 'show run' not in command and text is False: command += ' | json' cmds = [command] body = run_commands(module, cmds) elif module.params['transport'] == 'nxapi': cmds = [command] body = run_commands(module, cmds) return body def flatten_list(command_lists): flat_command_list = [] for command in command_lists: if isinstance(command, list): flat_command_list.extend(command) else: flat_command_list.append(command) return flat_command_list def local_existing(gexisting): jp_bidir = False isauth = False if gexisting: jp_bidir = gexisting.get('jp_bidir') isauth = gexisting.get('isauth') if jp_bidir and isauth: gexisting.pop('jp_bidir') gexisting.pop('isauth') gexisting['sparse'] = True return gexisting, jp_bidir, isauth def get_interface_type(interface): if interface.upper().startswith('ET'): return 'ethernet' elif interface.upper().startswith('VL'): return 'svi' elif interface.upper().startswith('LO'): return 'loopback' elif interface.upper().startswith('MG'): return 'management' elif interface.upper().startswith('MA'): return 'management' elif interface.upper().startswith('PO'): return 'portchannel' else: return 'unknown' def get_interface_mode(interface, intf_type, module): command = 'show interface {0}'.format(interface) mode = 'unknown' interface_table = {} body = execute_show_command(command, module) try: interface_table = body[0]['TABLE_interface']['ROW_interface'] except (KeyError, AttributeError, IndexError): return mode if intf_type in ['ethernet', 'portchannel']: mode = str(interface_table.get('eth_mode', 'layer3')) if mode in ['access', 'trunk']: mode = 'layer2' elif mode == 'routed': mode = 'layer3' elif intf_type in ['loopback', 'svi']: mode = 'layer3' return mode def get_pim_interface(module, interface): pim_interface = {} command = 'show ip pim interface {0}'.format(interface) body = execute_show_command(command, module, command_type='cli_show_ascii', text=True) if body: if 'not running' not in body[0]: body = execute_show_command(command, module) try: get_data = body[0]['TABLE_iod']['ROW_iod'] if isinstance(get_data.get('dr-priority'), unicode) or \ isinstance(get_data.get('dr-priority'), str): pim_interface['dr_prio'] = get_data.get('dr-priority') else: pim_interface['dr_prio'] = get_data.get('dr-priority')[0] hello_interval = get_data.get('hello-interval-sec') if hello_interval: hello_interval_msec = int(get_data.get('hello-interval-sec'))*1000 pim_interface['hello_interval'] = str(hello_interval_msec) border = get_data.get('is-border') if border == 'true': pim_interface['border'] = True elif border == 'false': pim_interface['border'] = False isauth = get_data.get('isauth-config') if isauth == 'true': pim_interface['isauth'] = True elif isauth == 'false': pim_interface['isauth'] = False pim_interface['neighbor_policy'] = get_data.get('nbr-policy-name') if pim_interface['neighbor_policy'] == 'none configured': pim_interface['neighbor_policy'] = None jp_in_policy = get_data.get('jp-in-policy-name') pim_interface['jp_policy_in'] = jp_in_policy if jp_in_policy == 'none configured': pim_interface['jp_policy_in'] = None if isinstance(get_data.get('jp-out-policy-name'), unicode) or \ isinstance(get_data.get('jp-out-policy-name'), str): pim_interface['jp_policy_out'] = get_data.get('jp-out-policy-name') else: pim_interface['jp_policy_out'] = get_data.get( 'jp-out-policy-name')[0] if pim_interface['jp_policy_out'] == 'none configured': pim_interface['jp_policy_out'] = None except (KeyError, AttributeError, TypeError, IndexError): return {} command = 'show run interface {0}'.format(interface) body = execute_show_command(command, module, command_type='cli_show_ascii') jp_configs = [] neigh = None if body: all_lines = body[0].splitlines() for each in all_lines: if 'jp-policy' in each: jp_configs.append(str(each.strip())) elif 'neighbor-policy' in each: neigh = str(each) pim_interface['neighbor_type'] = None neigh_type = None if neigh: if 'prefix-list' in neigh: neigh_type = 'prefix' else: neigh_type = 'routemap' pim_interface['neighbor_type'] = neigh_type len_existing = len(jp_configs) list_of_prefix_type = len([x for x in jp_configs if 'prefix-list' in x]) jp_type_in = None jp_type_out = None jp_bidir = False if len_existing == 1: # determine type last_word = jp_configs[0].split(' ')[-1] if last_word == 'in': if list_of_prefix_type: jp_type_in = 'prefix' else: jp_type_in = 'routemap' elif last_word == 'out': if list_of_prefix_type: jp_type_out = 'prefix' else: jp_type_out = 'routemap' else: jp_bidir = True if list_of_prefix_type: jp_type_in = 'prefix' jp_type_out = 'routemap' else: jp_type_in = 'routemap' jp_type_out = 'routemap' else: for each in jp_configs: last_word = each.split(' ')[-1] if last_word == 'in': if 'prefix-list' in each: jp_type_in = 'prefix' else: jp_type_in = 'routemap' elif last_word == 'out': if 'prefix-list' in each: jp_type_out = 'prefix' else: jp_type_out = 'routemap' pim_interface['jp_type_in'] = jp_type_in pim_interface['jp_type_out'] = jp_type_out pim_interface['jp_bidir'] = jp_bidir return pim_interface def fix_delta(delta, existing): if delta.get('sparse') is False and existing.get('sparse') is None: delta.pop('sparse') return delta def config_pim_interface(delta, existing, jp_bidir, isauth): command = None commands = [] delta = fix_delta(delta, existing) CMDS = { 'sparse': 'ip pim sparse-mode', 'dr_prio': 'ip pim dr-priority {0}', 'hello_interval': 'ip pim hello-interval {0}', 'hello_auth_key': 'ip pim hello-authentication ah-md5 {0}', 'border': 'ip pim border', 'jp_policy_out': 'ip pim jp-policy prefix-list {0} out', 'jp_policy_in': 'ip pim jp-policy prefix-list {0} in', 'jp_type_in': '', 'jp_type_out': '', 'neighbor_policy': 'ip pim neighbor-policy prefix-list {0}', 'neighbor_type': '' } if jp_bidir: if delta.get('jp_policy_in') or delta.get('jp_policy_out'): if existing.get('jp_type_in') == 'prefix': command = 'no ip pim jp-policy prefix-list {0}'.format( existing.get('jp_policy_in') ) else: command = 'no ip pim jp-policy {0}'.format( existing.get('jp_policy_in') ) if command: commands.append(command) for k, v in delta.items(): if k in ['dr_prio', 'hello_interval', 'hello_auth_key', 'border', 'sparse']: if v: command = CMDS.get(k).format(v) elif k == 'hello_auth_key': if isauth: command = 'no ip pim hello-authentication ah-md5' else: command = 'no ' + CMDS.get(k).format(v) if command: commands.append(command) elif k in ['neighbor_policy', 'jp_policy_in', 'jp_policy_out', 'neighbor_type']: if k in ['neighbor_policy', 'neighbor_type']: temp = delta.get('neighbor_policy') or existing.get( 'neighbor_policy') if delta.get('neighbor_type') == 'prefix': command = CMDS.get(k).format(temp) elif delta.get('neighbor_type') == 'routemap': command = 'ip pim neighbor-policy {0}'.format(temp) elif existing.get('neighbor_type') == 'prefix': command = CMDS.get(k).format(temp) elif existing.get('neighbor_type') == 'routemap': command = 'ip pim neighbor-policy {0}'.format(temp) elif k in ['jp_policy_in', 'jp_type_in']: temp = delta.get('jp_policy_in') or existing.get( 'jp_policy_in') if delta.get('jp_type_in') == 'prefix': command = CMDS.get(k).format(temp) elif delta.get('jp_type_in') == 'routemap': command = 'ip pim jp-policy {0} in'.format(temp) elif existing.get('jp_type_in') == 'prefix': command = CMDS.get(k).format(temp) elif existing.get('jp_type_in') == 'routemap': command = 'ip pim jp-policy {0} in'.format(temp) elif k in ['jp_policy_out', 'jp_type_out']: temp = delta.get('jp_policy_out') or existing.get( 'jp_policy_out') if delta.get('jp_type_out') == 'prefix': command = CMDS.get(k).format(temp) elif delta.get('jp_type_out') == 'routemap': command = 'ip pim jp-policy {0} out'.format(temp) elif existing.get('jp_type_out') == 'prefix': command = CMDS.get(k).format(temp) elif existing.get('jp_type_out') == 'routemap': command = 'ip pim jp-policy {0} out'.format(temp) if command: commands.append(command) command = None return commands def get_pim_interface_defaults(): dr_prio = '1' border = False hello_interval = '30000' hello_auth_key = False args = dict(dr_prio=dr_prio, border=border, hello_interval=hello_interval, hello_auth_key=hello_auth_key) default = dict((param, value) for (param, value) in args.items() if value is not None) return default def default_pim_interface_policies(existing, jp_bidir): commands = [] if jp_bidir: if existing.get('jp_policy_in') or existing.get('jp_policy_out'): if existing.get('jp_type_in') == 'prefix': command = 'no ip pim jp-policy prefix-list {0}'.format( existing.get('jp_policy_in') ) if command: commands.append(command) elif not jp_bidir: command = None for k, v in existing.items(): if k == 'jp_policy_in': if existing.get('jp_policy_in'): if existing.get('jp_type_in') == 'prefix': command = 'no ip pim jp-policy prefix-list {0} in'.format( existing.get('jp_policy_in') ) else: command = 'no ip pim jp-policy {0} in'.format( existing.get('jp_policy_in') ) elif k == 'jp_policy_out': if existing.get('jp_policy_out'): if existing.get('jp_type_out') == 'prefix': command = 'no ip pim jp-policy prefix-list {0} out'.format( existing.get('jp_policy_out') ) else: command = 'no ip pim jp-policy {0} out'.format( existing.get('jp_policy_out') ) if command: commands.append(command) command = None if existing.get('neighbor_policy'): command = 'no ip pim neighbor-policy' commands.append(command) return commands def config_pim_interface_defaults(existing, jp_bidir, isauth): command = [] # returns a dict defaults = get_pim_interface_defaults() delta = dict(set(defaults.items()).difference( existing.items())) if delta: # returns a list command = config_pim_interface(delta, existing, jp_bidir, isauth) comm = default_pim_interface_policies(existing, jp_bidir) if comm: for each in comm: command.append(each) return command def main(): argument_spec=dict( interface=dict(required=True), sparse=dict(type='bool', default=True), dr_prio=dict(type='str'), hello_auth_key=dict(type='str'), hello_interval=dict(type='int'), jp_policy_out=dict(type='str'), jp_policy_in=dict(type='str'), jp_type_out=dict(choices=['prefix', 'routemap']), jp_type_in=dict(choices=['prefix', 'routemap']), border=dict(type='bool'), neighbor_policy=dict(type='str'), neighbor_type=dict(choices=['prefix', 'routemap']), state=dict(choices=['present', 'absent', 'default'], default='present'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) state = module.params['state'] sparse = module.params['sparse'] interface = module.params['interface'] jp_type_in = module.params['jp_type_in'] jp_type_out = module.params['jp_type_out'] jp_policy_in = module.params['jp_policy_in'] jp_policy_out = module.params['jp_policy_out'] neighbor_policy = module.params['neighbor_policy'] neighbor_type = module.params['neighbor_type'] hello_interval = module.params['hello_interval'] intf_type = get_interface_type(interface) if get_interface_mode(interface, intf_type, module) == 'layer2': module.fail_json(msg='this module only works on Layer 3 interfaces.') if jp_policy_in: if not jp_type_in: module.fail_json(msg='jp_type_in required when using jp_policy_in.') if jp_policy_out: if not jp_type_out: module.fail_json(msg='jp_type_out required when using ' ' jp_policy_out.') if neighbor_policy: if not neighbor_type: module.fail_json(msg='neighbor_type required when using ' 'neighbor_policy.') get_existing = get_pim_interface(module, interface) existing, jp_bidir, isauth = local_existing(get_existing) end_state = existing changed = False commands = [] args = [ 'interface', 'sparse', 'dr_prio', 'hello_auth_key', 'hello_interval', 'jp_policy_out', 'jp_type_out', 'jp_type_in', 'jp_policy_in', 'border', 'neighbor_type', 'neighbor_policy' ] proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) ''' CANNOT_ABSENT = ['dr_prio', 'hello_interval', 'hello_auth_key', 'jp_policy_out', 'jp_policy_in', 'jp_type_out', 'jp_type_in', 'border', 'neighbor_type', 'neighbor_policy'] ''' if hello_interval: proposed['hello_interval'] = str(proposed['hello_interval'] * 1000) delta = dict(set(proposed.items()).difference(existing.items())) if state == 'present': if delta: command = config_pim_interface(delta, existing, jp_bidir, isauth) if command: commands.append(command) elif state == 'default': defaults = config_pim_interface_defaults(existing, jp_bidir, isauth) if defaults: commands.append(defaults) elif state == 'absent': if existing.get('sparse') is True: delta['sparse'] = False # defaults is a list of commands defaults = config_pim_interface_defaults(existing, jp_bidir, isauth) if defaults: commands.append(defaults) command = config_pim_interface(delta, existing, jp_bidir, isauth) commands.append(command) if commands: commands.insert(0, ['interface {0}'.format(interface)]) cmds = flatten_list(commands) results = {} if cmds: if module.check_mode: module.exit_json(changed=True, commands=cmds) else: changed = True load_config(module, cmds) time.sleep(1) get_existing = get_pim_interface(module, interface) end_state, jp_bidir, isauth = local_existing(get_existing) if 'configure' in cmds: cmds.pop(0) results['proposed'] = proposed results['existing'] = existing results['updates'] = cmds results['changed'] = changed results['warnings'] = warnings results['end_state'] = end_state module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
VT-vision-lab/VQA
PythonEvaluationTools/vqaEvaluation/vqaEval.py
1
8428
# coding=utf-8 __author__='aagrawal' import re # This code is based on the code written by Tsung-Yi Lin for MSCOCO Python API available at the following link: # (https://github.com/tylin/coco-caption/blob/master/pycocoevalcap/eval.py). import sys class VQAEval: def __init__(self, vqa, vqaRes, n=2): self.n = n self.accuracy = {} self.evalQA = {} self.evalQuesType = {} self.evalAnsType = {} self.vqa = vqa self.vqaRes = vqaRes self.params = {'question_id': vqa.getQuesIds()} self.contractions = {"aint": "ain't", "arent": "aren't", "cant": "can't", "couldve": "could've", "couldnt": "couldn't", \ "couldn'tve": "couldn't've", "couldnt've": "couldn't've", "didnt": "didn't", "doesnt": "doesn't", "dont": "don't", "hadnt": "hadn't", \ "hadnt've": "hadn't've", "hadn'tve": "hadn't've", "hasnt": "hasn't", "havent": "haven't", "hed": "he'd", "hed've": "he'd've", \ "he'dve": "he'd've", "hes": "he's", "howd": "how'd", "howll": "how'll", "hows": "how's", "Id've": "I'd've", "I'dve": "I'd've", \ "Im": "I'm", "Ive": "I've", "isnt": "isn't", "itd": "it'd", "itd've": "it'd've", "it'dve": "it'd've", "itll": "it'll", "let's": "let's", \ "maam": "ma'am", "mightnt": "mightn't", "mightnt've": "mightn't've", "mightn'tve": "mightn't've", "mightve": "might've", \ "mustnt": "mustn't", "mustve": "must've", "neednt": "needn't", "notve": "not've", "oclock": "o'clock", "oughtnt": "oughtn't", \ "ow's'at": "'ow's'at", "'ows'at": "'ow's'at", "'ow'sat": "'ow's'at", "shant": "shan't", "shed've": "she'd've", "she'dve": "she'd've", \ "she's": "she's", "shouldve": "should've", "shouldnt": "shouldn't", "shouldnt've": "shouldn't've", "shouldn'tve": "shouldn't've", \ "somebody'd": "somebodyd", "somebodyd've": "somebody'd've", "somebody'dve": "somebody'd've", "somebodyll": "somebody'll", \ "somebodys": "somebody's", "someoned": "someone'd", "someoned've": "someone'd've", "someone'dve": "someone'd've", \ "someonell": "someone'll", "someones": "someone's", "somethingd": "something'd", "somethingd've": "something'd've", \ "something'dve": "something'd've", "somethingll": "something'll", "thats": "that's", "thered": "there'd", "thered've": "there'd've", \ "there'dve": "there'd've", "therere": "there're", "theres": "there's", "theyd": "they'd", "theyd've": "they'd've", \ "they'dve": "they'd've", "theyll": "they'll", "theyre": "they're", "theyve": "they've", "twas": "'twas", "wasnt": "wasn't", \ "wed've": "we'd've", "we'dve": "we'd've", "weve": "we've", "werent": "weren't", "whatll": "what'll", "whatre": "what're", \ "whats": "what's", "whatve": "what've", "whens": "when's", "whered": "where'd", "wheres": "where's", "whereve": "where've", \ "whod": "who'd", "whod've": "who'd've", "who'dve": "who'd've", "wholl": "who'll", "whos": "who's", "whove": "who've", "whyll": "why'll", \ "whyre": "why're", "whys": "why's", "wont": "won't", "wouldve": "would've", "wouldnt": "wouldn't", "wouldnt've": "wouldn't've", \ "wouldn'tve": "wouldn't've", "yall": "y'all", "yall'll": "y'all'll", "y'allll": "y'all'll", "yall'd've": "y'all'd've", \ "y'alld've": "y'all'd've", "y'all'dve": "y'all'd've", "youd": "you'd", "youd've": "you'd've", "you'dve": "you'd've", \ "youll": "you'll", "youre": "you're", "youve": "you've"} self.manualMap = { 'none': '0', 'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', 'ten': '10' } self.articles = ['a', 'an', 'the' ] self.periodStrip = re.compile("(?!<=\d)(\.)(?!\d)") self.commaStrip = re.compile("(\d)(\,)(\d)") self.punct = [';', r"/", '[', ']', '"', '{', '}', '(', ')', '=', '+', '\\', '_', '-', '>', '<', '@', '`', ',', '?', '!'] def evaluate(self, quesIds=None): if quesIds == None: quesIds = [quesId for quesId in self.params['question_id']] gts = {} res = {} for quesId in quesIds: gts[quesId] = self.vqa.qa[quesId] res[quesId] = self.vqaRes.qa[quesId] # ================================================= # Compute accuracy # ================================================= accQA = [] accQuesType = {} accAnsType = {} print "computing accuracy" step = 0 for quesId in quesIds: for ansDic in gts[quesId]['answers']: ansDic['answer'] = ansDic['answer'].replace('\n', ' ') ansDic['answer'] = ansDic['answer'].replace('\t', ' ') ansDic['answer'] = ansDic['answer'].strip() resAns = res[quesId]['answer'] resAns = resAns.replace('\n', ' ') resAns = resAns.replace('\t', ' ') resAns = resAns.strip() gtAcc = [] gtAnswers = [ans['answer'] for ans in gts[quesId]['answers']] if len(set(gtAnswers)) > 1: for ansDic in gts[quesId]['answers']: ansDic['answer'] = self.processPunctuation(ansDic['answer']) ansDic['answer'] = self.processDigitArticle(ansDic['answer']) resAns = self.processPunctuation(resAns) resAns = self.processDigitArticle(resAns) for gtAnsDatum in gts[quesId]['answers']: otherGTAns = [item for item in gts[quesId]['answers'] if item!=gtAnsDatum] matchingAns = [item for item in otherGTAns if item['answer']==resAns] acc = min(1, float(len(matchingAns))/3) gtAcc.append(acc) quesType = gts[quesId]['question_type'] ansType = gts[quesId]['answer_type'] avgGTAcc = float(sum(gtAcc))/len(gtAcc) accQA.append(avgGTAcc) if quesType not in accQuesType: accQuesType[quesType] = [] accQuesType[quesType].append(avgGTAcc) if ansType not in accAnsType: accAnsType[ansType] = [] accAnsType[ansType].append(avgGTAcc) self.setEvalQA(quesId, avgGTAcc) self.setEvalQuesType(quesId, quesType, avgGTAcc) self.setEvalAnsType(quesId, ansType, avgGTAcc) if step%100 == 0: self.updateProgress(step/float(len(quesIds))) step = step + 1 self.setAccuracy(accQA, accQuesType, accAnsType) print "Done computing accuracy" def processPunctuation(self, inText): outText = inText for p in self.punct: if (p + ' ' in inText or ' ' + p in inText) or (re.search(self.commaStrip, inText) != None): outText = outText.replace(p, '') else: outText = outText.replace(p, ' ') outText = self.periodStrip.sub("", outText, re.UNICODE) return outText def processDigitArticle(self, inText): outText = [] tempText = inText.lower().split() for word in tempText: word = self.manualMap.setdefault(word, word) if word not in self.articles: outText.append(word) else: pass for wordId, word in enumerate(outText): if word in self.contractions: outText[wordId] = self.contractions[word] outText = ' '.join(outText) return outText def setAccuracy(self, accQA, accQuesType, accAnsType): self.accuracy['overall'] = round(100*float(sum(accQA))/len(accQA), self.n) self.accuracy['perQuestionType'] = {quesType: round(100*float(sum(accQuesType[quesType]))/len(accQuesType[quesType]), self.n) for quesType in accQuesType} self.accuracy['perAnswerType'] = {ansType: round(100*float(sum(accAnsType[ansType]))/len(accAnsType[ansType]), self.n) for ansType in accAnsType} def setEvalQA(self, quesId, acc): self.evalQA[quesId] = round(100*acc, self.n) def setEvalQuesType(self, quesId, quesType, acc): if quesType not in self.evalQuesType: self.evalQuesType[quesType] = {} self.evalQuesType[quesType][quesId] = round(100*acc, self.n) def setEvalAnsType(self, quesId, ansType, acc): if ansType not in self.evalAnsType: self.evalAnsType[ansType] = {} self.evalAnsType[ansType][quesId] = round(100*acc, self.n) def updateProgress(self, progress): barLength = 20 status = "" if isinstance(progress, int): progress = float(progress) if not isinstance(progress, float): progress = 0 status = "error: progress var must be float\r\n" if progress < 0: progress = 0 status = "Halt...\r\n" if progress >= 1: progress = 1 status = "Done...\r\n" block = int(round(barLength*progress)) text = "\rFinshed Percent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), int(progress*100), status) sys.stdout.write(text) sys.stdout.flush()
bsd-2-clause
pbrazdil/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/steps/preparechangelogforrevert.py
121
3180
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from webkitpy.common.checkout.changelog import ChangeLog from webkitpy.common.config import urls from webkitpy.tool.grammar import join_with_separators from webkitpy.tool.steps.abstractstep import AbstractStep class PrepareChangeLogForRevert(AbstractStep): @classmethod def _message_for_revert(cls, revision_list, reason, bug_url=None): message = "Unreviewed, rolling out %s.\n" % join_with_separators(['r' + str(revision) for revision in revision_list]) for revision in revision_list: message += "%s\n" % urls.view_revision_url(revision) if bug_url: message += "%s\n" % bug_url # Add an extra new line after the rollout links, before any reason. message += "\n" if reason: message += "%s\n\n" % reason return message def run(self, state): # This could move to prepare-ChangeLog by adding a --revert= option. self._tool.executive.run_and_throw_if_fail(self._tool.deprecated_port().prepare_changelog_command(), cwd=self._tool.scm().checkout_root) changelog_paths = self._tool.checkout().modified_changelogs(git_commit=None) bug_url = self._tool.bugs.bug_url_for_bug_id(state["bug_id"]) if state["bug_id"] else None message = self._message_for_revert(state["revision_list"], state["reason"], bug_url) for changelog_path in changelog_paths: # FIXME: Seems we should prepare the message outside of changelogs.py and then just pass in # text that we want to use to replace the reviewed by line. ChangeLog(changelog_path).update_with_unreviewed_message(message)
bsd-3-clause
Mozta/pagina-diagnostijuego
venv/lib/python2.7/site-packages/pip/_vendor/packaging/requirements.py
448
4327
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import string import re from pip._vendor.pyparsing import ( stringStart, stringEnd, originalTextFor, ParseException ) from pip._vendor.pyparsing import ZeroOrMore, Word, Optional, Regex, Combine from pip._vendor.pyparsing import Literal as L # noqa from pip._vendor.six.moves.urllib import parse as urlparse from .markers import MARKER_EXPR, Marker from .specifiers import LegacySpecifier, Specifier, SpecifierSet class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. """ ALPHANUM = Word(string.ascii_letters + string.digits) LBRACKET = L("[").suppress() RBRACKET = L("]").suppress() LPAREN = L("(").suppress() RPAREN = L(")").suppress() COMMA = L(",").suppress() SEMICOLON = L(";").suppress() AT = L("@").suppress() PUNCTUATION = Word("-_.") IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM) IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END)) NAME = IDENTIFIER("name") EXTRA = IDENTIFIER URI = Regex(r'[^ ]+')("url") URL = (AT + URI) EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA) EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras") VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE) VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE) VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY VERSION_MANY = Combine(VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=",", adjacent=False)("_raw_spec") _VERSION_SPEC = Optional(((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY)) _VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or '') VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier") VERSION_SPEC.setParseAction(lambda s, l, t: t[1]) MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker") MARKER_EXPR.setParseAction( lambda s, l, t: Marker(s[t._original_start:t._original_end]) ) MARKER_SEPERATOR = SEMICOLON MARKER = MARKER_SEPERATOR + MARKER_EXPR VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER) URL_AND_MARKER = URL + Optional(MARKER) NAMED_REQUIREMENT = \ NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER) REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd class Requirement(object): """Parse a requirement. Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. """ # TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name? def __init__(self, requirement_string): try: req = REQUIREMENT.parseString(requirement_string) except ParseException as e: raise InvalidRequirement( "Invalid requirement, parse error at \"{0!r}\"".format( requirement_string[e.loc:e.loc + 8])) self.name = req.name if req.url: parsed_url = urlparse.urlparse(req.url) if not (parsed_url.scheme and parsed_url.netloc) or ( not parsed_url.scheme and not parsed_url.netloc): raise InvalidRequirement("Invalid URL given") self.url = req.url else: self.url = None self.extras = set(req.extras.asList() if req.extras else []) self.specifier = SpecifierSet(req.specifier) self.marker = req.marker if req.marker else None def __str__(self): parts = [self.name] if self.extras: parts.append("[{0}]".format(",".join(sorted(self.extras)))) if self.specifier: parts.append(str(self.specifier)) if self.url: parts.append("@ {0}".format(self.url)) if self.marker: parts.append("; {0}".format(self.marker)) return "".join(parts) def __repr__(self): return "<Requirement({0!r})>".format(str(self))
gpl-3.0
RPGOne/scikit-learn
sklearn/metrics/tests/test_regression.py
18
6065
from __future__ import division, print_function import numpy as np from itertools import product from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.metrics import explained_variance_score from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from sklearn.metrics import median_absolute_error from sklearn.metrics import r2_score from sklearn.metrics.regression import _check_reg_targets def test_regression_metrics(n_samples=50): y_true = np.arange(n_samples) y_pred = y_true + 1 assert_almost_equal(mean_squared_error(y_true, y_pred), 1.) assert_almost_equal(mean_absolute_error(y_true, y_pred), 1.) assert_almost_equal(median_absolute_error(y_true, y_pred), 1.) assert_almost_equal(r2_score(y_true, y_pred), 0.995, 2) assert_almost_equal(explained_variance_score(y_true, y_pred), 1.) def test_multioutput_regression(): y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) y_pred = np.array([[0, 0, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1]]) error = mean_squared_error(y_true, y_pred) assert_almost_equal(error, (1. / 3 + 2. / 3 + 2. / 3) / 4.) # mean_absolute_error and mean_squared_error are equal because # it is a binary problem. error = mean_absolute_error(y_true, y_pred) assert_almost_equal(error, (1. / 3 + 2. / 3 + 2. / 3) / 4.) error = r2_score(y_true, y_pred, multioutput='variance_weighted') assert_almost_equal(error, 1. - 5. / 2) error = r2_score(y_true, y_pred, multioutput='uniform_average') assert_almost_equal(error, -.875) def test_regression_metrics_at_limits(): assert_almost_equal(mean_squared_error([0.], [0.]), 0.00, 2) assert_almost_equal(mean_absolute_error([0.], [0.]), 0.00, 2) assert_almost_equal(median_absolute_error([0.], [0.]), 0.00, 2) assert_almost_equal(explained_variance_score([0.], [0.]), 1.00, 2) assert_almost_equal(r2_score([0., 1], [0., 1]), 1.00, 2) def test__check_reg_targets(): # All of length 3 EXAMPLES = [ ("continuous", [1, 2, 3], 1), ("continuous", [[1], [2], [3]], 1), ("continuous-multioutput", [[1, 1], [2, 2], [3, 1]], 2), ("continuous-multioutput", [[5, 1], [4, 2], [3, 1]], 2), ("continuous-multioutput", [[1, 3, 4], [2, 2, 2], [3, 1, 1]], 3), ] for (type1, y1, n_out1), (type2, y2, n_out2) in product(EXAMPLES, repeat=2): if type1 == type2 and n_out1 == n_out2: y_type, y_check1, y_check2, multioutput = _check_reg_targets( y1, y2, None) assert_equal(type1, y_type) if type1 == 'continuous': assert_array_equal(y_check1, np.reshape(y1, (-1, 1))) assert_array_equal(y_check2, np.reshape(y2, (-1, 1))) else: assert_array_equal(y_check1, y1) assert_array_equal(y_check2, y2) else: assert_raises(ValueError, _check_reg_targets, y1, y2, None) def test_regression_multioutput_array(): y_true = [[1, 2], [2.5, -1], [4.5, 3], [5, 7]] y_pred = [[1, 1], [2, -1], [5, 4], [5, 6.5]] mse = mean_squared_error(y_true, y_pred, multioutput='raw_values') mae = mean_absolute_error(y_true, y_pred, multioutput='raw_values') r = r2_score(y_true, y_pred, multioutput='raw_values') evs = explained_variance_score(y_true, y_pred, multioutput='raw_values') assert_array_almost_equal(mse, [0.125, 0.5625], decimal=2) assert_array_almost_equal(mae, [0.25, 0.625], decimal=2) assert_array_almost_equal(r, [0.95, 0.93], decimal=2) assert_array_almost_equal(evs, [0.95, 0.93], decimal=2) # mean_absolute_error and mean_squared_error are equal because # it is a binary problem. y_true = [[0, 0]]*4 y_pred = [[1, 1]]*4 mse = mean_squared_error(y_true, y_pred, multioutput='raw_values') mae = mean_absolute_error(y_true, y_pred, multioutput='raw_values') r = r2_score(y_true, y_pred, multioutput='raw_values') assert_array_almost_equal(mse, [1., 1.], decimal=2) assert_array_almost_equal(mae, [1., 1.], decimal=2) assert_array_almost_equal(r, [0., 0.], decimal=2) r = r2_score([[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput='raw_values') assert_array_almost_equal(r, [0, -3.5], decimal=2) assert_equal(np.mean(r), r2_score([[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput='uniform_average')) evs = explained_variance_score([[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput='raw_values') assert_array_almost_equal(evs, [0, -1.25], decimal=2) # Checking for the condition in which both numerator and denominator is # zero. y_true = [[1, 3], [-1, 2]] y_pred = [[1, 4], [-1, 1]] r2 = r2_score(y_true, y_pred, multioutput='raw_values') assert_array_almost_equal(r2, [1., -3.], decimal=2) assert_equal(np.mean(r2), r2_score(y_true, y_pred, multioutput='uniform_average')) evs = explained_variance_score(y_true, y_pred, multioutput='raw_values') assert_array_almost_equal(evs, [1., -3.], decimal=2) assert_equal(np.mean(evs), explained_variance_score(y_true, y_pred)) def test_regression_custom_weights(): y_true = [[1, 2], [2.5, -1], [4.5, 3], [5, 7]] y_pred = [[1, 1], [2, -1], [5, 4], [5, 6.5]] msew = mean_squared_error(y_true, y_pred, multioutput=[0.4, 0.6]) maew = mean_absolute_error(y_true, y_pred, multioutput=[0.4, 0.6]) rw = r2_score(y_true, y_pred, multioutput=[0.4, 0.6]) evsw = explained_variance_score(y_true, y_pred, multioutput=[0.4, 0.6]) assert_almost_equal(msew, 0.39, decimal=2) assert_almost_equal(maew, 0.475, decimal=3) assert_almost_equal(rw, 0.94, decimal=2) assert_almost_equal(evsw, 0.94, decimal=2)
bsd-3-clause
chirilo/kuma
kuma/wiki/views/list.py
1
7664
# -*- coding: utf-8 -*- from django.http import Http404 from django.shortcuts import get_object_or_404, get_list_or_404, render from django.views.decorators.http import require_GET from kuma.core.utils import paginate from ..constants import DOCUMENTS_PER_PAGE from ..decorators import process_document_path, prevent_indexing from ..models import (Document, DocumentTag, Revision, ReviewTag, LocalizationTag) from ..queries import MultiQuerySet @require_GET def documents(request, category=None, tag=None): """ List wiki documents depending on the optionally given category or tag. """ category_id = None if category: try: category_id = int(category) category = unicode(dict(Document.CATEGORIES)[category_id]) except (KeyError, ValueError): raise Http404 # Taggit offers a slug - but use name here, because the slugification # stinks and is hard to customize. tag_obj = None if tag: matching_tags = get_list_or_404(DocumentTag, name__iexact=tag) for matching_tag in matching_tags: if matching_tag.name.lower() == tag.lower(): tag_obj = matching_tag break docs = Document.objects.filter_for_list(locale=request.locale, category=category_id, tag=tag_obj) paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE) context = { 'documents': paginated_docs, 'count': docs.count(), 'category': category, 'tag': tag, } return render(request, 'wiki/list/documents.html', context) @require_GET def templates(request): """ Returns listing of all templates """ docs = Document.objects.filter(is_template=True).order_by('title') paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE) context = { 'documents': paginated_docs, 'count': docs.count(), 'is_templates': True, } return render(request, 'wiki/list/documents.html', context) @require_GET def tags(request): """ Returns listing of all tags """ tags = DocumentTag.objects.order_by('name') tags = paginate(request, tags, per_page=DOCUMENTS_PER_PAGE) return render(request, 'wiki/list/tags.html', {'tags': tags}) @require_GET def needs_review(request, tag=None): """ Lists wiki documents with revisions flagged for review """ tag_obj = tag and get_object_or_404(ReviewTag, name=tag) or None docs = Document.objects.filter_for_review(locale=request.locale, tag=tag_obj) paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE) context = { 'documents': paginated_docs, 'count': docs.count(), 'tag': tag_obj, 'tag_name': tag, } return render(request, 'wiki/list/needs_review.html', context) @require_GET def with_localization_tag(request, tag=None): """ Lists wiki documents with localization tag """ tag_obj = tag and get_object_or_404(LocalizationTag, name=tag) or None docs = Document.objects.filter_with_localization_tag(locale=request.locale, tag=tag_obj) paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE) context = { 'documents': paginated_docs, 'count': docs.count(), 'tag': tag_obj, 'tag_name': tag, } return render(request, 'wiki/list/with_localization_tags.html', context) @require_GET def with_errors(request): """ Lists wiki documents with (KumaScript) errors """ docs = Document.objects.filter_for_list(locale=request.locale, errors=True) paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE) context = { 'documents': paginated_docs, 'count': docs.count(), 'errors': True, } return render(request, 'wiki/list/documents.html', context) @require_GET def without_parent(request): """Lists wiki documents without parent (no English source document)""" docs = Document.objects.filter_for_list(locale=request.locale, noparent=True) paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE) context = { 'documents': paginated_docs, 'count': docs.count(), 'noparent': True, } return render(request, 'wiki/list/documents.html', context) @require_GET def top_level(request): """Lists documents directly under /docs/""" docs = Document.objects.filter_for_list(locale=request.locale, toplevel=True) paginated_docs = paginate(request, docs, per_page=DOCUMENTS_PER_PAGE) context = { 'documents': paginated_docs, 'count': docs.count(), 'toplevel': True, } return render(request, 'wiki/list/documents.html', context) @require_GET @process_document_path @prevent_indexing def revisions(request, document_slug, document_locale): """ List all the revisions of a given document. """ locale = request.GET.get('locale', document_locale) document = get_object_or_404(Document.objects .select_related('current_revision'), locale=locale, slug=document_slug) if document.current_revision is None: raise Http404 def get_previous(revisions): for current_revision in revisions: for previous_revision in revisions: # we filter out all revisions that are not approved # as that's the way the get_previous method does it as well # also let's skip comparing the same revisions if (not previous_revision.is_approved or current_revision.pk == previous_revision.pk): continue # we stick to the first revision that we find if previous_revision.created < current_revision.created: current_revision.previous_revision = previous_revision break return revisions per_page = request.GET.get('limit', 10) if not request.user.is_authenticated() and per_page == 'all': return render(request, '403.html', {'reason': 'revisions_login_required'}, status=403) # Grab revisions, but defer summary and content because they can lead to # attempts to cache more than memcached allows. revisions = MultiQuerySet( (Revision.objects.filter(pk=document.current_revision.pk) .prefetch_related('creator', 'document') .transform(get_previous)), (Revision.objects.filter(document=document) .order_by('-created', '-id') .exclude(pk=document.current_revision.pk) .prefetch_related('creator', 'document') .transform(get_previous)) ) if not revisions.exists(): raise Http404 if per_page == 'all': page = None else: try: per_page = int(per_page) except ValueError: per_page = DOCUMENTS_PER_PAGE page = paginate(request, revisions, per_page) revisions = page.object_list context = { 'revisions': revisions, 'document': document, 'page': page, } return render(request, 'wiki/list/revisions.html', context)
mpl-2.0
haoxli/crosswalk-test-suite
cordova/cordova-webapp-android-tests/inst.apk.py
1996
3186
#!/usr/bin/env python import os import shutil import glob import time import sys import subprocess from optparse import OptionParser, make_option SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PARAMETERS = None ADB_CMD = "adb" def doCMD(cmd): # Do not need handle timeout in this short script, let tool do it print "-->> \"%s\"" % cmd output = [] cmd_return_code = 1 cmd_proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) while True: output_line = cmd_proc.stdout.readline().strip("\r\n") cmd_return_code = cmd_proc.poll() if output_line == '' and cmd_return_code is not None: break sys.stdout.write("%s\n" % output_line) sys.stdout.flush() output.append(output_line) return (cmd_return_code, output) def uninstPKGs(): action_status = True for root, dirs, files in os.walk(SCRIPT_DIR): for file in files: if file.endswith(".apk"): cmd = "%s -s %s uninstall org.xwalk.%s" % ( ADB_CMD, PARAMETERS.device, os.path.basename(os.path.splitext(file)[0])) (return_code, output) = doCMD(cmd) for line in output: if "Failure" in line: action_status = False break return action_status def instPKGs(): action_status = True for root, dirs, files in os.walk(SCRIPT_DIR): for file in files: if file.endswith(".apk"): cmd = "%s -s %s install %s" % (ADB_CMD, PARAMETERS.device, os.path.join(root, file)) (return_code, output) = doCMD(cmd) for line in output: if "Failure" in line: action_status = False break return action_status def main(): try: usage = "usage: inst.py -i" opts_parser = OptionParser(usage=usage) opts_parser.add_option( "-s", dest="device", action="store", help="Specify device") opts_parser.add_option( "-i", dest="binstpkg", action="store_true", help="Install package") opts_parser.add_option( "-u", dest="buninstpkg", action="store_true", help="Uninstall package") global PARAMETERS (PARAMETERS, args) = opts_parser.parse_args() except Exception as e: print "Got wrong option: %s, exit ..." % e sys.exit(1) if not PARAMETERS.device: (return_code, output) = doCMD("adb devices") for line in output: if str.find(line, "\tdevice") != -1: PARAMETERS.device = line.split("\t")[0] break if not PARAMETERS.device: print "No device found" sys.exit(1) if PARAMETERS.binstpkg and PARAMETERS.buninstpkg: print "-i and -u are conflict" sys.exit(1) if PARAMETERS.buninstpkg: if not uninstPKGs(): sys.exit(1) else: if not instPKGs(): sys.exit(1) if __name__ == "__main__": main() sys.exit(0)
bsd-3-clause
tinkerthaler/odoo
openerp/addons/base/res/res_country.py
283
4728
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv def location_name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100): if not args: args = [] ids = [] if len(name) == 2: ids = self.search(cr, user, [('code', 'ilike', name)] + args, limit=limit, context=context) search_domain = [('name', operator, name)] if ids: search_domain.append(('id', 'not in', ids)) ids.extend(self.search(cr, user, search_domain + args, limit=limit, context=context)) locations = self.name_get(cr, user, ids, context) return sorted(locations, key=lambda (id, name): ids.index(id)) class Country(osv.osv): _name = 'res.country' _description = 'Country' _columns = { 'name': fields.char('Country Name', help='The full name of the country.', required=True, translate=True), 'code': fields.char('Country Code', size=2, help='The ISO country code in two chars.\n' 'You can use this field for quick search.'), 'address_format': fields.text('Address Format', help="""You can state here the usual format to use for the \ addresses belonging to this country.\n\nYou can use the python-style string patern with all the field of the address \ (for example, use '%(street)s' to display the field 'street') plus \n%(state_name)s: the name of the state \n%(state_code)s: the code of the state \n%(country_name)s: the name of the country \n%(country_code)s: the code of the country"""), 'currency_id': fields.many2one('res.currency', 'Currency'), 'image': fields.binary("Image"), 'country_group_ids': fields.many2many('res.country.group', 'res_country_res_country_group_rel', 'res_country_id', 'res_country_group_id', string='Country Groups'), } _sql_constraints = [ ('name_uniq', 'unique (name)', 'The name of the country must be unique !'), ('code_uniq', 'unique (code)', 'The code of the country must be unique !') ] _defaults = { 'address_format': "%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s", } _order='name' name_search = location_name_search def create(self, cursor, user, vals, context=None): if vals.get('code'): vals['code'] = vals['code'].upper() return super(Country, self).create(cursor, user, vals, context=context) def write(self, cursor, user, ids, vals, context=None): if vals.get('code'): vals['code'] = vals['code'].upper() return super(Country, self).write(cursor, user, ids, vals, context=context) class CountryGroup(osv.osv): _description="Country Group" _name = 'res.country.group' _columns = { 'name': fields.char('Name', required=True), 'country_ids': fields.many2many('res.country', 'res_country_res_country_group_rel', 'res_country_group_id', 'res_country_id', string='Countries'), } class CountryState(osv.osv): _description="Country state" _name = 'res.country.state' _columns = { 'country_id': fields.many2one('res.country', 'Country', required=True), 'name': fields.char('State Name', required=True, help='Administrative divisions of a country. E.g. Fed. State, Departement, Canton'), 'code': fields.char('State Code', size=3, help='The state code in max. three chars.', required=True), } _order = 'code' name_search = location_name_search # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
IAMATinyCoder/SocialEDU
node_modules/gulp-sass/node_modules/node-sass/node_modules/pangyp/gyp/tools/graphviz.py
2679
2878
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Using the JSON dumped by the dump-dependency-json generator, generate input suitable for graphviz to render a dependency graph of targets.""" import collections import json import sys def ParseTarget(target): target, _, suffix = target.partition('#') filename, _, target = target.partition(':') return filename, target, suffix def LoadEdges(filename, targets): """Load the edges map from the dump file, and filter it to only show targets in |targets| and their depedendents.""" file = open('dump.json') edges = json.load(file) file.close() # Copy out only the edges we're interested in from the full edge list. target_edges = {} to_visit = targets[:] while to_visit: src = to_visit.pop() if src in target_edges: continue target_edges[src] = edges[src] to_visit.extend(edges[src]) return target_edges def WriteGraph(edges): """Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.""" # Bucket targets by file. files = collections.defaultdict(list) for src, dst in edges.items(): build_file, target_name, toolset = ParseTarget(src) files[build_file].append(src) print 'digraph D {' print ' fontsize=8' # Used by subgraphs. print ' node [fontsize=8]' # Output nodes by file. We must first write out each node within # its file grouping before writing out any edges that may refer # to those nodes. for filename, targets in files.items(): if len(targets) == 1: # If there's only one node for this file, simplify # the display by making it a box without an internal node. target = targets[0] build_file, target_name, toolset = ParseTarget(target) print ' "%s" [shape=box, label="%s\\n%s"]' % (target, filename, target_name) else: # Group multiple nodes together in a subgraph. print ' subgraph "cluster_%s" {' % filename print ' label = "%s"' % filename for target in targets: build_file, target_name, toolset = ParseTarget(target) print ' "%s" [label="%s"]' % (target, target_name) print ' }' # Now that we've placed all the nodes within subgraphs, output all # the edges between nodes. for src, dsts in edges.items(): for dst in dsts: print ' "%s" -> "%s"' % (src, dst) print '}' def main(): if len(sys.argv) < 2: print >>sys.stderr, __doc__ print >>sys.stderr print >>sys.stderr, 'usage: %s target1 target2...' % (sys.argv[0]) return 1 edges = LoadEdges('dump.json', sys.argv[1:]) WriteGraph(edges) return 0 if __name__ == '__main__': sys.exit(main())
gpl-3.0
vmarkovtsev/django
tests/fixtures_model_package/tests.py
312
2204
from __future__ import unicode_literals import warnings from django.core import management from django.test import TestCase from .models import Article class SampleTestCase(TestCase): fixtures = ['fixture1.json', 'fixture2.json'] def testClassFixtures(self): "Test cases can load fixture objects into models defined in packages" self.assertEqual(Article.objects.count(), 3) self.assertQuerysetEqual( Article.objects.all(), [ "Django conquers world!", "Copyright is fine the way it is", "Poker has no place on ESPN", ], lambda a: a.headline ) class FixtureTestCase(TestCase): def test_loaddata(self): "Fixtures can load data into models defined in packages" # Load fixture 1. Single JSON file, with two objects management.call_command("loaddata", "fixture1.json", verbosity=0) self.assertQuerysetEqual( Article.objects.all(), [ "Time to reform copyright", "Poker has no place on ESPN", ], lambda a: a.headline, ) # Load fixture 2. JSON file imported by default. Overwrites some # existing objects management.call_command("loaddata", "fixture2.json", verbosity=0) self.assertQuerysetEqual( Article.objects.all(), [ "Django conquers world!", "Copyright is fine the way it is", "Poker has no place on ESPN", ], lambda a: a.headline, ) # Load a fixture that doesn't exist with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") management.call_command("loaddata", "unknown.json", verbosity=0) self.assertEqual(len(w), 1) self.assertTrue(w[0].message, "No fixture named 'unknown' found.") self.assertQuerysetEqual( Article.objects.all(), [ "Django conquers world!", "Copyright is fine the way it is", "Poker has no place on ESPN", ], lambda a: a.headline, )
bsd-3-clause
plivo/plivo-python
plivo/rest/base_client.py
1
7843
# -*- coding: utf-8 -*- """ Base client, used for all API requests. """ import os import platform from collections import namedtuple from plivo.base import ResponseObject from plivo.exceptions import (AuthenticationError, InvalidRequestError, PlivoRestError, PlivoServerError, ResourceNotFoundError, ValidationError) from plivo.utils import is_valid_mainaccount, is_valid_subaccount from plivo.version import __version__ from requests import Request, Session AuthenticationCredentials = namedtuple('AuthenticationCredentials', 'auth_id auth_token') PLIVO_API = 'https://api.plivo.com' PLIVO_API_BASE_URI = '/'.join([PLIVO_API, 'v1/Account']) def get_user_agent(): return 'plivo-python/%s (Python: %s)' % (__version__, platform.python_version()) def fetch_credentials(auth_id, auth_token): """Fetches the right credentials either from params or from environment""" if not (auth_id and auth_token): try: auth_id = os.environ['PLIVO_AUTH_ID'] auth_token = os.environ['PLIVO_AUTH_TOKEN'] except KeyError: raise AuthenticationError('The Plivo Python SDK ' 'could not find your auth credentials.') if not (is_valid_mainaccount(auth_id) or is_valid_subaccount(auth_id)): raise AuthenticationError('Invalid auth_id supplied: %s' % auth_id) return AuthenticationCredentials(auth_id=auth_id, auth_token=auth_token) class BaseClient(object): def __init__(self, auth_id=None, auth_token=None, proxies=None, timeout=5): """ The Plivo API client. Deals with all the API requests to be made. """ self.base_uri = PLIVO_API_BASE_URI self.session = Session() self.session.headers.update({ 'User-Agent': get_user_agent(), 'Content-Type': 'application/json', 'Accept': 'application/json', }) self.session.auth = fetch_credentials(auth_id, auth_token) self.multipart_session = Session() self.multipart_session.headers.update({ 'User-Agent': get_user_agent(), 'Cache-Control': 'no-cache', 'Content-Type': 'multipart/form-data', }) self.multipart_session.auth = fetch_credentials(auth_id, auth_token) self.proxies = proxies self.timeout = timeout def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.session.close() self.multipart_session.close() def process_response(self, method, response, response_type=None, objects_type=None): """Processes the API response based on the status codes and method used to access the API """ try: response_json = response.json( object_hook=lambda x: ResponseObject(x) if isinstance(x, dict) else x) if response_type: r = response_type(self, response_json.__dict__) response_json = r if 'objects' in response_json and objects_type: response_json.objects = [ objects_type(self, obj.__dict__) for obj in response_json.objects ] except ValueError: response_json = None if response.status_code == 400: if response_json and 'error' in response_json: raise ValidationError(response_json.error) raise ValidationError( 'A parameter is missing or is invalid while accessing resource' 'at: {url}'.format(url=response.url)) if response.status_code == 401: if response_json and 'error' in response_json: raise AuthenticationError(response_json.error) raise AuthenticationError( 'Failed to authenticate while accessing resource at: ' '{url}'.format(url=response.url)) if response.status_code == 404: if response_json and 'error' in response_json: raise ResourceNotFoundError(response_json.error) raise ResourceNotFoundError( 'Resource not found at: {url}'.format(url=response.url)) if response.status_code == 405: if response_json and 'error' in response_json: raise InvalidRequestError(response_json.error) raise InvalidRequestError( 'HTTP method "{method}" not allowed to access resource at: ' '{url}'.format(method=method, url=response.url)) if response.status_code == 500: if response_json and 'error' in response_json: raise PlivoServerError(response_json.error) raise PlivoServerError( 'A server error occurred while accessing resource at: ' '{url}'.format(url=response.url)) if method == 'DELETE': if response.status_code != 204: raise PlivoRestError('Resource at {url} could not be ' 'deleted'.format(url=response.url)) elif response.status_code not in [200, 201, 202]: raise PlivoRestError( 'Received status code {status_code} for the HTTP method ' '"{method}"'.format( status_code=response.status_code, method=method)) return response_json def create_request(self, method, path=None, data=None): path = path or [] req = Request(method, '/'.join([self.base_uri, self.session.auth[0]] + list([str(p) for p in path])) + '/', **({ 'params': data } if method == 'GET' else { 'json': data })) return self.session.prepare_request(req) def create_multipart_request(self, method, path=None, data=None, files=None): path = path or [] data_args = {} if method == 'GET': data_args['params'] = data else: data_args['data'] = data if files and 'file' in files and files['file'] != '': data_args['files'] = files req = Request(method, '/'.join([self.base_uri, self.multipart_session.auth[0]] + list([str(p) for p in path])) + '/', **( data_args)) return self.multipart_session.prepare_request(req) def send_request(self, request, **kwargs): if 'session' in kwargs: session = kwargs['session'] del kwargs['session'] else: session = self.session return session.send( request, proxies=self.proxies, timeout=self.timeout, **kwargs) def request(self, method, path=None, data=None, response_type=None, objects_type=None, files=None, **kwargs): if files is not None: req = self.create_multipart_request(method, path, data, files) session = self.multipart_session else: req = self.create_request(method, path, data) session = self.session kwargs['session'] = session res = self.send_request(req, **kwargs) return self.process_response(method, res, response_type, objects_type)
mit
wangjun/python
renzongxian/0014/0014.py
40
1050
# Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-12-22 # Python 3.4 """ 第 0014 题: 纯文本文件 student.txt为学生信息, 里面的内容(包括花括号)如下所示: { "1":["张三",150,120,100], "2":["李四",90,99,95], "3":["王五",60,66,68] } 请将上述内容写到 student.xls 文件中。 """ import xlwt3 import json # 该部分参考了agmcs的代码,https://github.com/Show-Me-the-Code/python/blob/master/agmcs/0014/0014.py def write_txt_to_xls(txt_file): # Read form the txt file txt_object = open(txt_file, 'r') file_content = json.load(txt_object) # Write to the xls file xls_object = xlwt3.Workbook() sheet = xls_object.add_sheet('student') for i in range(len(file_content)): sheet.write(i, 0, i+1) data = file_content[str(i+1)] for j in range(len(data)): sheet.write(i, j+1, data[j]) xls_object.save('student.xls') if __name__ == '__main__': write_txt_to_xls('student.txt')
mit
firebitsbr/My-Gray-Hacker-Resources
Network_and_802.11/scanner/IPHeader.py
4
1256
#!/usr/bin/env python __author__ = "bt3" ''' A class for the IP header''' import os import struct import socket import ctypes class IP(ctypes.Structure): _fields_ = [ ('ihl', ctypes.c_ubyte, 4), ('version', ctypes.c_ubyte, 4), ('tos', ctypes.c_ubyte), ('len', ctypes.c_ushort), ('id', ctypes.c_ushort), ('offset', ctypes.c_ushort), ('ttl', ctypes.c_ubyte), ('protocol_num',ctypes.c_ubyte), ('sum', ctypes.c_ushort), ('src', ctypes.c_ulong), ('dst', ctypes.c_ulong) ] def __new__(self, socket_buffer=None): return self.from_buffer_copy(socket_buffer) def __init__(self, socket_buffer=None): # map protocol constants to their names self.protocol_map = {1:'ICMP', 6:'TCP', 17:'UDP'} # human readable IP addresses self.src_address = socket.inet_ntoa(struct.pack('<L', self.src)) self.dst_address = socket.inet_ntoa(struct.pack('<L', self.dst)) # human readable protocol try: self.protocol = self.protocol_map[self.protocol_num] except: self.protocol = str(self.protocol_num)
mit
roadmapper/ansible
lib/ansible/plugins/action/script.py
22
7460
# (c) 2012, 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 __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import re import shlex from ansible.errors import AnsibleError, AnsibleAction, _AnsibleActionDone, AnsibleActionFail, AnsibleActionSkip from ansible.executor.powershell import module_manifest as ps_manifest from ansible.module_utils._text import to_bytes, to_native, to_text from ansible.plugins.action import ActionBase class ActionModule(ActionBase): TRANSFERS_FILES = True # On Windows platform, absolute paths begin with a (back)slash # after chopping off a potential drive letter. windows_absolute_path_detection = re.compile(r'^(?:[a-zA-Z]\:)?(\\|\/)') def run(self, tmp=None, task_vars=None): ''' handler for file transfer operations ''' if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect try: creates = self._task.args.get('creates') if creates: # do not run the command if the line contains creates=filename # and the filename already exists. This allows idempotence # of command executions. if self._remote_file_exists(creates): raise AnsibleActionSkip("%s exists, matching creates option" % creates) removes = self._task.args.get('removes') if removes: # do not run the command if the line contains removes=filename # and the filename does not exist. This allows idempotence # of command executions. if not self._remote_file_exists(removes): raise AnsibleActionSkip("%s does not exist, matching removes option" % removes) # The chdir must be absolute, because a relative path would rely on # remote node behaviour & user config. chdir = self._task.args.get('chdir') if chdir: # Powershell is the only Windows-path aware shell if getattr(self._connection._shell, "_IS_WINDOWS", False) and \ not self.windows_absolute_path_detection.match(chdir): raise AnsibleActionFail('chdir %s must be an absolute path for a Windows remote node' % chdir) # Every other shell is unix-path-aware. if not getattr(self._connection._shell, "_IS_WINDOWS", False) and not chdir.startswith('/'): raise AnsibleActionFail('chdir %s must be an absolute path for a Unix-aware remote node' % chdir) # Split out the script as the first item in raw_params using # shlex.split() in order to support paths and files with spaces in the name. # Any arguments passed to the script will be added back later. raw_params = to_native(self._task.args.get('_raw_params', ''), errors='surrogate_or_strict') parts = [to_text(s, errors='surrogate_or_strict') for s in shlex.split(raw_params.strip())] source = parts[0] # Support executable paths and files with spaces in the name. executable = to_native(self._task.args.get('executable', ''), errors='surrogate_or_strict') try: source = self._loader.get_real_file(self._find_needle('files', source), decrypt=self._task.args.get('decrypt', True)) except AnsibleError as e: raise AnsibleActionFail(to_native(e)) # now we execute script, always assume changed. result['changed'] = True if not self._play_context.check_mode: # transfer the file to a remote tmp location tmp_src = self._connection._shell.join_path(self._connection._shell.tmpdir, os.path.basename(source)) # Convert raw_params to text for the purpose of replacing the script since # parts and tmp_src are both unicode strings and raw_params will be different # depending on Python version. # # Once everything is encoded consistently, replace the script path on the remote # system with the remainder of the raw_params. This preserves quoting in parameters # that would have been removed by shlex.split(). target_command = to_text(raw_params).strip().replace(parts[0], tmp_src) self._transfer_file(source, tmp_src) # set file permissions, more permissive when the copy is done as a different user self._fixup_perms2((self._connection._shell.tmpdir, tmp_src), execute=True) # add preparation steps to one ssh roundtrip executing the script env_dict = dict() env_string = self._compute_environment_string(env_dict) if executable: script_cmd = ' '.join([env_string, executable, target_command]) else: script_cmd = ' '.join([env_string, target_command]) if self._play_context.check_mode: raise _AnsibleActionDone() script_cmd = self._connection._shell.wrap_for_exec(script_cmd) exec_data = None # PowerShell runs the script in a special wrapper to enable things # like become and environment args if getattr(self._connection._shell, "_IS_WINDOWS", False): # FUTURE: use a more public method to get the exec payload pc = self._play_context exec_data = ps_manifest._create_powershell_wrapper( to_bytes(script_cmd), source, {}, env_dict, self._task.async_val, pc.become, pc.become_method, pc.become_user, pc.become_pass, pc.become_flags, "script", task_vars ) # build the necessary exec wrapper command # FUTURE: this still doesn't let script work on Windows with non-pipelined connections or # full manual exec of KEEP_REMOTE_FILES script_cmd = self._connection._shell.build_module_command(env_string='', shebang='#!powershell', cmd='') result.update(self._low_level_execute_command(cmd=script_cmd, in_data=exec_data, sudoable=True, chdir=chdir)) if 'rc' in result and result['rc'] != 0: raise AnsibleActionFail('non-zero return code') except AnsibleAction as e: result.update(e.result) finally: self._remove_tmp_path(self._connection._shell.tmpdir) return result
gpl-3.0
paulgriffiths/pyshapes
materials.py
1
3330
""" Materials classes. Library Version 1.0 Copyright 2013 Paul Griffiths Email: mail@paulgriffiths.net Distributed under the terms of the GNU General Public License. http://www.gnu.org/licenses/ """ from conversions import convert class _Material(): """ Base material class """ def __init__(self): self._specific_gravity = 1 def weight(self, quantity=1, volumeunits="cc", weightunits="grams"): """ Returns the weight of a specified volume of the material. Arguments: quantity -- the volume volumeunits -- units in which 'quantity' is stated weightunits -- units for which to return the weight For example, weight(35, "in3", "pounds") will return the weight, in pounds, of 35 cubic inches of the material. """ cc_quant = convert(quantity, volumeunits, "cc") w_grams = cc_quant * self._specific_gravity return convert(w_grams, "grams", weightunits) def specific_gravity(self): """ Returns the specific gravity of the material. """ return self._specific_gravity class DefaultMaterial(_Material): """ Default material class """ def __init__(self): _Material.__init__(self) self._specific_gravity = 1 class Water(_Material): """ Water material class """ def __init__(self): _Material.__init__(self) self._specific_gravity = 1 class _Cement(_Material): """ Generic cement class """ def __init__(self): _Material.__init__(self) class PortlandCement(_Cement): """ Portland cement class """ def __init__(self): _Cement.__init__(self) self._specific_gravity = 3.15 class _Metal(_Material): """ Generic metal class """ def __init__(self): _Material.__init__(self) class MildSteel(_Metal): """ Steel material class """ def __init__(self): _Metal.__init__(self) self._specific_gravity = 7.861093 class Aluminium(_Metal): """ Aluminium material class """ def __init__(self): _Metal.__init__(self) self._specific_gravity = 2.6989 class Copper(_Metal): """ Copper material class """ def __init__(self): _Metal.__init__(self) self._specific_gravity = 8.96 class Gold(_Metal): """ Gold material class """ def __init__(self): _Metal.__init__(self) self._specific_gravity = 19.32 class Silver(_Metal): """ Silver material class """ def __init__(self): _Metal.__init__(self) self._specific_gravity = 10.5 class Iron(_Metal): """ Iron material class """ def __init__(self): _Metal.__init__(self) self._specific_gravity = 7.894 class Lead(_Metal): """ Lead material class """ def __init__(self): _Metal.__init__(self) self._specific_gravity = 11.35 class Tin(_Metal): """ Tin material class """ def __init__(self): _Metal.__init__(self) self._specific_gravity = 7.31 class Zinc(_Metal): """ Zinc material class """ def __init__(self): _Metal.__init__(self) self._specific_gravity = 7.135
gpl-3.0
feureau/Small-Scripts
Windows Batch scripts/DeDRM_tools_6.5.5/DeDRM_Macintosh_Application/DeDRM.app/Contents/Resources/ignobleepub.py
2
17801
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import with_statement # ignobleepub.pyw, version 4.1 # Copyright © 2009-2010 by i♥cabbages # Released under the terms of the GNU General Public Licence, version 3 # <http://www.gnu.org/licenses/> # Modified 2010–2013 by some_updates, DiapDealer and Apprentice Alf # Modified 2015–2017 by Apprentice Harper # Windows users: Before running this program, you must first install Python 2.6 # from <http://www.python.org/download/> and PyCrypto from # <http://www.voidspace.org.uk/python/modules.shtml#pycrypto> (make sure to # install the version for Python 2.6). Save this script file as # ineptepub.pyw and double-click on it to run it. # # Mac OS X users: Save this script file as ineptepub.pyw. You can run this # program from the command line (pythonw ineptepub.pyw) or by double-clicking # it when it has been associated with PythonLauncher. # Revision history: # 1 - Initial release # 2 - Added OS X support by using OpenSSL when available # 3 - screen out improper key lengths to prevent segfaults on Linux # 3.1 - Allow Windows versions of libcrypto to be found # 3.2 - add support for encoding to 'utf-8' when building up list of files to decrypt from encryption.xml # 3.3 - On Windows try PyCrypto first, OpenSSL next # 3.4 - Modify interface to allow use with import # 3.5 - Fix for potential problem with PyCrypto # 3.6 - Revised to allow use in calibre plugins to eliminate need for duplicate code # 3.7 - Tweaked to match ineptepub more closely # 3.8 - Fixed to retain zip file metadata (e.g. file modification date) # 3.9 - moved unicode_argv call inside main for Windows DeDRM compatibility # 4.0 - Work if TkInter is missing # 4.1 - Import tkFileDialog, don't assume something else will import it. """ Decrypt Barnes & Noble encrypted ePub books. """ __license__ = 'GPL v3' __version__ = "4.1" import sys import os import traceback import zlib import zipfile from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED from contextlib import closing import xml.etree.ElementTree as etree # Wrap a stream so that output gets flushed immediately # and also make sure that any unicode strings get # encoded using "replace" before writing them. class SafeUnbuffered: def __init__(self, stream): self.stream = stream self.encoding = stream.encoding if self.encoding == None: self.encoding = "utf-8" def write(self, data): if isinstance(data,unicode): data = data.encode(self.encoding,"replace") self.stream.write(data) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) try: from calibre.constants import iswindows, isosx except: iswindows = sys.platform.startswith('win') isosx = sys.platform.startswith('darwin') def unicode_argv(): if iswindows: # Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode # strings. # Versions 2.x of Python don't support Unicode in sys.argv on # Windows, with the underlying Windows API instead replacing multi-byte # characters with '?'. from ctypes import POINTER, byref, cdll, c_int, windll from ctypes.wintypes import LPCWSTR, LPWSTR GetCommandLineW = cdll.kernel32.GetCommandLineW GetCommandLineW.argtypes = [] GetCommandLineW.restype = LPCWSTR CommandLineToArgvW = windll.shell32.CommandLineToArgvW CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)] CommandLineToArgvW.restype = POINTER(LPWSTR) cmd = GetCommandLineW() argc = c_int(0) argv = CommandLineToArgvW(cmd, byref(argc)) if argc.value > 0: # Remove Python executable and commands if present start = argc.value - len(sys.argv) return [argv[i] for i in xrange(start, argc.value)] return [u"ineptepub.py"] else: argvencoding = sys.stdin.encoding if argvencoding == None: argvencoding = "utf-8" return [arg if (type(arg) == unicode) else unicode(arg,argvencoding) for arg in sys.argv] class IGNOBLEError(Exception): pass def _load_crypto_libcrypto(): from ctypes import CDLL, POINTER, c_void_p, c_char_p, c_int, c_long, \ Structure, c_ulong, create_string_buffer, cast from ctypes.util import find_library if iswindows: libcrypto = find_library('libeay32') else: libcrypto = find_library('crypto') if libcrypto is None: raise IGNOBLEError('libcrypto not found') libcrypto = CDLL(libcrypto) AES_MAXNR = 14 c_char_pp = POINTER(c_char_p) c_int_p = POINTER(c_int) class AES_KEY(Structure): _fields_ = [('rd_key', c_long * (4 * (AES_MAXNR + 1))), ('rounds', c_int)] AES_KEY_p = POINTER(AES_KEY) def F(restype, name, argtypes): func = getattr(libcrypto, name) func.restype = restype func.argtypes = argtypes return func AES_set_decrypt_key = F(c_int, 'AES_set_decrypt_key', [c_char_p, c_int, AES_KEY_p]) AES_cbc_encrypt = F(None, 'AES_cbc_encrypt', [c_char_p, c_char_p, c_ulong, AES_KEY_p, c_char_p, c_int]) class AES(object): def __init__(self, userkey): self._blocksize = len(userkey) if (self._blocksize != 16) and (self._blocksize != 24) and (self._blocksize != 32) : raise IGNOBLEError('AES improper key used') return key = self._key = AES_KEY() rv = AES_set_decrypt_key(userkey, len(userkey) * 8, key) if rv < 0: raise IGNOBLEError('Failed to initialize AES key') def decrypt(self, data): out = create_string_buffer(len(data)) iv = ("\x00" * self._blocksize) rv = AES_cbc_encrypt(data, out, len(data), self._key, iv, 0) if rv == 0: raise IGNOBLEError('AES decryption failed') return out.raw return AES def _load_crypto_pycrypto(): from Crypto.Cipher import AES as _AES class AES(object): def __init__(self, key): self._aes = _AES.new(key, _AES.MODE_CBC, '\x00'*16) def decrypt(self, data): return self._aes.decrypt(data) return AES def _load_crypto(): AES = None cryptolist = (_load_crypto_libcrypto, _load_crypto_pycrypto) if sys.platform.startswith('win'): cryptolist = (_load_crypto_pycrypto, _load_crypto_libcrypto) for loader in cryptolist: try: AES = loader() break except (ImportError, IGNOBLEError): pass return AES AES = _load_crypto() META_NAMES = ('mimetype', 'META-INF/rights.xml', 'META-INF/encryption.xml') NSMAP = {'adept': 'http://ns.adobe.com/adept', 'enc': 'http://www.w3.org/2001/04/xmlenc#'} class Decryptor(object): def __init__(self, bookkey, encryption): enc = lambda tag: '{%s}%s' % (NSMAP['enc'], tag) self._aes = AES(bookkey) encryption = etree.fromstring(encryption) self._encrypted = encrypted = set() expr = './%s/%s/%s' % (enc('EncryptedData'), enc('CipherData'), enc('CipherReference')) for elem in encryption.findall(expr): path = elem.get('URI', None) if path is not None: path = path.encode('utf-8') encrypted.add(path) def decompress(self, bytes): dc = zlib.decompressobj(-15) bytes = dc.decompress(bytes) ex = dc.decompress('Z') + dc.flush() if ex: bytes = bytes + ex return bytes def decrypt(self, path, data): if path in self._encrypted: data = self._aes.decrypt(data)[16:] data = data[:-ord(data[-1])] data = self.decompress(data) return data # check file to make check whether it's probably an Adobe Adept encrypted ePub def ignobleBook(inpath): with closing(ZipFile(open(inpath, 'rb'))) as inf: namelist = set(inf.namelist()) if 'META-INF/rights.xml' not in namelist or \ 'META-INF/encryption.xml' not in namelist: return False try: rights = etree.fromstring(inf.read('META-INF/rights.xml')) adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag) expr = './/%s' % (adept('encryptedKey'),) bookkey = ''.join(rights.findtext(expr)) if len(bookkey) == 64: return True except: # if we couldn't check, assume it is return True return False def decryptBook(keyb64, inpath, outpath): if AES is None: raise IGNOBLEError(u"PyCrypto or OpenSSL must be installed.") key = keyb64.decode('base64')[:16] aes = AES(key) with closing(ZipFile(open(inpath, 'rb'))) as inf: namelist = set(inf.namelist()) if 'META-INF/rights.xml' not in namelist or \ 'META-INF/encryption.xml' not in namelist: print u"{0:s} is DRM-free.".format(os.path.basename(inpath)) return 1 for name in META_NAMES: namelist.remove(name) try: rights = etree.fromstring(inf.read('META-INF/rights.xml')) adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag) expr = './/%s' % (adept('encryptedKey'),) bookkey = ''.join(rights.findtext(expr)) if len(bookkey) != 64: print u"{0:s} is not a secure Barnes & Noble ePub.".format(os.path.basename(inpath)) return 1 bookkey = aes.decrypt(bookkey.decode('base64')) bookkey = bookkey[:-ord(bookkey[-1])] encryption = inf.read('META-INF/encryption.xml') decryptor = Decryptor(bookkey[-16:], encryption) kwds = dict(compression=ZIP_DEFLATED, allowZip64=False) with closing(ZipFile(open(outpath, 'wb'), 'w', **kwds)) as outf: zi = ZipInfo('mimetype') zi.compress_type=ZIP_STORED try: # if the mimetype is present, get its info, including time-stamp oldzi = inf.getinfo('mimetype') # copy across fields to be preserved zi.date_time = oldzi.date_time zi.comment = oldzi.comment zi.extra = oldzi.extra zi.internal_attr = oldzi.internal_attr # external attributes are dependent on the create system, so copy both. zi.external_attr = oldzi.external_attr zi.create_system = oldzi.create_system except: pass outf.writestr(zi, inf.read('mimetype')) for path in namelist: data = inf.read(path) zi = ZipInfo(path) zi.compress_type=ZIP_DEFLATED try: # get the file info, including time-stamp oldzi = inf.getinfo(path) # copy across useful fields zi.date_time = oldzi.date_time zi.comment = oldzi.comment zi.extra = oldzi.extra zi.internal_attr = oldzi.internal_attr # external attributes are dependent on the create system, so copy both. zi.external_attr = oldzi.external_attr zi.create_system = oldzi.create_system except: pass outf.writestr(zi, decryptor.decrypt(path, data)) except: print u"Could not decrypt {0:s} because of an exception:\n{1:s}".format(os.path.basename(inpath), traceback.format_exc()) return 2 return 0 def cli_main(): sys.stdout=SafeUnbuffered(sys.stdout) sys.stderr=SafeUnbuffered(sys.stderr) argv=unicode_argv() progname = os.path.basename(argv[0]) if len(argv) != 4: print u"usage: {0} <keyfile.b64> <inbook.epub> <outbook.epub>".format(progname) return 1 keypath, inpath, outpath = argv[1:] userkey = open(keypath,'rb').read() result = decryptBook(userkey, inpath, outpath) if result == 0: print u"Successfully decrypted {0:s} as {1:s}".format(os.path.basename(inpath),os.path.basename(outpath)) return result def gui_main(): try: import Tkinter import Tkconstants import tkFileDialog import tkMessageBox import traceback except: return cli_main() class DecryptionDialog(Tkinter.Frame): def __init__(self, root): Tkinter.Frame.__init__(self, root, border=5) self.status = Tkinter.Label(self, text=u"Select files for decryption") self.status.pack(fill=Tkconstants.X, expand=1) body = Tkinter.Frame(self) body.pack(fill=Tkconstants.X, expand=1) sticky = Tkconstants.E + Tkconstants.W body.grid_columnconfigure(1, weight=2) Tkinter.Label(body, text=u"Key file").grid(row=0) self.keypath = Tkinter.Entry(body, width=30) self.keypath.grid(row=0, column=1, sticky=sticky) if os.path.exists(u"bnepubkey.b64"): self.keypath.insert(0, u"bnepubkey.b64") button = Tkinter.Button(body, text=u"...", command=self.get_keypath) button.grid(row=0, column=2) Tkinter.Label(body, text=u"Input file").grid(row=1) self.inpath = Tkinter.Entry(body, width=30) self.inpath.grid(row=1, column=1, sticky=sticky) button = Tkinter.Button(body, text=u"...", command=self.get_inpath) button.grid(row=1, column=2) Tkinter.Label(body, text=u"Output file").grid(row=2) self.outpath = Tkinter.Entry(body, width=30) self.outpath.grid(row=2, column=1, sticky=sticky) button = Tkinter.Button(body, text=u"...", command=self.get_outpath) button.grid(row=2, column=2) buttons = Tkinter.Frame(self) buttons.pack() botton = Tkinter.Button( buttons, text=u"Decrypt", width=10, command=self.decrypt) botton.pack(side=Tkconstants.LEFT) Tkinter.Frame(buttons, width=10).pack(side=Tkconstants.LEFT) button = Tkinter.Button( buttons, text=u"Quit", width=10, command=self.quit) button.pack(side=Tkconstants.RIGHT) def get_keypath(self): keypath = tkFileDialog.askopenfilename( parent=None, title=u"Select Barnes & Noble \'.b64\' key file", defaultextension=u".b64", filetypes=[('base64-encoded files', '.b64'), ('All Files', '.*')]) if keypath: keypath = os.path.normpath(keypath) self.keypath.delete(0, Tkconstants.END) self.keypath.insert(0, keypath) return def get_inpath(self): inpath = tkFileDialog.askopenfilename( parent=None, title=u"Select B&N-encrypted ePub file to decrypt", defaultextension=u".epub", filetypes=[('ePub files', '.epub')]) if inpath: inpath = os.path.normpath(inpath) self.inpath.delete(0, Tkconstants.END) self.inpath.insert(0, inpath) return def get_outpath(self): outpath = tkFileDialog.asksaveasfilename( parent=None, title=u"Select unencrypted ePub file to produce", defaultextension=u".epub", filetypes=[('ePub files', '.epub')]) if outpath: outpath = os.path.normpath(outpath) self.outpath.delete(0, Tkconstants.END) self.outpath.insert(0, outpath) return def decrypt(self): keypath = self.keypath.get() inpath = self.inpath.get() outpath = self.outpath.get() if not keypath or not os.path.exists(keypath): self.status['text'] = u"Specified key file does not exist" return if not inpath or not os.path.exists(inpath): self.status['text'] = u"Specified input file does not exist" return if not outpath: self.status['text'] = u"Output file not specified" return if inpath == outpath: self.status['text'] = u"Must have different input and output files" return userkey = open(keypath,'rb').read() self.status['text'] = u"Decrypting..." try: decrypt_status = decryptBook(userkey, inpath, outpath) except Exception, e: self.status['text'] = u"Error: {0}".format(e.args[0]) return if decrypt_status == 0: self.status['text'] = u"File successfully decrypted" else: self.status['text'] = u"The was an error decrypting the file." root = Tkinter.Tk() root.title(u"Barnes & Noble ePub Decrypter v.{0}".format(__version__)) root.resizable(True, False) root.minsize(300, 0) DecryptionDialog(root).pack(fill=Tkconstants.X, expand=1) root.mainloop() return 0 if __name__ == '__main__': if len(sys.argv) > 1: sys.exit(cli_main()) sys.exit(gui_main())
gpl-3.0
SMALLplayer/smallplayer-image-creator
storage/.xbmc/addons/script.module.requests/lib/requests/packages/urllib3/poolmanager.py
13
5354
# urllib3/poolmanager.py # Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt) # # This module is part of urllib3 and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import logging from ._collections import RecentlyUsedContainer from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool from .connectionpool import connection_from_url, port_by_scheme from .request import RequestMethods from .util import parse_url __all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url'] pool_classes_by_scheme = { 'http': HTTPConnectionPool, 'https': HTTPSConnectionPool, } log = logging.getLogger(__name__) class PoolManager(RequestMethods): """ Allows for arbitrary requests while transparently keeping track of necessary connection pools for you. :param num_pools: Number of connection pools to cache before discarding the least recently used pool. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param \**connection_pool_kw: Additional parameters are used to create fresh :class:`urllib3.connectionpool.ConnectionPool` instances. Example: :: >>> manager = PoolManager(num_pools=2) >>> r = manager.request('GET', 'http://google.com/') >>> r = manager.request('GET', 'http://google.com/mail') >>> r = manager.request('GET', 'http://yahoo.com/') >>> len(manager.pools) 2 """ def __init__(self, num_pools=10, headers=None, **connection_pool_kw): RequestMethods.__init__(self, headers) self.connection_pool_kw = connection_pool_kw self.pools = RecentlyUsedContainer(num_pools, dispose_func=lambda p: p.close()) def clear(self): """ Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion. """ self.pools.clear() def connection_from_host(self, host, port=None, scheme='http'): """ Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. """ port = port or port_by_scheme.get(scheme, 80) pool_key = (scheme, host, port) # If the scheme, host, or port doesn't match existing open connections, # open a new ConnectionPool. pool = self.pools.get(pool_key) if pool: return pool # Make a fresh ConnectionPool of the desired type pool_cls = pool_classes_by_scheme[scheme] pool = pool_cls(host, port, **self.connection_pool_kw) self.pools[pool_key] = pool return pool def connection_from_url(self, url): """ Similar to :func:`urllib3.connectionpool.connection_from_url` but doesn't pass any additional parameters to the :class:`urllib3.connectionpool.ConnectionPool` constructor. Additional parameters are taken from the :class:`.PoolManager` constructor. """ u = parse_url(url) return self.connection_from_host(u.host, port=u.port, scheme=u.scheme) def urlopen(self, method, url, redirect=True, **kw): """ Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. """ u = parse_url(url) conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) kw['assert_same_host'] = False kw['redirect'] = False if 'headers' not in kw: kw['headers'] = self.headers response = conn.urlopen(method, u.request_uri, **kw) redirect_location = redirect and response.get_redirect_location() if not redirect_location: return response if response.status == 303: method = 'GET' log.info("Redirecting %s -> %s" % (url, redirect_location)) kw['retries'] = kw.get('retries', 3) - 1 # Persist retries countdown return self.urlopen(method, redirect_location, **kw) class ProxyManager(RequestMethods): """ Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method will make requests to any url through the defined proxy. """ def __init__(self, proxy_pool): self.proxy_pool = proxy_pool def _set_proxy_headers(self, headers=None): headers_ = {'Accept': '*/*'} if headers: headers_.update(headers) return headers_ def urlopen(self, method, url, **kw): "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute." kw['assert_same_host'] = False kw['headers'] = self._set_proxy_headers(kw.get('headers')) return self.proxy_pool.urlopen(method, url, **kw) def proxy_from_url(url, **pool_kw): proxy_pool = connection_from_url(url, **pool_kw) return ProxyManager(proxy_pool)
gpl-2.0
Alwnikrotikz/client175
mutagen/apev2.py
6
15832
# An APEv2 tag reader # # Copyright 2005 Joe Wreschnig # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # $Id: apev2.py 4008 2007-04-21 04:02:07Z piman $ """APEv2 reading and writing. The APEv2 format is most commonly used with Musepack files, but is also the format of choice for WavPack and other formats. Some MP3s also have APEv2 tags, but this can cause problems with many MP3 decoders and taggers. APEv2 tags, like Vorbis comments, are freeform key=value pairs. APEv2 keys can be any ASCII string with characters from 0x20 to 0x7E, between 2 and 255 characters long. Keys are case-sensitive, but readers are recommended to be case insensitive, and it is forbidden to multiple keys which differ only in case. Keys are usually stored title-cased (e.g. 'Artist' rather than 'artist'). APEv2 values are slightly more structured than Vorbis comments; values are flagged as one of text, binary, or an external reference (usually a URI). Based off the format specification found at http://wiki.hydrogenaudio.org/index.php?title=APEv2_specification. """ __all__ = ["APEv2", "APEv2File", "Open", "delete"] import struct from cStringIO import StringIO def is_valid_apev2_key(key): return (2 <= len(key) <= 255 and min(key) >= ' ' and max(key) <= '~' and key not in ["OggS", "TAG", "ID3", "MP+"]) # There are three different kinds of APE tag values. # "0: Item contains text information coded in UTF-8 # 1: Item contains binary information # 2: Item is a locator of external stored information [e.g. URL] # 3: reserved" TEXT, BINARY, EXTERNAL = range(3) HAS_HEADER = 1L << 31 HAS_NO_FOOTER = 1L << 30 IS_HEADER = 1L << 29 class error(IOError): pass class APENoHeaderError(error, ValueError): pass class APEUnsupportedVersionError(error, ValueError): pass class APEBadItemError(error, ValueError): pass from mutagen import Metadata, FileType from mutagen._util import DictMixin, cdata, utf8, delete_bytes class _APEv2Data(object): # Store offsets of the important parts of the file. start = header = data = footer = end = None # Footer or header; seek here and read 32 to get version/size/items/flags metadata = None # Actual tag data tag = None version = None size = None items = None flags = 0 # The tag is at the start rather than the end. A tag at both # the start and end of the file (i.e. the tag is the whole file) # is not considered to be at the start. is_at_start = False def __init__(self, fileobj): self.__find_metadata(fileobj) self.metadata = max(self.header, self.footer) if self.metadata is None: return self.__fill_missing(fileobj) self.__fix_brokenness(fileobj) if self.data is not None: fileobj.seek(self.data) self.tag = fileobj.read(self.size) def __find_metadata(self, fileobj): # Try to find a header or footer. # Check for a simple footer. try: fileobj.seek(-32, 2) except IOError: fileobj.seek(0, 2) return if fileobj.read(8) == "APETAGEX": fileobj.seek(-8, 1) self.footer = self.metadata = fileobj.tell() return # Check for an APEv2 tag followed by an ID3v1 tag at the end. try: fileobj.seek(-128, 2) if fileobj.read(3) == "TAG": fileobj.seek(-35, 1) # "TAG" + header length if fileobj.read(8) == "APETAGEX": fileobj.seek(-8, 1) self.footer = fileobj.tell() return # ID3v1 tag at the end, maybe preceded by Lyrics3v2. # (http://www.id3.org/lyrics3200.html) # (header length - "APETAGEX") - "LYRICS200" fileobj.seek(15, 1) if fileobj.read(9) == 'LYRICS200': fileobj.seek(-15, 1) # "LYRICS200" + size tag try: offset = int(fileobj.read(6)) except ValueError: raise IOError fileobj.seek(-32 - offset - 6, 1) if fileobj.read(8) == "APETAGEX": fileobj.seek(-8, 1) self.footer = fileobj.tell() return except IOError: pass # Check for a tag at the start. fileobj.seek(0, 0) if fileobj.read(8) == "APETAGEX": self.is_at_start = True self.header = 0 def __fill_missing(self, fileobj): fileobj.seek(self.metadata + 8) self.version = fileobj.read(4) self.size = cdata.uint_le(fileobj.read(4)) self.items = cdata.uint_le(fileobj.read(4)) self.flags = cdata.uint_le(fileobj.read(4)) if self.header is not None: self.data = self.header + 32 # If we're reading the header, the size is the header # offset + the size, which includes the footer. self.end = self.data + self.size fileobj.seek(self.end - 32, 0) if fileobj.read(8) == "APETAGEX": self.footer = self.end - 32 elif self.footer is not None: self.end = self.footer + 32 self.data = self.end - self.size if self.flags & HAS_HEADER: self.header = self.data - 32 else: self.header = self.data else: raise APENoHeaderError("No APE tag found") def __fix_brokenness(self, fileobj): # Fix broken tags written with PyMusepack. if self.header is not None: start = self.header else: start = self.data fileobj.seek(start) while start > 0: # Clean up broken writing from pre-Mutagen PyMusepack. # It didn't remove the first 24 bytes of header. try: fileobj.seek(-24, 1) except IOError: break else: if fileobj.read(8) == "APETAGEX": fileobj.seek(-8, 1) start = fileobj.tell() else: break self.start = start class APEv2(DictMixin, Metadata): """A file with an APEv2 tag. ID3v1 tags are silently ignored and overwritten. """ filename = None def __init__(self, *args, **kwargs): self.__casemap = {} self.__dict = {} super(APEv2, self).__init__(*args, **kwargs) # Internally all names are stored as lowercase, but the case # they were set with is remembered and used when saving. This # is roughly in line with the standard, which says that keys # are case-sensitive but two keys differing only in case are # not allowed, and recommends case-insensitive # implementations. def pprint(self): """Return tag key=value pairs in a human-readable format.""" items = self.items() items.sort() return "\n".join(["%s=%s" % (k, v.pprint()) for k, v in items]) def load(self, filename): """Load tags from a filename.""" self.filename = filename fileobj = file(filename, "rb") try: data = _APEv2Data(fileobj) finally: fileobj.close() if data.tag: self.clear() self.__casemap.clear() self.__parse_tag(data.tag, data.items) else: raise APENoHeaderError("No APE tag found") def __parse_tag(self, tag, count): fileobj = StringIO(tag) for i in range(count): size = cdata.uint_le(fileobj.read(4)) flags = cdata.uint_le(fileobj.read(4)) # Bits 1 and 2 bits are flags, 0-3 # Bit 0 is read/write flag, ignored kind = (flags & 6) >> 1 if kind == 3: raise APEBadItemError("value type must be 0, 1, or 2") key = value = fileobj.read(1) while key[-1:] != '\x00' and value: value = fileobj.read(1) key += value if key[-1:] == "\x00": key = key[:-1] value = fileobj.read(size) self[key] = APEValue(value, kind) def __getitem__(self, key): if not is_valid_apev2_key(key): raise KeyError("%r is not a valid APEv2 key" % key) return self.__dict[key.lower()] def __delitem__(self, key): if not is_valid_apev2_key(key): raise KeyError("%r is not a valid APEv2 key" % key) del(self.__dict[key.lower()]) def __setitem__(self, key, value): """'Magic' value setter. This function tries to guess at what kind of value you want to store. If you pass in a valid UTF-8 or Unicode string, it treats it as a text value. If you pass in a list, it treats it as a list of string/Unicode values. If you pass in a string that is not valid UTF-8, it assumes it is a binary value. If you need to force a specific type of value (e.g. binary data that also happens to be valid UTF-8, or an external reference), use the APEValue factory and set the value to the result of that: from mutagen.apev2 import APEValue, EXTERNAL tag['Website'] = APEValue('http://example.org', EXTERNAL) """ if not is_valid_apev2_key(key): raise KeyError("%r is not a valid APEv2 key" % key) if not isinstance(value, _APEValue): # let's guess at the content if we're not already a value... if isinstance(value, unicode): # unicode? we've got to be text. value = APEValue(utf8(value), TEXT) elif isinstance(value, list): # list? text. value = APEValue("\0".join(map(utf8, value)), TEXT) else: try: dummy = value.decode("utf-8") except UnicodeError: # invalid UTF8 text, probably binary value = APEValue(value, BINARY) else: # valid UTF8, probably text value = APEValue(value, TEXT) self.__casemap[key.lower()] = key self.__dict[key.lower()] = value def keys(self): return [self.__casemap.get(key, key) for key in self.__dict.keys()] def save(self, filename=None): """Save changes to a file. If no filename is given, the one most recently loaded is used. Tags are always written at the end of the file, and include a header and a footer. """ filename = filename or self.filename try: fileobj = file(filename, "r+b") except IOError: fileobj = file(filename, "w+b") data = _APEv2Data(fileobj) if data.is_at_start: delete_bytes(fileobj, data.end - data.start, data.start) elif data.start is not None: fileobj.seek(data.start) # Delete an ID3v1 tag if present, too. fileobj.truncate() fileobj.seek(0, 2) # "APE tags items should be sorted ascending by size... This is # not a MUST, but STRONGLY recommended. Actually the items should # be sorted by importance/byte, but this is not feasible." tags = [v._internal(k) for k, v in self.items()] tags.sort(lambda a, b: cmp(len(a), len(b))) num_tags = len(tags) tags = "".join(tags) header = "APETAGEX%s%s" %( # version, tag size, item count, flags struct.pack("<4I", 2000, len(tags) + 32, num_tags, HAS_HEADER | IS_HEADER), "\0" * 8) fileobj.write(header) fileobj.write(tags) footer = "APETAGEX%s%s" %( # version, tag size, item count, flags struct.pack("<4I", 2000, len(tags) + 32, num_tags, HAS_HEADER), "\0" * 8) fileobj.write(footer) fileobj.close() def delete(self, filename=None): """Remove tags from a file.""" filename = filename or self.filename fileobj = file(filename, "r+b") try: data = _APEv2Data(fileobj) if data.start is not None and data.size is not None: delete_bytes(fileobj, data.end - data.start, data.start) finally: fileobj.close() self.clear() Open = APEv2 def delete(filename): """Remove tags from a file.""" try: APEv2(filename).delete() except APENoHeaderError: pass def APEValue(value, kind): """APEv2 tag value factory. Use this if you need to specify the value's type manually. Binary and text data are automatically detected by APEv2.__setitem__. """ if kind == TEXT: return APETextValue(value, kind) elif kind == BINARY: return APEBinaryValue(value, kind) elif kind == EXTERNAL: return APEExtValue(value, kind) else: raise ValueError("kind must be TEXT, BINARY, or EXTERNAL") class _APEValue(object): def __init__(self, value, kind): self.kind = kind self.value = value def __len__(self): return len(self.value) def __str__(self): return self.value # Packed format for an item: # 4B: Value length # 4B: Value type # Key name # 1B: Null # Key value def _internal(self, key): return "%s%s\0%s" %( struct.pack("<2I", len(self.value), self.kind << 1), key, self.value) def __repr__(self): return "%s(%r, %d)" % (type(self).__name__, self.value, self.kind) class APETextValue(_APEValue): """An APEv2 text value. Text values are Unicode/UTF-8 strings. They can be accessed like strings (with a null seperating the values), or arrays of strings.""" def __unicode__(self): return unicode(str(self), "utf-8") def __iter__(self): """Iterate over the strings of the value (not the characters)""" return iter(unicode(self).split("\0")) def __getitem__(self, index): return unicode(self).split("\0")[index] def __len__(self): return self.value.count("\0") + 1 def __cmp__(self, other): return cmp(unicode(self), other) def __setitem__(self, index, value): values = list(self) values[index] = value.encode("utf-8") self.value = "\0".join(values).encode("utf-8") def pprint(self): return " / ".join(self) class APEBinaryValue(_APEValue): """An APEv2 binary value.""" def pprint(self): return "[%d bytes]" % len(self) class APEExtValue(_APEValue): """An APEv2 external value. External values are usually URI or IRI strings. """ def pprint(self): return "[External] %s" % unicode(self) class APEv2File(FileType): class _Info(object): length = 0 bitrate = 0 def __init__(self, fileobj): pass pprint = staticmethod(lambda: "Unknown format with APEv2 tag.") def load(self, filename): self.filename = filename self.info = self._Info(file(filename, "rb")) try: self.tags = APEv2(filename) except error: self.tags = None def add_tags(self): if self.tags is None: self.tags = APEv2() else: raise ValueError("%r already has tags: %r" % (self, self.tags)) def score(filename, fileobj, header): try: fileobj.seek(-160, 2) except IOError: fileobj.seek(0) footer = fileobj.read() filename = filename.lower() return (("APETAGEX" in footer) - header.startswith("ID3")) score = staticmethod(score)
gpl-3.0
mKeRix/home-assistant
homeassistant/components/pi_hole/const.py
3
1438
"""Constants for the pi_hole integration.""" from datetime import timedelta from homeassistant.const import UNIT_PERCENTAGE DOMAIN = "pi_hole" CONF_LOCATION = "location" DEFAULT_LOCATION = "admin" DEFAULT_METHOD = "GET" DEFAULT_NAME = "Pi-Hole" DEFAULT_SSL = False DEFAULT_VERIFY_SSL = True SERVICE_DISABLE = "disable" SERVICE_DISABLE_ATTR_DURATION = "duration" ATTR_BLOCKED_DOMAINS = "domains_blocked" MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5) DATA_KEY_API = "api" DATA_KEY_COORDINATOR = "coordinator" SENSOR_DICT = { "ads_blocked_today": ["Ads Blocked Today", "ads", "mdi:close-octagon-outline"], "ads_percentage_today": [ "Ads Percentage Blocked Today", UNIT_PERCENTAGE, "mdi:close-octagon-outline", ], "clients_ever_seen": ["Seen Clients", "clients", "mdi:account-outline"], "dns_queries_today": [ "DNS Queries Today", "queries", "mdi:comment-question-outline", ], "domains_being_blocked": ["Domains Blocked", "domains", "mdi:block-helper"], "queries_cached": ["DNS Queries Cached", "queries", "mdi:comment-question-outline"], "queries_forwarded": [ "DNS Queries Forwarded", "queries", "mdi:comment-question-outline", ], "unique_clients": ["DNS Unique Clients", "clients", "mdi:account-outline"], "unique_domains": ["DNS Unique Domains", "domains", "mdi:domain"], } SENSOR_LIST = list(SENSOR_DICT)
mit
benoitsteiner/tensorflow-xsmm
tensorflow/contrib/distribute/python/minimize_loss_test.py
9
15082
# 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. # ============================================================================== """Tests for running legacy optimizer code with DistributionStrategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy from tensorflow.contrib.distribute.python import combinations from tensorflow.contrib.distribute.python import mirrored_strategy from tensorflow.contrib.distribute.python.single_loss_example import batchnorm_example from tensorflow.contrib.distribute.python.single_loss_example import minimize_loss_example from tensorflow.contrib.tpu.python.tpu import tpu from tensorflow.python.data.ops import dataset_ops from tensorflow.python.eager import context from tensorflow.python.eager import test from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables as variables_lib from tensorflow.python.ops.losses import losses_impl class MinimizeLossStepTest(test.TestCase, parameterized.TestCase): @combinations.generate( combinations.times( combinations.distributions_and_v1_optimizers(), combinations.combine(mode=["graph"], use_callable_loss=[True, False]) + combinations.combine(mode=["eager"], use_callable_loss=[True]), combinations.combine(is_tpu=[False])) + combinations.combine( distribution=[combinations.tpu_strategy], optimizer_fn=[ combinations.adam_optimizer_v1_fn, # TODO(isaprykin): Make Adam v2 work with while_loops # and TPUs. ], mode=["graph"], use_callable_loss=[False], is_tpu=[True])) def testTrainNetwork(self, distribution, optimizer_fn, use_callable_loss, is_tpu): # TODO(priyag): Remove this once the step TPU Strategy is stable. if is_tpu: self.skipTest("TPU tests are WIP.") with distribution.scope(): model_fn, dataset_fn, layer = minimize_loss_example( optimizer_fn, use_bias=True, use_callable_loss=use_callable_loss) # TODO(isaprykin): Eliminate `is_tpu`. Probably add a # `DistributionStrategy.create_monitor` so that each DistributionStrategy # could influence its training loop. That method would return an instance # of Monitor. TPUMonitor would execute tpu.initialize_system() and # tpu.shutdown_system(). iterator = distribution.distribute_dataset( dataset_fn).make_one_shot_iterator() def run_step(): return distribution.group( distribution.call_for_each_tower( model_fn, iterator.get_next(), run_concurrently=layer.built)) if not context.executing_eagerly(): with self.test_session() as sess: if is_tpu: sess.run(tpu.initialize_system()) run_step = sess.make_callable(run_step()) self.evaluate(variables_lib.global_variables_initializer()) weights, biases = [], [] for _ in range(10): run_step() weights.append(self.evaluate(layer.kernel)) biases.append(self.evaluate(layer.bias)) if is_tpu: with self.test_session() as sess: sess.run(tpu.shutdown_system()) error = abs(numpy.add(numpy.squeeze(weights), numpy.squeeze(biases)) - 1) is_not_increasing = all(y <= x for x, y in zip(error, error[1:])) self.assertTrue(is_not_increasing) @combinations.generate( combinations.times( combinations.distributions_and_v1_optimizers() + combinations.distributions_and_v2_optimizers(), combinations.combine(mode=["graph", "eager"], is_tpu=[False])) + combinations.combine( distribution=[combinations.tpu_strategy], optimizer_fn=[ combinations.adam_optimizer_v1_fn, combinations.gradient_descent_optimizer_v1_fn, combinations.gradient_descent_optimizer_v2_fn, ], mode=["graph"], is_tpu=[True])) def testOptimizerInsideModelFn(self, distribution, optimizer_fn, is_tpu): # TODO(priyag): Remove this once the step TPU Strategy is stable. if is_tpu: self.skipTest("TPU tests are WIP.") created_variables = [] trainable_variables = [] def appending_creator(next_creator, *args, **kwargs): v = next_creator(*args, **kwargs) created_variables.append(v.name) if "trainable" in kwargs and kwargs["trainable"]: trainable_variables.append(v.name) return v # Creator scope needs to be set before it's used inside # `distribution.scope`. with variable_scope.variable_creator_scope( appending_creator), distribution.scope(): model_fn, dataset_fn, layer = minimize_loss_example( optimizer_fn, use_bias=True, use_callable_loss=True, create_optimizer_inside_model_fn=True) iterator = distribution.distribute_dataset( dataset_fn).make_one_shot_iterator() def run_step(): return distribution.group( distribution.call_for_each_tower( model_fn, iterator.get_next(), run_concurrently=layer.built)) if not context.executing_eagerly(): with self.test_session() as sess: if is_tpu: sess.run(tpu.initialize_system()) run_step = sess.make_callable(run_step()) self.evaluate(variables_lib.global_variables_initializer()) run_step() if is_tpu: with self.test_session() as sess: sess.run(tpu.shutdown_system()) def get_expected_variables(optimizer_fn, num_parameter_devices): variables_map = { "GradientDescent": ["dense/kernel", "dense/bias"], "Adam": [ "dense/kernel", "dense/bias", "beta1_power", "beta2_power", "dense/kernel/Adam", "dense/kernel/Adam_1", "dense/bias/Adam", "dense/bias/Adam_1" ] } variables = variables_map[optimizer_fn().get_name()] variables.extend([ v + "/replica_{}".format(replica) for v in variables for replica in range(1, num_parameter_devices) ]) return set([v + ":0" for v in variables]) self.assertEqual( get_expected_variables(optimizer_fn, len(distribution.parameter_devices)), set(created_variables)) @combinations.generate( combinations.times( combinations.combine(momentum=[0.8, 0.9, 0.99], renorm=[False, True]), combinations.times( combinations.distributions_and_v1_optimizers(), combinations.combine( mode=["graph", "eager"], is_tpu=[False], # TODO(isaprykin): Allow False here. Currently subsequent # towers will re-execute UPDATE_OPS of previous towers. update_ops_in_cross_tower_mode=[True])) + combinations.combine( distribution=[combinations.tpu_strategy], optimizer_fn=[ combinations.gradient_descent_optimizer_v1_fn, combinations.gradient_descent_optimizer_v2_fn ], mode=["graph"], is_tpu=[True], update_ops_in_cross_tower_mode=[False]))) def testTrainNetworkWithBatchNorm(self, distribution, optimizer_fn, momentum, renorm, is_tpu, update_ops_in_cross_tower_mode): """Verifies that moving mean updates are reduced across towers.""" # TODO(priyag): Remove this once the step TPU Strategy is stable. if is_tpu: self.skipTest("TPU tests are WIP.") with distribution.scope(): num_towers = len(distribution.worker_devices) model_fn, dataset_fn, batchnorm = batchnorm_example( optimizer_fn, batch_per_epoch=num_towers, momentum=momentum, renorm=renorm, update_ops_in_tower_mode=not update_ops_in_cross_tower_mode) # Make sure prefetching is disabled since that makes the # specific input on each device to be non deterministic, and # this test relies on specific input being on each device. if isinstance(distribution, mirrored_strategy.MirroredStrategy): self.assertFalse(distribution._prefetch_on_device) iterator = distribution.distribute_dataset( dataset_fn).make_one_shot_iterator() def run_step(): fetches = distribution.unwrap( distribution.call_for_each_tower( model_fn, iterator.get_next(), run_concurrently=batchnorm.built)) if update_ops_in_cross_tower_mode: fetches += ops.get_collection(ops.GraphKeys.UPDATE_OPS) return control_flow_ops.group(fetches) if not context.executing_eagerly(): with self.test_session() as sess: if is_tpu: sess.run(tpu.initialize_system()) run_step = sess.make_callable(run_step()) self.evaluate(variables_lib.global_variables_initializer()) expected_moving_means = [0.] * 8 def averaged_batch_mean(i): # Each batch has shape [16, 8] where the ith element in jth list is # (8 * j + i + tower_id * 100). So the batch mean in each tower is # (60 + i + tower_id * 100). So here comes its batch mean over all # towers: return 60. + i + (num_towers - 1.) / 2. * 100. for _ in range(10): run_step() moving_means = self.evaluate(batchnorm.moving_mean) # We make sure that the moving_mean is updated as if the sample mean is # calculated over all towers. for i, expected_moving_mean in enumerate(expected_moving_means): expected_moving_means[i] -= (( expected_moving_mean - averaged_batch_mean(i)) * (1.0 - momentum)) self.assertNear(expected_moving_means[i], moving_means[i], 0.0001) if is_tpu: with self.test_session() as sess: sess.run(tpu.shutdown_system()) @combinations.generate( combinations.times( combinations.combine( optimizer_fn=[ combinations.gradient_descent_optimizer_v1_fn, combinations.gradient_descent_optimizer_v2_fn ], loss_reduction=[ losses_impl.Reduction.SUM, losses_impl.Reduction.MEAN, losses_impl.Reduction.SUM_OVER_BATCH_SIZE, losses_impl.Reduction.SUM_OVER_NONZERO_WEIGHTS ]), combinations.times( combinations.combine( distribution=[ combinations.one_device_strategy, combinations.mirrored_strategy_with_gpu_and_cpu, combinations.mirrored_strategy_with_two_gpus ], is_tpu=[False]), combinations.combine( mode=["graph"], use_callable_loss=[True, False]) + combinations.combine(mode=["eager"], use_callable_loss=[True])) + combinations.combine( distribution=[combinations.tpu_strategy], is_tpu=[True], mode=["graph"], use_callable_loss=[True, False]))) def testMeanVsSum(self, distribution, optimizer_fn, loss_reduction, use_callable_loss, is_tpu): # TODO(priyag): Remove this once the step TPU Strategy is stable. if is_tpu: self.skipTest("TPU tests are WIP.") with distribution.scope(): all_vars = [] def model_fn(x, y): def loss_fn(): # Use fixed initialization to make the steps deterministic. w = variable_scope.get_variable("w", initializer=[[2.]]) all_vars.append(w) predict = math_ops.matmul(x, w) return losses_impl.mean_squared_error( y, predict, reduction=loss_reduction) optimizer = optimizer_fn() # GradientDescent with 0.2 learning rate if use_callable_loss: return optimizer.minimize(loss_fn) else: return optimizer.minimize(loss_fn()) def dataset_fn(): features = dataset_ops.Dataset.from_tensors([[2.], [7.]]) labels = dataset_ops.Dataset.from_tensors([[6.], [21.]]) return dataset_ops.Dataset.zip((features, labels)).repeat() iterator = distribution.distribute_dataset( dataset_fn).make_one_shot_iterator() def run_step(): return distribution.group( distribution.call_for_each_tower( model_fn, *iterator.get_next(), run_concurrently=False)) if not context.executing_eagerly(): with self.test_session() as sess: if is_tpu: sess.run(tpu.initialize_system()) run_step = sess.make_callable(run_step()) self.evaluate(variables_lib.global_variables_initializer()) run_step() v = all_vars[0] self.assertTrue(all([v is vi for vi in all_vars[1:]])) weight = numpy.squeeze(self.evaluate(v)) # Our model is: # predict = x * w # loss = (predict - y)^2 # dloss/dpredict = 2*(predict - y) # dloss/dw = 2 * x^T @ (predict - y) # For our batch size of 2, assuming sum loss reduction: # x = [2, 7] # y = [6, 21] # w_initial = 2 # predict = [4, 14] # predict - y = [-2, -7] # dloss/dw = 2 <[2, 7], [-2, -7]> = - 2(4 + 49) = -106 # So unreplicated the update to w with lr=0.2 is -0.2 * -106 = 21.2 # with sum loss reduction, or 10.6 with mean. if loss_reduction == losses_impl.Reduction.SUM: # Note that the "distribution.num_towers" factor will go away once # we split the input across towers, instead of pulling a complete # batch of input per tower. self.assertNear(weight, 2 + 21.2 * distribution.num_towers, 0.0001) else: # One of the mean loss reductions. self.assertNear(weight, 2 + 10.6, 0.0001) if is_tpu: with self.test_session() as sess: sess.run(tpu.shutdown_system()) if __name__ == "__main__": test.main()
apache-2.0
xujun10110/creepy
creepy/components/PersonProjectWizard.py
2
11164
#!/usr/bin/python # -*- coding: utf-8 -*- import os from PyQt4.QtGui import QWizard,QMessageBox,QWidget,QScrollArea,QLineEdit,QLabel,QVBoxLayout,QCheckBox,QGridLayout from PyQt4.QtCore import QString from models.PluginConfigurationListModel import PluginConfigurationListModel from models.ProjectWizardPossibleTargetsTable import ProjectWizardPossibleTargetsTable from models.InputPlugin import InputPlugin from yapsy.PluginManager import PluginManagerSingleton from ui.PersonProjectWizard import Ui_personProjectWizard try: _fromUtf8 = QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class PersonProjectWizard(QWizard): """ Loads the Person Based Project Wizard from the ui and shows it """ def __init__(self, parent=None): QWizard.__init__(self, parent) self.ui = Ui_personProjectWizard() self.ui.setupUi(self) self.selectedTargets = [] self.enabledPlugins = [] # Register the project name field so that it will become mandatory self.page(0).registerField('name*', self.ui.personProjectNameValue) self.ui.btnAddTarget.clicked.connect(self.addTargetsToSelected) self.ui.btnRemoveTarget.clicked.connect(self.removeTargetsFromSelected) self.ui.personProjectSearchForValue.returnPressed.connect(self.ui.personProjectSearchButton.setFocus) def addTargetsToSelected(self): selected = self.ui.personProjectSearchResultsTable.selectionModel().selectedRows() newTargets = [self.ui.personProjectSearchResultsTable.model().targets[i.row()] for i in selected] self.ui.personProjectSelectedTargetsTable.model().insertRows(newTargets, len(newTargets)) def removeTargetsFromSelected(self): selected = self.ui.personProjectSelectedTargetsTable.selectionModel().selectedRows() toRemove = [self.ui.personProjectSelectedTargetsTable.model().targets[i.row()] for i in selected] self.ui.personProjectSelectedTargetsTable.model().removeRows(toRemove, len(toRemove)) def showWarning(self, title, text): QMessageBox.warning(self, title, text) def initializePage(self, i): """ If the page to be loaded is the page containing the search options for our plugins, store the selected targets and load the relative search options based on the selected target. Also check if the selected plugins are empty and return the user back. <TODO> This should be done with registering a field for the selectedTargets TableView """ if i == 2: self.checkIfSelectedTargets() self.storeSelectedTargets() self.showPluginsSearchOptions() def checkIfSelectedTargets(self): if not self.ProjectWizardSelectedTargetsTable.targets: self.showWarning('No target selected', 'Please drag and drop your targets to the selected targets before proceeding') self.back() self.next() def storeSelectedTargets(self): ''' Stores a list of the selected targets for future use ''' self.selectedTargets = [] for target in self.ProjectWizardSelectedTargetsTable.targets: self.selectedTargets.append({'pluginName':target['pluginName'], 'targetUsername':target['targetUsername'], 'targetUserid':target['targetUserid'], 'targetFullname':target['targetFullname'] }) def searchForTargets(self): ''' Iterates the selected plugins and for each one performs a search with the given criteria. It then populates the PossibleTargets ListModel with the results ''' search_term = self.ui.personProjectSearchForValue.text().toUtf8() if not search_term: self.showWarning(self.trUtf8('Empty Search Term'), self.trUtf8('Please enter a search term')) else: selectedPlugins = list(self.ProjectWizardPluginListModel.checkedPlugins) possibleTargets = [] for i in selectedPlugins: pluginTargets = self.PluginManager.getPluginByName(i, 'Input').plugin_object.searchForTargets(search_term) if pluginTargets: possibleTargets.extend(pluginTargets) self.ProjectWizardPossibleTargetsTable = ProjectWizardPossibleTargetsTable(possibleTargets, self) self.ui.personProjectSearchResultsTable.setModel(self.ProjectWizardPossibleTargetsTable) self.ui.personProjectSelectedTargetsTable.setModel(self.ProjectWizardSelectedTargetsTable) def loadConfiguredPlugins(self): ''' Returns a list with the configured plugins that can be used ''' self.PluginManager = PluginManagerSingleton.get() self.PluginManager.setCategoriesFilter({ 'Input': InputPlugin}) self.PluginManager.setPluginPlaces([os.path.join(os.getcwdu(), 'plugins')]) self.PluginManager.locatePlugins() self.PluginManager.loadPlugins() pluginList = sorted(self.PluginManager.getAllPlugins(), key=lambda x: x.name) return [[plugin, 0] for plugin in pluginList ] def getNameForConfigurationOption(self, key): pass def showPluginsSearchOptions(self): ''' Loads the search options of all the selected plugins and populates the relevant UI elements with input fields for the string options and checkboxes for the boolean options ''' pl = [] for pluginName in list(set([target['pluginName'] for target in self.ProjectWizardSelectedTargetsTable.targets])): plugin = self.PluginManager.getPluginByName(pluginName, 'Input') self.enabledPlugins.append(plugin) pl.append(plugin) ''' Build the configuration page from the available saerch options and add the page to the stackwidget ''' page = QWidget() page.setObjectName(_fromUtf8('searchconfig_page_' + plugin.name)) scroll = QScrollArea() scroll.setWidgetResizable(True) layout = QVBoxLayout() titleLabel = QLabel(_fromUtf8(plugin.name + self.trUtf8(' Search Options'))) layout.addWidget(titleLabel) vboxWidget = QWidget() vboxWidget.setObjectName(_fromUtf8('searchconfig_vboxwidget_container_' + plugin.name)) vbox = QGridLayout() vbox.setObjectName(_fromUtf8('searchconfig_vbox_container_' + plugin.name)) gridLayoutRowIndex = 0 ''' Load the String options first ''' pluginStringOptions = plugin.plugin_object.readConfiguration('search_string_options')[1] if pluginStringOptions: for idx, item in enumerate(pluginStringOptions.keys()): itemLabel = plugin.plugin_object.getLabelForKey(item) label = QLabel() label.setObjectName(_fromUtf8('searchconfig_string_label_' + item)) label.setText(itemLabel) vbox.addWidget(label, idx, 0) value = QLineEdit() value.setObjectName(_fromUtf8('searchconfig_string_value_' + item)) value.setText(pluginStringOptions[item]) vbox.addWidget(value, idx, 1) gridLayoutRowIndex = idx + 1 ''' Load the boolean options ''' pluginBooleanOptions = plugin.plugin_object.readConfiguration('search_boolean_options')[1] if pluginBooleanOptions: for idx, item in enumerate(pluginBooleanOptions.keys()): itemLabel = plugin.plugin_object.getLabelForKey(item) cb = QCheckBox(itemLabel) cb.setObjectName(_fromUtf8('searchconfig_boolean_label_' + item)) if pluginBooleanOptions[item] == 'True': cb.toggle() vbox.addWidget(cb, gridLayoutRowIndex + idx, 0) #If there are no search options just show a message if not pluginBooleanOptions and not pluginStringOptions: label = QLabel() label.setObjectName(_fromUtf8('no_search_config_options')) label.setText(self.trUtf8('This plugin does not offer any search options.')) vbox.addWidget(label,0,0) vboxWidget.setLayout(vbox) scroll.setWidget(vboxWidget) layout.addWidget(scroll) layout.addStretch(1) page.setLayout(layout) self.ui.searchConfiguration.addWidget(page) self.ui.searchConfiguration.setCurrentIndex(0) self.SearchConfigPluginConfigurationListModel = PluginConfigurationListModel(pl, self) self.SearchConfigPluginConfigurationListModel.checkPluginConfiguration() self.ui.personProjectWizardSearchConfigPluginsList.setModel(self.SearchConfigPluginConfigurationListModel) self.ui.personProjectWizardSearchConfigPluginsList.clicked.connect(self.changePluginConfigurationPage) def changePluginConfigurationPage(self, modelIndex): ''' Called when the user clicks on a plugin in the list of the PluginConfiguration. This shows the relevant page with that plugin's configuration options ''' self.ui.searchConfiguration.setCurrentIndex(modelIndex.row()) def readSearchConfiguration(self): ''' Reads all the search configuration options for the enabled plugins and and returns a list of the enabled plugins and their options. ''' enabledPlugins = [] pages = (self.ui.searchConfiguration.widget(i) for i in range(self.ui.searchConfiguration.count())) for page in pages: for widg in [ scrollarea.children() for scrollarea in page.children() if type(scrollarea) == QScrollArea]: for i in widg[0].children(): plugin_name = str(i.objectName().replace('searchconfig_vboxwidget_container_', '')) string_options = {} for j in i.findChildren(QLabel): if str(j.text()).startswith('searchconfig'): string_options[str(j.objectName().replace('searchconfig_string_label_', ''))] = str(i.findChild(QLineEdit, j.objectName().replace('label', 'value')).text()) boolean_options = {} for k in i.findChildren(QCheckBox): boolean_options[str(k.objectName().replace('searchconfig_boolean_label_', ''))] = str(k.isChecked()) enabledPlugins.append({'pluginName':plugin_name, 'searchOptions':{'string':string_options, 'boolean':boolean_options}}) return enabledPlugins
gpl-3.0
WhireCrow/openwrt-mt7620
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/usr/lib/python2.7/distutils/command/check.py
32
5369
"""distutils.command.check Implements the Distutils 'check' command. """ __revision__ = "$Id$" from distutils.core import Command from distutils.dist import PKG_INFO_ENCODING from distutils.errors import DistutilsSetupError try: # docutils is installed from docutils.utils import Reporter from docutils.parsers.rst import Parser from docutils import frontend from docutils import nodes from StringIO import StringIO class SilentReporter(Reporter): def __init__(self, source, report_level, halt_level, stream=None, debug=0, encoding='ascii', error_handler='replace'): self.messages = [] Reporter.__init__(self, source, report_level, halt_level, stream, debug, encoding, error_handler) def system_message(self, level, message, *children, **kwargs): self.messages.append((level, message, children, kwargs)) HAS_DOCUTILS = True except ImportError: # docutils is not installed HAS_DOCUTILS = False class check(Command): """This command checks the meta-data of the package. """ description = ("perform some checks on the package") user_options = [('metadata', 'm', 'Verify meta-data'), ('restructuredtext', 'r', ('Checks if long string meta-data syntax ' 'are reStructuredText-compliant')), ('strict', 's', 'Will exit with an error if a check fails')] boolean_options = ['metadata', 'restructuredtext', 'strict'] def initialize_options(self): """Sets default values for options.""" self.restructuredtext = 0 self.metadata = 1 self.strict = 0 self._warnings = 0 def finalize_options(self): pass def warn(self, msg): """Counts the number of warnings that occurs.""" self._warnings += 1 return Command.warn(self, msg) def run(self): """Runs the command.""" # perform the various tests if self.metadata: self.check_metadata() if self.restructuredtext: if HAS_DOCUTILS: self.check_restructuredtext() elif self.strict: raise DistutilsSetupError('The docutils package is needed.') # let's raise an error in strict mode, if we have at least # one warning if self.strict and self._warnings > 0: raise DistutilsSetupError('Please correct your package.') def check_metadata(self): """Ensures that all required elements of meta-data are supplied. name, version, URL, (author and author_email) or (maintainer and maintainer_email)). Warns if any are missing. """ metadata = self.distribution.metadata missing = [] for attr in ('name', 'version', 'url'): if not (hasattr(metadata, attr) and getattr(metadata, attr)): missing.append(attr) if missing: self.warn("missing required meta-data: %s" % ', '.join(missing)) if metadata.author: if not metadata.author_email: self.warn("missing meta-data: if 'author' supplied, " + "'author_email' must be supplied too") elif metadata.maintainer: if not metadata.maintainer_email: self.warn("missing meta-data: if 'maintainer' supplied, " + "'maintainer_email' must be supplied too") else: self.warn("missing meta-data: either (author and author_email) " + "or (maintainer and maintainer_email) " + "must be supplied") def check_restructuredtext(self): """Checks if the long string fields are reST-compliant.""" data = self.distribution.get_long_description() if not isinstance(data, unicode): data = data.decode(PKG_INFO_ENCODING) for warning in self._check_rst_data(data): line = warning[-1].get('line') if line is None: warning = warning[1] else: warning = '%s (line %s)' % (warning[1], line) self.warn(warning) def _check_rst_data(self, data): """Returns warnings when the provided data doesn't compile.""" source_path = StringIO() parser = Parser() settings = frontend.OptionParser().get_default_values() settings.tab_width = 4 settings.pep_references = None settings.rfc_references = None reporter = SilentReporter(source_path, settings.report_level, settings.halt_level, stream=settings.warning_stream, debug=settings.debug, encoding=settings.error_encoding, error_handler=settings.error_encoding_error_handler) document = nodes.document(settings, reporter, source=source_path) document.note_source(source_path, -1) try: parser.parse(data, document) except AttributeError: reporter.messages.append((-1, 'Could not finish the parsing.', '', {})) return reporter.messages
gpl-2.0
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_11_01/operations/_operations.py
1
4744
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from azure.mgmt.core.exceptions import ARMErrorFormat from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class Operations(object): """Operations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2018_11_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs # type: Any ): # type: (...) -> Iterable["_models.OperationListResult"] """Lists all of the available Network Rest API operations. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either OperationListResult or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2018_11_01.models.OperationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2018-11-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request def extract_data(pipeline_response): deserialized = self._deserialize('OperationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list.metadata = {'url': '/providers/Microsoft.Network/operations'} # type: ignore
mit
francesconuma/yowsup
yowsup/demos/cli/cli.py
57
6023
import threading, inspect, shlex try: import Queue except ImportError: import queue as Queue try: import readline except ImportError: import pyreadline as readline class clicmd(object): def __init__(self, desc, order = 0): self.desc = desc self.order = order def __call__(self, fn): fn.clidesc = self.desc fn.cliorder = self.order return fn class Cli(object): def __init__(self): self.sentCache = {} self.commands = {} self.acceptingInput = False self.lastPrompt = True self.blockingQueue = Queue.Queue() self._queuedCmds = [] readline.set_completer(self.complete) readline.parse_and_bind('tab: complete') members = inspect.getmembers(self, predicate = inspect.ismethod) for m in members: if hasattr(m[1], "clidesc"): fname = m[0] fn = m[1] try: cmd, subcommand = fname.split('_') except ValueError: cmd = fname subcommand = "_" if not cmd in self.commands: self.commands[cmd] = {} self.commands[cmd][subcommand] = { "args": inspect.getargspec(fn)[0][1:], "optional": len(inspect.getargspec(fn)[3]) if inspect.getargspec(fn)[3] else 0, "desc": fn.clidesc, "fn": fn, "order": fn.cliorder } #self.cv = threading.Condition() self.inputThread = threading.Thread(target = self.startInputThread) self.inputThread.daemon = True def queueCmd(self, cmd): self._queuedCmds.append(cmd) def startInput(self): self.inputThread.start() ################### cmd input parsing #################### def print_usage(self): line_width = 100 outArr = [] def addToOut(ind, cmd): if ind >= len(outArr): outArr.extend([None] * (ind - len(outArr) + 1)) if outArr[ind] != None: for i in range(len(outArr) - 1, 0, -1): if outArr[i] is None: outArr[i] = outArr[ind] outArr[ind] = cmd return outArr.append(cmd) else: outArr[ind] = cmd for cmd, subcommands in self.commands.items(): for subcmd, subcmdDetails in subcommands.items(): out = "" out += ("/%s " % cmd).ljust(15) out += ("%s " % subcmd if subcmd != "_" else "").ljust(15) args = ("%s " % " ".join(["<%s>" % c for c in subcmdDetails["args"][0:len(subcmdDetails["args"])-subcmdDetails["optional"]]])) args += ("%s " % " ".join(["[%s]" % c for c in subcmdDetails["args"][len(subcmdDetails["args"])-subcmdDetails["optional"]:]])) out += args.ljust(30) out += subcmdDetails["desc"].ljust(20) addToOut(subcmdDetails["order"], out) print("----------------------------------------------") print("\n" . join(outArr)) print("----------------------------------------------") def execCmd(self, cmdInput): cmdInput = cmdInput.rstrip() if not len(cmdInput) > 1: return if cmdInput.startswith("/"): cmdInput = cmdInput[1:] else: self.print_usage() return cmdInputDissect = [c for c in shlex.split(cmdInput) if c] cmd = cmdInputDissect[0] if not cmd in self.commands: return self.print_usage() cmdData = self.commands[cmd] if len(cmdData) == 1 and "_" in cmdData: subcmdData = cmdData["_"] args = cmdInputDissect[1:] if len(cmdInputDissect) > 1 else [] else: args = cmdInputDissect[2:] if len(cmdInputDissect) > 2 else [] subcmd = cmdInputDissect[1] if len(cmdInputDissect) > 1 else "" if subcmd not in cmdData: return self.print_usage() subcmdData = cmdData[subcmd] targetFn = subcmdData["fn"] if len(subcmdData["args"]) < len(args) or len(subcmdData["args"]) - subcmdData["optional"] > len(args): return self.print_usage() return self.doExecCmd(lambda :targetFn(*args)) def doExecCmd(self, fn): return fn() def startInputThread(self): #cv.acquire() # Fix Python 2.x. global input try: input = raw_input except NameError: pass while(True): cmd = self._queuedCmds.pop(0) if len(self._queuedCmds) else input(self.getPrompt()).strip() wait = self.execCmd(cmd) if wait: self.acceptingInput = False self.blockingQueue.get(True) #cv.wait() #self.inputThread.wait() self.acceptingInput = True #cv.release() def getPrompt(self): return "[%s]:" % ("connected" if self.connected else "offline") def printPrompt(self): #return "Enter Message or command: (/%s)" % ", /".join(self.commandMappings) print(self.getPrompt()) def output(self, message, tag = "general", prompt = True): if self.acceptingInput == True and self.lastPrompt is True: print("") self.lastPrompt = prompt if tag is not None: print("%s: %s" % (tag, message)) else: print(message) if prompt: self.printPrompt() def complete(self, text, state): if state == 0: for cmd in self.commands: if cmd.startswith(text) and cmd != text: return cmd def notifyInputThread(self): self.blockingQueue.put(1) if __name__ == "__main__": c = Cli() c.print_usage()
gpl-3.0
globau/servo
tests/wpt/css-tests/tools/wptserve/tests/functional/test_server.py
86
1285
import unittest import urllib2 import wptserve from .base import TestUsingServer class TestFileHandler(TestUsingServer): def test_not_handled(self): with self.assertRaises(urllib2.HTTPError) as cm: resp = self.request("/not_existing") self.assertEqual(cm.exception.code, 404) class TestRewriter(TestUsingServer): def test_rewrite(self): @wptserve.handlers.handler def handler(request, response): return request.request_path route = ("GET", "/test/rewritten", handler) self.server.rewriter.register("GET", "/test/original", route[1]) self.server.router.register(*route) resp = self.request("/test/original") self.assertEqual(200, resp.getcode()) self.assertEqual("/test/rewritten", resp.read()) class TestRequestHandler(TestUsingServer): def test_exception(self): @wptserve.handlers.handler def handler(request, response): raise Exception route = ("GET", "/test/raises", handler) self.server.router.register(*route) with self.assertRaises(urllib2.HTTPError) as cm: resp = self.request("/test/raises") self.assertEqual(cm.exception.code, 500) if __name__ == "__main__": unittest.main()
mpl-2.0
AutorestCI/azure-sdk-for-python
azure-batch/azure/batch/models/pool_patch_parameter.py
1
3692
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class PoolPatchParameter(Model): """The set of changes to be made to a pool. :param start_task: A task to run on each compute node as it joins the pool. The task runs when the node is added to the pool or when the node is restarted. If this element is present, it overwrites any existing start task. If omitted, any existing start task is left unchanged. :type start_task: ~azure.batch.models.StartTask :param certificate_references: A list of certificates to be installed on each compute node in the pool. If this element is present, it replaces any existing certificate references configured on the pool. If omitted, any existing certificate references are left unchanged. For Windows compute nodes, the Batch service installs the certificates to the specified certificate store and location. For Linux compute nodes, the certificates are stored in a directory inside the task working directory and an environment variable AZ_BATCH_CERTIFICATES_DIR is supplied to the task to query for this location. For certificates with visibility of 'remoteUser', a 'certs' directory is created in the user's home directory (e.g., /home/{user-name}/certs) and certificates are placed in that directory. :type certificate_references: list[~azure.batch.models.CertificateReference] :param application_package_references: A list of application packages to be installed on each compute node in the pool. Changes to application package references affect all new compute nodes joining the pool, but do not affect compute nodes that are already in the pool until they are rebooted or reimaged. If this element is present, it replaces any existing application package references. If you specify an empty collection, then all application package references are removed from the pool. If omitted, any existing application package references are left unchanged. :type application_package_references: list[~azure.batch.models.ApplicationPackageReference] :param metadata: A list of name-value pairs associated with the pool as metadata. If this element is present, it replaces any existing metadata configured on the pool. If you specify an empty collection, any metadata is removed from the pool. If omitted, any existing metadata is left unchanged. :type metadata: list[~azure.batch.models.MetadataItem] """ _attribute_map = { 'start_task': {'key': 'startTask', 'type': 'StartTask'}, 'certificate_references': {'key': 'certificateReferences', 'type': '[CertificateReference]'}, 'application_package_references': {'key': 'applicationPackageReferences', 'type': '[ApplicationPackageReference]'}, 'metadata': {'key': 'metadata', 'type': '[MetadataItem]'}, } def __init__(self, start_task=None, certificate_references=None, application_package_references=None, metadata=None): self.start_task = start_task self.certificate_references = certificate_references self.application_package_references = application_package_references self.metadata = metadata
mit
hohoins/ml
cifar10/cifar10_eval.py
1
5552
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Evaluation for CIFAR-10. Accuracy: cifar10_train.py achieves 83.0% accuracy after 100K steps (256 epochs of data) as judged by cifar10_eval.py. Speed: On a single Tesla K40, cifar10_train.py processes a single batch of 128 images in 0.25-0.35 sec (i.e. 350 - 600 images /sec). The model reaches ~86% accuracy after 100K steps in 8 hours of training time. Usage: Please see the tutorial and website for how to download the CIFAR-10 data set, compile the program and train the model. http://tensorflow.org/tutorials/deep_cnn/ """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import math import time import numpy as np import tensorflow as tf import cifar10 FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('eval_dir', '/tmp/cifar10_eval', """Directory where to write event logs.""") tf.app.flags.DEFINE_string('eval_data', 'test', """Either 'test' or 'train_eval'.""") tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/cifar10_train', """Directory where to read model checkpoints.""") tf.app.flags.DEFINE_integer('eval_interval_secs', 1, """How often to run the eval.""") tf.app.flags.DEFINE_integer('num_examples', 10000, """Number of examples to run.""") tf.app.flags.DEFINE_boolean('run_once', False, """Whether to run eval only once.""") def eval_once(saver, summary_writer, top_k_op, summary_op): """Run Eval once. Args: saver: Saver. summary_writer: Summary writer. top_k_op: Top K op. summary_op: Summary op. """ with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: # Restores from checkpoint saver.restore(sess, ckpt.model_checkpoint_path) # Assuming model_checkpoint_path looks something like: # /my-favorite-path/cifar10_train/model.ckpt-0, # extract global_step from it. global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] else: print('No checkpoint file found') return # Start the queue runners. coord = tf.train.Coordinator() try: threads = [] for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS): threads.extend(qr.create_threads(sess, coord=coord, daemon=True, start=True)) num_iter = int(math.ceil(FLAGS.num_examples / FLAGS.batch_size)) true_count = 0 # Counts the number of correct predictions. total_sample_count = num_iter * FLAGS.batch_size step = 0 while step < num_iter and not coord.should_stop(): predictions = sess.run([top_k_op]) true_count += np.sum(predictions) step += 1 # Compute precision @ 1. precision = true_count / total_sample_count print('%s: precision @ 1 = %.3f' % (datetime.now(), precision)) summary = tf.Summary() summary.ParseFromString(sess.run(summary_op)) summary.value.add(tag='Precision @ 1', simple_value=precision) summary_writer.add_summary(summary, global_step) except Exception as e: # pylint: disable=broad-except coord.request_stop(e) coord.request_stop() coord.join(threads, stop_grace_period_secs=10) def evaluate(): """Eval CIFAR-10 for a number of steps.""" with tf.Graph().as_default(): # Get images and labels for CIFAR-10. eval_data = FLAGS.eval_data == 'test' images, labels = cifar10.inputs(eval_data=eval_data) # Build a Graph that computes the logits predictions from the # inference model. logits = cifar10.inference(images) # Calculate predictions. top_k_op = tf.nn.in_top_k(logits, labels, 1) # Restore the moving average version of the learned variables for eval. variable_averages = tf.train.ExponentialMovingAverage( cifar10.MOVING_AVERAGE_DECAY) variables_to_restore = variable_averages.variables_to_restore() saver = tf.train.Saver(variables_to_restore) # Build the summary operation based on the TF collection of Summaries. summary_op = tf.summary.merge_all() graph_def = tf.get_default_graph().as_graph_def() summary_writer = tf.summary.FileWriter(FLAGS.eval_dir, graph_def=graph_def) while True: eval_once(saver, summary_writer, top_k_op, summary_op) if FLAGS.run_once: break time.sleep(FLAGS.eval_interval_secs) def main(argv=None): # pylint: disable=unused-argument cifar10.maybe_download_and_extract() if tf.gfile.Exists(FLAGS.eval_dir): tf.gfile.DeleteRecursively(FLAGS.eval_dir) tf.gfile.MakeDirs(FLAGS.eval_dir) evaluate() if __name__ == '__main__': tf.app.run()
apache-2.0
gkoelln/youtube-dl
test/test_socks.py
50
3500
#!/usr/bin/env python # coding: utf-8 from __future__ import unicode_literals # Allow direct execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import random import subprocess from test.helper import ( FakeYDL, get_params, ) from youtube_dl.compat import ( compat_str, compat_urllib_request, ) class TestMultipleSocks(unittest.TestCase): @staticmethod def _check_params(attrs): params = get_params() for attr in attrs: if attr not in params: print('Missing %s. Skipping.' % attr) return return params def test_proxy_http(self): params = self._check_params(['primary_proxy', 'primary_server_ip']) if params is None: return ydl = FakeYDL({ 'proxy': params['primary_proxy'] }) self.assertEqual( ydl.urlopen('http://yt-dl.org/ip').read().decode('utf-8'), params['primary_server_ip']) def test_proxy_https(self): params = self._check_params(['primary_proxy', 'primary_server_ip']) if params is None: return ydl = FakeYDL({ 'proxy': params['primary_proxy'] }) self.assertEqual( ydl.urlopen('https://yt-dl.org/ip').read().decode('utf-8'), params['primary_server_ip']) def test_secondary_proxy_http(self): params = self._check_params(['secondary_proxy', 'secondary_server_ip']) if params is None: return ydl = FakeYDL() req = compat_urllib_request.Request('http://yt-dl.org/ip') req.add_header('Ytdl-request-proxy', params['secondary_proxy']) self.assertEqual( ydl.urlopen(req).read().decode('utf-8'), params['secondary_server_ip']) def test_secondary_proxy_https(self): params = self._check_params(['secondary_proxy', 'secondary_server_ip']) if params is None: return ydl = FakeYDL() req = compat_urllib_request.Request('https://yt-dl.org/ip') req.add_header('Ytdl-request-proxy', params['secondary_proxy']) self.assertEqual( ydl.urlopen(req).read().decode('utf-8'), params['secondary_server_ip']) class TestSocks(unittest.TestCase): _SKIP_SOCKS_TEST = True def setUp(self): if self._SKIP_SOCKS_TEST: return self.port = random.randint(20000, 30000) self.server_process = subprocess.Popen([ 'srelay', '-f', '-i', '127.0.0.1:%d' % self.port], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def tearDown(self): if self._SKIP_SOCKS_TEST: return self.server_process.terminate() self.server_process.communicate() def _get_ip(self, protocol): if self._SKIP_SOCKS_TEST: return '127.0.0.1' ydl = FakeYDL({ 'proxy': '%s://127.0.0.1:%d' % (protocol, self.port), }) return ydl.urlopen('http://yt-dl.org/ip').read().decode('utf-8') def test_socks4(self): self.assertTrue(isinstance(self._get_ip('socks4'), compat_str)) def test_socks4a(self): self.assertTrue(isinstance(self._get_ip('socks4a'), compat_str)) def test_socks5(self): self.assertTrue(isinstance(self._get_ip('socks5'), compat_str)) if __name__ == '__main__': unittest.main()
unlicense
levilucio/SyVOLT
UMLRT2Kiltera_MM/transformation/from_MPS/HConnectOPState2CProcDefTransition2InstotherInTransitions.py
1
5322
from core.himesis import Himesis import uuid class HConnectOPState2CProcDefTransition2InstotherInTransitions(Himesis): def __init__(self): """ Creates the himesis graph representing the DSLTrans rule ConnectOPState2CProcDefTransition2InstotherInTransitions. """ # Flag this instance as compiled now self.is_compiled = True super(HConnectOPState2CProcDefTransition2InstotherInTransitions, self).__init__(name='HConnectOPState2CProcDefTransition2InstotherInTransitions', num_nodes=0, edges=[]) # Set the graph attributes self["mm__"] = ['HimesisMM'] self["name"] = """ConnectOPState2CProcDefTransition2InstotherInTransitions""" self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'ConnectOPState2CProcDefTransition2InstotherInTransitions') # match model. We only support one match model self.add_node() self.vs[0]["mm__"] = """MatchModel""" # apply model node self.add_node() self.vs[1]["mm__"] = """ApplyModel""" # paired with relation between match and apply models self.add_node() self.vs[2]["mm__"] = """paired_with""" self.vs[2]["attr1"] = """ConnectOPState2CProcDefTransition2InstotherInTransitions""" # match class Transition(7.3.m.0Transition) node self.add_node() self.vs[3]["mm__"] = """Transition""" self.vs[3]["attr1"] = """+""" # match class IN1(7.3.m.1IN1) node self.add_node() self.vs[4]["mm__"] = """IN1""" self.vs[4]["attr1"] = """+""" # match class State(7.3.m.2State) node self.add_node() self.vs[5]["mm__"] = """State""" self.vs[5]["attr1"] = """+""" # match class Vertex(7.3.m.3Vertex) node self.add_node() self.vs[6]["mm__"] = """Vertex""" self.vs[6]["attr1"] = """+""" # apply class ConditionSet(7.3.a.0ConditionSet) node self.add_node() self.vs[7]["mm__"] = """ConditionSet""" self.vs[7]["attr1"] = """1""" # apply class ConditionBranch(7.3.a.1ConditionBranch) node self.add_node() self.vs[8]["mm__"] = """ConditionBranch""" self.vs[8]["attr1"] = """1""" # apply class Expr(7.3.a.2Expr) node self.add_node() self.vs[9]["mm__"] = """Expr""" self.vs[9]["attr1"] = """1""" # apply class Inst(7.3.a.3Inst) node self.add_node() self.vs[10]["mm__"] = """Inst""" self.vs[10]["attr1"] = """1""" # match association State--transitions-->Transition node self.add_node() self.vs[11]["attr1"] = """transitions""" self.vs[11]["mm__"] = """directLink_S""" # match association Transition--type-->IN1 node self.add_node() self.vs[12]["attr1"] = """type""" self.vs[12]["mm__"] = """directLink_S""" # match association Transition--src-->Vertex node self.add_node() self.vs[13]["attr1"] = """src""" self.vs[13]["mm__"] = """directLink_S""" # apply association ConditionSet--branches-->ConditionBranch node self.add_node() self.vs[14]["attr1"] = """branches""" self.vs[14]["mm__"] = """directLink_T""" # apply association ConditionBranch--if-->Expr node self.add_node() self.vs[15]["attr1"] = """if""" self.vs[15]["mm__"] = """directLink_T""" # apply association ConditionBranch--then-->Inst node self.add_node() self.vs[16]["attr1"] = """then""" self.vs[16]["mm__"] = """directLink_T""" # backward association ConditionSet-->Statenode self.add_node() self.vs[17]["mm__"] = """backward_link""" # backward association Inst-->Transitionnode self.add_node() self.vs[18]["mm__"] = """backward_link""" # Add the edges self.add_edges([ (0,3), # matchmodel -> match_class Transition(7.3.m.0Transition) (0,4), # matchmodel -> match_class IN1(7.3.m.1IN1) (0,5), # matchmodel -> match_class State(7.3.m.2State) (0,6), # matchmodel -> match_class Vertex(7.3.m.3Vertex) (1,7), # applymodel -> apply_classConditionSet(7.3.a.0ConditionSet) (1,8), # applymodel -> apply_classConditionBranch(7.3.a.1ConditionBranch) (1,9), # applymodel -> apply_classExpr(7.3.a.2Expr) (1,10), # applymodel -> apply_classInst(7.3.a.3Inst) (5,11), # match classState(7.3.m.2State) -> association transitions (11,3), # associationtransitions -> match_classState(7.3.m.0Transition) (3,12), # match classTransition(7.3.m.0Transition) -> association type (12,4), # associationtype -> match_classTransition(7.3.m.1IN1) (3,13), # match classTransition(7.3.m.0Transition) -> association src (13,6), # associationsrc -> match_classTransition(7.3.m.3Vertex) (7,14), # apply class ConditionSet(7.3.a.0ConditionSet) -> association branches (14,8), # associationbranches -> apply_classConditionBranch(7.3.a.1ConditionBranch) (8,15), # apply class ConditionBranch(7.3.a.1ConditionBranch) -> association if (15,9), # associationif -> apply_classExpr(7.3.a.2Expr) (8,16), # apply class ConditionBranch(7.3.a.1ConditionBranch) -> association then (16,10), # associationthen -> apply_classInst(7.3.a.3Inst) (7,17), # apply class ConditionSet(7.3.m.2State) -> backward_association (17,5), # backward_associationState -> match_class State(7.3.m.2State) (10,18), # apply class Inst(7.3.m.0Transition) -> backward_association (18,3), # backward_associationTransition -> match_class Transition(7.3.m.0Transition) (0,2), # matchmodel -> pairedwith (2,1) # pairedwith -> applyModel ]) self["equations"] = [((9,'literal'),('concat',(('constant','enp=A'),('concat',((6,'name'),('constant','A')))))),]
mit
eesatfan/openpli-enigma2
lib/python/Components/ServiceScan.py
6
7468
from enigma import eComponentScan, iDVBFrontend from Components.NimManager import nimmanager as nimmgr from Components.Converter.ChannelNumbers import channelnumbers class ServiceScan: Idle = 1 Running = 2 Done = 3 Error = 4 Errors = { 0: "error starting scanning", 1: "error while scanning", 2: "no resource manager", 3: "no channel list" } def scanStatusChanged(self): if self.state == self.Running: self.progressbar.setValue(self.scan.getProgress()) self.lcd_summary.updateProgress(self.scan.getProgress()) if self.scan.isDone(): errcode = self.scan.getError() if errcode == 0: self.state = self.Done self.servicelist.listAll() else: self.state = self.Error self.errorcode = errcode self.network.setText("") self.transponder.setText("") else: result = self.foundServices + self.scan.getNumServices() percentage = self.scan.getProgress() #TRANSLATORS: The stb is performing a channel scan, progress percentage is printed in '%d' (and '%%' will show a single '%' symbol) message = ngettext("Scanning - %d%% completed", "Scanning - %d%% completed", percentage) % percentage message += ", " #TRANSLATORS: Intermediate scanning result, '%d' channel(s) have been found so far message += ngettext("%d channel found", "%d channels found", result) % result self.text.setText(message) transponder = self.scan.getCurrentTransponder() network = "" tp_text = "" if transponder: tp_type = transponder.getSystem() if tp_type == iDVBFrontend.feSatellite: network = _("Satellite") tp = transponder.getDVBS() orb_pos = tp.orbital_position try: sat_name = str(nimmgr.getSatDescription(orb_pos)) except KeyError: sat_name = "" if orb_pos > 1800: # west orb_pos = 3600 - orb_pos h = _("W") else: h = _("E") if ("%d.%d" % (orb_pos/10, orb_pos%10)) in sat_name: network = sat_name else: network = ("%s %d.%d %s") % (sat_name, orb_pos / 10, orb_pos % 10, h) tp_text = { tp.System_DVB_S : "DVB-S", tp.System_DVB_S2 : "DVB-S2" }.get(tp.system, "") if tp_text == "DVB-S2": tp_text = ("%s %s") % ( tp_text, { tp.Modulation_Auto : "Auto", tp.Modulation_QPSK : "QPSK", tp.Modulation_8PSK : "8PSK", tp.Modulation_QAM16 : "QAM16" }.get(tp.modulation, "")) tp_text = ("%s %d%c / %d / %s") % ( tp_text, tp.frequency/1000, { tp.Polarisation_Horizontal : 'H', tp.Polarisation_Vertical : 'V', tp.Polarisation_CircularLeft : 'L', tp.Polarisation_CircularRight : 'R' }.get(tp.polarisation, ' '), tp.symbol_rate/1000, { tp.FEC_Auto : "AUTO", tp.FEC_1_2 : "1/2", tp.FEC_2_3 : "2/3", tp.FEC_3_4 : "3/4", tp.FEC_5_6 : "5/6", tp.FEC_7_8 : "7/8", tp.FEC_8_9 : "8/9", tp.FEC_3_5 : "3/5", tp.FEC_4_5 : "4/5", tp.FEC_9_10 : "9/10", tp.FEC_None : "NONE" }.get(tp.fec, "")) elif tp_type == iDVBFrontend.feCable: network = _("Cable") tp = transponder.getDVBC() tp_text = ("DVB-C %s %d / %d / %s") %( { tp.Modulation_Auto : "AUTO", tp.Modulation_QAM16 : "QAM16", tp.Modulation_QAM32 : "QAM32", tp.Modulation_QAM64 : "QAM64", tp.Modulation_QAM128 : "QAM128", tp.Modulation_QAM256 : "QAM256" }.get(tp.modulation, ""), tp.frequency, tp.symbol_rate/1000, { tp.FEC_Auto : "AUTO", tp.FEC_1_2 : "1/2", tp.FEC_2_3 : "2/3", tp.FEC_3_4 : "3/4", tp.FEC_5_6 : "5/6", tp.FEC_7_8 : "7/8", tp.FEC_8_9 : "8/9", tp.FEC_6_7 : "6/7", tp.FEC_None : "NONE" }.get(tp.fec_inner, "")) elif tp_type == iDVBFrontend.feTerrestrial: network = _("Terrestrial") tp = transponder.getDVBT() channel = channelnumbers.getChannelNumber(tp.frequency, self.scanList[self.run]["feid"]) if channel: channel = _("CH") + "%s " % channel freqMHz = "%0.1f MHz" % (tp.frequency/1000000.) tp_text = ("%s %s %s %s") %( { tp.System_DVB_T : "DVB-T", tp.System_DVB_T2 : "DVB-T2" }.get(tp.system, ""), { tp.Modulation_QPSK : "QPSK", tp.Modulation_QAM16 : "QAM16", tp.Modulation_QAM64 : "QAM64", tp.Modulation_Auto : "AUTO", tp.Modulation_QAM256 : "QAM256" }.get(tp.modulation, ""), "%s%s" % (channel, freqMHz.replace(".0","")), { tp.Bandwidth_8MHz : "Bw 8MHz", tp.Bandwidth_7MHz : "Bw 7MHz", tp.Bandwidth_6MHz : "Bw 6MHz", tp.Bandwidth_Auto : "Bw Auto", tp.Bandwidth_5MHz : "Bw 5MHz", tp.Bandwidth_1_712MHz : "Bw 1.712MHz", tp.Bandwidth_10MHz : "Bw 10MHz" }.get(tp.bandwidth, "")) else: print "unknown transponder type in scanStatusChanged" self.network.setText(network) self.transponder.setText(tp_text) if self.state == self.Done: result = self.foundServices + self.scan.getNumServices() self.text.setText(ngettext("Scanning completed, %d channel found", "Scanning completed, %d channels found", result) % result) if self.state == self.Error: self.text.setText(_("ERROR - failed to scan (%s)!") % (self.Errors[self.errorcode]) ) if self.state == self.Done or self.state == self.Error: if self.run != len(self.scanList) - 1: self.foundServices += self.scan.getNumServices() self.execEnd() self.run += 1 self.execBegin() def __init__(self, progressbar, text, servicelist, passNumber, scanList, network, transponder, frontendInfo, lcd_summary): self.foundServices = 0 self.progressbar = progressbar self.text = text self.servicelist = servicelist self.passNumber = passNumber self.scanList = scanList self.frontendInfo = frontendInfo self.transponder = transponder self.network = network self.run = 0 self.lcd_summary = lcd_summary def doRun(self): self.scan = eComponentScan() self.frontendInfo.frontend_source = lambda : self.scan.getFrontend() self.feid = self.scanList[self.run]["feid"] self.flags = self.scanList[self.run]["flags"] self.networkid = 0 if self.scanList[self.run].has_key("networkid"): self.networkid = self.scanList[self.run]["networkid"] self.state = self.Idle self.scanStatusChanged() for x in self.scanList[self.run]["transponders"]: self.scan.addInitial(x) def updatePass(self): size = len(self.scanList) if size > 1: self.passNumber.setText(_("pass") + " " + str(self.run + 1) + "/" + str(size) + " (" + _("Tuner") + " " + str(self.scanList[self.run]["feid"]) + ")") def execBegin(self): self.doRun() self.updatePass() self.scan.statusChanged.get().append(self.scanStatusChanged) self.scan.newService.get().append(self.newService) self.servicelist.clear() self.state = self.Running err = self.scan.start(self.feid, self.flags, self.networkid) self.frontendInfo.updateFrontendData() if err: self.state = self.Error self.errorcode = 0 self.scanStatusChanged() def execEnd(self): self.scan.statusChanged.get().remove(self.scanStatusChanged) self.scan.newService.get().remove(self.newService) if not self.isDone(): print "*** warning *** scan was not finished!" del self.scan def isDone(self): return self.state == self.Done or self.state == self.Error def newService(self): newServiceName = self.scan.getLastServiceName() newServiceRef = self.scan.getLastServiceRef() self.servicelist.addItem((newServiceName, newServiceRef)) self.lcd_summary.updateService(newServiceName) def destroy(self): pass
gpl-2.0
fernandog/Medusa
ext/boto/cloudsearch2/domain.py
153
21247
# Copyright (c) 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # from boto.cloudsearch2.optionstatus import IndexFieldStatus from boto.cloudsearch2.optionstatus import ServicePoliciesStatus from boto.cloudsearch2.optionstatus import ExpressionStatus from boto.cloudsearch2.optionstatus import AvailabilityOptionsStatus from boto.cloudsearch2.optionstatus import ScalingParametersStatus from boto.cloudsearch2.document import DocumentServiceConnection from boto.cloudsearch2.search import SearchConnection def handle_bool(value): if value in [True, 'true', 'True', 'TRUE', 1]: return True return False class Domain(object): """ A Cloudsearch domain. :ivar name: The name of the domain. :ivar id: The internally generated unique identifier for the domain. :ivar created: A boolean which is True if the domain is created. It can take several minutes to initialize a domain when CreateDomain is called. Newly created search domains are returned with a False value for Created until domain creation is complete :ivar deleted: A boolean which is True if the search domain has been deleted. The system must clean up resources dedicated to the search domain when delete is called. Newly deleted search domains are returned from list_domains with a True value for deleted for several minutes until resource cleanup is complete. :ivar processing: True if processing is being done to activate the current domain configuration. :ivar num_searchable_docs: The number of documents that have been submittted to the domain and indexed. :ivar requires_index_document: True if index_documents needs to be called to activate the current domain configuration. :ivar search_instance_count: The number of search instances that are available to process search requests. :ivar search_instance_type: The instance type that is being used to process search requests. :ivar search_partition_count: The number of partitions across which the search index is spread. """ def __init__(self, layer1, data): """ Constructor - Create a domain object from a layer1 and data params :type layer1: :class:`boto.cloudsearch2.layer1.Layer1` object :param layer1: A :class:`boto.cloudsearch2.layer1.Layer1` object which is used to perform operations on the domain. """ self.layer1 = layer1 self.update_from_data(data) def update_from_data(self, data): self.created = data['Created'] self.deleted = data['Deleted'] self.processing = data['Processing'] self.requires_index_documents = data['RequiresIndexDocuments'] self.domain_id = data['DomainId'] self.domain_name = data['DomainName'] self.search_instance_count = data['SearchInstanceCount'] self.search_instance_type = data.get('SearchInstanceType', None) self.search_partition_count = data['SearchPartitionCount'] self._doc_service = data['DocService'] self._service_arn = data['ARN'] self._search_service = data['SearchService'] @property def service_arn(self): return self._service_arn @property def doc_service_endpoint(self): return self._doc_service['Endpoint'] @property def search_service_endpoint(self): return self._search_service['Endpoint'] @property def created(self): return self._created @created.setter def created(self, value): self._created = handle_bool(value) @property def deleted(self): return self._deleted @deleted.setter def deleted(self, value): self._deleted = handle_bool(value) @property def processing(self): return self._processing @processing.setter def processing(self, value): self._processing = handle_bool(value) @property def requires_index_documents(self): return self._requires_index_documents @requires_index_documents.setter def requires_index_documents(self, value): self._requires_index_documents = handle_bool(value) @property def search_partition_count(self): return self._search_partition_count @search_partition_count.setter def search_partition_count(self, value): self._search_partition_count = int(value) @property def search_instance_count(self): return self._search_instance_count @search_instance_count.setter def search_instance_count(self, value): self._search_instance_count = int(value) @property def name(self): return self.domain_name @property def id(self): return self.domain_id def delete(self): """ Delete this domain and all index data associated with it. """ return self.layer1.delete_domain(self.name) def get_analysis_schemes(self): """ Return a list of Analysis Scheme objects. """ return self.layer1.describe_analysis_schemes(self.name) def get_availability_options(self): """ Return a :class:`boto.cloudsearch2.option.AvailabilityOptionsStatus` object representing the currently defined availability options for the domain. :return: OptionsStatus object :rtype: :class:`boto.cloudsearch2.option.AvailabilityOptionsStatus` object """ return AvailabilityOptionsStatus( self, refresh_fn=self.layer1.describe_availability_options, refresh_key=['DescribeAvailabilityOptionsResponse', 'DescribeAvailabilityOptionsResult', 'AvailabilityOptions'], save_fn=self.layer1.update_availability_options) def get_scaling_options(self): """ Return a :class:`boto.cloudsearch2.option.ScalingParametersStatus` object representing the currently defined scaling options for the domain. :return: ScalingParametersStatus object :rtype: :class:`boto.cloudsearch2.option.ScalingParametersStatus` object """ return ScalingParametersStatus( self, refresh_fn=self.layer1.describe_scaling_parameters, refresh_key=['DescribeScalingParametersResponse', 'DescribeScalingParametersResult', 'ScalingParameters'], save_fn=self.layer1.update_scaling_parameters) def get_access_policies(self): """ Return a :class:`boto.cloudsearch2.option.ServicePoliciesStatus` object representing the currently defined access policies for the domain. :return: ServicePoliciesStatus object :rtype: :class:`boto.cloudsearch2.option.ServicePoliciesStatus` object """ return ServicePoliciesStatus( self, refresh_fn=self.layer1.describe_service_access_policies, refresh_key=['DescribeServiceAccessPoliciesResponse', 'DescribeServiceAccessPoliciesResult', 'AccessPolicies'], save_fn=self.layer1.update_service_access_policies) def index_documents(self): """ Tells the search domain to start indexing its documents using the latest text processing options and IndexFields. This operation must be invoked to make options whose OptionStatus has OptionState of RequiresIndexDocuments visible in search results. """ self.layer1.index_documents(self.name) def get_index_fields(self, field_names=None): """ Return a list of index fields defined for this domain. :return: list of IndexFieldStatus objects :rtype: list of :class:`boto.cloudsearch2.option.IndexFieldStatus` object """ data = self.layer1.describe_index_fields(self.name, field_names) data = (data['DescribeIndexFieldsResponse'] ['DescribeIndexFieldsResult'] ['IndexFields']) return [IndexFieldStatus(self, d) for d in data] def create_index_field(self, field_name, field_type, default='', facet=False, returnable=False, searchable=False, sortable=False, highlight=False, source_field=None, analysis_scheme=None): """ Defines an ``IndexField``, either replacing an existing definition or creating a new one. :type field_name: string :param field_name: The name of a field in the search index. :type field_type: string :param field_type: The type of field. Valid values are int | double | literal | text | date | latlon | int-array | double-array | literal-array | text-array | date-array :type default: string or int :param default: The default value for the field. If the field is of type ``int`` this should be an integer value. Otherwise, it's a string. :type facet: bool :param facet: A boolean to indicate whether facets are enabled for this field or not. Does not apply to fields of type ``int, int-array, text, text-array``. :type returnable: bool :param returnable: A boolean to indicate whether values of this field can be returned in search results or used in ranking. :type searchable: bool :param searchable: A boolean to indicate whether search is enabled for this field or not. :type sortable: bool :param sortable: A boolean to indicate whether sorting is enabled for this field or not. Does not apply to fields of array types. :type highlight: bool :param highlight: A boolean to indicate whether highlighting is enabled for this field or not. Does not apply to fields of type ``double, int, date, latlon`` :type source_field: list of strings or string :param source_field: For array types, this is the list of fields to treat as the source. For singular types, pass a string only. :type analysis_scheme: string :param analysis_scheme: The analysis scheme to use for this field. Only applies to ``text | text-array`` field types :return: IndexFieldStatus objects :rtype: :class:`boto.cloudsearch2.option.IndexFieldStatus` object :raises: BaseException, InternalException, LimitExceededException, InvalidTypeException, ResourceNotFoundException """ index = { 'IndexFieldName': field_name, 'IndexFieldType': field_type } if field_type == 'literal': index['LiteralOptions'] = { 'FacetEnabled': facet, 'ReturnEnabled': returnable, 'SearchEnabled': searchable, 'SortEnabled': sortable } if default: index['LiteralOptions']['DefaultValue'] = default if source_field: index['LiteralOptions']['SourceField'] = source_field elif field_type == 'literal-array': index['LiteralArrayOptions'] = { 'FacetEnabled': facet, 'ReturnEnabled': returnable, 'SearchEnabled': searchable } if default: index['LiteralArrayOptions']['DefaultValue'] = default if source_field: index['LiteralArrayOptions']['SourceFields'] = \ ','.join(source_field) elif field_type == 'int': index['IntOptions'] = { 'DefaultValue': default, 'FacetEnabled': facet, 'ReturnEnabled': returnable, 'SearchEnabled': searchable, 'SortEnabled': sortable } if default: index['IntOptions']['DefaultValue'] = default if source_field: index['IntOptions']['SourceField'] = source_field elif field_type == 'int-array': index['IntArrayOptions'] = { 'FacetEnabled': facet, 'ReturnEnabled': returnable, 'SearchEnabled': searchable } if default: index['IntArrayOptions']['DefaultValue'] = default if source_field: index['IntArrayOptions']['SourceFields'] = \ ','.join(source_field) elif field_type == 'date': index['DateOptions'] = { 'FacetEnabled': facet, 'ReturnEnabled': returnable, 'SearchEnabled': searchable, 'SortEnabled': sortable } if default: index['DateOptions']['DefaultValue'] = default if source_field: index['DateOptions']['SourceField'] = source_field elif field_type == 'date-array': index['DateArrayOptions'] = { 'FacetEnabled': facet, 'ReturnEnabled': returnable, 'SearchEnabled': searchable } if default: index['DateArrayOptions']['DefaultValue'] = default if source_field: index['DateArrayOptions']['SourceFields'] = \ ','.join(source_field) elif field_type == 'double': index['DoubleOptions'] = { 'FacetEnabled': facet, 'ReturnEnabled': returnable, 'SearchEnabled': searchable, 'SortEnabled': sortable } if default: index['DoubleOptions']['DefaultValue'] = default if source_field: index['DoubleOptions']['SourceField'] = source_field elif field_type == 'double-array': index['DoubleArrayOptions'] = { 'FacetEnabled': facet, 'ReturnEnabled': returnable, 'SearchEnabled': searchable } if default: index['DoubleArrayOptions']['DefaultValue'] = default if source_field: index['DoubleArrayOptions']['SourceFields'] = \ ','.join(source_field) elif field_type == 'text': index['TextOptions'] = { 'ReturnEnabled': returnable, 'HighlightEnabled': highlight, 'SortEnabled': sortable } if default: index['TextOptions']['DefaultValue'] = default if source_field: index['TextOptions']['SourceField'] = source_field if analysis_scheme: index['TextOptions']['AnalysisScheme'] = analysis_scheme elif field_type == 'text-array': index['TextArrayOptions'] = { 'ReturnEnabled': returnable, 'HighlightEnabled': highlight } if default: index['TextArrayOptions']['DefaultValue'] = default if source_field: index['TextArrayOptions']['SourceFields'] = \ ','.join(source_field) if analysis_scheme: index['TextArrayOptions']['AnalysisScheme'] = analysis_scheme elif field_type == 'latlon': index['LatLonOptions'] = { 'FacetEnabled': facet, 'ReturnEnabled': returnable, 'SearchEnabled': searchable, 'SortEnabled': sortable } if default: index['LatLonOptions']['DefaultValue'] = default if source_field: index['LatLonOptions']['SourceField'] = source_field data = self.layer1.define_index_field(self.name, index) data = (data['DefineIndexFieldResponse'] ['DefineIndexFieldResult'] ['IndexField']) return IndexFieldStatus(self, data, self.layer1.describe_index_fields) def get_expressions(self, names=None): """ Return a list of rank expressions defined for this domain. :return: list of ExpressionStatus objects :rtype: list of :class:`boto.cloudsearch2.option.ExpressionStatus` object """ fn = self.layer1.describe_expressions data = fn(self.name, names) data = (data['DescribeExpressionsResponse'] ['DescribeExpressionsResult'] ['Expressions']) return [ExpressionStatus(self, d, fn) for d in data] def create_expression(self, name, value): """ Create a new expression. :type name: string :param name: The name of an expression for processing during a search request. :type value: string :param value: The expression to evaluate for ranking or thresholding while processing a search request. The Expression syntax is based on JavaScript expressions and supports: * Single value, sort enabled numeric fields (int, double, date) * Other expressions * The _score variable, which references a document's relevance score * The _time variable, which references the current epoch time * Integer, floating point, hex, and octal literals * Arithmetic operators: + - * / % * Bitwise operators: | & ^ ~ << >> >>> * Boolean operators (including the ternary operator): && || ! ?: * Comparison operators: < <= == >= > * Mathematical functions: abs ceil exp floor ln log2 log10 logn max min pow sqrt pow * Trigonometric functions: acos acosh asin asinh atan atan2 atanh cos cosh sin sinh tanh tan * The haversin distance function Expressions always return an integer value from 0 to the maximum 64-bit signed integer value (2^63 - 1). Intermediate results are calculated as double-precision floating point values and the return value is rounded to the nearest integer. If the expression is invalid or evaluates to a negative value, it returns 0. If the expression evaluates to a value greater than the maximum, it returns the maximum value. The source data for an Expression can be the name of an IndexField of type int or double, another Expression or the reserved name _score. The _score source is defined to return as a double from 0 to 10.0 (inclusive) to indicate how relevant a document is to the search request, taking into account repetition of search terms in the document and proximity of search terms to each other in each matching IndexField in the document. For more information about using rank expressions to customize ranking, see the Amazon CloudSearch Developer Guide. :return: ExpressionStatus object :rtype: :class:`boto.cloudsearch2.option.ExpressionStatus` object :raises: BaseException, InternalException, LimitExceededException, InvalidTypeException, ResourceNotFoundException """ data = self.layer1.define_expression(self.name, name, value) data = (data['DefineExpressionResponse'] ['DefineExpressionResult'] ['Expression']) return ExpressionStatus(self, data, self.layer1.describe_expressions) def get_document_service(self): return DocumentServiceConnection(domain=self) def get_search_service(self): return SearchConnection(domain=self) def __repr__(self): return '<Domain: %s>' % self.domain_name
gpl-3.0
yanweifu/chainer
cupy/math/floating.py
4
1285
from cupy import elementwise from cupy.math import ufunc signbit = elementwise.create_ufunc( 'cupy_signbit', ['e->?', 'f->?', 'd->?'], 'out0 = signbit(in0)', doc='''Tests elementwise if the sign bit is set (i.e. less than zero). .. seealso:: :data:`numpy.signbit` ''') copysign = ufunc.create_math_ufunc( 'copysign', 2, 'cupy_copysign', '''Returns the first arugment with the sign bit of the second elementwise. .. seealso:: :data:`numpy.copysign` ''') ldexp = elementwise.create_ufunc( 'cupy_ldexp', ['ei->e', 'fi->f', 'el->e', 'fl->f', 'di->d', 'dl->d'], 'out0 = ldexp(in0, in1)', doc='''Computes ``x1 * 2 ** x2`` elementwise. .. seealso:: :data:`numpy.ldexp` ''') frexp = elementwise.create_ufunc( 'cupy_frexp', ['e->ei', 'f->fi', 'd->di'], 'int nptr; out0 = frexp(in0, &nptr); out1 = nptr', doc='''Decomposes each element to mantissa and two's exponent. This ufunc outputs two arrays of the input dtype and the ``int`` dtype. .. seealso:: :data:`numpy.frexp` ''') nextafter = ufunc.create_math_ufunc( 'nextafter', 2, 'cupy_nextafter', '''Computes the nearest neighbor float values towards the second argument. .. seealso:: :data:`numpy.nextafter` ''')
mit
alsrgv/tensorflow
tensorflow/python/ops/distributions/laplace.py
15
8293
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """The Laplace distribution class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn from tensorflow.python.ops import random_ops from tensorflow.python.ops.distributions import distribution from tensorflow.python.ops.distributions import special_math from tensorflow.python.util import deprecation from tensorflow.python.util.tf_export import tf_export __all__ = [ "Laplace", "LaplaceWithSoftplusScale", ] @tf_export(v1=["distributions.Laplace"]) class Laplace(distribution.Distribution): """The Laplace distribution with location `loc` and `scale` parameters. #### Mathematical details The probability density function (pdf) of this distribution is, ```none pdf(x; mu, sigma) = exp(-|x - mu| / sigma) / Z Z = 2 sigma ``` where `loc = mu`, `scale = sigma`, and `Z` is the normalization constant. Note that the Laplace distribution can be thought of two exponential distributions spliced together "back-to-back." The Lpalce distribution is a member of the [location-scale family]( https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be constructed as, ```none X ~ Laplace(loc=0, scale=1) Y = loc + scale * X ``` """ @deprecation.deprecated( "2019-01-01", "The TensorFlow Distributions library has moved to " "TensorFlow Probability " "(https://github.com/tensorflow/probability). You " "should update all references to use `tfp.distributions` " "instead of `tf.distributions`.", warn_once=True) def __init__(self, loc, scale, validate_args=False, allow_nan_stats=True, name="Laplace"): """Construct Laplace distribution with parameters `loc` and `scale`. The parameters `loc` and `scale` must be shaped in a way that supports broadcasting (e.g., `loc / scale` is a valid operation). Args: loc: Floating point tensor which characterizes the location (center) of the distribution. scale: Positive floating point tensor which characterizes the spread of the distribution. validate_args: Python `bool`, default `False`. When `True` distribution parameters are checked for validity despite possibly degrading runtime performance. When `False` invalid inputs may silently render incorrect outputs. allow_nan_stats: Python `bool`, default `True`. When `True`, statistics (e.g., mean, mode, variance) use the value "`NaN`" to indicate the result is undefined. When `False`, an exception is raised if one or more of the statistic's batch members are undefined. name: Python `str` name prefixed to Ops created by this class. Raises: TypeError: if `loc` and `scale` are of different dtype. """ parameters = dict(locals()) with ops.name_scope(name, values=[loc, scale]) as name: with ops.control_dependencies([check_ops.assert_positive(scale)] if validate_args else []): self._loc = array_ops.identity(loc, name="loc") self._scale = array_ops.identity(scale, name="scale") check_ops.assert_same_float_dtype([self._loc, self._scale]) super(Laplace, self).__init__( dtype=self._loc.dtype, reparameterization_type=distribution.FULLY_REPARAMETERIZED, validate_args=validate_args, allow_nan_stats=allow_nan_stats, parameters=parameters, graph_parents=[self._loc, self._scale], name=name) @staticmethod def _param_shapes(sample_shape): return dict( zip(("loc", "scale"), ([ops.convert_to_tensor( sample_shape, dtype=dtypes.int32)] * 2))) @property def loc(self): """Distribution parameter for the location.""" return self._loc @property def scale(self): """Distribution parameter for scale.""" return self._scale def _batch_shape_tensor(self): return array_ops.broadcast_dynamic_shape( array_ops.shape(self.loc), array_ops.shape(self.scale)) def _batch_shape(self): return array_ops.broadcast_static_shape( self.loc.get_shape(), self.scale.get_shape()) def _event_shape_tensor(self): return constant_op.constant([], dtype=dtypes.int32) def _event_shape(self): return tensor_shape.scalar() def _sample_n(self, n, seed=None): shape = array_ops.concat([[n], self.batch_shape_tensor()], 0) # Uniform variates must be sampled from the open-interval `(-1, 1)` rather # than `[-1, 1)`. In the case of `(0, 1)` we'd use # `np.finfo(self.dtype.as_numpy_dtype).tiny` because it is the smallest, # positive, "normal" number. However, the concept of subnormality exists # only at zero; here we need the smallest usable number larger than -1, # i.e., `-1 + eps/2`. uniform_samples = random_ops.random_uniform( shape=shape, minval=np.nextafter(self.dtype.as_numpy_dtype(-1.), self.dtype.as_numpy_dtype(0.)), maxval=1., dtype=self.dtype, seed=seed) return (self.loc - self.scale * math_ops.sign(uniform_samples) * math_ops.log1p(-math_ops.abs(uniform_samples))) def _log_prob(self, x): return self._log_unnormalized_prob(x) - self._log_normalization() def _prob(self, x): return math_ops.exp(self._log_prob(x)) def _log_cdf(self, x): return special_math.log_cdf_laplace(self._z(x)) def _log_survival_function(self, x): return special_math.log_cdf_laplace(-self._z(x)) def _cdf(self, x): z = self._z(x) return (0.5 + 0.5 * math_ops.sign(z) * (1. - math_ops.exp(-math_ops.abs(z)))) def _log_unnormalized_prob(self, x): return -math_ops.abs(self._z(x)) def _log_normalization(self): return math.log(2.) + math_ops.log(self.scale) def _entropy(self): # Use broadcasting rules to calculate the full broadcast scale. scale = self.scale + array_ops.zeros_like(self.loc) return math.log(2.) + 1. + math_ops.log(scale) def _mean(self): return self.loc + array_ops.zeros_like(self.scale) def _stddev(self): return math.sqrt(2.) * self.scale + array_ops.zeros_like(self.loc) def _median(self): return self._mean() def _mode(self): return self._mean() def _z(self, x): return (x - self.loc) / self.scale class LaplaceWithSoftplusScale(Laplace): """Laplace with softplus applied to `scale`.""" @deprecation.deprecated( "2019-01-01", "Use `tfd.Laplace(loc, tf.nn.softplus(scale)) " "instead.", warn_once=True) def __init__(self, loc, scale, validate_args=False, allow_nan_stats=True, name="LaplaceWithSoftplusScale"): parameters = dict(locals()) with ops.name_scope(name, values=[loc, scale]) as name: super(LaplaceWithSoftplusScale, self).__init__( loc=loc, scale=nn.softplus(scale, name="softplus_scale"), validate_args=validate_args, allow_nan_stats=allow_nan_stats, name=name) self._parameters = parameters
apache-2.0
enriquesanchezb/practica_utad_2016
venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py
196
11401
from __future__ import absolute_import import errno import warnings import hmac from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning SSLContext = None HAS_SNI = False create_default_context = None # Maps the length of a digest to a possible hash function producing this digest HASHFUNC_MAP = { 32: md5, 40: sha1, 64: sha256, } def _const_compare_digest_backport(a, b): """ Compare two digests of equal length in constant time. The digests must be of type str/bytes. Returns True if the digests match, and False otherwise. """ result = abs(len(a) - len(b)) for l, r in zip(bytearray(a), bytearray(b)): result |= l ^ r return result == 0 _const_compare_digest = getattr(hmac, 'compare_digest', _const_compare_digest_backport) try: # Test for SSL features import ssl from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23 from ssl import HAS_SNI # Has SNI? except ImportError: pass try: from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION except ImportError: OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000 OP_NO_COMPRESSION = 0x20000 # A secure default. # Sources for more information on TLS ciphers: # # - https://wiki.mozilla.org/Security/Server_Side_TLS # - https://www.ssllabs.com/projects/best-practices/index.html # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/ # # The general intent is: # - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE), # - prefer ECDHE over DHE for better performance, # - prefer any AES-GCM over any AES-CBC for better performance and security, # - use 3DES as fallback which is secure but slow, # - disable NULL authentication, MD5 MACs and DSS for security reasons. DEFAULT_CIPHERS = ( 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:' '!eNULL:!MD5' ) try: from ssl import SSLContext # Modern SSL? except ImportError: import sys class SSLContext(object): # Platform-specific: Python 2 & 3.1 supports_set_ciphers = ((2, 7) <= sys.version_info < (3,) or (3, 2) <= sys.version_info) def __init__(self, protocol_version): self.protocol = protocol_version # Use default values from a real SSLContext self.check_hostname = False self.verify_mode = ssl.CERT_NONE self.ca_certs = None self.options = 0 self.certfile = None self.keyfile = None self.ciphers = None def load_cert_chain(self, certfile, keyfile): self.certfile = certfile self.keyfile = keyfile def load_verify_locations(self, cafile=None, capath=None): self.ca_certs = cafile if capath is not None: raise SSLError("CA directories not supported in older Pythons") def set_ciphers(self, cipher_suite): if not self.supports_set_ciphers: raise TypeError( 'Your version of Python does not support setting ' 'a custom cipher suite. Please upgrade to Python ' '2.7, 3.2, or later if you need this functionality.' ) self.ciphers = cipher_suite def wrap_socket(self, socket, server_hostname=None): warnings.warn( 'A true SSLContext object is not available. This prevents ' 'urllib3 from configuring SSL appropriately and may cause ' 'certain SSL connections to fail. For more information, see ' 'https://urllib3.readthedocs.org/en/latest/security.html' '#insecureplatformwarning.', InsecurePlatformWarning ) kwargs = { 'keyfile': self.keyfile, 'certfile': self.certfile, 'ca_certs': self.ca_certs, 'cert_reqs': self.verify_mode, 'ssl_version': self.protocol, } if self.supports_set_ciphers: # Platform-specific: Python 2.7+ return wrap_socket(socket, ciphers=self.ciphers, **kwargs) else: # Platform-specific: Python 2.6 return wrap_socket(socket, **kwargs) def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ fingerprint = fingerprint.replace(':', '').lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if not hashfunc: raise SSLError( 'Fingerprint of invalid length: {0}'.format(fingerprint)) # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if not _const_compare_digest(cert_digest, fingerprint_bytes): raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' .format(fingerprint, hexlify(cert_digest))) def resolve_cert_reqs(candidate): """ Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_NONE`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbrevation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket. """ if candidate is None: return CERT_NONE if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'CERT_' + candidate) return res return candidate def resolve_ssl_version(candidate): """ like resolve_cert_reqs """ if candidate is None: return PROTOCOL_SSLv23 if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'PROTOCOL_' + candidate) return res return candidate def create_urllib3_context(ssl_version=None, cert_reqs=None, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION context.options |= options if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6 context.set_ciphers(ciphers or DEFAULT_CIPHERS) context.verify_mode = cert_reqs if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False return context def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. This is not supported on Python 2.6 as the ssl module does not support it. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). """ context = ssl_context if context is None: context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir: try: context.load_verify_locations(ca_certs, ca_cert_dir) except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise if certfile: context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) warnings.warn( 'An HTTPS request has been made, but the SNI (Subject Name ' 'Indication) extension to TLS is not available on this platform. ' 'This may cause the server to present an incorrect TLS ' 'certificate, which can cause validation failures. For more ' 'information, see ' 'https://urllib3.readthedocs.org/en/latest/security.html' '#snimissingwarning.', SNIMissingWarning ) return context.wrap_socket(sock)
apache-2.0
redhataccess/rhi-pool
insights/ui/rules.py
1
2020
import logging import time from insights.ui.base import Base from insights.ui.locators import rules_locators from insights.ui.navigator import Navigator LOGGER = logging.getLogger('insights_portal') class Rules(Base): """ Identifies contents from Rules page of Insights """ def navigate_to_entity(self): Navigator(self.browser).go_to_rules() def go_to_filter(self, name=None): """ This will select rules filter """ time.sleep(5) #Added explicit wait as rules cards takes time to load if name is not None: LOGGER.info("Checking filter: " + name) if name is 'Availability': self.click(rules_locators['rules.filter.availability']) elif name is 'Performance': self.click(rules_locators['rules.filter.performance']) elif name is 'Stability': self.click(rules_locators['rules.filter.stability']) elif name is 'Security': self.click(rules_locators['rules.filter.security']) elif name is 'All': self.click(rules_locators['rules.filter.all']) def get_active_filter_text(self): return self.find_element(rules_locators['rules.active.filter']).text def get_rule_card_title(self): time.sleep(5) #Added explicit wait as rule cards takes time to load rules_title = self.find_elements(rules_locators['rules.cards']) title = [] for rule_title in rules_title: title.append(rule_title.text) LOGGER.info(title) return title def search_rule(self, search_text='HTTPoxy'): self.click(rules_locators['rules.search.box']) self.field_update("rules.search.box", search_text) self.click(rules_locators['rules.search.icon']) time.sleep(5) #Wait for search rules def get_rules_count(self): rule_blocks = self.find_elements(rules_locators['rules.content.blocks']) return len(rule_blocks)
gpl-3.0
liangazhou/django-rdp
packages/PyDev/plugins/org.python.pydev_4.4.0.201510052309/pysrc/third_party/wrapped_for_pydev/ctypes/wintypes.py
106
2387
#@PydevCodeAnalysisIgnore # XXX This module needs cleanup. from ctypes import * DWORD = c_ulong WORD = c_ushort BYTE = c_byte ULONG = c_ulong LONG = c_long LARGE_INTEGER = c_longlong ULARGE_INTEGER = c_ulonglong HANDLE = c_ulong # in the header files: void * HWND = HANDLE HDC = HANDLE HMODULE = HANDLE HINSTANCE = HANDLE HRGN = HANDLE HTASK = HANDLE HKEY = HANDLE HPEN = HANDLE HGDIOBJ = HANDLE HMENU = HANDLE LCID = DWORD WPARAM = c_uint LPARAM = c_long BOOL = c_long VARIANT_BOOL = c_short LPCOLESTR = LPOLESTR = OLESTR = c_wchar_p LPCWSTR = LPWSTR = c_wchar_p LPCSTR = LPSTR = c_char_p class RECT(Structure): _fields_ = [("left", c_long), ("top", c_long), ("right", c_long), ("bottom", c_long)] RECTL = RECT class POINT(Structure): _fields_ = [("x", c_long), ("y", c_long)] POINTL = POINT class SIZE(Structure): _fields_ = [("cx", c_long), ("cy", c_long)] SIZEL = SIZE def RGB(red, green, blue): return red + (green << 8) + (blue << 16) class FILETIME(Structure): _fields_ = [("dwLowDateTime", DWORD), ("dwHighDateTime", DWORD)] class MSG(Structure): _fields_ = [("hWnd", HWND), ("message", c_uint), ("wParam", WPARAM), ("lParam", LPARAM), ("time", DWORD), ("pt", POINT)] MAX_PATH = 260 class WIN32_FIND_DATAA(Structure): _fields_ = [("dwFileAttributes", DWORD), ("ftCreationTime", FILETIME), ("ftLastAccessTime", FILETIME), ("ftLastWriteTime", FILETIME), ("nFileSizeHigh", DWORD), ("nFileSizeLow", DWORD), ("dwReserved0", DWORD), ("dwReserved1", DWORD), ("cFileName", c_char * MAX_PATH), ("cAlternameFileName", c_char * 14)] class WIN32_FIND_DATAW(Structure): _fields_ = [("dwFileAttributes", DWORD), ("ftCreationTime", FILETIME), ("ftLastAccessTime", FILETIME), ("ftLastWriteTime", FILETIME), ("nFileSizeHigh", DWORD), ("nFileSizeLow", DWORD), ("dwReserved0", DWORD), ("dwReserved1", DWORD), ("cFileName", c_wchar * MAX_PATH), ("cAlternameFileName", c_wchar * 14)]
apache-2.0
BrianPainter/video_village
videos/migrations/0001_initial.py
2
1467
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-07-08 00:49 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Video', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('uploader_name', models.CharField(blank=True, max_length=255)), ('file', models.FileField(upload_to='')), ('title', models.CharField(blank=True, max_length=255)), ('description', models.TextField(blank=True)), ('email', models.EmailField(max_length=254)), ('approved', models.BooleanField(default=False)), ('status', models.CharField(choices=[('a', 'Approved'), ('r', 'Rejected'), ('s', 'Submitted')], default='s', max_length=1)), ('moderation_notes', models.TextField(blank=True, null=True)), ('length', models.IntegerField(blank=True, null=True)), ('moderated_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
mit
DaanHoogland/cloudstack
test/integration/component/test_escalations_templates.py
3
33155
# 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. # Import Local Modules from marvin.cloudstackTestCase import cloudstackTestCase, unittest from marvin.lib.utils import (cleanup_resources, validateList) from marvin.lib.base import (Account, Zone, Template, Hypervisor, ServiceOffering) from marvin.lib.common import (get_domain, get_zone, get_template, list_os_types, get_builtin_template_info) from marvin.codes import PASS from nose.plugins.attrib import attr import time class TestTemplates(cloudstackTestCase): @classmethod def setUpClass(cls): try: cls._cleanup = [] cls.testClient = super(TestTemplates, cls).getClsTestClient() cls.api_client = cls.testClient.getApiClient() cls.services = cls.testClient.getParsedTestDataConfig() # Get Domain, Zone, Template cls.domain = get_domain(cls.api_client) cls.zone = get_zone( cls.api_client, cls.testClient.getZoneForTests()) cls.template = get_template( cls.api_client, cls.zone.id, cls.services["ostype"] ) cls.hypervisor = cls.testClient.getHypervisorInfo() cls.services['mode'] = cls.zone.networktype cls.mgtSvrDetails = cls.config.__dict__["mgtSvr"][0].__dict__ builtin_info = get_builtin_template_info(cls.api_client, cls.zone.id) cls.services["privatetemplate"]["url"] = builtin_info[0] cls.services["privatetemplate"]["hypervisor"] = builtin_info[1] cls.services["privatetemplate"]["format"] = builtin_info[2] cls.services["templates"]["url"] = builtin_info[0] cls.services["templates"]["hypervisor"] = builtin_info[1] cls.services["templates"]["format"] = builtin_info[2] except Exception as e: cls.tearDownClass() raise Exception("Warning: Exception in setup : %s" % e) return def setUp(self): self.apiClient = self.testClient.getApiClient() self.cleanup = [] self.account = Account.create( self.apiClient, self.services["account"], domainid=self.domain.id ) # Getting authentication for user in newly created Account self.user = self.account.user[0] self.userapiclient = self.testClient.getUserApiClient( self.user.username, self.domain.name) self.cleanup.append(self.account) def tearDown(self): # Clean up, terminate the created resources cleanup_resources(self.apiClient, self.cleanup) return @classmethod def tearDownClass(cls): try: cleanup_resources(cls.api_client, cls._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def __verify_values(self, expected_vals, actual_vals): """ @Desc: Function to verify expected and actual values @Steps: Step1: Initializing return flag to True Step1: Verifying length of expected and actual dictionaries is matching. If not matching returning false Step2: Listing all the keys from expected dictionary Step3: Looping through each key from step2 and verifying expected and actual dictionaries have same value If not making return flag to False Step4: returning the return flag after all the values are verified """ return_flag = True if len(expected_vals) != len(actual_vals): return False keys = expected_vals.keys() for i in range(0, len(expected_vals)): exp_val = expected_vals[keys[i]] act_val = actual_vals[keys[i]] if exp_val == act_val: return_flag = return_flag and True else: return_flag = return_flag and False self.debug( "expected Value: %s, is not matching with actual value: %s" % (exp_val, act_val)) return return_flag def download(self, apiclient, template_id, retries=72, interval=5): """Check if template download will finish in 6 minutes""" while retries > -1: time.sleep(interval) template_response = Template.list( apiclient, id=template_id, zoneid=self.zone.id, templatefilter='self' ) if isinstance(template_response, list): template = template_response[0] if not hasattr(template, 'status') or not template or not template.status: retries = retries - 1 continue # If template is ready, # template.status = Download Complete # Downloading - x% Downloaded # if Failed # Error - Any other string if 'Failed' in template.status: raise Exception( "Failed to download template: status - %s" % template.status) elif template.status == 'Download Complete' and template.isready: return elif 'Downloaded' in template.status: retries = retries - 1 continue elif 'Installing' not in template.status: if retries >= 0: retries = retries - 1 continue raise Exception( "Error in downloading template: status - %s" % template.status) else: retries = retries - 1 raise Exception("Template download failed exception.") @attr(tags=["advanced", "basic"], required_hardware="true") def test_01_list_templates_pagination(self): """ @Desc: Test to List Templates pagination @steps: Step1: Listing all the Templates for a user Step2: Verifying that no Templates are listed Step3: Creating (page size + 1) number of Templates Step4: Listing all the Templates again for a user Step5: Verifying that list size is (page size + 1) Step6: Listing all the Templates in page1 Step7: Verifying that list size is (page size) Step8: Listing all the Templates in page2 Step9: Verifying that list size is 1 Step10: Listing the template by Id Step11: Verifying if the template is downloaded and ready. If yes the continuing If not waiting and checking for template to be ready till timeout Step12: Deleting the Template present in page 2 Step13: Listing all the Templates in page2 Step14: Verifying that no Templates are listed """ # Listing all the Templates for a User list_templates_before = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"] ) # Verifying that no Templates are listed self.assertIsNone( list_templates_before, "Templates listed for newly created User" ) self.services["privatetemplate"]["ostype"] = self.services["ostype"] # Creating pagesize + 1 number of Templates for i in range(0, (self.services["pagesize"] + 1)): template_created = Template.register( self.userapiclient, self.services["privatetemplate"], self.zone.id, hypervisor=self.hypervisor ) self.assertIsNotNone( template_created, "Template creation failed" ) # Listing all the Templates for a User list_templates_after = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"] ) status = validateList(list_templates_after) self.assertEquals( PASS, status[0], "Templates creation failed" ) # Verifying that list size is pagesize + 1 self.assertEquals( self.services["pagesize"] + 1, len(list_templates_after), "Failed to create pagesize + 1 number of Templates" ) # Listing all the Templates in page 1 list_templates_page1 = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"], page=1, pagesize=self.services["pagesize"] ) status = validateList(list_templates_page1) self.assertEquals( PASS, status[0], "Failed to list Templates in page 1" ) # Verifying the list size to be equal to pagesize self.assertEquals( self.services["pagesize"], len(list_templates_page1), "Size of Templates in page 1 is not matching" ) # Listing all the Templates in page 2 list_templates_page2 = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"], page=2, pagesize=self.services["pagesize"] ) status = validateList(list_templates_page2) self.assertEquals( PASS, status[0], "Failed to list Templates in page 2" ) # Verifying the list size to be equal to 1 self.assertEquals( 1, len(list_templates_page2), "Size of Templates in page 2 is not matching" ) # Verifying the state of the template to be ready. If not waiting for # state to become ready self.download(self.apiClient, template_created.id) # Deleting the Template present in page 2 Template.delete( template_created, self.userapiclient ) # Listing all the Templates in page 2 again list_templates_page2 = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"], page=2, pagesize=self.services["pagesize"] ) # Verifying that there are no Templates listed self.assertIsNone( list_templates_page2, "Templates not deleted from page 2" ) del self.services["privatetemplate"]["ostype"] return @attr(tags=["advanced", "basic"], required_hardware="true") def test_02_download_template(self): """ @Desc: Test to Download Template @steps: Step1: Listing all the Templates for a user Step2: Verifying that no Templates are listed Step3: Creating a Templates Step4: Listing all the Templates again for a user Step5: Verifying that list size is 1 Step6: Verifying if the template is in ready state. If yes the continuing If not waiting and checking for template to be ready till timeout Step7: Downloading the template (Extract) Step8: Verifying that Template is downloaded """ # Listing all the Templates for a User list_templates_before = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"] ) # Verifying that no Templates are listed self.assertIsNone( list_templates_before, "Templates listed for newly created User" ) self.services["privatetemplate"]["ostype"] = self.services["ostype"] self.services["privatetemplate"]["isextractable"] = True # Creating aTemplate template_created = Template.register( self.userapiclient, self.services["privatetemplate"], self.zone.id, hypervisor=self.hypervisor ) self.assertIsNotNone( template_created, "Template creation failed" ) # Listing all the Templates for a User list_templates_after = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"] ) status = validateList(list_templates_after) self.assertEquals( PASS, status[0], "Templates creation failed" ) # Verifying that list size is 1 self.assertEquals( 1, len(list_templates_after), "Failed to create a Template" ) # Verifying the state of the template to be ready. If not waiting for # state to become ready till time out self.download(self.apiClient, template_created.id) # Downloading the Template name download_template = Template.extract( self.userapiclient, template_created.id, mode="HTTP_DOWNLOAD", zoneid=self.zone.id ) self.assertIsNotNone( download_template, "Download Template failed" ) # Verifying the details of downloaded template self.assertEquals( "DOWNLOAD_URL_CREATED", download_template.state, "Download URL not created for Template" ) self.assertIsNotNone( download_template.url, "Download URL not created for Template" ) self.assertEquals( template_created.id, download_template.id, "Download Template details are not same as Template created" ) del self.services["privatetemplate"]["ostype"] del self.services["privatetemplate"]["isextractable"] return @attr(tags=["advanced", "basic"], required_hardware="true") def test_03_edit_template_details(self): """ @Desc: Test to Edit Template name, displaytext, OSType @steps: Step1: Listing all the Templates for a user Step2: Verifying that no Templates are listed Step3: Creating a Templates Step4: Listing all the Templates again for a user Step5: Verifying that list size is 1 Step6: Verifying if the template is in ready state. If yes the continuing If not waiting and checking for template to be ready till timeout Step7: Editing the template name Step8: Verifying that Template name is edited Step9: Editing the template displaytext Step10: Verifying that Template displaytext is edited Step11: Editing the template ostypeid Step12: Verifying that Template ostypeid is edited Step13: Editing the template name, displaytext Step14: Verifying that Template name, displaytext are edited Step15: Editing the template name, displaytext, ostypeid Step16: Verifying that Template name, displaytext and ostypeid are edited """ # Listing all the Templates for a User list_templates_before = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"] ) # Verifying that no Templates are listed self.assertIsNone( list_templates_before, "Templates listed for newly created User" ) self.services["privatetemplate"]["ostype"] = self.services["ostype"] # Creating aTemplate template_created = Template.register( self.userapiclient, self.services["privatetemplate"], self.zone.id, hypervisor=self.hypervisor ) self.assertIsNotNone( template_created, "Template creation failed" ) # Listing all the Templates for a User list_templates_after = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"] ) status = validateList(list_templates_after) self.assertEquals( PASS, status[0], "Templates creation failed" ) # Verifying that list size is 1 self.assertEquals( 1, len(list_templates_after), "Failed to create a Template" ) # Verifying the state of the template to be ready. If not waiting for # state to become ready till time out self.download(self.apiClient, template_created.id) # Editing the Template name edited_template = Template.update( template_created, self.userapiclient, name="NewTemplateName" ) self.assertIsNotNone( edited_template, "Editing Template failed" ) # Verifying the details of edited template expected_dict = { "id": template_created.id, "name": "NewTemplateName", "displaytest": template_created.displaytext, "account": template_created.account, "domainid": template_created.domainid, "format": template_created.format, "ostypeid": template_created.ostypeid, "templatetype": template_created.templatetype, } actual_dict = { "id": edited_template.id, "name": edited_template.name, "displaytest": edited_template.displaytext, "account": edited_template.account, "domainid": edited_template.domainid, "format": edited_template.format, "ostypeid": edited_template.ostypeid, "templatetype": edited_template.templatetype, } edit_template_status = self.__verify_values( expected_dict, actual_dict ) self.assertEqual( True, edit_template_status, "Edited Template details are not as expected" ) # Editing the Template displaytext edited_template = Template.update( template_created, self.userapiclient, displaytext="TemplateDisplaytext" ) self.assertIsNotNone( edited_template, "Editing Template failed" ) # Verifying the details of edited template expected_dict = { "id": template_created.id, "name": "NewTemplateName", "displaytest": "TemplateDisplaytext", "account": template_created.account, "domainid": template_created.domainid, "format": template_created.format, "ostypeid": template_created.ostypeid, "templatetype": template_created.templatetype, } actual_dict = { "id": edited_template.id, "name": edited_template.name, "displaytest": edited_template.displaytext, "account": edited_template.account, "domainid": edited_template.domainid, "format": edited_template.format, "ostypeid": edited_template.ostypeid, "templatetype": edited_template.templatetype, } edit_template_status = self.__verify_values( expected_dict, actual_dict ) self.assertEqual( True, edit_template_status, "Edited Template details are not as expected" ) # Editing the Template ostypeid ostype_list = list_os_types(self.userapiclient) status = validateList(ostype_list) self.assertEquals( PASS, status[0], "Failed to list OS Types" ) for i in range(0, len(ostype_list)): if ostype_list[i].id != template_created.ostypeid: newostypeid = ostype_list[i].id break edited_template = Template.update( template_created, self.userapiclient, ostypeid=newostypeid ) self.assertIsNotNone( edited_template, "Editing Template failed" ) # Verifying the details of edited template expected_dict = { "id": template_created.id, "name": "NewTemplateName", "displaytest": "TemplateDisplaytext", "account": template_created.account, "domainid": template_created.domainid, "format": template_created.format, "ostypeid": newostypeid, "templatetype": template_created.templatetype, } actual_dict = { "id": edited_template.id, "name": edited_template.name, "displaytest": edited_template.displaytext, "account": edited_template.account, "domainid": edited_template.domainid, "format": edited_template.format, "ostypeid": edited_template.ostypeid, "templatetype": edited_template.templatetype, } edit_template_status = self.__verify_values( expected_dict, actual_dict ) self.assertEqual( True, edit_template_status, "Edited Template details are not as expected" ) # Editing the Template name, displaytext edited_template = Template.update( template_created, self.userapiclient, name=template_created.name, displaytext=template_created.displaytext ) self.assertIsNotNone( edited_template, "Editing Template failed" ) # Verifying the details of edited template expected_dict = { "id": template_created.id, "name": template_created.name, "displaytest": template_created.displaytext, "account": template_created.account, "domainid": template_created.domainid, "format": template_created.format, "ostypeid": newostypeid, "templatetype": template_created.templatetype, } actual_dict = { "id": edited_template.id, "name": edited_template.name, "displaytest": edited_template.displaytext, "account": edited_template.account, "domainid": edited_template.domainid, "format": edited_template.format, "ostypeid": edited_template.ostypeid, "templatetype": edited_template.templatetype, } edit_template_status = self.__verify_values( expected_dict, actual_dict ) self.assertEqual( True, edit_template_status, "Edited Template details are not as expected" ) # Editing the Template name, displaytext, ostypeid edited_template = Template.update( template_created, self.userapiclient, name="NewTemplateName", displaytext="TemplateDisplaytext", ostypeid=template_created.ostypeid ) self.assertIsNotNone( edited_template, "Editing Template failed" ) # Verifying the details of edited template expected_dict = { "id": template_created.id, "name": "NewTemplateName", "displaytest": "TemplateDisplaytext", "account": template_created.account, "domainid": template_created.domainid, "format": template_created.format, "ostypeid": template_created.ostypeid, "templatetype": template_created.templatetype, } actual_dict = { "id": edited_template.id, "name": edited_template.name, "displaytest": edited_template.displaytext, "account": edited_template.account, "domainid": edited_template.domainid, "format": edited_template.format, "ostypeid": edited_template.ostypeid, "templatetype": edited_template.templatetype, } edit_template_status = self.__verify_values( expected_dict, actual_dict ) self.assertEqual( True, edit_template_status, "Edited Template details are not as expected" ) del self.services["privatetemplate"]["ostype"] return @attr(tags=["advanced", "basic"], required_hardware="true") def test_04_copy_template(self): """ @Desc: Test to copy Template from one zone to another @steps: Step1: Listing Zones available for a user Step2: Verifying if the zones listed are greater than 1. If Yes continuing. If not halting the test. Step3: Listing all the templates for a user in zone1 Step4: Verifying that no templates are listed Step5: Listing all the templates for a user in zone2 Step6: Verifying that no templates are listed Step7: Creating a Template in zone 1 Step8: Listing all the Templates again for a user in zone1 Step9: Verifying that list size is 1 Step10: Listing all the templates for a user in zone2 Step11: Verifying that no templates are listed Step12: Copying the template created in step7 from zone1 to zone2 Step13: Listing all the templates for a user in zone2 Step14: Verifying that list size is 1 Step15: Listing all the Templates for a user in zone1 Step16: Verifying that list size is 1 """ # Listing Zones available for a user zones_list = Zone.list( self.userapiclient, available=True ) status = validateList(zones_list) self.assertEquals( PASS, status[0], "Failed to list Zones" ) if not len(zones_list) > 1: raise unittest.SkipTest("Not enough zones exist to copy template") else: # Listing all the Templates for a User in Zone 1 list_templates_zone1 = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"], zoneid=zones_list[0].id ) # Verifying that no Templates are listed self.assertIsNone( list_templates_zone1, "Templates listed for newly created User in Zone1" ) # Listing all the Templates for a User in Zone 2 list_templates_zone2 = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"], zoneid=zones_list[1].id ) # Verifying that no Templates are listed self.assertIsNone( list_templates_zone2, "Templates listed for newly created User in Zone2" ) self.services["privatetemplate"][ "ostype"] = self.services["ostype"] # Listing Hypervisors in Zone 1 hypervisor_list = Hypervisor.list( self.apiClient, zoneid=zones_list[0].id ) status = validateList(zones_list) self.assertEquals( PASS, status[0], "Failed to list Hypervisors in Zone 1" ) # Creating aTemplate in Zone 1 template_created = Template.register( self.userapiclient, self.services["privatetemplate"], zones_list[0].id, hypervisor=hypervisor_list[0].name ) self.assertIsNotNone( template_created, "Template creation failed" ) # Listing all the Templates for a User in Zone 1 list_templates_zone1 = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"], zoneid=zones_list[0].id ) status = validateList(list_templates_zone1) self.assertEquals( PASS, status[0], "Templates creation failed in Zone1" ) # Verifying that list size is 1 self.assertEquals( 1, len(list_templates_zone1), "Failed to create a Template" ) # Listing all the Templates for a User in Zone 2 list_templates_zone2 = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"], zoneid=zones_list[1].id ) # Verifying that no Templates are listed self.assertIsNone( list_templates_zone2, "Templates listed for newly created User in Zone2" ) # Verifying the state of the template to be ready. If not waiting # for state to become ready till time out self.download(self.apiClient, template_created.id) # Copying the Template from Zone1 to Zone2 copied_template = template_created.copy( self.userapiclient, sourcezoneid=template_created.zoneid, destzoneid=zones_list[1].id ) self.assertIsNotNone( copied_template, "Copying Template from Zone1 to Zone2 failed" ) # Listing all the Templates for a User in Zone 1 list_templates_zone1 = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"], zoneid=zones_list[0].id ) status = validateList(list_templates_zone1) self.assertEquals( PASS, status[0], "Templates creation failed in Zone1" ) # Verifying that list size is 1 self.assertEquals( 1, len(list_templates_zone1), "Failed to create a Template" ) # Listing all the Templates for a User in Zone 2 list_templates_zone2 = Template.list( self.userapiclient, listall=self.services["listall"], templatefilter=self.services["templatefilter"], zoneid=zones_list[1].id ) status = validateList(list_templates_zone2) self.assertEquals( PASS, status[0], "Template failed to copy into Zone2" ) # Verifying that list size is 1 self.assertEquals( 1, len(list_templates_zone2), "Template failed to copy into Zone2" ) self.assertNotEquals( "Connection refused", list_templates_zone2[0].status, "Failed to copy Template" ) self.assertEquals( True, list_templates_zone2[0].isready, "Failed to copy Template" ) del self.services["privatetemplate"]["ostype"] return
apache-2.0
KhalidGit/flask
Work/TriviaMVA/TriviaMVA/env/Lib/site-packages/pip/_vendor/requests/cookies.py
821
16686
# -*- coding: utf-8 -*- """ Compatibility code to be able to use `cookielib.CookieJar` with requests. requests.utils imports from here, so be careful with imports. """ import time import collections from .compat import cookielib, urlparse, urlunparse, Morsel try: import threading # grr, pyflakes: this fixes "redefinition of unused 'threading'" threading except ImportError: import dummy_threading as threading class MockRequest(object): """Wraps a `requests.Request` to mimic a `urllib2.Request`. The code in `cookielib.CookieJar` expects this interface in order to correctly manage cookie policies, i.e., determine whether a cookie can be set, given the domains of the request and the cookie. The original request object is read-only. The client is responsible for collecting the new headers via `get_new_headers()` and interpreting them appropriately. You probably want `get_cookie_header`, defined below. """ def __init__(self, request): self._r = request self._new_headers = {} self.type = urlparse(self._r.url).scheme def get_type(self): return self.type def get_host(self): return urlparse(self._r.url).netloc def get_origin_req_host(self): return self.get_host() def get_full_url(self): # Only return the response's URL if the user hadn't set the Host # header if not self._r.headers.get('Host'): return self._r.url # If they did set it, retrieve it and reconstruct the expected domain host = self._r.headers['Host'] parsed = urlparse(self._r.url) # Reconstruct the URL as we expect it return urlunparse([ parsed.scheme, host, parsed.path, parsed.params, parsed.query, parsed.fragment ]) def is_unverifiable(self): return True def has_header(self, name): return name in self._r.headers or name in self._new_headers def get_header(self, name, default=None): return self._r.headers.get(name, self._new_headers.get(name, default)) def add_header(self, key, val): """cookielib has no legitimate use for this method; add it back if you find one.""" raise NotImplementedError("Cookie headers should be added with add_unredirected_header()") def add_unredirected_header(self, name, value): self._new_headers[name] = value def get_new_headers(self): return self._new_headers @property def unverifiable(self): return self.is_unverifiable() @property def origin_req_host(self): return self.get_origin_req_host() @property def host(self): return self.get_host() class MockResponse(object): """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`. ...what? Basically, expose the parsed HTTP headers from the server response the way `cookielib` expects to see them. """ def __init__(self, headers): """Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers """ self._headers = headers def info(self): return self._headers def getheaders(self, name): self._headers.getheaders(name) def extract_cookies_to_jar(jar, request, response): """Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object """ if not (hasattr(response, '_original_response') and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req) def get_cookie_header(jar, request): """Produce an appropriate Cookie header string to be sent with `request`, or None.""" r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie') def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for cookie in cookiejar: if cookie.name == name: if domain is None or domain == cookie.domain: if path is None or path == cookie.path: clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name) class CookieConflictError(RuntimeError): """There are two cookies that meet the criteria specified in the cookie jar. Use .get and .set and include domain and path args in order to be more specific.""" class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping): """Compatibility class; is a cookielib.CookieJar, but exposes a dict interface. This is the CookieJar we create by default for requests and sessions that don't specify one, since some clients may expect response.cookies and session.cookies to support dict operations. Don't use the dict interface internally; it's just for compatibility with with external client code. All `requests` code should work out of the box with externally provided instances of CookieJar, e.g., LWPCookieJar and FileCookieJar. Caution: dictionary operations that are normally O(1) may be O(n). Unlike a regular CookieJar, this class is pickleable. """ def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. Caution: operation is O(n), not O(1).""" try: return self._find_no_duplicates(name, domain, path) except KeyError: return default def set(self, name, value, **kwargs): """Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains.""" # support client code that unsets cookies by assignment of a None value: if value is None: remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path')) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c def iterkeys(self): """Dict-like iterkeys() that returns an iterator of names of cookies from the jar. See itervalues() and iteritems().""" for cookie in iter(self): yield cookie.name def keys(self): """Dict-like keys() that returns a list of names of cookies from the jar. See values() and items().""" return list(self.iterkeys()) def itervalues(self): """Dict-like itervalues() that returns an iterator of values of cookies from the jar. See iterkeys() and iteritems().""" for cookie in iter(self): yield cookie.value def values(self): """Dict-like values() that returns a list of values of cookies from the jar. See keys() and items().""" return list(self.itervalues()) def iteritems(self): """Dict-like iteritems() that returns an iterator of name-value tuples from the jar. See iterkeys() and itervalues().""" for cookie in iter(self): yield cookie.name, cookie.value def items(self): """Dict-like items() that returns a list of name-value tuples from the jar. See keys() and values(). Allows client-code to call "dict(RequestsCookieJar) and get a vanilla python dict of key value pairs.""" return list(self.iteritems()) def list_domains(self): """Utility method to list all the domains in the jar.""" domains = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains def list_paths(self): """Utility method to list all the paths in the jar.""" paths = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths def multiple_domains(self): """Returns True if there are multiple domains in the jar. Returns False otherwise.""" domains = [] for cookie in iter(self): if cookie.domain is not None and cookie.domain in domains: return True domains.append(cookie.domain) return False # there is only one domain in jar def get_dict(self, domain=None, path=None): """Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements.""" dictionary = {} for cookie in iter(self): if (domain is None or cookie.domain == domain) and (path is None or cookie.path == path): dictionary[cookie.name] = cookie.value return dictionary def __getitem__(self, name): """Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. Caution: operation is O(n), not O(1).""" return self._find_no_duplicates(name) def __setitem__(self, name, value): """Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead.""" self.set(name, value) def __delitem__(self, name): """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name().""" remove_cookie_by_name(self, name) def set_cookie(self, cookie, *args, **kwargs): if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'): cookie.value = cookie.value.replace('\\"', '') return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs) def update(self, other): """Updates this jar with cookies from another CookieJar or dict-like""" if isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(cookie) else: super(RequestsCookieJar, self).update(other) def _find(self, name, domain=None, path=None): """Requests uses this method internally to get cookie values. Takes as args name and optional domain and path. Returns a cookie.value. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies.""" for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) def _find_no_duplicates(self, name, domain=None, path=None): """__get_item__ and get call _find_no_duplicates -- never used in Requests internally. Takes as args name and optional domain and path. Returns a cookie.value. Throws KeyError if cookie is not found and CookieConflictError if there are multiple cookies that match name and optionally domain and path.""" toReturn = None for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: if toReturn is not None: # if there are multiple cookies that meet passed in criteria raise CookieConflictError('There are multiple cookies with name, %r' % (name)) toReturn = cookie.value # we will eventually return this as long as no cookie conflict if toReturn: return toReturn raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path)) def __getstate__(self): """Unlike a normal CookieJar, this class is pickleable.""" state = self.__dict__.copy() # remove the unpickleable RLock object state.pop('_cookies_lock') return state def __setstate__(self, state): """Unlike a normal CookieJar, this class is pickleable.""" self.__dict__.update(state) if '_cookies_lock' not in self.__dict__: self._cookies_lock = threading.RLock() def copy(self): """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.update(self) return new_cj def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = dict( version=0, name=name, value=value, port=None, domain='', path='/', secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False,) badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return cookielib.Cookie(**result) def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: expires = time.time() + morsel['max-age'] elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = time.mktime( time.strptime(morsel['expires'], time_template)) - time.timezone return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, ) def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones. """ if cookiejar is None: cookiejar = RequestsCookieJar() if cookie_dict is not None: names_from_jar = [cookie.name for cookie in cookiejar] for name in cookie_dict: if overwrite or (name not in names_from_jar): cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) return cookiejar def merge_cookies(cookiejar, cookies): """Add cookies to cookiejar and returns a merged CookieJar. :param cookiejar: CookieJar object to add the cookies to. :param cookies: Dictionary or CookieJar object to be added. """ if not isinstance(cookiejar, cookielib.CookieJar): raise ValueError('You can only merge into CookieJar') if isinstance(cookies, dict): cookiejar = cookiejar_from_dict( cookies, cookiejar=cookiejar, overwrite=False) elif isinstance(cookies, cookielib.CookieJar): try: cookiejar.update(cookies) except AttributeError: for cookie_in_jar in cookies: cookiejar.set_cookie(cookie_in_jar) return cookiejar
apache-2.0
g-k/servo
tests/wpt/harness/wptrunner/vcs.py
40
1379
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import subprocess from functools import partial from mozlog.structured import get_default_logger logger = None def vcs(bin_name): def inner(command, *args, **kwargs): global logger if logger is None: logger = get_default_logger("vcs") repo = kwargs.pop("repo", None) log_error = kwargs.pop("log_error", True) if kwargs: raise TypeError, kwargs args = list(args) proc_kwargs = {} if repo is not None: proc_kwargs["cwd"] = repo command_line = [bin_name, command] + args logger.debug(" ".join(command_line)) try: return subprocess.check_output(command_line, stderr=subprocess.STDOUT, **proc_kwargs) except subprocess.CalledProcessError as e: if log_error: logger.error(e.output) raise return inner git = vcs("git") hg = vcs("hg") def bind_to_repo(vcs_func, repo): return partial(vcs_func, repo=repo) def is_git_root(path): try: rv = git("rev-parse", "--show-cdup", repo=path) except subprocess.CalledProcessError: return False return rv == "\n"
mpl-2.0
kobotoolbox/kobo_selenium_tests
kobo_selenium_tests/selenium_ide_exported/create_form_test_template.py
1
7253
# -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException import unittest, time, re class CreateFormTestTemplate(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "http://kf.kbtdev.org/" self.verificationErrors = [] self.accept_next_alert = True def test_create_form_test_template(self): driver = self.driver driver.get(self.base_url + "") for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".forms-header__title"): break except: pass time.sleep(1) else: self.fail("time out") self.assertFalse(self.is_element_present(By.CSS_SELECTOR, ".forms__card")) self.assertTrue(self.is_element_present(By.CSS_SELECTOR, ".forms-empty__button")) driver.find_element_by_css_selector(".forms-empty__button").click() for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".forms__addform__start"): break except: pass time.sleep(1) else: self.fail("time out") # Click the form creation button using JavaScript to avoid element not visible errors. # WARNING: The 'runScript' command doesn't export to python, so a manual edit is necessary. # ERROR: Caught exception [ERROR: Unsupported command [runScript | $(".forms__addform__start").click(); | ]] for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".form-title"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_css_selector(".form-title").click() for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".survey-header__title input"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_css_selector(".survey-header__title input").send_keys(Keys.SHIFT, Keys.END, Keys.SHIFT, Keys.DELETE) driver.find_element_by_css_selector(".survey-header__title input").send_keys("Selenium test form title.", Keys.ENTER) self.assertEqual("Selenium test form title.", driver.find_element_by_css_selector(".form-title").text) self.assertTrue(self.is_element_present(By.CSS_SELECTOR, ".survey-editor .fa-plus")) driver.find_element_by_css_selector(".survey-editor .fa-plus").click() for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".row__questiontypes__form > input"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_css_selector(".row__questiontypes__form > input").send_keys("Selenium test question label.", Keys.TAB) self.assertTrue(self.is_element_present(By.CSS_SELECTOR, ".row__questiontypes__form > button")) driver.find_element_by_css_selector(".row__questiontypes__form > button").click() for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".questiontypelist__item[data-menu-item=\"select_one\"]"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_css_selector(".questiontypelist__item[data-menu-item=\"select_one\"]").click() for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".card--selectquestion__expansion li:nth-child(1) span"): break except: pass time.sleep(1) else: self.fail("time out") self.assertEqual("Selenium test question label.", driver.find_element_by_css_selector(".card__header-title").text) driver.find_element_by_css_selector(".card--selectquestion__expansion li:nth-child(1) .editable-wrapper span:first-child").click() for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".card--selectquestion__expansion li:nth-child(1) input"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_css_selector(".card--selectquestion__expansion li:nth-child(1) input").send_keys(Keys.SHIFT, Keys.END, Keys.SHIFT, Keys.DELETE) driver.find_element_by_css_selector(".card--selectquestion__expansion li:nth-child(1) input").send_keys("Selenium test question choice 1.", Keys.ENTER) self.assertEqual("Selenium test question choice 1.", driver.find_element_by_css_selector(".card--selectquestion__expansion li:nth-child(1) span").text) self.assertTrue(self.is_element_present(By.CSS_SELECTOR, ".card--selectquestion__expansion li:nth-child(2) span")) driver.find_element_by_css_selector(".card--selectquestion__expansion li:nth-child(2) span").click() for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".card--selectquestion__expansion li:nth-child(2) input"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_css_selector(".card--selectquestion__expansion li:nth-child(2) input").send_keys(Keys.SHIFT, Keys.END, Keys.SHIFT, Keys.DELETE) driver.find_element_by_css_selector(".card--selectquestion__expansion li:nth-child(2) input").send_keys("Selenium test question choice 2.", Keys.ENTER) self.assertEqual("Selenium test question choice 2.", driver.find_element_by_css_selector(".card--selectquestion__expansion li:nth-child(2) span").text) self.assertTrue(self.is_element_present(By.ID, "save")) driver.find_element_by_id("save").click() for i in range(60): try: if self.is_element_present(By.CSS_SELECTOR, ".forms__card__title"): break except: pass time.sleep(1) else: self.fail("time out") self.assertEqual("Selenium test form title.", driver.find_element_by_css_selector(".forms__card__title").text) def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException, e: return False return True def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException, e: return False return True def close_alert_and_get_its_text(self): try: alert = self.driver.switch_to_alert() alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True def tearDown(self): self.driver.quit() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main()
gpl-3.0
kustodian/ansible
lib/ansible/plugins/test/files.py
170
1518
# (c) 2015, Ansible, Inc # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from os.path import isdir, isfile, isabs, exists, lexists, islink, samefile, ismount from ansible import errors class TestModule(object): ''' Ansible file jinja2 tests ''' def tests(self): return { # file testing 'is_dir': isdir, 'directory': isdir, 'is_file': isfile, 'file': isfile, 'is_link': islink, 'link': islink, 'exists': exists, 'link_exists': lexists, # path testing 'is_abs': isabs, 'abs': isabs, 'is_same_file': samefile, 'same_file': samefile, 'is_mount': ismount, 'mount': ismount, }
gpl-3.0