repo_name
stringlengths
5
100
path
stringlengths
4
299
copies
stringlengths
1
5
size
stringlengths
4
7
content
stringlengths
666
1.03M
license
stringclasses
15 values
hash
int64
-9,223,351,895,964,839,000
9,223,297,778B
line_mean
float64
3.17
100
line_max
int64
7
1k
alpha_frac
float64
0.25
0.98
autogenerated
bool
1 class
tysonclugg/django
tests/auth_tests/test_validators.py
25
10145
import os from django.contrib.auth import validators from django.contrib.auth.models import User from django.contrib.auth.password_validation import ( CommonPasswordValidator, MinimumLengthValidator, NumericPasswordValidator, UserAttributeSimilarityValidator, get_default_password_validators, get_password_validators, password_changed, password_validators_help_text_html, password_validators_help_texts, validate_password, ) from django.core.exceptions import ValidationError from django.db import models from django.test import TestCase, override_settings from django.test.utils import isolate_apps @override_settings(AUTH_PASSWORD_VALIDATORS=[ {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 12, }}, ]) class PasswordValidationTest(TestCase): def test_get_default_password_validators(self): validators = get_default_password_validators() self.assertEqual(len(validators), 2) self.assertEqual(validators[0].__class__.__name__, 'CommonPasswordValidator') self.assertEqual(validators[1].__class__.__name__, 'MinimumLengthValidator') self.assertEqual(validators[1].min_length, 12) def test_get_password_validators_custom(self): validator_config = [{'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}] validators = get_password_validators(validator_config) self.assertEqual(len(validators), 1) self.assertEqual(validators[0].__class__.__name__, 'CommonPasswordValidator') self.assertEqual(get_password_validators([]), []) def test_validate_password(self): self.assertIsNone(validate_password('sufficiently-long')) msg_too_short = 'This password is too short. It must contain at least 12 characters.' with self.assertRaises(ValidationError) as cm: validate_password('django4242') self.assertEqual(cm.exception.messages, [msg_too_short]) self.assertEqual(cm.exception.error_list[0].code, 'password_too_short') with self.assertRaises(ValidationError) as cm: validate_password('password') self.assertEqual(cm.exception.messages, ['This password is too common.', msg_too_short]) self.assertEqual(cm.exception.error_list[0].code, 'password_too_common') self.assertIsNone(validate_password('password', password_validators=[])) def test_password_changed(self): self.assertIsNone(password_changed('password')) def test_password_validators_help_texts(self): help_texts = password_validators_help_texts() self.assertEqual(len(help_texts), 2) self.assertIn('12 characters', help_texts[1]) self.assertEqual(password_validators_help_texts(password_validators=[]), []) def test_password_validators_help_text_html(self): help_text = password_validators_help_text_html() self.assertEqual(help_text.count('<li>'), 2) self.assertIn('12 characters', help_text) @override_settings(AUTH_PASSWORD_VALIDATORS=[]) def test_empty_password_validator_help_text_html(self): self.assertEqual(password_validators_help_text_html(), '') class MinimumLengthValidatorTest(TestCase): def test_validate(self): expected_error = "This password is too short. It must contain at least %d characters." self.assertIsNone(MinimumLengthValidator().validate('12345678')) self.assertIsNone(MinimumLengthValidator(min_length=3).validate('123')) with self.assertRaises(ValidationError) as cm: MinimumLengthValidator().validate('1234567') self.assertEqual(cm.exception.messages, [expected_error % 8]) self.assertEqual(cm.exception.error_list[0].code, 'password_too_short') with self.assertRaises(ValidationError) as cm: MinimumLengthValidator(min_length=3).validate('12') self.assertEqual(cm.exception.messages, [expected_error % 3]) def test_help_text(self): self.assertEqual( MinimumLengthValidator().get_help_text(), "Your password must contain at least 8 characters." ) class UserAttributeSimilarityValidatorTest(TestCase): def test_validate(self): user = User.objects.create_user( username='testclient', password='password', email='testclient@example.com', first_name='Test', last_name='Client', ) expected_error = "The password is too similar to the %s." self.assertIsNone(UserAttributeSimilarityValidator().validate('testclient')) with self.assertRaises(ValidationError) as cm: UserAttributeSimilarityValidator().validate('testclient', user=user), self.assertEqual(cm.exception.messages, [expected_error % "username"]) self.assertEqual(cm.exception.error_list[0].code, 'password_too_similar') with self.assertRaises(ValidationError) as cm: UserAttributeSimilarityValidator().validate('example.com', user=user), self.assertEqual(cm.exception.messages, [expected_error % "email address"]) with self.assertRaises(ValidationError) as cm: UserAttributeSimilarityValidator( user_attributes=['first_name'], max_similarity=0.3, ).validate('testclient', user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # max_similarity=1 doesn't allow passwords that are identical to the # attribute's value. with self.assertRaises(ValidationError) as cm: UserAttributeSimilarityValidator( user_attributes=['first_name'], max_similarity=1, ).validate(user.first_name, user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # max_similarity=0 rejects all passwords. with self.assertRaises(ValidationError) as cm: UserAttributeSimilarityValidator( user_attributes=['first_name'], max_similarity=0, ).validate('XXX', user=user) self.assertEqual(cm.exception.messages, [expected_error % "first name"]) # Passes validation. self.assertIsNone( UserAttributeSimilarityValidator(user_attributes=['first_name']).validate('testclient', user=user) ) @isolate_apps('auth_tests') def test_validate_property(self): class TestUser(models.Model): pass @property def username(self): return 'foobar' with self.assertRaises(ValidationError) as cm: UserAttributeSimilarityValidator().validate('foobar', user=TestUser()), self.assertEqual(cm.exception.messages, ['The password is too similar to the username.']) def test_help_text(self): self.assertEqual( UserAttributeSimilarityValidator().get_help_text(), "Your password can't be too similar to your other personal information." ) class CommonPasswordValidatorTest(TestCase): def test_validate(self): expected_error = "This password is too common." self.assertIsNone(CommonPasswordValidator().validate('a-safe-password')) with self.assertRaises(ValidationError) as cm: CommonPasswordValidator().validate('godzilla') self.assertEqual(cm.exception.messages, [expected_error]) def test_validate_custom_list(self): path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'common-passwords-custom.txt') validator = CommonPasswordValidator(password_list_path=path) expected_error = "This password is too common." self.assertIsNone(validator.validate('a-safe-password')) with self.assertRaises(ValidationError) as cm: validator.validate('from-my-custom-list') self.assertEqual(cm.exception.messages, [expected_error]) self.assertEqual(cm.exception.error_list[0].code, 'password_too_common') def test_help_text(self): self.assertEqual( CommonPasswordValidator().get_help_text(), "Your password can't be a commonly used password." ) class NumericPasswordValidatorTest(TestCase): def test_validate(self): expected_error = "This password is entirely numeric." self.assertIsNone(NumericPasswordValidator().validate('a-safe-password')) with self.assertRaises(ValidationError) as cm: NumericPasswordValidator().validate('42424242') self.assertEqual(cm.exception.messages, [expected_error]) self.assertEqual(cm.exception.error_list[0].code, 'password_entirely_numeric') def test_help_text(self): self.assertEqual( NumericPasswordValidator().get_help_text(), "Your password can't be entirely numeric." ) class UsernameValidatorsTests(TestCase): def test_unicode_validator(self): valid_usernames = ['joe', 'René', 'ᴮᴵᴳᴮᴵᴿᴰ', 'أحمد'] invalid_usernames = [ "o'connell", "عبد ال", "zerowidth\u200Bspace", "nonbreaking\u00A0space", "en\u2013dash", ] v = validators.UnicodeUsernameValidator() for valid in valid_usernames: with self.subTest(valid=valid): v(valid) for invalid in invalid_usernames: with self.subTest(invalid=invalid): with self.assertRaises(ValidationError): v(invalid) def test_ascii_validator(self): valid_usernames = ['glenn', 'GLEnN', 'jean-marc'] invalid_usernames = ["o'connell", 'Éric', 'jean marc', "أحمد"] v = validators.ASCIIUsernameValidator() for valid in valid_usernames: with self.subTest(valid=valid): v(valid) for invalid in invalid_usernames: with self.subTest(invalid=invalid): with self.assertRaises(ValidationError): v(invalid)
bsd-3-clause
-290,188,637,694,032,100
42.230769
110
0.667655
false
shootstar/ctest
ceilometer/agent.py
1
3976
# -*- encoding: utf-8 -*- # # Copyright © 2013 Julien Danjou # # Author: Julien Danjou <julien@danjou.info> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import abc import itertools from oslo.config import cfg from stevedore import dispatch from ceilometer.logger import logger from ceilometer.openstack.common import context from ceilometer.openstack.common import log from ceilometer import pipeline LOG = log.getLogger(__name__) class PollingTask(object): """Polling task for polling counters and inject into pipeline A polling task can be invoked periodically or only once""" def __init__(self, agent_manager): self.manager = agent_manager self.pollsters = set() self.publish_context = pipeline.PublishContext( agent_manager.context, cfg.CONF.counter_source) def add(self, pollster, pipelines): self.publish_context.add_pipelines(pipelines) self.pollsters.update([pollster]) @abc.abstractmethod def poll_and_publish(self): """Polling counter and publish into pipeline.""" class AgentManager(object): def __init__(self, extension_manager): logger.debug("AGENT MANAGER") publisher_manager = dispatch.NameDispatchExtensionManager( namespace=pipeline.PUBLISHER_NAMESPACE, check_func=lambda x: True, invoke_on_load=True, ) self.pipeline_manager = pipeline.setup_pipeline(publisher_manager) self.pollster_manager = extension_manager self.context = context.RequestContext('admin', 'admin', is_admin=True) logger.debug("pipeline manager:{}".format(self.pipeline_manager)) logger.debug("pollster manager:{}".format(self.pollster_manager)) @abc.abstractmethod def create_polling_task(self): """Create an empty polling task.""" def setup_polling_tasks(self): polling_tasks = {} logger.debug("setup polling tasks") for pipeline, pollster in itertools.product( self.pipeline_manager.pipelines, self.pollster_manager.extensions): logger.debug("pipeline:{},pollster:{}".format(pipeline,pollster)) for counter in pollster.obj.get_counter_names(): logger.debug("counter:{}".format(counter)) if pipeline.support_counter(counter): logger.debug("pipeline support counter:{}".format(counter)) polling_task = polling_tasks.get(pipeline.interval, None) if not polling_task: polling_task = self.create_polling_task() polling_tasks[pipeline.interval] = polling_task polling_task.add(pollster, [pipeline]) break logger.debug("POLLINGTASK:{}".format([p.name for p in polling_task.pollsters])) return polling_tasks def initialize_service_hook(self, service): logger.debug("service:{}".format(service)) self.service = service for interval, task in self.setup_polling_tasks().iteritems(): logger.debug("intervak:{} task:{}".format(interval,task)) #openstack.common.threadgroup.pyなどが呼ばれる self.service.tg.add_timer(interval, self.interval_task, task=task) def interval_task(self, task): task.poll_and_publish()
apache-2.0
2,645,021,736,772,453,000
36.018692
87
0.644282
false
hy-2013/scrapy
scrapy/xlib/tx/_newclient.py
159
55339
# -*- test-case-name: twisted.web.test.test_newclient -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ An U{HTTP 1.1<http://www.w3.org/Protocols/rfc2616/rfc2616.html>} client. The way to use the functionality provided by this module is to: - Connect a L{HTTP11ClientProtocol} to an HTTP server - Create a L{Request} with the appropriate data - Pass the request to L{HTTP11ClientProtocol.request} - The returned Deferred will fire with a L{Response} object - Create a L{IProtocol} provider which can handle the response body - Connect it to the response with L{Response.deliverBody} - When the protocol's C{connectionLost} method is called, the response is complete. See L{Response.deliverBody} for details. Various other classes in this module support this usage: - HTTPParser is the basic HTTP parser. It can handle the parts of HTTP which are symmetric between requests and responses. - HTTPClientParser extends HTTPParser to handle response-specific parts of HTTP. One instance is created for each request to parse the corresponding response. """ __metaclass__ = type from zope.interface import implements from twisted.python import log from twisted.python.reflect import fullyQualifiedName from twisted.python.failure import Failure from twisted.internet.interfaces import IConsumer, IPushProducer from twisted.internet.error import ConnectionDone from twisted.internet.defer import Deferred, succeed, fail, maybeDeferred from twisted.internet.defer import CancelledError from twisted.internet.protocol import Protocol from twisted.protocols.basic import LineReceiver from twisted.web.http_headers import Headers from twisted.web.http import NO_CONTENT, NOT_MODIFIED from twisted.web.http import _DataLoss, PotentialDataLoss from twisted.web.http import _IdentityTransferDecoder, _ChunkedTransferDecoder from .iweb import IResponse, UNKNOWN_LENGTH # States HTTPParser can be in STATUS = 'STATUS' HEADER = 'HEADER' BODY = 'BODY' DONE = 'DONE' class BadHeaders(Exception): """ Headers passed to L{Request} were in some way invalid. """ class ExcessWrite(Exception): """ The body L{IBodyProducer} for a request tried to write data after indicating it had finished writing data. """ class ParseError(Exception): """ Some received data could not be parsed. @ivar data: The string which could not be parsed. """ def __init__(self, reason, data): Exception.__init__(self, reason, data) self.data = data class BadResponseVersion(ParseError): """ The version string in a status line was unparsable. """ class _WrapperException(Exception): """ L{_WrapperException} is the base exception type for exceptions which include one or more other exceptions as the low-level causes. @ivar reasons: A list of exceptions. See subclass documentation for more details. """ def __init__(self, reasons): Exception.__init__(self, reasons) self.reasons = reasons class RequestGenerationFailed(_WrapperException): """ There was an error while creating the bytes which make up a request. @ivar reasons: A C{list} of one or more L{Failure} instances giving the reasons the request generation was considered to have failed. """ class RequestTransmissionFailed(_WrapperException): """ There was an error while sending the bytes which make up a request. @ivar reasons: A C{list} of one or more L{Failure} instances giving the reasons the request transmission was considered to have failed. """ class ConnectionAborted(Exception): """ The connection was explicitly aborted by application code. """ class WrongBodyLength(Exception): """ An L{IBodyProducer} declared the number of bytes it was going to produce (via its C{length} attribute) and then produced a different number of bytes. """ class ResponseDone(Exception): """ L{ResponseDone} may be passed to L{IProtocol.connectionLost} on the protocol passed to L{Response.deliverBody} and indicates that the entire response has been delivered. """ class ResponseFailed(_WrapperException): """ L{ResponseFailed} indicates that all of the response to a request was not received for some reason. @ivar reasons: A C{list} of one or more L{Failure} instances giving the reasons the response was considered to have failed. @ivar response: If specified, the L{Response} received from the server (and in particular the status code and the headers). """ def __init__(self, reasons, response=None): _WrapperException.__init__(self, reasons) self.response = response class ResponseNeverReceived(ResponseFailed): """ A L{ResponseFailed} that knows no response bytes at all have been received. """ class RequestNotSent(Exception): """ L{RequestNotSent} indicates that an attempt was made to issue a request but for reasons unrelated to the details of the request itself, the request could not be sent. For example, this may indicate that an attempt was made to send a request using a protocol which is no longer connected to a server. """ def _callAppFunction(function): """ Call C{function}. If it raises an exception, log it with a minimal description of the source. @return: C{None} """ try: function() except: log.err(None, "Unexpected exception from %s" % ( fullyQualifiedName(function),)) class HTTPParser(LineReceiver): """ L{HTTPParser} handles the parsing side of HTTP processing. With a suitable subclass, it can parse either the client side or the server side of the connection. @ivar headers: All of the non-connection control message headers yet received. @ivar state: State indicator for the response parsing state machine. One of C{STATUS}, C{HEADER}, C{BODY}, C{DONE}. @ivar _partialHeader: C{None} or a C{list} of the lines of a multiline header while that header is being received. """ # NOTE: According to HTTP spec, we're supposed to eat the # 'Proxy-Authenticate' and 'Proxy-Authorization' headers also, but that # doesn't sound like a good idea to me, because it makes it impossible to # have a non-authenticating transparent proxy in front of an authenticating # proxy. An authenticating proxy can eat them itself. -jknight # # Further, quoting # http://homepages.tesco.net/J.deBoynePollard/FGA/web-proxy-connection-header.html # regarding the 'Proxy-Connection' header: # # The Proxy-Connection: header is a mistake in how some web browsers # use HTTP. Its name is the result of a false analogy. It is not a # standard part of the protocol. There is a different standard # protocol mechanism for doing what it does. And its existence # imposes a requirement upon HTTP servers such that no proxy HTTP # server can be standards-conforming in practice. # # -exarkun # Some servers (like http://news.ycombinator.com/) return status lines and # HTTP headers delimited by \n instead of \r\n. delimiter = '\n' CONNECTION_CONTROL_HEADERS = set([ 'content-length', 'connection', 'keep-alive', 'te', 'trailers', 'transfer-encoding', 'upgrade', 'proxy-connection']) def connectionMade(self): self.headers = Headers() self.connHeaders = Headers() self.state = STATUS self._partialHeader = None def switchToBodyMode(self, decoder): """ Switch to body parsing mode - interpret any more bytes delivered as part of the message body and deliver them to the given decoder. """ if self.state == BODY: raise RuntimeError("already in body mode") self.bodyDecoder = decoder self.state = BODY self.setRawMode() def lineReceived(self, line): """ Handle one line from a response. """ # Handle the normal CR LF case. if line[-1:] == '\r': line = line[:-1] if self.state == STATUS: self.statusReceived(line) self.state = HEADER elif self.state == HEADER: if not line or line[0] not in ' \t': if self._partialHeader is not None: header = ''.join(self._partialHeader) name, value = header.split(':', 1) value = value.strip() self.headerReceived(name, value) if not line: # Empty line means the header section is over. self.allHeadersReceived() else: # Line not beginning with LWS is another header. self._partialHeader = [line] else: # A line beginning with LWS is a continuation of a header # begun on a previous line. self._partialHeader.append(line) def rawDataReceived(self, data): """ Pass data from the message body to the body decoder object. """ self.bodyDecoder.dataReceived(data) def isConnectionControlHeader(self, name): """ Return C{True} if the given lower-cased name is the name of a connection control header (rather than an entity header). According to RFC 2616, section 14.10, the tokens in the Connection header are probably relevant here. However, I am not sure what the practical consequences of either implementing or ignoring that are. So I leave it unimplemented for the time being. """ return name in self.CONNECTION_CONTROL_HEADERS def statusReceived(self, status): """ Callback invoked whenever the first line of a new message is received. Override this. @param status: The first line of an HTTP request or response message without trailing I{CR LF}. @type status: C{str} """ def headerReceived(self, name, value): """ Store the given header in C{self.headers}. """ name = name.lower() if self.isConnectionControlHeader(name): headers = self.connHeaders else: headers = self.headers headers.addRawHeader(name, value) def allHeadersReceived(self): """ Callback invoked after the last header is passed to C{headerReceived}. Override this to change to the C{BODY} or C{DONE} state. """ self.switchToBodyMode(None) class HTTPClientParser(HTTPParser): """ An HTTP parser which only handles HTTP responses. @ivar request: The request with which the expected response is associated. @type request: L{Request} @ivar NO_BODY_CODES: A C{set} of response codes which B{MUST NOT} have a body. @ivar finisher: A callable to invoke when this response is fully parsed. @ivar _responseDeferred: A L{Deferred} which will be called back with the response when all headers in the response have been received. Thereafter, C{None}. @ivar _everReceivedData: C{True} if any bytes have been received. """ NO_BODY_CODES = set([NO_CONTENT, NOT_MODIFIED]) _transferDecoders = { 'chunked': _ChunkedTransferDecoder, } bodyDecoder = None def __init__(self, request, finisher): self.request = request self.finisher = finisher self._responseDeferred = Deferred() self._everReceivedData = False def dataReceived(self, data): """ Override so that we know if any response has been received. """ self._everReceivedData = True HTTPParser.dataReceived(self, data) def parseVersion(self, strversion): """ Parse version strings of the form Protocol '/' Major '.' Minor. E.g. 'HTTP/1.1'. Returns (protocol, major, minor). Will raise ValueError on bad syntax. """ try: proto, strnumber = strversion.split('/') major, minor = strnumber.split('.') major, minor = int(major), int(minor) except ValueError as e: raise BadResponseVersion(str(e), strversion) if major < 0 or minor < 0: raise BadResponseVersion("version may not be negative", strversion) return (proto, major, minor) def statusReceived(self, status): """ Parse the status line into its components and create a response object to keep track of this response's state. """ parts = status.split(' ', 2) if len(parts) != 3: raise ParseError("wrong number of parts", status) try: statusCode = int(parts[1]) except ValueError: raise ParseError("non-integer status code", status) self.response = Response( self.parseVersion(parts[0]), statusCode, parts[2], self.headers, self.transport) def _finished(self, rest): """ Called to indicate that an entire response has been received. No more bytes will be interpreted by this L{HTTPClientParser}. Extra bytes are passed up and the state of this L{HTTPClientParser} is set to I{DONE}. @param rest: A C{str} giving any extra bytes delivered to this L{HTTPClientParser} which are not part of the response being parsed. """ self.state = DONE self.finisher(rest) def isConnectionControlHeader(self, name): """ Content-Length in the response to a HEAD request is an entity header, not a connection control header. """ if self.request.method == 'HEAD' and name == 'content-length': return False return HTTPParser.isConnectionControlHeader(self, name) def allHeadersReceived(self): """ Figure out how long the response body is going to be by examining headers and stuff. """ if (self.response.code in self.NO_BODY_CODES or self.request.method == 'HEAD'): self.response.length = 0 self._finished(self.clearLineBuffer()) else: transferEncodingHeaders = self.connHeaders.getRawHeaders( 'transfer-encoding') if transferEncodingHeaders: # This could be a KeyError. However, that would mean we do not # know how to decode the response body, so failing the request # is as good a behavior as any. Perhaps someday we will want # to normalize/document/test this specifically, but failing # seems fine to me for now. transferDecoder = self._transferDecoders[transferEncodingHeaders[0].lower()] # If anyone ever invents a transfer encoding other than # chunked (yea right), and that transfer encoding can predict # the length of the response body, it might be sensible to # allow the transfer decoder to set the response object's # length attribute. else: contentLengthHeaders = self.connHeaders.getRawHeaders('content-length') if contentLengthHeaders is None: contentLength = None elif len(contentLengthHeaders) == 1: contentLength = int(contentLengthHeaders[0]) self.response.length = contentLength else: # "HTTP Message Splitting" or "HTTP Response Smuggling" # potentially happening. Or it's just a buggy server. raise ValueError( "Too many Content-Length headers; response is invalid") if contentLength == 0: self._finished(self.clearLineBuffer()) transferDecoder = None else: transferDecoder = lambda x, y: _IdentityTransferDecoder( contentLength, x, y) if transferDecoder is None: self.response._bodyDataFinished() else: # Make sure as little data as possible from the response body # gets delivered to the response object until the response # object actually indicates it is ready to handle bytes # (probably because an application gave it a way to interpret # them). self.transport.pauseProducing() self.switchToBodyMode(transferDecoder( self.response._bodyDataReceived, self._finished)) # This must be last. If it were first, then application code might # change some state (for example, registering a protocol to receive the # response body). Then the pauseProducing above would be wrong since # the response is ready for bytes and nothing else would ever resume # the transport. self._responseDeferred.callback(self.response) del self._responseDeferred def connectionLost(self, reason): if self.bodyDecoder is not None: try: try: self.bodyDecoder.noMoreData() except PotentialDataLoss: self.response._bodyDataFinished(Failure()) except _DataLoss: self.response._bodyDataFinished( Failure(ResponseFailed([reason, Failure()], self.response))) else: self.response._bodyDataFinished() except: # Handle exceptions from both the except suites and the else # suite. Those functions really shouldn't raise exceptions, # but maybe there's some buggy application code somewhere # making things difficult. log.err() elif self.state != DONE: if self._everReceivedData: exceptionClass = ResponseFailed else: exceptionClass = ResponseNeverReceived self._responseDeferred.errback(Failure(exceptionClass([reason]))) del self._responseDeferred class Request: """ A L{Request} instance describes an HTTP request to be sent to an HTTP server. @ivar method: The HTTP method to for this request, ex: 'GET', 'HEAD', 'POST', etc. @type method: C{str} @ivar uri: The relative URI of the resource to request. For example, C{'/foo/bar?baz=quux'}. @type uri: C{str} @ivar headers: Headers to be sent to the server. It is important to note that this object does not create any implicit headers. So it is up to the HTTP Client to add required headers such as 'Host'. @type headers: L{twisted.web.http_headers.Headers} @ivar bodyProducer: C{None} or an L{IBodyProducer} provider which produces the content body to send to the remote HTTP server. @ivar persistent: Set to C{True} when you use HTTP persistent connection. @type persistent: C{bool} """ def __init__(self, method, uri, headers, bodyProducer, persistent=False): self.method = method self.uri = uri self.headers = headers self.bodyProducer = bodyProducer self.persistent = persistent def _writeHeaders(self, transport, TEorCL): hosts = self.headers.getRawHeaders('host', ()) if len(hosts) != 1: raise BadHeaders("Exactly one Host header required") # In the future, having the protocol version be a parameter to this # method would probably be good. It would be nice if this method # weren't limited to issuing HTTP/1.1 requests. requestLines = [] requestLines.append( '%s %s HTTP/1.1\r\n' % (self.method, self.uri)) if not self.persistent: requestLines.append('Connection: close\r\n') if TEorCL is not None: requestLines.append(TEorCL) for name, values in self.headers.getAllRawHeaders(): requestLines.extend(['%s: %s\r\n' % (name, v) for v in values]) requestLines.append('\r\n') transport.writeSequence(requestLines) def _writeToChunked(self, transport): """ Write this request to the given transport using chunked transfer-encoding to frame the body. """ self._writeHeaders(transport, 'Transfer-Encoding: chunked\r\n') encoder = ChunkedEncoder(transport) encoder.registerProducer(self.bodyProducer, True) d = self.bodyProducer.startProducing(encoder) def cbProduced(ignored): encoder.unregisterProducer() def ebProduced(err): encoder._allowNoMoreWrites() # Don't call the encoder's unregisterProducer because it will write # a zero-length chunk. This would indicate to the server that the # request body is complete. There was an error, though, so we # don't want to do that. transport.unregisterProducer() return err d.addCallbacks(cbProduced, ebProduced) return d def _writeToContentLength(self, transport): """ Write this request to the given transport using content-length to frame the body. """ self._writeHeaders( transport, 'Content-Length: %d\r\n' % (self.bodyProducer.length,)) # This Deferred is used to signal an error in the data written to the # encoder below. It can only errback and it will only do so before too # many bytes have been written to the encoder and before the producer # Deferred fires. finishedConsuming = Deferred() # This makes sure the producer writes the correct number of bytes for # the request body. encoder = LengthEnforcingConsumer( self.bodyProducer, transport, finishedConsuming) transport.registerProducer(self.bodyProducer, True) finishedProducing = self.bodyProducer.startProducing(encoder) def combine(consuming, producing): # This Deferred is returned and will be fired when the first of # consuming or producing fires. If it's cancelled, forward that # cancellation to the producer. def cancelConsuming(ign): finishedProducing.cancel() ultimate = Deferred(cancelConsuming) # Keep track of what has happened so far. This initially # contains None, then an integer uniquely identifying what # sequence of events happened. See the callbacks and errbacks # defined below for the meaning of each value. state = [None] def ebConsuming(err): if state == [None]: # The consuming Deferred failed first. This means the # overall writeTo Deferred is going to errback now. The # producing Deferred should not fire later (because the # consumer should have called stopProducing on the # producer), but if it does, a callback will be ignored # and an errback will be logged. state[0] = 1 ultimate.errback(err) else: # The consuming Deferred errbacked after the producing # Deferred fired. This really shouldn't ever happen. # If it does, I goofed. Log the error anyway, just so # there's a chance someone might notice and complain. log.err( err, "Buggy state machine in %r/[%d]: " "ebConsuming called" % (self, state[0])) def cbProducing(result): if state == [None]: # The producing Deferred succeeded first. Nothing will # ever happen to the consuming Deferred. Tell the # encoder we're done so it can check what the producer # wrote and make sure it was right. state[0] = 2 try: encoder._noMoreWritesExpected() except: # Fail the overall writeTo Deferred - something the # producer did was wrong. ultimate.errback() else: # Success - succeed the overall writeTo Deferred. ultimate.callback(None) # Otherwise, the consuming Deferred already errbacked. The # producing Deferred wasn't supposed to fire, but it did # anyway. It's buggy, but there's not really anything to be # done about it. Just ignore this result. def ebProducing(err): if state == [None]: # The producing Deferred failed first. This means the # overall writeTo Deferred is going to errback now. # Tell the encoder that we're done so it knows to reject # further writes from the producer (which should not # happen, but the producer may be buggy). state[0] = 3 encoder._allowNoMoreWrites() ultimate.errback(err) else: # The producing Deferred failed after the consuming # Deferred failed. It shouldn't have, so it's buggy. # Log the exception in case anyone who can fix the code # is watching. log.err(err, "Producer is buggy") consuming.addErrback(ebConsuming) producing.addCallbacks(cbProducing, ebProducing) return ultimate d = combine(finishedConsuming, finishedProducing) def f(passthrough): # Regardless of what happens with the overall Deferred, once it # fires, the producer registered way up above the definition of # combine should be unregistered. transport.unregisterProducer() return passthrough d.addBoth(f) return d def writeTo(self, transport): """ Format this L{Request} as an HTTP/1.1 request and write it to the given transport. If bodyProducer is not None, it will be associated with an L{IConsumer}. @return: A L{Deferred} which fires with C{None} when the request has been completely written to the transport or with a L{Failure} if there is any problem generating the request bytes. """ if self.bodyProducer is not None: if self.bodyProducer.length is UNKNOWN_LENGTH: return self._writeToChunked(transport) else: return self._writeToContentLength(transport) else: self._writeHeaders(transport, None) return succeed(None) def stopWriting(self): """ Stop writing this request to the transport. This can only be called after C{writeTo} and before the L{Deferred} returned by C{writeTo} fires. It should cancel any asynchronous task started by C{writeTo}. The L{Deferred} returned by C{writeTo} need not be fired if this method is called. """ # If bodyProducer is None, then the Deferred returned by writeTo has # fired already and this method cannot be called. _callAppFunction(self.bodyProducer.stopProducing) class LengthEnforcingConsumer: """ An L{IConsumer} proxy which enforces an exact length requirement on the total data written to it. @ivar _length: The number of bytes remaining to be written. @ivar _producer: The L{IBodyProducer} which is writing to this consumer. @ivar _consumer: The consumer to which at most C{_length} bytes will be forwarded. @ivar _finished: A L{Deferred} which will be fired with a L{Failure} if too many bytes are written to this consumer. """ def __init__(self, producer, consumer, finished): self._length = producer.length self._producer = producer self._consumer = consumer self._finished = finished def _allowNoMoreWrites(self): """ Indicate that no additional writes are allowed. Attempts to write after calling this method will be met with an exception. """ self._finished = None def write(self, bytes): """ Write C{bytes} to the underlying consumer unless C{_noMoreWritesExpected} has been called or there are/have been too many bytes. """ if self._finished is None: # No writes are supposed to happen any more. Try to convince the # calling code to stop calling this method by calling its # stopProducing method and then throwing an exception at it. This # exception isn't documented as part of the API because you're # never supposed to expect it: only buggy code will ever receive # it. self._producer.stopProducing() raise ExcessWrite() if len(bytes) <= self._length: self._length -= len(bytes) self._consumer.write(bytes) else: # No synchronous exception is raised in *this* error path because # we still have _finished which we can use to report the error to a # better place than the direct caller of this method (some # arbitrary application code). _callAppFunction(self._producer.stopProducing) self._finished.errback(WrongBodyLength("too many bytes written")) self._allowNoMoreWrites() def _noMoreWritesExpected(self): """ Called to indicate no more bytes will be written to this consumer. Check to see that the correct number have been written. @raise WrongBodyLength: If not enough bytes have been written. """ if self._finished is not None: self._allowNoMoreWrites() if self._length: raise WrongBodyLength("too few bytes written") def makeStatefulDispatcher(name, template): """ Given a I{dispatch} name and a function, return a function which can be used as a method and which, when called, will call another method defined on the instance and return the result. The other method which is called is determined by the value of the C{_state} attribute of the instance. @param name: A string which is used to construct the name of the subsidiary method to invoke. The subsidiary method is named like C{'_%s_%s' % (name, _state)}. @param template: A function object which is used to give the returned function a docstring. @return: The dispatcher function. """ def dispatcher(self, *args, **kwargs): func = getattr(self, '_' + name + '_' + self._state, None) if func is None: raise RuntimeError( "%r has no %s method in state %s" % (self, name, self._state)) return func(*args, **kwargs) dispatcher.__doc__ = template.__doc__ return dispatcher class Response: """ A L{Response} instance describes an HTTP response received from an HTTP server. L{Response} should not be subclassed or instantiated. @ivar _transport: The transport which is delivering this response. @ivar _bodyProtocol: The L{IProtocol} provider to which the body is delivered. C{None} before one has been registered with C{deliverBody}. @ivar _bodyBuffer: A C{list} of the strings passed to C{bodyDataReceived} before C{deliverBody} is called. C{None} afterwards. @ivar _state: Indicates what state this L{Response} instance is in, particularly with respect to delivering bytes from the response body to an application-suppled protocol object. This may be one of C{'INITIAL'}, C{'CONNECTED'}, C{'DEFERRED_CLOSE'}, or C{'FINISHED'}, with the following meanings: - INITIAL: This is the state L{Response} objects start in. No protocol has yet been provided and the underlying transport may still have bytes to deliver to it. - DEFERRED_CLOSE: If the underlying transport indicates all bytes have been delivered but no application-provided protocol is yet available, the L{Response} moves to this state. Data is buffered and waiting for a protocol to be delivered to. - CONNECTED: If a protocol is provided when the state is INITIAL, the L{Response} moves to this state. Any buffered data is delivered and any data which arrives from the transport subsequently is given directly to the protocol. - FINISHED: If a protocol is provided in the DEFERRED_CLOSE state, the L{Response} moves to this state after delivering all buffered data to the protocol. Otherwise, if the L{Response} is in the CONNECTED state, if the transport indicates there is no more data, the L{Response} moves to this state. Nothing else can happen once the L{Response} is in this state. """ implements(IResponse) length = UNKNOWN_LENGTH _bodyProtocol = None _bodyFinished = False def __init__(self, version, code, phrase, headers, _transport): self.version = version self.code = code self.phrase = phrase self.headers = headers self._transport = _transport self._bodyBuffer = [] self._state = 'INITIAL' def deliverBody(self, protocol): """ Dispatch the given L{IProtocol} depending of the current state of the response. """ deliverBody = makeStatefulDispatcher('deliverBody', deliverBody) def _deliverBody_INITIAL(self, protocol): """ Deliver any buffered data to C{protocol} and prepare to deliver any future data to it. Move to the C{'CONNECTED'} state. """ # Now that there's a protocol to consume the body, resume the # transport. It was previously paused by HTTPClientParser to avoid # reading too much data before it could be handled. self._transport.resumeProducing() protocol.makeConnection(self._transport) self._bodyProtocol = protocol for data in self._bodyBuffer: self._bodyProtocol.dataReceived(data) self._bodyBuffer = None self._state = 'CONNECTED' def _deliverBody_CONNECTED(self, protocol): """ It is invalid to attempt to deliver data to a protocol when it is already being delivered to another protocol. """ raise RuntimeError( "Response already has protocol %r, cannot deliverBody " "again" % (self._bodyProtocol,)) def _deliverBody_DEFERRED_CLOSE(self, protocol): """ Deliver any buffered data to C{protocol} and then disconnect the protocol. Move to the C{'FINISHED'} state. """ # Unlike _deliverBody_INITIAL, there is no need to resume the # transport here because all of the response data has been received # already. Some higher level code may want to resume the transport if # that code expects further data to be received over it. protocol.makeConnection(self._transport) for data in self._bodyBuffer: protocol.dataReceived(data) self._bodyBuffer = None protocol.connectionLost(self._reason) self._state = 'FINISHED' def _deliverBody_FINISHED(self, protocol): """ It is invalid to attempt to deliver data to a protocol after the response body has been delivered to another protocol. """ raise RuntimeError( "Response already finished, cannot deliverBody now.") def _bodyDataReceived(self, data): """ Called by HTTPClientParser with chunks of data from the response body. They will be buffered or delivered to the protocol passed to deliverBody. """ _bodyDataReceived = makeStatefulDispatcher('bodyDataReceived', _bodyDataReceived) def _bodyDataReceived_INITIAL(self, data): """ Buffer any data received for later delivery to a protocol passed to C{deliverBody}. Little or no data should be buffered by this method, since the transport has been paused and will not be resumed until a protocol is supplied. """ self._bodyBuffer.append(data) def _bodyDataReceived_CONNECTED(self, data): """ Deliver any data received to the protocol to which this L{Response} is connected. """ self._bodyProtocol.dataReceived(data) def _bodyDataReceived_DEFERRED_CLOSE(self, data): """ It is invalid for data to be delivered after it has been indicated that the response body has been completely delivered. """ raise RuntimeError("Cannot receive body data after _bodyDataFinished") def _bodyDataReceived_FINISHED(self, data): """ It is invalid for data to be delivered after the response body has been delivered to a protocol. """ raise RuntimeError("Cannot receive body data after protocol disconnected") def _bodyDataFinished(self, reason=None): """ Called by HTTPClientParser when no more body data is available. If the optional reason is supplied, this indicates a problem or potential problem receiving all of the response body. """ _bodyDataFinished = makeStatefulDispatcher('bodyDataFinished', _bodyDataFinished) def _bodyDataFinished_INITIAL(self, reason=None): """ Move to the C{'DEFERRED_CLOSE'} state to wait for a protocol to which to deliver the response body. """ self._state = 'DEFERRED_CLOSE' if reason is None: reason = Failure(ResponseDone("Response body fully received")) self._reason = reason def _bodyDataFinished_CONNECTED(self, reason=None): """ Disconnect the protocol and move to the C{'FINISHED'} state. """ if reason is None: reason = Failure(ResponseDone("Response body fully received")) self._bodyProtocol.connectionLost(reason) self._bodyProtocol = None self._state = 'FINISHED' def _bodyDataFinished_DEFERRED_CLOSE(self): """ It is invalid to attempt to notify the L{Response} of the end of the response body data more than once. """ raise RuntimeError("Cannot finish body data more than once") def _bodyDataFinished_FINISHED(self): """ It is invalid to attempt to notify the L{Response} of the end of the response body data more than once. """ raise RuntimeError("Cannot finish body data after protocol disconnected") class ChunkedEncoder: """ Helper object which exposes L{IConsumer} on top of L{HTTP11ClientProtocol} for streaming request bodies to the server. """ implements(IConsumer) def __init__(self, transport): self.transport = transport def _allowNoMoreWrites(self): """ Indicate that no additional writes are allowed. Attempts to write after calling this method will be met with an exception. """ self.transport = None def registerProducer(self, producer, streaming): """ Register the given producer with C{self.transport}. """ self.transport.registerProducer(producer, streaming) def write(self, data): """ Write the given request body bytes to the transport using chunked encoding. @type data: C{str} """ if self.transport is None: raise ExcessWrite() self.transport.writeSequence(("%x\r\n" % len(data), data, "\r\n")) def unregisterProducer(self): """ Indicate that the request body is complete and finish the request. """ self.write('') self.transport.unregisterProducer() self._allowNoMoreWrites() class TransportProxyProducer: """ An L{IPushProducer} implementation which wraps another such thing and proxies calls to it until it is told to stop. @ivar _producer: The wrapped L{IPushProducer} provider or C{None} after this proxy has been stopped. """ implements(IPushProducer) # LineReceiver uses this undocumented attribute of transports to decide # when to stop calling lineReceived or rawDataReceived (if it finds it to # be true, it doesn't bother to deliver any more data). Set disconnecting # to False here and never change it to true so that all data is always # delivered to us and so that LineReceiver doesn't fail with an # AttributeError. disconnecting = False def __init__(self, producer): self._producer = producer def _stopProxying(self): """ Stop forwarding calls of L{IPushProducer} methods to the underlying L{IPushProvider} provider. """ self._producer = None def stopProducing(self): """ Proxy the stoppage to the underlying producer, unless this proxy has been stopped. """ if self._producer is not None: self._producer.stopProducing() def resumeProducing(self): """ Proxy the resumption to the underlying producer, unless this proxy has been stopped. """ if self._producer is not None: self._producer.resumeProducing() def pauseProducing(self): """ Proxy the pause to the underlying producer, unless this proxy has been stopped. """ if self._producer is not None: self._producer.pauseProducing() class HTTP11ClientProtocol(Protocol): """ L{HTTP11ClientProtocol} is an implementation of the HTTP 1.1 client protocol. It supports as few features as possible. @ivar _parser: After a request is issued, the L{HTTPClientParser} to which received data making up the response to that request is delivered. @ivar _finishedRequest: After a request is issued, the L{Deferred} which will fire when a L{Response} object corresponding to that request is available. This allows L{HTTP11ClientProtocol} to fail the request if there is a connection or parsing problem. @ivar _currentRequest: After a request is issued, the L{Request} instance used to make that request. This allows L{HTTP11ClientProtocol} to stop request generation if necessary (for example, if the connection is lost). @ivar _transportProxy: After a request is issued, the L{TransportProxyProducer} to which C{_parser} is connected. This allows C{_parser} to pause and resume the transport in a way which L{HTTP11ClientProtocol} can exert some control over. @ivar _responseDeferred: After a request is issued, the L{Deferred} from C{_parser} which will fire with a L{Response} when one has been received. This is eventually chained with C{_finishedRequest}, but only in certain cases to avoid double firing that Deferred. @ivar _state: Indicates what state this L{HTTP11ClientProtocol} instance is in with respect to transmission of a request and reception of a response. This may be one of the following strings: - QUIESCENT: This is the state L{HTTP11ClientProtocol} instances start in. Nothing is happening: no request is being sent and no response is being received or expected. - TRANSMITTING: When a request is made (via L{request}), the instance moves to this state. L{Request.writeTo} has been used to start to send a request but it has not yet finished. - TRANSMITTING_AFTER_RECEIVING_RESPONSE: The server has returned a complete response but the request has not yet been fully sent yet. The instance will remain in this state until the request is fully sent. - GENERATION_FAILED: There was an error while the request. The request was not fully sent to the network. - WAITING: The request was fully sent to the network. The instance is now waiting for the response to be fully received. - ABORTING: Application code has requested that the HTTP connection be aborted. - CONNECTION_LOST: The connection has been lost. @ivar _abortDeferreds: A list of C{Deferred} instances that will fire when the connection is lost. """ _state = 'QUIESCENT' _parser = None _finishedRequest = None _currentRequest = None _transportProxy = None _responseDeferred = None def __init__(self, quiescentCallback=lambda c: None): self._quiescentCallback = quiescentCallback self._abortDeferreds = [] @property def state(self): return self._state def request(self, request): """ Issue C{request} over C{self.transport} and return a L{Deferred} which will fire with a L{Response} instance or an error. @param request: The object defining the parameters of the request to issue. @type request: L{Request} @rtype: L{Deferred} @return: The deferred may errback with L{RequestGenerationFailed} if the request was not fully written to the transport due to a local error. It may errback with L{RequestTransmissionFailed} if it was not fully written to the transport due to a network error. It may errback with L{ResponseFailed} if the request was sent (not necessarily received) but some or all of the response was lost. It may errback with L{RequestNotSent} if it is not possible to send any more requests using this L{HTTP11ClientProtocol}. """ if self._state != 'QUIESCENT': return fail(RequestNotSent()) self._state = 'TRANSMITTING' _requestDeferred = maybeDeferred(request.writeTo, self.transport) def cancelRequest(ign): # Explicitly cancel the request's deferred if it's still trying to # write when this request is cancelled. if self._state in ( 'TRANSMITTING', 'TRANSMITTING_AFTER_RECEIVING_RESPONSE'): _requestDeferred.cancel() else: self.transport.abortConnection() self._disconnectParser(Failure(CancelledError())) self._finishedRequest = Deferred(cancelRequest) # Keep track of the Request object in case we need to call stopWriting # on it. self._currentRequest = request self._transportProxy = TransportProxyProducer(self.transport) self._parser = HTTPClientParser(request, self._finishResponse) self._parser.makeConnection(self._transportProxy) self._responseDeferred = self._parser._responseDeferred def cbRequestWrotten(ignored): if self._state == 'TRANSMITTING': self._state = 'WAITING' self._responseDeferred.chainDeferred(self._finishedRequest) def ebRequestWriting(err): if self._state == 'TRANSMITTING': self._state = 'GENERATION_FAILED' self.transport.abortConnection() self._finishedRequest.errback( Failure(RequestGenerationFailed([err]))) else: log.err(err, 'Error writing request, but not in valid state ' 'to finalize request: %s' % self._state) _requestDeferred.addCallbacks(cbRequestWrotten, ebRequestWriting) return self._finishedRequest def _finishResponse(self, rest): """ Called by an L{HTTPClientParser} to indicate that it has parsed a complete response. @param rest: A C{str} giving any trailing bytes which were given to the L{HTTPClientParser} which were not part of the response it was parsing. """ _finishResponse = makeStatefulDispatcher('finishResponse', _finishResponse) def _finishResponse_WAITING(self, rest): # Currently the rest parameter is ignored. Don't forget to use it if # we ever add support for pipelining. And maybe check what trailers # mean. if self._state == 'WAITING': self._state = 'QUIESCENT' else: # The server sent the entire response before we could send the # whole request. That sucks. Oh well. Fire the request() # Deferred with the response. But first, make sure that if the # request does ever finish being written that it won't try to fire # that Deferred. self._state = 'TRANSMITTING_AFTER_RECEIVING_RESPONSE' self._responseDeferred.chainDeferred(self._finishedRequest) # This will happen if we're being called due to connection being lost; # if so, no need to disconnect parser again, or to call # _quiescentCallback. if self._parser is None: return reason = ConnectionDone("synthetic!") connHeaders = self._parser.connHeaders.getRawHeaders('connection', ()) if (('close' in connHeaders) or self._state != "QUIESCENT" or not self._currentRequest.persistent): self._giveUp(Failure(reason)) else: # We call the quiescent callback first, to ensure connection gets # added back to connection pool before we finish the request. try: self._quiescentCallback(self) except: # If callback throws exception, just log it and disconnect; # keeping persistent connections around is an optimisation: log.err() self.transport.loseConnection() self._disconnectParser(reason) _finishResponse_TRANSMITTING = _finishResponse_WAITING def _disconnectParser(self, reason): """ If there is still a parser, call its C{connectionLost} method with the given reason. If there is not, do nothing. @type reason: L{Failure} """ if self._parser is not None: parser = self._parser self._parser = None self._currentRequest = None self._finishedRequest = None self._responseDeferred = None # The parser is no longer allowed to do anything to the real # transport. Stop proxying from the parser's transport to the real # transport before telling the parser it's done so that it can't do # anything. self._transportProxy._stopProxying() self._transportProxy = None parser.connectionLost(reason) def _giveUp(self, reason): """ Lose the underlying connection and disconnect the parser with the given L{Failure}. Use this method instead of calling the transport's loseConnection method directly otherwise random things will break. """ self.transport.loseConnection() self._disconnectParser(reason) def dataReceived(self, bytes): """ Handle some stuff from some place. """ try: self._parser.dataReceived(bytes) except: self._giveUp(Failure()) def connectionLost(self, reason): """ The underlying transport went away. If appropriate, notify the parser object. """ connectionLost = makeStatefulDispatcher('connectionLost', connectionLost) def _connectionLost_QUIESCENT(self, reason): """ Nothing is currently happening. Move to the C{'CONNECTION_LOST'} state but otherwise do nothing. """ self._state = 'CONNECTION_LOST' def _connectionLost_GENERATION_FAILED(self, reason): """ The connection was in an inconsistent state. Move to the C{'CONNECTION_LOST'} state but otherwise do nothing. """ self._state = 'CONNECTION_LOST' def _connectionLost_TRANSMITTING(self, reason): """ Fail the L{Deferred} for the current request, notify the request object that it does not need to continue transmitting itself, and move to the C{'CONNECTION_LOST'} state. """ self._state = 'CONNECTION_LOST' self._finishedRequest.errback( Failure(RequestTransmissionFailed([reason]))) del self._finishedRequest # Tell the request that it should stop bothering now. self._currentRequest.stopWriting() def _connectionLost_TRANSMITTING_AFTER_RECEIVING_RESPONSE(self, reason): """ Move to the C{'CONNECTION_LOST'} state. """ self._state = 'CONNECTION_LOST' def _connectionLost_WAITING(self, reason): """ Disconnect the response parser so that it can propagate the event as necessary (for example, to call an application protocol's C{connectionLost} method, or to fail a request L{Deferred}) and move to the C{'CONNECTION_LOST'} state. """ self._disconnectParser(reason) self._state = 'CONNECTION_LOST' def _connectionLost_ABORTING(self, reason): """ Disconnect the response parser with a L{ConnectionAborted} failure, and move to the C{'CONNECTION_LOST'} state. """ self._disconnectParser(Failure(ConnectionAborted())) self._state = 'CONNECTION_LOST' for d in self._abortDeferreds: d.callback(None) self._abortDeferreds = [] def abort(self): """ Close the connection and cause all outstanding L{request} L{Deferred}s to fire with an error. """ if self._state == "CONNECTION_LOST": return succeed(None) self.transport.loseConnection() self._state = 'ABORTING' d = Deferred() self._abortDeferreds.append(d) return d
bsd-3-clause
-1,537,035,971,554,219,800
35.503298
92
0.622671
false
Changaco/oh-mainline
vendor/packages/Django/django/contrib/formtools/tests/wizard/forms.py
90
7721
from __future__ import unicode_literals from django import forms, http from django.conf import settings from django.db import models from django.test import TestCase from django.template.response import TemplateResponse from django.utils.importlib import import_module from django.contrib.auth.models import User from django.contrib.formtools.wizard.views import (WizardView, SessionWizardView, CookieWizardView) class DummyRequest(http.HttpRequest): def __init__(self, POST=None): super(DummyRequest, self).__init__() self.method = POST and "POST" or "GET" if POST is not None: self.POST.update(POST) self.session = {} self._dont_enforce_csrf_checks = True def get_request(*args, **kwargs): request = DummyRequest(*args, **kwargs) engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore(None) return request class Step1(forms.Form): name = forms.CharField() class Step2(forms.Form): name = forms.CharField() class Step3(forms.Form): data = forms.CharField() class CustomKwargsStep1(Step1): def __init__(self, test=None, *args, **kwargs): self.test = test return super(CustomKwargsStep1, self).__init__(*args, **kwargs) class TestModel(models.Model): name = models.CharField(max_length=100) class Meta: app_label = 'formtools' class TestModelForm(forms.ModelForm): class Meta: model = TestModel TestModelFormSet = forms.models.modelformset_factory(TestModel, form=TestModelForm, extra=2) class TestWizard(WizardView): storage_name = 'django.contrib.formtools.wizard.storage.session.SessionStorage' def dispatch(self, request, *args, **kwargs): response = super(TestWizard, self).dispatch(request, *args, **kwargs) return response, self def get_form_kwargs(self, step, *args, **kwargs): kwargs = super(TestWizard, self).get_form_kwargs(step, *args, **kwargs) if step == 'kwargs_test': kwargs['test'] = True return kwargs class FormTests(TestCase): def test_form_init(self): testform = TestWizard.get_initkwargs([Step1, Step2]) self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2}) testform = TestWizard.get_initkwargs([('start', Step1), ('step2', Step2)]) self.assertEqual( testform['form_list'], {'start': Step1, 'step2': Step2}) testform = TestWizard.get_initkwargs([Step1, Step2, ('finish', Step3)]) self.assertEqual( testform['form_list'], {'0': Step1, '1': Step2, 'finish': Step3}) def test_first_step(self): request = get_request() testform = TestWizard.as_view([Step1, Step2]) response, instance = testform(request) self.assertEqual(instance.steps.current, '0') testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) response, instance = testform(request) self.assertEqual(instance.steps.current, 'start') def test_persistence(self): testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) request = get_request({'test_wizard-current_step': 'start', 'name': 'data1'}) response, instance = testform(request) self.assertEqual(instance.steps.current, 'start') instance.storage.current_step = 'step2' testform2 = TestWizard.as_view([('start', Step1), ('step2', Step2)]) request.POST = {'test_wizard-current_step': 'step2'} response, instance = testform2(request) self.assertEqual(instance.steps.current, 'step2') def test_form_condition(self): request = get_request() testform = TestWizard.as_view( [('start', Step1), ('step2', Step2), ('step3', Step3)], condition_dict={'step2': True}) response, instance = testform(request) self.assertEqual(instance.get_next_step(), 'step2') testform = TestWizard.as_view( [('start', Step1), ('step2', Step2), ('step3', Step3)], condition_dict={'step2': False}) response, instance = testform(request) self.assertEqual(instance.get_next_step(), 'step3') def test_form_kwargs(self): request = get_request() testform = TestWizard.as_view([('start', Step1), ('kwargs_test', CustomKwargsStep1)]) response, instance = testform(request) self.assertEqual(instance.get_form_kwargs('start'), {}) self.assertEqual(instance.get_form_kwargs('kwargs_test'), {'test': True}) self.assertEqual(instance.get_form('kwargs_test').test, True) def test_form_prefix(self): request = get_request() testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) response, instance = testform(request) self.assertEqual(instance.get_form_prefix(), 'start') self.assertEqual(instance.get_form_prefix('another'), 'another') def test_form_initial(self): request = get_request() testform = TestWizard.as_view([('start', Step1), ('step2', Step2)], initial_dict={'start': {'name': 'value1'}}) response, instance = testform(request) self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'}) self.assertEqual(instance.get_form_initial('step2'), {}) def test_form_instance(self): request = get_request() the_instance = TestModel() testform = TestWizard.as_view([('start', TestModelForm), ('step2', Step2)], instance_dict={'start': the_instance}) response, instance = testform(request) self.assertEqual( instance.get_form_instance('start'), the_instance) self.assertEqual( instance.get_form_instance('non_exist_instance'), None) def test_formset_instance(self): request = get_request() the_instance1, created = TestModel.objects.get_or_create( name='test object 1') the_instance2, created = TestModel.objects.get_or_create( name='test object 2') testform = TestWizard.as_view([('start', TestModelFormSet), ('step2', Step2)], instance_dict={'start': TestModel.objects.filter(name='test object 1')}) response, instance = testform(request) self.assertEqual(list(instance.get_form_instance('start')), [the_instance1]) self.assertEqual(instance.get_form_instance('non_exist_instance'), None) self.assertEqual(instance.get_form().initial_form_count(), 1) def test_done(self): request = get_request() testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) response, instance = testform(request) self.assertRaises(NotImplementedError, instance.done, None) def test_revalidation(self): request = get_request() testform = TestWizard.as_view([('start', Step1), ('step2', Step2)]) response, instance = testform(request) instance.render_done(None) self.assertEqual(instance.storage.current_step, 'start') class SessionFormTests(TestCase): def test_init(self): request = get_request() testform = SessionWizardView.as_view([('start', Step1)]) self.assertTrue(isinstance(testform(request), TemplateResponse)) class CookieFormTests(TestCase): def test_init(self): request = get_request() testform = CookieWizardView.as_view([('start', Step1)]) self.assertTrue(isinstance(testform(request), TemplateResponse))
agpl-3.0
4,668,045,561,474,885,000
33.779279
92
0.626344
false
prodromou87/gem5
src/mem/ruby/network/BasicRouter.py
53
1825
# Copyright (c) 2011 Advanced Micro Devices, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Steve Reinhardt # Brad Beckmann from m5.params import * from ClockedObject import ClockedObject class BasicRouter(ClockedObject): type = 'BasicRouter' cxx_header = "mem/ruby/network/BasicRouter.hh" router_id = Param.Int("ID in relation to other routers")
bsd-3-clause
-5,291,621,779,156,777,000
49.694444
72
0.783562
false
cmunk/protwis
build/management/commands/find_protein_templates.py
3
5163
from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.db import connection from build.management.commands.base_build import Command as BaseBuild from protein.models import (Protein, ProteinConformation, ProteinSequenceType, ProteinSegment, ProteinConformationTemplateStructure) from structure.models import Structure from common.alignment import Alignment from cProfile import Profile class Command(BaseBuild): help = 'Goes though all protein records and finds the best structural templates for the whole 7TM domain, and ' \ + 'each helix individually' def add_arguments(self, parser): parser.add_argument('-p', '--proc', type=int, action='store', dest='proc', default=1, help='Number of processes to run') parser.add_argument('-r', '--profile', action='store_true', dest='profile', default=False, help='Profile the script with cProfile') # segments segments = ProteinSegment.objects.filter(slug__in=settings.REFERENCE_POSITIONS) # fetch representative (inactive) structures FIXME add active structure?? structures = Structure.objects.filter(representative=True, protein_conformation__state__slug=settings.DEFAULT_PROTEIN_STATE).prefetch_related( 'protein_conformation__protein__parent__family') # fetch all protein conformations pconfs = ProteinConformation.objects.all().prefetch_related('protein__family', 'template_structure') def handle(self, *args, **options): # run with profiling if options['profile']: profiler = Profile() profiler.runcall(self._handle, *args, **options) profiler.print_stats() # run without profiling else: self._handle(*args, **options) def _handle(self, *args, **options): try: self.logger.info('ASSIGNING STRUCTURE TEMPLATES FOR PROTEINS') self.prepare_input(options['proc'], self.pconfs) self.logger.info('COMPLETED ASSIGNING STRUCTURE TEMPLATES FOR PROTEINS') except Exception as msg: print(msg) self.logger.error(msg) def main_func(self, positions, iteration): # pconfs if not positions[1]: pconfs = self.pconfs[positions[0]:] else: pconfs = self.pconfs[positions[0]:positions[1]] # find templates for pconf in pconfs: # filter structure sequence queryset to include only sequences from within the same class pconf_class = pconf.protein.family.slug[:3] class_sps = self.structures.filter( protein_conformation__protein__parent__family__slug__startswith=pconf_class) sps = [] sps_str = [] if class_sps.exists(): for structure in class_sps: sps.append(structure.protein_conformation.protein.parent) # use the wild-type sequence for main tpl sps_str.append(structure.protein_conformation.protein) # use the structure sequence for segment tpl else: for structure in self.structures: sps.append(structure.protein_conformation.protein.parent) sps_str.append(structure.protein_conformation.protein) # overall template = self.find_segment_template(pconf, sps, self.segments) template_structure = self.fetch_template_structure(self.structures, template.protein.entry_name) pconf.template_structure = template_structure pconf.save() self.logger.info("Assigned {} as overall template for {}".format(template_structure, pconf)) # for each segment for segment in self.segments: template = self.find_segment_template(pconf, sps_str, [segment]) template_structure = self.fetch_template_structure(self.structures, template.protein.parent.entry_name) pcts, created = ProteinConformationTemplateStructure.objects.get_or_create(protein_conformation=pconf, protein_segment=segment, defaults={'structure': template_structure}) if pcts.structure != template_structure: pcts.structure = template_structure pcts.save() self.logger.info("Assigned {} as {} template for {}".format(template_structure, segment, pconf)) def find_segment_template(self, pconf, sconfs, segments): a = Alignment() a.load_reference_protein(pconf.protein) a.load_proteins(sconfs) a.load_segments(segments) a.build_alignment() a.calculate_similarity() return a.proteins[1] def fetch_template_structure(self, structures, template_protein): for structure in structures: structure_protein = structure.protein_conformation.protein.parent.entry_name if structure_protein == template_protein: return structure
apache-2.0
9,122,762,605,943,273,000
43.517241
119
0.635871
false
njvack/ge-mri-rtafni
scanner-console/vendor/dicom/filereader.py
4
30365
# filereader.py """Read a dicom media file""" # Copyright (c) 2008-2012 Darcy Mason # This file is part of pydicom, released under a modified MIT license. # See the file license.txt included with this distribution, also # available at http://pydicom.googlecode.com from __future__ import absolute_import # Need zlib and io.BytesIO for deflate-compressed file import os.path import warnings import zlib from io import BytesIO import logging from dicom.tag import TupleTag from dicom.dataelem import RawDataElement from dicom.util.hexutil import bytes2hex from dicom.valuerep import extra_length_VRs from dicom.charset import default_encoding, convert_encodings from dicom import in_py3 logger = logging.getLogger('pydicom') stat_available = True try: from os import stat except: stat_available = False from os import SEEK_CUR import dicom.UID # for Implicit/Explicit/Little/Big Endian transfer syntax UIDs from dicom.filebase import DicomFile, DicomFileLike from dicom.filebase import DicomIO, DicomBytesIO from dicom.dataset import Dataset, FileDataset from dicom.datadict import dictionaryVR from dicom.dataelem import DataElement, DeferredDataElement from dicom.tag import Tag, ItemTag, ItemDelimiterTag, SequenceDelimiterTag from dicom.sequence import Sequence from dicom.misc import size_in_bytes from dicom.fileutil import absorb_delimiter_item, read_undefined_length_value from dicom.fileutil import length_of_undefined_length from struct import Struct, unpack from sys import byteorder sys_is_little_endian = (byteorder == 'little') class InvalidDicomError(Exception): """Exception that is raised when the the file does not seem to be a valid dicom file. This is the case when the four characters "DICM" are not present at position 128 in the file. (According to the dicom specification, each dicom file should have this.) To force reading the file (because maybe it is a dicom file without a header), use read_file(..., force=True). """ def __init__(self, *args): if not args: args = ('The specified file is not a valid DICOM file.',) Exception.__init__(self, *args) class DicomIter(object): """Iterator over DICOM data elements created from a file-like object """ def __init__(self, fp, stop_when=None, force=False): """Read the preamble and meta info, prepare iterator for remainder fp -- an open DicomFileLike object, at start of file Adds flags to fp: Big/Little-endian and Implicit/Explicit VR """ self.fp = fp self.stop_when = stop_when self.preamble = preamble = read_preamble(fp, force) self.has_header = has_header = (preamble is not None) self.file_meta_info = Dataset() if has_header: self.file_meta_info = file_meta_info = _read_file_meta_info(fp) transfer_syntax = file_meta_info.TransferSyntaxUID if transfer_syntax == dicom.UID.ExplicitVRLittleEndian: self._is_implicit_VR = False self._is_little_endian = True elif transfer_syntax == dicom.UID.ImplicitVRLittleEndian: self._is_implicit_VR = True self._is_little_endian = True elif transfer_syntax == dicom.UID.ExplicitVRBigEndian: self._is_implicit_VR = False self._is_little_endian = False elif transfer_syntax == dicom.UID.DeflatedExplicitVRLittleEndian: # See PS3.6-2008 A.5 (p 71) -- when written, the entire dataset # following the file metadata was prepared the normal way, # then "deflate" compression applied. # All that is needed here is to decompress and then # use as normal in a file-like object zipped = fp.read() # -MAX_WBITS part is from comp.lang.python answer: # groups.google.com/group/comp.lang.python/msg/e95b3b38a71e6799 unzipped = zlib.decompress(zipped, -zlib.MAX_WBITS) fp = BytesIO(unzipped) # a file-like object self.fp = fp # point to new object self._is_implicit_VR = False self._is_little_endian = True else: # Any other syntax should be Explicit VR Little Endian, # e.g. all Encapsulated (JPEG etc) are ExplVR-LE # by Standard PS 3.5-2008 A.4 (p63) self._is_implicit_VR = False self._is_little_endian = True else: # no header -- make assumptions fp.TransferSyntaxUID = dicom.UID.ImplicitVRLittleEndian self._is_little_endian = True self._is_implicit_VR = True impl_expl = ("Explicit", "Implicit")[self._is_implicit_VR] big_little = ("Big", "Little")[self._is_little_endian] logger.debug("Using {0:s} VR, {1:s} Endian transfer syntax".format( impl_expl, big_little)) def __iter__(self): tags = sorted(self.file_meta_info.keys()) for tag in tags: yield self.file_meta_info[tag] for data_element in data_element_generator(self.fp, self._is_implicit_VR, self._is_little_endian, stop_when=self.stop_when): yield data_element def data_element_generator(fp, is_implicit_VR, is_little_endian, stop_when=None, defer_size=None, encoding=default_encoding): """Create a generator to efficiently return the raw data elements Returns (VR, length, raw_bytes, value_tell, is_little_endian), where: VR -- None if implicit VR, otherwise the VR read from the file length -- the length as in the DICOM data element (could be DICOM "undefined length" 0xffffffffL), value_bytes -- the raw bytes from the DICOM file (not parsed into python types) is_little_endian -- True if transfer syntax is little endian; else False """ # Summary of DICOM standard PS3.5-2008 chapter 7: # If Implicit VR, data element is: # tag, 4-byte length, value. # The 4-byte length can be FFFFFFFF (undefined length)* # If Explicit VR: # if OB, OW, OF, SQ, UN, or UT: # tag, VR, 2-bytes reserved (both zero), 4-byte length, value # For all but UT, the length can be FFFFFFFF (undefined length)* # else: (any other VR) # tag, VR, (2 byte length), value # * for undefined length, a Sequence Delimitation Item marks the end # of the Value Field. # Note, except for the special_VRs, both impl and expl VR use 8 bytes; # the special VRs follow the 8 bytes with a 4-byte length # With a generator, state is stored, so we can break down # into the individual cases, and not have to check them again for each # data element if is_little_endian: endian_chr = "<" else: endian_chr = ">" if is_implicit_VR: element_struct = Struct(endian_chr + "HHL") else: # Explicit VR # tag, VR, 2-byte length (or 0 if special VRs) element_struct = Struct(endian_chr + "HH2sH") extra_length_struct = Struct(endian_chr + "L") # for special VRs extra_length_unpack = extra_length_struct.unpack # for lookup speed # Make local variables so have faster lookup fp_read = fp.read fp_tell = fp.tell logger_debug = logger.debug debugging = dicom.debugging element_struct_unpack = element_struct.unpack while True: # Read tag, VR, length, get ready to read value bytes_read = fp_read(8) if len(bytes_read) < 8: raise StopIteration # at end of file if debugging: debug_msg = "{0:08x}: {1}".format(fp.tell() - 8, bytes2hex(bytes_read)) if is_implicit_VR: # must reset VR each time; could have set last iteration (e.g. SQ) VR = None group, elem, length = element_struct_unpack(bytes_read) else: # explicit VR group, elem, VR, length = element_struct_unpack(bytes_read) if in_py3: VR = VR.decode(default_encoding) if VR in extra_length_VRs: bytes_read = fp_read(4) length = extra_length_unpack(bytes_read)[0] if debugging: debug_msg += " " + bytes2hex(bytes_read) if debugging: debug_msg = "%-47s (%04x, %04x)" % (debug_msg, group, elem) if not is_implicit_VR: debug_msg += " %s " % VR if length != 0xFFFFFFFFL: debug_msg += "Length: %d" % length else: debug_msg += "Length: Undefined length (FFFFFFFF)" logger_debug(debug_msg) # Positioned to read the value, but may not want to -- check stop_when value_tell = fp_tell() tag = TupleTag((group, elem)) if stop_when is not None: # XXX VR may be None here!! Should stop_when just take tag? if stop_when(tag, VR, length): if debugging: logger_debug("Reading ended by stop_when callback. " "Rewinding to start of data element.") rewind_length = 8 if not is_implicit_VR and VR in extra_length_VRs: rewind_length += 4 fp.seek(value_tell - rewind_length) raise StopIteration # Reading the value # First case (most common): reading a value with a defined length if length != 0xFFFFFFFFL: if defer_size is not None and length > defer_size: # Flag as deferred by setting value to None, and skip bytes value = None logger_debug("Defer size exceeded." "Skipping forward to next data element.") fp.seek(fp_tell() + length) else: value = fp_read(length) if debugging: dotdot = " " if length > 12: dotdot = "..." logger_debug("%08x: %-34s %s %r %s" % (value_tell, bytes2hex(value[:12]), dotdot, value[:12], dotdot)) # If the tag is (0008,0005) Specific Character Set, then store it if tag == (0x08, 0x05): from dicom.values import convert_string encoding = convert_string(value, is_little_endian, encoding=default_encoding) # Store the encoding value in the generator for use with future elements (SQs) encoding = convert_encodings(encoding) yield RawDataElement(tag, VR, length, value, value_tell, is_implicit_VR, is_little_endian) # Second case: undefined length - must seek to delimiter, # unless is SQ type, in which case is easier to parse it, because # undefined length SQs and items of undefined lengths can be nested # and it would be error-prone to read to the correct outer delimiter else: # Try to look up type to see if is a SQ # if private tag, won't be able to look it up in dictionary, # in which case just ignore it and read the bytes unless it is # identified as a Sequence if VR is None: try: VR = dictionaryVR(tag) except KeyError: # Look ahead to see if it consists of items and is thus a SQ next_tag = TupleTag(unpack(endian_chr + "HH", fp_read(4))) # Rewind the file fp.seek(fp_tell() - 4) if next_tag == ItemTag: VR = 'SQ' if VR == 'SQ': if debugging: msg = "{0:08x}: Reading/parsing undefined length sequence" logger_debug(msg.format(fp_tell())) seq = read_sequence(fp, is_implicit_VR, is_little_endian, length, encoding) yield DataElement(tag, VR, seq, value_tell, is_undefined_length=True) else: delimiter = SequenceDelimiterTag if debugging: logger_debug("Reading undefined length data element") value = read_undefined_length_value(fp, is_little_endian, delimiter, defer_size) # If the tag is (0008,0005) Specific Character Set, then store it if tag == (0x08, 0x05): from dicom.values import convert_string encoding = convert_string(value, is_little_endian, encoding=default_encoding) # Store the encoding value in the generator for use with future elements (SQs) encoding = convert_encodings(encoding) yield RawDataElement(tag, VR, length, value, value_tell, is_implicit_VR, is_little_endian) def read_dataset(fp, is_implicit_VR, is_little_endian, bytelength=None, stop_when=None, defer_size=None, parent_encoding=default_encoding): """Return a Dataset instance containing the next dataset in the file. :param fp: an opened file object :param is_implicit_VR: True if file transfer syntax is implicit VR :param is_little_endian: True if file has little endian transfer syntax :param bytelength: None to read until end of file or ItemDeliterTag, else a fixed number of bytes to read :param stop_when: optional call_back function which can terminate reading. See help for data_element_generator for details :param defer_size: optional size to avoid loading large elements in memory. See help for data_element_generator for details :param parent_encoding: optional encoding to use as a default in case a Specific Character Set (0008,0005) isn't specified :returns: a Dataset instance """ raw_data_elements = dict() fpStart = fp.tell() de_gen = data_element_generator(fp, is_implicit_VR, is_little_endian, stop_when, defer_size, parent_encoding) try: while (bytelength is None) or (fp.tell() - fpStart < bytelength): raw_data_element = next(de_gen) # Read data elements. Stop on some errors, but return what was read tag = raw_data_element.tag # Check for ItemDelimiterTag --dataset is an item in a sequence if tag == (0xFFFE, 0xE00D): break raw_data_elements[tag] = raw_data_element except StopIteration: pass except EOFError as details: # XXX is this error visible enough to user code with just logging? logger.error(str(details) + " in file " + getattr(fp, "name", "<no filename>")) except NotImplementedError as details: logger.error(details) return Dataset(raw_data_elements) def read_sequence(fp, is_implicit_VR, is_little_endian, bytelength, encoding, offset=0): """Read and return a Sequence -- i.e. a list of Datasets""" seq = [] # use builtin list to start for speed, convert to Sequence at end is_undefined_length = False if bytelength != 0: # SQ of length 0 possible (PS 3.5-2008 7.5.1a (p.40) if bytelength == 0xffffffffL: is_undefined_length = True bytelength = None fp_tell = fp.tell # for speed in loop fpStart = fp_tell() while (not bytelength) or (fp_tell() - fpStart < bytelength): file_tell = fp.tell() dataset = read_sequence_item(fp, is_implicit_VR, is_little_endian, encoding) if dataset is None: # None is returned if hit Sequence Delimiter break dataset.file_tell = file_tell + offset seq.append(dataset) seq = Sequence(seq) seq.is_undefined_length = is_undefined_length return seq def read_sequence_item(fp, is_implicit_VR, is_little_endian, encoding): """Read and return a single sequence item, i.e. a Dataset""" if is_little_endian: tag_length_format = "<HHL" else: tag_length_format = ">HHL" try: bytes_read = fp.read(8) group, element, length = unpack(tag_length_format, bytes_read) except: raise IOError("No tag to read at file position " "{0:05x}".format(fp.tell())) tag = (group, element) if tag == SequenceDelimiterTag: # No more items, time to stop reading data_element = DataElement(tag, None, None, fp.tell() - 4) logger.debug("{0:08x}: {1}".format(fp.tell() - 8, "End of Sequence")) if length != 0: logger.warning("Expected 0x00000000 after delimiter, found 0x%x," " at position 0x%x" % (length, fp.tell() - 4)) return None if tag != ItemTag: logger.warning("Expected sequence item with tag %s at file position " "0x%x" % (ItemTag, fp.tell() - 4)) else: logger.debug("{0:08x}: {1} Found Item tag (start of item)".format( fp.tell() - 4, bytes2hex(bytes_read))) is_undefined_length = False if length == 0xFFFFFFFFL: ds = read_dataset(fp, is_implicit_VR, is_little_endian, bytelength=None, parent_encoding=encoding) ds.is_undefined_length_sequence_item = True else: ds = read_dataset(fp, is_implicit_VR, is_little_endian, length, parent_encoding=encoding) logger.debug("%08x: Finished sequence item" % fp.tell()) return ds def not_group2(tag, VR, length): return (tag.group != 2) def _read_file_meta_info(fp): """Return the file meta information. fp must be set after the 128 byte preamble and 'DICM' marker """ # File meta info always LittleEndian, Explicit VR. After will change these # to the transfer syntax values set in the meta info # Get group length data element, whose value is the length of the meta_info fp_save = fp.tell() # in case need to rewind debugging = dicom.debugging if debugging: logger.debug("Try to read group length info...") bytes_read = fp.read(8) group, elem, VR, length = unpack("<HH2sH", bytes_read) if debugging: debug_msg = "{0:08x}: {1}".format(fp.tell() - 8, bytes2hex(bytes_read)) if in_py3: VR = VR.decode(default_encoding) if VR in extra_length_VRs: bytes_read = fp.read(4) length = unpack("<L", bytes_read)[0] if debugging: debug_msg += " " + bytes2hex(bytes_read) if debugging: debug_msg = "{0:<47s} ({1:04x}, {2:04x}) {3:2s} Length: {4:d}".format( debug_msg, group, elem, VR, length) logger.debug(debug_msg) # Store meta group length if it exists, then read until not group 2 if group == 2 and elem == 0: bytes_read = fp.read(length) if debugging: logger.debug("{0:08x}: {1}".format(fp.tell() - length, bytes2hex(bytes_read))) group_length = unpack("<L", bytes_read)[0] expected_ds_start = fp.tell() + group_length if debugging: msg = "value (group length) = {0:d}".format(group_length) msg += " regular dataset should start at {0:08x}".format( expected_ds_start) logger.debug(" " * 10 + msg) else: expected_ds_start = None if debugging: logger.debug(" " * 10 + "(0002,0000) Group length not found.") # Changed in pydicom 0.9.7 -- don't trust the group length, just read # until no longer group 2 data elements. But check the length and # give a warning if group 2 ends at different location. # Rewind to read the first data element as part of the file_meta dataset if debugging: logger.debug("Rewinding and reading whole dataset " "including this first data element") fp.seek(fp_save) file_meta = read_dataset(fp, is_implicit_VR=False, is_little_endian=True, stop_when=not_group2) fp_now = fp.tell() if expected_ds_start and fp_now != expected_ds_start: logger.info("*** Group length for file meta dataset " "did not match end of group 2 data ***") else: if debugging: logger.debug("--- End of file meta data found " "as expected ---------") return file_meta def read_file_meta_info(filename): """Read and return the DICOM file meta information only. This function is meant to be used in user code, for quickly going through a series of files to find one which is referenced to a particular SOP, without having to read the entire files. """ fp = DicomFile(filename, 'rb') preamble = read_preamble(fp, False) # if no header, raise exception return _read_file_meta_info(fp) def read_preamble(fp, force): """Read and return the DICOM preamble and read past the 'DICM' marker. If 'DICM' does not exist, assume no preamble, return None, and rewind file to the beginning.. """ logger.debug("Reading preamble...") preamble = fp.read(0x80) if dicom.debugging: sample = bytes2hex(preamble[:8]) + "..." + bytes2hex(preamble[-8:]) logger.debug("{0:08x}: {1}".format(fp.tell() - 0x80, sample)) magic = fp.read(4) if magic != b"DICM": if force: logger.info("File is not a standard DICOM file; 'DICM' header is " "missing. Assuming no header and continuing") preamble = None fp.seek(0) else: raise InvalidDicomError("File is missing 'DICM' marker. " "Use force=True to force reading") else: logger.debug("{0:08x}: 'DICM' marker found".format(fp.tell() - 4)) return preamble def _at_pixel_data(tag, VR, length): return tag == (0x7fe0, 0x0010) def read_partial(fileobj, stop_when=None, defer_size=None, force=False): """Parse a DICOM file until a condition is met ``read_partial`` is normally not called directly. Use ``read_file`` instead, unless you need to stop on some condition other than reaching pixel data. :arg fileobj: a file-like object. This function does not close it. :arg stop_when: a callable which takes tag, VR, length, and returns True or False. If stop_when returns True, read_data_element will raise StopIteration. If None (default), then the whole file is read. :returns: a set instance """ # Read preamble -- raise an exception if missing and force=False preamble = read_preamble(fileobj, force) file_meta_dataset = Dataset() # Assume a transfer syntax, correct it as necessary is_implicit_VR = True is_little_endian = True if preamble: file_meta_dataset = _read_file_meta_info(fileobj) transfer_syntax = file_meta_dataset.TransferSyntaxUID if transfer_syntax == dicom.UID.ImplicitVRLittleEndian: pass elif transfer_syntax == dicom.UID.ExplicitVRLittleEndian: is_implicit_VR = False elif transfer_syntax == dicom.UID.ExplicitVRBigEndian: is_implicit_VR = False is_little_endian = False elif transfer_syntax == dicom.UID.DeflatedExplicitVRLittleEndian: # See PS3.6-2008 A.5 (p 71) # when written, the entire dataset following # the file metadata was prepared the normal way, # then "deflate" compression applied. # All that is needed here is to decompress and then # use as normal in a file-like object zipped = fileobj.read() # -MAX_WBITS part is from comp.lang.python answer: # groups.google.com/group/comp.lang.python/msg/e95b3b38a71e6799 unzipped = zlib.decompress(zipped, -zlib.MAX_WBITS) fileobj = BytesIO(unzipped) # a file-like object is_implicit_VR = False else: # Any other syntax should be Explicit VR Little Endian, # e.g. all Encapsulated (JPEG etc) are ExplVR-LE # by Standard PS 3.5-2008 A.4 (p63) is_implicit_VR = False else: # no header -- use the is_little_endian, implicit assumptions file_meta_dataset.TransferSyntaxUID = dicom.UID.ImplicitVRLittleEndian try: dataset = read_dataset(fileobj, is_implicit_VR, is_little_endian, stop_when=stop_when, defer_size=defer_size) except EOFError as e: pass # error already logged in read_dataset return FileDataset(fileobj, dataset, preamble, file_meta_dataset, is_implicit_VR, is_little_endian) def read_file(fp, defer_size=None, stop_before_pixels=False, force=False): """Read and parse a DICOM file :param fp: either a file-like object, or a string containing the file name. If a file-like object, the caller is responsible for closing it. :param defer_size: if a data element value is larger than defer_size, then the value is not read into memory until it is accessed in code. Specify an integer (bytes), or a string value with units: e.g. "512 KB", "2 MB". Default None means all elements read into memory. :param stop_before_pixels: Set True to stop before reading pixels (and anything after them). If False (default), the full file will be read and parsed. :param force: Set to True to force reading even if no header is found. If False, a dicom.filereader.InvalidDicomError is raised when the file is not valid DICOM. :returns: a FileDataset instance """ # Open file if not already a file object caller_owns_file = True if isinstance(fp, basestring): # caller provided a file name; we own the file handle caller_owns_file = False logger.debug("Reading file '{0}'".format(fp)) fp = open(fp, 'rb') if dicom.debugging: logger.debug("\n" + "-" * 80) logger.debug("Call to read_file()") msg = ("filename:'%s', defer_size='%s'" ", stop_before_pixels=%s, force=%s") logger.debug(msg % (fp.name, defer_size, stop_before_pixels, force)) if caller_owns_file: logger.debug("Caller passed file object") else: logger.debug("Caller passed file name") logger.debug("-" * 80) # Convert size to defer reading into bytes, and store in file object # if defer_size is not None: # defer_size = size_in_bytes(defer_size) # fp.defer_size = defer_size # Iterate through all items and store them --include file meta if present stop_when = None if stop_before_pixels: stop_when = _at_pixel_data try: dataset = read_partial(fp, stop_when, defer_size=defer_size, force=force) finally: if not caller_owns_file: fp.close() # XXX need to store transfer syntax etc. return dataset def data_element_offset_to_value(is_implicit_VR, VR): """Return number of bytes from start of data element to start of value""" if is_implicit_VR: offset = 8 # tag of 4 plus 4-byte length else: if VR in extra_length_VRs: offset = 12 # tag 4 + 2 VR + 2 reserved + 4 length else: offset = 8 # tag 4 + 2 VR + 2 length return offset def read_deferred_data_element(fileobj_type, filename, timestamp, raw_data_elem): """Read the previously deferred value from the file into memory and return a raw data element""" logger.debug("Reading deferred element %r" % str(raw_data_elem.tag)) # If it wasn't read from a file, then return an error if filename is None: raise IOError("Deferred read -- original filename not stored. " "Cannot re-open") # Check that the file is the same as when originally read if not os.path.exists(filename): raise IOError("Deferred read -- original file " "{0:s} is missing".format(filename)) if stat_available and (timestamp is not None): statinfo = stat(filename) if statinfo.st_mtime != timestamp: warnings.warn("Deferred read warning -- file modification time " "has changed.") # Open the file, position to the right place # fp = self.typefileobj(self.filename, "rb") fp = fileobj_type(filename, 'rb') is_implicit_VR = raw_data_elem.is_implicit_VR is_little_endian = raw_data_elem.is_little_endian offset = data_element_offset_to_value(is_implicit_VR, raw_data_elem.VR) fp.seek(raw_data_elem.value_tell - offset) elem_gen = data_element_generator(fp, is_implicit_VR, is_little_endian, defer_size=None) # Read the data element and check matches what was stored before data_elem = next(elem_gen) fp.close() if data_elem.VR != raw_data_elem.VR: raise ValueError("Deferred read VR {0:s} does not match " "original {1:s}".format(data_elem.VR, raw_data_elem.VR)) if data_elem.tag != raw_data_elem.tag: raise ValueError("Deferred read tag {0!r} does not match " "original {1!r}".format(data_elem.tag, raw_data_elem.tag)) # Everything is ok, now this object should act like usual DataElement return data_elem
mit
-4,455,271,611,898,587,600
43.328467
98
0.592195
false
jctanner/ansible
test/support/integration/plugins/modules/mongodb_parameter.py
49
6737
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Loic Blot <loic.blot@unix-experience.fr> # Sponsored by Infopro Digital. http://www.infopro-digital.com/ # Sponsored by E.T.A.I. http://www.etai.fr/ # # 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 = r''' --- module: mongodb_parameter short_description: Change an administrative parameter on a MongoDB server description: - Change an administrative parameter on a MongoDB server. version_added: "2.1" options: login_user: description: - The MongoDB username used to authenticate with. type: str login_password: description: - The login user's password used to authenticate with. type: str login_host: description: - The host running the database. type: str default: localhost login_port: description: - The MongoDB port to connect to. default: 27017 type: int login_database: description: - The database where login credentials are stored. type: str replica_set: description: - Replica set to connect to (automatically connects to primary for writes). type: str ssl: description: - Whether to use an SSL connection when connecting to the database. type: bool default: no param: description: - MongoDB administrative parameter to modify. type: str required: true value: description: - MongoDB administrative parameter value to set. type: str required: true param_type: description: - Define the type of parameter value. default: str type: str choices: [int, str] notes: - Requires the pymongo Python package on the remote host, version 2.4.2+. - This can be installed using pip or the OS package manager. - See also U(http://api.mongodb.org/python/current/installation.html) requirements: [ "pymongo" ] author: "Loic Blot (@nerzhul)" ''' EXAMPLES = r''' - name: Set MongoDB syncdelay to 60 (this is an int) mongodb_parameter: param: syncdelay value: 60 param_type: int ''' RETURN = r''' before: description: value before modification returned: success type: str after: description: value after modification returned: success type: str ''' import os import traceback try: from pymongo.errors import ConnectionFailure from pymongo.errors import OperationFailure from pymongo import version as PyMongoVersion from pymongo import MongoClient except ImportError: try: # for older PyMongo 2.2 from pymongo import Connection as MongoClient except ImportError: pymongo_found = False else: pymongo_found = True else: pymongo_found = True from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.six.moves import configparser from ansible.module_utils._text import to_native # ========================================= # MongoDB module specific support methods. # def load_mongocnf(): config = configparser.RawConfigParser() mongocnf = os.path.expanduser('~/.mongodb.cnf') try: config.readfp(open(mongocnf)) creds = dict( user=config.get('client', 'user'), password=config.get('client', 'pass') ) except (configparser.NoOptionError, IOError): return False return creds # ========================================= # Module execution. # def main(): module = AnsibleModule( argument_spec=dict( login_user=dict(default=None), login_password=dict(default=None, no_log=True), login_host=dict(default='localhost'), login_port=dict(default=27017, type='int'), login_database=dict(default=None), replica_set=dict(default=None), param=dict(required=True), value=dict(required=True), param_type=dict(default="str", choices=['str', 'int']), ssl=dict(default=False, type='bool'), ) ) if not pymongo_found: module.fail_json(msg=missing_required_lib('pymongo')) login_user = module.params['login_user'] login_password = module.params['login_password'] login_host = module.params['login_host'] login_port = module.params['login_port'] login_database = module.params['login_database'] replica_set = module.params['replica_set'] ssl = module.params['ssl'] param = module.params['param'] param_type = module.params['param_type'] value = module.params['value'] # Verify parameter is coherent with specified type try: if param_type == 'int': value = int(value) except ValueError: module.fail_json(msg="value '%s' is not %s" % (value, param_type)) try: if replica_set: client = MongoClient(login_host, int(login_port), replicaset=replica_set, ssl=ssl) else: client = MongoClient(login_host, int(login_port), ssl=ssl) if login_user is None and login_password is None: mongocnf_creds = load_mongocnf() if mongocnf_creds is not False: login_user = mongocnf_creds['user'] login_password = mongocnf_creds['password'] elif login_password is None or login_user is None: module.fail_json(msg='when supplying login arguments, both login_user and login_password must be provided') if login_user is not None and login_password is not None: client.admin.authenticate(login_user, login_password, source=login_database) except ConnectionFailure as e: module.fail_json(msg='unable to connect to database: %s' % to_native(e), exception=traceback.format_exc()) db = client.admin try: after_value = db.command("setParameter", **{param: value}) except OperationFailure as e: module.fail_json(msg="unable to change parameter: %s" % to_native(e), exception=traceback.format_exc()) if "was" not in after_value: module.exit_json(changed=True, msg="Unable to determine old value, assume it changed.") else: module.exit_json(changed=(value != after_value["was"]), before=after_value["was"], after=value) if __name__ == '__main__': main()
gpl-3.0
-2,628,535,095,379,755,000
29.210762
119
0.62179
false
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.3/Lib/bsddb/test/test_thread.py
3
15518
"""TestCases for multi-threaded access to a DB. """ import os import sys import time import errno import shutil import tempfile from pprint import pprint from whrandom import random try: True, False except NameError: True = 1 False = 0 DASH = '-' try: from threading import Thread, currentThread have_threads = True except ImportError: have_threads = False import unittest from test_all import verbose try: # For Python 2.3 from bsddb import db, dbutils except ImportError: # For earlier Pythons w/distutils pybsddb from bsddb3 import db, dbutils #---------------------------------------------------------------------- class BaseThreadedTestCase(unittest.TestCase): dbtype = db.DB_UNKNOWN # must be set in derived class dbopenflags = 0 dbsetflags = 0 envflags = 0 def setUp(self): if verbose: dbutils._deadlock_VerboseFile = sys.stdout homeDir = os.path.join(os.path.dirname(sys.argv[0]), 'db_home') self.homeDir = homeDir try: os.mkdir(homeDir) except OSError, e: if e.errno <> errno.EEXIST: raise self.env = db.DBEnv() self.setEnvOpts() self.env.open(homeDir, self.envflags | db.DB_CREATE) self.filename = self.__class__.__name__ + '.db' self.d = db.DB(self.env) if self.dbsetflags: self.d.set_flags(self.dbsetflags) self.d.open(self.filename, self.dbtype, self.dbopenflags|db.DB_CREATE) def tearDown(self): self.d.close() self.env.close() shutil.rmtree(self.homeDir) def setEnvOpts(self): pass def makeData(self, key): return DASH.join([key] * 5) #---------------------------------------------------------------------- class ConcurrentDataStoreBase(BaseThreadedTestCase): dbopenflags = db.DB_THREAD envflags = db.DB_THREAD | db.DB_INIT_CDB | db.DB_INIT_MPOOL readers = 0 # derived class should set writers = 0 records = 1000 def test01_1WriterMultiReaders(self): if verbose: print '\n', '-=' * 30 print "Running %s.test01_1WriterMultiReaders..." % \ self.__class__.__name__ threads = [] for x in range(self.writers): wt = Thread(target = self.writerThread, args = (self.d, self.records, x), name = 'writer %d' % x, )#verbose = verbose) threads.append(wt) for x in range(self.readers): rt = Thread(target = self.readerThread, args = (self.d, x), name = 'reader %d' % x, )#verbose = verbose) threads.append(rt) for t in threads: t.start() for t in threads: t.join() def writerThread(self, d, howMany, writerNum): #time.sleep(0.01 * writerNum + 0.01) name = currentThread().getName() start = howMany * writerNum stop = howMany * (writerNum + 1) - 1 if verbose: print "%s: creating records %d - %d" % (name, start, stop) for x in range(start, stop): key = '%04d' % x dbutils.DeadlockWrap(d.put, key, self.makeData(key), max_retries=12) if verbose and x % 100 == 0: print "%s: records %d - %d finished" % (name, start, x) if verbose: print "%s: finished creating records" % name ## # Each write-cursor will be exclusive, the only one that can update the DB... ## if verbose: print "%s: deleting a few records" % name ## c = d.cursor(flags = db.DB_WRITECURSOR) ## for x in range(10): ## key = int(random() * howMany) + start ## key = '%04d' % key ## if d.has_key(key): ## c.set(key) ## c.delete() ## c.close() if verbose: print "%s: thread finished" % name def readerThread(self, d, readerNum): time.sleep(0.01 * readerNum) name = currentThread().getName() for loop in range(5): c = d.cursor() count = 0 rec = c.first() while rec: count += 1 key, data = rec self.assertEqual(self.makeData(key), data) rec = c.next() if verbose: print "%s: found %d records" % (name, count) c.close() time.sleep(0.05) if verbose: print "%s: thread finished" % name class BTreeConcurrentDataStore(ConcurrentDataStoreBase): dbtype = db.DB_BTREE writers = 2 readers = 10 records = 1000 class HashConcurrentDataStore(ConcurrentDataStoreBase): dbtype = db.DB_HASH writers = 2 readers = 10 records = 1000 #---------------------------------------------------------------------- class SimpleThreadedBase(BaseThreadedTestCase): dbopenflags = db.DB_THREAD envflags = db.DB_THREAD | db.DB_INIT_MPOOL | db.DB_INIT_LOCK readers = 5 writers = 3 records = 1000 def setEnvOpts(self): self.env.set_lk_detect(db.DB_LOCK_DEFAULT) def test02_SimpleLocks(self): if verbose: print '\n', '-=' * 30 print "Running %s.test02_SimpleLocks..." % self.__class__.__name__ threads = [] for x in range(self.writers): wt = Thread(target = self.writerThread, args = (self.d, self.records, x), name = 'writer %d' % x, )#verbose = verbose) threads.append(wt) for x in range(self.readers): rt = Thread(target = self.readerThread, args = (self.d, x), name = 'reader %d' % x, )#verbose = verbose) threads.append(rt) for t in threads: t.start() for t in threads: t.join() def writerThread(self, d, howMany, writerNum): name = currentThread().getName() start = howMany * writerNum stop = howMany * (writerNum + 1) - 1 if verbose: print "%s: creating records %d - %d" % (name, start, stop) # create a bunch of records for x in xrange(start, stop): key = '%04d' % x dbutils.DeadlockWrap(d.put, key, self.makeData(key), max_retries=12) if verbose and x % 100 == 0: print "%s: records %d - %d finished" % (name, start, x) # do a bit or reading too if random() <= 0.05: for y in xrange(start, x): key = '%04d' % x data = dbutils.DeadlockWrap(d.get, key, max_retries=12) self.assertEqual(data, self.makeData(key)) # flush them try: dbutils.DeadlockWrap(d.sync, max_retries=12) except db.DBIncompleteError, val: if verbose: print "could not complete sync()..." # read them back, deleting a few for x in xrange(start, stop): key = '%04d' % x data = dbutils.DeadlockWrap(d.get, key, max_retries=12) if verbose and x % 100 == 0: print "%s: fetched record (%s, %s)" % (name, key, data) self.assertEqual(data, self.makeData(key)) if random() <= 0.10: dbutils.DeadlockWrap(d.delete, key, max_retries=12) if verbose: print "%s: deleted record %s" % (name, key) if verbose: print "%s: thread finished" % name def readerThread(self, d, readerNum): time.sleep(0.01 * readerNum) name = currentThread().getName() for loop in range(5): c = d.cursor() count = 0 rec = dbutils.DeadlockWrap(c.first, max_retries=10) while rec: count += 1 key, data = rec self.assertEqual(self.makeData(key), data) rec = dbutils.DeadlockWrap(c.next, max_retries=10) if verbose: print "%s: found %d records" % (name, count) c.close() time.sleep(0.05) if verbose: print "%s: thread finished" % name class BTreeSimpleThreaded(SimpleThreadedBase): dbtype = db.DB_BTREE class HashSimpleThreaded(SimpleThreadedBase): dbtype = db.DB_HASH #---------------------------------------------------------------------- class ThreadedTransactionsBase(BaseThreadedTestCase): dbopenflags = db.DB_THREAD | db.DB_AUTO_COMMIT envflags = (db.DB_THREAD | db.DB_INIT_MPOOL | db.DB_INIT_LOCK | db.DB_INIT_LOG | db.DB_INIT_TXN ) readers = 0 writers = 0 records = 2000 txnFlag = 0 def setEnvOpts(self): #self.env.set_lk_detect(db.DB_LOCK_DEFAULT) pass def test03_ThreadedTransactions(self): if verbose: print '\n', '-=' * 30 print "Running %s.test03_ThreadedTransactions..." % \ self.__class__.__name__ threads = [] for x in range(self.writers): wt = Thread(target = self.writerThread, args = (self.d, self.records, x), name = 'writer %d' % x, )#verbose = verbose) threads.append(wt) for x in range(self.readers): rt = Thread(target = self.readerThread, args = (self.d, x), name = 'reader %d' % x, )#verbose = verbose) threads.append(rt) dt = Thread(target = self.deadlockThread) dt.start() for t in threads: t.start() for t in threads: t.join() self.doLockDetect = False dt.join() def doWrite(self, d, name, start, stop): finished = False while not finished: try: txn = self.env.txn_begin(None, self.txnFlag) for x in range(start, stop): key = '%04d' % x d.put(key, self.makeData(key), txn) if verbose and x % 100 == 0: print "%s: records %d - %d finished" % (name, start, x) txn.commit() finished = True except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) txn.abort() time.sleep(0.05) def writerThread(self, d, howMany, writerNum): name = currentThread().getName() start = howMany * writerNum stop = howMany * (writerNum + 1) - 1 if verbose: print "%s: creating records %d - %d" % (name, start, stop) step = 100 for x in range(start, stop, step): self.doWrite(d, name, x, min(stop, x+step)) if verbose: print "%s: finished creating records" % name if verbose: print "%s: deleting a few records" % name finished = False while not finished: try: recs = [] txn = self.env.txn_begin(None, self.txnFlag) for x in range(10): key = int(random() * howMany) + start key = '%04d' % key data = d.get(key, None, txn, db.DB_RMW) if data is not None: d.delete(key, txn) recs.append(key) txn.commit() finished = True if verbose: print "%s: deleted records %s" % (name, recs) except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) txn.abort() time.sleep(0.05) if verbose: print "%s: thread finished" % name def readerThread(self, d, readerNum): time.sleep(0.01 * readerNum + 0.05) name = currentThread().getName() for loop in range(5): finished = False while not finished: try: txn = self.env.txn_begin(None, self.txnFlag) c = d.cursor(txn) count = 0 rec = c.first() while rec: count += 1 key, data = rec self.assertEqual(self.makeData(key), data) rec = c.next() if verbose: print "%s: found %d records" % (name, count) c.close() txn.commit() finished = True except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val: if verbose: print "%s: Aborting transaction (%s)" % (name, val[1]) c.close() txn.abort() time.sleep(0.05) time.sleep(0.05) if verbose: print "%s: thread finished" % name def deadlockThread(self): self.doLockDetect = True while self.doLockDetect: time.sleep(0.5) try: aborted = self.env.lock_detect( db.DB_LOCK_RANDOM, db.DB_LOCK_CONFLICT) if verbose and aborted: print "deadlock: Aborted %d deadlocked transaction(s)" \ % aborted except db.DBError: pass class BTreeThreadedTransactions(ThreadedTransactionsBase): dbtype = db.DB_BTREE writers = 3 readers = 5 records = 2000 class HashThreadedTransactions(ThreadedTransactionsBase): dbtype = db.DB_HASH writers = 1 readers = 5 records = 2000 class BTreeThreadedNoWaitTransactions(ThreadedTransactionsBase): dbtype = db.DB_BTREE writers = 3 readers = 5 records = 2000 txnFlag = db.DB_TXN_NOWAIT class HashThreadedNoWaitTransactions(ThreadedTransactionsBase): dbtype = db.DB_HASH writers = 1 readers = 5 records = 2000 txnFlag = db.DB_TXN_NOWAIT #---------------------------------------------------------------------- def test_suite(): suite = unittest.TestSuite() if have_threads: suite.addTest(unittest.makeSuite(BTreeConcurrentDataStore)) suite.addTest(unittest.makeSuite(HashConcurrentDataStore)) suite.addTest(unittest.makeSuite(BTreeSimpleThreaded)) suite.addTest(unittest.makeSuite(HashSimpleThreaded)) suite.addTest(unittest.makeSuite(BTreeThreadedTransactions)) suite.addTest(unittest.makeSuite(HashThreadedTransactions)) suite.addTest(unittest.makeSuite(BTreeThreadedNoWaitTransactions)) suite.addTest(unittest.makeSuite(HashThreadedNoWaitTransactions)) else: print "Threads not available, skipping thread tests." return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
mit
-1,714,255,267,183,319,300
30.036
88
0.501418
false
vipulkanade/EventbriteDjango
lib/python2.7/site-packages/gunicorn/_compat.py
30
8763
import sys from gunicorn import six PY26 = (sys.version_info[:2] == (2, 6)) PY33 = (sys.version_info >= (3, 3)) def _check_if_pyc(fname): """Return True if the extension is .pyc, False if .py and None if otherwise""" from imp import find_module from os.path import realpath, dirname, basename, splitext # Normalize the file-path for the find_module() filepath = realpath(fname) dirpath = dirname(filepath) module_name = splitext(basename(filepath))[0] # Validate and fetch try: fileobj, fullpath, (_, _, pytype) = find_module(module_name, [dirpath]) except ImportError: raise IOError("Cannot find config file. " "Path maybe incorrect! : {0}".format(filepath)) return pytype, fileobj, fullpath def _get_codeobj(pyfile): """ Returns the code object, given a python file """ from imp import PY_COMPILED, PY_SOURCE result, fileobj, fullpath = _check_if_pyc(pyfile) # WARNING: # fp.read() can blowup if the module is extremely large file. # Lookout for overflow errors. try: data = fileobj.read() finally: fileobj.close() # This is a .pyc file. Treat accordingly. if result is PY_COMPILED: # .pyc format is as follows: # 0 - 4 bytes: Magic number, which changes with each create of .pyc file. # First 2 bytes change with each marshal of .pyc file. Last 2 bytes is "\r\n". # 4 - 8 bytes: Datetime value, when the .py was last changed. # 8 - EOF: Marshalled code object data. # So to get code object, just read the 8th byte onwards till EOF, and # UN-marshal it. import marshal code_obj = marshal.loads(data[8:]) elif result is PY_SOURCE: # This is a .py file. code_obj = compile(data, fullpath, 'exec') else: # Unsupported extension raise Exception("Input file is unknown format: {0}".format(fullpath)) # Return code object return code_obj if six.PY3: def execfile_(fname, *args): if fname.endswith(".pyc"): code = _get_codeobj(fname) else: code = compile(open(fname, 'rb').read(), fname, 'exec') return six.exec_(code, *args) def bytes_to_str(b): if isinstance(b, six.text_type): return b return str(b, 'latin1') import urllib.parse def unquote_to_wsgi_str(string): return _unquote_to_bytes(string).decode('latin-1') _unquote_to_bytes = urllib.parse.unquote_to_bytes else: def execfile_(fname, *args): """ Overriding PY2 execfile() implementation to support .pyc files """ if fname.endswith(".pyc"): return six.exec_(_get_codeobj(fname), *args) return execfile(fname, *args) def bytes_to_str(s): if isinstance(s, unicode): return s.encode('utf-8') return s import urllib unquote_to_wsgi_str = urllib.unquote # The following code adapted from trollius.py33_exceptions def _wrap_error(exc, mapping, key): if key not in mapping: return new_err_cls = mapping[key] new_err = new_err_cls(*exc.args) # raise a new exception with the original traceback if hasattr(exc, '__traceback__'): traceback = exc.__traceback__ else: traceback = sys.exc_info()[2] six.reraise(new_err_cls, new_err, traceback) if PY33: import builtins BlockingIOError = builtins.BlockingIOError BrokenPipeError = builtins.BrokenPipeError ChildProcessError = builtins.ChildProcessError ConnectionRefusedError = builtins.ConnectionRefusedError ConnectionResetError = builtins.ConnectionResetError InterruptedError = builtins.InterruptedError ConnectionAbortedError = builtins.ConnectionAbortedError PermissionError = builtins.PermissionError FileNotFoundError = builtins.FileNotFoundError ProcessLookupError = builtins.ProcessLookupError def wrap_error(func, *args, **kw): return func(*args, **kw) else: import errno import select import socket class BlockingIOError(OSError): pass class BrokenPipeError(OSError): pass class ChildProcessError(OSError): pass class ConnectionRefusedError(OSError): pass class InterruptedError(OSError): pass class ConnectionResetError(OSError): pass class ConnectionAbortedError(OSError): pass class PermissionError(OSError): pass class FileNotFoundError(OSError): pass class ProcessLookupError(OSError): pass _MAP_ERRNO = { errno.EACCES: PermissionError, errno.EAGAIN: BlockingIOError, errno.EALREADY: BlockingIOError, errno.ECHILD: ChildProcessError, errno.ECONNABORTED: ConnectionAbortedError, errno.ECONNREFUSED: ConnectionRefusedError, errno.ECONNRESET: ConnectionResetError, errno.EINPROGRESS: BlockingIOError, errno.EINTR: InterruptedError, errno.ENOENT: FileNotFoundError, errno.EPERM: PermissionError, errno.EPIPE: BrokenPipeError, errno.ESHUTDOWN: BrokenPipeError, errno.EWOULDBLOCK: BlockingIOError, errno.ESRCH: ProcessLookupError, } def wrap_error(func, *args, **kw): """ Wrap socket.error, IOError, OSError, select.error to raise new specialized exceptions of Python 3.3 like InterruptedError (PEP 3151). """ try: return func(*args, **kw) except (socket.error, IOError, OSError) as exc: if hasattr(exc, 'winerror'): _wrap_error(exc, _MAP_ERRNO, exc.winerror) # _MAP_ERRNO does not contain all Windows errors. # For some errors like "file not found", exc.errno should # be used (ex: ENOENT). _wrap_error(exc, _MAP_ERRNO, exc.errno) raise except select.error as exc: if exc.args: _wrap_error(exc, _MAP_ERRNO, exc.args[0]) raise if PY26: from urlparse import ( _parse_cache, MAX_CACHE_SIZE, clear_cache, _splitnetloc, SplitResult, scheme_chars, ) def urlsplit(url, scheme='', allow_fragments=True): """Parse a URL into 5 components: <scheme>://<netloc>/<path>?<query>#<fragment> Return a 5-tuple: (scheme, netloc, path, query, fragment). Note that we don't break the components up in smaller bits (e.g. netloc is a single string) and we don't expand % escapes.""" allow_fragments = bool(allow_fragments) key = url, scheme, allow_fragments, type(url), type(scheme) cached = _parse_cache.get(key, None) if cached: return cached if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() netloc = query = fragment = '' i = url.find(':') if i > 0: if url[:i] == 'http': # optimize the common case scheme = url[:i].lower() url = url[i+1:] if url[:2] == '//': netloc, url = _splitnetloc(url, 2) if (('[' in netloc and ']' not in netloc) or (']' in netloc and '[' not in netloc)): raise ValueError("Invalid IPv6 URL") if allow_fragments and '#' in url: url, fragment = url.split('#', 1) if '?' in url: url, query = url.split('?', 1) v = SplitResult(scheme, netloc, url, query, fragment) _parse_cache[key] = v return v for c in url[:i]: if c not in scheme_chars: break else: # make sure "url" is not actually a port number (in which case # "scheme" is really part of the path) rest = url[i+1:] if not rest or any(c not in '0123456789' for c in rest): # not a port number scheme, url = url[:i].lower(), rest if url[:2] == '//': netloc, url = _splitnetloc(url, 2) if (('[' in netloc and ']' not in netloc) or (']' in netloc and '[' not in netloc)): raise ValueError("Invalid IPv6 URL") if allow_fragments and '#' in url: url, fragment = url.split('#', 1) if '?' in url: url, query = url.split('?', 1) v = SplitResult(scheme, netloc, url, query, fragment) _parse_cache[key] = v return v else: from gunicorn.six.moves.urllib.parse import urlsplit
mit
5,232,737,172,263,703,000
31.820225
99
0.585758
false
richardcs/ansible
lib/ansible/modules/network/cloudengine/ce_dldp_interface.py
7
22686
#!/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_dldp_interface version_added: "2.4" short_description: Manages interface DLDP configuration on HUAWEI CloudEngine switches. description: - Manages interface DLDP configuration on HUAWEI CloudEngine switches. author: - Zhou Zhijin (@QijunPan) notes: - If C(state=present, enable=disable), interface DLDP enable will be turned off and related interface DLDP confuration will be cleared. - If C(state=absent), only local_mac is supported to configure. options: interface: description: - Must be fully qualified interface name, i.e. GE1/0/1, 10GE1/0/1, 40GE1/0/22, 100GE1/0/1. required: true enable: description: - Set interface DLDP enable state. choices: ['enable', 'disable'] mode_enable: description: - Set DLDP compatible-mode enable state. choices: ['enable', 'disable'] local_mac: description: - Set the source MAC address for DLDP packets sent in the DLDP-compatible mode. The value of MAC address is in H-H-H format. H contains 1 to 4 hexadecimal digits. reset: description: - Specify whether reseting interface DLDP state. choices: ['enable', 'disable'] state: description: - Manage the state of the resource. default: present choices: ['present','absent'] ''' EXAMPLES = ''' - name: DLDP interface 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: "Configure interface DLDP enable state and ensure global dldp enable is turned on" ce_dldp_interface: interface: 40GE2/0/1 enable: enable provider: "{{ cli }}" - name: "Configuire interface DLDP compatible-mode enable state and ensure interface DLDP state is already enabled" ce_dldp_interface: interface: 40GE2/0/1 enable: enable mode_enable: enable provider: "{{ cli }}" - name: "Configuire the source MAC address for DLDP packets sent in the DLDP-compatible mode and ensure interface DLDP state and compatible-mode enable state is already enabled" ce_dldp_interface: interface: 40GE2/0/1 enable: enable mode_enable: enable local_mac: aa-aa-aa provider: "{{ cli }}" - name: "Reset DLDP state of specified interface and ensure interface DLDP state is already enabled" ce_dldp_interface: interface: 40GE2/0/1 enable: enable reset: enable provider: "{{ cli }}" - name: "Unconfigure interface DLDP local mac addreess when C(state=absent)" ce_dldp_interface: interface: 40GE2/0/1 state: absent local_mac: aa-aa-aa provider: "{{ cli }}" ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: always type: dict sample: { "enable": "enalbe", "interface": "40GE2/0/22", "local_mac": "aa-aa-aa", "mode_enable": "enable", "reset": "enable" } existing: description: k/v pairs of existing interface DLDP configration returned: always type: dict sample: { "enable": "disable", "interface": "40GE2/0/22", "local_mac": null, "mode_enable": null, "reset": "disable" } end_state: description: k/v pairs of interface DLDP configration after module execution returned: always type: dict sample: { "enable": "enable", "interface": "40GE2/0/22", "local_mac": "00aa-00aa-00aa", "mode_enable": "enable", "reset": "enable" } updates: description: command sent to the device returned: always type: list sample: [ "dldp enable", "dldp compatible-mode enable", "dldp compatible-mode local-mac aa-aa-aa", "dldp reset" ] changed: description: check to see if a change was made on the device returned: always type: boolean sample: true ''' import copy import re from xml.etree import ElementTree from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.cloudengine.ce import ce_argument_spec, set_nc_config, get_nc_config, execute_nc_action CE_NC_ACTION_RESET_INTF_DLDP = """ <action> <dldp xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <resetIfDldp> <ifName>%s</ifName> </resetIfDldp> </dldp> </action> """ CE_NC_GET_INTF_DLDP_CONFIG = """ <filter type="subtree"> <dldp xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <dldpInterfaces> <dldpInterface> <ifName>%s</ifName> <dldpEnable></dldpEnable> <dldpCompatibleEnable></dldpCompatibleEnable> <dldpLocalMac></dldpLocalMac> </dldpInterface> </dldpInterfaces> </dldp> </filter> """ CE_NC_MERGE_DLDP_INTF_CONFIG = """ <config> <dldp xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <dldpInterfaces> <dldpInterface operation="merge"> <ifName>%s</ifName> <dldpEnable>%s</dldpEnable> <dldpCompatibleEnable>%s</dldpCompatibleEnable> <dldpLocalMac>%s</dldpLocalMac> </dldpInterface> </dldpInterfaces> </dldp> </config> """ CE_NC_CREATE_DLDP_INTF_CONFIG = """ <config> <dldp xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <dldpInterfaces> <dldpInterface operation="create"> <ifName>%s</ifName> <dldpEnable>%s</dldpEnable> <dldpCompatibleEnable>%s</dldpCompatibleEnable> <dldpLocalMac>%s</dldpLocalMac> </dldpInterface> </dldpInterfaces> </dldp> </config> """ CE_NC_DELETE_DLDP_INTF_CONFIG = """ <config> <dldp xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <dldpInterfaces> <dldpInterface operation="delete"> <ifName>%s</ifName> </dldpInterface> </dldpInterfaces> </dldp> </config> """ def judge_is_mac_same(mac1, mac2): """Judge whether two macs are the same""" if mac1 == mac2: return True list1 = re.findall(r'([0-9A-Fa-f]+)', mac1) list2 = re.findall(r'([0-9A-Fa-f]+)', mac2) if len(list1) != len(list2): return False for index, value in enumerate(list1, start=0): if value.lstrip('0').lower() != list2[index].lstrip('0').lower(): return False return True def get_interface_type(interface): """Gets the type of interface, such as 10GE, ETH-TRUNK, VLANIF...""" if interface is None: return None iftype = None if interface.upper().startswith('GE'): iftype = 'ge' elif interface.upper().startswith('10GE'): iftype = '10ge' elif interface.upper().startswith('25GE'): iftype = '25ge' elif interface.upper().startswith('4X10GE'): iftype = '4x10ge' elif interface.upper().startswith('40GE'): iftype = '40ge' elif interface.upper().startswith('100GE'): iftype = '100ge' elif interface.upper().startswith('VLANIF'): iftype = 'vlanif' elif interface.upper().startswith('LOOPBACK'): iftype = 'loopback' elif interface.upper().startswith('METH'): iftype = 'meth' elif interface.upper().startswith('ETH-TRUNK'): iftype = 'eth-trunk' elif interface.upper().startswith('VBDIF'): iftype = 'vbdif' elif interface.upper().startswith('NVE'): iftype = 'nve' elif interface.upper().startswith('TUNNEL'): iftype = 'tunnel' elif interface.upper().startswith('ETHERNET'): iftype = 'ethernet' elif interface.upper().startswith('FCOE-PORT'): iftype = 'fcoe-port' elif interface.upper().startswith('FABRIC-PORT'): iftype = 'fabric-port' elif interface.upper().startswith('STACK-PORT'): iftype = 'stack-Port' elif interface.upper().startswith('NULL'): iftype = 'null' else: return None return iftype.lower() class DldpInterface(object): """Manage interface dldp configration""" def __init__(self, argument_spec): self.spec = argument_spec self.module = None self.init_module() # DLDP interface configration info self.interface = self.module.params['interface'] self.enable = self.module.params['enable'] or None self.reset = self.module.params['reset'] or None self.mode_enable = self.module.params['mode_enable'] or None self.local_mac = self.module.params['local_mac'] or None self.state = self.module.params['state'] self.dldp_intf_conf = dict() self.same_conf = False # state self.changed = False self.updates_cmd = list() self.results = dict() self.proposed = dict() self.existing = list() self.end_state = list() def check_config_if_same(self): """Judge whether current config is the same as what we excepted""" if self.state == 'absent': return False else: if self.enable and self.enable != self.dldp_intf_conf['dldpEnable']: return False if self.mode_enable and self.mode_enable != self.dldp_intf_conf['dldpCompatibleEnable']: return False if self.local_mac: flag = judge_is_mac_same( self.local_mac, self.dldp_intf_conf['dldpLocalMac']) if not flag: return False if self.reset and self.reset == 'enable': return False return True def check_macaddr(self): """Check mac-address whether valid""" valid_char = '0123456789abcdef-' mac = self.local_mac if len(mac) > 16: return False mac_list = re.findall(r'([0-9a-fA-F]+)', mac) if len(mac_list) != 3: return False if mac.count('-') != 2: return False for _, value in enumerate(mac, start=0): if value.lower() not in valid_char: return False return True def check_params(self): """Check all input params""" if not self.interface: self.module.fail_json(msg='Error: Interface name cannot be empty.') if self.interface: intf_type = get_interface_type(self.interface) if not intf_type: self.module.fail_json( msg='Error: Interface name of %s ' 'is error.' % self.interface) if (self.state == 'absent') and (self.reset or self.mode_enable or self.enable): self.module.fail_json(msg="Error: It's better to use state=present when " "configuring or unconfiguring enable, mode_enable " "or using reset flag. state=absent is just for " "when using local_mac param.") if self.state == 'absent' and not self.local_mac: self.module.fail_json( msg="Error: Please specify local_mac parameter.") if self.state == 'present': if (self.dldp_intf_conf['dldpEnable'] == 'disable' and not self.enable and (self.mode_enable or self.local_mac or self.reset)): self.module.fail_json(msg="Error: when DLDP is already disabled on this port, " "mode_enable, local_mac and reset parameters are not " "expected to configure.") if self.enable == 'disable' and (self.mode_enable or self.local_mac or self.reset): self.module.fail_json(msg="Error: when using enable=disable, " "mode_enable, local_mac and reset parameters " "are not expected to configure.") if self.local_mac and (self.mode_enable == 'disable' or (self.dldp_intf_conf['dldpCompatibleEnable'] == 'disable' and self.mode_enable != 'enable')): self.module.fail_json(msg="Error: when DLDP compatible-mode is disabled on this port, " "Configuring local_mac is not allowed.") if self.local_mac: if not self.check_macaddr(): self.module.fail_json( msg="Error: local_mac has invalid value %s." % self.local_mac) def init_module(self): """Init module object""" self.module = AnsibleModule( argument_spec=self.spec, supports_check_mode=True) def check_response(self, xml_str, xml_name): """Check if response message is already succeed""" if "<ok/>" not in xml_str: self.module.fail_json(msg='Error: %s failed.' % xml_name) def get_dldp_intf_exist_config(self): """Get current dldp existed config""" dldp_conf = dict() xml_str = CE_NC_GET_INTF_DLDP_CONFIG % self.interface con_obj = get_nc_config(self.module, xml_str) if "<data/>" in con_obj: dldp_conf['dldpEnable'] = 'disable' dldp_conf['dldpCompatibleEnable'] = "" dldp_conf['dldpLocalMac'] = "" return dldp_conf xml_str = con_obj.replace('\r', '').replace('\n', '').\ replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\ replace('xmlns="http://www.huawei.com/netconf/vrp"', "") # get global DLDP info root = ElementTree.fromstring(xml_str) topo = root.find("data/dldp/dldpInterfaces/dldpInterface") if topo is None: self.module.fail_json( msg="Error: Get current DLDP configration failed.") for eles in topo: if eles.tag in ["dldpEnable", "dldpCompatibleEnable", "dldpLocalMac"]: if not eles.text: dldp_conf[eles.tag] = "" else: if eles.tag == "dldpEnable" or eles.tag == "dldpCompatibleEnable": if eles.text == 'true': value = 'enable' else: value = 'disable' else: value = eles.text dldp_conf[eles.tag] = value return dldp_conf def config_intf_dldp(self): """Config global dldp""" if self.same_conf: return if self.state == "present": enable = self.enable if not self.enable: enable = self.dldp_intf_conf['dldpEnable'] if enable == 'enable': enable = 'true' else: enable = 'false' mode_enable = self.mode_enable if not self.mode_enable: mode_enable = self.dldp_intf_conf['dldpCompatibleEnable'] if mode_enable == 'enable': mode_enable = 'true' else: mode_enable = 'false' local_mac = self.local_mac if not self.local_mac: local_mac = self.dldp_intf_conf['dldpLocalMac'] if self.enable == 'disable' and self.enable != self.dldp_intf_conf['dldpEnable']: xml_str = CE_NC_DELETE_DLDP_INTF_CONFIG % self.interface ret_xml = set_nc_config(self.module, xml_str) self.check_response(ret_xml, "DELETE_DLDP_INTF_CONFIG") elif self.dldp_intf_conf['dldpEnable'] == 'disable' and self.enable == 'enable': xml_str = CE_NC_CREATE_DLDP_INTF_CONFIG % ( self.interface, 'true', mode_enable, local_mac) ret_xml = set_nc_config(self.module, xml_str) self.check_response(ret_xml, "CREATE_DLDP_INTF_CONFIG") elif self.dldp_intf_conf['dldpEnable'] == 'enable': if mode_enable == 'false': local_mac = '' xml_str = CE_NC_MERGE_DLDP_INTF_CONFIG % ( self.interface, enable, mode_enable, local_mac) ret_xml = set_nc_config(self.module, xml_str) self.check_response(ret_xml, "MERGE_DLDP_INTF_CONFIG") if self.reset == 'enable': xml_str = CE_NC_ACTION_RESET_INTF_DLDP % self.interface ret_xml = execute_nc_action(self.module, xml_str) self.check_response(ret_xml, "ACTION_RESET_INTF_DLDP") self.changed = True else: if self.local_mac and judge_is_mac_same(self.local_mac, self.dldp_intf_conf['dldpLocalMac']): if self.dldp_intf_conf['dldpEnable'] == 'enable': dldp_enable = 'true' else: dldp_enable = 'false' if self.dldp_intf_conf['dldpCompatibleEnable'] == 'enable': dldp_compat_enable = 'true' else: dldp_compat_enable = 'false' xml_str = CE_NC_MERGE_DLDP_INTF_CONFIG % (self.interface, dldp_enable, dldp_compat_enable, '') ret_xml = set_nc_config(self.module, xml_str) self.check_response(ret_xml, "UNDO_DLDP_INTF_LOCAL_MAC_CONFIG") self.changed = True def get_existing(self): """Get existing info""" dldp_conf = dict() dldp_conf['interface'] = self.interface dldp_conf['enable'] = self.dldp_intf_conf.get('dldpEnable', None) dldp_conf['mode_enable'] = self.dldp_intf_conf.get( 'dldpCompatibleEnable', None) dldp_conf['local_mac'] = self.dldp_intf_conf.get('dldpLocalMac', None) dldp_conf['reset'] = 'disable' self.existing = copy.deepcopy(dldp_conf) def get_proposed(self): """Get proposed result """ self.proposed = dict(interface=self.interface, enable=self.enable, mode_enable=self.mode_enable, local_mac=self.local_mac, reset=self.reset, state=self.state) def get_update_cmd(self): """Get updatede commands""" if self.same_conf: return if self.state == "present": if self.enable and self.enable != self.dldp_intf_conf['dldpEnable']: if self.enable == 'enable': self.updates_cmd.append("dldp enable") elif self.enable == 'disable': self.updates_cmd.append("undo dldp enable") if self.mode_enable and self.mode_enable != self.dldp_intf_conf['dldpCompatibleEnable']: if self.mode_enable == 'enable': self.updates_cmd.append("dldp compatible-mode enable") else: self.updates_cmd.append("undo dldp compatible-mode enable") if self.local_mac: flag = judge_is_mac_same( self.local_mac, self.dldp_intf_conf['dldpLocalMac']) if not flag: self.updates_cmd.append( "dldp compatible-mode local-mac %s" % self.local_mac) if self.reset and self.reset == 'enable': self.updates_cmd.append('dldp reset') else: if self.changed: self.updates_cmd.append("undo dldp compatible-mode local-mac") def get_end_state(self): """Get end state info""" dldp_conf = dict() self.dldp_intf_conf = self.get_dldp_intf_exist_config() dldp_conf['interface'] = self.interface dldp_conf['enable'] = self.dldp_intf_conf.get('dldpEnable', None) dldp_conf['mode_enable'] = self.dldp_intf_conf.get( 'dldpCompatibleEnable', None) dldp_conf['local_mac'] = self.dldp_intf_conf.get('dldpLocalMac', None) dldp_conf['reset'] = 'disable' if self.reset == 'enable': dldp_conf['reset'] = 'enable' self.end_state = copy.deepcopy(dldp_conf) def show_result(self): """Show result""" self.results['changed'] = self.changed self.results['proposed'] = self.proposed self.results['existing'] = self.existing self.results['end_state'] = self.end_state if self.changed: self.results['updates'] = self.updates_cmd else: self.results['updates'] = list() self.module.exit_json(**self.results) def work(self): """Excute task""" self.dldp_intf_conf = self.get_dldp_intf_exist_config() self.check_params() self.same_conf = self.check_config_if_same() self.get_existing() self.get_proposed() self.config_intf_dldp() self.get_update_cmd() self.get_end_state() self.show_result() def main(): """Main function entry""" argument_spec = dict( interface=dict(required=True, type='str'), enable=dict(choices=['enable', 'disable'], type='str'), reset=dict(choices=['enable', 'disable'], type='str'), mode_enable=dict(choices=['enable', 'disable'], type='str'), local_mac=dict(type='str'), state=dict(choices=['absent', 'present'], default='present'), ) argument_spec.update(ce_argument_spec) dldp_intf_obj = DldpInterface(argument_spec) dldp_intf_obj.work() if __name__ == '__main__': main()
gpl-3.0
-2,418,286,735,730,111,000
33.52968
124
0.569294
false
apache/airflow
tests/providers/google/common/utils/test_id_token_credentials.py
3
6936
# 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 json import os import re import unittest from unittest import mock import pytest from google.auth import exceptions from google.auth.environment_vars import CREDENTIALS from airflow.providers.google.common.utils.id_token_credentials import ( IDTokenCredentialsAdapter, get_default_id_token_credentials, ) class TestIDTokenCredentialsAdapter(unittest.TestCase): def test_should_use_id_token_from_parent_credentials(self): parent_credentials = mock.MagicMock() type(parent_credentials).id_token = mock.PropertyMock(side_effect=["ID_TOKEN1", "ID_TOKEN2"]) creds = IDTokenCredentialsAdapter(credentials=parent_credentials) assert creds.token == "ID_TOKEN1" request_adapter = mock.MagicMock() creds.refresh(request_adapter) assert creds.token == "ID_TOKEN2" class TestGetDefaultIdTokenCredentials(unittest.TestCase): @mock.patch.dict("os.environ") @mock.patch( "google.auth._cloud_sdk.get_application_default_credentials_path", return_value="/tmp/INVALID_PATH.json", ) @mock.patch( "google.auth.compute_engine._metadata.ping", return_value=False, ) def test_should_raise_exception(self, mock_metadata_ping, mock_gcloud_sdk_path): if CREDENTIALS in os.environ: del os.environ[CREDENTIALS] with pytest.raises( exceptions.DefaultCredentialsError, match=re.escape( "Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS " "or explicitly create credentials and re-run the application. For more information, please " "see https://cloud.google.com/docs/authentication/getting-started" ), ): get_default_id_token_credentials(target_audience="example.org") @mock.patch.dict("os.environ") @mock.patch( "google.auth._cloud_sdk.get_application_default_credentials_path", return_value="/tmp/INVALID_PATH.json", ) @mock.patch( "google.auth.compute_engine._metadata.ping", return_value=True, ) @mock.patch( "google.auth.compute_engine.IDTokenCredentials", ) def test_should_support_metadata_credentials(self, credentials, mock_metadata_ping, mock_gcloud_sdk_path): if CREDENTIALS in os.environ: del os.environ[CREDENTIALS] assert credentials.return_value == get_default_id_token_credentials(target_audience="example.org") @mock.patch.dict("os.environ") @mock.patch( "airflow.providers.google.common.utils.id_token_credentials.open", mock.mock_open( read_data=json.dumps( { "client_id": "CLIENT_ID", "client_secret": "CLIENT_SECRET", "refresh_token": "REFRESH_TOKEN", "type": "authorized_user", } ) ), ) @mock.patch("google.auth._cloud_sdk.get_application_default_credentials_path", return_value=__file__) def test_should_support_user_credentials_from_gcloud(self, mock_gcloud_sdk_path): if CREDENTIALS in os.environ: del os.environ[CREDENTIALS] credentials = get_default_id_token_credentials(target_audience="example.org") assert isinstance(credentials, IDTokenCredentialsAdapter) assert credentials.credentials.client_secret == "CLIENT_SECRET" @mock.patch.dict("os.environ") @mock.patch( "airflow.providers.google.common.utils.id_token_credentials.open", mock.mock_open( read_data=json.dumps( { "type": "service_account", "project_id": "PROJECT_ID", "private_key_id": "PRIVATE_KEY_ID", "private_key": "PRIVATE_KEY", "client_email": "CLIENT_EMAIL", "client_id": "CLIENT_ID", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/CERT", } ) ), ) @mock.patch("google.auth._service_account_info.from_dict", return_value="SIGNER") @mock.patch("google.auth._cloud_sdk.get_application_default_credentials_path", return_value=__file__) def test_should_support_service_account_from_gcloud(self, mock_gcloud_sdk_path, mock_from_dict): if CREDENTIALS in os.environ: del os.environ[CREDENTIALS] credentials = get_default_id_token_credentials(target_audience="example.org") assert credentials.service_account_email == "CLIENT_EMAIL" @mock.patch.dict("os.environ") @mock.patch( "airflow.providers.google.common.utils.id_token_credentials.open", mock.mock_open( read_data=json.dumps( { "type": "service_account", "project_id": "PROJECT_ID", "private_key_id": "PRIVATE_KEY_ID", "private_key": "PRIVATE_KEY", "client_email": "CLIENT_EMAIL", "client_id": "CLIENT_ID", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/CERT", } ) ), ) @mock.patch("google.auth._service_account_info.from_dict", return_value="SIGNER") def test_should_support_service_account_from_env(self, mock_gcloud_sdk_path): os.environ[CREDENTIALS] = __file__ credentials = get_default_id_token_credentials(target_audience="example.org") assert credentials.service_account_email == "CLIENT_EMAIL"
apache-2.0
-6,909,240,019,518,783,000
40.783133
110
0.629614
false
bhairavmehta95/flashcard-helper-alexa-skill
sqlalchemy/__init__.py
10
2217
# sqlalchemy/__init__.py # Copyright (C) 2005-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from .sql import ( alias, all_, and_, any_, asc, between, bindparam, case, cast, collate, column, delete, desc, distinct, except_, except_all, exists, extract, false, func, funcfilter, insert, intersect, intersect_all, join, lateral, literal, literal_column, modifier, not_, null, or_, outerjoin, outparam, over, select, subquery, table, tablesample, text, true, tuple_, type_coerce, union, union_all, update, within_group, ) from .types import ( ARRAY, BIGINT, BINARY, BLOB, BOOLEAN, BigInteger, Binary, Boolean, CHAR, CLOB, DATE, DATETIME, DECIMAL, Date, DateTime, Enum, FLOAT, Float, INT, INTEGER, Integer, Interval, JSON, LargeBinary, NCHAR, NVARCHAR, NUMERIC, Numeric, PickleType, REAL, SMALLINT, SmallInteger, String, TEXT, TIME, TIMESTAMP, Text, Time, TypeDecorator, Unicode, UnicodeText, VARBINARY, VARCHAR, ) from .schema import ( CheckConstraint, Column, ColumnDefault, Constraint, DefaultClause, FetchedValue, ForeignKey, ForeignKeyConstraint, Index, MetaData, PassiveDefault, PrimaryKeyConstraint, Sequence, Table, ThreadLocalMetaData, UniqueConstraint, DDL, BLANK_SCHEMA ) from .inspection import inspect from .engine import create_engine, engine_from_config __version__ = '1.1.4' def __go(lcls): global __all__ from . import events from . import util as _sa_util import inspect as _inspect __all__ = sorted(name for name, obj in lcls.items() if not (name.startswith('_') or _inspect.ismodule(obj))) _sa_util.dependencies.resolve_all("sqlalchemy") __go(locals())
mit
-4,962,913,042,351,135,000
14.184932
77
0.583672
false
thisispuneet/potato-blog
django/middleware/gzip.py
321
1455
import re from django.utils.text import compress_string from django.utils.cache import patch_vary_headers re_accepts_gzip = re.compile(r'\bgzip\b') class GZipMiddleware(object): """ This middleware compresses content if the browser allows gzip compression. It sets the Vary header accordingly, so that caches will base their storage on the Accept-Encoding header. """ def process_response(self, request, response): # It's not worth compressing non-OK or really short responses. if response.status_code != 200 or len(response.content) < 200: return response patch_vary_headers(response, ('Accept-Encoding',)) # Avoid gzipping if we've already got a content-encoding. if response.has_header('Content-Encoding'): return response # MSIE have issues with gzipped respones of various content types. if "msie" in request.META.get('HTTP_USER_AGENT', '').lower(): ctype = response.get('Content-Type', '').lower() if not ctype.startswith("text/") or "javascript" in ctype: return response ae = request.META.get('HTTP_ACCEPT_ENCODING', '') if not re_accepts_gzip.search(ae): return response response.content = compress_string(response.content) response['Content-Encoding'] = 'gzip' response['Content-Length'] = str(len(response.content)) return response
bsd-3-clause
-7,578,307,989,054,543,000
37.289474
79
0.656357
false
peiyuwang/pants
src/python/pants/util/netrc.py
33
1725
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import collections import os from netrc import netrc as NetrcDb from netrc import NetrcParseError class Netrc(object): """Fetches username and password from ~/.netrc for logged in user.""" class NetrcError(Exception): """Raised to indicate Netrc errors""" def __init__(self, *args, **kwargs): super(Netrc.NetrcError, self).__init__(*args, **kwargs) def __init__(self): self._login = collections.defaultdict(lambda: None) self._password = collections.defaultdict(lambda: None) def getusername(self, repository): self._ensure_loaded() return self._login[repository] def getpassword(self, repository): self._ensure_loaded() return self._password[repository] def _ensure_loaded(self): if not self._login and not self._password: db = os.path.expanduser('~/.netrc') if not os.path.exists(db): raise self.NetrcError('A ~/.netrc file is required to authenticate') try: db = NetrcDb(db) for host, value in db.hosts.items(): auth = db.authenticators(host) if auth: login, _, password = auth self._login[host] = login self._password[host] = password if len(self._login) == 0: raise self.NetrcError('Found no usable authentication blocks in ~/.netrc') except NetrcParseError as e: raise self.NetrcError('Problem parsing ~/.netrc: {}'.format(e))
apache-2.0
-8,505,929,409,016,100,000
32.823529
93
0.653913
false
shawngraham/music-lab-scripts
07_louisiana/louisiana.py
3
11115
# -*- coding: utf-8 -*- ## # TRACK 7 # TOO BLUE # Brian Foo (brianfoo.com) # This file builds the sequence file for use with ChucK from the data supplied ## # Library dependancies import csv import json import math import os import pprint import time # Config BPM = 100 # Beats per minute, e.g. 60, 75, 100, 120, 150 DIVISIONS_PER_BEAT = 4 # e.g. 4 = quarter notes, 8 = eighth notes, etc VARIANCE_MS = 20 # +/- milliseconds an instrument note should be off by to give it a little more "natural" feel GAIN = 0.4 # base gain TEMPO = 1.0 # base tempo MS_PER_YEAR = 7200 # Files INSTRUMENTS_INPUT_FILE = 'data/instruments.csv' LAND_LOSS_INPUT_FILE = 'data/land_loss.json' SUMMARY_OUTPUT_FILE = 'data/report_summary.csv' SUMMARY_SEQUENCE_OUTPUT_FILE = 'data/report_sequence.csv' INSTRUMENTS_OUTPUT_FILE = 'data/ck_instruments.csv' SEQUENCE_OUTPUT_FILE = 'data/ck_sequence.csv' INSTRUMENTS_DIR = 'instruments/' # Output options WRITE_SEQUENCE = True WRITE_REPORT = True # Calculations BEAT_MS = round(60.0 / BPM * 1000) ROUND_TO_NEAREST = round(BEAT_MS / DIVISIONS_PER_BEAT) BEATS_PER_YEAR = round(MS_PER_YEAR / BEAT_MS) GROUPS_PER_YEAR = int(BEATS_PER_YEAR) GROUP_MS = MS_PER_YEAR / GROUPS_PER_YEAR # Init years = [] instruments = [] sequence = [] hindex = 0 # For creating pseudo-random numbers def halton(index, base): result = 0.0 f = 1.0 / base i = 1.0 * index while(i > 0): result += f * (i % base) i = math.floor(i / base) f = f / base return result # floor {n} to nearest {nearest} def floorToNearest(n, nearest): return 1.0 * math.floor(1.0*n/nearest) * nearest # round {n} to nearest {nearest} def roundToNearest(n, nearest): return 1.0 * round(1.0*n/nearest) * nearest # Read instruments from file with open(INSTRUMENTS_INPUT_FILE, 'rb') as f: r = csv.reader(f, delimiter=',') next(r, None) # remove header for file,min_loss,max_loss,min_c_loss,max_c_loss,from_gain,to_gain,from_tempo,to_tempo,tempo_offset,interval_phase,interval,interval_offset,active in r: if int(active): index = len(instruments) # build instrument object _beat_ms = int(round(BEAT_MS/TEMPO)) instrument = { 'index': index, 'file': INSTRUMENTS_DIR + file, 'min_loss': float(min_loss), 'max_loss': float(max_loss), 'min_c_loss': float(min_c_loss), 'max_c_loss': float(max_c_loss), 'from_gain': float(from_gain) * GAIN, 'to_gain': float(to_gain) * GAIN, 'from_tempo': float(from_tempo) * TEMPO, 'to_tempo': float(to_tempo) * TEMPO, 'tempo_offset': float(tempo_offset), 'interval_ms': int(int(interval_phase)*_beat_ms), 'interval': int(interval), 'interval_offset': int(interval_offset), 'from_beat_ms': int(round(BEAT_MS/(float(from_tempo)*TEMPO))), 'to_beat_ms': int(round(BEAT_MS/(float(to_tempo)*TEMPO))), 'beat_ms': _beat_ms } # add instrument to instruments instruments.append(instrument) # Read countries from file with open(LAND_LOSS_INPUT_FILE) as data_file: years = json.load(data_file) # Break years up into groups for i, year in enumerate(years): total_loss = len(year['losses']) years[i]['total_loss'] = total_loss years[i]['loss_per_group'] = 1.0 * total_loss / GROUPS_PER_YEAR # Normalize groups all_years_loss = 1.0 * sum([y['total_loss'] for y in years]) min_group_value = min([y['loss_per_group'] for y in years]) max_group_value = max([y['loss_per_group'] for y in years]) for i, year in enumerate(years): years[i]['loss_per_group_n'] = year['loss_per_group'] / all_years_loss years[i]['group_loss'] = (1.0 * year['loss_per_group'] - min_group_value) / (max_group_value - min_group_value) # Calculate total time total_ms = len(years) * MS_PER_YEAR total_seconds = int(1.0*total_ms/1000) print('Main sequence time: '+time.strftime('%M:%S', time.gmtime(total_seconds)) + ' (' + str(total_seconds) + 's)') print('Ms per beat: ' + str(BEAT_MS)) print('Beats per year: ' + str(BEATS_PER_YEAR)) # Multiplier based on sine curve def getMultiplier(percent_complete, rad=1.0): radians = percent_complete * (math.pi * rad) multiplier = math.sin(radians) if multiplier < 0: multiplier = 0.0 elif multiplier > 1: multplier = 1.0 return multiplier # Retrieve gain based on current beat def getGain(instrument, percent_complete): multiplier = getMultiplier(percent_complete) from_gain = instrument['from_gain'] to_gain = instrument['to_gain'] min_gain = min(from_gain, to_gain) gain = multiplier * (to_gain - from_gain) + from_gain gain = max(min_gain, round(gain, 2)) return gain # Get beat duration in ms based on current point in time def getBeatMs(instrument, percent_complete, round_to): multiplier = getMultiplier(percent_complete) from_beat_ms = instrument['from_beat_ms'] to_beat_ms = instrument['to_beat_ms'] ms = multiplier * (to_beat_ms - from_beat_ms) + from_beat_ms ms = int(roundToNearest(ms, round_to)) return ms # Return if the instrument should be played in the given interval def isValidInterval(instrument, elapsed_ms): interval_ms = instrument['interval_ms'] interval = instrument['interval'] interval_offset = instrument['interval_offset'] return int(math.floor(1.0*elapsed_ms/interval_ms)) % interval == interval_offset # Add beats to sequence def addBeatsToSequence(instrument, duration, ms, round_to): global sequence global hindex beat_ms = int(roundToNearest(instrument['beat_ms'], round_to)) offset_ms = int(instrument['tempo_offset'] * instrument['from_beat_ms']) ms += offset_ms previous_ms = int(ms) from_beat_ms = instrument['from_beat_ms'] to_beat_ms = instrument['to_beat_ms'] min_ms = min(from_beat_ms, to_beat_ms) remaining_duration = int(duration) elapsed_duration = offset_ms while remaining_duration >= min_ms: elapsed_ms = int(ms) elapsed_beat = int((elapsed_ms-previous_ms) / beat_ms) percent_complete = 1.0 * elapsed_duration / duration this_beat_ms = getBeatMs(instrument, percent_complete, round_to) # add to sequence if in valid interval if isValidInterval(instrument, elapsed_ms): h = halton(hindex, 3) variance = int(h * VARIANCE_MS * 2 - VARIANCE_MS) sequence.append({ 'instrument_index': instrument['index'], 'instrument': instrument, 'position': 0, 'rate': 1, 'gain': getGain(instrument, percent_complete), 'elapsed_ms': max([elapsed_ms + variance, 0]), 'duration': min([this_beat_ms, MS_PER_YEAR]) }) hindex += 1 remaining_duration -= this_beat_ms elapsed_duration += this_beat_ms ms += this_beat_ms # Build sequence for instrument in instruments: ms = None queue_duration = 0 c_loss = 0 current_ms = 0 # Go through each year for year in years: for g in range(GROUPS_PER_YEAR): c_loss += year['loss_per_group_n'] is_valid = year['group_loss'] >= instrument['min_loss'] and year['group_loss'] < instrument['max_loss'] and c_loss >= instrument['min_c_loss'] and c_loss < instrument['max_c_loss'] # If not valid, add it queue to sequence if not is_valid and queue_duration > 0 and ms != None or is_valid and ms != None and current_ms > (ms+queue_duration): addBeatsToSequence(instrument.copy(), queue_duration, ms, ROUND_TO_NEAREST) ms = None queue_duration = 0 # If valid, add time to queue if is_valid: if ms==None: ms = current_ms queue_duration += GROUP_MS current_ms += GROUP_MS # Add remaining queue to sequence if queue_duration > 0 and ms != None: addBeatsToSequence(instrument.copy(), queue_duration, ms, ROUND_TO_NEAREST) # Sort sequence sequence = sorted(sequence, key=lambda k: k['elapsed_ms']) # Add milliseconds to sequence elapsed = 0 for i, step in enumerate(sequence): sequence[i]['milliseconds'] = step['elapsed_ms'] - elapsed elapsed = step['elapsed_ms'] # Write instruments to file if WRITE_SEQUENCE and len(instruments) > 0: with open(INSTRUMENTS_OUTPUT_FILE, 'wb') as f: w = csv.writer(f) for index, instrument in enumerate(instruments): w.writerow([index]) w.writerow([instrument['file']]) f.seek(-2, os.SEEK_END) # remove newline f.truncate() print('Successfully wrote instruments to file: '+INSTRUMENTS_OUTPUT_FILE) # Write sequence to file if WRITE_SEQUENCE and len(sequence) > 0: with open(SEQUENCE_OUTPUT_FILE, 'wb') as f: w = csv.writer(f) for step in sequence: w.writerow([step['instrument_index']]) w.writerow([step['position']]) w.writerow([step['gain']]) w.writerow([step['rate']]) w.writerow([step['milliseconds']]) f.seek(-2, os.SEEK_END) # remove newline f.truncate() print('Successfully wrote sequence to file: '+SEQUENCE_OUTPUT_FILE) # Write summary files if WRITE_REPORT: with open(SUMMARY_OUTPUT_FILE, 'wb') as f: w = csv.writer(f) header = ['Time', 'Year Start', 'Year End', 'Group', 'Loss', 'Loss Cum'] w.writerow(header) start_ms = 0 cumulative_loss = 0 for y in years: # cumulative_loss += y['loss'] for g in range(GROUPS_PER_YEAR): cumulative_loss += y['loss_per_group_n'] elapsed = start_ms elapsed_f = time.strftime('%M:%S', time.gmtime(int(elapsed/1000))) ms = int(elapsed % 1000) elapsed_f += '.' + str(ms) row = [elapsed_f, y['year_start'], y['year_end'], g, y['group_loss'], cumulative_loss] w.writerow(row) start_ms += GROUP_MS print('Successfully wrote summary file: '+SUMMARY_OUTPUT_FILE) if len(sequence) > 0: with open(SUMMARY_SEQUENCE_OUTPUT_FILE, 'wb') as f: w = csv.writer(f) w.writerow(['Time', 'Instrument', 'Gain']) for step in sequence: instrument = instruments[step['instrument_index']] elapsed = step['elapsed_ms'] elapsed_f = time.strftime('%M:%S', time.gmtime(int(elapsed/1000))) ms = int(elapsed % 1000) elapsed_f += '.' + str(ms) w.writerow([elapsed_f, instrument['file'], step['gain']]) f.seek(-2, os.SEEK_END) # remove newline f.truncate() print('Successfully wrote sequence report to file: '+SUMMARY_SEQUENCE_OUTPUT_FILE)
mit
1,060,422,183,825,063,800
36.298658
192
0.603509
false
alsrgv/tensorflow
tensorflow/python/platform/self_check.py
6
2436
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Platform-specific code for checking the integrity of the TensorFlow build.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os try: from tensorflow.python.platform import build_info except ImportError: raise ImportError("Could not import tensorflow. Do not import tensorflow " "from its source directory; change directory to outside " "the TensorFlow source tree, and relaunch your Python " "interpreter from there.") def preload_check(): """Raises an exception if the environment is not correctly configured. Raises: ImportError: If the check detects that the environment is not correctly configured, and attempting to load the TensorFlow runtime will fail. """ if os.name == "nt": # Attempt to load any DLLs that the Python extension depends on before # we load the Python extension, so that we can raise an actionable error # message if they are not found. import ctypes # pylint: disable=g-import-not-at-top if hasattr(build_info, "msvcp_dll_name"): try: ctypes.WinDLL(build_info.msvcp_dll_name) except OSError: raise ImportError( "Could not find %r. TensorFlow requires that this DLL be " "installed in a directory that is named in your %%PATH%% " "environment variable. You may install this DLL by downloading " "Visual C++ 2015 Redistributable Update 3 from this URL: " "https://www.microsoft.com/en-us/download/details.aspx?id=53587" % build_info.msvcp_dll_name) else: # TODO(mrry): Consider adding checks for the Linux and Mac OS X builds. pass
apache-2.0
225,487,111,714,470,720
41
80
0.676108
false
EliotBerriot/django
django/contrib/admin/__init__.py
562
1243
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here # has been referenced in documentation. from django.contrib.admin.decorators import register from django.contrib.admin.filters import ( AllValuesFieldListFilter, BooleanFieldListFilter, ChoicesFieldListFilter, DateFieldListFilter, FieldListFilter, ListFilter, RelatedFieldListFilter, RelatedOnlyFieldListFilter, SimpleListFilter, ) from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import ( HORIZONTAL, VERTICAL, ModelAdmin, StackedInline, TabularInline, ) from django.contrib.admin.sites import AdminSite, site from django.utils.module_loading import autodiscover_modules __all__ = [ "register", "ACTION_CHECKBOX_NAME", "ModelAdmin", "HORIZONTAL", "VERTICAL", "StackedInline", "TabularInline", "AdminSite", "site", "ListFilter", "SimpleListFilter", "FieldListFilter", "BooleanFieldListFilter", "RelatedFieldListFilter", "ChoicesFieldListFilter", "DateFieldListFilter", "AllValuesFieldListFilter", "RelatedOnlyFieldListFilter", "autodiscover", ] def autodiscover(): autodiscover_modules('admin', register_to=site) default_app_config = 'django.contrib.admin.apps.AdminConfig'
bsd-3-clause
5,927,016,434,097,670,000
41.862069
79
0.786002
false
wkschwartz/django
tests/string_lookup/tests.py
123
2332
from django.test import TestCase from .models import Article, Bar, Base, Child, Foo, Whiz class StringLookupTests(TestCase): def test_string_form_referencing(self): """ Regression test for #1661 and #1662 String form referencing of models works, both as pre and post reference, on all RelatedField types. """ f1 = Foo(name="Foo1") f1.save() f2 = Foo(name="Foo2") f2.save() w1 = Whiz(name="Whiz1") w1.save() b1 = Bar(name="Bar1", normal=f1, fwd=w1, back=f2) b1.save() self.assertEqual(b1.normal, f1) self.assertEqual(b1.fwd, w1) self.assertEqual(b1.back, f2) base1 = Base(name="Base1") base1.save() child1 = Child(name="Child1", parent=base1) child1.save() self.assertEqual(child1.parent, base1) def test_unicode_chars_in_queries(self): """ Regression tests for #3937 make sure we can use unicode characters in queries. If these tests fail on MySQL, it's a problem with the test setup. A properly configured UTF-8 database can handle this. """ fx = Foo(name='Bjorn', friend='François') fx.save() self.assertEqual(Foo.objects.get(friend__contains='\xe7'), fx) def test_queries_on_textfields(self): """ Regression tests for #5087 make sure we can perform queries on TextFields. """ a = Article(name='Test', text='The quick brown fox jumps over the lazy dog.') a.save() self.assertEqual(Article.objects.get(text__exact='The quick brown fox jumps over the lazy dog.'), a) self.assertEqual(Article.objects.get(text__contains='quick brown fox'), a) def test_ipaddress_on_postgresql(self): """ Regression test for #708 "like" queries on IP address fields require casting with HOST() (on PostgreSQL). """ a = Article(name='IP test', text='The body', submitted_from='192.0.2.100') a.save() self.assertSequenceEqual(Article.objects.filter(submitted_from__contains='192.0.2'), [a]) # The searches do not match the subnet mask (/32 in this case) self.assertEqual(Article.objects.filter(submitted_from__contains='32').count(), 0)
bsd-3-clause
-3,081,739,055,040,176,600
29.272727
108
0.607036
false
naro/django-guardian
guardian/tests/other_test.py
35
12667
import guardian from django.contrib.auth.models import AnonymousUser from django.contrib.auth.models import Group from django.contrib.auth.models import Permission from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from django.test import TestCase from guardian.backends import ObjectPermissionBackend from guardian.exceptions import GuardianError from guardian.exceptions import NotUserNorGroup from guardian.exceptions import ObjectNotPersisted from guardian.exceptions import WrongAppError from guardian.models import GroupObjectPermission from guardian.models import UserObjectPermission from itertools import chain class UserPermissionTests(TestCase): fixtures = ['tests.json'] def setUp(self): self.user = User.objects.get(username='jack') self.ctype = ContentType.objects.create(name='foo', model='bar', app_label='fake-for-guardian-tests') self.obj1 = ContentType.objects.create(name='ct1', model='foo', app_label='guardian-tests') self.obj2 = ContentType.objects.create(name='ct2', model='bar', app_label='guardian-tests') def test_assignement(self): self.assertFalse(self.user.has_perm('change_contenttype', self.ctype)) UserObjectPermission.objects.assign('change_contenttype', self.user, self.ctype) self.assertTrue(self.user.has_perm('change_contenttype', self.ctype)) self.assertTrue(self.user.has_perm('contenttypes.change_contenttype', self.ctype)) def test_assignement_and_remove(self): UserObjectPermission.objects.assign('change_contenttype', self.user, self.ctype) self.assertTrue(self.user.has_perm('change_contenttype', self.ctype)) UserObjectPermission.objects.remove_perm('change_contenttype', self.user, self.ctype) self.assertFalse(self.user.has_perm('change_contenttype', self.ctype)) def test_ctypes(self): UserObjectPermission.objects.assign('change_contenttype', self.user, self.obj1) self.assertTrue(self.user.has_perm('change_contenttype', self.obj1)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj2)) UserObjectPermission.objects.remove_perm('change_contenttype', self.user, self.obj1) UserObjectPermission.objects.assign('change_contenttype', self.user, self.obj2) self.assertTrue(self.user.has_perm('change_contenttype', self.obj2)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj1)) UserObjectPermission.objects.assign('change_contenttype', self.user, self.obj1) UserObjectPermission.objects.assign('change_contenttype', self.user, self.obj2) self.assertTrue(self.user.has_perm('change_contenttype', self.obj2)) self.assertTrue(self.user.has_perm('change_contenttype', self.obj1)) UserObjectPermission.objects.remove_perm('change_contenttype', self.user, self.obj1) UserObjectPermission.objects.remove_perm('change_contenttype', self.user, self.obj2) self.assertFalse(self.user.has_perm('change_contenttype', self.obj2)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj1)) def test_get_for_object(self): perms = UserObjectPermission.objects.get_for_object(self.user, self.ctype) self.assertEqual(perms.count(), 0) to_assign = sorted([ 'delete_contenttype', 'change_contenttype', ]) for perm in to_assign: UserObjectPermission.objects.assign(perm, self.user, self.ctype) perms = UserObjectPermission.objects.get_for_object(self.user, self.ctype) codenames = sorted(chain(*perms.values_list('permission__codename'))) self.assertEqual(to_assign, codenames) def test_assign_validation(self): self.assertRaises(Permission.DoesNotExist, UserObjectPermission.objects.assign, 'change_group', self.user, self.user) group = Group.objects.create(name='test_group_assign_validation') ctype = ContentType.objects.get_for_model(group) perm = Permission.objects.get(codename='change_user') create_info = dict( permission = perm, user = self.user, content_type = ctype, object_pk = group.pk ) self.assertRaises(ValidationError, UserObjectPermission.objects.create, **create_info) def test_unicode(self): obj_perm = UserObjectPermission.objects.assign("change_user", self.user, self.user) self.assertTrue(isinstance(obj_perm.__unicode__(), unicode)) def test_errors(self): not_saved_user = User(username='not_saved_user') self.assertRaises(ObjectNotPersisted, UserObjectPermission.objects.assign, "change_user", self.user, not_saved_user) self.assertRaises(ObjectNotPersisted, UserObjectPermission.objects.remove_perm, "change_user", self.user, not_saved_user) self.assertRaises(ObjectNotPersisted, UserObjectPermission.objects.get_for_object, "change_user", not_saved_user) class GroupPermissionTests(TestCase): fixtures = ['tests.json'] def setUp(self): self.user = User.objects.get(username='jack') self.group, created = Group.objects.get_or_create(name='jackGroup') self.user.groups.add(self.group) self.ctype = ContentType.objects.create(name='foo', model='bar', app_label='fake-for-guardian-tests') self.obj1 = ContentType.objects.create(name='ct1', model='foo', app_label='guardian-tests') self.obj2 = ContentType.objects.create(name='ct2', model='bar', app_label='guardian-tests') def test_assignement(self): self.assertFalse(self.user.has_perm('change_contenttype', self.ctype)) self.assertFalse(self.user.has_perm('contenttypes.change_contenttype', self.ctype)) GroupObjectPermission.objects.assign('change_contenttype', self.group, self.ctype) self.assertTrue(self.user.has_perm('change_contenttype', self.ctype)) self.assertTrue(self.user.has_perm('contenttypes.change_contenttype', self.ctype)) def test_assignement_and_remove(self): GroupObjectPermission.objects.assign('change_contenttype', self.group, self.ctype) self.assertTrue(self.user.has_perm('change_contenttype', self.ctype)) GroupObjectPermission.objects.remove_perm('change_contenttype', self.group, self.ctype) self.assertFalse(self.user.has_perm('change_contenttype', self.ctype)) def test_ctypes(self): GroupObjectPermission.objects.assign('change_contenttype', self.group, self.obj1) self.assertTrue(self.user.has_perm('change_contenttype', self.obj1)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj2)) GroupObjectPermission.objects.remove_perm('change_contenttype', self.group, self.obj1) GroupObjectPermission.objects.assign('change_contenttype', self.group, self.obj2) self.assertTrue(self.user.has_perm('change_contenttype', self.obj2)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj1)) GroupObjectPermission.objects.assign('change_contenttype', self.group, self.obj1) GroupObjectPermission.objects.assign('change_contenttype', self.group, self.obj2) self.assertTrue(self.user.has_perm('change_contenttype', self.obj2)) self.assertTrue(self.user.has_perm('change_contenttype', self.obj1)) GroupObjectPermission.objects.remove_perm('change_contenttype', self.group, self.obj1) GroupObjectPermission.objects.remove_perm('change_contenttype', self.group, self.obj2) self.assertFalse(self.user.has_perm('change_contenttype', self.obj2)) self.assertFalse(self.user.has_perm('change_contenttype', self.obj1)) def test_get_for_object(self): group = Group.objects.create(name='get_group_perms_for_object') self.user.groups.add(group) perms = GroupObjectPermission.objects.get_for_object(group, self.ctype) self.assertEqual(perms.count(), 0) to_assign = sorted([ 'delete_contenttype', 'change_contenttype', ]) for perm in to_assign: GroupObjectPermission.objects.assign(perm, group, self.ctype) perms = GroupObjectPermission.objects.get_for_object(group, self.ctype) codenames = sorted(chain(*perms.values_list('permission__codename'))) self.assertEqual(to_assign, codenames) def test_assign_validation(self): self.assertRaises(Permission.DoesNotExist, GroupObjectPermission.objects.assign, 'change_user', self.group, self.group) user = User.objects.create(username='test_user_assign_validation') ctype = ContentType.objects.get_for_model(user) perm = Permission.objects.get(codename='change_group') create_info = dict( permission = perm, group = self.group, content_type = ctype, object_pk = user.pk ) self.assertRaises(ValidationError, GroupObjectPermission.objects.create, **create_info) def test_unicode(self): obj_perm = GroupObjectPermission.objects.assign("change_group", self.group, self.group) self.assertTrue(isinstance(obj_perm.__unicode__(), unicode)) def test_errors(self): not_saved_group = Group(name='not_saved_group') self.assertRaises(ObjectNotPersisted, GroupObjectPermission.objects.assign, "change_group", self.group, not_saved_group) self.assertRaises(ObjectNotPersisted, GroupObjectPermission.objects.remove_perm, "change_group", self.group, not_saved_group) self.assertRaises(ObjectNotPersisted, GroupObjectPermission.objects.get_for_object, "change_group", not_saved_group) class ObjectPermissionBackendTests(TestCase): def setUp(self): self.user = User.objects.create(username='jack') self.backend = ObjectPermissionBackend() def test_attrs(self): self.assertTrue(self.backend.supports_anonymous_user) self.assertTrue(self.backend.supports_object_permissions) self.assertTrue(self.backend.supports_inactive_user) def test_authenticate(self): self.assertEqual(self.backend.authenticate( self.user.username, self.user.password), None) def test_has_perm_noobj(self): result = self.backend.has_perm(self.user, "change_contenttype") self.assertFalse(result) def test_has_perm_notauthed(self): user = AnonymousUser() self.assertFalse(self.backend.has_perm(user, "change_user", self.user)) def test_has_perm_wrong_app(self): self.assertRaises(WrongAppError, self.backend.has_perm, self.user, "no_app.change_user", self.user) def test_obj_is_not_model(self): for obj in (Group, 666, "String", [2, 1, 5, 7], {}): self.assertFalse(self.backend.has_perm(self.user, "any perm", obj)) def test_not_active_user(self): user = User.objects.create(username='non active user') ctype = ContentType.objects.create(name='foo', model='bar', app_label='fake-for-guardian-tests') perm = 'change_contenttype' UserObjectPermission.objects.assign(perm, user, ctype) self.assertTrue(self.backend.has_perm(user, perm, ctype)) user.is_active = False user.save() self.assertFalse(self.backend.has_perm(user, perm, ctype)) class GuardianBaseTests(TestCase): def has_attrs(self): self.assertTrue(hasattr(guardian, '__version__')) def test_version(self): for x in guardian.VERSION: self.assertTrue(isinstance(x, (int, str))) def test_get_version(self): self.assertTrue(isinstance(guardian.get_version(), str)) class TestExceptions(TestCase): def _test_error_class(self, exc_cls): self.assertTrue(isinstance(exc_cls, GuardianError)) def test_error_classes(self): self.assertTrue(isinstance(GuardianError(), Exception)) guardian_errors = [NotUserNorGroup] for err in guardian_errors: self._test_error_class(err())
bsd-2-clause
1,039,504,633,094,305,000
40.667763
92
0.671509
false
charukiewicz/beer-manager
venv/lib/python3.4/site-packages/flask/module.py
850
1363
# -*- coding: utf-8 -*- """ flask.module ~~~~~~~~~~~~ Implements a class that represents module blueprints. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os from .blueprints import Blueprint def blueprint_is_module(bp): """Used to figure out if something is actually a module""" return isinstance(bp, Module) class Module(Blueprint): """Deprecated module support. Until Flask 0.6 modules were a different name of the concept now available as blueprints in Flask. They are essentially doing the same but have some bad semantics for templates and static files that were fixed with blueprints. .. versionchanged:: 0.7 Modules were deprecated in favor for blueprints. """ def __init__(self, import_name, name=None, url_prefix=None, static_path=None, subdomain=None): if name is None: assert '.' in import_name, 'name required if package name ' \ 'does not point to a submodule' name = import_name.rsplit('.', 1)[1] Blueprint.__init__(self, name, import_name, url_prefix=url_prefix, subdomain=subdomain, template_folder='templates') if os.path.isdir(os.path.join(self.root_path, 'static')): self._static_folder = 'static'
mit
-3,892,983,344,031,195,000
31.452381
76
0.634629
false
DBuildService/atomic-reactor
tests/plugins/test_build_source_container.py
1
8892
""" Copyright (c) 2019 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ import os import subprocess import tempfile from flexmock import flexmock import pytest import json import tarfile import re from atomic_reactor.constants import PLUGIN_FETCH_SOURCES_KEY from atomic_reactor.inner import DockerBuildWorkflow from atomic_reactor.constants import EXPORTED_SQUASHED_IMAGE_NAME from atomic_reactor.core import DockerTasker from atomic_reactor.plugin import BuildStepPluginsRunner, PluginFailedException from atomic_reactor.plugins.build_source_container import SourceContainerPlugin from atomic_reactor.plugins.pre_reactor_config import ( ReactorConfigPlugin, ) from tests.docker_mock import mock_docker from tests.constants import MOCK_SOURCE class MockSource(object): def __init__(self, tmpdir): tmpdir = str(tmpdir) self.dockerfile_path = os.path.join(tmpdir, 'Dockerfile') self.path = tmpdir self.config = flexmock(image_build_method=None) def get_build_file_path(self): return self.dockerfile_path, self.path class MockInsideBuilder(object): def __init__(self): mock_docker() self.tasker = DockerTasker() self.base_image = None self.image_id = None self.image = None self.df_path = None self.df_dir = None self.parent_images_digests = {} def ensure_not_built(self): pass def mock_workflow(tmpdir, sources_dir='', remote_dir=''): workflow = DockerBuildWorkflow(source=MOCK_SOURCE) builder = MockInsideBuilder() source = MockSource(tmpdir) setattr(builder, 'source', source) setattr(workflow, 'source', source) setattr(workflow, 'builder', builder) workflow.plugin_workspace[ReactorConfigPlugin.key] = {} workflow.prebuild_results[PLUGIN_FETCH_SOURCES_KEY] = { 'image_sources_dir': os.path.join(tmpdir.strpath, sources_dir), 'remote_sources_dir': os.path.join(tmpdir.strpath, remote_dir), } return workflow @pytest.mark.parametrize('sources_dir, sources_dir_exists, sources_dir_empty', [ ('sources_dir', False, True), ('sources_dir', True, True), ('sources_dir', True, False)]) @pytest.mark.parametrize('remote_dir, remote_dir_exists, remote_dir_empty', [ ('remote_sources_dir', False, True), ('remote_sources_dir', True, True), ('remote_sources_dir', True, False)]) @pytest.mark.parametrize('export_failed', (True, False)) def test_running_build(tmpdir, caplog, user_params, sources_dir, sources_dir_exists, sources_dir_empty, remote_dir, remote_dir_exists, remote_dir_empty, export_failed): """ Test if proper result is returned and if plugin works """ sources_dir_path = os.path.join(tmpdir.strpath, sources_dir) if sources_dir_exists: os.mkdir(sources_dir_path) if not sources_dir_empty: os.mknod(os.path.join(sources_dir_path, 'stub.srpm')) remote_dir_path = os.path.join(tmpdir.strpath, remote_dir) if remote_dir_exists: os.mkdir(remote_dir_path) if not remote_dir_empty: os.mknod(os.path.join(remote_dir_path, 'remote-sources.tar.gz')) workflow = mock_workflow(tmpdir, sources_dir, remote_dir) mocked_tasker = flexmock(workflow.builder.tasker) mocked_tasker.should_receive('wait').and_return(0) runner = BuildStepPluginsRunner( mocked_tasker, workflow, [{ 'name': SourceContainerPlugin.key, 'args': {}, }] ) temp_image_output_dir = os.path.join(str(tmpdir), 'image_output_dir') temp_image_export_dir = os.path.join(str(tmpdir), 'image_export_dir') tempfile_chain = flexmock(tempfile).should_receive("mkdtemp").and_return(temp_image_output_dir) tempfile_chain.and_return(temp_image_export_dir) os.mkdir(temp_image_export_dir) os.makedirs(os.path.join(temp_image_output_dir, 'blobs', 'sha256')) def check_check_output(args, **kwargs): if args[0] == 'skopeo': assert args[0] == 'skopeo' assert args[1] == 'copy' assert args[2] == 'oci:%s' % temp_image_output_dir assert args[3] == 'docker-archive:%s' % os.path.join(temp_image_export_dir, EXPORTED_SQUASHED_IMAGE_NAME) if export_failed: raise subprocess.CalledProcessError(returncode=1, cmd=args, output="Failed") return '' else: args_expect = ['bsi', '-d'] drivers = [] if sources_dir and sources_dir_exists: drivers.append('sourcedriver_rpm_dir') if remote_dir and remote_dir_exists: drivers.append('sourcedriver_extra_src_dir') args_expect.append(','.join(drivers)) if sources_dir and sources_dir_exists: args_expect.append('-s') args_expect.append(sources_dir_path) if remote_dir and remote_dir_exists: args_expect.append('-e') args_expect.append(remote_dir_path) args_expect.append('-o') args_expect.append(temp_image_output_dir) assert args == args_expect return 'stub stdout' check_output_times = 2 if not sources_dir_exists and not remote_dir_exists: check_output_times = 0 (flexmock(subprocess) .should_receive("check_output") .times(check_output_times) .replace_with(check_check_output)) blob_sha = "f568c411849e21aa3917973f1c5b120f6b52fe69b1944dfb977bc11bed6fbb6d" index_json = {"schemaVersion": 2, "manifests": [{"mediaType": "application/vnd.oci.image.manifest.v1+json", "digest": "sha256:%s" % blob_sha, "size": 645, "annotations": {"org.opencontainers.image.ref.name": "latest-source"}, "platform": {"architecture": "amd64", "os": "linux"}}]} blob_json = {"schemaVersion": 2, "layers": []} with open(os.path.join(temp_image_output_dir, 'index.json'), 'w') as fp: fp.write(json.dumps(index_json)) with open(os.path.join(temp_image_output_dir, 'blobs', 'sha256', blob_sha), 'w') as fp: fp.write(json.dumps(blob_json)) if not export_failed: export_tar = os.path.join(temp_image_export_dir, EXPORTED_SQUASHED_IMAGE_NAME) with open(export_tar, "wb") as f: with tarfile.TarFile(mode="w", fileobj=f) as tf: for f in os.listdir(temp_image_output_dir): tf.add(os.path.join(temp_image_output_dir, f), f) if not sources_dir_exists and not remote_dir_exists: build_result = runner.run() err_msg = "No SRPMs directory '{}' available".format(sources_dir_path) err_msg += "\nNo Remote source directory '{}' available".format(remote_dir_path) # Since Python 3.7 logger adds additional whitespaces by default -> checking without them assert re.sub(r'\s+', " ", err_msg) in re.sub(r'\s+', " ", caplog.text) assert build_result.is_failed() elif export_failed: with pytest.raises(PluginFailedException): runner.run() else: build_result = runner.run() assert not build_result.is_failed() assert build_result.oci_image_path assert 'stub stdout' in caplog.text empty_srpm_msg = "SRPMs directory '{}' is empty".format(sources_dir_path) empty_remote_msg = "Remote source directory '{}' is empty".format(remote_dir_path) if sources_dir_exists and sources_dir_empty: assert empty_srpm_msg in caplog.text else: assert empty_srpm_msg not in caplog.text if remote_dir_exists and remote_dir_empty: assert empty_remote_msg in caplog.text else: assert empty_remote_msg not in caplog.text def test_failed_build(tmpdir, caplog, user_params): """ Test if proper error state is returned when build inside build container failed """ (flexmock(subprocess).should_receive('check_output') .and_raise(subprocess.CalledProcessError(1, 'cmd', output='stub stdout'))) workflow = mock_workflow(tmpdir) mocked_tasker = flexmock(workflow.builder.tasker) mocked_tasker.should_receive('wait').and_return(1) runner = BuildStepPluginsRunner( mocked_tasker, workflow, [{ 'name': SourceContainerPlugin.key, 'args': {}, }] ) build_result = runner.run() assert build_result.is_failed() assert 'BSI failed with output:' in caplog.text assert 'stub stdout' in caplog.text
bsd-3-clause
8,574,303,398,522,537,000
36.518987
99
0.627643
false
ivanhorvath/openshift-tools
openshift/installer/vendored/openshift-ansible-3.6.173.0.59/roles/lib_openshift/library/oc_label.py
7
59170
#!/usr/bin/env python # pylint: disable=missing-docstring # flake8: noqa: T001 # ___ ___ _ _ ___ ___ _ _____ ___ ___ # / __| __| \| | __| _ \ /_\_ _| __| \ # | (_ | _|| .` | _|| / / _ \| | | _|| |) | # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____ # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _| # | |) | (_) | | .` | (_) || | | _|| |) | | | | # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_| # # Copyright 2016 Red Hat, Inc. and/or its affiliates # and other contributors as indicated by the @author tags. # # 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. # # -*- -*- -*- Begin included fragment: lib/import.py -*- -*- -*- ''' OpenShiftCLI class that wraps the oc commands in a subprocess ''' # pylint: disable=too-many-lines from __future__ import print_function import atexit import copy import json import os import re import shutil import subprocess import tempfile # pylint: disable=import-error try: import ruamel.yaml as yaml except ImportError: import yaml from ansible.module_utils.basic import AnsibleModule # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*- # -*- -*- -*- Begin included fragment: doc/label -*- -*- -*- DOCUMENTATION = ''' --- module: oc_label short_description: Create, modify, and idempotently manage openshift labels. description: - Modify openshift labels programmatically. options: state: description: - State controls the action that will be taken with resource - 'present' will create or update and object to the desired state - 'absent' will ensure certain labels are removed - 'list' will read the labels - 'add' will insert labels to the already existing labels default: present choices: ["present", "absent", "list", "add"] aliases: [] kubeconfig: description: - The path for the kubeconfig file to use for authentication required: false default: /etc/origin/master/admin.kubeconfig aliases: [] debug: description: - Turn on debug output. required: false default: False aliases: [] kind: description: - The kind of object that can be managed. default: node choices: - node - pod - namespace aliases: [] labels: description: - A list of labels for the resource. - Each list consists of a key and a value. - eg, {'key': 'foo', 'value': 'bar'} required: false default: None aliases: [] selector: description: - The selector to apply to the resource query required: false default: None aliases: [] author: - "Joel Diaz <jdiaz@redhat.com>" extends_documentation_fragment: [] ''' EXAMPLES = ''' - name: Add a single label to a node's existing labels oc_label: name: ip-172-31-5-23.ec2.internal state: add kind: node labels: - key: logging-infra-fluentd value: 'true' - name: remove a label from a node oc_label: name: ip-172-31-5-23.ec2.internal state: absent kind: node labels: - key: color value: blue - name: Ensure node has these exact labels oc_label: name: ip-172-31-5-23.ec2.internal state: present kind: node labels: - key: color value: green - key: type value: master - key: environment value: production ''' # -*- -*- -*- End included fragment: doc/label -*- -*- -*- # -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*- class YeditException(Exception): # pragma: no cover ''' Exception class for Yedit ''' pass # pylint: disable=too-many-public-methods class Yedit(object): # pragma: no cover ''' Class to modify yaml files ''' re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$" re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z{}/_-]+)" com_sep = set(['.', '#', '|', ':']) # pylint: disable=too-many-arguments def __init__(self, filename=None, content=None, content_type='yaml', separator='.', backup=False): self.content = content self._separator = separator self.filename = filename self.__yaml_dict = content self.content_type = content_type self.backup = backup self.load(content_type=self.content_type) if self.__yaml_dict is None: self.__yaml_dict = {} @property def separator(self): ''' getter method for separator ''' return self._separator @separator.setter def separator(self, inc_sep): ''' setter method for separator ''' self._separator = inc_sep @property def yaml_dict(self): ''' getter method for yaml_dict ''' return self.__yaml_dict @yaml_dict.setter def yaml_dict(self, value): ''' setter method for yaml_dict ''' self.__yaml_dict = value @staticmethod def parse_key(key, sep='.'): '''parse the key allowing the appropriate separator''' common_separators = list(Yedit.com_sep - set([sep])) return re.findall(Yedit.re_key.format(''.join(common_separators)), key) @staticmethod def valid_key(key, sep='.'): '''validate the incoming key''' common_separators = list(Yedit.com_sep - set([sep])) if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key): return False return True @staticmethod def remove_entry(data, key, sep='.'): ''' remove data at location key ''' if key == '' and isinstance(data, dict): data.clear() return True elif key == '' and isinstance(data, list): del data[:] return True if not (key and Yedit.valid_key(key, sep)) and \ isinstance(data, (list, dict)): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes[:-1]: if dict_key and isinstance(data, dict): data = data.get(dict_key) elif (arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1): data = data[int(arr_ind)] else: return None # process last index for remove # expected list entry if key_indexes[-1][0]: if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501 del data[int(key_indexes[-1][0])] return True # expected dict entry elif key_indexes[-1][1]: if isinstance(data, dict): del data[key_indexes[-1][1]] return True @staticmethod def add_entry(data, key, item=None, sep='.'): ''' Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a#b return c ''' if key == '': pass elif (not (key and Yedit.valid_key(key, sep)) and isinstance(data, (list, dict))): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes[:-1]: if dict_key: if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501 data = data[dict_key] continue elif data and not isinstance(data, dict): raise YeditException("Unexpected item type found while going through key " + "path: {} (at key: {})".format(key, dict_key)) data[dict_key] = {} data = data[dict_key] elif (arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1): data = data[int(arr_ind)] else: raise YeditException("Unexpected item type found while going through key path: {}".format(key)) if key == '': data = item # process last index for add # expected list entry elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501 data[int(key_indexes[-1][0])] = item # expected dict entry elif key_indexes[-1][1] and isinstance(data, dict): data[key_indexes[-1][1]] = item # didn't add/update to an existing list, nor add/update key to a dict # so we must have been provided some syntax like a.b.c[<int>] = "data" for a # non-existent array else: raise YeditException("Error adding to object at path: {}".format(key)) return data @staticmethod def get_entry(data, key, sep='.'): ''' Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a.b return c ''' if key == '': pass elif (not (key and Yedit.valid_key(key, sep)) and isinstance(data, (list, dict))): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes: if dict_key and isinstance(data, dict): data = data.get(dict_key) elif (arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1): data = data[int(arr_ind)] else: return None return data @staticmethod def _write(filename, contents): ''' Actually write the file contents to disk. This helps with mocking. ''' tmp_filename = filename + '.yedit' with open(tmp_filename, 'w') as yfd: yfd.write(contents) os.rename(tmp_filename, filename) def write(self): ''' write to file ''' if not self.filename: raise YeditException('Please specify a filename.') if self.backup and self.file_exists(): shutil.copy(self.filename, self.filename + '.orig') # Try to set format attributes if supported try: self.yaml_dict.fa.set_block_style() except AttributeError: pass # Try to use RoundTripDumper if supported. try: Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper)) except AttributeError: Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False)) return (True, self.yaml_dict) def read(self): ''' read from file ''' # check if it exists if self.filename is None or not self.file_exists(): return None contents = None with open(self.filename) as yfd: contents = yfd.read() return contents def file_exists(self): ''' return whether file exists ''' if os.path.exists(self.filename): return True return False def load(self, content_type='yaml'): ''' return yaml file ''' contents = self.read() if not contents and not self.content: return None if self.content: if isinstance(self.content, dict): self.yaml_dict = self.content return self.yaml_dict elif isinstance(self.content, str): contents = self.content # check if it is yaml try: if content_type == 'yaml' and contents: # Try to set format attributes if supported try: self.yaml_dict.fa.set_block_style() except AttributeError: pass # Try to use RoundTripLoader if supported. try: self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader) except AttributeError: self.yaml_dict = yaml.safe_load(contents) # Try to set format attributes if supported try: self.yaml_dict.fa.set_block_style() except AttributeError: pass elif content_type == 'json' and contents: self.yaml_dict = json.loads(contents) except yaml.YAMLError as err: # Error loading yaml or json raise YeditException('Problem with loading yaml file. {}'.format(err)) return self.yaml_dict def get(self, key): ''' get a specified key''' try: entry = Yedit.get_entry(self.yaml_dict, key, self.separator) except KeyError: entry = None return entry def pop(self, path, key_or_item): ''' remove a key, value pair from a dict or an item for a list''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if entry is None: return (False, self.yaml_dict) if isinstance(entry, dict): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member if key_or_item in entry: entry.pop(key_or_item) return (True, self.yaml_dict) return (False, self.yaml_dict) elif isinstance(entry, list): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member ind = None try: ind = entry.index(key_or_item) except ValueError: return (False, self.yaml_dict) entry.pop(ind) return (True, self.yaml_dict) return (False, self.yaml_dict) def delete(self, path): ''' remove path from a dict''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if entry is None: return (False, self.yaml_dict) result = Yedit.remove_entry(self.yaml_dict, path, self.separator) if not result: return (False, self.yaml_dict) return (True, self.yaml_dict) def exists(self, path, value): ''' check if value exists at path''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if isinstance(entry, list): if value in entry: return True return False elif isinstance(entry, dict): if isinstance(value, dict): rval = False for key, val in value.items(): if entry[key] != val: rval = False break else: rval = True return rval return value in entry return entry == value def append(self, path, value): '''append value to a list''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if entry is None: self.put(path, []) entry = Yedit.get_entry(self.yaml_dict, path, self.separator) if not isinstance(entry, list): return (False, self.yaml_dict) # AUDIT:maybe-no-member makes sense due to loading data from # a serialized format. # pylint: disable=maybe-no-member entry.append(value) return (True, self.yaml_dict) # pylint: disable=too-many-arguments def update(self, path, value, index=None, curr_value=None): ''' put path, value into a dict ''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if isinstance(entry, dict): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member if not isinstance(value, dict): raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' + 'value=[{}] type=[{}]'.format(value, type(value))) entry.update(value) return (True, self.yaml_dict) elif isinstance(entry, list): # AUDIT:maybe-no-member makes sense due to fuzzy types # pylint: disable=maybe-no-member ind = None if curr_value: try: ind = entry.index(curr_value) except ValueError: return (False, self.yaml_dict) elif index is not None: ind = index if ind is not None and entry[ind] != value: entry[ind] = value return (True, self.yaml_dict) # see if it exists in the list try: ind = entry.index(value) except ValueError: # doesn't exist, append it entry.append(value) return (True, self.yaml_dict) # already exists, return if ind is not None: return (False, self.yaml_dict) return (False, self.yaml_dict) def put(self, path, value): ''' put path, value into a dict ''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError: entry = None if entry == value: return (False, self.yaml_dict) # deepcopy didn't work # Try to use ruamel.yaml and fallback to pyyaml try: tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader) except AttributeError: tmp_copy = copy.deepcopy(self.yaml_dict) # set the format attributes if available try: tmp_copy.fa.set_block_style() except AttributeError: pass result = Yedit.add_entry(tmp_copy, path, value, self.separator) if result is None: return (False, self.yaml_dict) # When path equals "" it is a special case. # "" refers to the root of the document # Only update the root path (entire document) when its a list or dict if path == '': if isinstance(result, list) or isinstance(result, dict): self.yaml_dict = result return (True, self.yaml_dict) return (False, self.yaml_dict) self.yaml_dict = tmp_copy return (True, self.yaml_dict) def create(self, path, value): ''' create a yaml file ''' if not self.file_exists(): # deepcopy didn't work # Try to use ruamel.yaml and fallback to pyyaml try: tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader) except AttributeError: tmp_copy = copy.deepcopy(self.yaml_dict) # set the format attributes if available try: tmp_copy.fa.set_block_style() except AttributeError: pass result = Yedit.add_entry(tmp_copy, path, value, self.separator) if result is not None: self.yaml_dict = tmp_copy return (True, self.yaml_dict) return (False, self.yaml_dict) @staticmethod def get_curr_value(invalue, val_type): '''return the current value''' if invalue is None: return None curr_value = invalue if val_type == 'yaml': curr_value = yaml.load(invalue) elif val_type == 'json': curr_value = json.loads(invalue) return curr_value @staticmethod def parse_value(inc_value, vtype=''): '''determine value type passed''' true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON', ] false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF'] # It came in as a string but you didn't specify value_type as string # we will convert to bool if it matches any of the above cases if isinstance(inc_value, str) and 'bool' in vtype: if inc_value not in true_bools and inc_value not in false_bools: raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype)) elif isinstance(inc_value, bool) and 'str' in vtype: inc_value = str(inc_value) # There is a special case where '' will turn into None after yaml loading it so skip if isinstance(inc_value, str) and inc_value == '': pass # If vtype is not str then go ahead and attempt to yaml load it. elif isinstance(inc_value, str) and 'str' not in vtype: try: inc_value = yaml.safe_load(inc_value) except Exception: raise YeditException('Could not determine type of incoming value. ' + 'value=[{}] vtype=[{}]'.format(type(inc_value), vtype)) return inc_value @staticmethod def process_edits(edits, yamlfile): '''run through a list of edits and process them one-by-one''' results = [] for edit in edits: value = Yedit.parse_value(edit['value'], edit.get('value_type', '')) if edit.get('action') == 'update': # pylint: disable=line-too-long curr_value = Yedit.get_curr_value( Yedit.parse_value(edit.get('curr_value')), edit.get('curr_value_format')) rval = yamlfile.update(edit['key'], value, edit.get('index'), curr_value) elif edit.get('action') == 'append': rval = yamlfile.append(edit['key'], value) else: rval = yamlfile.put(edit['key'], value) if rval[0]: results.append({'key': edit['key'], 'edit': rval[1]}) return {'changed': len(results) > 0, 'results': results} # pylint: disable=too-many-return-statements,too-many-branches @staticmethod def run_ansible(params): '''perform the idempotent crud operations''' yamlfile = Yedit(filename=params['src'], backup=params['backup'], separator=params['separator']) state = params['state'] if params['src']: rval = yamlfile.load() if yamlfile.yaml_dict is None and state != 'present': return {'failed': True, 'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) + 'file exists, that it is has correct permissions, and is valid yaml.'} if state == 'list': if params['content']: content = Yedit.parse_value(params['content'], params['content_type']) yamlfile.yaml_dict = content if params['key']: rval = yamlfile.get(params['key']) or {} return {'changed': False, 'result': rval, 'state': state} elif state == 'absent': if params['content']: content = Yedit.parse_value(params['content'], params['content_type']) yamlfile.yaml_dict = content if params['update']: rval = yamlfile.pop(params['key'], params['value']) else: rval = yamlfile.delete(params['key']) if rval[0] and params['src']: yamlfile.write() return {'changed': rval[0], 'result': rval[1], 'state': state} elif state == 'present': # check if content is different than what is in the file if params['content']: content = Yedit.parse_value(params['content'], params['content_type']) # We had no edits to make and the contents are the same if yamlfile.yaml_dict == content and \ params['value'] is None: return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state} yamlfile.yaml_dict = content # If we were passed a key, value then # we enapsulate it in a list and process it # Key, Value passed to the module : Converted to Edits list # edits = [] _edit = {} if params['value'] is not None: _edit['value'] = params['value'] _edit['value_type'] = params['value_type'] _edit['key'] = params['key'] if params['update']: _edit['action'] = 'update' _edit['curr_value'] = params['curr_value'] _edit['curr_value_format'] = params['curr_value_format'] _edit['index'] = params['index'] elif params['append']: _edit['action'] = 'append' edits.append(_edit) elif params['edits'] is not None: edits = params['edits'] if edits: results = Yedit.process_edits(edits, yamlfile) # if there were changes and a src provided to us we need to write if results['changed'] and params['src']: yamlfile.write() return {'changed': results['changed'], 'result': results['results'], 'state': state} # no edits to make if params['src']: # pylint: disable=redefined-variable-type rval = yamlfile.write() return {'changed': rval[0], 'result': rval[1], 'state': state} # We were passed content but no src, key or value, or edits. Return contents in memory return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state} return {'failed': True, 'msg': 'Unkown state passed'} # -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*- # -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*- # pylint: disable=too-many-lines # noqa: E301,E302,E303,T001 class OpenShiftCLIError(Exception): '''Exception class for openshiftcli''' pass ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')] def locate_oc_binary(): ''' Find and return oc binary file ''' # https://github.com/openshift/openshift-ansible/issues/3410 # oc can be in /usr/local/bin in some cases, but that may not # be in $PATH due to ansible/sudo paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS oc_binary = 'oc' # Use shutil.which if it is available, otherwise fallback to a naive path search try: which_result = shutil.which(oc_binary, path=os.pathsep.join(paths)) if which_result is not None: oc_binary = which_result except AttributeError: for path in paths: if os.path.exists(os.path.join(path, oc_binary)): oc_binary = os.path.join(path, oc_binary) break return oc_binary # pylint: disable=too-few-public-methods class OpenShiftCLI(object): ''' Class to wrap the command line tools ''' def __init__(self, namespace, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False, all_namespaces=False): ''' Constructor for OpenshiftCLI ''' self.namespace = namespace self.verbose = verbose self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig) self.all_namespaces = all_namespaces self.oc_binary = locate_oc_binary() # Pylint allows only 5 arguments to be passed. # pylint: disable=too-many-arguments def _replace_content(self, resource, rname, content, force=False, sep='.'): ''' replace the current object with the content ''' res = self._get(resource, rname) if not res['results']: return res fname = Utils.create_tmpfile(rname + '-') yed = Yedit(fname, res['results'][0], separator=sep) changes = [] for key, value in content.items(): changes.append(yed.put(key, value)) if any([change[0] for change in changes]): yed.write() atexit.register(Utils.cleanup, [fname]) return self._replace(fname, force) return {'returncode': 0, 'updated': False} def _replace(self, fname, force=False): '''replace the current object with oc replace''' # We are removing the 'resourceVersion' to handle # a race condition when modifying oc objects yed = Yedit(fname) results = yed.delete('metadata.resourceVersion') if results[0]: yed.write() cmd = ['replace', '-f', fname] if force: cmd.append('--force') return self.openshift_cmd(cmd) def _create_from_content(self, rname, content): '''create a temporary file and then call oc create on it''' fname = Utils.create_tmpfile(rname + '-') yed = Yedit(fname, content=content) yed.write() atexit.register(Utils.cleanup, [fname]) return self._create(fname) def _create(self, fname): '''call oc create on a filename''' return self.openshift_cmd(['create', '-f', fname]) def _delete(self, resource, name=None, selector=None): '''call oc delete on a resource''' cmd = ['delete', resource] if selector is not None: cmd.append('--selector={}'.format(selector)) elif name is not None: cmd.append(name) else: raise OpenShiftCLIError('Either name or selector is required when calling delete.') return self.openshift_cmd(cmd) def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501 '''process a template template_name: the name of the template to process create: whether to send to oc create after processing params: the parameters for the template template_data: the incoming template's data; instead of a file ''' cmd = ['process'] if template_data: cmd.extend(['-f', '-']) else: cmd.append(template_name) if params: param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()] cmd.append('-v') cmd.extend(param_str) results = self.openshift_cmd(cmd, output=True, input_data=template_data) if results['returncode'] != 0 or not create: return results fname = Utils.create_tmpfile(template_name + '-') yed = Yedit(fname, results['results']) yed.write() atexit.register(Utils.cleanup, [fname]) return self.openshift_cmd(['create', '-f', fname]) def _get(self, resource, name=None, selector=None): '''return a resource by name ''' cmd = ['get', resource] if selector is not None: cmd.append('--selector={}'.format(selector)) elif name is not None: cmd.append(name) cmd.extend(['-o', 'json']) rval = self.openshift_cmd(cmd, output=True) # Ensure results are retuned in an array if 'items' in rval: rval['results'] = rval['items'] elif not isinstance(rval['results'], list): rval['results'] = [rval['results']] return rval def _schedulable(self, node=None, selector=None, schedulable=True): ''' perform oadm manage-node scheduable ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) cmd.append('--schedulable={}'.format(schedulable)) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501 def _list_pods(self, node=None, selector=None, pod_selector=None): ''' perform oadm list pods node: the node in which to list pods selector: the label selector filter if provided pod_selector: the pod selector filter if provided ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) if pod_selector: cmd.append('--pod-selector={}'.format(pod_selector)) cmd.extend(['--list-pods', '-o', 'json']) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # pylint: disable=too-many-arguments def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False): ''' perform oadm manage-node evacuate ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) if dry_run: cmd.append('--dry-run') if pod_selector: cmd.append('--pod-selector={}'.format(pod_selector)) if grace_period: cmd.append('--grace-period={}'.format(int(grace_period))) if force: cmd.append('--force') cmd.append('--evacuate') return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') def _version(self): ''' return the openshift version''' return self.openshift_cmd(['version'], output=True, output_type='raw') def _import_image(self, url=None, name=None, tag=None): ''' perform image import ''' cmd = ['import-image'] image = '{0}'.format(name) if tag: image += ':{0}'.format(tag) cmd.append(image) if url: cmd.append('--from={0}/{1}'.format(url, image)) cmd.append('-n{0}'.format(self.namespace)) cmd.append('--confirm') return self.openshift_cmd(cmd) def _run(self, cmds, input_data): ''' Actually executes the command. This makes mocking easier. ''' curr_env = os.environ.copy() curr_env.update({'KUBECONFIG': self.kubeconfig}) proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env) stdout, stderr = proc.communicate(input_data) return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8') # pylint: disable=too-many-arguments,too-many-branches def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None): '''Base command for oc ''' cmds = [self.oc_binary] if oadm: cmds.append('adm') cmds.extend(cmd) if self.all_namespaces: cmds.extend(['--all-namespaces']) elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501 cmds.extend(['-n', self.namespace]) if self.verbose: print(' '.join(cmds)) try: returncode, stdout, stderr = self._run(cmds, input_data) except OSError as ex: returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex) rval = {"returncode": returncode, "cmd": ' '.join(cmds)} if output_type == 'json': rval['results'] = {} if output and stdout: try: rval['results'] = json.loads(stdout) except ValueError as verr: if "No JSON object could be decoded" in verr.args: rval['err'] = verr.args elif output_type == 'raw': rval['results'] = stdout if output else '' if self.verbose: print("STDOUT: {0}".format(stdout)) print("STDERR: {0}".format(stderr)) if 'err' in rval or returncode != 0: rval.update({"stderr": stderr, "stdout": stdout}) return rval class Utils(object): # pragma: no cover ''' utilities for openshiftcli modules ''' @staticmethod def _write(filename, contents): ''' Actually write the file contents to disk. This helps with mocking. ''' with open(filename, 'w') as sfd: sfd.write(contents) @staticmethod def create_tmp_file_from_contents(rname, data, ftype='yaml'): ''' create a file in tmp with name and contents''' tmp = Utils.create_tmpfile(prefix=rname) if ftype == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripDumper'): Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper)) else: Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False)) elif ftype == 'json': Utils._write(tmp, json.dumps(data)) else: Utils._write(tmp, data) # Register cleanup when module is done atexit.register(Utils.cleanup, [tmp]) return tmp @staticmethod def create_tmpfile_copy(inc_file): '''create a temporary copy of a file''' tmpfile = Utils.create_tmpfile('lib_openshift-') Utils._write(tmpfile, open(inc_file).read()) # Cleanup the tmpfile atexit.register(Utils.cleanup, [tmpfile]) return tmpfile @staticmethod def create_tmpfile(prefix='tmp'): ''' Generates and returns a temporary file name ''' with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp: return tmp.name @staticmethod def create_tmp_files_from_contents(content, content_type=None): '''Turn an array of dict: filename, content into a files array''' if not isinstance(content, list): content = [content] files = [] for item in content: path = Utils.create_tmp_file_from_contents(item['path'] + '-', item['data'], ftype=content_type) files.append({'name': os.path.basename(item['path']), 'path': path}) return files @staticmethod def cleanup(files): '''Clean up on exit ''' for sfile in files: if os.path.exists(sfile): if os.path.isdir(sfile): shutil.rmtree(sfile) elif os.path.isfile(sfile): os.remove(sfile) @staticmethod def exists(results, _name): ''' Check to see if the results include the name ''' if not results: return False if Utils.find_result(results, _name): return True return False @staticmethod def find_result(results, _name): ''' Find the specified result by name''' rval = None for result in results: if 'metadata' in result and result['metadata']['name'] == _name: rval = result break return rval @staticmethod def get_resource_file(sfile, sfile_type='yaml'): ''' return the service file ''' contents = None with open(sfile) as sfd: contents = sfd.read() if sfile_type == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripLoader'): contents = yaml.load(contents, yaml.RoundTripLoader) else: contents = yaml.safe_load(contents) elif sfile_type == 'json': contents = json.loads(contents) return contents @staticmethod def filter_versions(stdout): ''' filter the oc version output ''' version_dict = {} version_search = ['oc', 'openshift', 'kubernetes'] for line in stdout.strip().split('\n'): for term in version_search: if not line: continue if line.startswith(term): version_dict[term] = line.split()[-1] # horrible hack to get openshift version in Openshift 3.2 # By default "oc version in 3.2 does not return an "openshift" version if "openshift" not in version_dict: version_dict["openshift"] = version_dict["oc"] return version_dict @staticmethod def add_custom_versions(versions): ''' create custom versions strings ''' versions_dict = {} for tech, version in versions.items(): # clean up "-" from version if "-" in version: version = version.split("-")[0] if version.startswith('v'): versions_dict[tech + '_numeric'] = version[1:].split('+')[0] # "v3.3.0.33" is what we have, we want "3.3" versions_dict[tech + '_short'] = version[1:4] return versions_dict @staticmethod def openshift_installed(): ''' check if openshift is installed ''' import rpm transaction_set = rpm.TransactionSet() rpmquery = transaction_set.dbMatch("name", "atomic-openshift") return rpmquery.count() > 0 # Disabling too-many-branches. This is a yaml dictionary comparison function # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements @staticmethod def check_def_equal(user_def, result_def, skip_keys=None, debug=False): ''' Given a user defined definition, compare it with the results given back by our query. ''' # Currently these values are autogenerated and we do not need to check them skip = ['metadata', 'status'] if skip_keys: skip.extend(skip_keys) for key, value in result_def.items(): if key in skip: continue # Both are lists if isinstance(value, list): if key not in user_def: if debug: print('User data does not have key [%s]' % key) print('User data: %s' % user_def) return False if not isinstance(user_def[key], list): if debug: print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key])) return False if len(user_def[key]) != len(value): if debug: print("List lengths are not equal.") print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value))) print("user_def: %s" % user_def[key]) print("value: %s" % value) return False for values in zip(user_def[key], value): if isinstance(values[0], dict) and isinstance(values[1], dict): if debug: print('sending list - list') print(type(values[0])) print(type(values[1])) result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug) if not result: print('list compare returned false') return False elif value != user_def[key]: if debug: print('value should be identical') print(user_def[key]) print(value) return False # recurse on a dictionary elif isinstance(value, dict): if key not in user_def: if debug: print("user_def does not have key [%s]" % key) return False if not isinstance(user_def[key], dict): if debug: print("dict returned false: not instance of dict") return False # before passing ensure keys match api_values = set(value.keys()) - set(skip) user_values = set(user_def[key].keys()) - set(skip) if api_values != user_values: if debug: print("keys are not equal in dict") print(user_values) print(api_values) return False result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug) if not result: if debug: print("dict returned false") print(result) return False # Verify each key, value pair is the same else: if key not in user_def or value != user_def[key]: if debug: print("value not equal; user_def does not have key") print(key) print(value) if key in user_def: print(user_def[key]) return False if debug: print('returning true') return True class OpenShiftCLIConfig(object): '''Generic Config''' def __init__(self, rname, namespace, kubeconfig, options): self.kubeconfig = kubeconfig self.name = rname self.namespace = namespace self._options = options @property def config_options(self): ''' return config options ''' return self._options def to_option_list(self, ascommalist=''): '''return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs''' return self.stringify(ascommalist) def stringify(self, ascommalist=''): ''' return the options hash as cli params in a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs ''' rval = [] for key in sorted(self.config_options.keys()): data = self.config_options[key] if data['include'] \ and (data['value'] or isinstance(data['value'], int)): if key == ascommalist: val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())]) else: val = data['value'] rval.append('--{}={}'.format(key.replace('_', '-'), val)) return rval # -*- -*- -*- End included fragment: lib/base.py -*- -*- -*- # -*- -*- -*- Begin included fragment: class/oc_label.py -*- -*- -*- # pylint: disable=too-many-instance-attributes class OCLabel(OpenShiftCLI): ''' Class to wrap the oc command line tools ''' # pylint allows 5 # pylint: disable=too-many-arguments def __init__(self, name, namespace, kind, kubeconfig, labels=None, selector=None, verbose=False): ''' Constructor for OCLabel ''' super(OCLabel, self).__init__(namespace, kubeconfig=kubeconfig, verbose=verbose) self.name = name self.kind = kind self.labels = labels self._curr_labels = None self.selector = selector @property def current_labels(self): '''property for the current labels''' if self._curr_labels is None: results = self.get() self._curr_labels = results['labels'] return self._curr_labels @current_labels.setter def current_labels(self, data): '''property setter for current labels''' self._curr_labels = data def compare_labels(self, host_labels): ''' compare incoming labels against current labels''' for label in self.labels: if label['key'] not in host_labels or \ label['value'] != host_labels[label['key']]: return False return True def all_user_labels_exist(self): ''' return whether all the labels already exist ''' for current_host_labels in self.current_labels: rbool = self.compare_labels(current_host_labels) if not rbool: return False return True def any_label_exists(self): ''' return whether any single label already exists ''' for current_host_labels in self.current_labels: for label in self.labels: if label['key'] in current_host_labels: return True return False def get_user_keys(self): ''' go through list of user key:values and return all keys ''' user_keys = [] for label in self.labels: user_keys.append(label['key']) return user_keys def get_current_label_keys(self): ''' collect all the current label keys ''' current_label_keys = [] for current_host_labels in self.current_labels: for key in current_host_labels.keys(): current_label_keys.append(key) return list(set(current_label_keys)) def get_extra_current_labels(self): ''' return list of labels that are currently stored, but aren't in user-provided list ''' extra_labels = [] user_label_keys = self.get_user_keys() current_label_keys = self.get_current_label_keys() for current_key in current_label_keys: if current_key not in user_label_keys: extra_labels.append(current_key) return extra_labels def extra_current_labels(self): ''' return whether there are labels currently stored that user hasn't directly provided ''' extra_labels = self.get_extra_current_labels() if len(extra_labels) > 0: return True return False def replace(self): ''' replace currently stored labels with user provided labels ''' cmd = self.cmd_template() # First delete any extra labels extra_labels = self.get_extra_current_labels() if len(extra_labels) > 0: for label in extra_labels: cmd.append("{}-".format(label)) # Now add/modify the user-provided label list if len(self.labels) > 0: for label in self.labels: cmd.append("{}={}".format(label['key'], label['value'])) # --overwrite for the case where we are updating existing labels cmd.append("--overwrite") return self.openshift_cmd(cmd) def get(self): '''return label information ''' result_dict = {} label_list = [] if self.name: result = self._get(resource=self.kind, name=self.name, selector=self.selector) if result['results'][0] and 'labels' in result['results'][0]['metadata']: label_list.append(result['results'][0]['metadata']['labels']) else: label_list.append({}) else: result = self._get(resource=self.kind, selector=self.selector) for item in result['results'][0]['items']: if 'labels' in item['metadata']: label_list.append(item['metadata']['labels']) else: label_list.append({}) self.current_labels = label_list result_dict['labels'] = self.current_labels result_dict['item_count'] = len(self.current_labels) result['results'] = result_dict return result def cmd_template(self): ''' boilerplate oc command for modifying lables on this object ''' # let's build the cmd with what we have passed in cmd = ["label", self.kind] if self.selector: cmd.extend(["--selector", self.selector]) elif self.name: cmd.extend([self.name]) return cmd def add(self): ''' add labels ''' cmd = self.cmd_template() for label in self.labels: cmd.append("{}={}".format(label['key'], label['value'])) cmd.append("--overwrite") return self.openshift_cmd(cmd) def delete(self): '''delete the labels''' cmd = self.cmd_template() for label in self.labels: cmd.append("{}-".format(label['key'])) return self.openshift_cmd(cmd) # pylint: disable=too-many-branches,too-many-return-statements @staticmethod def run_ansible(params, check_mode=False): ''' run the idempotent ansible code prams comes from the ansible portion of this module check_mode: does the module support check mode. (module.check_mode) ''' oc_label = OCLabel(params['name'], params['namespace'], params['kind'], params['kubeconfig'], params['labels'], params['selector'], verbose=params['debug']) state = params['state'] name = params['name'] selector = params['selector'] api_rval = oc_label.get() ##### # Get ##### if state == 'list': return {'changed': False, 'results': api_rval['results'], 'state': "list"} ####### # Add ####### if state == 'add': if not (name or selector): return {'failed': True, 'msg': "Param 'name' or 'selector' is required if state == 'add'"} if not oc_label.all_user_labels_exist(): if check_mode: return {'changed': False, 'msg': 'Would have performed an addition.'} api_rval = oc_label.add() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} return {'changed': True, 'results': api_rval, 'state': "add"} return {'changed': False, 'state': "add"} ######## # Delete ######## if state == 'absent': if not (name or selector): return {'failed': True, 'msg': "Param 'name' or 'selector' is required if state == 'absent'"} if oc_label.any_label_exists(): if check_mode: return {'changed': False, 'msg': 'Would have performed a delete.'} api_rval = oc_label.delete() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} return {'changed': True, 'results': api_rval, 'state': "absent"} return {'changed': False, 'state': "absent"} if state == 'present': ######## # Update ######## if not (name or selector): return {'failed': True, 'msg': "Param 'name' or 'selector' is required if state == 'present'"} # if all the labels passed in don't already exist # or if there are currently stored labels that haven't # been passed in if not oc_label.all_user_labels_exist() or \ oc_label.extra_current_labels(): if check_mode: return {'changed': False, 'msg': 'Would have made changes.'} api_rval = oc_label.replace() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} # return the created object api_rval = oc_label.get() if api_rval['returncode'] != 0: return {'failed': True, 'msg': api_rval} return {'changed': True, 'results': api_rval, 'state': "present"} return {'changed': False, 'results': api_rval, 'state': "present"} return {'failed': True, 'changed': False, 'results': 'Unknown state passed. %s' % state, 'state': "unknown"} # -*- -*- -*- End included fragment: class/oc_label.py -*- -*- -*- # -*- -*- -*- Begin included fragment: ansible/oc_label.py -*- -*- -*- def main(): ''' ansible oc module for labels ''' module = AnsibleModule( argument_spec=dict( kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), state=dict(default='present', type='str', choices=['present', 'absent', 'list', 'add']), debug=dict(default=False, type='bool'), kind=dict(default='node', type='str', choices=['node', 'pod', 'namespace']), name=dict(default=None, type='str'), namespace=dict(default=None, type='str'), labels=dict(default=None, type='list'), selector=dict(default=None, type='str'), ), supports_check_mode=True, mutually_exclusive=(['name', 'selector']), ) results = OCLabel.run_ansible(module.params, module.check_mode) if 'failed' in results: module.fail_json(**results) module.exit_json(**results) if __name__ == '__main__': main() # -*- -*- -*- End included fragment: ansible/oc_label.py -*- -*- -*-
apache-2.0
1,205,464,759,380,454,100
32.772831
118
0.530201
false
apache/spark
python/pyspark/sql/functions.py
14
161861
# # 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. # """ A collections of builtin functions """ import sys import functools import warnings from pyspark import since, SparkContext from pyspark.rdd import PythonEvalType from pyspark.sql.column import Column, _to_java_column, _to_seq, _create_column_from_literal from pyspark.sql.dataframe import DataFrame from pyspark.sql.types import StringType, DataType # Keep UserDefinedFunction import for backwards compatible import; moved in SPARK-22409 from pyspark.sql.udf import UserDefinedFunction, _create_udf # noqa: F401 from pyspark.sql.udf import _create_udf # Keep pandas_udf and PandasUDFType import for backwards compatible import; moved in SPARK-28264 from pyspark.sql.pandas.functions import pandas_udf, PandasUDFType # noqa: F401 from pyspark.sql.utils import to_str # Note to developers: all of PySpark functions here take string as column names whenever possible. # Namely, if columns are referred as arguments, they can be always both Column or string, # even though there might be few exceptions for legacy or inevitable reasons. # If you are fixing other language APIs together, also please note that Scala side is not the case # since it requires to make every single overridden definition. def _get_get_jvm_function(name, sc): """ Retrieves JVM function identified by name from Java gateway associated with sc. """ return getattr(sc._jvm.functions, name) def _invoke_function(name, *args): """ Invokes JVM function identified by name with args and wraps the result with :class:`~pyspark.sql.Column`. """ jf = _get_get_jvm_function(name, SparkContext._active_spark_context) return Column(jf(*args)) def _invoke_function_over_column(name, col): """ Invokes unary JVM function identified by name and wraps the result with :class:`~pyspark.sql.Column`. """ return _invoke_function(name, _to_java_column(col)) def _invoke_binary_math_function(name, col1, col2): """ Invokes binary JVM math function identified by name and wraps the result with :class:`~pyspark.sql.Column`. """ return _invoke_function( name, # For legacy reasons, the arguments here can be implicitly converted into floats, # if they are not columns or strings. _to_java_column(col1) if isinstance(col1, (str, Column)) else float(col1), _to_java_column(col2) if isinstance(col2, (str, Column)) else float(col2) ) def _options_to_str(options=None): if options: return {key: to_str(value) for (key, value) in options.items()} return {} def lit(col): """ Creates a :class:`~pyspark.sql.Column` of literal value. .. versionadded:: 1.3.0 Examples -------- >>> df.select(lit(5).alias('height')).withColumn('spark_user', lit(True)).take(1) [Row(height=5, spark_user=True)] """ return col if isinstance(col, Column) else _invoke_function("lit", col) @since(1.3) def col(col): """ Returns a :class:`~pyspark.sql.Column` based on the given column name.' Examples -------- >>> col('x') Column<'x'> >>> column('x') Column<'x'> """ return _invoke_function("col", col) column = col @since(1.3) def asc(col): """ Returns a sort expression based on the ascending order of the given column name. """ return ( col.asc() if isinstance(col, Column) else _invoke_function("asc", col) ) @since(1.3) def desc(col): """ Returns a sort expression based on the descending order of the given column name. """ return ( col.desc() if isinstance(col, Column) else _invoke_function("desc", col) ) @since(1.3) def sqrt(col): """ Computes the square root of the specified float value. """ return _invoke_function_over_column("sqrt", col) @since(1.3) def abs(col): """ Computes the absolute value. """ return _invoke_function_over_column("abs", col) @since(1.3) def max(col): """ Aggregate function: returns the maximum value of the expression in a group. """ return _invoke_function_over_column("max", col) @since(1.3) def min(col): """ Aggregate function: returns the minimum value of the expression in a group. """ return _invoke_function_over_column("min", col) @since(1.3) def count(col): """ Aggregate function: returns the number of items in a group. """ return _invoke_function_over_column("count", col) @since(1.3) def sum(col): """ Aggregate function: returns the sum of all values in the expression. """ return _invoke_function_over_column("sum", col) @since(1.3) def avg(col): """ Aggregate function: returns the average of the values in a group. """ return _invoke_function_over_column("avg", col) @since(1.3) def mean(col): """ Aggregate function: returns the average of the values in a group. """ return _invoke_function_over_column("mean", col) @since(1.3) def sumDistinct(col): """ Aggregate function: returns the sum of distinct values in the expression. .. deprecated:: 3.2.0 Use :func:`sum_distinct` instead. """ warnings.warn("Deprecated in 3.2, use sum_distinct instead.", FutureWarning) return sum_distinct(col) @since(3.2) def sum_distinct(col): """ Aggregate function: returns the sum of distinct values in the expression. """ return _invoke_function_over_column("sum_distinct", col) def product(col): """ Aggregate function: returns the product of the values in a group. .. versionadded:: 3.2.0 Parameters ---------- col : str, :class:`Column` column containing values to be multiplied together Examples -------- >>> df = spark.range(1, 10).toDF('x').withColumn('mod3', col('x') % 3) >>> prods = df.groupBy('mod3').agg(product('x').alias('product')) >>> prods.orderBy('mod3').show() +----+-------+ |mod3|product| +----+-------+ | 0| 162.0| | 1| 28.0| | 2| 80.0| +----+-------+ """ return _invoke_function_over_column("product", col) def acos(col): """ .. versionadded:: 1.4.0 Returns ------- :class:`~pyspark.sql.Column` inverse cosine of `col`, as if computed by `java.lang.Math.acos()` """ return _invoke_function_over_column("acos", col) def acosh(col): """ Computes inverse hyperbolic cosine of the input column. .. versionadded:: 3.1.0 Returns ------- :class:`~pyspark.sql.Column` """ return _invoke_function_over_column("acosh", col) def asin(col): """ .. versionadded:: 1.3.0 Returns ------- :class:`~pyspark.sql.Column` inverse sine of `col`, as if computed by `java.lang.Math.asin()` """ return _invoke_function_over_column("asin", col) def asinh(col): """ Computes inverse hyperbolic sine of the input column. .. versionadded:: 3.1.0 Returns ------- :class:`~pyspark.sql.Column` """ return _invoke_function_over_column("asinh", col) def atan(col): """ .. versionadded:: 1.4.0 Returns ------- :class:`~pyspark.sql.Column` inverse tangent of `col`, as if computed by `java.lang.Math.atan()` """ return _invoke_function_over_column("atan", col) def atanh(col): """ Computes inverse hyperbolic tangent of the input column. .. versionadded:: 3.1.0 Returns ------- :class:`~pyspark.sql.Column` """ return _invoke_function_over_column("atanh", col) @since(1.4) def cbrt(col): """ Computes the cube-root of the given value. """ return _invoke_function_over_column("cbrt", col) @since(1.4) def ceil(col): """ Computes the ceiling of the given value. """ return _invoke_function_over_column("ceil", col) def cos(col): """ .. versionadded:: 1.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str angle in radians Returns ------- :class:`~pyspark.sql.Column` cosine of the angle, as if computed by `java.lang.Math.cos()`. """ return _invoke_function_over_column("cos", col) def cosh(col): """ .. versionadded:: 1.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str hyperbolic angle Returns ------- :class:`~pyspark.sql.Column` hyperbolic cosine of the angle, as if computed by `java.lang.Math.cosh()` """ return _invoke_function_over_column("cosh", col) @since(1.4) def exp(col): """ Computes the exponential of the given value. """ return _invoke_function_over_column("exp", col) @since(1.4) def expm1(col): """ Computes the exponential of the given value minus one. """ return _invoke_function_over_column("expm1", col) @since(1.4) def floor(col): """ Computes the floor of the given value. """ return _invoke_function_over_column("floor", col) @since(1.4) def log(col): """ Computes the natural logarithm of the given value. """ return _invoke_function_over_column("log", col) @since(1.4) def log10(col): """ Computes the logarithm of the given value in Base 10. """ return _invoke_function_over_column("log10", col) @since(1.4) def log1p(col): """ Computes the natural logarithm of the given value plus one. """ return _invoke_function_over_column("log1p", col) @since(1.4) def rint(col): """ Returns the double value that is closest in value to the argument and is equal to a mathematical integer. """ return _invoke_function_over_column("rint", col) @since(1.4) def signum(col): """ Computes the signum of the given value. """ return _invoke_function_over_column("signum", col) def sin(col): """ .. versionadded:: 1.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str Returns ------- :class:`~pyspark.sql.Column` sine of the angle, as if computed by `java.lang.Math.sin()` """ return _invoke_function_over_column("sin", col) def sinh(col): """ .. versionadded:: 1.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str hyperbolic angle Returns ------- :class:`~pyspark.sql.Column` hyperbolic sine of the given value, as if computed by `java.lang.Math.sinh()` """ return _invoke_function_over_column("sinh", col) def tan(col): """ .. versionadded:: 1.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str angle in radians Returns ------- :class:`~pyspark.sql.Column` tangent of the given value, as if computed by `java.lang.Math.tan()` """ return _invoke_function_over_column("tan", col) def tanh(col): """ .. versionadded:: 1.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str hyperbolic angle Returns ------- :class:`~pyspark.sql.Column` hyperbolic tangent of the given value as if computed by `java.lang.Math.tanh()` """ return _invoke_function_over_column("tanh", col) @since(1.4) def toDegrees(col): """ .. deprecated:: 2.1.0 Use :func:`degrees` instead. """ warnings.warn("Deprecated in 2.1, use degrees instead.", FutureWarning) return degrees(col) @since(1.4) def toRadians(col): """ .. deprecated:: 2.1.0 Use :func:`radians` instead. """ warnings.warn("Deprecated in 2.1, use radians instead.", FutureWarning) return radians(col) @since(1.4) def bitwiseNOT(col): """ Computes bitwise not. .. deprecated:: 3.2.0 Use :func:`bitwise_not` instead. """ warnings.warn("Deprecated in 3.2, use bitwise_not instead.", FutureWarning) return bitwise_not(col) @since(3.2) def bitwise_not(col): """ Computes bitwise not. """ return _invoke_function_over_column("bitwise_not", col) @since(2.4) def asc_nulls_first(col): """ Returns a sort expression based on the ascending order of the given column name, and null values return before non-null values. """ return ( col.asc_nulls_first() if isinstance(col, Column) else _invoke_function("asc_nulls_first", col) ) @since(2.4) def asc_nulls_last(col): """ Returns a sort expression based on the ascending order of the given column name, and null values appear after non-null values. """ return ( col.asc_nulls_last() if isinstance(col, Column) else _invoke_function("asc_nulls_last", col) ) @since(2.4) def desc_nulls_first(col): """ Returns a sort expression based on the descending order of the given column name, and null values appear before non-null values. """ return ( col.desc_nulls_first() if isinstance(col, Column) else _invoke_function("desc_nulls_first", col) ) @since(2.4) def desc_nulls_last(col): """ Returns a sort expression based on the descending order of the given column name, and null values appear after non-null values. """ return ( col.desc_nulls_last() if isinstance(col, Column) else _invoke_function("desc_nulls_last", col) ) @since(1.6) def stddev(col): """ Aggregate function: alias for stddev_samp. """ return _invoke_function_over_column("stddev", col) @since(1.6) def stddev_samp(col): """ Aggregate function: returns the unbiased sample standard deviation of the expression in a group. """ return _invoke_function_over_column("stddev_samp", col) @since(1.6) def stddev_pop(col): """ Aggregate function: returns population standard deviation of the expression in a group. """ return _invoke_function_over_column("stddev_pop", col) @since(1.6) def variance(col): """ Aggregate function: alias for var_samp """ return _invoke_function_over_column("variance", col) @since(1.6) def var_samp(col): """ Aggregate function: returns the unbiased sample variance of the values in a group. """ return _invoke_function_over_column("var_samp", col) @since(1.6) def var_pop(col): """ Aggregate function: returns the population variance of the values in a group. """ return _invoke_function_over_column("var_pop", col) @since(1.6) def skewness(col): """ Aggregate function: returns the skewness of the values in a group. """ return _invoke_function_over_column("skewness", col) @since(1.6) def kurtosis(col): """ Aggregate function: returns the kurtosis of the values in a group. """ return _invoke_function_over_column("kurtosis", col) def collect_list(col): """ Aggregate function: returns a list of objects with duplicates. .. versionadded:: 1.6.0 Notes ----- The function is non-deterministic because the order of collected results depends on the order of the rows which may be non-deterministic after a shuffle. Examples -------- >>> df2 = spark.createDataFrame([(2,), (5,), (5,)], ('age',)) >>> df2.agg(collect_list('age')).collect() [Row(collect_list(age)=[2, 5, 5])] """ return _invoke_function_over_column("collect_list", col) def collect_set(col): """ Aggregate function: returns a set of objects with duplicate elements eliminated. .. versionadded:: 1.6.0 Notes ----- The function is non-deterministic because the order of collected results depends on the order of the rows which may be non-deterministic after a shuffle. Examples -------- >>> df2 = spark.createDataFrame([(2,), (5,), (5,)], ('age',)) >>> df2.agg(collect_set('age')).collect() [Row(collect_set(age)=[5, 2])] """ return _invoke_function_over_column("collect_set", col) def degrees(col): """ Converts an angle measured in radians to an approximately equivalent angle measured in degrees. .. versionadded:: 2.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str angle in radians Returns ------- :class:`~pyspark.sql.Column` angle in degrees, as if computed by `java.lang.Math.toDegrees()` """ return _invoke_function_over_column("degrees", col) def radians(col): """ Converts an angle measured in degrees to an approximately equivalent angle measured in radians. .. versionadded:: 2.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str angle in degrees Returns ------- :class:`~pyspark.sql.Column` angle in radians, as if computed by `java.lang.Math.toRadians()` """ return _invoke_function_over_column("radians", col) def atan2(col1, col2): """ .. versionadded:: 1.4.0 Parameters ---------- col1 : str, :class:`~pyspark.sql.Column` or float coordinate on y-axis col2 : str, :class:`~pyspark.sql.Column` or float coordinate on x-axis Returns ------- :class:`~pyspark.sql.Column` the `theta` component of the point (`r`, `theta`) in polar coordinates that corresponds to the point (`x`, `y`) in Cartesian coordinates, as if computed by `java.lang.Math.atan2()` """ return _invoke_binary_math_function("atan2", col1, col2) @since(1.4) def hypot(col1, col2): """ Computes ``sqrt(a^2 + b^2)`` without intermediate overflow or underflow. """ return _invoke_binary_math_function("hypot", col1, col2) @since(1.4) def pow(col1, col2): """ Returns the value of the first argument raised to the power of the second argument. """ return _invoke_binary_math_function("pow", col1, col2) @since(1.6) def row_number(): """ Window function: returns a sequential number starting at 1 within a window partition. """ return _invoke_function("row_number") @since(1.6) def dense_rank(): """ Window function: returns the rank of rows within a window partition, without any gaps. The difference between rank and dense_rank is that dense_rank leaves no gaps in ranking sequence when there are ties. That is, if you were ranking a competition using dense_rank and had three people tie for second place, you would say that all three were in second place and that the next person came in third. Rank would give me sequential numbers, making the person that came in third place (after the ties) would register as coming in fifth. This is equivalent to the DENSE_RANK function in SQL. """ return _invoke_function("dense_rank") @since(1.6) def rank(): """ Window function: returns the rank of rows within a window partition. The difference between rank and dense_rank is that dense_rank leaves no gaps in ranking sequence when there are ties. That is, if you were ranking a competition using dense_rank and had three people tie for second place, you would say that all three were in second place and that the next person came in third. Rank would give me sequential numbers, making the person that came in third place (after the ties) would register as coming in fifth. This is equivalent to the RANK function in SQL. """ return _invoke_function("rank") @since(1.6) def cume_dist(): """ Window function: returns the cumulative distribution of values within a window partition, i.e. the fraction of rows that are below the current row. """ return _invoke_function("cume_dist") @since(1.6) def percent_rank(): """ Window function: returns the relative rank (i.e. percentile) of rows within a window partition. """ return _invoke_function("percent_rank") @since(1.3) def approxCountDistinct(col, rsd=None): """ .. deprecated:: 2.1.0 Use :func:`approx_count_distinct` instead. """ warnings.warn("Deprecated in 2.1, use approx_count_distinct instead.", FutureWarning) return approx_count_distinct(col, rsd) def approx_count_distinct(col, rsd=None): """Aggregate function: returns a new :class:`~pyspark.sql.Column` for approximate distinct count of column `col`. .. versionadded:: 2.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str rsd : float, optional maximum relative standard deviation allowed (default = 0.05). For rsd < 0.01, it is more efficient to use :func:`count_distinct` Examples -------- >>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collect() [Row(distinct_ages=2)] """ sc = SparkContext._active_spark_context if rsd is None: jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col)) else: jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col), rsd) return Column(jc) @since(1.6) def broadcast(df): """Marks a DataFrame as small enough for use in broadcast joins.""" sc = SparkContext._active_spark_context return DataFrame(sc._jvm.functions.broadcast(df._jdf), df.sql_ctx) def coalesce(*cols): """Returns the first column that is not null. .. versionadded:: 1.4.0 Examples -------- >>> cDf = spark.createDataFrame([(None, None), (1, None), (None, 2)], ("a", "b")) >>> cDf.show() +----+----+ | a| b| +----+----+ |null|null| | 1|null| |null| 2| +----+----+ >>> cDf.select(coalesce(cDf["a"], cDf["b"])).show() +--------------+ |coalesce(a, b)| +--------------+ | null| | 1| | 2| +--------------+ >>> cDf.select('*', coalesce(cDf["a"], lit(0.0))).show() +----+----+----------------+ | a| b|coalesce(a, 0.0)| +----+----+----------------+ |null|null| 0.0| | 1|null| 1.0| |null| 2| 0.0| +----+----+----------------+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.coalesce(_to_seq(sc, cols, _to_java_column)) return Column(jc) def corr(col1, col2): """Returns a new :class:`~pyspark.sql.Column` for the Pearson Correlation Coefficient for ``col1`` and ``col2``. .. versionadded:: 1.6.0 Examples -------- >>> a = range(20) >>> b = [2 * x for x in range(20)] >>> df = spark.createDataFrame(zip(a, b), ["a", "b"]) >>> df.agg(corr("a", "b").alias('c')).collect() [Row(c=1.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.corr(_to_java_column(col1), _to_java_column(col2))) def covar_pop(col1, col2): """Returns a new :class:`~pyspark.sql.Column` for the population covariance of ``col1`` and ``col2``. .. versionadded:: 2.0.0 Examples -------- >>> a = [1] * 10 >>> b = [1] * 10 >>> df = spark.createDataFrame(zip(a, b), ["a", "b"]) >>> df.agg(covar_pop("a", "b").alias('c')).collect() [Row(c=0.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.covar_pop(_to_java_column(col1), _to_java_column(col2))) def covar_samp(col1, col2): """Returns a new :class:`~pyspark.sql.Column` for the sample covariance of ``col1`` and ``col2``. .. versionadded:: 2.0.0 Examples -------- >>> a = [1] * 10 >>> b = [1] * 10 >>> df = spark.createDataFrame(zip(a, b), ["a", "b"]) >>> df.agg(covar_samp("a", "b").alias('c')).collect() [Row(c=0.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.covar_samp(_to_java_column(col1), _to_java_column(col2))) def countDistinct(col, *cols): """Returns a new :class:`~pyspark.sql.Column` for distinct count of ``col`` or ``cols``. An alias of :func:`count_distinct`, and it is encouraged to use :func:`count_distinct` directly. .. versionadded:: 1.3.0 """ return count_distinct(col, *cols) def count_distinct(col, *cols): """Returns a new :class:`Column` for distinct count of ``col`` or ``cols``. .. versionadded:: 3.2.0 Examples -------- >>> df.agg(count_distinct(df.age, df.name).alias('c')).collect() [Row(c=2)] >>> df.agg(count_distinct("age", "name").alias('c')).collect() [Row(c=2)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.count_distinct(_to_java_column(col), _to_seq(sc, cols, _to_java_column)) return Column(jc) def first(col, ignorenulls=False): """Aggregate function: returns the first value in a group. The function by default returns the first values it sees. It will return the first non-null value it sees when ignoreNulls is set to true. If all values are null, then null is returned. .. versionadded:: 1.3.0 Notes ----- The function is non-deterministic because its results depends on the order of the rows which may be non-deterministic after a shuffle. """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.first(_to_java_column(col), ignorenulls) return Column(jc) def grouping(col): """ Aggregate function: indicates whether a specified column in a GROUP BY list is aggregated or not, returns 1 for aggregated or 0 for not aggregated in the result set. .. versionadded:: 2.0.0 Examples -------- >>> df.cube("name").agg(grouping("name"), sum("age")).orderBy("name").show() +-----+--------------+--------+ | name|grouping(name)|sum(age)| +-----+--------------+--------+ | null| 1| 7| |Alice| 0| 2| | Bob| 0| 5| +-----+--------------+--------+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.grouping(_to_java_column(col)) return Column(jc) def grouping_id(*cols): """ Aggregate function: returns the level of grouping, equals to (grouping(c1) << (n-1)) + (grouping(c2) << (n-2)) + ... + grouping(cn) .. versionadded:: 2.0.0 Notes ----- The list of columns should match with grouping columns exactly, or empty (means all the grouping columns). Examples -------- >>> df.cube("name").agg(grouping_id(), sum("age")).orderBy("name").show() +-----+-------------+--------+ | name|grouping_id()|sum(age)| +-----+-------------+--------+ | null| 1| 7| |Alice| 0| 2| | Bob| 0| 5| +-----+-------------+--------+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.grouping_id(_to_seq(sc, cols, _to_java_column)) return Column(jc) @since(1.6) def input_file_name(): """Creates a string column for the file name of the current Spark task. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.input_file_name()) def isnan(col): """An expression that returns true iff the column is NaN. .. versionadded:: 1.6.0 Examples -------- >>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b")) >>> df.select(isnan("a").alias("r1"), isnan(df.a).alias("r2")).collect() [Row(r1=False, r2=False), Row(r1=True, r2=True)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.isnan(_to_java_column(col))) def isnull(col): """An expression that returns true iff the column is null. .. versionadded:: 1.6.0 Examples -------- >>> df = spark.createDataFrame([(1, None), (None, 2)], ("a", "b")) >>> df.select(isnull("a").alias("r1"), isnull(df.a).alias("r2")).collect() [Row(r1=False, r2=False), Row(r1=True, r2=True)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.isnull(_to_java_column(col))) def last(col, ignorenulls=False): """Aggregate function: returns the last value in a group. The function by default returns the last values it sees. It will return the last non-null value it sees when ignoreNulls is set to true. If all values are null, then null is returned. .. versionadded:: 1.3.0 Notes ----- The function is non-deterministic because its results depends on the order of the rows which may be non-deterministic after a shuffle. """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.last(_to_java_column(col), ignorenulls) return Column(jc) def monotonically_increasing_id(): """A column that generates monotonically increasing 64-bit integers. The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive. The current implementation puts the partition ID in the upper 31 bits, and the record number within each partition in the lower 33 bits. The assumption is that the data frame has less than 1 billion partitions, and each partition has less than 8 billion records. .. versionadded:: 1.6.0 Notes ----- The function is non-deterministic because its result depends on partition IDs. As an example, consider a :class:`DataFrame` with two partitions, each with 3 records. This expression would return the following IDs: 0, 1, 2, 8589934592 (1L << 33), 8589934593, 8589934594. >>> df0 = sc.parallelize(range(2), 2).mapPartitions(lambda x: [(1,), (2,), (3,)]).toDF(['col1']) >>> df0.select(monotonically_increasing_id().alias('id')).collect() [Row(id=0), Row(id=1), Row(id=2), Row(id=8589934592), Row(id=8589934593), Row(id=8589934594)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.monotonically_increasing_id()) def nanvl(col1, col2): """Returns col1 if it is not NaN, or col2 if col1 is NaN. Both inputs should be floating point columns (:class:`DoubleType` or :class:`FloatType`). .. versionadded:: 1.6.0 Examples -------- >>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b")) >>> df.select(nanvl("a", "b").alias("r1"), nanvl(df.a, df.b).alias("r2")).collect() [Row(r1=1.0, r2=1.0), Row(r1=2.0, r2=2.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.nanvl(_to_java_column(col1), _to_java_column(col2))) def percentile_approx(col, percentage, accuracy=10000): """Returns the approximate `percentile` of the numeric column `col` which is the smallest value in the ordered `col` values (sorted from least to greatest) such that no more than `percentage` of `col` values is less than the value or equal to that value. The value of percentage must be between 0.0 and 1.0. The accuracy parameter (default: 10000) is a positive numeric literal which controls approximation accuracy at the cost of memory. Higher value of accuracy yields better accuracy, 1.0/accuracy is the relative error of the approximation. When percentage is an array, each value of the percentage array must be between 0.0 and 1.0. In this case, returns the approximate percentile array of column col at the given percentage array. .. versionadded:: 3.1.0 Examples -------- >>> key = (col("id") % 3).alias("key") >>> value = (randn(42) + key * 10).alias("value") >>> df = spark.range(0, 1000, 1, 1).select(key, value) >>> df.select( ... percentile_approx("value", [0.25, 0.5, 0.75], 1000000).alias("quantiles") ... ).printSchema() root |-- quantiles: array (nullable = true) | |-- element: double (containsNull = false) >>> df.groupBy("key").agg( ... percentile_approx("value", 0.5, lit(1000000)).alias("median") ... ).printSchema() root |-- key: long (nullable = true) |-- median: double (nullable = true) """ sc = SparkContext._active_spark_context if isinstance(percentage, (list, tuple)): # A local list percentage = sc._jvm.functions.array(_to_seq(sc, [ _create_column_from_literal(x) for x in percentage ])) elif isinstance(percentage, Column): # Already a Column percentage = _to_java_column(percentage) else: # Probably scalar percentage = _create_column_from_literal(percentage) accuracy = ( _to_java_column(accuracy) if isinstance(accuracy, Column) else _create_column_from_literal(accuracy) ) return Column(sc._jvm.functions.percentile_approx(_to_java_column(col), percentage, accuracy)) def rand(seed=None): """Generates a random column with independent and identically distributed (i.i.d.) samples uniformly distributed in [0.0, 1.0). .. versionadded:: 1.4.0 Notes ----- The function is non-deterministic in general case. Examples -------- >>> df.withColumn('rand', rand(seed=42) * 3).collect() [Row(age=2, name='Alice', rand=2.4052597283576684), Row(age=5, name='Bob', rand=2.3913904055683974)] """ sc = SparkContext._active_spark_context if seed is not None: jc = sc._jvm.functions.rand(seed) else: jc = sc._jvm.functions.rand() return Column(jc) def randn(seed=None): """Generates a column with independent and identically distributed (i.i.d.) samples from the standard normal distribution. .. versionadded:: 1.4.0 Notes ----- The function is non-deterministic in general case. Examples -------- >>> df.withColumn('randn', randn(seed=42)).collect() [Row(age=2, name='Alice', randn=1.1027054481455365), Row(age=5, name='Bob', randn=0.7400395449950132)] """ sc = SparkContext._active_spark_context if seed is not None: jc = sc._jvm.functions.randn(seed) else: jc = sc._jvm.functions.randn() return Column(jc) def round(col, scale=0): """ Round the given value to `scale` decimal places using HALF_UP rounding mode if `scale` >= 0 or at integral part when `scale` < 0. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([(2.5,)], ['a']).select(round('a', 0).alias('r')).collect() [Row(r=3.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.round(_to_java_column(col), scale)) def bround(col, scale=0): """ Round the given value to `scale` decimal places using HALF_EVEN rounding mode if `scale` >= 0 or at integral part when `scale` < 0. .. versionadded:: 2.0.0 Examples -------- >>> spark.createDataFrame([(2.5,)], ['a']).select(bround('a', 0).alias('r')).collect() [Row(r=2.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.bround(_to_java_column(col), scale)) def shiftLeft(col, numBits): """Shift the given value numBits left. .. versionadded:: 1.5.0 .. deprecated:: 3.2.0 Use :func:`shiftleft` instead. """ warnings.warn("Deprecated in 3.2, use shiftleft instead.", FutureWarning) return shiftleft(col, numBits) def shiftleft(col, numBits): """Shift the given value numBits left. .. versionadded:: 3.2.0 Examples -------- >>> spark.createDataFrame([(21,)], ['a']).select(shiftleft('a', 1).alias('r')).collect() [Row(r=42)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.shiftleft(_to_java_column(col), numBits)) def shiftRight(col, numBits): """(Signed) shift the given value numBits right. .. versionadded:: 1.5.0 .. deprecated:: 3.2.0 Use :func:`shiftright` instead. """ warnings.warn("Deprecated in 3.2, use shiftright instead.", FutureWarning) return shiftright(col, numBits) def shiftright(col, numBits): """(Signed) shift the given value numBits right. .. versionadded:: 3.2.0 Examples -------- >>> spark.createDataFrame([(42,)], ['a']).select(shiftright('a', 1).alias('r')).collect() [Row(r=21)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.shiftRight(_to_java_column(col), numBits) return Column(jc) def shiftRightUnsigned(col, numBits): """Unsigned shift the given value numBits right. .. versionadded:: 1.5.0 .. deprecated:: 3.2.0 Use :func:`shiftrightunsigned` instead. """ warnings.warn("Deprecated in 3.2, use shiftrightunsigned instead.", FutureWarning) return shiftrightunsigned(col, numBits) def shiftrightunsigned(col, numBits): """Unsigned shift the given value numBits right. .. versionadded:: 3.2.0 Examples -------- >>> df = spark.createDataFrame([(-42,)], ['a']) >>> df.select(shiftrightunsigned('a', 1).alias('r')).collect() [Row(r=9223372036854775787)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.shiftRightUnsigned(_to_java_column(col), numBits) return Column(jc) def spark_partition_id(): """A column for partition ID. .. versionadded:: 1.6.0 Notes ----- This is non deterministic because it depends on data partitioning and task scheduling. Examples -------- >>> df.repartition(1).select(spark_partition_id().alias("pid")).collect() [Row(pid=0), Row(pid=0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.spark_partition_id()) def expr(str): """Parses the expression string into the column that it represents .. versionadded:: 1.5.0 Examples -------- >>> df.select(expr("length(name)")).collect() [Row(length(name)=5), Row(length(name)=3)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.expr(str)) def struct(*cols): """Creates a new struct column. .. versionadded:: 1.4.0 Parameters ---------- cols : list, set, str or :class:`~pyspark.sql.Column` column names or :class:`~pyspark.sql.Column`\\s to contain in the output struct. Examples -------- >>> df.select(struct('age', 'name').alias("struct")).collect() [Row(struct=Row(age=2, name='Alice')), Row(struct=Row(age=5, name='Bob'))] >>> df.select(struct([df.age, df.name]).alias("struct")).collect() [Row(struct=Row(age=2, name='Alice')), Row(struct=Row(age=5, name='Bob'))] """ sc = SparkContext._active_spark_context if len(cols) == 1 and isinstance(cols[0], (list, set)): cols = cols[0] jc = sc._jvm.functions.struct(_to_seq(sc, cols, _to_java_column)) return Column(jc) def greatest(*cols): """ Returns the greatest value of the list of column names, skipping null values. This function takes at least 2 parameters. It will return null iff all parameters are null. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([(1, 4, 3)], ['a', 'b', 'c']) >>> df.select(greatest(df.a, df.b, df.c).alias("greatest")).collect() [Row(greatest=4)] """ if len(cols) < 2: raise ValueError("greatest should take at least two columns") sc = SparkContext._active_spark_context return Column(sc._jvm.functions.greatest(_to_seq(sc, cols, _to_java_column))) def least(*cols): """ Returns the least value of the list of column names, skipping null values. This function takes at least 2 parameters. It will return null iff all parameters are null. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([(1, 4, 3)], ['a', 'b', 'c']) >>> df.select(least(df.a, df.b, df.c).alias("least")).collect() [Row(least=1)] """ if len(cols) < 2: raise ValueError("least should take at least two columns") sc = SparkContext._active_spark_context return Column(sc._jvm.functions.least(_to_seq(sc, cols, _to_java_column))) def when(condition, value): """Evaluates a list of conditions and returns one of multiple possible result expressions. If :func:`pyspark.sql.Column.otherwise` is not invoked, None is returned for unmatched conditions. .. versionadded:: 1.4.0 Parameters ---------- condition : :class:`~pyspark.sql.Column` a boolean :class:`~pyspark.sql.Column` expression. value : a literal value, or a :class:`~pyspark.sql.Column` expression. >>> df.select(when(df['age'] == 2, 3).otherwise(4).alias("age")).collect() [Row(age=3), Row(age=4)] >>> df.select(when(df.age == 2, df.age + 1).alias("age")).collect() [Row(age=3), Row(age=None)] """ sc = SparkContext._active_spark_context if not isinstance(condition, Column): raise TypeError("condition should be a Column") v = value._jc if isinstance(value, Column) else value jc = sc._jvm.functions.when(condition._jc, v) return Column(jc) def log(arg1, arg2=None): """Returns the first argument-based logarithm of the second argument. If there is only one argument, then this takes the natural logarithm of the argument. .. versionadded:: 1.5.0 Examples -------- >>> df.select(log(10.0, df.age).alias('ten')).rdd.map(lambda l: str(l.ten)[:7]).collect() ['0.30102', '0.69897'] >>> df.select(log(df.age).alias('e')).rdd.map(lambda l: str(l.e)[:7]).collect() ['0.69314', '1.60943'] """ sc = SparkContext._active_spark_context if arg2 is None: jc = sc._jvm.functions.log(_to_java_column(arg1)) else: jc = sc._jvm.functions.log(arg1, _to_java_column(arg2)) return Column(jc) def log2(col): """Returns the base-2 logarithm of the argument. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([(4,)], ['a']).select(log2('a').alias('log2')).collect() [Row(log2=2.0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.log2(_to_java_column(col))) def conv(col, fromBase, toBase): """ Convert a number in a string column from one base to another. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([("010101",)], ['n']) >>> df.select(conv(df.n, 2, 16).alias('hex')).collect() [Row(hex='15')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.conv(_to_java_column(col), fromBase, toBase)) def factorial(col): """ Computes the factorial of the given value. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([(5,)], ['n']) >>> df.select(factorial(df.n).alias('f')).collect() [Row(f=120)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.factorial(_to_java_column(col))) # --------------- Window functions ------------------------ def lag(col, offset=1, default=None): """ Window function: returns the value that is `offset` rows before the current row, and `default` if there is less than `offset` rows before the current row. For example, an `offset` of one will return the previous row at any given point in the window partition. This is equivalent to the LAG function in SQL. .. versionadded:: 1.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression offset : int, optional number of row to extend default : optional default value """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.lag(_to_java_column(col), offset, default)) def lead(col, offset=1, default=None): """ Window function: returns the value that is `offset` rows after the current row, and `default` if there is less than `offset` rows after the current row. For example, an `offset` of one will return the next row at any given point in the window partition. This is equivalent to the LEAD function in SQL. .. versionadded:: 1.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression offset : int, optional number of row to extend default : optional default value """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.lead(_to_java_column(col), offset, default)) def nth_value(col, offset, ignoreNulls=False): """ Window function: returns the value that is the `offset`\\th row of the window frame (counting from 1), and `null` if the size of window frame is less than `offset` rows. It will return the `offset`\\th non-null value it sees when `ignoreNulls` is set to true. If all values are null, then null is returned. This is equivalent to the nth_value function in SQL. .. versionadded:: 3.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression offset : int, optional number of row to use as the value ignoreNulls : bool, optional indicates the Nth value should skip null in the determination of which row to use """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.nth_value(_to_java_column(col), offset, ignoreNulls)) def ntile(n): """ Window function: returns the ntile group id (from 1 to `n` inclusive) in an ordered window partition. For example, if `n` is 4, the first quarter of the rows will get value 1, the second quarter will get 2, the third quarter will get 3, and the last quarter will get 4. This is equivalent to the NTILE function in SQL. .. versionadded:: 1.4.0 Parameters ---------- n : int an integer """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.ntile(int(n))) # ---------------------- Date/Timestamp functions ------------------------------ @since(1.5) def current_date(): """ Returns the current date at the start of query evaluation as a :class:`DateType` column. All calls of current_date within the same query return the same value. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.current_date()) def current_timestamp(): """ Returns the current timestamp at the start of query evaluation as a :class:`TimestampType` column. All calls of current_timestamp within the same query return the same value. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.current_timestamp()) def date_format(date, format): """ Converts a date/timestamp/string to a value of string in the format specified by the date format given by the second argument. A pattern could be for instance `dd.MM.yyyy` and could return a string like '18.03.1993'. All pattern letters of `datetime pattern`_. can be used. .. _datetime pattern: https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html .. versionadded:: 1.5.0 Notes ----- Whenever possible, use specialized functions like `year`. Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(date_format('dt', 'MM/dd/yyy').alias('date')).collect() [Row(date='04/08/2015')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.date_format(_to_java_column(date), format)) def year(col): """ Extract the year of a given date as integer. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(year('dt').alias('year')).collect() [Row(year=2015)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.year(_to_java_column(col))) def quarter(col): """ Extract the quarter of a given date as integer. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(quarter('dt').alias('quarter')).collect() [Row(quarter=2)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.quarter(_to_java_column(col))) def month(col): """ Extract the month of a given date as integer. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(month('dt').alias('month')).collect() [Row(month=4)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.month(_to_java_column(col))) def dayofweek(col): """ Extract the day of the week of a given date as integer. .. versionadded:: 2.3.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(dayofweek('dt').alias('day')).collect() [Row(day=4)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.dayofweek(_to_java_column(col))) def dayofmonth(col): """ Extract the day of the month of a given date as integer. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(dayofmonth('dt').alias('day')).collect() [Row(day=8)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.dayofmonth(_to_java_column(col))) def dayofyear(col): """ Extract the day of the year of a given date as integer. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(dayofyear('dt').alias('day')).collect() [Row(day=98)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.dayofyear(_to_java_column(col))) def hour(col): """ Extract the hours of a given date as integer. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08 13:08:15',)], ['ts']) >>> df.select(hour('ts').alias('hour')).collect() [Row(hour=13)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.hour(_to_java_column(col))) def minute(col): """ Extract the minutes of a given date as integer. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08 13:08:15',)], ['ts']) >>> df.select(minute('ts').alias('minute')).collect() [Row(minute=8)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.minute(_to_java_column(col))) def second(col): """ Extract the seconds of a given date as integer. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08 13:08:15',)], ['ts']) >>> df.select(second('ts').alias('second')).collect() [Row(second=15)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.second(_to_java_column(col))) def weekofyear(col): """ Extract the week number of a given date as integer. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(weekofyear(df.dt).alias('week')).collect() [Row(week=15)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.weekofyear(_to_java_column(col))) def date_add(start, days): """ Returns the date that is `days` days after `start` .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(date_add(df.dt, 1).alias('next_date')).collect() [Row(next_date=datetime.date(2015, 4, 9))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.date_add(_to_java_column(start), days)) def date_sub(start, days): """ Returns the date that is `days` days before `start` .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(date_sub(df.dt, 1).alias('prev_date')).collect() [Row(prev_date=datetime.date(2015, 4, 7))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.date_sub(_to_java_column(start), days)) def datediff(end, start): """ Returns the number of days from `start` to `end`. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08','2015-05-10')], ['d1', 'd2']) >>> df.select(datediff(df.d2, df.d1).alias('diff')).collect() [Row(diff=32)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.datediff(_to_java_column(end), _to_java_column(start))) def add_months(start, months): """ Returns the date that is `months` months after `start` .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> df.select(add_months(df.dt, 1).alias('next_month')).collect() [Row(next_month=datetime.date(2015, 5, 8))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.add_months(_to_java_column(start), months)) def months_between(date1, date2, roundOff=True): """ Returns number of months between dates date1 and date2. If date1 is later than date2, then the result is positive. If date1 and date2 are on the same day of month, or both are the last day of month, returns an integer (time of day will be ignored). The result is rounded off to 8 digits unless `roundOff` is set to `False`. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('1997-02-28 10:30:00', '1996-10-30')], ['date1', 'date2']) >>> df.select(months_between(df.date1, df.date2).alias('months')).collect() [Row(months=3.94959677)] >>> df.select(months_between(df.date1, df.date2, False).alias('months')).collect() [Row(months=3.9495967741935485)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.months_between( _to_java_column(date1), _to_java_column(date2), roundOff)) def to_date(col, format=None): """Converts a :class:`~pyspark.sql.Column` into :class:`pyspark.sql.types.DateType` using the optionally specified format. Specify formats according to `datetime pattern`_. By default, it follows casting rules to :class:`pyspark.sql.types.DateType` if the format is omitted. Equivalent to ``col.cast("date")``. .. _datetime pattern: https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html .. versionadded:: 2.2.0 Examples -------- >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) >>> df.select(to_date(df.t).alias('date')).collect() [Row(date=datetime.date(1997, 2, 28))] >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) >>> df.select(to_date(df.t, 'yyyy-MM-dd HH:mm:ss').alias('date')).collect() [Row(date=datetime.date(1997, 2, 28))] """ sc = SparkContext._active_spark_context if format is None: jc = sc._jvm.functions.to_date(_to_java_column(col)) else: jc = sc._jvm.functions.to_date(_to_java_column(col), format) return Column(jc) def to_timestamp(col, format=None): """Converts a :class:`~pyspark.sql.Column` into :class:`pyspark.sql.types.TimestampType` using the optionally specified format. Specify formats according to `datetime pattern`_. By default, it follows casting rules to :class:`pyspark.sql.types.TimestampType` if the format is omitted. Equivalent to ``col.cast("timestamp")``. .. _datetime pattern: https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html .. versionadded:: 2.2.0 Examples -------- >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) >>> df.select(to_timestamp(df.t).alias('dt')).collect() [Row(dt=datetime.datetime(1997, 2, 28, 10, 30))] >>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) >>> df.select(to_timestamp(df.t, 'yyyy-MM-dd HH:mm:ss').alias('dt')).collect() [Row(dt=datetime.datetime(1997, 2, 28, 10, 30))] """ sc = SparkContext._active_spark_context if format is None: jc = sc._jvm.functions.to_timestamp(_to_java_column(col)) else: jc = sc._jvm.functions.to_timestamp(_to_java_column(col), format) return Column(jc) def trunc(date, format): """ Returns date truncated to the unit specified by the format. .. versionadded:: 1.5.0 Parameters ---------- date : :class:`~pyspark.sql.Column` or str format : str 'year', 'yyyy', 'yy' or 'month', 'mon', 'mm' Examples -------- >>> df = spark.createDataFrame([('1997-02-28',)], ['d']) >>> df.select(trunc(df.d, 'year').alias('year')).collect() [Row(year=datetime.date(1997, 1, 1))] >>> df.select(trunc(df.d, 'mon').alias('month')).collect() [Row(month=datetime.date(1997, 2, 1))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.trunc(_to_java_column(date), format)) def date_trunc(format, timestamp): """ Returns timestamp truncated to the unit specified by the format. .. versionadded:: 2.3.0 Parameters ---------- format : str 'year', 'yyyy', 'yy', 'month', 'mon', 'mm', 'day', 'dd', 'hour', 'minute', 'second', 'week', 'quarter' timestamp : :class:`~pyspark.sql.Column` or str Examples -------- >>> df = spark.createDataFrame([('1997-02-28 05:02:11',)], ['t']) >>> df.select(date_trunc('year', df.t).alias('year')).collect() [Row(year=datetime.datetime(1997, 1, 1, 0, 0))] >>> df.select(date_trunc('mon', df.t).alias('month')).collect() [Row(month=datetime.datetime(1997, 2, 1, 0, 0))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.date_trunc(format, _to_java_column(timestamp))) def next_day(date, dayOfWeek): """ Returns the first date which is later than the value of the date column. Day of the week parameter is case insensitive, and accepts: "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun". .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('2015-07-27',)], ['d']) >>> df.select(next_day(df.d, 'Sun').alias('date')).collect() [Row(date=datetime.date(2015, 8, 2))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.next_day(_to_java_column(date), dayOfWeek)) def last_day(date): """ Returns the last day of the month which the given date belongs to. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('1997-02-10',)], ['d']) >>> df.select(last_day(df.d).alias('date')).collect() [Row(date=datetime.date(1997, 2, 28))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.last_day(_to_java_column(date))) def from_unixtime(timestamp, format="yyyy-MM-dd HH:mm:ss"): """ Converts the number of seconds from unix epoch (1970-01-01 00:00:00 UTC) to a string representing the timestamp of that moment in the current system time zone in the given format. .. versionadded:: 1.5.0 Examples -------- >>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") >>> time_df = spark.createDataFrame([(1428476400,)], ['unix_time']) >>> time_df.select(from_unixtime('unix_time').alias('ts')).collect() [Row(ts='2015-04-08 00:00:00')] >>> spark.conf.unset("spark.sql.session.timeZone") """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.from_unixtime(_to_java_column(timestamp), format)) def unix_timestamp(timestamp=None, format='yyyy-MM-dd HH:mm:ss'): """ Convert time string with given pattern ('yyyy-MM-dd HH:mm:ss', by default) to Unix time stamp (in seconds), using the default timezone and the default locale, return null if fail. if `timestamp` is None, then it returns current timestamp. .. versionadded:: 1.5.0 Examples -------- >>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") >>> time_df = spark.createDataFrame([('2015-04-08',)], ['dt']) >>> time_df.select(unix_timestamp('dt', 'yyyy-MM-dd').alias('unix_time')).collect() [Row(unix_time=1428476400)] >>> spark.conf.unset("spark.sql.session.timeZone") """ sc = SparkContext._active_spark_context if timestamp is None: return Column(sc._jvm.functions.unix_timestamp()) return Column(sc._jvm.functions.unix_timestamp(_to_java_column(timestamp), format)) def from_utc_timestamp(timestamp, tz): """ This is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in UTC, and renders that timestamp as a timestamp in the given time zone. However, timestamp in Spark represents number of microseconds from the Unix epoch, which is not timezone-agnostic. So in Spark this function just shift the timestamp value from UTC timezone to the given timezone. This function may return confusing result if the input is a string with timezone, e.g. '2018-03-13T06:18:23+00:00'. The reason is that, Spark firstly cast the string to timestamp according to the timezone in the string, and finally display the result by converting the timestamp to string according to the session local timezone. .. versionadded:: 1.5.0 Parameters ---------- timestamp : :class:`~pyspark.sql.Column` or str the column that contains timestamps tz : :class:`~pyspark.sql.Column` or str A string detailing the time zone ID that the input should be adjusted to. It should be in the format of either region-based zone IDs or zone offsets. Region IDs must have the form 'area/city', such as 'America/Los_Angeles'. Zone offsets must be in the format '(+|-)HH:mm', for example '-08:00' or '+01:00'. Also 'UTC' and 'Z' are supported as aliases of '+00:00'. Other short names are not recommended to use because they can be ambiguous. .. versionchanged:: 2.4 `tz` can take a :class:`~pyspark.sql.Column` containing timezone ID strings. Examples -------- >>> df = spark.createDataFrame([('1997-02-28 10:30:00', 'JST')], ['ts', 'tz']) >>> df.select(from_utc_timestamp(df.ts, "PST").alias('local_time')).collect() [Row(local_time=datetime.datetime(1997, 2, 28, 2, 30))] >>> df.select(from_utc_timestamp(df.ts, df.tz).alias('local_time')).collect() [Row(local_time=datetime.datetime(1997, 2, 28, 19, 30))] """ sc = SparkContext._active_spark_context if isinstance(tz, Column): tz = _to_java_column(tz) return Column(sc._jvm.functions.from_utc_timestamp(_to_java_column(timestamp), tz)) def to_utc_timestamp(timestamp, tz): """ This is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in the given timezone, and renders that timestamp as a timestamp in UTC. However, timestamp in Spark represents number of microseconds from the Unix epoch, which is not timezone-agnostic. So in Spark this function just shift the timestamp value from the given timezone to UTC timezone. This function may return confusing result if the input is a string with timezone, e.g. '2018-03-13T06:18:23+00:00'. The reason is that, Spark firstly cast the string to timestamp according to the timezone in the string, and finally display the result by converting the timestamp to string according to the session local timezone. .. versionadded:: 1.5.0 Parameters ---------- timestamp : :class:`~pyspark.sql.Column` or str the column that contains timestamps tz : :class:`~pyspark.sql.Column` or str A string detailing the time zone ID that the input should be adjusted to. It should be in the format of either region-based zone IDs or zone offsets. Region IDs must have the form 'area/city', such as 'America/Los_Angeles'. Zone offsets must be in the format '(+|-)HH:mm', for example '-08:00' or '+01:00'. Also 'UTC' and 'Z' are upported as aliases of '+00:00'. Other short names are not recommended to use because they can be ambiguous. .. versionchanged:: 2.4.0 `tz` can take a :class:`~pyspark.sql.Column` containing timezone ID strings. Examples -------- >>> df = spark.createDataFrame([('1997-02-28 10:30:00', 'JST')], ['ts', 'tz']) >>> df.select(to_utc_timestamp(df.ts, "PST").alias('utc_time')).collect() [Row(utc_time=datetime.datetime(1997, 2, 28, 18, 30))] >>> df.select(to_utc_timestamp(df.ts, df.tz).alias('utc_time')).collect() [Row(utc_time=datetime.datetime(1997, 2, 28, 1, 30))] """ sc = SparkContext._active_spark_context if isinstance(tz, Column): tz = _to_java_column(tz) return Column(sc._jvm.functions.to_utc_timestamp(_to_java_column(timestamp), tz)) def timestamp_seconds(col): """ .. versionadded:: 3.1.0 Examples -------- >>> from pyspark.sql.functions import timestamp_seconds >>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") >>> time_df = spark.createDataFrame([(1230219000,)], ['unix_time']) >>> time_df.select(timestamp_seconds(time_df.unix_time).alias('ts')).show() +-------------------+ | ts| +-------------------+ |2008-12-25 07:30:00| +-------------------+ >>> spark.conf.unset("spark.sql.session.timeZone") """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.timestamp_seconds(_to_java_column(col))) def window(timeColumn, windowDuration, slideDuration=None, startTime=None): """Bucketize rows into one or more time windows given a timestamp specifying column. Window starts are inclusive but the window ends are exclusive, e.g. 12:05 will be in the window [12:05,12:10) but not in [12:00,12:05). Windows can support microsecond precision. Windows in the order of months are not supported. The time column must be of :class:`pyspark.sql.types.TimestampType`. Durations are provided as strings, e.g. '1 second', '1 day 12 hours', '2 minutes'. Valid interval strings are 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond'. If the ``slideDuration`` is not provided, the windows will be tumbling windows. The startTime is the offset with respect to 1970-01-01 00:00:00 UTC with which to start window intervals. For example, in order to have hourly tumbling windows that start 15 minutes past the hour, e.g. 12:15-13:15, 13:15-14:15... provide `startTime` as `15 minutes`. The output column will be a struct called 'window' by default with the nested columns 'start' and 'end', where 'start' and 'end' will be of :class:`pyspark.sql.types.TimestampType`. .. versionadded:: 2.0.0 Examples -------- >>> df = spark.createDataFrame([("2016-03-11 09:00:07", 1)]).toDF("date", "val") >>> w = df.groupBy(window("date", "5 seconds")).agg(sum("val").alias("sum")) >>> w.select(w.window.start.cast("string").alias("start"), ... w.window.end.cast("string").alias("end"), "sum").collect() [Row(start='2016-03-11 09:00:05', end='2016-03-11 09:00:10', sum=1)] """ def check_string_field(field, fieldName): if not field or type(field) is not str: raise TypeError("%s should be provided as a string" % fieldName) sc = SparkContext._active_spark_context time_col = _to_java_column(timeColumn) check_string_field(windowDuration, "windowDuration") if slideDuration and startTime: check_string_field(slideDuration, "slideDuration") check_string_field(startTime, "startTime") res = sc._jvm.functions.window(time_col, windowDuration, slideDuration, startTime) elif slideDuration: check_string_field(slideDuration, "slideDuration") res = sc._jvm.functions.window(time_col, windowDuration, slideDuration) elif startTime: check_string_field(startTime, "startTime") res = sc._jvm.functions.window(time_col, windowDuration, windowDuration, startTime) else: res = sc._jvm.functions.window(time_col, windowDuration) return Column(res) # ---------------------------- misc functions ---------------------------------- def crc32(col): """ Calculates the cyclic redundancy check value (CRC32) of a binary column and returns the value as a bigint. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([('ABC',)], ['a']).select(crc32('a').alias('crc32')).collect() [Row(crc32=2743272264)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.crc32(_to_java_column(col))) def md5(col): """Calculates the MD5 digest and returns the value as a 32 character hex string. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([('ABC',)], ['a']).select(md5('a').alias('hash')).collect() [Row(hash='902fbdd2b1df0c4f70b4a5d23525e932')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.md5(_to_java_column(col)) return Column(jc) def sha1(col): """Returns the hex string result of SHA-1. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([('ABC',)], ['a']).select(sha1('a').alias('hash')).collect() [Row(hash='3c01bdbb26f358bab27f267924aa2c9a03fcfdb8')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.sha1(_to_java_column(col)) return Column(jc) def sha2(col, numBits): """Returns the hex string result of SHA-2 family of hash functions (SHA-224, SHA-256, SHA-384, and SHA-512). The numBits indicates the desired bit length of the result, which must have a value of 224, 256, 384, 512, or 0 (which is equivalent to 256). .. versionadded:: 1.5.0 Examples -------- >>> digests = df.select(sha2(df.name, 256).alias('s')).collect() >>> digests[0] Row(s='3bc51062973c458d5a6f2d8d64a023246354ad7e064b1e4e009ec8a0699a3043') >>> digests[1] Row(s='cd9fb1e148ccd8442e5aa74904cc73bf6fb54d1d54d333bd596aa9bb4bb4e961') """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.sha2(_to_java_column(col), numBits) return Column(jc) def hash(*cols): """Calculates the hash code of given columns, and returns the result as an int column. .. versionadded:: 2.0.0 Examples -------- >>> spark.createDataFrame([('ABC',)], ['a']).select(hash('a').alias('hash')).collect() [Row(hash=-757602832)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.hash(_to_seq(sc, cols, _to_java_column)) return Column(jc) def xxhash64(*cols): """Calculates the hash code of given columns using the 64-bit variant of the xxHash algorithm, and returns the result as a long column. .. versionadded:: 3.0.0 Examples -------- >>> spark.createDataFrame([('ABC',)], ['a']).select(xxhash64('a').alias('hash')).collect() [Row(hash=4105715581806190027)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.xxhash64(_to_seq(sc, cols, _to_java_column)) return Column(jc) def assert_true(col, errMsg=None): """ Returns null if the input column is true; throws an exception with the provided error message otherwise. .. versionadded:: 3.1.0 Examples -------- >>> df = spark.createDataFrame([(0,1)], ['a', 'b']) >>> df.select(assert_true(df.a < df.b).alias('r')).collect() [Row(r=None)] >>> df = spark.createDataFrame([(0,1)], ['a', 'b']) >>> df.select(assert_true(df.a < df.b, df.a).alias('r')).collect() [Row(r=None)] >>> df = spark.createDataFrame([(0,1)], ['a', 'b']) >>> df.select(assert_true(df.a < df.b, 'error').alias('r')).collect() [Row(r=None)] """ sc = SparkContext._active_spark_context if errMsg is None: return Column(sc._jvm.functions.assert_true(_to_java_column(col))) if not isinstance(errMsg, (str, Column)): raise TypeError( "errMsg should be a Column or a str, got {}".format(type(errMsg)) ) errMsg = ( _create_column_from_literal(errMsg) if isinstance(errMsg, str) else _to_java_column(errMsg) ) return Column(sc._jvm.functions.assert_true(_to_java_column(col), errMsg)) @since(3.1) def raise_error(errMsg): """ Throws an exception with the provided error message. """ if not isinstance(errMsg, (str, Column)): raise TypeError( "errMsg should be a Column or a str, got {}".format(type(errMsg)) ) sc = SparkContext._active_spark_context errMsg = ( _create_column_from_literal(errMsg) if isinstance(errMsg, str) else _to_java_column(errMsg) ) return Column(sc._jvm.functions.raise_error(errMsg)) # ---------------------- String/Binary functions ------------------------------ @since(1.5) def upper(col): """ Converts a string expression to upper case. """ return _invoke_function_over_column("upper", col) @since(1.5) def lower(col): """ Converts a string expression to lower case. """ return _invoke_function_over_column("lower", col) @since(1.5) def ascii(col): """ Computes the numeric value of the first character of the string column. """ return _invoke_function_over_column("ascii", col) @since(1.5) def base64(col): """ Computes the BASE64 encoding of a binary column and returns it as a string column. """ return _invoke_function_over_column("base64", col) @since(1.5) def unbase64(col): """ Decodes a BASE64 encoded string column and returns it as a binary column. """ return _invoke_function_over_column("unbase64", col) @since(1.5) def ltrim(col): """ Trim the spaces from left end for the specified string value. """ return _invoke_function_over_column("ltrim", col) @since(1.5) def rtrim(col): """ Trim the spaces from right end for the specified string value. """ return _invoke_function_over_column("rtrim", col) @since(1.5) def trim(col): """ Trim the spaces from both ends for the specified string column. """ return _invoke_function_over_column("trim", col) def concat_ws(sep, *cols): """ Concatenates multiple input string columns together into a single string column, using the given separator. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) >>> df.select(concat_ws('-', df.s, df.d).alias('s')).collect() [Row(s='abcd-123')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.concat_ws(sep, _to_seq(sc, cols, _to_java_column))) @since(1.5) def decode(col, charset): """ Computes the first argument into a string from a binary using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.decode(_to_java_column(col), charset)) @since(1.5) def encode(col, charset): """ Computes the first argument into a binary from a string using the provided character set (one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.encode(_to_java_column(col), charset)) def format_number(col, d): """ Formats the number X to a format like '#,--#,--#.--', rounded to d decimal places with HALF_EVEN round mode, and returns the result as a string. .. versionadded:: 1.5.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str the column name of the numeric value to be formatted d : int the N decimal places >>> spark.createDataFrame([(5,)], ['a']).select(format_number('a', 4).alias('v')).collect() [Row(v='5.0000')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.format_number(_to_java_column(col), d)) def format_string(format, *cols): """ Formats the arguments in printf-style and returns the result as a string column. .. versionadded:: 1.5.0 Parameters ---------- format : str string that can contain embedded format tags and used as result column's value cols : :class:`~pyspark.sql.Column` or str column names or :class:`~pyspark.sql.Column`\\s to be used in formatting Examples -------- >>> df = spark.createDataFrame([(5, "hello")], ['a', 'b']) >>> df.select(format_string('%d %s', df.a, df.b).alias('v')).collect() [Row(v='5 hello')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.format_string(format, _to_seq(sc, cols, _to_java_column))) def instr(str, substr): """ Locate the position of the first occurrence of substr column in the given string. Returns null if either of the arguments are null. .. versionadded:: 1.5.0 Notes ----- The position is not zero based, but 1 based index. Returns 0 if substr could not be found in str. >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(instr(df.s, 'b').alias('s')).collect() [Row(s=2)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.instr(_to_java_column(str), substr)) def overlay(src, replace, pos, len=-1): """ Overlay the specified portion of `src` with `replace`, starting from byte position `pos` of `src` and proceeding for `len` bytes. .. versionadded:: 3.0.0 Examples -------- >>> df = spark.createDataFrame([("SPARK_SQL", "CORE")], ("x", "y")) >>> df.select(overlay("x", "y", 7).alias("overlayed")).show() +----------+ | overlayed| +----------+ |SPARK_CORE| +----------+ """ if not isinstance(pos, (int, str, Column)): raise TypeError( "pos should be an integer or a Column / column name, got {}".format(type(pos))) if len is not None and not isinstance(len, (int, str, Column)): raise TypeError( "len should be an integer or a Column / column name, got {}".format(type(len))) pos = _create_column_from_literal(pos) if isinstance(pos, int) else _to_java_column(pos) len = _create_column_from_literal(len) if isinstance(len, int) else _to_java_column(len) sc = SparkContext._active_spark_context return Column(sc._jvm.functions.overlay( _to_java_column(src), _to_java_column(replace), pos, len )) def sentences(string, language=None, country=None): """ Splits a string into arrays of sentences, where each sentence is an array of words. The 'language' and 'country' arguments are optional, and if omitted, the default locale is used. .. versionadded:: 3.2.0 Parameters ---------- string : :class:`~pyspark.sql.Column` or str a string to be split language : :class:`~pyspark.sql.Column` or str, optional a language of the locale country : :class:`~pyspark.sql.Column` or str, optional a country of the locale Examples -------- >>> df = spark.createDataFrame([["This is an example sentence."]], ["string"]) >>> df.select(sentences(df.string, lit("en"), lit("US"))).show(truncate=False) +-----------------------------------+ |sentences(string, en, US) | +-----------------------------------+ |[[This, is, an, example, sentence]]| +-----------------------------------+ """ if language is None: language = lit("") if country is None: country = lit("") sc = SparkContext._active_spark_context return Column(sc._jvm.functions.sentences( _to_java_column(string), _to_java_column(language), _to_java_column(country) )) def substring(str, pos, len): """ Substring starts at `pos` and is of length `len` when str is String type or returns the slice of byte array that starts at `pos` in byte and is of length `len` when str is Binary type. .. versionadded:: 1.5.0 Notes ----- The position is not zero based, but 1 based index. Examples -------- >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(substring(df.s, 1, 2).alias('s')).collect() [Row(s='ab')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.substring(_to_java_column(str), pos, len)) def substring_index(str, delim, count): """ Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything the left of the final delimiter (counting from left) is returned. If count is negative, every to the right of the final delimiter (counting from the right) is returned. substring_index performs a case-sensitive match when searching for delim. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('a.b.c.d',)], ['s']) >>> df.select(substring_index(df.s, '.', 2).alias('s')).collect() [Row(s='a.b')] >>> df.select(substring_index(df.s, '.', -3).alias('s')).collect() [Row(s='b.c.d')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.substring_index(_to_java_column(str), delim, count)) def levenshtein(left, right): """Computes the Levenshtein distance of the two given strings. .. versionadded:: 1.5.0 Examples -------- >>> df0 = spark.createDataFrame([('kitten', 'sitting',)], ['l', 'r']) >>> df0.select(levenshtein('l', 'r').alias('d')).collect() [Row(d=3)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.levenshtein(_to_java_column(left), _to_java_column(right)) return Column(jc) def locate(substr, str, pos=1): """ Locate the position of the first occurrence of substr in a string column, after position pos. .. versionadded:: 1.5.0 Parameters ---------- substr : str a string str : :class:`~pyspark.sql.Column` or str a Column of :class:`pyspark.sql.types.StringType` pos : int, optional start position (zero based) Notes ----- The position is not zero based, but 1 based index. Returns 0 if substr could not be found in str. Examples -------- >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(locate('b', df.s, 1).alias('s')).collect() [Row(s=2)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.locate(substr, _to_java_column(str), pos)) def lpad(col, len, pad): """ Left-pad the string column to width `len` with `pad`. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(lpad(df.s, 6, '#').alias('s')).collect() [Row(s='##abcd')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.lpad(_to_java_column(col), len, pad)) def rpad(col, len, pad): """ Right-pad the string column to width `len` with `pad`. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('abcd',)], ['s',]) >>> df.select(rpad(df.s, 6, '#').alias('s')).collect() [Row(s='abcd##')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.rpad(_to_java_column(col), len, pad)) def repeat(col, n): """ Repeats a string column n times, and returns it as a new string column. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('ab',)], ['s',]) >>> df.select(repeat(df.s, 3).alias('s')).collect() [Row(s='ababab')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.repeat(_to_java_column(col), n)) def split(str, pattern, limit=-1): """ Splits str around matches of the given pattern. .. versionadded:: 1.5.0 Parameters ---------- str : :class:`~pyspark.sql.Column` or str a string expression to split pattern : str a string representing a regular expression. The regex string should be a Java regular expression. limit : int, optional an integer which controls the number of times `pattern` is applied. * ``limit > 0``: The resulting array's length will not be more than `limit`, and the resulting array's last entry will contain all input beyond the last matched pattern. * ``limit <= 0``: `pattern` will be applied as many times as possible, and the resulting array can be of any size. .. versionchanged:: 3.0 `split` now takes an optional `limit` field. If not provided, default limit value is -1. Examples -------- >>> df = spark.createDataFrame([('oneAtwoBthreeC',)], ['s',]) >>> df.select(split(df.s, '[ABC]', 2).alias('s')).collect() [Row(s=['one', 'twoBthreeC'])] >>> df.select(split(df.s, '[ABC]', -1).alias('s')).collect() [Row(s=['one', 'two', 'three', ''])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.split(_to_java_column(str), pattern, limit)) def regexp_extract(str, pattern, idx): r"""Extract a specific group matched by a Java regex, from the specified string column. If the regex did not match, or the specified group did not match, an empty string is returned. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_extract('str', r'(\d+)-(\d+)', 1).alias('d')).collect() [Row(d='100')] >>> df = spark.createDataFrame([('foo',)], ['str']) >>> df.select(regexp_extract('str', r'(\d+)', 1).alias('d')).collect() [Row(d='')] >>> df = spark.createDataFrame([('aaaac',)], ['str']) >>> df.select(regexp_extract('str', '(a+)(b)?(c)', 2).alias('d')).collect() [Row(d='')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.regexp_extract(_to_java_column(str), pattern, idx) return Column(jc) def regexp_replace(str, pattern, replacement): r"""Replace all substrings of the specified string value that match regexp with rep. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('100-200',)], ['str']) >>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect() [Row(d='-----')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.regexp_replace(_to_java_column(str), pattern, replacement) return Column(jc) def initcap(col): """Translate the first letter of each word to upper case in the sentence. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([('ab cd',)], ['a']).select(initcap("a").alias('v')).collect() [Row(v='Ab Cd')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.initcap(_to_java_column(col))) def soundex(col): """ Returns the SoundEx encoding for a string .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([("Peters",),("Uhrbach",)], ['name']) >>> df.select(soundex(df.name).alias("soundex")).collect() [Row(soundex='P362'), Row(soundex='U612')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.soundex(_to_java_column(col))) def bin(col): """Returns the string representation of the binary value of the given column. .. versionadded:: 1.5.0 Examples -------- >>> df.select(bin(df.age).alias('c')).collect() [Row(c='10'), Row(c='101')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.bin(_to_java_column(col)) return Column(jc) def hex(col): """Computes hex value of the given column, which could be :class:`pyspark.sql.types.StringType`, :class:`pyspark.sql.types.BinaryType`, :class:`pyspark.sql.types.IntegerType` or :class:`pyspark.sql.types.LongType`. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([('ABC', 3)], ['a', 'b']).select(hex('a'), hex('b')).collect() [Row(hex(a)='414243', hex(b)='3')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.hex(_to_java_column(col)) return Column(jc) def unhex(col): """Inverse of hex. Interprets each pair of characters as a hexadecimal number and converts to the byte representation of number. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([('414243',)], ['a']).select(unhex('a')).collect() [Row(unhex(a)=bytearray(b'ABC'))] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.unhex(_to_java_column(col))) def length(col): """Computes the character length of string data or number of bytes of binary data. The length of character data includes the trailing spaces. The length of binary data includes binary zeros. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([('ABC ',)], ['a']).select(length('a').alias('length')).collect() [Row(length=4)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.length(_to_java_column(col))) def translate(srcCol, matching, replace): """A function translate any character in the `srcCol` by a character in `matching`. The characters in `replace` is corresponding to the characters in `matching`. The translate will happen when any character in the string matching with the character in the `matching`. .. versionadded:: 1.5.0 Examples -------- >>> spark.createDataFrame([('translate',)], ['a']).select(translate('a', "rnlt", "123") \\ ... .alias('r')).collect() [Row(r='1a2s3ae')] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.translate(_to_java_column(srcCol), matching, replace)) # ---------------------- Collection functions ------------------------------ def create_map(*cols): """Creates a new map column. .. versionadded:: 2.0.0 Parameters ---------- cols : :class:`~pyspark.sql.Column` or str column names or :class:`~pyspark.sql.Column`\\s that are grouped as key-value pairs, e.g. (key1, value1, key2, value2, ...). Examples -------- >>> df.select(create_map('name', 'age').alias("map")).collect() [Row(map={'Alice': 2}), Row(map={'Bob': 5})] >>> df.select(create_map([df.name, df.age]).alias("map")).collect() [Row(map={'Alice': 2}), Row(map={'Bob': 5})] """ sc = SparkContext._active_spark_context if len(cols) == 1 and isinstance(cols[0], (list, set)): cols = cols[0] jc = sc._jvm.functions.map(_to_seq(sc, cols, _to_java_column)) return Column(jc) def map_from_arrays(col1, col2): """Creates a new map from two arrays. .. versionadded:: 2.4.0 Parameters ---------- col1 : :class:`~pyspark.sql.Column` or str name of column containing a set of keys. All elements should not be null col2 : :class:`~pyspark.sql.Column` or str name of column containing a set of values Examples -------- >>> df = spark.createDataFrame([([2, 5], ['a', 'b'])], ['k', 'v']) >>> df.select(map_from_arrays(df.k, df.v).alias("map")).show() +----------------+ | map| +----------------+ |{2 -> a, 5 -> b}| +----------------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_from_arrays(_to_java_column(col1), _to_java_column(col2))) def array(*cols): """Creates a new array column. .. versionadded:: 1.4.0 Parameters ---------- cols : :class:`~pyspark.sql.Column` or str column names or :class:`~pyspark.sql.Column`\\s that have the same data type. Examples -------- >>> df.select(array('age', 'age').alias("arr")).collect() [Row(arr=[2, 2]), Row(arr=[5, 5])] >>> df.select(array([df.age, df.age]).alias("arr")).collect() [Row(arr=[2, 2]), Row(arr=[5, 5])] """ sc = SparkContext._active_spark_context if len(cols) == 1 and isinstance(cols[0], (list, set)): cols = cols[0] jc = sc._jvm.functions.array(_to_seq(sc, cols, _to_java_column)) return Column(jc) def array_contains(col, value): """ Collection function: returns null if the array is null, true if the array contains the given value, and false otherwise. .. versionadded:: 1.5.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column containing array value : value or column to check for in array Examples -------- >>> df = spark.createDataFrame([(["a", "b", "c"],), ([],)], ['data']) >>> df.select(array_contains(df.data, "a")).collect() [Row(array_contains(data, a)=True), Row(array_contains(data, a)=False)] >>> df.select(array_contains(df.data, lit("a"))).collect() [Row(array_contains(data, a)=True), Row(array_contains(data, a)=False)] """ sc = SparkContext._active_spark_context value = value._jc if isinstance(value, Column) else value return Column(sc._jvm.functions.array_contains(_to_java_column(col), value)) def arrays_overlap(a1, a2): """ Collection function: returns true if the arrays contain any common non-null element; if not, returns null if both the arrays are non-empty and any of them contains a null element; returns false otherwise. .. versionadded:: 2.4.0 Examples -------- >>> df = spark.createDataFrame([(["a", "b"], ["b", "c"]), (["a"], ["b", "c"])], ['x', 'y']) >>> df.select(arrays_overlap(df.x, df.y).alias("overlap")).collect() [Row(overlap=True), Row(overlap=False)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.arrays_overlap(_to_java_column(a1), _to_java_column(a2))) def slice(x, start, length): """ Collection function: returns an array containing all the elements in `x` from index `start` (array indices start at 1, or from the end if `start` is negative) with the specified `length`. .. versionadded:: 2.4.0 Parameters ---------- x : :class:`~pyspark.sql.Column` or str the array to be sliced start : :class:`~pyspark.sql.Column` or int the starting index length : :class:`~pyspark.sql.Column` or int the length of the slice Examples -------- >>> df = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ['x']) >>> df.select(slice(df.x, 2, 2).alias("sliced")).collect() [Row(sliced=[2, 3]), Row(sliced=[5])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.slice( _to_java_column(x), start._jc if isinstance(start, Column) else start, length._jc if isinstance(length, Column) else length )) def array_join(col, delimiter, null_replacement=None): """ Concatenates the elements of `column` using the `delimiter`. Null values are replaced with `null_replacement` if set, otherwise they are ignored. .. versionadded:: 2.4.0 Examples -------- >>> df = spark.createDataFrame([(["a", "b", "c"],), (["a", None],)], ['data']) >>> df.select(array_join(df.data, ",").alias("joined")).collect() [Row(joined='a,b,c'), Row(joined='a')] >>> df.select(array_join(df.data, ",", "NULL").alias("joined")).collect() [Row(joined='a,b,c'), Row(joined='a,NULL')] """ sc = SparkContext._active_spark_context if null_replacement is None: return Column(sc._jvm.functions.array_join(_to_java_column(col), delimiter)) else: return Column(sc._jvm.functions.array_join( _to_java_column(col), delimiter, null_replacement)) def concat(*cols): """ Concatenates multiple input columns together into a single column. The function works with strings, binary and compatible array columns. .. versionadded:: 1.5.0 Examples -------- >>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) >>> df.select(concat(df.s, df.d).alias('s')).collect() [Row(s='abcd123')] >>> df = spark.createDataFrame([([1, 2], [3, 4], [5]), ([1, 2], None, [3])], ['a', 'b', 'c']) >>> df.select(concat(df.a, df.b, df.c).alias("arr")).collect() [Row(arr=[1, 2, 3, 4, 5]), Row(arr=None)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.concat(_to_seq(sc, cols, _to_java_column))) def array_position(col, value): """ Collection function: Locates the position of the first occurrence of the given value in the given array. Returns null if either of the arguments are null. .. versionadded:: 2.4.0 Notes ----- The position is not zero based, but 1 based index. Returns 0 if the given value could not be found in the array. Examples -------- >>> df = spark.createDataFrame([(["c", "b", "a"],), ([],)], ['data']) >>> df.select(array_position(df.data, "a")).collect() [Row(array_position(data, a)=3), Row(array_position(data, a)=0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_position(_to_java_column(col), value)) def element_at(col, extraction): """ Collection function: Returns element of array at given index in extraction if col is array. Returns value for the given key in extraction if col is map. .. versionadded:: 2.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column containing array or map extraction : index to check for in array or key to check for in map Notes ----- The position is not zero based, but 1 based index. Examples -------- >>> df = spark.createDataFrame([(["a", "b", "c"],), ([],)], ['data']) >>> df.select(element_at(df.data, 1)).collect() [Row(element_at(data, 1)='a'), Row(element_at(data, 1)=None)] >>> df = spark.createDataFrame([({"a": 1.0, "b": 2.0},), ({},)], ['data']) >>> df.select(element_at(df.data, lit("a"))).collect() [Row(element_at(data, a)=1.0), Row(element_at(data, a)=None)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.element_at( _to_java_column(col), lit(extraction)._jc)) def array_remove(col, element): """ Collection function: Remove all elements that equal to element from the given array. .. versionadded:: 2.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column containing array element : element to be removed from the array Examples -------- >>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([],)], ['data']) >>> df.select(array_remove(df.data, 1)).collect() [Row(array_remove(data, 1)=[2, 3]), Row(array_remove(data, 1)=[])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_remove(_to_java_column(col), element)) def array_distinct(col): """ Collection function: removes duplicate values from the array. .. versionadded:: 2.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> df = spark.createDataFrame([([1, 2, 3, 2],), ([4, 5, 5, 4],)], ['data']) >>> df.select(array_distinct(df.data)).collect() [Row(array_distinct(data)=[1, 2, 3]), Row(array_distinct(data)=[4, 5])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_distinct(_to_java_column(col))) def array_intersect(col1, col2): """ Collection function: returns an array of the elements in the intersection of col1 and col2, without duplicates. .. versionadded:: 2.4.0 Parameters ---------- col1 : :class:`~pyspark.sql.Column` or str name of column containing array col2 : :class:`~pyspark.sql.Column` or str name of column containing array Examples -------- >>> from pyspark.sql import Row >>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])]) >>> df.select(array_intersect(df.c1, df.c2)).collect() [Row(array_intersect(c1, c2)=['a', 'c'])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_intersect(_to_java_column(col1), _to_java_column(col2))) def array_union(col1, col2): """ Collection function: returns an array of the elements in the union of col1 and col2, without duplicates. .. versionadded:: 2.4.0 Parameters ---------- col1 : :class:`~pyspark.sql.Column` or str name of column containing array col2 : :class:`~pyspark.sql.Column` or str name of column containing array Examples -------- >>> from pyspark.sql import Row >>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])]) >>> df.select(array_union(df.c1, df.c2)).collect() [Row(array_union(c1, c2)=['b', 'a', 'c', 'd', 'f'])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_union(_to_java_column(col1), _to_java_column(col2))) def array_except(col1, col2): """ Collection function: returns an array of the elements in col1 but not in col2, without duplicates. .. versionadded:: 2.4.0 Parameters ---------- col1 : :class:`~pyspark.sql.Column` or str name of column containing array col2 : :class:`~pyspark.sql.Column` or str name of column containing array Examples -------- >>> from pyspark.sql import Row >>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])]) >>> df.select(array_except(df.c1, df.c2)).collect() [Row(array_except(c1, c2)=['b'])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_except(_to_java_column(col1), _to_java_column(col2))) def explode(col): """ Returns a new row for each element in the given array or map. Uses the default column name `col` for elements in the array and `key` and `value` for elements in the map unless specified otherwise. .. versionadded:: 1.4.0 Examples -------- >>> from pyspark.sql import Row >>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={"a": "b"})]) >>> eDF.select(explode(eDF.intlist).alias("anInt")).collect() [Row(anInt=1), Row(anInt=2), Row(anInt=3)] >>> eDF.select(explode(eDF.mapfield).alias("key", "value")).show() +---+-----+ |key|value| +---+-----+ | a| b| +---+-----+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.explode(_to_java_column(col)) return Column(jc) def posexplode(col): """ Returns a new row for each element with position in the given array or map. Uses the default column name `pos` for position, and `col` for elements in the array and `key` and `value` for elements in the map unless specified otherwise. .. versionadded:: 2.1.0 Examples -------- >>> from pyspark.sql import Row >>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={"a": "b"})]) >>> eDF.select(posexplode(eDF.intlist)).collect() [Row(pos=0, col=1), Row(pos=1, col=2), Row(pos=2, col=3)] >>> eDF.select(posexplode(eDF.mapfield)).show() +---+---+-----+ |pos|key|value| +---+---+-----+ | 0| a| b| +---+---+-----+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.posexplode(_to_java_column(col)) return Column(jc) def explode_outer(col): """ Returns a new row for each element in the given array or map. Unlike explode, if the array/map is null or empty then null is produced. Uses the default column name `col` for elements in the array and `key` and `value` for elements in the map unless specified otherwise. .. versionadded:: 2.3.0 Examples -------- >>> df = spark.createDataFrame( ... [(1, ["foo", "bar"], {"x": 1.0}), (2, [], {}), (3, None, None)], ... ("id", "an_array", "a_map") ... ) >>> df.select("id", "an_array", explode_outer("a_map")).show() +---+----------+----+-----+ | id| an_array| key|value| +---+----------+----+-----+ | 1|[foo, bar]| x| 1.0| | 2| []|null| null| | 3| null|null| null| +---+----------+----+-----+ >>> df.select("id", "a_map", explode_outer("an_array")).show() +---+----------+----+ | id| a_map| col| +---+----------+----+ | 1|{x -> 1.0}| foo| | 1|{x -> 1.0}| bar| | 2| {}|null| | 3| null|null| +---+----------+----+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.explode_outer(_to_java_column(col)) return Column(jc) def posexplode_outer(col): """ Returns a new row for each element with position in the given array or map. Unlike posexplode, if the array/map is null or empty then the row (null, null) is produced. Uses the default column name `pos` for position, and `col` for elements in the array and `key` and `value` for elements in the map unless specified otherwise. .. versionadded:: 2.3.0 Examples -------- >>> df = spark.createDataFrame( ... [(1, ["foo", "bar"], {"x": 1.0}), (2, [], {}), (3, None, None)], ... ("id", "an_array", "a_map") ... ) >>> df.select("id", "an_array", posexplode_outer("a_map")).show() +---+----------+----+----+-----+ | id| an_array| pos| key|value| +---+----------+----+----+-----+ | 1|[foo, bar]| 0| x| 1.0| | 2| []|null|null| null| | 3| null|null|null| null| +---+----------+----+----+-----+ >>> df.select("id", "a_map", posexplode_outer("an_array")).show() +---+----------+----+----+ | id| a_map| pos| col| +---+----------+----+----+ | 1|{x -> 1.0}| 0| foo| | 1|{x -> 1.0}| 1| bar| | 2| {}|null|null| | 3| null|null|null| +---+----------+----+----+ """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.posexplode_outer(_to_java_column(col)) return Column(jc) def get_json_object(col, path): """ Extracts json object from a json string based on json path specified, and returns json string of the extracted json object. It will return null if the input json string is invalid. .. versionadded:: 1.6.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str string column in json format path : str path to the json object to extract Examples -------- >>> data = [("1", '''{"f1": "value1", "f2": "value2"}'''), ("2", '''{"f1": "value12"}''')] >>> df = spark.createDataFrame(data, ("key", "jstring")) >>> df.select(df.key, get_json_object(df.jstring, '$.f1').alias("c0"), \\ ... get_json_object(df.jstring, '$.f2').alias("c1") ).collect() [Row(key='1', c0='value1', c1='value2'), Row(key='2', c0='value12', c1=None)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.get_json_object(_to_java_column(col), path) return Column(jc) def json_tuple(col, *fields): """Creates a new row for a json column according to the given field names. .. versionadded:: 1.6.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str string column in json format fields : str fields to extract Examples -------- >>> data = [("1", '''{"f1": "value1", "f2": "value2"}'''), ("2", '''{"f1": "value12"}''')] >>> df = spark.createDataFrame(data, ("key", "jstring")) >>> df.select(df.key, json_tuple(df.jstring, 'f1', 'f2')).collect() [Row(key='1', c0='value1', c1='value2'), Row(key='2', c0='value12', c1=None)] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.json_tuple(_to_java_column(col), _to_seq(sc, fields)) return Column(jc) def from_json(col, schema, options=None): """ Parses a column containing a JSON string into a :class:`MapType` with :class:`StringType` as keys type, :class:`StructType` or :class:`ArrayType` with the specified schema. Returns `null`, in the case of an unparseable string. .. versionadded:: 2.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str string column in json format schema : :class:`DataType` or str a StructType or ArrayType of StructType to use when parsing the json column. .. versionchanged:: 2.3 the DDL-formatted string is also supported for ``schema``. options : dict, optional options to control parsing. accepts the same options as the json datasource. See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-json.html#data-source-option>`_ in the version you use. .. # noqa Examples -------- >>> from pyspark.sql.types import * >>> data = [(1, '''{"a": 1}''')] >>> schema = StructType([StructField("a", IntegerType())]) >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(from_json(df.value, schema).alias("json")).collect() [Row(json=Row(a=1))] >>> df.select(from_json(df.value, "a INT").alias("json")).collect() [Row(json=Row(a=1))] >>> df.select(from_json(df.value, "MAP<STRING,INT>").alias("json")).collect() [Row(json={'a': 1})] >>> data = [(1, '''[{"a": 1}]''')] >>> schema = ArrayType(StructType([StructField("a", IntegerType())])) >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(from_json(df.value, schema).alias("json")).collect() [Row(json=[Row(a=1)])] >>> schema = schema_of_json(lit('''{"a": 0}''')) >>> df.select(from_json(df.value, schema).alias("json")).collect() [Row(json=Row(a=None))] >>> data = [(1, '''[1, 2, 3]''')] >>> schema = ArrayType(IntegerType()) >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(from_json(df.value, schema).alias("json")).collect() [Row(json=[1, 2, 3])] """ sc = SparkContext._active_spark_context if isinstance(schema, DataType): schema = schema.json() elif isinstance(schema, Column): schema = _to_java_column(schema) jc = sc._jvm.functions.from_json(_to_java_column(col), schema, _options_to_str(options)) return Column(jc) def to_json(col, options=None): """ Converts a column containing a :class:`StructType`, :class:`ArrayType` or a :class:`MapType` into a JSON string. Throws an exception, in the case of an unsupported type. .. versionadded:: 2.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column containing a struct, an array or a map. options : dict, optional options to control converting. accepts the same options as the JSON datasource. See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-json.html#data-source-option>`_ in the version you use. Additionally the function supports the `pretty` option which enables pretty JSON generation. .. # noqa Examples -------- >>> from pyspark.sql import Row >>> from pyspark.sql.types import * >>> data = [(1, Row(age=2, name='Alice'))] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json='{"age":2,"name":"Alice"}')] >>> data = [(1, [Row(age=2, name='Alice'), Row(age=3, name='Bob')])] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json='[{"age":2,"name":"Alice"},{"age":3,"name":"Bob"}]')] >>> data = [(1, {"name": "Alice"})] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json='{"name":"Alice"}')] >>> data = [(1, [{"name": "Alice"}, {"name": "Bob"}])] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json='[{"name":"Alice"},{"name":"Bob"}]')] >>> data = [(1, ["Alice", "Bob"])] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_json(df.value).alias("json")).collect() [Row(json='["Alice","Bob"]')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.to_json(_to_java_column(col), _options_to_str(options)) return Column(jc) def schema_of_json(json, options=None): """ Parses a JSON string and infers its schema in DDL format. .. versionadded:: 2.4.0 Parameters ---------- json : :class:`~pyspark.sql.Column` or str a JSON string or a foldable string column containing a JSON string. options : dict, optional options to control parsing. accepts the same options as the JSON datasource. See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-json.html#data-source-option>`_ in the version you use. .. # noqa .. versionchanged:: 3.0 It accepts `options` parameter to control schema inferring. Examples -------- >>> df = spark.range(1) >>> df.select(schema_of_json(lit('{"a": 0}')).alias("json")).collect() [Row(json='STRUCT<`a`: BIGINT>')] >>> schema = schema_of_json('{a: 1}', {'allowUnquotedFieldNames':'true'}) >>> df.select(schema.alias("json")).collect() [Row(json='STRUCT<`a`: BIGINT>')] """ if isinstance(json, str): col = _create_column_from_literal(json) elif isinstance(json, Column): col = _to_java_column(json) else: raise TypeError("schema argument should be a column or string") sc = SparkContext._active_spark_context jc = sc._jvm.functions.schema_of_json(col, _options_to_str(options)) return Column(jc) def schema_of_csv(csv, options=None): """ Parses a CSV string and infers its schema in DDL format. .. versionadded:: 3.0.0 Parameters ---------- csv : :class:`~pyspark.sql.Column` or str a CSV string or a foldable string column containing a CSV string. options : dict, optional options to control parsing. accepts the same options as the CSV datasource. See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-csv.html#data-source-option>`_ in the version you use. .. # noqa Examples -------- >>> df = spark.range(1) >>> df.select(schema_of_csv(lit('1|a'), {'sep':'|'}).alias("csv")).collect() [Row(csv='STRUCT<`_c0`: INT, `_c1`: STRING>')] >>> df.select(schema_of_csv('1|a', {'sep':'|'}).alias("csv")).collect() [Row(csv='STRUCT<`_c0`: INT, `_c1`: STRING>')] """ if isinstance(csv, str): col = _create_column_from_literal(csv) elif isinstance(csv, Column): col = _to_java_column(csv) else: raise TypeError("schema argument should be a column or string") sc = SparkContext._active_spark_context jc = sc._jvm.functions.schema_of_csv(col, _options_to_str(options)) return Column(jc) def to_csv(col, options=None): """ Converts a column containing a :class:`StructType` into a CSV string. Throws an exception, in the case of an unsupported type. .. versionadded:: 3.0.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column containing a struct. options: dict, optional options to control converting. accepts the same options as the CSV datasource. See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-csv.html#data-source-option>`_ in the version you use. .. # noqa Examples -------- >>> from pyspark.sql import Row >>> data = [(1, Row(age=2, name='Alice'))] >>> df = spark.createDataFrame(data, ("key", "value")) >>> df.select(to_csv(df.value).alias("csv")).collect() [Row(csv='2,Alice')] """ sc = SparkContext._active_spark_context jc = sc._jvm.functions.to_csv(_to_java_column(col), _options_to_str(options)) return Column(jc) def size(col): """ Collection function: returns the length of the array or map stored in the column. .. versionadded:: 1.5.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> df = spark.createDataFrame([([1, 2, 3],),([1],),([],)], ['data']) >>> df.select(size(df.data)).collect() [Row(size(data)=3), Row(size(data)=1), Row(size(data)=0)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.size(_to_java_column(col))) def array_min(col): """ Collection function: returns the minimum value of the array. .. versionadded:: 2.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> df = spark.createDataFrame([([2, 1, 3],), ([None, 10, -1],)], ['data']) >>> df.select(array_min(df.data).alias('min')).collect() [Row(min=1), Row(min=-1)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_min(_to_java_column(col))) def array_max(col): """ Collection function: returns the maximum value of the array. .. versionadded:: 2.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> df = spark.createDataFrame([([2, 1, 3],), ([None, 10, -1],)], ['data']) >>> df.select(array_max(df.data).alias('max')).collect() [Row(max=3), Row(max=10)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_max(_to_java_column(col))) def sort_array(col, asc=True): """ Collection function: sorts the input array in ascending or descending order according to the natural ordering of the array elements. Null elements will be placed at the beginning of the returned array in ascending order or at the end of the returned array in descending order. .. versionadded:: 1.5.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression asc : bool, optional Examples -------- >>> df = spark.createDataFrame([([2, 1, None, 3],),([1],),([],)], ['data']) >>> df.select(sort_array(df.data).alias('r')).collect() [Row(r=[None, 1, 2, 3]), Row(r=[1]), Row(r=[])] >>> df.select(sort_array(df.data, asc=False).alias('r')).collect() [Row(r=[3, 2, 1, None]), Row(r=[1]), Row(r=[])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.sort_array(_to_java_column(col), asc)) def array_sort(col): """ Collection function: sorts the input array in ascending order. The elements of the input array must be orderable. Null elements will be placed at the end of the returned array. .. versionadded:: 2.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> df = spark.createDataFrame([([2, 1, None, 3],),([1],),([],)], ['data']) >>> df.select(array_sort(df.data).alias('r')).collect() [Row(r=[1, 2, 3, None]), Row(r=[1]), Row(r=[])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_sort(_to_java_column(col))) def shuffle(col): """ Collection function: Generates a random permutation of the given array. .. versionadded:: 2.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Notes ----- The function is non-deterministic. Examples -------- >>> df = spark.createDataFrame([([1, 20, 3, 5],), ([1, 20, None, 3],)], ['data']) >>> df.select(shuffle(df.data).alias('s')).collect() # doctest: +SKIP [Row(s=[3, 1, 5, 20]), Row(s=[20, None, 3, 1])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.shuffle(_to_java_column(col))) def reverse(col): """ Collection function: returns a reversed string or an array with reverse order of elements. .. versionadded:: 1.5.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> df = spark.createDataFrame([('Spark SQL',)], ['data']) >>> df.select(reverse(df.data).alias('s')).collect() [Row(s='LQS krapS')] >>> df = spark.createDataFrame([([2, 1, 3],) ,([1],) ,([],)], ['data']) >>> df.select(reverse(df.data).alias('r')).collect() [Row(r=[3, 1, 2]), Row(r=[1]), Row(r=[])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.reverse(_to_java_column(col))) def flatten(col): """ Collection function: creates a single array from an array of arrays. If a structure of nested arrays is deeper than two levels, only one level of nesting is removed. .. versionadded:: 2.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> df = spark.createDataFrame([([[1, 2, 3], [4, 5], [6]],), ([None, [4, 5]],)], ['data']) >>> df.select(flatten(df.data).alias('r')).collect() [Row(r=[1, 2, 3, 4, 5, 6]), Row(r=None)] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.flatten(_to_java_column(col))) def map_keys(col): """ Collection function: Returns an unordered array containing the keys of the map. .. versionadded:: 2.3.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> from pyspark.sql.functions import map_keys >>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as data") >>> df.select(map_keys("data").alias("keys")).show() +------+ | keys| +------+ |[1, 2]| +------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_keys(_to_java_column(col))) def map_values(col): """ Collection function: Returns an unordered array containing the values of the map. .. versionadded:: 2.3.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> from pyspark.sql.functions import map_values >>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as data") >>> df.select(map_values("data").alias("values")).show() +------+ |values| +------+ |[a, b]| +------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_values(_to_java_column(col))) def map_entries(col): """ Collection function: Returns an unordered array of all entries in the given map. .. versionadded:: 3.0.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> from pyspark.sql.functions import map_entries >>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as data") >>> df.select(map_entries("data").alias("entries")).show() +----------------+ | entries| +----------------+ |[{1, a}, {2, b}]| +----------------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_entries(_to_java_column(col))) def map_from_entries(col): """ Collection function: Returns a map created from the given array of entries. .. versionadded:: 2.4.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression Examples -------- >>> from pyspark.sql.functions import map_from_entries >>> df = spark.sql("SELECT array(struct(1, 'a'), struct(2, 'b')) as data") >>> df.select(map_from_entries("data").alias("map")).show() +----------------+ | map| +----------------+ |{1 -> a, 2 -> b}| +----------------+ """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.map_from_entries(_to_java_column(col))) def array_repeat(col, count): """ Collection function: creates an array containing a column repeated count times. .. versionadded:: 2.4.0 Examples -------- >>> df = spark.createDataFrame([('ab',)], ['data']) >>> df.select(array_repeat(df.data, 3).alias('r')).collect() [Row(r=['ab', 'ab', 'ab'])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.array_repeat( _to_java_column(col), _to_java_column(count) if isinstance(count, Column) else count )) def arrays_zip(*cols): """ Collection function: Returns a merged array of structs in which the N-th struct contains all N-th values of input arrays. .. versionadded:: 2.4.0 Parameters ---------- cols : :class:`~pyspark.sql.Column` or str columns of arrays to be merged. Examples -------- >>> from pyspark.sql.functions import arrays_zip >>> df = spark.createDataFrame([(([1, 2, 3], [2, 3, 4]))], ['vals1', 'vals2']) >>> df.select(arrays_zip(df.vals1, df.vals2).alias('zipped')).collect() [Row(zipped=[Row(vals1=1, vals2=2), Row(vals1=2, vals2=3), Row(vals1=3, vals2=4)])] """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.arrays_zip(_to_seq(sc, cols, _to_java_column))) def map_concat(*cols): """Returns the union of all the given maps. .. versionadded:: 2.4.0 Parameters ---------- cols : :class:`~pyspark.sql.Column` or str column names or :class:`~pyspark.sql.Column`\\s Examples -------- >>> from pyspark.sql.functions import map_concat >>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as map1, map(3, 'c') as map2") >>> df.select(map_concat("map1", "map2").alias("map3")).show(truncate=False) +------------------------+ |map3 | +------------------------+ |{1 -> a, 2 -> b, 3 -> c}| +------------------------+ """ sc = SparkContext._active_spark_context if len(cols) == 1 and isinstance(cols[0], (list, set)): cols = cols[0] jc = sc._jvm.functions.map_concat(_to_seq(sc, cols, _to_java_column)) return Column(jc) def sequence(start, stop, step=None): """ Generate a sequence of integers from `start` to `stop`, incrementing by `step`. If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`, otherwise -1. .. versionadded:: 2.4.0 Examples -------- >>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2')) >>> df1.select(sequence('C1', 'C2').alias('r')).collect() [Row(r=[-2, -1, 0, 1, 2])] >>> df2 = spark.createDataFrame([(4, -4, -2)], ('C1', 'C2', 'C3')) >>> df2.select(sequence('C1', 'C2', 'C3').alias('r')).collect() [Row(r=[4, 2, 0, -2, -4])] """ sc = SparkContext._active_spark_context if step is None: return Column(sc._jvm.functions.sequence(_to_java_column(start), _to_java_column(stop))) else: return Column(sc._jvm.functions.sequence( _to_java_column(start), _to_java_column(stop), _to_java_column(step))) def from_csv(col, schema, options=None): """ Parses a column containing a CSV string to a row with the specified schema. Returns `null`, in the case of an unparseable string. .. versionadded:: 3.0.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str string column in CSV format schema :class:`~pyspark.sql.Column` or str a string with schema in DDL format to use when parsing the CSV column. options : dict, optional options to control parsing. accepts the same options as the CSV datasource. See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-csv.html#data-source-option>`_ in the version you use. .. # noqa Examples -------- >>> data = [("1,2,3",)] >>> df = spark.createDataFrame(data, ("value",)) >>> df.select(from_csv(df.value, "a INT, b INT, c INT").alias("csv")).collect() [Row(csv=Row(a=1, b=2, c=3))] >>> value = data[0][0] >>> df.select(from_csv(df.value, schema_of_csv(value)).alias("csv")).collect() [Row(csv=Row(_c0=1, _c1=2, _c2=3))] >>> data = [(" abc",)] >>> df = spark.createDataFrame(data, ("value",)) >>> options = {'ignoreLeadingWhiteSpace': True} >>> df.select(from_csv(df.value, "s string", options).alias("csv")).collect() [Row(csv=Row(s='abc'))] """ sc = SparkContext._active_spark_context if isinstance(schema, str): schema = _create_column_from_literal(schema) elif isinstance(schema, Column): schema = _to_java_column(schema) else: raise TypeError("schema argument should be a column or string") jc = sc._jvm.functions.from_csv(_to_java_column(col), schema, _options_to_str(options)) return Column(jc) def _unresolved_named_lambda_variable(*name_parts): """ Create `o.a.s.sql.expressions.UnresolvedNamedLambdaVariable`, convert it to o.s.sql.Column and wrap in Python `Column` Parameters ---------- name_parts : str """ sc = SparkContext._active_spark_context name_parts_seq = _to_seq(sc, name_parts) expressions = sc._jvm.org.apache.spark.sql.catalyst.expressions return Column( sc._jvm.Column( expressions.UnresolvedNamedLambdaVariable(name_parts_seq) ) ) def _get_lambda_parameters(f): import inspect signature = inspect.signature(f) parameters = signature.parameters.values() # We should exclude functions that use # variable args and keyword argnames # as well as keyword only args supported_parameter_types = { inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.POSITIONAL_ONLY, } # Validate that # function arity is between 1 and 3 if not (1 <= len(parameters) <= 3): raise ValueError( "f should take between 1 and 3 arguments, but provided function takes {}".format( len(parameters) ) ) # and all arguments can be used as positional if not all(p.kind in supported_parameter_types for p in parameters): raise ValueError( "f should use only POSITIONAL or POSITIONAL OR KEYWORD arguments" ) return parameters def _create_lambda(f): """ Create `o.a.s.sql.expressions.LambdaFunction` corresponding to transformation described by f :param f: A Python of one of the following forms: - (Column) -> Column: ... - (Column, Column) -> Column: ... - (Column, Column, Column) -> Column: ... """ parameters = _get_lambda_parameters(f) sc = SparkContext._active_spark_context expressions = sc._jvm.org.apache.spark.sql.catalyst.expressions argnames = ["x", "y", "z"] args = [ _unresolved_named_lambda_variable( expressions.UnresolvedNamedLambdaVariable.freshVarName(arg) ) for arg in argnames[: len(parameters)] ] result = f(*args) if not isinstance(result, Column): raise ValueError("f should return Column, got {}".format(type(result))) jexpr = result._jc.expr() jargs = _to_seq(sc, [arg._jc.expr() for arg in args]) return expressions.LambdaFunction(jexpr, jargs, False) def _invoke_higher_order_function(name, cols, funs): """ Invokes expression identified by name, (relative to ```org.apache.spark.sql.catalyst.expressions``) and wraps the result with Column (first Scala one, then Python). :param name: Name of the expression :param cols: a list of columns :param funs: a list of((*Column) -> Column functions. :return: a Column """ sc = SparkContext._active_spark_context expressions = sc._jvm.org.apache.spark.sql.catalyst.expressions expr = getattr(expressions, name) jcols = [_to_java_column(col).expr() for col in cols] jfuns = [_create_lambda(f) for f in funs] return Column(sc._jvm.Column(expr(*jcols + jfuns))) def transform(col, f): """ Returns an array of elements after applying a transformation to each element in the input array. .. versionadded:: 3.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression f : function a function that is applied to each element of the input array. Can take one of the following forms: - Unary ``(x: Column) -> Column: ...`` - Binary ``(x: Column, i: Column) -> Column...``, where the second argument is a 0-based index of the element. and can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). Returns ------- :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame([(1, [1, 2, 3, 4])], ("key", "values")) >>> df.select(transform("values", lambda x: x * 2).alias("doubled")).show() +------------+ | doubled| +------------+ |[2, 4, 6, 8]| +------------+ >>> def alternate(x, i): ... return when(i % 2 == 0, x).otherwise(-x) >>> df.select(transform("values", alternate).alias("alternated")).show() +--------------+ | alternated| +--------------+ |[1, -2, 3, -4]| +--------------+ """ return _invoke_higher_order_function("ArrayTransform", [col], [f]) def exists(col, f): """ Returns whether a predicate holds for one or more elements in the array. .. versionadded:: 3.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression f : function ``(x: Column) -> Column: ...`` returning the Boolean expression. Can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). :return: a :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame([(1, [1, 2, 3, 4]), (2, [3, -1, 0])],("key", "values")) >>> df.select(exists("values", lambda x: x < 0).alias("any_negative")).show() +------------+ |any_negative| +------------+ | false| | true| +------------+ """ return _invoke_higher_order_function("ArrayExists", [col], [f]) def forall(col, f): """ Returns whether a predicate holds for every element in the array. .. versionadded:: 3.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression f : function ``(x: Column) -> Column: ...`` returning the Boolean expression. Can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). Returns ------- :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame( ... [(1, ["bar"]), (2, ["foo", "bar"]), (3, ["foobar", "foo"])], ... ("key", "values") ... ) >>> df.select(forall("values", lambda x: x.rlike("foo")).alias("all_foo")).show() +-------+ |all_foo| +-------+ | false| | false| | true| +-------+ """ return _invoke_higher_order_function("ArrayForAll", [col], [f]) def filter(col, f): """ Returns an array of elements for which a predicate holds in a given array. .. versionadded:: 3.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression f : function A function that returns the Boolean expression. Can take one of the following forms: - Unary ``(x: Column) -> Column: ...`` - Binary ``(x: Column, i: Column) -> Column...``, where the second argument is a 0-based index of the element. and can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). Returns ------- :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame( ... [(1, ["2018-09-20", "2019-02-03", "2019-07-01", "2020-06-01"])], ... ("key", "values") ... ) >>> def after_second_quarter(x): ... return month(to_date(x)) > 6 >>> df.select( ... filter("values", after_second_quarter).alias("after_second_quarter") ... ).show(truncate=False) +------------------------+ |after_second_quarter | +------------------------+ |[2018-09-20, 2019-07-01]| +------------------------+ """ return _invoke_higher_order_function("ArrayFilter", [col], [f]) def aggregate(col, initialValue, merge, finish=None): """ Applies a binary operator to an initial state and all elements in the array, and reduces this to a single state. The final state is converted into the final result by applying a finish function. Both functions can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). .. versionadded:: 3.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression initialValue : :class:`~pyspark.sql.Column` or str initial value. Name of column or expression merge : function a binary function ``(acc: Column, x: Column) -> Column...`` returning expression of the same type as ``zero`` finish : function an optional unary function ``(x: Column) -> Column: ...`` used to convert accumulated value. Returns ------- :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame([(1, [20.0, 4.0, 2.0, 6.0, 10.0])], ("id", "values")) >>> df.select(aggregate("values", lit(0.0), lambda acc, x: acc + x).alias("sum")).show() +----+ | sum| +----+ |42.0| +----+ >>> def merge(acc, x): ... count = acc.count + 1 ... sum = acc.sum + x ... return struct(count.alias("count"), sum.alias("sum")) >>> df.select( ... aggregate( ... "values", ... struct(lit(0).alias("count"), lit(0.0).alias("sum")), ... merge, ... lambda acc: acc.sum / acc.count, ... ).alias("mean") ... ).show() +----+ |mean| +----+ | 8.4| +----+ """ if finish is not None: return _invoke_higher_order_function( "ArrayAggregate", [col, initialValue], [merge, finish] ) else: return _invoke_higher_order_function( "ArrayAggregate", [col, initialValue], [merge] ) def zip_with(left, right, f): """ Merge two given arrays, element-wise, into a single array using a function. If one array is shorter, nulls are appended at the end to match the length of the longer array, before applying the function. .. versionadded:: 3.1.0 Parameters ---------- left : :class:`~pyspark.sql.Column` or str name of the first column or expression right : :class:`~pyspark.sql.Column` or str name of the second column or expression f : function a binary function ``(x1: Column, x2: Column) -> Column...`` Can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). Returns ------- :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame([(1, [1, 3, 5, 8], [0, 2, 4, 6])], ("id", "xs", "ys")) >>> df.select(zip_with("xs", "ys", lambda x, y: x ** y).alias("powers")).show(truncate=False) +---------------------------+ |powers | +---------------------------+ |[1.0, 9.0, 625.0, 262144.0]| +---------------------------+ >>> df = spark.createDataFrame([(1, ["foo", "bar"], [1, 2, 3])], ("id", "xs", "ys")) >>> df.select(zip_with("xs", "ys", lambda x, y: concat_ws("_", x, y)).alias("xs_ys")).show() +-----------------+ | xs_ys| +-----------------+ |[foo_1, bar_2, 3]| +-----------------+ """ return _invoke_higher_order_function("ZipWith", [left, right], [f]) def transform_keys(col, f): """ Applies a function to every key-value pair in a map and returns a map with the results of those applications as the new keys for the pairs. .. versionadded:: 3.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression f : function a binary function ``(k: Column, v: Column) -> Column...`` Can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). Returns ------- :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame([(1, {"foo": -2.0, "bar": 2.0})], ("id", "data")) >>> df.select(transform_keys( ... "data", lambda k, _: upper(k)).alias("data_upper") ... ).show(truncate=False) +-------------------------+ |data_upper | +-------------------------+ |{BAR -> 2.0, FOO -> -2.0}| +-------------------------+ """ return _invoke_higher_order_function("TransformKeys", [col], [f]) def transform_values(col, f): """ Applies a function to every key-value pair in a map and returns a map with the results of those applications as the new values for the pairs. .. versionadded:: 3.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression f : function a binary function ``(k: Column, v: Column) -> Column...`` Can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). Returns ------- :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame([(1, {"IT": 10.0, "SALES": 2.0, "OPS": 24.0})], ("id", "data")) >>> df.select(transform_values( ... "data", lambda k, v: when(k.isin("IT", "OPS"), v + 10.0).otherwise(v) ... ).alias("new_data")).show(truncate=False) +---------------------------------------+ |new_data | +---------------------------------------+ |{OPS -> 34.0, IT -> 20.0, SALES -> 2.0}| +---------------------------------------+ """ return _invoke_higher_order_function("TransformValues", [col], [f]) def map_filter(col, f): """ Returns a map whose key-value pairs satisfy a predicate. .. versionadded:: 3.1.0 Parameters ---------- col : :class:`~pyspark.sql.Column` or str name of column or expression f : function a binary function ``(k: Column, v: Column) -> Column...`` Can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). Returns ------- :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame([(1, {"foo": 42.0, "bar": 1.0, "baz": 32.0})], ("id", "data")) >>> df.select(map_filter( ... "data", lambda _, v: v > 30.0).alias("data_filtered") ... ).show(truncate=False) +--------------------------+ |data_filtered | +--------------------------+ |{baz -> 32.0, foo -> 42.0}| +--------------------------+ """ return _invoke_higher_order_function("MapFilter", [col], [f]) def map_zip_with(col1, col2, f): """ Merge two given maps, key-wise into a single map using a function. .. versionadded:: 3.1.0 Parameters ---------- col1 : :class:`~pyspark.sql.Column` or str name of the first column or expression col2 : :class:`~pyspark.sql.Column` or str name of the second column or expression f : function a ternary function ``(k: Column, v1: Column, v2: Column) -> Column...`` Can use methods of :class:`~pyspark.sql.Column`, functions defined in :py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. Python ``UserDefinedFunctions`` are not supported (`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). Returns ------- :class:`~pyspark.sql.Column` Examples -------- >>> df = spark.createDataFrame([ ... (1, {"IT": 24.0, "SALES": 12.00}, {"IT": 2.0, "SALES": 1.4})], ... ("id", "base", "ratio") ... ) >>> df.select(map_zip_with( ... "base", "ratio", lambda k, v1, v2: round(v1 * v2, 2)).alias("updated_data") ... ).show(truncate=False) +---------------------------+ |updated_data | +---------------------------+ |{SALES -> 16.8, IT -> 48.0}| +---------------------------+ """ return _invoke_higher_order_function("MapZipWith", [col1, col2], [f]) # ---------------------- Partition transform functions -------------------------------- def years(col): """ Partition transform function: A transform for timestamps and dates to partition data into years. .. versionadded:: 3.1.0 Examples -------- >>> df.writeTo("catalog.db.table").partitionedBy( # doctest: +SKIP ... years("ts") ... ).createOrReplace() Notes ----- This function can be used only in combination with :py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` method of the `DataFrameWriterV2`. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.years(_to_java_column(col))) def months(col): """ Partition transform function: A transform for timestamps and dates to partition data into months. .. versionadded:: 3.1.0 Examples -------- >>> df.writeTo("catalog.db.table").partitionedBy( ... months("ts") ... ).createOrReplace() # doctest: +SKIP Notes ----- This function can be used only in combination with :py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` method of the `DataFrameWriterV2`. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.months(_to_java_column(col))) def days(col): """ Partition transform function: A transform for timestamps and dates to partition data into days. .. versionadded:: 3.1.0 Examples -------- >>> df.writeTo("catalog.db.table").partitionedBy( # doctest: +SKIP ... days("ts") ... ).createOrReplace() Notes ----- This function can be used only in combination with :py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` method of the `DataFrameWriterV2`. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.days(_to_java_column(col))) def hours(col): """ Partition transform function: A transform for timestamps to partition data into hours. .. versionadded:: 3.1.0 Examples -------- >>> df.writeTo("catalog.db.table").partitionedBy( # doctest: +SKIP ... hours("ts") ... ).createOrReplace() Notes ----- This function can be used only in combination with :py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` method of the `DataFrameWriterV2`. """ sc = SparkContext._active_spark_context return Column(sc._jvm.functions.hours(_to_java_column(col))) def bucket(numBuckets, col): """ Partition transform function: A transform for any type that partitions by a hash of the input column. .. versionadded:: 3.1.0 Examples -------- >>> df.writeTo("catalog.db.table").partitionedBy( # doctest: +SKIP ... bucket(42, "ts") ... ).createOrReplace() Notes ----- This function can be used only in combination with :py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` method of the `DataFrameWriterV2`. """ if not isinstance(numBuckets, (int, Column)): raise TypeError( "numBuckets should be a Column or an int, got {}".format(type(numBuckets)) ) sc = SparkContext._active_spark_context numBuckets = ( _create_column_from_literal(numBuckets) if isinstance(numBuckets, int) else _to_java_column(numBuckets) ) return Column(sc._jvm.functions.bucket(numBuckets, _to_java_column(col))) # ---------------------------- User Defined Function ---------------------------------- def udf(f=None, returnType=StringType()): """Creates a user defined function (UDF). .. versionadded:: 1.3.0 Parameters ---------- f : function python function if used as a standalone function returnType : :class:`pyspark.sql.types.DataType` or str the return type of the user-defined function. The value can be either a :class:`pyspark.sql.types.DataType` object or a DDL-formatted type string. Examples -------- >>> from pyspark.sql.types import IntegerType >>> slen = udf(lambda s: len(s), IntegerType()) >>> @udf ... def to_upper(s): ... if s is not None: ... return s.upper() ... >>> @udf(returnType=IntegerType()) ... def add_one(x): ... if x is not None: ... return x + 1 ... >>> df = spark.createDataFrame([(1, "John Doe", 21)], ("id", "name", "age")) >>> df.select(slen("name").alias("slen(name)"), to_upper("name"), add_one("age")).show() +----------+--------------+------------+ |slen(name)|to_upper(name)|add_one(age)| +----------+--------------+------------+ | 8| JOHN DOE| 22| +----------+--------------+------------+ Notes ----- The user-defined functions are considered deterministic by default. Due to optimization, duplicate invocations may be eliminated or the function may even be invoked more times than it is present in the query. If your function is not deterministic, call `asNondeterministic` on the user defined function. E.g.: >>> from pyspark.sql.types import IntegerType >>> import random >>> random_udf = udf(lambda: int(random.random() * 100), IntegerType()).asNondeterministic() The user-defined functions do not support conditional expressions or short circuiting in boolean expressions and it ends up with being executed all internally. If the functions can fail on special rows, the workaround is to incorporate the condition into the functions. The user-defined functions do not take keyword arguments on the calling side. """ # The following table shows most of Python data and SQL type conversions in normal UDFs that # are not yet visible to the user. Some of behaviors are buggy and might be changed in the near # future. The table might have to be eventually documented externally. # Please see SPARK-28131's PR to see the codes in order to generate the table below. # # +-----------------------------+--------------+----------+------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+----------------------------+------------+--------------+------------------+----------------------+ # noqa # |SQL Type \ Python Value(Type)|None(NoneType)|True(bool)|1(int)| a(str)| 1970-01-01(date)|1970-01-01 00:00:00(datetime)|1.0(float)|array('i', [1])(array)|[1](list)| (1,)(tuple)|bytearray(b'ABC')(bytearray)| 1(Decimal)|{'a': 1}(dict)|Row(kwargs=1)(Row)|Row(namedtuple=1)(Row)| # noqa # +-----------------------------+--------------+----------+------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+----------------------------+------------+--------------+------------------+----------------------+ # noqa # | boolean| None| True| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | tinyint| None| None| 1| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | smallint| None| None| 1| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | int| None| None| 1| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | bigint| None| None| 1| None| None| None| None| None| None| None| None| None| None| X| X| # noqa # | string| None| 'true'| '1'| 'a'|'java.util.Gregor...| 'java.util.Gregor...| '1.0'| '[I@66cbb73a'| '[1]'|'[Ljava.lang.Obje...| '[B@5a51eb1a'| '1'| '{a=1}'| X| X| # noqa # | date| None| X| X| X|datetime.date(197...| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa # | timestamp| None| X| X| X| X| datetime.datetime...| X| X| X| X| X| X| X| X| X| # noqa # | float| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa # | double| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa # | array<int>| None| None| None| None| None| None| None| [1]| [1]| [1]| [65, 66, 67]| None| None| X| X| # noqa # | binary| None| None| None|bytearray(b'a')| None| None| None| None| None| None| bytearray(b'ABC')| None| None| X| X| # noqa # | decimal(10,0)| None| None| None| None| None| None| None| None| None| None| None|Decimal('1')| None| X| X| # noqa # | map<string,int>| None| None| None| None| None| None| None| None| None| None| None| None| {'a': 1}| X| X| # noqa # | struct<_1:int>| None| X| X| X| X| X| X| X|Row(_1=1)| Row(_1=1)| X| X| Row(_1=None)| Row(_1=1)| Row(_1=1)| # noqa # +-----------------------------+--------------+----------+------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+----------------------------+------------+--------------+------------------+----------------------+ # noqa # # Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be # used in `returnType`. # Note: The values inside of the table are generated by `repr`. # Note: 'X' means it throws an exception during the conversion. # Note: Python 3.7.3 is used. # decorator @udf, @udf(), @udf(dataType()) if f is None or isinstance(f, (str, DataType)): # If DataType has been passed as a positional argument # for decorator use it as a returnType return_type = f or returnType return functools.partial(_create_udf, returnType=return_type, evalType=PythonEvalType.SQL_BATCHED_UDF) else: return _create_udf(f=f, returnType=returnType, evalType=PythonEvalType.SQL_BATCHED_UDF) def _test(): import doctest from pyspark.sql import Row, SparkSession import pyspark.sql.functions globs = pyspark.sql.functions.__dict__.copy() spark = SparkSession.builder\ .master("local[4]")\ .appName("sql.functions tests")\ .getOrCreate() sc = spark.sparkContext globs['sc'] = sc globs['spark'] = spark globs['df'] = spark.createDataFrame([Row(age=2, name='Alice'), Row(age=5, name='Bob')]) (failure_count, test_count) = doctest.testmod( pyspark.sql.functions, globs=globs, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE) spark.stop() if failure_count: sys.exit(-1) if __name__ == "__main__": _test()
apache-2.0
-4,960,368,121,740,678,000
31.058031
309
0.584804
false
vitorespindola/home-assistant
homeassistant/components/light/tellstick.py
4
2926
""" Support for Tellstick lights. """ import logging # pylint: disable=no-name-in-module, import-error from homeassistant.components.light import Light, ATTR_BRIGHTNESS from homeassistant.const import ATTR_FRIENDLY_NAME import tellcore.constants as tellcore_constants def setup_platform(hass, config, add_devices_callback, discovery_info=None): """ Find and return tellstick lights. """ try: import tellcore.telldus as telldus except ImportError: logging.getLogger(__name__).exception( "Failed to import tellcore") return [] core = telldus.TelldusCore() switches_and_lights = core.devices() lights = [] for switch in switches_and_lights: if switch.methods(tellcore_constants.TELLSTICK_DIM): lights.append(TellstickLight(switch)) add_devices_callback(lights) class TellstickLight(Light): """ Represents a tellstick light """ last_sent_command_mask = (tellcore_constants.TELLSTICK_TURNON | tellcore_constants.TELLSTICK_TURNOFF | tellcore_constants.TELLSTICK_DIM | tellcore_constants.TELLSTICK_UP | tellcore_constants.TELLSTICK_DOWN) def __init__(self, tellstick): self.tellstick = tellstick self.state_attr = {ATTR_FRIENDLY_NAME: tellstick.name} self._brightness = 0 @property def name(self): """ Returns the name of the switch if any. """ return self.tellstick.name @property def is_on(self): """ True if switch is on. """ return self._brightness > 0 @property def brightness(self): """ Brightness of this light between 0..255. """ return self._brightness def turn_off(self, **kwargs): """ Turns the switch off. """ self.tellstick.turn_off() self._brightness = 0 def turn_on(self, **kwargs): """ Turns the switch on. """ brightness = kwargs.get(ATTR_BRIGHTNESS) if brightness is None: self._brightness = 255 else: self._brightness = brightness self.tellstick.dim(self._brightness) def update(self): """ Update state of the light. """ last_command = self.tellstick.last_sent_command( self.last_sent_command_mask) if last_command == tellcore_constants.TELLSTICK_TURNON: self._brightness = 255 elif last_command == tellcore_constants.TELLSTICK_TURNOFF: self._brightness = 0 elif (last_command == tellcore_constants.TELLSTICK_DIM or last_command == tellcore_constants.TELLSTICK_UP or last_command == tellcore_constants.TELLSTICK_DOWN): last_sent_value = self.tellstick.last_sent_value() if last_sent_value is not None: self._brightness = last_sent_value
mit
9,059,041,214,639,521,000
32.632184
76
0.613465
false
cpd4t/CPD4T_Minecraft_Workshop
trafficlights.py
2
1305
# import modules import mcpi.minecraft as minecraft from time import sleep # connect python to minecraft mc = minecraft.Minecraft.create() # create CONSTANTS for block and light colours AIR = 0 STONE = 1 WOOL = 35 BLACK = 15 RED = 14 AMBER = 4 GREEN = 5 # clear area in middle of map and move player there mc.setBlocks(-60, 0, -60, 60, 50, 60, AIR) mc.setBlocks(-60, -1, -60, 60, -1, 60, STONE) mc.player.setPos(5, 0, 0) # create initial light stack for i in range(1, 7): mc.setBlock(10, 0 +i, 0, WOOL, 8) mc.setBlock(9, 6, 0, WOOL, BLACK) mc.setBlock(9, 5, 0, WOOL, BLACK) mc.setBlock(9, 4, 0, WOOL, BLACK) # wait three seconds before starting sequence sleep(3) # traffic light sequence while True: # turn on red mc.setBlock(9, 6, 0, WOOL, RED) # wait three seconds sleep(3) # turn on amber mc.setBlock(9, 5, 0, WOOL, AMBER) # wait one second sleep(1) # turn off red & amber, turn on green mc.setBlock(9, 6, 0, WOOL, BLACK) mc.setBlock(9, 5, 0, WOOL, BLACK) mc.setBlock(9, 4, 0, WOOL, GREEN) # wait three seconds sleep(3) # turn off green mc.setBlock(9, 4, 0, WOOL, BLACK) # turn on amber mc.setBlock(9, 5, 0, WOOL, AMBER) # wait one second sleep(1) # turn off amber mc.setBlock(9, 5, 0, WOOL, BLACK)
cc0-1.0
1,322,080,360,059,579,400
20.75
51
0.636015
false
crossbario/crossbar-fabric-cli
docs/conf.py
1
5424
# -*- coding: utf-8 -*- ##################################################################################### # # Copyright (c) Crossbar.io Technologies GmbH # # Unless a separate license agreement exists between you and Crossbar.io GmbH (e.g. # you have purchased a commercial license), the license terms below apply. # # Should you enter into a separate license agreement after having received a copy of # this software, then the terms of such license agreement replace the terms below at # the time at which such license agreement becomes effective. # # In case a separate license agreement ends, and such agreement ends without being # replaced by another separate license agreement, the license terms below apply # from the time at which said agreement ends. # # LICENSE TERMS # # This program is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License, version 3, as published by the # Free Software Foundation. This program is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.en.html>. # ##################################################################################### #from __future__ import absolute_import import sys import os import shlex import time from cbsh import __version__ try: import sphinx_rtd_theme except ImportError: sphinx_rtd_theme = None try: from sphinxcontrib import spelling except ImportError: spelling = None # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('./_extensions')) #sys.path.insert(0, os.path.abspath('..')) # Check if we are building on readthedocs RTD_BUILD = os.environ.get('READTHEDOCS', None) == 'True' # -- Project information ----------------------------------------------------- project = 'Crossbar.io Shell' copyright = '2018, Crossbar.io Technologies GmbH' author = 'Crossbar.io Technologies GmbH' # The short X.Y version version = __version__ # The full version, including alpha/beta/rc tags release = __version__ # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ # 'sphinxcontrib.xbr', 'sphinxcontrib.spelling', ] # extensions not available on RTD if spelling is not None: extensions.append('sphinxcontrib.spelling') spelling_lang = 'en_US' spelling_show_suggestions = False spelling_word_list_filename = 'spelling_wordlist.txt' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'contents' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' #pygments_style = 'monokai' #pygments_style = 'native' #pygments_style = 'pastie' #pygments_style = 'friendly' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # if sphinx_rtd_theme: html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = "default" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {}
mit
-4,284,822,098,671,075,000
32.689441
85
0.683075
false
powlo/script.module.pydevd
lib/tests/check_pydevconsole.py
7
3892
import sys import os #Put pydevconsole in the path. sys.argv[0] = os.path.dirname(sys.argv[0]) sys.path.insert(1, os.path.join(os.path.dirname(sys.argv[0]))) print('Running tests with:', sys.executable) print('PYTHONPATH:') print('\n'.join(sorted(sys.path))) import threading import unittest import pydevconsole from pydev_imports import xmlrpclib, SimpleXMLRPCServer try: raw_input raw_input_name = 'raw_input' except NameError: raw_input_name = 'input' #======================================================================================================================= # Test #======================================================================================================================= class Test(unittest.TestCase): def startClientThread(self, client_port): class ClientThread(threading.Thread): def __init__(self, client_port): threading.Thread.__init__(self) self.client_port = client_port def run(self): class HandleRequestInput: def RequestInput(self): return 'RequestInput: OK' handle_request_input = HandleRequestInput() import pydev_localhost print('Starting client with:', pydev_localhost.get_localhost(), self.client_port) client_server = SimpleXMLRPCServer((pydev_localhost.get_localhost(), self.client_port), logRequests=False) client_server.register_function(handle_request_input.RequestInput) client_server.serve_forever() client_thread = ClientThread(client_port) client_thread.setDaemon(True) client_thread.start() return client_thread def getFreeAddresses(self): import socket s = socket.socket() s.bind(('', 0)) port0 = s.getsockname()[1] s1 = socket.socket() s1.bind(('', 0)) port1 = s1.getsockname()[1] s.close() s1.close() return port0, port1 def testServer(self): client_port, server_port = self.getFreeAddresses() class ServerThread(threading.Thread): def __init__(self, client_port, server_port): threading.Thread.__init__(self) self.client_port = client_port self.server_port = server_port def run(self): import pydev_localhost print('Starting server with:', pydev_localhost.get_localhost(), self.server_port, self.client_port) pydevconsole.StartServer(pydev_localhost.get_localhost(), self.server_port, self.client_port) server_thread = ServerThread(client_port, server_port) server_thread.setDaemon(True) server_thread.start() client_thread = self.startClientThread(client_port) #@UnusedVariable import time time.sleep(.3) #let's give it some time to start the threads import pydev_localhost server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), server_port)) server.addExec("import sys; print('Running with: %s %s' % (sys.executable or sys.platform, sys.version))") server.addExec('class Foo:') server.addExec(' pass') server.addExec('') server.addExec('foo = Foo()') server.addExec('a = %s()' % raw_input_name) server.addExec('print (a)') #======================================================================================================================= # main #======================================================================================================================= if __name__ == '__main__': unittest.main()
epl-1.0
-538,343,551,622,194,500
36.066667
122
0.507965
false
umkay/zulip
zerver/logging_handlers.py
9
3074
from __future__ import absolute_import from django.conf import settings import logging import traceback import platform from django.core import mail from django.http import HttpRequest from django.utils.log import AdminEmailHandler from django.views.debug import ExceptionReporter, get_exception_reporter_filter from zerver.lib.queue import queue_json_publish class AdminZulipHandler(logging.Handler): """An exception log handler that sends the exception to the queue to be sent to the Zulip feedback server. """ # adapted in part from django/utils/log.py def __init__(self): # type: () -> None logging.Handler.__init__(self) def emit(self, record): # type: (ExceptionReporter) -> None try: request = record.request # type: HttpRequest filter = get_exception_reporter_filter(request) if record.exc_info: stack_trace = ''.join(traceback.format_exception(*record.exc_info)) else: stack_trace = None try: user_profile = request.user user_full_name = user_profile.full_name user_email = user_profile.email except Exception: traceback.print_exc() # Error was triggered by an anonymous user. user_full_name = None user_email = None report = dict( node = platform.node(), method = request.method, path = request.path, data = request.GET if request.method == 'GET' else filter.get_post_parameters(request), remote_addr = request.META.get('REMOTE_ADDR', None), query_string = request.META.get('QUERY_STRING', None), server_name = request.META.get('SERVER_NAME', None), message = record.getMessage(), stack_trace = stack_trace, user_full_name = user_full_name, user_email = user_email, ) except: traceback.print_exc() report = dict( node = platform.node(), message = record.getMessage(), ) try: if settings.STAGING_ERROR_NOTIFICATIONS: # On staging, process the report directly so it can happen inside this # try/except to prevent looping from zilencer.error_notify import notify_server_error notify_server_error(report) else: queue_json_publish('error_reports', dict( type = "server", report = report, ), lambda x: None) except: # If this breaks, complain loudly but don't pass the traceback up the stream # However, we *don't* want to use logging.exception since that could trigger a loop. logging.warning("Reporting an exception triggered an exception!", exc_info=True)
apache-2.0
-5,967,621,564,974,732,000
35.595238
96
0.562459
false
vanzaj/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
Chapter3_MCMC/github_pull.py
95
2327
#github data scrapper """ variables of interest: indp. variables - language, given as a binary variable. Need 4 positions for 5 langagues - #number of days created ago, 1 position - has wiki? Boolean, 1 position - followers, 1 position - following, 1 position - constant dep. variables -stars/watchers -forks """ from json import loads import datetime import numpy as np from requests import get MAX = 8000000 today = datetime.datetime.today() randint = np.random.randint N = 120 #sample size. auth = ("username", "password" ) language_mappings = {"Python": 0, "JavaScript": 1, "Ruby": 2, "Java":3, "Shell":4, "PHP":5} #define data matrix: X = np.zeros( (N , 12), dtype = int ) for i in xrange(N): is_fork = True is_valid_language = False while is_fork == True or is_valid_language == False: is_fork = True is_valid_language = False params = {"since":randint(0, MAX ) } r = get("https://api.github.com/repositories", params = params, auth=auth ) results = loads( r.text )[0] #im only interested in the first one, and if it is not a fork. is_fork = results["fork"] r = get( results["url"], auth = auth) #check the language repo_results = loads( r.text ) try: language_mappings[ repo_results["language" ] ] is_valid_language = True except: pass #languages X[ i, language_mappings[ repo_results["language" ] ] ] = 1 #delta time X[ i, 6] = ( today - datetime.datetime.strptime( repo_results["created_at"][:10], "%Y-%m-%d" ) ).days #haswiki X[i, 7] = repo_results["has_wiki"] #get user information r = get( results["owner"]["url"] , auth = auth) user_results = loads( r.text ) X[i, 8] = user_results["following"] X[i, 9] = user_results["followers"] #get dep. data X[i, 10] = repo_results["watchers_count"] X[i, 11] = repo_results["forks_count"] print print " -------------- " print i, ": ", results["full_name"], repo_results["language" ], repo_results["watchers_count"], repo_results["forks_count"] print " -------------- " print np.savetxt("data/github_data.csv", X, delimiter=",", fmt="%d" )
mit
2,395,613,771,689,942,500
27.036145
127
0.576708
false
yahman72/robotframework
src/robot/output/loggerhelper.py
4
4060
# Copyright 2008-2015 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from robot import utils from robot.errors import DataError from robot.model import Message as BaseMessage LEVELS = { 'NONE' : 6, 'ERROR' : 5, 'FAIL' : 4, 'WARN' : 3, 'INFO' : 2, 'DEBUG' : 1, 'TRACE' : 0, } class AbstractLogger: def __init__(self, level='TRACE'): self._is_logged = IsLogged(level) def set_level(self, level): return self._is_logged.set_level(level) def trace(self, msg): self.write(msg, 'TRACE') def debug(self, msg): self.write(msg, 'DEBUG') def info(self, msg): self.write(msg, 'INFO') def warn(self, msg): self.write(msg, 'WARN') def fail(self, msg): html = False if msg.startswith("*HTML*"): html = True msg = msg[6:].lstrip() self.write(msg, 'FAIL', html) def error(self, msg): self.write(msg, 'ERROR') def write(self, message, level, html=False): self.message(Message(message, level, html)) def message(self, msg): raise NotImplementedError(self.__class__) class Message(BaseMessage): __slots__ = ['_message'] def __init__(self, message, level='INFO', html=False, timestamp=None): message = self._normalize_message(message) level, html = self._get_level_and_html(level, html) timestamp = timestamp or utils.get_timestamp() BaseMessage.__init__(self, message, level, html, timestamp) def _normalize_message(self, msg): if callable(msg): return msg if not isinstance(msg, unicode): msg = utils.unic(msg) if '\r\n' in msg: msg = msg.replace('\r\n', '\n') return msg def _get_level_and_html(self, level, html): level = level.upper() if level == 'HTML': return 'INFO', True if level not in LEVELS: raise DataError("Invalid log level '%s'" % level) return level, html def _get_message(self): if callable(self._message): self._message = self._message() return self._message def _set_message(self, message): self._message = message message = property(_get_message, _set_message) class IsLogged: def __init__(self, level): self._str_level = level self._int_level = self._level_to_int(level) def __call__(self, level): return self._level_to_int(level) >= self._int_level def set_level(self, level): old = self._str_level.upper() self.__init__(level) return old def _level_to_int(self, level): try: return LEVELS[level.upper()] except KeyError: raise DataError("Invalid log level '%s'" % level) class AbstractLoggerProxy: _methods = NotImplemented _no_method = lambda *args: None def __init__(self, logger): self.logger = logger for name in self._methods: setattr(self, name, self._get_method(logger, name)) def _get_method(self, logger, name): for method_name in self._get_method_names(name): if hasattr(logger, method_name): return getattr(logger, method_name) return self._no_method def _get_method_names(self, name): return [name, self._toCamelCase(name)] def _toCamelCase(self, name): parts = name.split('_') return ''.join([parts[0]] + [part.capitalize() for part in parts[1:]])
apache-2.0
604,106,667,064,531,500
26.808219
78
0.598768
false
Lkhagvadelger/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/performance_tests/perftest.py
115
17075
# Copyright (C) 2012 Google Inc. All rights reserved. # Copyright (C) 2012 Zoltan Horvath, Adobe Systems Incorporated. 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. import errno import logging import math import re import os import signal import socket import subprocess import sys import time # Import for auto-install if sys.platform not in ('cygwin', 'win32'): # FIXME: webpagereplay doesn't work on win32. See https://bugs.webkit.org/show_bug.cgi?id=88279. import webkitpy.thirdparty.autoinstalled.webpagereplay.replay from webkitpy.layout_tests.controllers.test_result_writer import TestResultWriter from webkitpy.port.driver import DriverInput from webkitpy.port.driver import DriverOutput DEFAULT_TEST_RUNNER_COUNT = 4 _log = logging.getLogger(__name__) class PerfTestMetric(object): def __init__(self, metric, unit=None, iterations=None): # FIXME: Fix runner.js to report correct metric names self._iterations = iterations or [] self._unit = unit or self.metric_to_unit(metric) self._metric = self.time_unit_to_metric(self._unit) if metric == 'Time' else metric def name(self): return self._metric def has_values(self): return bool(self._iterations) def append_group(self, group_values): assert isinstance(group_values, list) self._iterations.append(group_values) def grouped_iteration_values(self): return self._iterations def flattened_iteration_values(self): return [value for group_values in self._iterations for value in group_values] def unit(self): return self._unit @staticmethod def metric_to_unit(metric): assert metric in ('Time', 'Malloc', 'JSHeap') return 'ms' if metric == 'Time' else 'bytes' @staticmethod def time_unit_to_metric(unit): return {'fps': 'FrameRate', 'runs/s': 'Runs', 'ms': 'Time'}[unit] class PerfTest(object): def __init__(self, port, test_name, test_path, test_runner_count=DEFAULT_TEST_RUNNER_COUNT): self._port = port self._test_name = test_name self._test_path = test_path self._description = None self._metrics = {} self._ordered_metrics_name = [] self._test_runner_count = test_runner_count def test_name(self): return self._test_name def test_name_without_file_extension(self): return re.sub(r'\.\w+$', '', self.test_name()) def test_path(self): return self._test_path def description(self): return self._description def prepare(self, time_out_ms): return True def _create_driver(self): return self._port.create_driver(worker_number=0, no_timeout=True) def run(self, time_out_ms): for _ in xrange(self._test_runner_count): driver = self._create_driver() try: if not self._run_with_driver(driver, time_out_ms): return None finally: driver.stop() should_log = not self._port.get_option('profile') if should_log and self._description: _log.info('DESCRIPTION: %s' % self._description) results = {} for metric_name in self._ordered_metrics_name: metric = self._metrics[metric_name] results[metric.name()] = metric.grouped_iteration_values() if should_log: legacy_chromium_bot_compatible_name = self.test_name_without_file_extension().replace('/', ': ') self.log_statistics(legacy_chromium_bot_compatible_name + ': ' + metric.name(), metric.flattened_iteration_values(), metric.unit()) return results @staticmethod def log_statistics(test_name, values, unit): sorted_values = sorted(values) # Compute the mean and variance using Knuth's online algorithm (has good numerical stability). square_sum = 0 mean = 0 for i, time in enumerate(sorted_values): delta = time - mean sweep = i + 1.0 mean += delta / sweep square_sum += delta * (time - mean) middle = int(len(sorted_values) / 2) mean = sum(sorted_values) / len(values) median = sorted_values[middle] if len(sorted_values) % 2 else (sorted_values[middle - 1] + sorted_values[middle]) / 2 stdev = math.sqrt(square_sum / (len(sorted_values) - 1)) if len(sorted_values) > 1 else 0 _log.info('RESULT %s= %s %s' % (test_name, mean, unit)) _log.info('median= %s %s, stdev= %s %s, min= %s %s, max= %s %s' % (median, unit, stdev, unit, sorted_values[0], unit, sorted_values[-1], unit)) _description_regex = re.compile(r'^Description: (?P<description>.*)$', re.IGNORECASE) _metrics_regex = re.compile(r'^(?P<metric>Time|Malloc|JS Heap):') _statistics_keys = ['avg', 'median', 'stdev', 'min', 'max', 'unit', 'values'] _score_regex = re.compile(r'^(?P<key>' + r'|'.join(_statistics_keys) + r')\s+(?P<value>([0-9\.]+(,\s+)?)+)\s*(?P<unit>.*)') def _run_with_driver(self, driver, time_out_ms): output = self.run_single(driver, self.test_path(), time_out_ms) self._filter_output(output) if self.run_failed(output): return False current_metric = None for line in re.split('\n', output.text): description_match = self._description_regex.match(line) metric_match = self._metrics_regex.match(line) score = self._score_regex.match(line) if description_match: self._description = description_match.group('description') elif metric_match: current_metric = metric_match.group('metric').replace(' ', '') elif score: if score.group('key') != 'values': continue metric = self._ensure_metrics(current_metric, score.group('unit')) metric.append_group(map(lambda value: float(value), score.group('value').split(', '))) else: _log.error('ERROR: ' + line) return False return True def _ensure_metrics(self, metric_name, unit=None): if metric_name not in self._metrics: self._metrics[metric_name] = PerfTestMetric(metric_name, unit) self._ordered_metrics_name.append(metric_name) return self._metrics[metric_name] def run_single(self, driver, test_path, time_out_ms, should_run_pixel_test=False): return driver.run_test(DriverInput(test_path, time_out_ms, image_hash=None, should_run_pixel_test=should_run_pixel_test), stop_when_done=False) def run_failed(self, output): if output.text == None or output.error: pass elif output.timeout: _log.error('timeout: %s' % self.test_name()) elif output.crash: _log.error('crash: %s' % self.test_name()) else: return False if output.error: _log.error('error: %s\n%s' % (self.test_name(), output.error)) return True @staticmethod def _should_ignore_line(regexps, line): if not line: return True for regexp in regexps: if regexp.search(line): return True return False _lines_to_ignore_in_stderr = [ re.compile(r'^Unknown option:'), re.compile(r'^\[WARNING:proxy_service.cc'), re.compile(r'^\[INFO:'), # These stderr messages come from content_shell on chromium-linux. re.compile(r'INFO:SkFontHost_fontconfig.cpp'), re.compile(r'Running without the SUID sandbox'), ] _lines_to_ignore_in_parser_result = [ re.compile(r'^Running \d+ times$'), re.compile(r'^Ignoring warm-up '), re.compile(r'^Info:'), re.compile(r'^\d+(.\d+)?(\s*(runs\/s|ms|fps))?$'), # Following are for handle existing test like Dromaeo re.compile(re.escape("""main frame - has 1 onunload handler(s)""")), re.compile(re.escape("""frame "<!--framePath //<!--frame0-->-->" - has 1 onunload handler(s)""")), re.compile(re.escape("""frame "<!--framePath //<!--frame0-->/<!--frame0-->-->" - has 1 onunload handler(s)""")), # Following is for html5.html re.compile(re.escape("""Blocked access to external URL http://www.whatwg.org/specs/web-apps/current-work/""")), re.compile(r"CONSOLE MESSAGE: (line \d+: )?Blocked script execution in '[A-Za-z0-9\-\.:]+' because the document's frame is sandboxed and the 'allow-scripts' permission is not set."), re.compile(r"CONSOLE MESSAGE: (line \d+: )?Not allowed to load local resource"), # Dromaeo reports values for subtests. Ignore them for now. re.compile(r'(?P<name>.+): \[(?P<values>(\d+(.\d+)?,\s+)*\d+(.\d+)?)\]'), ] def _filter_output(self, output): if output.error: output.error = '\n'.join([line for line in re.split('\n', output.error) if not self._should_ignore_line(self._lines_to_ignore_in_stderr, line)]) if output.text: output.text = '\n'.join([line for line in re.split('\n', output.text) if not self._should_ignore_line(self._lines_to_ignore_in_parser_result, line)]) class SingleProcessPerfTest(PerfTest): def __init__(self, port, test_name, test_path, test_runner_count=1): super(SingleProcessPerfTest, self).__init__(port, test_name, test_path, test_runner_count) class ReplayServer(object): def __init__(self, archive, record): self._process = None # FIXME: Should error if local proxy isn't set to forward requests to localhost:8080 and localhost:8443 replay_path = webkitpy.thirdparty.autoinstalled.webpagereplay.replay.__file__ args = ['python', replay_path, '--no-dns_forwarding', '--port', '8080', '--ssl_port', '8443', '--use_closest_match', '--log_level', 'warning'] if record: args.append('--record') args.append(archive) self._process = subprocess.Popen(args) def wait_until_ready(self): for i in range(0, 3): try: connection = socket.create_connection(('localhost', '8080'), timeout=1) connection.close() return True except socket.error: time.sleep(1) continue return False def stop(self): if self._process: self._process.send_signal(signal.SIGINT) self._process.wait() self._process = None def __del__(self): self.stop() class ReplayPerfTest(PerfTest): _FORCE_GC_FILE = 'resources/force-gc.html' def __init__(self, port, test_name, test_path, test_runner_count=DEFAULT_TEST_RUNNER_COUNT): super(ReplayPerfTest, self).__init__(port, test_name, test_path, test_runner_count) self.force_gc_test = self._port.host.filesystem.join(self._port.perf_tests_dir(), self._FORCE_GC_FILE) def _start_replay_server(self, archive, record): try: return ReplayServer(archive, record) except OSError as error: if error.errno == errno.ENOENT: _log.error("Replay tests require web-page-replay.") else: raise error def prepare(self, time_out_ms): filesystem = self._port.host.filesystem path_without_ext = filesystem.splitext(self.test_path())[0] self._archive_path = filesystem.join(path_without_ext + '.wpr') self._expected_image_path = filesystem.join(path_without_ext + '-expected.png') self._url = filesystem.read_text_file(self.test_path()).split('\n')[0] if filesystem.isfile(self._archive_path) and filesystem.isfile(self._expected_image_path): _log.info("Replay ready for %s" % self._archive_path) return True _log.info("Preparing replay for %s" % self.test_name()) driver = self._port.create_driver(worker_number=0, no_timeout=True) try: output = self.run_single(driver, self._archive_path, time_out_ms, record=True) finally: driver.stop() if not output or not filesystem.isfile(self._archive_path): _log.error("Failed to prepare a replay for %s" % self.test_name()) return False _log.info("Prepared replay for %s" % self.test_name()) return True def _run_with_driver(self, driver, time_out_ms): times = [] malloc = [] js_heap = [] for i in range(0, 6): output = self.run_single(driver, self.test_path(), time_out_ms) if not output or self.run_failed(output): return False if i == 0: continue times.append(output.test_time * 1000) if not output.measurements: continue for metric, result in output.measurements.items(): assert metric == 'Malloc' or metric == 'JSHeap' if metric == 'Malloc': malloc.append(result) else: js_heap.append(result) if times: self._ensure_metrics('Time').append_group(times) if malloc: self._ensure_metrics('Malloc').append_group(malloc) if js_heap: self._ensure_metrics('JSHeap').append_group(js_heap) return True def run_single(self, driver, url, time_out_ms, record=False): server = self._start_replay_server(self._archive_path, record) if not server: _log.error("Web page replay didn't start.") return None try: _log.debug("Waiting for Web page replay to start.") if not server.wait_until_ready(): _log.error("Web page replay didn't start.") return None _log.debug("Web page replay started. Loading the page.") # Force GC to prevent pageload noise. See https://bugs.webkit.org/show_bug.cgi?id=98203 super(ReplayPerfTest, self).run_single(driver, self.force_gc_test, time_out_ms, False) output = super(ReplayPerfTest, self).run_single(driver, self._url, time_out_ms, should_run_pixel_test=True) if self.run_failed(output): return None if not output.image: _log.error("Loading the page did not generate image results") _log.error(output.text) return None filesystem = self._port.host.filesystem dirname = filesystem.dirname(self._archive_path) filename = filesystem.split(self._archive_path)[1] writer = TestResultWriter(filesystem, self._port, dirname, filename) if record: writer.write_image_files(actual_image=None, expected_image=output.image) else: writer.write_image_files(actual_image=output.image, expected_image=None) return output finally: server.stop() class PerfTestFactory(object): _pattern_map = [ (re.compile(r'^Dromaeo/'), SingleProcessPerfTest), (re.compile(r'(.+)\.replay$'), ReplayPerfTest), ] @classmethod def create_perf_test(cls, port, test_name, path, test_runner_count=DEFAULT_TEST_RUNNER_COUNT): for (pattern, test_class) in cls._pattern_map: if pattern.match(test_name): return test_class(port, test_name, path, test_runner_count) return PerfTest(port, test_name, path, test_runner_count)
bsd-3-clause
-8,570,852,912,088,339,000
38.43418
190
0.611186
false
exploreodoo/datStruct
odoo/openerp/addons/test_impex/tests/test_import.py
231
30712
# -*- coding: utf-8 -*- import openerp.modules.registry import openerp from openerp.tests import common from openerp.tools.misc import mute_logger def ok(n): """ Successful import of ``n`` records :param int n: number of records which should have been imported """ return n, 0, 0, 0 def error(row, message, record=None, **kwargs): """ Failed import of the record ``record`` at line ``row``, with the error message ``message`` :param str message: :param dict record: """ return ( -1, dict(record or {}, **kwargs), "Line %d : %s" % (row, message), '') def values(seq, field='value'): return [item[field] for item in seq] class ImporterCase(common.TransactionCase): model_name = False def __init__(self, *args, **kwargs): super(ImporterCase, self).__init__(*args, **kwargs) self.model = None def setUp(self): super(ImporterCase, self).setUp() self.model = self.registry(self.model_name) def import_(self, fields, rows, context=None): return self.model.import_data( self.cr, openerp.SUPERUSER_ID, fields, rows, context=context) def read(self, fields=('value',), domain=(), context=None): return self.model.read( self.cr, openerp.SUPERUSER_ID, self.model.search(self.cr, openerp.SUPERUSER_ID, domain, context=context), fields=fields, context=context) def browse(self, domain=(), context=None): return self.model.browse( self.cr, openerp.SUPERUSER_ID, self.model.search(self.cr, openerp.SUPERUSER_ID, domain, context=context), context=context) def xid(self, record): ModelData = self.registry('ir.model.data') ids = ModelData.search( self.cr, openerp.SUPERUSER_ID, [('model', '=', record._name), ('res_id', '=', record.id)]) if ids: d = ModelData.read( self.cr, openerp.SUPERUSER_ID, ids, ['name', 'module'])[0] if d['module']: return '%s.%s' % (d['module'], d['name']) return d['name'] name = record.name_get()[0][1] # fix dotted name_get results, otherwise xid lookups blow up name = name.replace('.', '-') ModelData.create(self.cr, openerp.SUPERUSER_ID, { 'name': name, 'model': record._name, 'res_id': record.id, 'module': '__test__' }) return '__test__.' + name class test_ids_stuff(ImporterCase): model_name = 'export.integer' def test_create_with_id(self): self.assertEqual( self.import_(['.id', 'value'], [['42', '36']]), error(1, u"Unknown database identifier '42'")) def test_create_with_xid(self): self.assertEqual( self.import_(['id', 'value'], [['somexmlid', '42']]), ok(1)) self.assertEqual( 'somexmlid', self.xid(self.browse()[0])) def test_update_with_id(self): id = self.model.create(self.cr, openerp.SUPERUSER_ID, {'value': 36}) self.assertEqual( 36, self.model.browse(self.cr, openerp.SUPERUSER_ID, id).value) self.assertEqual( self.import_(['.id', 'value'], [[str(id), '42']]), ok(1)) self.assertEqual( [42], # updated value to imported values(self.read())) def test_update_with_xid(self): self.import_(['id', 'value'], [['somexmlid', '36']]) self.assertEqual([36], values(self.read())) self.import_(['id', 'value'], [['somexmlid', '1234567']]) self.assertEqual([1234567], values(self.read())) def test_wrong_format(self): self.assertEqual( self.import_(['value'], [['50%']]), error(1, u"'50%' does not seem to be an integer for field 'unknown'")) class test_boolean_field(ImporterCase): model_name = 'export.boolean' def test_empty(self): self.assertEqual( self.import_(['value'], []), ok(0)) def test_exported(self): self.assertEqual( self.import_(['value'], [ ['False'], ['True'], ]), ok(2)) records = self.read() self.assertEqual([ False, True, ], values(records)) def test_falses(self): self.assertEqual( self.import_(['value'], [ [u'0'], [u'no'], [u'false'], [u'FALSE'], [u''], ]), ok(5)) self.assertEqual([ False, False, False, False, False, ], values(self.read())) def test_trues(self): self.assertEqual( self.import_(['value'], [ ['off'], ['None'], ['nil'], ['()'], ['f'], ['#f'], # Problem: OpenOffice (and probably excel) output localized booleans ['VRAI'], [u'OFF'], [u'是的'], ['!&%#${}'], ['%(field)s'], ]), ok(11)) self.assertEqual( [True] * 11, values(self.read())) class test_integer_field(ImporterCase): model_name = 'export.integer' def test_none(self): self.assertEqual( self.import_(['value'], []), ok(0)) def test_empty(self): self.assertEqual( self.import_(['value'], [['']]), ok(1)) self.assertEqual( [False], values(self.read())) def test_zero(self): self.assertEqual( self.import_(['value'], [['0']]), ok(1)) self.assertEqual( self.import_(['value'], [['-0']]), ok(1)) self.assertEqual([False, False], values(self.read())) def test_positives(self): self.assertEqual( self.import_(['value'], [ ['1'], ['42'], [str(2**31-1)], ['12345678'] ]), ok(4)) self.assertEqual([ 1, 42, 2**31-1, 12345678 ], values(self.read())) def test_negatives(self): self.assertEqual( self.import_(['value'], [ ['-1'], ['-42'], [str(-(2**31 - 1))], [str(-(2**31))], ['-12345678'] ]), ok(5)) self.assertEqual([ -1, -42, -(2**31 - 1), -(2**31), -12345678 ], values(self.read())) @mute_logger('openerp.sql_db') def test_out_of_range(self): self.assertEqual( self.import_(['value'], [[str(2**31)]]), error(1, "integer out of range\n")) # auto-rollbacks if error is in process_liness, but not during # ir.model.data write. Can differentiate because former ends lines # error lines with "!" self.cr.rollback() self.assertEqual( self.import_(['value'], [[str(-2**32)]]), error(1, "integer out of range\n")) def test_nonsense(self): self.assertEqual( self.import_(['value'], [['zorglub']]), error(1, u"'zorglub' does not seem to be an integer for field 'unknown'")) class test_float_field(ImporterCase): model_name = 'export.float' def test_none(self): self.assertEqual( self.import_(['value'], []), ok(0)) def test_empty(self): self.assertEqual( self.import_(['value'], [['']]), ok(1)) self.assertEqual( [False], values(self.read())) def test_zero(self): self.assertEqual( self.import_(['value'], [['0']]), ok(1)) self.assertEqual( self.import_(['value'], [['-0']]), ok(1)) self.assertEqual([False, False], values(self.read())) def test_positives(self): self.assertEqual( self.import_(['value'], [ ['1'], ['42'], [str(2**31-1)], ['12345678'], [str(2**33)], ['0.000001'], ]), ok(6)) self.assertEqual([ 1, 42, 2**31-1, 12345678, 2.0**33, .000001 ], values(self.read())) def test_negatives(self): self.assertEqual( self.import_(['value'], [ ['-1'], ['-42'], [str(-2**31 + 1)], [str(-2**31)], ['-12345678'], [str(-2**33)], ['-0.000001'], ]), ok(7)) self.assertEqual([ -1, -42, -(2**31 - 1), -(2**31), -12345678, -2.0**33, -.000001 ], values(self.read())) def test_nonsense(self): self.assertEqual( self.import_(['value'], [['foobar']]), error(1, u"'foobar' does not seem to be a number for field 'unknown'")) class test_string_field(ImporterCase): model_name = 'export.string.bounded' def test_empty(self): self.assertEqual( self.import_(['value'], [['']]), ok(1)) self.assertEqual([False], values(self.read())) def test_imported(self): self.assertEqual( self.import_(['value'], [ [u'foobar'], [u'foobarbaz'], [u'Með suð í eyrum við spilum endalaust'], [u"People 'get' types. They use them all the time. Telling " u"someone he can't pound a nail with a banana doesn't much " u"surprise him."] ]), ok(4)) self.assertEqual([ u"foobar", u"foobarbaz", u"Með suð í eyrum ", u"People 'get' typ", ], values(self.read())) class test_unbound_string_field(ImporterCase): model_name = 'export.string' def test_imported(self): self.assertEqual( self.import_(['value'], [ [u'í dag viðrar vel til loftárása'], # ackbar.jpg [u"If they ask you about fun, you tell them – fun is a filthy" u" parasite"] ]), ok(2)) self.assertEqual([ u"í dag viðrar vel til loftárása", u"If they ask you about fun, you tell them – fun is a filthy parasite" ], values(self.read())) class test_text(ImporterCase): model_name = 'export.text' def test_empty(self): self.assertEqual( self.import_(['value'], [['']]), ok(1)) self.assertEqual([False], values(self.read())) def test_imported(self): s = (u"Breiðskífa er notað um útgefna hljómplötu sem inniheldur " u"stúdíóupptökur frá einum flytjanda. Breiðskífur eru oftast " u"milli 25-80 mínútur og er lengd þeirra oft miðuð við 33⅓ " u"snúninga 12 tommu vínylplötur (sem geta verið allt að 30 mín " u"hvor hlið).\n\nBreiðskífur eru stundum tvöfaldar og eru þær þá" u" gefnar út á tveimur geisladiskum eða tveimur vínylplötum.") self.assertEqual( self.import_(['value'], [[s]]), ok(1)) self.assertEqual([s], values(self.read())) class test_selection(ImporterCase): model_name = 'export.selection' translations_fr = [ ("Qux", "toto"), ("Bar", "titi"), ("Foo", "tete"), ] def test_imported(self): self.assertEqual( self.import_(['value'], [ ['Qux'], ['Bar'], ['Foo'], ['2'], ]), ok(4)) self.assertEqual([3, 2, 1, 2], values(self.read())) def test_imported_translated(self): self.registry('res.lang').create(self.cr, openerp.SUPERUSER_ID, { 'name': u'Français', 'code': 'fr_FR', 'translatable': True, 'date_format': '%d.%m.%Y', 'decimal_point': ',', 'thousands_sep': ' ', }) Translations = self.registry('ir.translation') for source, value in self.translations_fr: Translations.create(self.cr, openerp.SUPERUSER_ID, { 'name': 'export.selection,value', 'lang': 'fr_FR', 'type': 'selection', 'src': source, 'value': value }) self.assertEqual( self.import_(['value'], [ ['toto'], ['tete'], ['titi'], ], context={'lang': 'fr_FR'}), ok(3)) self.assertEqual([3, 1, 2], values(self.read())) self.assertEqual( self.import_(['value'], [['Foo']], context={'lang': 'fr_FR'}), ok(1)) def test_invalid(self): self.assertEqual( self.import_(['value'], [['Baz']]), error(1, u"Value 'Baz' not found in selection field 'unknown'")) self.cr.rollback() self.assertEqual( self.import_(['value'], [[42]]), error(1, u"Value '42' not found in selection field 'unknown'")) class test_selection_function(ImporterCase): model_name = 'export.selection.function' translations_fr = [ ("Corge", "toto"), ("Grault", "titi"), ("Wheee", "tete"), ("Moog", "tutu"), ] def test_imported(self): """ import uses fields_get, so translates import label (may or may not be good news) *and* serializes the selection function to reverse it: import does not actually know that the selection field uses a function """ # NOTE: conflict between a value and a label => ? self.assertEqual( self.import_(['value'], [ ['3'], ["Grault"], ]), ok(2)) self.assertEqual( [3, 1], values(self.read())) def test_translated(self): """ Expects output of selection function returns translated labels """ self.registry('res.lang').create(self.cr, openerp.SUPERUSER_ID, { 'name': u'Français', 'code': 'fr_FR', 'translatable': True, 'date_format': '%d.%m.%Y', 'decimal_point': ',', 'thousands_sep': ' ', }) Translations = self.registry('ir.translation') for source, value in self.translations_fr: Translations.create(self.cr, openerp.SUPERUSER_ID, { 'name': 'export.selection,value', 'lang': 'fr_FR', 'type': 'selection', 'src': source, 'value': value }) self.assertEqual( self.import_(['value'], [ ['toto'], ['tete'], ], context={'lang': 'fr_FR'}), ok(2)) self.assertEqual( self.import_(['value'], [['Wheee']], context={'lang': 'fr_FR'}), ok(1)) class test_m2o(ImporterCase): model_name = 'export.many2one' def test_by_name(self): # create integer objects integer_id1 = self.registry('export.integer').create( self.cr, openerp.SUPERUSER_ID, {'value': 42}) integer_id2 = self.registry('export.integer').create( self.cr, openerp.SUPERUSER_ID, {'value': 36}) # get its name name1 = dict(self.registry('export.integer').name_get( self.cr, openerp.SUPERUSER_ID,[integer_id1]))[integer_id1] name2 = dict(self.registry('export.integer').name_get( self.cr, openerp.SUPERUSER_ID,[integer_id2]))[integer_id2] self.assertEqual( self.import_(['value'], [ # import by name_get [name1], [name1], [name2], ]), ok(3)) # correct ids assigned to corresponding records self.assertEqual([ (integer_id1, name1), (integer_id1, name1), (integer_id2, name2),], values(self.read())) def test_by_xid(self): ExportInteger = self.registry('export.integer') integer_id = ExportInteger.create( self.cr, openerp.SUPERUSER_ID, {'value': 42}) xid = self.xid(ExportInteger.browse( self.cr, openerp.SUPERUSER_ID, [integer_id])[0]) self.assertEqual( self.import_(['value/id'], [[xid]]), ok(1)) b = self.browse() self.assertEqual(42, b[0].value.value) def test_by_id(self): integer_id = self.registry('export.integer').create( self.cr, openerp.SUPERUSER_ID, {'value': 42}) self.assertEqual( self.import_(['value/.id'], [[integer_id]]), ok(1)) b = self.browse() self.assertEqual(42, b[0].value.value) def test_by_names(self): integer_id1 = self.registry('export.integer').create( self.cr, openerp.SUPERUSER_ID, {'value': 42}) integer_id2 = self.registry('export.integer').create( self.cr, openerp.SUPERUSER_ID, {'value': 42}) name1 = dict(self.registry('export.integer').name_get( self.cr, openerp.SUPERUSER_ID,[integer_id1]))[integer_id1] name2 = dict(self.registry('export.integer').name_get( self.cr, openerp.SUPERUSER_ID,[integer_id2]))[integer_id2] # names should be the same self.assertEqual(name1, name2) self.assertEqual( self.import_(['value'], [[name2]]), ok(1)) self.assertEqual([ (integer_id1, name1) ], values(self.read())) def test_fail_by_implicit_id(self): """ Can't implicitly import records by id """ # create integer objects integer_id1 = self.registry('export.integer').create( self.cr, openerp.SUPERUSER_ID, {'value': 42}) integer_id2 = self.registry('export.integer').create( self.cr, openerp.SUPERUSER_ID, {'value': 36}) self.assertEqual( self.import_(['value'], [ # import by id, without specifying it [integer_id1], [integer_id2], [integer_id1], ]), error(1, u"No matching record found for name '%s' in field 'unknown'" % integer_id1)) def test_sub_field(self): """ Does not implicitly create the record, does not warn that you can't import m2o subfields (at all)... """ self.assertEqual( self.import_(['value/value'], [['42']]), error(1, u"Can not create Many-To-One records indirectly, import the field separately")) def test_fail_noids(self): self.assertEqual( self.import_(['value'], [['nameisnoexist:3']]), error(1, u"No matching record found for name 'nameisnoexist:3' in field 'unknown'")) self.cr.rollback() self.assertEqual( self.import_(['value/id'], [['noxidhere']]), error(1, u"No matching record found for external id 'noxidhere' in field 'unknown'")) self.cr.rollback() self.assertEqual( self.import_(['value/.id'], [[66]]), error(1, u"No matching record found for database id '66' in field 'unknown'")) class test_m2m(ImporterCase): model_name = 'export.many2many' # apparently, one and only thing which works is a # csv_internal_sep-separated list of ids, xids, or names (depending if # m2m/.id, m2m/id or m2m[/anythingelse] def test_ids(self): id1 = self.registry('export.many2many.other').create( self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'}) id2 = self.registry('export.many2many.other').create( self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'}) id3 = self.registry('export.many2many.other').create( self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'}) id4 = self.registry('export.many2many.other').create( self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'}) id5 = self.registry('export.many2many.other').create( self.cr, openerp.SUPERUSER_ID, {'value': 99, 'str': 'record4'}) self.assertEqual( self.import_(['value/.id'], [ ['%d,%d' % (id1, id2)], ['%d,%d,%d' % (id1, id3, id4)], ['%d,%d,%d' % (id1, id2, id3)], ['%d' % id5] ]), ok(4)) ids = lambda records: [record.id for record in records] b = self.browse() self.assertEqual(ids(b[0].value), [id1, id2]) self.assertEqual(values(b[0].value), [3, 44]) self.assertEqual(ids(b[2].value), [id1, id2, id3]) self.assertEqual(values(b[2].value), [3, 44, 84]) def test_noids(self): self.assertEqual( self.import_(['value/.id'], [['42']]), error(1, u"No matching record found for database id '42' in field 'unknown'")) def test_xids(self): M2O_o = self.registry('export.many2many.other') id1 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'}) id2 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'}) id3 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'}) id4 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'}) records = M2O_o.browse(self.cr, openerp.SUPERUSER_ID, [id1, id2, id3, id4]) self.assertEqual( self.import_(['value/id'], [ ['%s,%s' % (self.xid(records[0]), self.xid(records[1]))], ['%s' % self.xid(records[3])], ['%s,%s' % (self.xid(records[2]), self.xid(records[1]))], ]), ok(3)) b = self.browse() self.assertEqual(values(b[0].value), [3, 44]) self.assertEqual(values(b[2].value), [44, 84]) def test_noxids(self): self.assertEqual( self.import_(['value/id'], [['noxidforthat']]), error(1, u"No matching record found for external id 'noxidforthat' in field 'unknown'")) def test_names(self): M2O_o = self.registry('export.many2many.other') id1 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'}) id2 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'}) id3 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'}) id4 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'}) records = M2O_o.browse(self.cr, openerp.SUPERUSER_ID, [id1, id2, id3, id4]) name = lambda record: record.name_get()[0][1] self.assertEqual( self.import_(['value'], [ ['%s,%s' % (name(records[1]), name(records[2]))], ['%s,%s,%s' % (name(records[0]), name(records[1]), name(records[2]))], ['%s,%s' % (name(records[0]), name(records[3]))], ]), ok(3)) b = self.browse() self.assertEqual(values(b[1].value), [3, 44, 84]) self.assertEqual(values(b[2].value), [3, 9]) def test_nonames(self): self.assertEqual( self.import_(['value'], [['wherethem2mhavenonames']]), error(1, u"No matching record found for name 'wherethem2mhavenonames' in field 'unknown'")) def test_import_to_existing(self): M2O_o = self.registry('export.many2many.other') id1 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 3, 'str': 'record0'}) id2 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 44, 'str': 'record1'}) id3 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 84, 'str': 'record2'}) id4 = M2O_o.create(self.cr, openerp.SUPERUSER_ID, {'value': 9, 'str': 'record3'}) xid = 'myxid' self.assertEqual( self.import_(['id', 'value/.id'], [[xid, '%d,%d' % (id1, id2)]]), ok(1)) self.assertEqual( self.import_(['id', 'value/.id'], [[xid, '%d,%d' % (id3, id4)]]), ok(1)) b = self.browse() self.assertEqual(len(b), 1) # TODO: replacement of existing m2m values is correct? self.assertEqual(values(b[0].value), [84, 9]) class test_o2m(ImporterCase): model_name = 'export.one2many' def test_name_get(self): s = u'Java is a DSL for taking large XML files and converting them to' \ u' stack traces' self.assertEqual( self.import_( ['const', 'value'], [['5', s]]), error(1, u"No matching record found for name '%s' in field 'unknown'" % s)) def test_single(self): self.assertEqual( self.import_(['const', 'value/value'], [ ['5', '63'] ]), ok(1)) (b,) = self.browse() self.assertEqual(b.const, 5) self.assertEqual(values(b.value), [63]) def test_multicore(self): self.assertEqual( self.import_(['const', 'value/value'], [ ['5', '63'], ['6', '64'], ]), ok(2)) b1, b2 = self.browse() self.assertEqual(b1.const, 5) self.assertEqual(values(b1.value), [63]) self.assertEqual(b2.const, 6) self.assertEqual(values(b2.value), [64]) def test_multisub(self): self.assertEqual( self.import_(['const', 'value/value'], [ ['5', '63'], ['', '64'], ['', '65'], ['', '66'], ]), ok(4)) (b,) = self.browse() self.assertEqual(values(b.value), [63, 64, 65, 66]) def test_multi_subfields(self): self.assertEqual( self.import_(['value/str', 'const', 'value/value'], [ ['this', '5', '63'], ['is', '', '64'], ['the', '', '65'], ['rhythm', '', '66'], ]), ok(4)) (b,) = self.browse() self.assertEqual(values(b.value), [63, 64, 65, 66]) self.assertEqual( values(b.value, 'str'), 'this is the rhythm'.split()) def test_link_inline(self): id1 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, { 'str': 'Bf', 'value': 109 }) id2 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, { 'str': 'Me', 'value': 262 }) try: self.import_(['const', 'value/.id'], [ ['42', '%d,%d' % (id1, id2)] ]) except ValueError, e: # should be Exception(Database ID doesn't exist: export.one2many.child : $id1,$id2) self.assertIs(type(e), ValueError) self.assertEqual( e.args[0], "invalid literal for int() with base 10: '%d,%d'" % (id1, id2)) def test_link(self): id1 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, { 'str': 'Bf', 'value': 109 }) id2 = self.registry('export.one2many.child').create(self.cr, openerp.SUPERUSER_ID, { 'str': 'Me', 'value': 262 }) self.assertEqual( self.import_(['const', 'value/.id'], [ ['42', str(id1)], ['', str(id2)], ]), ok(2)) [b] = self.browse() self.assertEqual(b.const, 42) # automatically forces link between core record and o2ms self.assertEqual(values(b.value), [109, 262]) self.assertEqual(values(b.value, field='parent_id'), [b, b]) def test_link_2(self): O2M_c = self.registry('export.one2many.child') id1 = O2M_c.create(self.cr, openerp.SUPERUSER_ID, { 'str': 'Bf', 'value': 109 }) id2 = O2M_c.create(self.cr, openerp.SUPERUSER_ID, { 'str': 'Me', 'value': 262 }) self.assertEqual( self.import_(['const', 'value/.id', 'value/value'], [ ['42', str(id1), '1'], ['', str(id2), '2'], ]), ok(2)) [b] = self.browse() self.assertEqual(b.const, 42) self.assertEqual(values(b.value), [1, 2]) self.assertEqual(values(b.value, field='parent_id'), [b, b]) class test_o2m_multiple(ImporterCase): model_name = 'export.one2many.multiple' def test_multi_mixed(self): self.assertEqual( self.import_(['const', 'child1/value', 'child2/value'], [ ['5', '11', '21'], ['', '12', '22'], ['', '13', '23'], ['', '14', ''], ]), ok(4)) [b] = self.browse() self.assertEqual(values(b.child1), [11, 12, 13, 14]) self.assertEqual(values(b.child2), [21, 22, 23]) def test_multi(self): self.assertEqual( self.import_(['const', 'child1/value', 'child2/value'], [ ['5', '11', '21'], ['', '12', ''], ['', '13', ''], ['', '14', ''], ['', '', '22'], ['', '', '23'], ]), ok(6)) [b] = self.browse() self.assertEqual(values(b.child1), [11, 12, 13, 14]) self.assertEqual(values(b.child2), [21, 22, 23]) def test_multi_fullsplit(self): self.assertEqual( self.import_(['const', 'child1/value', 'child2/value'], [ ['5', '11', ''], ['', '12', ''], ['', '13', ''], ['', '14', ''], ['', '', '21'], ['', '', '22'], ['', '', '23'], ]), ok(7)) [b] = self.browse() self.assertEqual(b.const, 5) self.assertEqual(values(b.child1), [11, 12, 13, 14]) self.assertEqual(values(b.child2), [21, 22, 23]) # function, related, reference: written to db as-is... # => function uses @type for value coercion/conversion
gpl-2.0
7,760,320,796,659,249,000
33.396184
103
0.491206
false
quiet-oceans/motuclient-setuptools
motu/utils_messages.py
1
2031
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Python motu client # # Motu, a high efficient, robust and Standard compliant Web Server for # Geographic Data Dissemination. # # http://cls-motu.sourceforge.net/ # # (C) Copyright 2009-2010, by CLS (Collecte Localisation Satellites) - # http://www.cls.fr - and Contributors # # # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. # # This library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. from pkg_resources import resource_filename _messages = None MESSAGES_FILE = 'data/messages.properties' def get_external_messages(): """Return a table of externalized messages. The table is lazzy instancied (loaded once when called the first time).""" global _messages if _messages is None: propFile = file(resource_filename(__name__, MESSAGES_FILE), "rU") propDict = dict() for propLine in propFile: propDef = propLine.strip() if len(propDef) == 0: continue if propDef[0] in ('!', '#'): continue punctuation = [propDef.find(c) for c in ':= '] + [len(propDef)] found = min([pos for pos in punctuation if pos != -1]) name = propDef[:found].rstrip() value = propDef[found:].lstrip(":= ").rstrip() propDict[name] = value propFile.close() _messages = propDict return _messages
lgpl-3.0
-5,541,262,570,118,658,000
35.267857
78
0.659281
false
p0psicles/SickGear
sickbeard/notifiers/plex.py
3
11492
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickGear. # # SickGear 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. # # SickGear 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 SickGear. If not, see <http://www.gnu.org/licenses/>. import urllib import urllib2 import base64 import re import sickbeard from sickbeard import logger from sickbeard import common from sickbeard.exceptions import ex from sickbeard.encodingKludge import fixStupidEncodings try: import xml.etree.cElementTree as etree except ImportError: import elementtree.ElementTree as etree class PLEXNotifier: def _send_to_plex(self, command, host, username=None, password=None): """Handles communication to Plex hosts via HTTP API Args: command: Dictionary of field/data pairs, encoded via urllib and passed to the legacy xbmcCmds HTTP API host: Plex host:port username: Plex API username password: Plex API password Returns: Returns 'OK' for successful commands or False if there was an error """ # fill in omitted parameters if not username: username = sickbeard.PLEX_USERNAME if not password: password = sickbeard.PLEX_PASSWORD if not host: logger.log(u'PLEX: No host specified, check your settings', logger.ERROR) return False for key in command: if type(command[key]) == unicode: command[key] = command[key].encode('utf-8') enc_command = urllib.urlencode(command) logger.log(u'PLEX: Encoded API command: ' + enc_command, logger.DEBUG) url = 'http://%s/xbmcCmds/xbmcHttp/?%s' % (host, enc_command) try: req = urllib2.Request(url) # if we have a password, use authentication if password: base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = 'Basic %s' % base64string req.add_header('Authorization', authheader) logger.log(u'PLEX: Contacting (with auth header) via url: ' + url, logger.DEBUG) else: logger.log(u'PLEX: Contacting via url: ' + url, logger.DEBUG) response = urllib2.urlopen(req) result = response.read().decode(sickbeard.SYS_ENCODING) response.close() logger.log(u'PLEX: HTTP response: ' + result.replace('\n', ''), logger.DEBUG) # could return result response = re.compile('<html><li>(.+\w)</html>').findall(result) return 'OK' except (urllib2.URLError, IOError) as e: logger.log(u'PLEX: Warning: Couldn\'t contact Plex at ' + fixStupidEncodings(url) + ' ' + ex(e), logger.WARNING) return False def _notify_pmc(self, message, title='SickGear', host=None, username=None, password=None, force=False): """Internal wrapper for the notify_snatch and notify_download functions Args: message: Message body of the notice to send title: Title of the notice to send host: Plex Media Client(s) host:port username: Plex username password: Plex password force: Used for the Test method to override config safety checks Returns: Returns a list results in the format of host:ip:result The result will either be 'OK' or False, this is used to be parsed by the calling function. """ # suppress notifications if the notifier is disabled but the notify options are checked if not sickbeard.USE_PLEX and not force: return False # fill in omitted parameters if not host: host = sickbeard.PLEX_HOST if not username: username = sickbeard.PLEX_USERNAME if not password: password = sickbeard.PLEX_PASSWORD result = '' for curHost in [x.strip() for x in host.split(',')]: logger.log(u'PLEX: Sending notification to \'%s\' - %s' % (curHost, message), logger.MESSAGE) command = {'command': 'ExecBuiltIn', 'parameter': 'Notification(%s,%s)' % (title.encode('utf-8'), message.encode('utf-8'))} notify_result = self._send_to_plex(command, curHost, username, password) if notify_result: result += '%s:%s' % (curHost, str(notify_result)) return result ############################################################################## # Public functions ############################################################################## def notify_snatch(self, ep_name): if sickbeard.PLEX_NOTIFY_ONSNATCH: self._notify_pmc(ep_name, common.notifyStrings[common.NOTIFY_SNATCH]) def notify_download(self, ep_name): if sickbeard.PLEX_NOTIFY_ONDOWNLOAD: self._notify_pmc(ep_name, common.notifyStrings[common.NOTIFY_DOWNLOAD]) def notify_subtitle_download(self, ep_name, lang): if sickbeard.PLEX_NOTIFY_ONSUBTITLEDOWNLOAD: self._notify_pmc(ep_name + ': ' + lang, common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD]) def notify_git_update(self, new_version='??'): if sickbeard.USE_PLEX: update_text = common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT] title = common.notifyStrings[common.NOTIFY_GIT_UPDATE] self._notify_pmc(update_text + new_version, title) def test_notify_pmc(self, host, username, password): return self._notify_pmc('This is a test notification from SickGear', 'Test', host, username, password, force=True) def test_notify_pms(self, host, username, password): return self.update_library(host=host, username=username, password=password, force=False) def update_library(self, ep_obj=None, host=None, username=None, password=None, force=True): """Handles updating the Plex Media Server host via HTTP API Plex Media Server currently only supports updating the whole video library and not a specific path. Returns: Returns None for no issue, else a string of host with connection issues """ if sickbeard.USE_PLEX and sickbeard.PLEX_UPDATE_LIBRARY: if not sickbeard.PLEX_SERVER_HOST: logger.log(u'PLEX: No Plex Media Server host specified, check your settings', logger.DEBUG) return False if not host: host = sickbeard.PLEX_SERVER_HOST if not username: username = sickbeard.PLEX_USERNAME if not password: password = sickbeard.PLEX_PASSWORD # if username and password were provided, fetch the auth token from plex.tv token_arg = '' if username and password: logger.log(u'PLEX: fetching plex.tv credentials for user: ' + username, logger.DEBUG) req = urllib2.Request('https://plex.tv/users/sign_in.xml', data='') authheader = 'Basic %s' % base64.encodestring('%s:%s' % (username, password))[:-1] req.add_header('Authorization', authheader) req.add_header('X-Plex-Device-Name', 'SickGear') req.add_header('X-Plex-Product', 'SickGear Notifier') req.add_header('X-Plex-Client-Identifier', '5f48c063eaf379a565ff56c9bb2b401e') req.add_header('X-Plex-Version', '1.0') try: response = urllib2.urlopen(req) auth_tree = etree.parse(response) token = auth_tree.findall('.//authentication-token')[0].text token_arg = '?X-Plex-Token=' + token except urllib2.URLError as e: logger.log(u'PLEX: Error fetching credentials from from plex.tv for user %s: %s' % (username, ex(e)), logger.MESSAGE) except (ValueError, IndexError) as e: logger.log(u'PLEX: Error parsing plex.tv response: ' + ex(e), logger.MESSAGE) file_location = '' if None is ep_obj else ep_obj.location host_list = [x.strip() for x in host.split(',')] hosts_all = {} hosts_match = {} hosts_failed = [] for cur_host in host_list: url = 'http://%s/library/sections%s' % (cur_host, token_arg) try: xml_tree = etree.parse(urllib.urlopen(url)) media_container = xml_tree.getroot() except IOError as e: logger.log(u'PLEX: Error while trying to contact Plex Media Server: ' + ex(e), logger.ERROR) hosts_failed.append(cur_host) continue sections = media_container.findall('.//Directory') if not sections: logger.log(u'PLEX: Plex Media Server not running on: ' + cur_host, logger.MESSAGE) hosts_failed.append(cur_host) continue for section in sections: if 'show' == section.attrib['type']: keyed_host = [(str(section.attrib['key']), cur_host)] hosts_all.update(keyed_host) if not file_location: continue for section_location in section.findall('.//Location'): section_path = re.sub(r'[/\\]+', '/', section_location.attrib['path'].lower()) section_path = re.sub(r'^(.{,2})[/\\]', '', section_path) location_path = re.sub(r'[/\\]+', '/', file_location.lower()) location_path = re.sub(r'^(.{,2})[/\\]', '', location_path) if section_path in location_path: hosts_match.update(keyed_host) hosts_try = (hosts_all.copy(), hosts_match.copy())[len(hosts_match)] host_list = [] for section_key, cur_host in hosts_try.items(): url = 'http://%s/library/sections/%s/refresh%s' % (cur_host, section_key, token_arg) try: force and urllib.urlopen(url) host_list.append(cur_host) except Exception as e: logger.log(u'PLEX: Error updating library section for Plex Media Server: ' + ex(e), logger.ERROR) hosts_failed.append(cur_host) if len(hosts_match): logger.log(u'PLEX: Updating hosts where TV section paths match the downloaded show: ' + ', '.join(set(host_list)), logger.MESSAGE) else: logger.log(u'PLEX: Updating all hosts with TV sections: ' + ', '.join(set(host_list)), logger.MESSAGE) return (', '.join(set(hosts_failed)), None)[not len(hosts_failed)] notifier = PLEXNotifier
gpl-3.0
-5,119,957,435,221,077,000
41.72119
146
0.580056
false
JeremieSamson/jasper
client/vocabcompiler.py
34
19268
# -*- coding: utf-8-*- """ Iterates over all the WORDS variables in the modules and creates a vocabulary for the respective stt_engine if needed. """ import os import tempfile import logging import hashlib import subprocess import tarfile import re import contextlib import shutil from abc import ABCMeta, abstractmethod, abstractproperty import yaml import brain import jasperpath from g2p import PhonetisaurusG2P try: import cmuclmtk except ImportError: logging.getLogger(__name__).error("Error importing CMUCLMTK module. " + "PocketsphinxVocabulary will not work " + "correctly.", exc_info=True) class AbstractVocabulary(object): """ Abstract base class for Vocabulary classes. Please note that subclasses have to implement the compile_vocabulary() method and set a string as the PATH_PREFIX class attribute. """ __metaclass__ = ABCMeta @classmethod def phrases_to_revision(cls, phrases): """ Calculates a revision from phrases by using the SHA1 hash function. Arguments: phrases -- a list of phrases Returns: A revision string for given phrases. """ sorted_phrases = sorted(phrases) joined_phrases = '\n'.join(sorted_phrases) sha1 = hashlib.sha1() sha1.update(joined_phrases) return sha1.hexdigest() def __init__(self, name='default', path='.'): """ Initializes a new Vocabulary instance. Optional Arguments: name -- (optional) the name of the vocabulary (Default: 'default') path -- (optional) the path in which the vocabulary exists or will be created (Default: '.') """ self.name = name self.path = os.path.abspath(os.path.join(path, self.PATH_PREFIX, name)) self._logger = logging.getLogger(__name__) @property def revision_file(self): """ Returns: The path of the the revision file as string """ return os.path.join(self.path, 'revision') @abstractproperty def is_compiled(self): """ Checks if the vocabulary is compiled by checking if the revision file is readable. This method should be overridden by subclasses to check for class-specific additional files, too. Returns: True if the dictionary is compiled, else False """ return os.access(self.revision_file, os.R_OK) @property def compiled_revision(self): """ Reads the compiled revision from the revision file. Returns: the revision of this vocabulary (i.e. the string inside the revision file), or None if is_compiled if False """ if not self.is_compiled: return None with open(self.revision_file, 'r') as f: revision = f.read().strip() self._logger.debug("compiled_revision is '%s'", revision) return revision def matches_phrases(self, phrases): """ Convenience method to check if this vocabulary exactly contains the phrases passed to this method. Arguments: phrases -- a list of phrases Returns: True if phrases exactly matches the phrases inside this vocabulary. """ return (self.compiled_revision == self.phrases_to_revision(phrases)) def compile(self, phrases, force=False): """ Compiles this vocabulary. If the force argument is True, compilation will be forced regardless of necessity (which means that the preliminary check if the current revision already equals the revision after compilation will be skipped). This method is not meant to be overridden by subclasses - use the _compile_vocabulary()-method instead. Arguments: phrases -- a list of phrases that this vocabulary will contain force -- (optional) forces compilation (Default: False) Returns: The revision of the compiled vocabulary """ revision = self.phrases_to_revision(phrases) if not force and self.compiled_revision == revision: self._logger.debug('Compilation not neccessary, compiled ' + 'version matches phrases.') return revision if not os.path.exists(self.path): self._logger.debug("Vocabulary dir '%s' does not exist, " + "creating...", self.path) try: os.makedirs(self.path) except OSError: self._logger.error("Couldn't create vocabulary dir '%s'", self.path, exc_info=True) raise try: with open(self.revision_file, 'w') as f: f.write(revision) except (OSError, IOError): self._logger.error("Couldn't write revision file in '%s'", self.revision_file, exc_info=True) raise else: self._logger.info('Starting compilation...') try: self._compile_vocabulary(phrases) except Exception as e: self._logger.error("Fatal compilation Error occured, " + "cleaning up...", exc_info=True) try: os.remove(self.revision_file) except OSError: pass raise e else: self._logger.info('Compilation done.') return revision @abstractmethod def _compile_vocabulary(self, phrases): """ Abstract method that should be overridden in subclasses with custom compilation code. Arguments: phrases -- a list of phrases that this vocabulary will contain """ class DummyVocabulary(AbstractVocabulary): PATH_PREFIX = 'dummy-vocabulary' @property def is_compiled(self): """ Checks if the vocabulary is compiled by checking if the revision file is readable. Returns: True if this vocabulary has been compiled, else False """ return super(self.__class__, self).is_compiled def _compile_vocabulary(self, phrases): """ Does nothing (because this is a dummy class for testing purposes). """ pass class PocketsphinxVocabulary(AbstractVocabulary): PATH_PREFIX = 'pocketsphinx-vocabulary' @property def languagemodel_file(self): """ Returns: The path of the the pocketsphinx languagemodel file as string """ return os.path.join(self.path, 'languagemodel') @property def dictionary_file(self): """ Returns: The path of the pocketsphinx dictionary file as string """ return os.path.join(self.path, 'dictionary') @property def is_compiled(self): """ Checks if the vocabulary is compiled by checking if the revision, languagemodel and dictionary files are readable. Returns: True if this vocabulary has been compiled, else False """ return (super(self.__class__, self).is_compiled and os.access(self.languagemodel_file, os.R_OK) and os.access(self.dictionary_file, os.R_OK)) @property def decoder_kwargs(self): """ Convenience property to use this Vocabulary with the __init__() method of the pocketsphinx.Decoder class. Returns: A dict containing kwargs for the pocketsphinx.Decoder.__init__() method. Example: decoder = pocketsphinx.Decoder(**vocab_instance.decoder_kwargs, hmm='/path/to/hmm') """ return {'lm': self.languagemodel_file, 'dict': self.dictionary_file} def _compile_vocabulary(self, phrases): """ Compiles the vocabulary to the Pocketsphinx format by creating a languagemodel and a dictionary. Arguments: phrases -- a list of phrases that this vocabulary will contain """ text = " ".join([("<s> %s </s>" % phrase) for phrase in phrases]) self._logger.debug('Compiling languagemodel...') vocabulary = self._compile_languagemodel(text, self.languagemodel_file) self._logger.debug('Starting dictionary...') self._compile_dictionary(vocabulary, self.dictionary_file) def _compile_languagemodel(self, text, output_file): """ Compiles the languagemodel from a text. Arguments: text -- the text the languagemodel will be generated from output_file -- the path of the file this languagemodel will be written to Returns: A list of all unique words this vocabulary contains. """ with tempfile.NamedTemporaryFile(suffix='.vocab', delete=False) as f: vocab_file = f.name # Create vocab file from text self._logger.debug("Creating vocab file: '%s'", vocab_file) cmuclmtk.text2vocab(text, vocab_file) # Create language model from text self._logger.debug("Creating languagemodel file: '%s'", output_file) cmuclmtk.text2lm(text, output_file, vocab_file=vocab_file) # Get words from vocab file self._logger.debug("Getting words from vocab file and removing it " + "afterwards...") words = [] with open(vocab_file, 'r') as f: for line in f: line = line.strip() if not line.startswith('#') and line not in ('<s>', '</s>'): words.append(line) os.remove(vocab_file) return words def _compile_dictionary(self, words, output_file): """ Compiles the dictionary from a list of words. Arguments: words -- a list of all unique words this vocabulary contains output_file -- the path of the file this dictionary will be written to """ # create the dictionary self._logger.debug("Getting phonemes for %d words...", len(words)) g2pconverter = PhonetisaurusG2P(**PhonetisaurusG2P.get_config()) phonemes = g2pconverter.translate(words) self._logger.debug("Creating dict file: '%s'", output_file) with open(output_file, "w") as f: for word, pronounciations in phonemes.items(): for i, pronounciation in enumerate(pronounciations, start=1): if i == 1: line = "%s\t%s\n" % (word, pronounciation) else: line = "%s(%d)\t%s\n" % (word, i, pronounciation) f.write(line) class JuliusVocabulary(AbstractVocabulary): class VoxForgeLexicon(object): def __init__(self, fname, membername=None): self._dict = {} self.parse(fname, membername) @contextlib.contextmanager def open_dict(self, fname, membername=None): if tarfile.is_tarfile(fname): if not membername: raise ValueError('archive membername not set!') tf = tarfile.open(fname) f = tf.extractfile(membername) yield f f.close() tf.close() else: with open(fname) as f: yield f def parse(self, fname, membername=None): pattern = re.compile(r'\[(.+)\]\W(.+)') with self.open_dict(fname, membername=membername) as f: for line in f: matchobj = pattern.search(line) if matchobj: word, phoneme = [x.strip() for x in matchobj.groups()] if word in self._dict: self._dict[word].append(phoneme) else: self._dict[word] = [phoneme] def translate_word(self, word): if word in self._dict: return self._dict[word] else: return [] PATH_PREFIX = 'julius-vocabulary' @property def dfa_file(self): """ Returns: The path of the the julius dfa file as string """ return os.path.join(self.path, 'dfa') @property def dict_file(self): """ Returns: The path of the the julius dict file as string """ return os.path.join(self.path, 'dict') @property def is_compiled(self): return (super(self.__class__, self).is_compiled and os.access(self.dfa_file, os.R_OK) and os.access(self.dict_file, os.R_OK)) def _get_grammar(self, phrases): return {'S': [['NS_B', 'WORD_LOOP', 'NS_E']], 'WORD_LOOP': [['WORD_LOOP', 'WORD'], ['WORD']]} def _get_word_defs(self, lexicon, phrases): word_defs = {'NS_B': [('<s>', 'sil')], 'NS_E': [('</s>', 'sil')], 'WORD': []} words = [] for phrase in phrases: if ' ' in phrase: for word in phrase.split(' '): words.append(word) else: words.append(phrase) for word in words: for phoneme in lexicon.translate_word(word): word_defs['WORD'].append((word, phoneme)) return word_defs def _compile_vocabulary(self, phrases): prefix = 'jasper' tmpdir = tempfile.mkdtemp() lexicon_file = jasperpath.data('julius-stt', 'VoxForge.tgz') lexicon_archive_member = 'VoxForge/VoxForgeDict' profile_path = jasperpath.config('profile.yml') if os.path.exists(profile_path): with open(profile_path, 'r') as f: profile = yaml.safe_load(f) if 'julius' in profile: if 'lexicon' in profile['julius']: lexicon_file = profile['julius']['lexicon'] if 'lexicon_archive_member' in profile['julius']: lexicon_archive_member = \ profile['julius']['lexicon_archive_member'] lexicon = JuliusVocabulary.VoxForgeLexicon(lexicon_file, lexicon_archive_member) # Create grammar file tmp_grammar_file = os.path.join(tmpdir, os.extsep.join([prefix, 'grammar'])) with open(tmp_grammar_file, 'w') as f: grammar = self._get_grammar(phrases) for definition in grammar.pop('S'): f.write("%s: %s\n" % ('S', ' '.join(definition))) for name, definitions in grammar.items(): for definition in definitions: f.write("%s: %s\n" % (name, ' '.join(definition))) # Create voca file tmp_voca_file = os.path.join(tmpdir, os.extsep.join([prefix, 'voca'])) with open(tmp_voca_file, 'w') as f: for category, words in self._get_word_defs(lexicon, phrases).items(): f.write("%% %s\n" % category) for word, phoneme in words: f.write("%s\t\t\t%s\n" % (word, phoneme)) # mkdfa.pl olddir = os.getcwd() os.chdir(tmpdir) cmd = ['mkdfa.pl', str(prefix)] with tempfile.SpooledTemporaryFile() as out_f: subprocess.call(cmd, stdout=out_f, stderr=out_f) out_f.seek(0) for line in out_f.read().splitlines(): line = line.strip() if line: self._logger.debug(line) os.chdir(olddir) tmp_dfa_file = os.path.join(tmpdir, os.extsep.join([prefix, 'dfa'])) tmp_dict_file = os.path.join(tmpdir, os.extsep.join([prefix, 'dict'])) shutil.move(tmp_dfa_file, self.dfa_file) shutil.move(tmp_dict_file, self.dict_file) shutil.rmtree(tmpdir) def get_phrases_from_module(module): """ Gets phrases from a module. Arguments: module -- a module reference Returns: The list of phrases in this module. """ return module.WORDS if hasattr(module, 'WORDS') else [] def get_keyword_phrases(): """ Gets the keyword phrases from the keywords file in the jasper data dir. Returns: A list of keyword phrases. """ phrases = [] with open(jasperpath.data('keyword_phrases'), mode="r") as f: for line in f: phrase = line.strip() if phrase: phrases.append(phrase) return phrases def get_all_phrases(): """ Gets phrases from all modules. Returns: A list of phrases in all modules plus additional phrases passed to this function. """ phrases = [] modules = brain.Brain.get_modules() for module in modules: phrases.extend(get_phrases_from_module(module)) return sorted(list(set(phrases))) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Vocabcompiler Demo') parser.add_argument('--base-dir', action='store', help='the directory in which the vocabulary will be ' + 'compiled.') parser.add_argument('--debug', action='store_true', help='show debug messages') args = parser.parse_args() logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO) base_dir = args.base_dir if args.base_dir else tempfile.mkdtemp() phrases = get_all_phrases() print("Module phrases: %r" % phrases) for subclass in AbstractVocabulary.__subclasses__(): if hasattr(subclass, 'PATH_PREFIX'): vocab = subclass(path=base_dir) print("Vocabulary in: %s" % vocab.path) print("Revision file: %s" % vocab.revision_file) print("Compiled revision: %s" % vocab.compiled_revision) print("Is compiled: %r" % vocab.is_compiled) print("Matches phrases: %r" % vocab.matches_phrases(phrases)) if not vocab.is_compiled or not vocab.matches_phrases(phrases): print("Compiling...") vocab.compile(phrases) print("") print("Vocabulary in: %s" % vocab.path) print("Revision file: %s" % vocab.revision_file) print("Compiled revision: %s" % vocab.compiled_revision) print("Is compiled: %r" % vocab.is_compiled) print("Matches phrases: %r" % vocab.matches_phrases(phrases)) print("") if not args.base_dir: print("Removing temporary directory '%s'..." % base_dir) shutil.rmtree(base_dir)
mit
-3,122,387,151,979,729,000
33.223801
79
0.554027
false
thuswa/subdms
subdms/repository.py
1
5729
#!/usr/bin/env python # -*- coding: utf-8 -*- # $Id$ # Last modified Wed Jul 7 20:53:01 2010 on stalker # update count: 604 # # subdms - A document management system based on subversion. # Copyright (C) 2009 Albert Thuswaldner # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sys # from . import lowlevel # Python 3.X # from . import frontend # Python 3.X import lowlevel import frontend import string class repository: def __init__(self): self.conf = lowlevel.config() self.cmd = lowlevel.command() self.link = lowlevel.linkname() self.proj = frontend.project() self.svncmd = lowlevel.svncmd() def checkrepotools(self): """Check if the needed repo tools exist.""" if not self.cmd.exists(self.conf.svnadmin): sys.exit("Error: Can not find svnadmin command.") if not self.cmd.exists(self.conf.svnlook): sys.exit("Error: Can not find svnlook command.") def createrepo(self): """ create repsitory and layout """ self.cmd.svncreaterepo(self.conf.repopath) # Create category dirs in repo for cat in self.conf.categories: self.proj.createcategory(cat) print("Create repository: "+self.conf.repopath) def installhooks(self): """ Install hooks in repository """ repohooklist=['pre-commit', 'post-commit'] for repohook in repohooklist: repohookpath = self.link.const_repohookpath(repohook) # Copy hooks to dir in repository and set to executable self.cmd.copyfile(self.link.const_hookfilepath(repohook), \ repohookpath) self.cmd.setexecutable(repohookpath) print("Install hook: "+repohook+" -> "+self.conf.hookspath) def installtemplates(self): """ Install templates in repository """ doc = frontend.document() # Create url for template types in repo category = self.conf.categories[1] project = "TMPL" description = 'Subdms Template' defaulttype = "GEN" doctypes = [defaulttype] doctypes.extend(self.conf.doctypes.split(",")) issue = '1' # Create template project self.proj.createproject(category, project, description, doctypes) # Add default templates to repo for tmpl in self.conf.tmpltypes: tmplnamelist = self.link.const_docnamelist(category, project, \ defaulttype, issue, tmpl) tmplfname = self.conf.gettemplate(tmpl) tmplpath = self.link.const_defaulttmplpath(tmplfname) keywords = "general, example, template" doc.adddocument(tmplpath, tmplnamelist, "default", keywords) doc.release(tmplnamelist) print("Install template: "+tmplfname+" -> "+self.conf.repourl) def walkrepo(self, path): """ Walk the repo and list the content. """ repolist= [] for p in self.svncmd.recursivels(path): repolist.append(p["name"]) return repolist def walkrepoleafs(self, path): """ Walk the repo and list all files. """ filenamelist= [] for p in self.svncmd.recursivels(path): if p["kind"] == self.svncmd.filekind: filenamelist.append(p["name"]) return filenamelist def walkreponodes(self, path): """ Walk the repo and list all paths. """ pathnamelist = [] for p in self.svncmd.recursivels(path): if p["kind"] != self.svncmd.filekind: pathnamelist.append(p["name"]) return pathnamelist def upgraderepo(self): """ Upgrade layout in repo. """ projpath = self.conf.repourl+"/P" trunkpath = self.conf.repourl+"/trunk" splitpath = trunkpath.rsplit("///")[1] # Create category dirs in repo for cat in self.conf.categories: self.proj.createcategory(cat) for old_path in self.walkreponodes(trunkpath): new_path = projpath + old_path.rsplit(splitpath)[1].upper() print(new_path) self.svncmd.mkdir(new_path, "Upgrade document path") def upgradefilename(self): """ Upgrade document file names. """ projpath = self.conf.repourl+"/P" trunkpath = self.conf.repourl+"/trunk" splitpath = trunkpath.rsplit("///")[1] for old_name in self.walkrepoleafs(trunkpath): docext = old_name.rsplit(".")[1] new_base = old_name.rsplit(splitpath)[1].rsplit(".")[0].upper() new_baselist = new_base.split("/") new_basename = "P-" + new_baselist[-1] new_path = string.join(new_baselist[:-1], "/") new_name = projpath + new_path + "/" + new_basename + \ "." + docext print(new_name) self.svncmd.server_side_copy(old_name, new_name, \ "Upgrade document name")
gpl-3.0
2,118,118,750,216,691,000
38.239726
76
0.595916
false
gromez/Sick-Beard
lib/imdb/linguistics.py
50
9220
""" linguistics module (imdb package). This module provides functions and data to handle in a smart way languages and articles (in various languages) at the beginning of movie titles. Copyright 2009-2012 Davide Alberani <da@erlug.linux.it> 2012 Alberto Malagoli <albemala AT gmail.com> 2009 H. Turgut Uyar <uyar@tekir.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ # List of generic articles used when the language of the title is unknown (or # we don't have information about articles in that language). # XXX: Managing titles in a lot of different languages, a function to recognize # an initial article can't be perfect; sometimes we'll stumble upon a short # word that is an article in some language, but it's not in another; in these # situations we have to choose if we want to interpret this little word # as an article or not (remember that we don't know what the original language # of the title was). # Example: 'en' is (I suppose) an article in Some Language. Unfortunately it # seems also to be a preposition in other languages (French?). # Running a script over the whole list of titles (and aliases), I've found # that 'en' is used as an article only 376 times, and as another thing 594 # times, so I've decided to _always_ consider 'en' as a non article. # # Here is a list of words that are _never_ considered as articles, complete # with the cound of times they are used in a way or another: # 'en' (376 vs 594), 'to' (399 vs 727), 'as' (198 vs 276), 'et' (79 vs 99), # 'des' (75 vs 150), 'al' (78 vs 304), 'ye' (14 vs 70), # 'da' (23 vs 298), "'n" (8 vs 12) # # I've left in the list 'i' (1939 vs 2151) and 'uno' (52 vs 56) # I'm not sure what '-al' is, and so I've left it out... # # Generic list of articles in utf-8 encoding: GENERIC_ARTICLES = ('the', 'la', 'a', 'die', 'der', 'le', 'el', "l'", 'il', 'das', 'les', 'i', 'o', 'ein', 'un', 'de', 'los', 'an', 'una', 'las', 'eine', 'den', 'het', 'gli', 'lo', 'os', 'ang', 'oi', 'az', 'een', 'ha-', 'det', 'ta', 'al-', 'mga', "un'", 'uno', 'ett', 'dem', 'egy', 'els', 'eines', '\xc3\x8f', '\xc3\x87', '\xc3\x94\xc3\xaf', '\xc3\x8f\xc3\xa9') # Lists of articles separated by language. If possible, the list should # be sorted by frequency (not very important, but...) # If you want to add a list of articles for another language, mail it # it at imdbpy-devel@lists.sourceforge.net; non-ascii articles must be utf-8 # encoded. LANG_ARTICLES = { 'English': ('the', 'a', 'an'), 'Italian': ('la', 'le', "l'", 'il', 'i', 'un', 'una', 'gli', 'lo', "un'", 'uno'), 'Spanish': ('la', 'le', 'el', 'les', 'un', 'los', 'una', 'uno', 'unos', 'unas'), 'Portuguese': ('a', 'as', 'o', 'os', 'um', 'uns', 'uma', 'umas'), 'Turkish': (), # Some languages doesn't have articles. } LANG_ARTICLESget = LANG_ARTICLES.get # Maps a language to countries where it is the main language. # If you want to add an entry for another language or country, mail it at # imdbpy-devel@lists.sourceforge.net . LANG_COUNTRIES = { 'English': ('Canada', 'Swaziland', 'Ghana', 'St. Lucia', 'Liberia', 'Jamaica', 'Bahamas', 'New Zealand', 'Lesotho', 'Kenya', 'Solomon Islands', 'United States', 'South Africa', 'St. Vincent and the Grenadines', 'Fiji', 'UK', 'Nigeria', 'Australia', 'USA', 'St. Kitts and Nevis', 'Belize', 'Sierra Leone', 'Gambia', 'Namibia', 'Micronesia', 'Kiribati', 'Grenada', 'Antigua and Barbuda', 'Barbados', 'Malta', 'Zimbabwe', 'Ireland', 'Uganda', 'Trinidad and Tobago', 'South Sudan', 'Guyana', 'Botswana', 'United Kingdom', 'Zambia'), 'Italian': ('Italy', 'San Marino', 'Vatican City'), 'Spanish': ('Spain', 'Mexico', 'Argentina', 'Bolivia', 'Guatemala', 'Uruguay', 'Peru', 'Cuba', 'Dominican Republic', 'Panama', 'Costa Rica', 'Ecuador', 'El Salvador', 'Chile', 'Equatorial Guinea', 'Spain', 'Colombia', 'Nicaragua', 'Venezuela', 'Honduras', 'Paraguay'), 'French': ('Cameroon', 'Burkina Faso', 'Dominica', 'Gabon', 'Monaco', 'France', "Cote d'Ivoire", 'Benin', 'Togo', 'Central African Republic', 'Mali', 'Niger', 'Congo, Republic of', 'Guinea', 'Congo, Democratic Republic of the', 'Luxembourg', 'Haiti', 'Chad', 'Burundi', 'Madagascar', 'Comoros', 'Senegal'), 'Portuguese': ('Portugal', 'Brazil', 'Sao Tome and Principe', 'Cape Verde', 'Angola', 'Mozambique', 'Guinea-Bissau'), 'German': ('Liechtenstein', 'Austria', 'West Germany', 'Switzerland', 'East Germany', 'Germany'), 'Arabic': ('Saudi Arabia', 'Kuwait', 'Jordan', 'Oman', 'Yemen', 'United Arab Emirates', 'Mauritania', 'Lebanon', 'Bahrain', 'Libya', 'Palestinian State (proposed)', 'Qatar', 'Algeria', 'Morocco', 'Iraq', 'Egypt', 'Djibouti', 'Sudan', 'Syria', 'Tunisia'), 'Turkish': ('Turkey', 'Azerbaijan'), 'Swahili': ('Tanzania',), 'Swedish': ('Sweden',), 'Icelandic': ('Iceland',), 'Estonian': ('Estonia',), 'Romanian': ('Romania',), 'Samoan': ('Samoa',), 'Slovenian': ('Slovenia',), 'Tok Pisin': ('Papua New Guinea',), 'Palauan': ('Palau',), 'Macedonian': ('Macedonia',), 'Hindi': ('India',), 'Dutch': ('Netherlands', 'Belgium', 'Suriname'), 'Marshallese': ('Marshall Islands',), 'Korean': ('Korea, North', 'Korea, South', 'North Korea', 'South Korea'), 'Vietnamese': ('Vietnam',), 'Danish': ('Denmark',), 'Khmer': ('Cambodia',), 'Lao': ('Laos',), 'Somali': ('Somalia',), 'Filipino': ('Philippines',), 'Hungarian': ('Hungary',), 'Ukrainian': ('Ukraine',), 'Bosnian': ('Bosnia and Herzegovina',), 'Georgian': ('Georgia',), 'Lithuanian': ('Lithuania',), 'Malay': ('Brunei',), 'Tetum': ('East Timor',), 'Norwegian': ('Norway',), 'Armenian': ('Armenia',), 'Russian': ('Russia',), 'Slovak': ('Slovakia',), 'Thai': ('Thailand',), 'Croatian': ('Croatia',), 'Turkmen': ('Turkmenistan',), 'Nepali': ('Nepal',), 'Finnish': ('Finland',), 'Uzbek': ('Uzbekistan',), 'Albanian': ('Albania', 'Kosovo'), 'Hebrew': ('Israel',), 'Bulgarian': ('Bulgaria',), 'Greek': ('Cyprus', 'Greece'), 'Burmese': ('Myanmar',), 'Latvian': ('Latvia',), 'Serbian': ('Serbia',), 'Afar': ('Eritrea',), 'Catalan': ('Andorra',), 'Chinese': ('China', 'Taiwan'), 'Czech': ('Czech Republic', 'Czechoslovakia'), 'Bislama': ('Vanuatu',), 'Japanese': ('Japan',), 'Kinyarwanda': ('Rwanda',), 'Amharic': ('Ethiopia',), 'Persian': ('Afghanistan', 'Iran'), 'Tajik': ('Tajikistan',), 'Mongolian': ('Mongolia',), 'Dzongkha': ('Bhutan',), 'Urdu': ('Pakistan',), 'Polish': ('Poland',), 'Sinhala': ('Sri Lanka',), } # Maps countries to their main language. COUNTRY_LANG = {} for lang in LANG_COUNTRIES: for country in LANG_COUNTRIES[lang]: COUNTRY_LANG[country] = lang def toUnicode(articles): """Convert a list of articles utf-8 encoded to unicode strings.""" return tuple([art.decode('utf_8') for art in articles]) def toDicts(articles): """Given a list of utf-8 encoded articles, build two dictionary (one utf-8 encoded and another one with unicode keys) for faster matches.""" uArticles = toUnicode(articles) return dict([(x, x) for x in articles]), dict([(x, x) for x in uArticles]) def addTrailingSpace(articles): """From the given list of utf-8 encoded articles, return two lists (one utf-8 encoded and another one in unicode) where a space is added at the end - if the last char is not ' or -.""" _spArticles = [] _spUnicodeArticles = [] for article in articles: if article[-1] not in ("'", '-'): article += ' ' _spArticles.append(article) _spUnicodeArticles.append(article.decode('utf_8')) return _spArticles, _spUnicodeArticles # Caches. _ART_CACHE = {} _SP_ART_CACHE = {} def articlesDictsForLang(lang): """Return dictionaries of articles specific for the given language, or the default one if the language is not known.""" if lang in _ART_CACHE: return _ART_CACHE[lang] artDicts = toDicts(LANG_ARTICLESget(lang, GENERIC_ARTICLES)) _ART_CACHE[lang] = artDicts return artDicts def spArticlesForLang(lang): """Return lists of articles (plus optional spaces) specific for the given language, or the default one if the language is not known.""" if lang in _SP_ART_CACHE: return _SP_ART_CACHE[lang] spArticles = addTrailingSpace(LANG_ARTICLESget(lang, GENERIC_ARTICLES)) _SP_ART_CACHE[lang] = spArticles return spArticles
gpl-3.0
-2,224,904,809,962,816,500
44.418719
532
0.627766
false
brandonrobertz/namecoin-core
contrib/zmq/zmq_sub.py
9
3056
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """ ZMQ example using python3's asyncio Bitcoin should be started with the command line arguments: bitcoind -testnet -daemon \ -zmqpubrawtx=tcp://127.0.0.1:28332 \ -zmqpubrawblock=tcp://127.0.0.1:28332 \ -zmqpubhashtx=tcp://127.0.0.1:28332 \ -zmqpubhashblock=tcp://127.0.0.1:28332 We use the asyncio library here. `self.handle()` installs itself as a future at the end of the function. Since it never returns with the event loop having an empty stack of futures, this creates an infinite loop. An alternative is to wrap the contents of `handle` inside `while True`. A blocking example using python 2.7 can be obtained from the git history: https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py """ import binascii import asyncio import zmq import zmq.asyncio import signal import struct import sys if not (sys.version_info.major >= 3 and sys.version_info.minor >= 5): print("This example only works with Python 3.5 and greater") sys.exit(1) port = 28332 class ZMQHandler(): def __init__(self): self.loop = zmq.asyncio.install() self.zmqContext = zmq.asyncio.Context() self.zmqSubSocket = self.zmqContext.socket(zmq.SUB) self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashblock") self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashtx") self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawblock") self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawtx") self.zmqSubSocket.connect("tcp://127.0.0.1:%i" % port) async def handle(self) : msg = await self.zmqSubSocket.recv_multipart() topic = msg[0] body = msg[1] sequence = "Unknown" if len(msg[-1]) == 4: msgSequence = struct.unpack('<I', msg[-1])[-1] sequence = str(msgSequence) if topic == b"hashblock": print('- HASH BLOCK ('+sequence+') -') print(binascii.hexlify(body)) elif topic == b"hashtx": print('- HASH TX ('+sequence+') -') print(binascii.hexlify(body)) elif topic == b"rawblock": print('- RAW BLOCK HEADER ('+sequence+') -') print(binascii.hexlify(body[:80])) elif topic == b"rawtx": print('- RAW TX ('+sequence+') -') print(binascii.hexlify(body)) # schedule ourselves to receive the next message asyncio.ensure_future(self.handle()) def start(self): self.loop.add_signal_handler(signal.SIGINT, self.stop) self.loop.create_task(self.handle()) self.loop.run_forever() def stop(self): self.loop.stop() self.zmqContext.destroy() daemon = ZMQHandler() daemon.start()
mit
-1,572,662,996,304,262,000
35.380952
107
0.637435
false
alessandrocamilli/l10n-italy
l10n_it_base_location_geonames_import/geonames_import.py
12
1409
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Agile Business Group (http://www.agilebg.com) # @author Lorenzo Battistini <lorenzo.battistini@agilebg.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, api class better_zip_geonames_import(models.TransientModel): _inherit = 'better.zip.geonames.import' @api.model def select_or_create_state( self, row, country_id, code_row_index=4, name_row_index=3 ): return super(better_zip_geonames_import, self).select_or_create_state( row, country_id, code_row_index=6, name_row_index=5)
agpl-3.0
5,053,863,013,718,167,000
41.69697
78
0.627395
false
Evervolv/android_external_chromium_org
media/tools/layout_tests/layouttests.py
144
8952
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Layout tests module that is necessary for the layout analyzer. Layout tests are stored in an SVN repository and LayoutTestCaseManager collects these layout test cases (including description). """ import copy import csv import locale import re import sys import urllib2 import pysvn # LayoutTests SVN root location. DEFAULT_LAYOUTTEST_LOCATION = ( 'http://src.chromium.org/blink/trunk/LayoutTests/') # LayoutTests SVN view link DEFAULT_LAYOUTTEST_SVN_VIEW_LOCATION = ( 'http://src.chromium.org/viewvc/blink/trunk/LayoutTests/') # When parsing the test HTML file and finding the test description, # this script tries to find the test description using sentences # starting with these keywords. This is adhoc but it is the only way # since there is no standard for writing test description. KEYWORDS_FOR_TEST_DESCRIPTION = ['This test', 'Tests that', 'Test '] # If cannot find the keywords, this script tries to find test case # description by the following tags. TAGS_FOR_TEST_DESCRIPTION = ['title', 'p', 'div'] # If cannot find the tags, this script tries to find the test case # description in the sentence containing following words. KEYWORD_FOR_TEST_DESCRIPTION_FAIL_SAFE = ['PASSED ', 'PASS:'] class LayoutTests(object): """A class to store test names in layout tests. The test names (including regular expression patterns) are read from a CSV file and used for getting layout test names from repository. """ def __init__(self, layouttest_root_path=DEFAULT_LAYOUTTEST_LOCATION, parent_location_list=None, filter_names=None, recursion=False): """Initialize LayoutTests using root and CSV file. Args: layouttest_root_path: A location string where layout tests are stored. parent_location_list: A list of parent directories that are needed for getting layout tests. filter_names: A list of test name patterns that are used for filtering test names (e.g., media/*.html). recursion: a boolean indicating whether the test names are sought recursively. """ if layouttest_root_path.startswith('http://'): name_map = self.GetLayoutTestNamesFromSVN(parent_location_list, layouttest_root_path, recursion) else: # TODO(imasaki): support other forms such as CSV for reading test names. pass self.name_map = copy.copy(name_map) if filter_names: # Filter names. for lt_name in name_map.iterkeys(): match = False for filter_name in filter_names: if re.search(filter_name, lt_name): match = True break if not match: del self.name_map[lt_name] # We get description only for the filtered names. for lt_name in self.name_map.iterkeys(): self.name_map[lt_name] = 'No description available' @staticmethod def ExtractTestDescription(txt): """Extract the description description from test code in HTML. Currently, we have 4 rules described in the code below. (This example falls into rule 1): <p> This tests the intrinsic size of a video element is the default 300,150 before metadata is loaded, and 0,0 after metadata is loaded for an audio-only file. </p> The strategy is very adhoc since the original test case files (in HTML format) do not have standard way to store test description. Args: txt: A HTML text which may or may not contain test description. Returns: A string that contains test description. Returns 'UNKNOWN' if the test description is not found. """ # (1) Try to find test description that contains keywords such as # 'test that' and surrounded by p tag. # This is the most common case. for keyword in KEYWORDS_FOR_TEST_DESCRIPTION: # Try to find <p> and </p>. pattern = r'<p>(.*' + keyword + '.*)</p>' matches = re.search(pattern, txt) if matches is not None: return matches.group(1).strip() # (2) Try to find it by using more generic keywords such as 'PASS' etc. for keyword in KEYWORD_FOR_TEST_DESCRIPTION_FAIL_SAFE: # Try to find new lines. pattern = r'\n(.*' + keyword + '.*)\n' matches = re.search(pattern, txt) if matches is not None: # Remove 'p' tag. text = matches.group(1).strip() return text.replace('<p>', '').replace('</p>', '') # (3) Try to find it by using HTML tag such as title. for tag in TAGS_FOR_TEST_DESCRIPTION: pattern = r'<' + tag + '>(.*)</' + tag + '>' matches = re.search(pattern, txt) if matches is not None: return matches.group(1).strip() # (4) Try to find it by using test description and remove 'p' tag. for keyword in KEYWORDS_FOR_TEST_DESCRIPTION: # Try to find <p> and </p>. pattern = r'\n(.*' + keyword + '.*)\n' matches = re.search(pattern, txt) if matches is not None: # Remove 'p' tag. text = matches.group(1).strip() return text.replace('<p>', '').replace('</p>', '') # (5) cannot find test description using existing rules. return 'UNKNOWN' @staticmethod def GetLayoutTestNamesFromSVN(parent_location_list, layouttest_root_path, recursion): """Get LayoutTest names from SVN. Args: parent_location_list: a list of locations of parent directories. This is used when getting layout tests using PySVN.list(). layouttest_root_path: the root path of layout tests directory. recursion: a boolean indicating whether the test names are sought recursively. Returns: a map containing test names as keys for de-dupe. """ client = pysvn.Client() # Get directory structure in the repository SVN. name_map = {} for parent_location in parent_location_list: if parent_location.endswith('/'): full_path = layouttest_root_path + parent_location try: file_list = client.list(full_path, recurse=recursion) for file_name in file_list: if sys.stdout.isatty(): default_encoding = sys.stdout.encoding else: default_encoding = locale.getpreferredencoding() file_name = file_name[0].repos_path.encode(default_encoding) # Remove the word '/truck/LayoutTests'. file_name = file_name.replace('/trunk/LayoutTests/', '') if file_name.endswith('.html'): name_map[file_name] = True except: print 'Unable to list tests in %s.' % full_path return name_map @staticmethod def GetLayoutTestNamesFromCSV(csv_file_path): """Get layout test names from CSV file. Args: csv_file_path: the path for the CSV file containing test names (including regular expression patterns). The CSV file content has one column and each row contains a test name. Returns: a list of test names in string. """ file_object = file(csv_file_path, 'r') reader = csv.reader(file_object) names = [row[0] for row in reader] file_object.close() return names @staticmethod def GetParentDirectoryList(names): """Get parent directory list from test names. Args: names: a list of test names. The test names also have path information as well (e.g., media/video-zoom.html). Returns: a list of parent directories for the given test names. """ pd_map = {} for name in names: p_dir = name[0:name.rfind('/') + 1] pd_map[p_dir] = True return list(pd_map.iterkeys()) def JoinWithTestExpectation(self, test_expectations): """Join layout tests with the test expectation file using test name as key. Args: test_expectations: a test expectations object. Returns: test_info_map contains test name as key and another map as value. The other map contains test description and the test expectation information which contains keyword (e.g., 'GPU') as key (we do not care about values). The map data structure is used since we have to look up these keywords several times. """ test_info_map = {} for (lt_name, desc) in self.name_map.items(): test_info_map[lt_name] = {} test_info_map[lt_name]['desc'] = desc for (te_name, te_info) in ( test_expectations.all_test_expectation_info.items()): if te_name == lt_name or ( te_name in lt_name and te_name.endswith('/')): # Only keep the first match when found. test_info_map[lt_name]['te_info'] = te_info break return test_info_map
bsd-3-clause
-5,619,286,742,419,377,000
35.688525
79
0.642761
false
CydarLtd/ansible
lib/ansible/cli/pull.py
30
12743
# (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 datetime import os import platform import random import shutil import socket import sys import time from ansible.errors import AnsibleOptionsError from ansible.cli import CLI from ansible.module_utils._text import to_native from ansible.plugins import module_loader from ansible.utils.cmd_functions import run_cmd try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() ######################################################## class PullCLI(CLI): ''' is used to up a remote copy of ansible on each managed node, each set to run via cron and update playbook source via a source repository. This inverts the default *push* architecture of ansible into a *pull* architecture, which has near-limitless scaling potential. The setup playbook can be tuned to change the cron frequency, logging locations, and parameters to ansible-pull. This is useful both for extreme scale-out as well as periodic remediation. Usage of the 'fetch' module to retrieve logs from ansible-pull runs would be an excellent way to gather and analyze remote logs from ansible-pull. ''' DEFAULT_REPO_TYPE = 'git' DEFAULT_PLAYBOOK = 'local.yml' PLAYBOOK_ERRORS = { 1: 'File does not exist', 2: 'File is not readable' } SUPPORTED_REPO_MODULES = ['git'] ARGUMENTS = { 'playbook.yml': 'The name of one the YAML format files to run as an Ansible playbook.' 'This can be a relative path within the checkout. By default, Ansible will' "look for a playbook based on the host's fully-qualified domain name," 'on the host hostname and finally a playbook named *local.yml*.', } def parse(self): ''' create an options parser for bin/ansible ''' self.parser = CLI.base_parser( usage='%prog -U <repository> [options] [<playbook.yml>]', connect_opts=True, vault_opts=True, runtask_opts=True, subset_opts=True, inventory_opts=True, module_opts=True, runas_prompt_opts=True, desc="pulls playbooks from a VCS repo and executes them for the local host", ) # options unique to pull self.parser.add_option('--purge', default=False, action='store_true', help='purge checkout after playbook run') self.parser.add_option('-o', '--only-if-changed', dest='ifchanged', default=False, action='store_true', help='only run the playbook if the repository has been updated') self.parser.add_option('-s', '--sleep', dest='sleep', default=None, help='sleep for random interval (between 0 and n number of seconds) before starting. This is a useful way to disperse git requests') self.parser.add_option('-f', '--force', dest='force', default=False, action='store_true', help='run the playbook even if the repository could not be updated') self.parser.add_option('-d', '--directory', dest='dest', default=None, help='directory to checkout repository to') self.parser.add_option('-U', '--url', dest='url', default=None, help='URL of the playbook repository') self.parser.add_option('--full', dest='fullclone', action='store_true', help='Do a full clone, instead of a shallow one.') self.parser.add_option('-C', '--checkout', dest='checkout', help='branch/tag/commit to checkout. Defaults to behavior of repository module.') self.parser.add_option('--accept-host-key', default=False, dest='accept_host_key', action='store_true', help='adds the hostkey for the repo url if not already added') self.parser.add_option('-m', '--module-name', dest='module_name', default=self.DEFAULT_REPO_TYPE, help='Repository module name, which ansible will use to check out the repo. Default is %s.' % self.DEFAULT_REPO_TYPE) self.parser.add_option('--verify-commit', dest='verify', default=False, action='store_true', help='verify GPG signature of checked out commit, if it fails abort running the playbook.' ' This needs the corresponding VCS module to support such an operation') self.parser.add_option('--clean', dest='clean', default=False, action='store_true', help='modified files in the working repository will be discarded') self.parser.add_option('--track-subs', dest='tracksubs', default=False, action='store_true', help='submodules will track the latest changes. This is equivalent to specifying the --remote flag to git submodule update') # for pull we don't wan't a default self.parser.set_defaults(inventory=None) super(PullCLI, self).parse() if not self.options.dest: hostname = socket.getfqdn() # use a hostname dependent directory, in case of $HOME on nfs self.options.dest = os.path.join('~/.ansible/pull', hostname) self.options.dest = os.path.expandvars(os.path.expanduser(self.options.dest)) if self.options.sleep: try: secs = random.randint(0,int(self.options.sleep)) self.options.sleep = secs except ValueError: raise AnsibleOptionsError("%s is not a number." % self.options.sleep) if not self.options.url: raise AnsibleOptionsError("URL for repository not specified, use -h for help") if self.options.module_name not in self.SUPPORTED_REPO_MODULES: raise AnsibleOptionsError("Unsuported repo module %s, choices are %s" % (self.options.module_name, ','.join(self.SUPPORTED_REPO_MODULES))) display.verbosity = self.options.verbosity self.validate_conflicts(vault_opts=True) def run(self): ''' use Runner lib to do SSH things ''' super(PullCLI, self).run() # log command line now = datetime.datetime.now() display.display(now.strftime("Starting Ansible Pull at %F %T")) display.display(' '.join(sys.argv)) # Build Checkout command # Now construct the ansible command node = platform.node() host = socket.getfqdn() limit_opts = 'localhost,%s,127.0.0.1' % ','.join(set([host, node, host.split('.')[0], node.split('.')[0]])) base_opts = '-c local ' if self.options.verbosity > 0: base_opts += ' -%s' % ''.join([ "v" for x in range(0, self.options.verbosity) ]) # Attempt to use the inventory passed in as an argument # It might not yet have been downloaded so use localhost as default if not self.options.inventory or ( ',' not in self.options.inventory and not os.path.exists(self.options.inventory)): inv_opts = 'localhost,' else: inv_opts = self.options.inventory #FIXME: enable more repo modules hg/svn? if self.options.module_name == 'git': repo_opts = "name=%s dest=%s" % (self.options.url, self.options.dest) if self.options.checkout: repo_opts += ' version=%s' % self.options.checkout if self.options.accept_host_key: repo_opts += ' accept_hostkey=yes' if self.options.private_key_file: repo_opts += ' key_file=%s' % self.options.private_key_file if self.options.verify: repo_opts += ' verify_commit=yes' if self.options.clean: repo_opts += ' force=yes' if self.options.tracksubs: repo_opts += ' track_submodules=yes' if not self.options.fullclone: repo_opts += ' depth=1' path = module_loader.find_plugin(self.options.module_name) if path is None: raise AnsibleOptionsError(("module '%s' not found.\n" % self.options.module_name)) bin_path = os.path.dirname(os.path.abspath(sys.argv[0])) # hardcode local and inventory/host as this is just meant to fetch the repo cmd = '%s/ansible -i "%s" %s -m %s -a "%s" all -l "%s"' % (bin_path, inv_opts, base_opts, self.options.module_name, repo_opts, limit_opts) for ev in self.options.extra_vars: cmd += ' -e "%s"' % ev # Nap? if self.options.sleep: display.display("Sleeping for %d seconds..." % self.options.sleep) time.sleep(self.options.sleep) # RUN the Checkout command display.debug("running ansible with VCS module to checkout repo") display.vvvv('EXEC: %s' % cmd) rc, out, err = run_cmd(cmd, live=True) if rc != 0: if self.options.force: display.warning("Unable to update repository. Continuing with (forced) run of playbook.") else: return rc elif self.options.ifchanged and '"changed": true' not in out: display.display("Repository has not changed, quitting.") return 0 playbook = self.select_playbook(self.options.dest) if playbook is None: raise AnsibleOptionsError("Could not find a playbook to run.") # Build playbook command cmd = '%s/ansible-playbook %s %s' % (bin_path, base_opts, playbook) if self.options.vault_password_file: cmd += " --vault-password-file=%s" % self.options.vault_password_file if self.options.inventory: cmd += ' -i "%s"' % self.options.inventory for ev in self.options.extra_vars: cmd += ' -e "%s"' % ev if self.options.ask_sudo_pass or self.options.ask_su_pass or self.options.become_ask_pass: cmd += ' --ask-become-pass' if self.options.skip_tags: cmd += ' --skip-tags "%s"' % to_native(u','.join(self.options.skip_tags)) if self.options.tags: cmd += ' -t "%s"' % to_native(u','.join(self.options.tags)) if self.options.subset: cmd += ' -l "%s"' % self.options.subset else: cmd += ' -l "%s"' % limit_opts os.chdir(self.options.dest) # RUN THE PLAYBOOK COMMAND display.debug("running ansible-playbook to do actual work") display.debug('EXEC: %s' % cmd) rc, out, err = run_cmd(cmd, live=True) if self.options.purge: os.chdir('/') try: shutil.rmtree(self.options.dest) except Exception as e: display.error("Failed to remove %s: %s" % (self.options.dest, str(e))) return rc def try_playbook(self, path): if not os.path.exists(path): return 1 if not os.access(path, os.R_OK): return 2 return 0 def select_playbook(self, path): playbook = None if len(self.args) > 0 and self.args[0] is not None: playbook = os.path.join(path, self.args[0]) rc = self.try_playbook(playbook) if rc != 0: display.warning("%s: %s" % (playbook, self.PLAYBOOK_ERRORS[rc])) return None return playbook else: fqdn = socket.getfqdn() hostpb = os.path.join(path, fqdn + '.yml') shorthostpb = os.path.join(path, fqdn.split('.')[0] + '.yml') localpb = os.path.join(path, self.DEFAULT_PLAYBOOK) errors = [] for pb in [hostpb, shorthostpb, localpb]: rc = self.try_playbook(pb) if rc == 0: playbook = pb break else: errors.append("%s: %s" % (pb, self.PLAYBOOK_ERRORS[rc])) if playbook is None: display.warning("\n".join(errors)) return playbook
gpl-3.0
4,841,745,649,648,492,000
43.400697
150
0.60237
false
FlorianLudwig/odoo
addons/account_followup/wizard/account_followup_print.py
217
16379
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import datetime import time from openerp import tools from openerp.osv import fields, osv from openerp.tools.translate import _ class account_followup_stat_by_partner(osv.osv): _name = "account_followup.stat.by.partner" _description = "Follow-up Statistics by Partner" _rec_name = 'partner_id' _auto = False def _get_invoice_partner_id(self, cr, uid, ids, field_name, arg, context=None): result = {} for rec in self.browse(cr, uid, ids, context=context): result[rec.id] = rec.partner_id.address_get(adr_pref=['invoice']).get('invoice', rec.partner_id.id) return result _columns = { 'partner_id': fields.many2one('res.partner', 'Partner', readonly=True), 'date_move':fields.date('First move', readonly=True), 'date_move_last':fields.date('Last move', readonly=True), 'date_followup':fields.date('Latest follow-up', readonly=True), 'max_followup_id': fields.many2one('account_followup.followup.line', 'Max Follow Up Level', readonly=True, ondelete="cascade"), 'balance':fields.float('Balance', readonly=True), 'company_id': fields.many2one('res.company', 'Company', readonly=True), 'invoice_partner_id': fields.function(_get_invoice_partner_id, type='many2one', relation='res.partner', string='Invoice Address') } _depends = { 'account.move.line': [ 'account_id', 'company_id', 'credit', 'date', 'debit', 'followup_date', 'followup_line_id', 'partner_id', 'reconcile_id', ], 'account.account': ['active', 'type'], } def init(self, cr): tools.drop_view_if_exists(cr, 'account_followup_stat_by_partner') # Here we don't have other choice but to create a virtual ID based on the concatenation # of the partner_id and the company_id, because if a partner is shared between 2 companies, # we want to see 2 lines for him in this table. It means that both company should be able # to send him follow-ups separately . An assumption that the number of companies will not # reach 10 000 records is made, what should be enough for a time. cr.execute(""" create view account_followup_stat_by_partner as ( SELECT l.partner_id * 10000::bigint + l.company_id as id, l.partner_id AS partner_id, min(l.date) AS date_move, max(l.date) AS date_move_last, max(l.followup_date) AS date_followup, max(l.followup_line_id) AS max_followup_id, sum(l.debit - l.credit) AS balance, l.company_id as company_id FROM account_move_line l LEFT JOIN account_account a ON (l.account_id = a.id) WHERE a.active AND a.type = 'receivable' AND l.reconcile_id is NULL AND l.partner_id IS NOT NULL GROUP BY l.partner_id, l.company_id )""") class account_followup_sending_results(osv.osv_memory): def do_report(self, cr, uid, ids, context=None): if context is None: context = {} return context.get('report_data') def do_done(self, cr, uid, ids, context=None): return {} def _get_description(self, cr, uid, context=None): if context is None: context = {} return context.get('description') def _get_need_printing(self, cr, uid, context=None): if context is None: context = {} return context.get('needprinting') _name = 'account_followup.sending.results' _description = 'Results from the sending of the different letters and emails' _columns = { 'description': fields.text("Description", readonly=True), 'needprinting': fields.boolean("Needs Printing") } _defaults = { 'needprinting':_get_need_printing, 'description':_get_description, } class account_followup_print(osv.osv_memory): _name = 'account_followup.print' _description = 'Print Follow-up & Send Mail to Customers' _columns = { 'date': fields.date('Follow-up Sending Date', required=True, help="This field allow you to select a forecast date to plan your follow-ups"), 'followup_id': fields.many2one('account_followup.followup', 'Follow-Up', required=True, readonly = True), 'partner_ids': fields.many2many('account_followup.stat.by.partner', 'partner_stat_rel', 'osv_memory_id', 'partner_id', 'Partners', required=True), 'company_id':fields.related('followup_id', 'company_id', type='many2one', relation='res.company', store=True, readonly=True), 'email_conf': fields.boolean('Send Email Confirmation'), 'email_subject': fields.char('Email Subject', size=64), 'partner_lang': fields.boolean('Send Email in Partner Language', help='Do not change message text, if you want to send email in partner language, or configure from company'), 'email_body': fields.text('Email Body'), 'summary': fields.text('Summary', readonly=True), 'test_print': fields.boolean('Test Print', help='Check if you want to print follow-ups without changing follow-up level.'), } def _get_followup(self, cr, uid, context=None): if context is None: context = {} if context.get('active_model', 'ir.ui.menu') == 'account_followup.followup': return context.get('active_id', False) company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id followp_id = self.pool.get('account_followup.followup').search(cr, uid, [('company_id', '=', company_id)], context=context) return followp_id and followp_id[0] or False def process_partners(self, cr, uid, partner_ids, data, context=None): partner_obj = self.pool.get('res.partner') partner_ids_to_print = [] nbmanuals = 0 manuals = {} nbmails = 0 nbunknownmails = 0 nbprints = 0 resulttext = " " for partner in self.pool.get('account_followup.stat.by.partner').browse(cr, uid, partner_ids, context=context): if partner.max_followup_id.manual_action: partner_obj.do_partner_manual_action(cr, uid, [partner.partner_id.id], context=context) nbmanuals = nbmanuals + 1 key = partner.partner_id.payment_responsible_id.name or _("Anybody") if not key in manuals.keys(): manuals[key]= 1 else: manuals[key] = manuals[key] + 1 if partner.max_followup_id.send_email: nbunknownmails += partner_obj.do_partner_mail(cr, uid, [partner.partner_id.id], context=context) nbmails += 1 if partner.max_followup_id.send_letter: partner_ids_to_print.append(partner.id) nbprints += 1 message = "%s<I> %s </I>%s" % (_("Follow-up letter of "), partner.partner_id.latest_followup_level_id_without_lit.name, _(" will be sent")) partner_obj.message_post(cr, uid, [partner.partner_id.id], body=message, context=context) if nbunknownmails == 0: resulttext += str(nbmails) + _(" email(s) sent") else: resulttext += str(nbmails) + _(" email(s) should have been sent, but ") + str(nbunknownmails) + _(" had unknown email address(es)") + "\n <BR/> " resulttext += "<BR/>" + str(nbprints) + _(" letter(s) in report") + " \n <BR/>" + str(nbmanuals) + _(" manual action(s) assigned:") needprinting = False if nbprints > 0: needprinting = True resulttext += "<p align=\"center\">" for item in manuals: resulttext = resulttext + "<li>" + item + ":" + str(manuals[item]) + "\n </li>" resulttext += "</p>" result = {} action = partner_obj.do_partner_print(cr, uid, partner_ids_to_print, data, context=context) result['needprinting'] = needprinting result['resulttext'] = resulttext result['action'] = action or {} return result def do_update_followup_level(self, cr, uid, to_update, partner_list, date, context=None): #update the follow-up level on account.move.line for id in to_update.keys(): if to_update[id]['partner_id'] in partner_list: self.pool.get('account.move.line').write(cr, uid, [int(id)], {'followup_line_id': to_update[id]['level'], 'followup_date': date}) def clear_manual_actions(self, cr, uid, partner_list, context=None): # Partnerlist is list to exclude # Will clear the actions of partners that have no due payments anymore partner_list_ids = [partner.partner_id.id for partner in self.pool.get('account_followup.stat.by.partner').browse(cr, uid, partner_list, context=context)] ids = self.pool.get('res.partner').search(cr, uid, ['&', ('id', 'not in', partner_list_ids), '|', ('payment_responsible_id', '!=', False), ('payment_next_action_date', '!=', False)], context=context) partners_to_clear = [] for part in self.pool.get('res.partner').browse(cr, uid, ids, context=context): if not part.unreconciled_aml_ids: partners_to_clear.append(part.id) self.pool.get('res.partner').action_done(cr, uid, partners_to_clear, context=context) return len(partners_to_clear) def do_process(self, cr, uid, ids, context=None): context = dict(context or {}) #Get partners tmp = self._get_partners_followp(cr, uid, ids, context=context) partner_list = tmp['partner_ids'] to_update = tmp['to_update'] date = self.browse(cr, uid, ids, context=context)[0].date data = self.read(cr, uid, ids, context=context)[0] data['followup_id'] = data['followup_id'][0] #Update partners self.do_update_followup_level(cr, uid, to_update, partner_list, date, context=context) #process the partners (send mails...) restot_context = context.copy() restot = self.process_partners(cr, uid, partner_list, data, context=restot_context) context.update(restot_context) #clear the manual actions if nothing is due anymore nbactionscleared = self.clear_manual_actions(cr, uid, partner_list, context=context) if nbactionscleared > 0: restot['resulttext'] = restot['resulttext'] + "<li>" + _("%s partners have no credits and as such the action is cleared") %(str(nbactionscleared)) + "</li>" #return the next action mod_obj = self.pool.get('ir.model.data') model_data_ids = mod_obj.search(cr, uid, [('model','=','ir.ui.view'),('name','=','view_account_followup_sending_results')], context=context) resource_id = mod_obj.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id'] context.update({'description': restot['resulttext'], 'needprinting': restot['needprinting'], 'report_data': restot['action']}) return { 'name': _('Send Letters and Emails: Actions Summary'), 'view_type': 'form', 'context': context, 'view_mode': 'tree,form', 'res_model': 'account_followup.sending.results', 'views': [(resource_id,'form')], 'type': 'ir.actions.act_window', 'target': 'new', } def _get_msg(self, cr, uid, context=None): return self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.follow_up_msg _defaults = { 'date': lambda *a: time.strftime('%Y-%m-%d'), 'followup_id': _get_followup, 'email_body': "", 'email_subject': _('Invoices Reminder'), 'partner_lang': True, } def _get_partners_followp(self, cr, uid, ids, context=None): data = {} data = self.browse(cr, uid, ids, context=context)[0] company_id = data.company_id.id cr.execute( "SELECT l.partner_id, l.followup_line_id,l.date_maturity, l.date, l.id "\ "FROM account_move_line AS l "\ "LEFT JOIN account_account AS a "\ "ON (l.account_id=a.id) "\ "WHERE (l.reconcile_id IS NULL) "\ "AND (a.type='receivable') "\ "AND (l.state<>'draft') "\ "AND (l.partner_id is NOT NULL) "\ "AND (a.active) "\ "AND (l.debit > 0) "\ "AND (l.company_id = %s) " \ "AND (l.blocked = False)" \ "ORDER BY l.date", (company_id,)) #l.blocked added to take litigation into account and it is not necessary to change follow-up level of account move lines without debit move_lines = cr.fetchall() old = None fups = {} fup_id = 'followup_id' in context and context['followup_id'] or data.followup_id.id date = 'date' in context and context['date'] or data.date current_date = datetime.date(*time.strptime(date, '%Y-%m-%d')[:3]) cr.execute( "SELECT * "\ "FROM account_followup_followup_line "\ "WHERE followup_id=%s "\ "ORDER BY delay", (fup_id,)) #Create dictionary of tuples where first element is the date to compare with the due date and second element is the id of the next level for result in cr.dictfetchall(): delay = datetime.timedelta(days=result['delay']) fups[old] = (current_date - delay, result['id']) old = result['id'] partner_list = [] to_update = {} #Fill dictionary of accountmovelines to_update with the partners that need to be updated for partner_id, followup_line_id, date_maturity,date, id in move_lines: if not partner_id: continue if followup_line_id not in fups: continue stat_line_id = partner_id * 10000 + company_id if date_maturity: if date_maturity <= fups[followup_line_id][0].strftime('%Y-%m-%d'): if stat_line_id not in partner_list: partner_list.append(stat_line_id) to_update[str(id)]= {'level': fups[followup_line_id][1], 'partner_id': stat_line_id} elif date and date <= fups[followup_line_id][0].strftime('%Y-%m-%d'): if stat_line_id not in partner_list: partner_list.append(stat_line_id) to_update[str(id)]= {'level': fups[followup_line_id][1], 'partner_id': stat_line_id} return {'partner_ids': partner_list, 'to_update': to_update} # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
4,183,829,698,044,093,400
48.483384
181
0.573112
false
appneta/boto
boto/ec2/blockdevicemapping.py
149
6372
# Copyright (c) 2009-2012 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2012 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. # class BlockDeviceType(object): """ Represents parameters for a block device. """ def __init__(self, connection=None, ephemeral_name=None, no_device=False, volume_id=None, snapshot_id=None, status=None, attach_time=None, delete_on_termination=False, size=None, volume_type=None, iops=None, encrypted=None): self.connection = connection self.ephemeral_name = ephemeral_name self.no_device = no_device self.volume_id = volume_id self.snapshot_id = snapshot_id self.status = status self.attach_time = attach_time self.delete_on_termination = delete_on_termination self.size = size self.volume_type = volume_type self.iops = iops self.encrypted = encrypted def startElement(self, name, attrs, connection): pass def endElement(self, name, value, connection): lname = name.lower() if name == 'volumeId': self.volume_id = value elif lname == 'virtualname': self.ephemeral_name = value elif lname == 'nodevice': self.no_device = (value == 'true') elif lname == 'snapshotid': self.snapshot_id = value elif lname == 'volumesize': self.size = int(value) elif lname == 'status': self.status = value elif lname == 'attachtime': self.attach_time = value elif lname == 'deleteontermination': self.delete_on_termination = (value == 'true') elif lname == 'volumetype': self.volume_type = value elif lname == 'iops': self.iops = int(value) elif lname == 'encrypted': self.encrypted = (value == 'true') else: setattr(self, name, value) # for backwards compatibility EBSBlockDeviceType = BlockDeviceType class BlockDeviceMapping(dict): """ Represents a collection of BlockDeviceTypes when creating ec2 instances. Example: dev_sda1 = BlockDeviceType() dev_sda1.size = 100 # change root volume to 100GB instead of default bdm = BlockDeviceMapping() bdm['/dev/sda1'] = dev_sda1 reservation = image.run(..., block_device_map=bdm, ...) """ def __init__(self, connection=None): """ :type connection: :class:`boto.ec2.EC2Connection` :param connection: Optional connection. """ dict.__init__(self) self.connection = connection self.current_name = None self.current_value = None def startElement(self, name, attrs, connection): lname = name.lower() if lname in ['ebs', 'virtualname']: self.current_value = BlockDeviceType(self) return self.current_value def endElement(self, name, value, connection): lname = name.lower() if lname in ['device', 'devicename']: self.current_name = value elif lname in ['item', 'member']: self[self.current_name] = self.current_value def ec2_build_list_params(self, params, prefix=''): pre = '%sBlockDeviceMapping' % prefix return self._build_list_params(params, prefix=pre) def autoscale_build_list_params(self, params, prefix=''): pre = '%sBlockDeviceMappings.member' % prefix return self._build_list_params(params, prefix=pre) def _build_list_params(self, params, prefix=''): i = 1 for dev_name in self: pre = '%s.%d' % (prefix, i) params['%s.DeviceName' % pre] = dev_name block_dev = self[dev_name] if block_dev.ephemeral_name: params['%s.VirtualName' % pre] = block_dev.ephemeral_name else: if block_dev.no_device: params['%s.NoDevice' % pre] = '' else: if block_dev.snapshot_id: params['%s.Ebs.SnapshotId' % pre] = block_dev.snapshot_id if block_dev.size: params['%s.Ebs.VolumeSize' % pre] = block_dev.size if block_dev.delete_on_termination: params['%s.Ebs.DeleteOnTermination' % pre] = 'true' else: params['%s.Ebs.DeleteOnTermination' % pre] = 'false' if block_dev.volume_type: params['%s.Ebs.VolumeType' % pre] = block_dev.volume_type if block_dev.iops is not None: params['%s.Ebs.Iops' % pre] = block_dev.iops # The encrypted flag (even if False) cannot be specified for the root EBS # volume. if block_dev.encrypted is not None: if block_dev.encrypted: params['%s.Ebs.Encrypted' % pre] = 'true' else: params['%s.Ebs.Encrypted' % pre] = 'false' i += 1
mit
-153,593,812,756,178,620
37.618182
93
0.572191
false
h3biomed/ansible
lib/ansible/parsing/yaml/constructor.py
28
6151
# (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 yaml.constructor import SafeConstructor, ConstructorError from yaml.nodes import MappingNode from ansible.module_utils._text import to_bytes from ansible.parsing.yaml.objects import AnsibleMapping, AnsibleSequence, AnsibleUnicode from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode from ansible.utils.unsafe_proxy import wrap_var from ansible.parsing.vault import VaultLib from ansible.utils.display import Display display = Display() class AnsibleConstructor(SafeConstructor): def __init__(self, file_name=None, vault_secrets=None): self._ansible_file_name = file_name super(AnsibleConstructor, self).__init__() self._vaults = {} self.vault_secrets = vault_secrets or [] self._vaults['default'] = VaultLib(secrets=self.vault_secrets) def construct_yaml_map(self, node): data = AnsibleMapping() yield data value = self.construct_mapping(node) data.update(value) data.ansible_pos = self._node_position_info(node) def construct_mapping(self, node, deep=False): # Most of this is from yaml.constructor.SafeConstructor. We replicate # it here so that we can warn users when they have duplicate dict keys # (pyyaml silently allows overwriting keys) if not isinstance(node, MappingNode): raise ConstructorError(None, None, "expected a mapping node, but found %s" % node.id, node.start_mark) self.flatten_mapping(node) mapping = AnsibleMapping() # Add our extra information to the returned value mapping.ansible_pos = self._node_position_info(node) for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: raise ConstructorError("while constructing a mapping", node.start_mark, "found unacceptable key (%s)" % exc, key_node.start_mark) if key in mapping: display.warning(u'While constructing a mapping from {1}, line {2}, column {3}, found a duplicate dict key ({0}).' u' Using last defined value only.'.format(key, *mapping.ansible_pos)) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mapping def construct_yaml_str(self, node): # Override the default string handling function # to always return unicode objects value = self.construct_scalar(node) ret = AnsibleUnicode(value) ret.ansible_pos = self._node_position_info(node) return ret def construct_vault_encrypted_unicode(self, node): value = self.construct_scalar(node) b_ciphertext_data = to_bytes(value) # could pass in a key id here to choose the vault to associate with # TODO/FIXME: plugin vault selector vault = self._vaults['default'] if vault.secrets is None: raise ConstructorError(context=None, context_mark=None, problem="found !vault but no vault password provided", problem_mark=node.start_mark, note=None) ret = AnsibleVaultEncryptedUnicode(b_ciphertext_data) ret.vault = vault return ret def construct_yaml_seq(self, node): data = AnsibleSequence() yield data data.extend(self.construct_sequence(node)) data.ansible_pos = self._node_position_info(node) def construct_yaml_unsafe(self, node): return wrap_var(self.construct_yaml_str(node)) def _node_position_info(self, node): # the line number where the previous token has ended (plus empty lines) # Add one so that the first line is line 1 rather than line 0 column = node.start_mark.column + 1 line = node.start_mark.line + 1 # in some cases, we may have pre-read the data and then # passed it to the load() call for YAML, in which case we # want to override the default datasource (which would be # '<string>') to the actual filename we read in datasource = self._ansible_file_name or node.start_mark.name return (datasource, line, column) AnsibleConstructor.add_constructor( u'tag:yaml.org,2002:map', AnsibleConstructor.construct_yaml_map) AnsibleConstructor.add_constructor( u'tag:yaml.org,2002:python/dict', AnsibleConstructor.construct_yaml_map) AnsibleConstructor.add_constructor( u'tag:yaml.org,2002:str', AnsibleConstructor.construct_yaml_str) AnsibleConstructor.add_constructor( u'tag:yaml.org,2002:python/unicode', AnsibleConstructor.construct_yaml_str) AnsibleConstructor.add_constructor( u'tag:yaml.org,2002:seq', AnsibleConstructor.construct_yaml_seq) AnsibleConstructor.add_constructor( u'!unsafe', AnsibleConstructor.construct_yaml_unsafe) AnsibleConstructor.add_constructor( u'!vault', AnsibleConstructor.construct_vault_encrypted_unicode) AnsibleConstructor.add_constructor(u'!vault-encrypted', AnsibleConstructor.construct_vault_encrypted_unicode)
gpl-3.0
5,346,259,552,239,621,000
37.93038
129
0.667371
false
DDEFISHER/servo
components/script/dom/bindings/codegen/parser/tests/test_incomplete_types.py
276
1731
import WebIDL def WebIDLTest(parser, harness): parser.parse(""" interface TestIncompleteTypes { attribute FooInterface attr1; FooInterface method1(FooInterface arg); }; interface FooInterface { }; """) results = parser.finish() harness.ok(True, "TestIncompleteTypes interface parsed without error.") harness.check(len(results), 2, "Should be two productions.") iface = results[0] harness.ok(isinstance(iface, WebIDL.IDLInterface), "Should be an IDLInterface") harness.check(iface.identifier.QName(), "::TestIncompleteTypes", "Interface has the right QName") harness.check(iface.identifier.name, "TestIncompleteTypes", "Interface has the right name") harness.check(len(iface.members), 2, "Expect 2 members") attr = iface.members[0] harness.ok(isinstance(attr, WebIDL.IDLAttribute), "Should be an IDLAttribute") method = iface.members[1] harness.ok(isinstance(method, WebIDL.IDLMethod), "Should be an IDLMethod") harness.check(attr.identifier.QName(), "::TestIncompleteTypes::attr1", "Attribute has the right QName") harness.check(attr.type.name, "FooInterface", "Previously unresolved type has the right name") harness.check(method.identifier.QName(), "::TestIncompleteTypes::method1", "Attribute has the right QName") (returnType, args) = method.signatures()[0] harness.check(returnType.name, "FooInterface", "Previously unresolved type has the right name") harness.check(args[0].type.name, "FooInterface", "Previously unresolved type has the right name")
mpl-2.0
5,511,528,726,485,117,000
38.340909
101
0.65338
false
Charence/stk-code
tools/batch.py
16
3189
from matplotlib import pyplot from os import listdir def is_numeric(x): try: float(x) except ValueError: return False return True avg_lap_time = {} avg_pos = {} avg_speed = {} avg_top = {} total_rescued = {} tests = len(listdir('../../batch'))-1 for file in listdir('../../batch'): if (file == '.DS_Store'): continue f = open('../../batch/'+file,'r') ''' name_index = file.find('.') kart_name = str(file[:name_index]) first = file.find('.',name_index+1) track_name = file[name_index+1:first] second = file.find('.',first+1) run = int(file[first+1:second]) ''' track_name = "snowmountain" kart_names = ["gnu", "sara", "tux", "elephpant"] if track_name == "snowmountain": contents = f.readlines() ''' contents = contents[2:contents.index("[debug ] profile: \n")-1] content = [s for s in contents if kart_name in s] data = [float(x) for x in content[0].split() if is_numeric(x)] if kart_name not in avg_lap_time: avg_lap_time[kart_name] = [] avg_pos[kart_name] = [] avg_speed[kart_name] = [] avg_top[kart_name] = [] total_rescued[kart_name] = [] avg_lap_time[kart_name].append(data[2]/4) avg_pos[kart_name].append(data[1]) avg_speed[kart_name].append(data[3]) avg_top[kart_name].append(data[4]) total_rescued[kart_name].append(data[7]) ''' contents = contents[2:6] #TODO check if all is in here for kart in kart_names: content = [s for s in contents if kart in s] data = [float(x) for x in content[0].split() if is_numeric(x)] if kart not in avg_lap_time: avg_lap_time[kart] = [] avg_pos[kart] = [] avg_speed[kart] = [] avg_top[kart] = [] total_rescued[kart] = [] avg_lap_time[kart].append(data[2]/4) avg_pos[kart].append(data[1]) avg_speed[kart].append(data[3]) avg_top[kart].append(data[4]) total_rescued[kart].append(data[7]) tests = len(avg_lap_time["gnu"]) print total_rescued for kart in kart_names: print "rescues for ", kart , ": ", sum(total_rescued[kart])/tests print "avg_lap_time for " , kart , ": " , sum(avg_lap_time[kart])/tests print "avg_pos for " , kart , ": " , sum(avg_pos[kart])/tests print "avg_speed for " , kart , ": " , sum(avg_speed[kart])/tests print "avg_top for " , kart , ": " , sum(avg_top[kart])/tests pyplot.subplot(2,2,1) pyplot.plot(list(xrange(tests)),avg_pos["gnu"], "b-") pyplot.xlabel("tests") pyplot.ylabel("gnu") pyplot.subplot(2,2,2) pyplot.plot(list(xrange(tests)),avg_pos["sara"], "r-") pyplot.xlabel("tests") pyplot.ylabel("sara") pyplot.subplot(2,2,3) pyplot.plot(list(xrange(tests)),avg_pos["elephpant"], "y-") pyplot.xlabel("tests") pyplot.ylabel("elephpant") pyplot.subplot(2,2,4) pyplot.plot(list(xrange(tests)),avg_pos["tux"], "g-") pyplot.xlabel("tests") pyplot.ylabel("tux") pyplot.show()
gpl-3.0
35,945,694,768,538,510
29.961165
75
0.550329
false
camilonova/django
tests/model_inheritance/test_abstract_inheritance.py
27
12010
from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.core.checks import Error from django.core.exceptions import FieldDoesNotExist, FieldError from django.db import models from django.test import TestCase from django.test.utils import isolate_apps @isolate_apps('model_inheritance') class AbstractInheritanceTests(TestCase): def test_single_parent(self): class AbstractBase(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class AbstractDescendant(AbstractBase): name = models.CharField(max_length=50) class Meta: abstract = True class DerivedChild(AbstractBase): name = models.CharField(max_length=50) class DerivedGrandChild(AbstractDescendant): pass self.assertEqual(AbstractDescendant._meta.get_field('name').max_length, 50) self.assertEqual(DerivedChild._meta.get_field('name').max_length, 50) self.assertEqual(DerivedGrandChild._meta.get_field('name').max_length, 50) def test_multiple_parents_mro(self): class AbstractBaseOne(models.Model): class Meta: abstract = True class AbstractBaseTwo(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class DescendantOne(AbstractBaseOne, AbstractBaseTwo): class Meta: abstract = True class DescendantTwo(AbstractBaseOne, AbstractBaseTwo): name = models.CharField(max_length=50) class Meta: abstract = True class Derived(DescendantOne, DescendantTwo): pass self.assertEqual(DescendantOne._meta.get_field('name').max_length, 30) self.assertEqual(DescendantTwo._meta.get_field('name').max_length, 50) self.assertEqual(Derived._meta.get_field('name').max_length, 50) def test_multiple_inheritance_cannot_shadow_concrete_inherited_field(self): class ConcreteParent(models.Model): name = models.CharField(max_length=255) class AbstractParent(models.Model): name = models.IntegerField() class Meta: abstract = True class FirstChild(ConcreteParent, AbstractParent): pass class AnotherChild(AbstractParent, ConcreteParent): pass self.assertIsInstance(FirstChild._meta.get_field('name'), models.CharField) self.assertEqual( AnotherChild.check(), [Error( "The field 'name' clashes with the field 'name' " "from model 'model_inheritance.concreteparent'.", obj=AnotherChild._meta.get_field('name'), id="models.E006", )] ) def test_virtual_field(self): class RelationModel(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class RelatedModelAbstract(models.Model): field = GenericRelation(RelationModel) class Meta: abstract = True class ModelAbstract(models.Model): field = models.CharField(max_length=100) class Meta: abstract = True class OverrideRelatedModelAbstract(RelatedModelAbstract): field = models.CharField(max_length=100) class ExtendModelAbstract(ModelAbstract): field = GenericRelation(RelationModel) self.assertIsInstance(OverrideRelatedModelAbstract._meta.get_field('field'), models.CharField) self.assertIsInstance(ExtendModelAbstract._meta.get_field('field'), GenericRelation) def test_cannot_override_indirect_abstract_field(self): class AbstractBase(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class ConcreteDescendant(AbstractBase): pass msg = ( "Local field 'name' in class 'Descendant' clashes with field of " "the same name from base class 'ConcreteDescendant'." ) with self.assertRaisesMessage(FieldError, msg): class Descendant(ConcreteDescendant): name = models.IntegerField() def test_override_field_with_attr(self): class AbstractBase(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=30) full_name = models.CharField(max_length=150) class Meta: abstract = True class Descendant(AbstractBase): middle_name = None def full_name(self): return self.first_name + self.last_name with self.assertRaises(FieldDoesNotExist): Descendant._meta.get_field('middle_name') with self.assertRaises(FieldDoesNotExist): Descendant._meta.get_field('full_name') def test_overriding_field_removed_by_concrete_model(self): class AbstractModel(models.Model): foo = models.CharField(max_length=30) class Meta: abstract = True class RemovedAbstractModelField(AbstractModel): foo = None class OverrideRemovedFieldByConcreteModel(RemovedAbstractModelField): foo = models.CharField(max_length=50) self.assertEqual(OverrideRemovedFieldByConcreteModel._meta.get_field('foo').max_length, 50) def test_shadowed_fkey_id(self): class Foo(models.Model): pass class AbstractBase(models.Model): foo = models.ForeignKey(Foo, models.CASCADE) class Meta: abstract = True class Descendant(AbstractBase): foo_id = models.IntegerField() self.assertEqual( Descendant.check(), [Error( "The field 'foo_id' clashes with the field 'foo' " "from model 'model_inheritance.descendant'.", obj=Descendant._meta.get_field('foo_id'), id='models.E006', )] ) def test_shadow_related_name_when_set_to_none(self): class AbstractBase(models.Model): bar = models.IntegerField() class Meta: abstract = True class Foo(AbstractBase): bar = None foo = models.IntegerField() class Bar(models.Model): bar = models.ForeignKey(Foo, models.CASCADE, related_name='bar') self.assertEqual(Bar.check(), []) def test_reverse_foreign_key(self): class AbstractBase(models.Model): foo = models.CharField(max_length=100) class Meta: abstract = True class Descendant(AbstractBase): pass class Foo(models.Model): foo = models.ForeignKey(Descendant, models.CASCADE, related_name='foo') self.assertEqual( Foo._meta.get_field('foo').check(), [ Error( "Reverse accessor for 'Foo.foo' clashes with field name 'Descendant.foo'.", hint=( "Rename field 'Descendant.foo', or add/change a related_name " "argument to the definition for field 'Foo.foo'." ), obj=Foo._meta.get_field('foo'), id='fields.E302', ), Error( "Reverse query name for 'Foo.foo' clashes with field name 'Descendant.foo'.", hint=( "Rename field 'Descendant.foo', or add/change a related_name " "argument to the definition for field 'Foo.foo'." ), obj=Foo._meta.get_field('foo'), id='fields.E303', ), ] ) def test_multi_inheritance_field_clashes(self): class AbstractBase(models.Model): name = models.CharField(max_length=30) class Meta: abstract = True class ConcreteBase(AbstractBase): pass class AbstractDescendant(ConcreteBase): class Meta: abstract = True class ConcreteDescendant(AbstractDescendant): name = models.CharField(max_length=100) self.assertEqual( ConcreteDescendant.check(), [Error( "The field 'name' clashes with the field 'name' from " "model 'model_inheritance.concretebase'.", obj=ConcreteDescendant._meta.get_field('name'), id="models.E006", )] ) def test_override_one2one_relation_auto_field_clashes(self): class ConcreteParent(models.Model): name = models.CharField(max_length=255) class AbstractParent(models.Model): name = models.IntegerField() class Meta: abstract = True msg = ( "Auto-generated field 'concreteparent_ptr' in class 'Descendant' " "for parent_link to base class 'ConcreteParent' clashes with " "declared field of the same name." ) with self.assertRaisesMessage(FieldError, msg): class Descendant(ConcreteParent, AbstractParent): concreteparent_ptr = models.CharField(max_length=30) def test_abstract_model_with_regular_python_mixin_mro(self): class AbstractModel(models.Model): name = models.CharField(max_length=255) age = models.IntegerField() class Meta: abstract = True class Mixin: age = None class Mixin2: age = 2 class DescendantMixin(Mixin): pass class ConcreteModel(models.Model): foo = models.IntegerField() class ConcreteModel2(ConcreteModel): age = models.SmallIntegerField() def fields(model): if not hasattr(model, '_meta'): return list() return list((f.name, f.__class__) for f in model._meta.get_fields()) model_dict = {'__module__': 'model_inheritance'} model1 = type('Model1', (AbstractModel, Mixin), model_dict.copy()) model2 = type('Model2', (Mixin2, AbstractModel), model_dict.copy()) model3 = type('Model3', (DescendantMixin, AbstractModel), model_dict.copy()) model4 = type('Model4', (Mixin2, Mixin, AbstractModel), model_dict.copy()) model5 = type('Model5', (Mixin2, ConcreteModel2, Mixin, AbstractModel), model_dict.copy()) self.assertEqual( fields(model1), [('id', models.AutoField), ('name', models.CharField), ('age', models.IntegerField)] ) self.assertEqual(fields(model2), [('id', models.AutoField), ('name', models.CharField)]) self.assertEqual(getattr(model2, 'age'), 2) self.assertEqual(fields(model3), [('id', models.AutoField), ('name', models.CharField)]) self.assertEqual(fields(model4), [('id', models.AutoField), ('name', models.CharField)]) self.assertEqual(getattr(model4, 'age'), 2) self.assertEqual( fields(model5), [ ('id', models.AutoField), ('foo', models.IntegerField), ('concretemodel_ptr', models.OneToOneField), ('age', models.SmallIntegerField), ('concretemodel2_ptr', models.OneToOneField), ('name', models.CharField), ] )
bsd-3-clause
6,525,059,401,537,391,000
33.119318
102
0.581932
false
hbhzwj/imalse
tools/ns-allinone-3.14.1/ns-3.14.1/src/csma-layout/bindings/modulegen__gcc_LP64.py
12
456237
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.csma_layout', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## csma-channel.h (module 'csma'): ns3::WireState [enumeration] module.add_enum('WireState', ['IDLE', 'TRANSMITTING', 'PROPAGATING'], import_from_module='ns.csma') ## 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') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper [class] module.add_class('AsciiTraceHelper', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice [class] module.add_class('AsciiTraceHelperForDevice', allow_subclassing=True, import_from_module='ns.network') ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv4 [class] module.add_class('AsciiTraceHelperForIpv4', allow_subclassing=True, import_from_module='ns.internet') ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv6 [class] module.add_class('AsciiTraceHelperForIpv6', allow_subclassing=True, import_from_module='ns.internet') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## csma-channel.h (module 'csma'): ns3::CsmaDeviceRec [class] module.add_class('CsmaDeviceRec', import_from_module='ns.csma') ## csma-star-helper.h (module 'csma-layout'): ns3::CsmaStarHelper [class] module.add_class('CsmaStarHelper') ## data-rate.h (module 'network'): ns3::DataRate [class] module.add_class('DataRate', import_from_module='ns.network') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['0']) ## int-to-type.h (module 'core'): ns3::IntToType<0>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 0 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<1> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['1']) ## int-to-type.h (module 'core'): ns3::IntToType<1>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 1 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<2> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['2']) ## int-to-type.h (module 'core'): ns3::IntToType<2>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 2 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<3> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['3']) ## int-to-type.h (module 'core'): ns3::IntToType<3>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 3 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<4> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['4']) ## int-to-type.h (module 'core'): ns3::IntToType<4>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 4 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<5> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['5']) ## int-to-type.h (module 'core'): ns3::IntToType<5>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 5 >'], import_from_module='ns.core') ## int-to-type.h (module 'core'): ns3::IntToType<6> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=['6']) ## int-to-type.h (module 'core'): ns3::IntToType<6>::v_e [enumeration] module.add_enum('v_e', ['value'], outer_class=root_module['ns3::IntToType< 6 >'], import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper [class] module.add_class('Ipv4AddressHelper', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-interface-container.h (module 'internet'): ns3::Ipv4InterfaceContainer [class] module.add_class('Ipv4InterfaceContainer', import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address-generator.h (module 'internet'): ns3::Ipv6AddressGenerator [class] module.add_class('Ipv6AddressGenerator', import_from_module='ns.internet') ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6AddressHelper [class] module.add_class('Ipv6AddressHelper', import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress [class] module.add_class('Ipv6InterfaceAddress', import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e [enumeration] module.add_enum('State_e', ['TENTATIVE', 'DEPRECATED', 'PREFERRED', 'PERMANENT', 'HOMEADDRESS', 'TENTATIVE_OPTIMISTIC', 'INVALID'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e [enumeration] module.add_enum('Scope_e', ['HOST', 'LINKLOCAL', 'GLOBAL'], outer_class=root_module['ns3::Ipv6InterfaceAddress'], import_from_module='ns.internet') ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6InterfaceContainer [class] module.add_class('Ipv6InterfaceContainer', import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## net-device-container.h (module 'network'): ns3::NetDeviceContainer [class] module.add_class('NetDeviceContainer', import_from_module='ns.network') ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## pcap-file.h (module 'network'): ns3::PcapFile [class] module.add_class('PcapFile', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelper [class] module.add_class('PcapHelper', import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelper [enumeration] module.add_enum('', ['DLT_NULL', 'DLT_EN10MB', 'DLT_PPP', 'DLT_RAW', 'DLT_IEEE802_11', 'DLT_PRISM_HEADER', 'DLT_IEEE802_11_RADIO'], outer_class=root_module['ns3::PcapHelper'], import_from_module='ns.network') ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice [class] module.add_class('PcapHelperForDevice', allow_subclassing=True, import_from_module='ns.network') ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv4 [class] module.add_class('PcapHelperForIpv4', allow_subclassing=True, import_from_module='ns.internet') ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv6 [class] module.add_class('PcapHelperForIpv6', allow_subclassing=True, import_from_module='ns.internet') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## timer.h (module 'core'): ns3::Timer [class] module.add_class('Timer', import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::DestroyPolicy [enumeration] module.add_enum('DestroyPolicy', ['CANCEL_ON_DESTROY', 'REMOVE_ON_DESTROY', 'CHECK_ON_DESTROY'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer.h (module 'core'): ns3::Timer::State [enumeration] module.add_enum('State', ['RUNNING', 'EXPIRED', 'SUSPENDED'], outer_class=root_module['ns3::Timer'], import_from_module='ns.core') ## timer-impl.h (module 'core'): ns3::TimerImpl [class] module.add_class('TimerImpl', allow_subclassing=True, import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## csma-helper.h (module 'csma'): ns3::CsmaHelper [class] module.add_class('CsmaHelper', import_from_module='ns.csma', parent=[root_module['ns3::PcapHelperForDevice'], root_module['ns3::AsciiTraceHelperForDevice']]) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## internet-stack-helper.h (module 'internet'): ns3::InternetStackHelper [class] module.add_class('InternetStackHelper', import_from_module='ns.internet', parent=[root_module['ns3::PcapHelperForIpv4'], root_module['ns3::PcapHelperForIpv6'], root_module['ns3::AsciiTraceHelperForIpv4'], root_module['ns3::AsciiTraceHelperForIpv6']]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'CS1', 'AF11', 'AF12', 'AF13', 'CS2', 'AF21', 'AF22', 'AF23', 'CS3', 'AF31', 'AF32', 'AF33', 'CS4', 'AF41', 'AF42', 'AF43', 'CS5', 'EF', 'CS6', 'CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['NotECT', 'ECT1', 'ECT0', 'CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv6-header.h (module 'internet'): ns3::Ipv6Header [class] module.add_class('Ipv6Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::NextHeader_e [enumeration] module.add_enum('NextHeader_e', ['IPV6_EXT_HOP_BY_HOP', 'IPV6_IPV4', 'IPV6_TCP', 'IPV6_UDP', 'IPV6_IPV6', 'IPV6_EXT_ROUTING', 'IPV6_EXT_FRAGMENTATION', 'IPV6_EXT_CONFIDENTIALITY', 'IPV6_EXT_AUTHENTIFICATION', 'IPV6_ICMPV6', 'IPV6_EXT_END', 'IPV6_EXT_DESTINATION', 'IPV6_SCTP', 'IPV6_EXT_MOBILITY', 'IPV6_UDP_LITE'], outer_class=root_module['ns3::Ipv6Header'], import_from_module='ns.internet') ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper [class] module.add_class('PcapFileWrapper', import_from_module='ns.network', parent=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4MulticastRoute', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4MulticastRoute>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Ipv4Route', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Ipv4Route>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::OutputStreamWrapper', 'ns3::empty', 'ns3::DefaultDeleter<ns3::OutputStreamWrapper>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## socket.h (module 'network'): ns3::Socket [class] module.add_class('Socket', import_from_module='ns.network', parent=root_module['ns3::Object']) ## socket.h (module 'network'): ns3::Socket::SocketErrno [enumeration] module.add_enum('SocketErrno', ['ERROR_NOTERROR', 'ERROR_ISCONN', 'ERROR_NOTCONN', 'ERROR_MSGSIZE', 'ERROR_AGAIN', 'ERROR_SHUTDOWN', 'ERROR_OPNOTSUPP', 'ERROR_AFNOSUPPORT', 'ERROR_INVAL', 'ERROR_BADF', 'ERROR_NOROUTETOHOST', 'ERROR_NODEV', 'ERROR_ADDRNOTAVAIL', 'ERROR_ADDRINUSE', 'SOCKET_ERRNO_LAST'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::Socket::SocketType [enumeration] module.add_enum('SocketType', ['NS3_SOCK_STREAM', 'NS3_SOCK_SEQPACKET', 'NS3_SOCK_DGRAM', 'NS3_SOCK_RAW'], outer_class=root_module['ns3::Socket'], import_from_module='ns.network') ## socket.h (module 'network'): ns3::SocketAddressTag [class] module.add_class('SocketAddressTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## csma-channel.h (module 'csma'): ns3::CsmaChannel [class] module.add_class('CsmaChannel', import_from_module='ns.csma', parent=root_module['ns3::Channel']) ## data-rate.h (module 'network'): ns3::DataRateChecker [class] module.add_class('DataRateChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## data-rate.h (module 'network'): ns3::DataRateValue [class] module.add_class('DataRateValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol [class] module.add_class('IpL4Protocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus [enumeration] module.add_enum('RxStatus', ['RX_OK', 'RX_CSUM_FAILED', 'RX_ENDPOINT_CLOSED', 'RX_ENDPOINT_UNREACH'], outer_class=root_module['ns3::IpL4Protocol'], import_from_module='ns.internet') ## ipv4.h (module 'internet'): ns3::Ipv4 [class] module.add_class('Ipv4', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol [class] module.add_class('Ipv4L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv4']) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_BAD_CHECKSUM', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_FRAGMENT_TIMEOUT'], outer_class=root_module['ns3::Ipv4L3Protocol'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute [class] module.add_class('Ipv4MulticastRoute', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route [class] module.add_class('Ipv4Route', import_from_module='ns.internet', parent=root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol [class] module.add_class('Ipv4RoutingProtocol', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6.h (module 'internet'): ns3::Ipv6 [class] module.add_class('Ipv6', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface [class] module.add_class('Ipv6Interface', import_from_module='ns.internet', parent=root_module['ns3::Object']) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol [class] module.add_class('Ipv6L3Protocol', import_from_module='ns.internet', parent=root_module['ns3::Ipv6']) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol::DropReason [enumeration] module.add_enum('DropReason', ['DROP_TTL_EXPIRED', 'DROP_NO_ROUTE', 'DROP_INTERFACE_DOWN', 'DROP_ROUTE_ERROR', 'DROP_UNKNOWN_PROTOCOL'], outer_class=root_module['ns3::Ipv6L3Protocol'], import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper [class] module.add_class('OutputStreamWrapper', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## nstime.h (module 'core'): ns3::TimeChecker [class] module.add_class('TimeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) module.add_container('std::vector< bool >', 'bool', container_type='vector') module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type='map') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AsciiTraceHelper_methods(root_module, root_module['ns3::AsciiTraceHelper']) register_Ns3AsciiTraceHelperForDevice_methods(root_module, root_module['ns3::AsciiTraceHelperForDevice']) register_Ns3AsciiTraceHelperForIpv4_methods(root_module, root_module['ns3::AsciiTraceHelperForIpv4']) register_Ns3AsciiTraceHelperForIpv6_methods(root_module, root_module['ns3::AsciiTraceHelperForIpv6']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3CsmaDeviceRec_methods(root_module, root_module['ns3::CsmaDeviceRec']) register_Ns3CsmaStarHelper_methods(root_module, root_module['ns3::CsmaStarHelper']) register_Ns3DataRate_methods(root_module, root_module['ns3::DataRate']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3IntToType__0_methods(root_module, root_module['ns3::IntToType< 0 >']) register_Ns3IntToType__1_methods(root_module, root_module['ns3::IntToType< 1 >']) register_Ns3IntToType__2_methods(root_module, root_module['ns3::IntToType< 2 >']) register_Ns3IntToType__3_methods(root_module, root_module['ns3::IntToType< 3 >']) register_Ns3IntToType__4_methods(root_module, root_module['ns3::IntToType< 4 >']) register_Ns3IntToType__5_methods(root_module, root_module['ns3::IntToType< 5 >']) register_Ns3IntToType__6_methods(root_module, root_module['ns3::IntToType< 6 >']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4AddressHelper_methods(root_module, root_module['ns3::Ipv4AddressHelper']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4InterfaceContainer_methods(root_module, root_module['ns3::Ipv4InterfaceContainer']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6AddressGenerator_methods(root_module, root_module['ns3::Ipv6AddressGenerator']) register_Ns3Ipv6AddressHelper_methods(root_module, root_module['ns3::Ipv6AddressHelper']) register_Ns3Ipv6InterfaceAddress_methods(root_module, root_module['ns3::Ipv6InterfaceAddress']) register_Ns3Ipv6InterfaceContainer_methods(root_module, root_module['ns3::Ipv6InterfaceContainer']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3PcapFile_methods(root_module, root_module['ns3::PcapFile']) register_Ns3PcapHelper_methods(root_module, root_module['ns3::PcapHelper']) register_Ns3PcapHelperForDevice_methods(root_module, root_module['ns3::PcapHelperForDevice']) register_Ns3PcapHelperForIpv4_methods(root_module, root_module['ns3::PcapHelperForIpv4']) register_Ns3PcapHelperForIpv6_methods(root_module, root_module['ns3::PcapHelperForIpv6']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3Timer_methods(root_module, root_module['ns3::Timer']) register_Ns3TimerImpl_methods(root_module, root_module['ns3::TimerImpl']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3CsmaHelper_methods(root_module, root_module['ns3::CsmaHelper']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3InternetStackHelper_methods(root_module, root_module['ns3::InternetStackHelper']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Ipv6Header_methods(root_module, root_module['ns3::Ipv6Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3PcapFileWrapper_methods(root_module, root_module['ns3::PcapFileWrapper']) 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__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >']) register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Socket_methods(root_module, root_module['ns3::Socket']) register_Ns3SocketAddressTag_methods(root_module, root_module['ns3::SocketAddressTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketSetDontFragmentTag_methods(root_module, root_module['ns3::SocketSetDontFragmentTag']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3Channel_methods(root_module, root_module['ns3::Channel']) register_Ns3CsmaChannel_methods(root_module, root_module['ns3::CsmaChannel']) register_Ns3DataRateChecker_methods(root_module, root_module['ns3::DataRateChecker']) register_Ns3DataRateValue_methods(root_module, root_module['ns3::DataRateValue']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3IpL4Protocol_methods(root_module, root_module['ns3::IpL4Protocol']) register_Ns3Ipv4_methods(root_module, root_module['ns3::Ipv4']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4L3Protocol_methods(root_module, root_module['ns3::Ipv4L3Protocol']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv4MulticastRoute_methods(root_module, root_module['ns3::Ipv4MulticastRoute']) register_Ns3Ipv4Route_methods(root_module, root_module['ns3::Ipv4Route']) register_Ns3Ipv4RoutingProtocol_methods(root_module, root_module['ns3::Ipv4RoutingProtocol']) register_Ns3Ipv6_methods(root_module, root_module['ns3::Ipv6']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6Interface_methods(root_module, root_module['ns3::Ipv6Interface']) register_Ns3Ipv6L3Protocol_methods(root_module, root_module['ns3::Ipv6L3Protocol']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3OutputStreamWrapper_methods(root_module, root_module['ns3::OutputStreamWrapper']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3TimeChecker_methods(root_module, root_module['ns3::TimeChecker']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) 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_Ns3AsciiTraceHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper(ns3::AsciiTraceHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelper::AsciiTraceHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::OutputStreamWrapper> ns3::AsciiTraceHelper::CreateFileStream(std::string filename, std::_Ios_Openmode filemode=std::ios_base::out) [member function] cls.add_method('CreateFileStream', 'ns3::Ptr< ns3::OutputStreamWrapper >', [param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode', default_value='std::ios_base::out')]) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDequeueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDequeueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultDropSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultDropSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultEnqueueSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultEnqueueSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithContext(ns3::Ptr<ns3::OutputStreamWrapper> file, std::string context, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('std::string', 'context'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): static void ns3::AsciiTraceHelper::DefaultReceiveSinkWithoutContext(ns3::Ptr<ns3::OutputStreamWrapper> file, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('DefaultReceiveSinkWithoutContext', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'file'), param('ns3::Ptr< ns3::Packet const >', 'p')], is_static=True) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::AsciiTraceHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3AsciiTraceHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice(ns3::AsciiTraceHelperForDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::AsciiTraceHelperForDevice::AsciiTraceHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::NetDevice> nd) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::NetDevice >', 'nd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, std::string ndName, bool explicitFilename=false) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ndName) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ndName')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NetDeviceContainer d) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NetDeviceContainer', 'd')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function] cls.add_method('EnableAscii', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAscii(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t deviceid) [member function] cls.add_method('EnableAscii', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(std::string prefix) [member function] cls.add_method('EnableAsciiAll', 'void', [param('std::string', 'prefix')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiAll(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiAll', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## trace-helper.h (module 'network'): void ns3::AsciiTraceHelperForDevice::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function] cls.add_method('EnableAsciiInternal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3AsciiTraceHelperForIpv4_methods(root_module, cls): ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv4::AsciiTraceHelperForIpv4(ns3::AsciiTraceHelperForIpv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelperForIpv4 const &', 'arg0')]) ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv4::AsciiTraceHelperForIpv4() [constructor] cls.add_constructor([]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, std::string ipv4Name, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('std::string', 'ipv4Name'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ipv4Name, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ipv4Name'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, ns3::Ipv4InterfaceContainer c) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('ns3::Ipv4InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ipv4InterfaceContainer c) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ipv4InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv4', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4All(std::string prefix) [member function] cls.add_method('EnableAsciiIpv4All', 'void', [param('std::string', 'prefix')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4All(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiIpv4All', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv4::EnableAsciiIpv4Internal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv4Internal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3AsciiTraceHelperForIpv6_methods(root_module, cls): ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv6::AsciiTraceHelperForIpv6(ns3::AsciiTraceHelperForIpv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::AsciiTraceHelperForIpv6 const &', 'arg0')]) ## internet-trace-helper.h (module 'internet'): ns3::AsciiTraceHelperForIpv6::AsciiTraceHelperForIpv6() [constructor] cls.add_constructor([]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, std::string ipv6Name, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('std::string', 'ipv6Name'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string ipv6Name, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'ipv6Name'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, ns3::Ipv6InterfaceContainer c) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('ns3::Ipv6InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::Ipv6InterfaceContainer c) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::Ipv6InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, ns3::NodeContainer n) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(std::string prefix, uint32_t nodeid, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6(ns3::Ptr<ns3::OutputStreamWrapper> stream, uint32_t nodeid, uint32_t interface) [member function] cls.add_method('EnableAsciiIpv6', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6All(std::string prefix) [member function] cls.add_method('EnableAsciiIpv6All', 'void', [param('std::string', 'prefix')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6All(ns3::Ptr<ns3::OutputStreamWrapper> stream) [member function] cls.add_method('EnableAsciiIpv6All', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')]) ## internet-trace-helper.h (module 'internet'): void ns3::AsciiTraceHelperForIpv6::EnableAsciiIpv6Internal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv6Internal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3CsmaDeviceRec_methods(root_module, cls): ## csma-channel.h (module 'csma'): ns3::CsmaDeviceRec::CsmaDeviceRec() [constructor] cls.add_constructor([]) ## csma-channel.h (module 'csma'): ns3::CsmaDeviceRec::CsmaDeviceRec(ns3::Ptr<ns3::CsmaNetDevice> device) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')]) ## csma-channel.h (module 'csma'): ns3::CsmaDeviceRec::CsmaDeviceRec(ns3::CsmaDeviceRec const & arg0) [copy constructor] cls.add_constructor([param('ns3::CsmaDeviceRec const &', 'arg0')]) ## csma-channel.h (module 'csma'): bool ns3::CsmaDeviceRec::IsActive() [member function] cls.add_method('IsActive', 'bool', []) ## csma-channel.h (module 'csma'): ns3::CsmaDeviceRec::active [variable] cls.add_instance_attribute('active', 'bool', is_const=False) ## csma-channel.h (module 'csma'): ns3::CsmaDeviceRec::devicePtr [variable] cls.add_instance_attribute('devicePtr', 'ns3::Ptr< ns3::CsmaNetDevice >', is_const=False) return def register_Ns3CsmaStarHelper_methods(root_module, cls): ## csma-star-helper.h (module 'csma-layout'): ns3::CsmaStarHelper::CsmaStarHelper(ns3::CsmaStarHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::CsmaStarHelper const &', 'arg0')]) ## csma-star-helper.h (module 'csma-layout'): ns3::CsmaStarHelper::CsmaStarHelper(uint32_t numSpokes, ns3::CsmaHelper csmaHelper) [constructor] cls.add_constructor([param('uint32_t', 'numSpokes'), param('ns3::CsmaHelper', 'csmaHelper')]) ## csma-star-helper.h (module 'csma-layout'): void ns3::CsmaStarHelper::AssignIpv4Addresses(ns3::Ipv4AddressHelper address) [member function] cls.add_method('AssignIpv4Addresses', 'void', [param('ns3::Ipv4AddressHelper', 'address')]) ## csma-star-helper.h (module 'csma-layout'): void ns3::CsmaStarHelper::AssignIpv6Addresses(ns3::Ipv6Address network, ns3::Ipv6Prefix prefix) [member function] cls.add_method('AssignIpv6Addresses', 'void', [param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'prefix')]) ## csma-star-helper.h (module 'csma-layout'): ns3::Ptr<ns3::Node> ns3::CsmaStarHelper::GetHub() const [member function] cls.add_method('GetHub', 'ns3::Ptr< ns3::Node >', [], is_const=True) ## csma-star-helper.h (module 'csma-layout'): ns3::NetDeviceContainer ns3::CsmaStarHelper::GetHubDevices() const [member function] cls.add_method('GetHubDevices', 'ns3::NetDeviceContainer', [], is_const=True) ## csma-star-helper.h (module 'csma-layout'): ns3::Ipv4Address ns3::CsmaStarHelper::GetHubIpv4Address(uint32_t i) const [member function] cls.add_method('GetHubIpv4Address', 'ns3::Ipv4Address', [param('uint32_t', 'i')], is_const=True) ## csma-star-helper.h (module 'csma-layout'): ns3::Ipv6Address ns3::CsmaStarHelper::GetHubIpv6Address(uint32_t i) const [member function] cls.add_method('GetHubIpv6Address', 'ns3::Ipv6Address', [param('uint32_t', 'i')], is_const=True) ## csma-star-helper.h (module 'csma-layout'): ns3::NetDeviceContainer ns3::CsmaStarHelper::GetSpokeDevices() const [member function] cls.add_method('GetSpokeDevices', 'ns3::NetDeviceContainer', [], is_const=True) ## csma-star-helper.h (module 'csma-layout'): ns3::Ipv4Address ns3::CsmaStarHelper::GetSpokeIpv4Address(uint32_t i) const [member function] cls.add_method('GetSpokeIpv4Address', 'ns3::Ipv4Address', [param('uint32_t', 'i')], is_const=True) ## csma-star-helper.h (module 'csma-layout'): ns3::Ipv6Address ns3::CsmaStarHelper::GetSpokeIpv6Address(uint32_t i) const [member function] cls.add_method('GetSpokeIpv6Address', 'ns3::Ipv6Address', [param('uint32_t', 'i')], is_const=True) ## csma-star-helper.h (module 'csma-layout'): ns3::Ptr<ns3::Node> ns3::CsmaStarHelper::GetSpokeNode(uint32_t i) const [member function] cls.add_method('GetSpokeNode', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## csma-star-helper.h (module 'csma-layout'): void ns3::CsmaStarHelper::InstallStack(ns3::InternetStackHelper stack) [member function] cls.add_method('InstallStack', 'void', [param('ns3::InternetStackHelper', 'stack')]) ## csma-star-helper.h (module 'csma-layout'): uint32_t ns3::CsmaStarHelper::SpokeCount() const [member function] cls.add_method('SpokeCount', 'uint32_t', [], is_const=True) return def register_Ns3DataRate_methods(root_module, cls): cls.add_output_stream_operator() cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('>=') ## data-rate.h (module 'network'): ns3::DataRate::DataRate(ns3::DataRate const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRate const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(uint64_t bps) [constructor] cls.add_constructor([param('uint64_t', 'bps')]) ## data-rate.h (module 'network'): ns3::DataRate::DataRate(std::string rate) [constructor] cls.add_constructor([param('std::string', 'rate')]) ## data-rate.h (module 'network'): double ns3::DataRate::CalculateTxTime(uint32_t bytes) const [member function] cls.add_method('CalculateTxTime', 'double', [param('uint32_t', 'bytes')], is_const=True) ## data-rate.h (module 'network'): uint64_t ns3::DataRate::GetBitRate() const [member function] cls.add_method('GetBitRate', 'uint64_t', [], is_const=True) return def register_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_Ns3IntToType__0_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<0>::IntToType(ns3::IntToType<0> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 0 > const &', 'arg0')]) return def register_Ns3IntToType__1_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<1>::IntToType(ns3::IntToType<1> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 1 > const &', 'arg0')]) return def register_Ns3IntToType__2_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<2>::IntToType(ns3::IntToType<2> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 2 > const &', 'arg0')]) return def register_Ns3IntToType__3_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<3>::IntToType(ns3::IntToType<3> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 3 > const &', 'arg0')]) return def register_Ns3IntToType__4_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<4>::IntToType(ns3::IntToType<4> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 4 > const &', 'arg0')]) return def register_Ns3IntToType__5_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<5>::IntToType(ns3::IntToType<5> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 5 > const &', 'arg0')]) return def register_Ns3IntToType__6_methods(root_module, cls): ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType() [constructor] cls.add_constructor([]) ## int-to-type.h (module 'core'): ns3::IntToType<6>::IntToType(ns3::IntToType<6> const & arg0) [copy constructor] cls.add_constructor([param('ns3::IntToType< 6 > const &', 'arg0')]) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4AddressHelper_methods(root_module, cls): ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper::Ipv4AddressHelper(ns3::Ipv4AddressHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressHelper const &', 'arg0')]) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper::Ipv4AddressHelper() [constructor] cls.add_constructor([]) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4AddressHelper::Ipv4AddressHelper(ns3::Ipv4Address network, ns3::Ipv4Mask mask, ns3::Ipv4Address base="0.0.0.1") [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'network'), param('ns3::Ipv4Mask', 'mask'), param('ns3::Ipv4Address', 'base', default_value='"0.0.0.1"')]) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4InterfaceContainer ns3::Ipv4AddressHelper::Assign(ns3::NetDeviceContainer const & c) [member function] cls.add_method('Assign', 'ns3::Ipv4InterfaceContainer', [param('ns3::NetDeviceContainer const &', 'c')]) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4AddressHelper::NewAddress() [member function] cls.add_method('NewAddress', 'ns3::Ipv4Address', []) ## ipv4-address-helper.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4AddressHelper::NewNetwork() [member function] cls.add_method('NewNetwork', 'ns3::Ipv4Address', []) ## ipv4-address-helper.h (module 'internet'): void ns3::Ipv4AddressHelper::SetBase(ns3::Ipv4Address network, ns3::Ipv4Mask mask, ns3::Ipv4Address base="0.0.0.1") [member function] cls.add_method('SetBase', 'void', [param('ns3::Ipv4Address', 'network'), param('ns3::Ipv4Mask', 'mask'), param('ns3::Ipv4Address', 'base', default_value='"0.0.0.1"')]) return def register_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4InterfaceContainer_methods(root_module, cls): ## ipv4-interface-container.h (module 'internet'): ns3::Ipv4InterfaceContainer::Ipv4InterfaceContainer(ns3::Ipv4InterfaceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceContainer const &', 'arg0')]) ## ipv4-interface-container.h (module 'internet'): ns3::Ipv4InterfaceContainer::Ipv4InterfaceContainer() [constructor] cls.add_constructor([]) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(ns3::Ipv4InterfaceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::Ipv4InterfaceContainer', 'other')]) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface')]) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(std::pair<ns3::Ptr<ns3::Ipv4>,unsigned int> ipInterfacePair) [member function] cls.add_method('Add', 'void', [param('std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int >', 'ipInterfacePair')]) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::Add(std::string ipv4Name, uint32_t interface) [member function] cls.add_method('Add', 'void', [param('std::string', 'ipv4Name'), param('uint32_t', 'interface')]) ## ipv4-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int> > > > ns3::Ipv4InterfaceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > > >', [], is_const=True) ## ipv4-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv4>, unsigned int> > > > ns3::Ipv4InterfaceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int > > >', [], is_const=True) ## ipv4-interface-container.h (module 'internet'): std::pair<ns3::Ptr<ns3::Ipv4>,unsigned int> ns3::Ipv4InterfaceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'std::pair< ns3::Ptr< ns3::Ipv4 >, unsigned int >', [param('uint32_t', 'i')], is_const=True) ## ipv4-interface-container.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceContainer::GetAddress(uint32_t i, uint32_t j=0) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4Address', [param('uint32_t', 'i'), param('uint32_t', 'j', default_value='0')], is_const=True) ## ipv4-interface-container.h (module 'internet'): uint32_t ns3::Ipv4InterfaceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## ipv4-interface-container.h (module 'internet'): void ns3::Ipv4InterfaceContainer::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')]) 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::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::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::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::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_Ns3Ipv6AddressGenerator_methods(root_module, cls): ## ipv6-address-generator.h (module 'internet'): ns3::Ipv6AddressGenerator::Ipv6AddressGenerator() [constructor] cls.add_constructor([]) ## ipv6-address-generator.h (module 'internet'): ns3::Ipv6AddressGenerator::Ipv6AddressGenerator(ns3::Ipv6AddressGenerator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressGenerator const &', 'arg0')]) ## ipv6-address-generator.h (module 'internet'): static bool ns3::Ipv6AddressGenerator::AddAllocated(ns3::Ipv6Address const addr) [member function] cls.add_method('AddAllocated', 'bool', [param('ns3::Ipv6Address const', 'addr')], is_static=True) ## ipv6-address-generator.h (module 'internet'): static ns3::Ipv6Address ns3::Ipv6AddressGenerator::GetAddress(ns3::Ipv6Prefix const prefix) [member function] cls.add_method('GetAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const', 'prefix')], is_static=True) ## ipv6-address-generator.h (module 'internet'): static ns3::Ipv6Address ns3::Ipv6AddressGenerator::GetNetwork(ns3::Ipv6Prefix const prefix) [member function] cls.add_method('GetNetwork', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const', 'prefix')], is_static=True) ## ipv6-address-generator.h (module 'internet'): static void ns3::Ipv6AddressGenerator::Init(ns3::Ipv6Address const net, ns3::Ipv6Prefix const prefix, ns3::Ipv6Address const interfaceId="::1") [member function] cls.add_method('Init', 'void', [param('ns3::Ipv6Address const', 'net'), param('ns3::Ipv6Prefix const', 'prefix'), param('ns3::Ipv6Address const', 'interfaceId', default_value='"::1"')], is_static=True) ## ipv6-address-generator.h (module 'internet'): static void ns3::Ipv6AddressGenerator::InitAddress(ns3::Ipv6Address const interfaceId, ns3::Ipv6Prefix const prefix) [member function] cls.add_method('InitAddress', 'void', [param('ns3::Ipv6Address const', 'interfaceId'), param('ns3::Ipv6Prefix const', 'prefix')], is_static=True) ## ipv6-address-generator.h (module 'internet'): static ns3::Ipv6Address ns3::Ipv6AddressGenerator::NextAddress(ns3::Ipv6Prefix const prefix) [member function] cls.add_method('NextAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const', 'prefix')], is_static=True) ## ipv6-address-generator.h (module 'internet'): static ns3::Ipv6Address ns3::Ipv6AddressGenerator::NextNetwork(ns3::Ipv6Prefix const prefix) [member function] cls.add_method('NextNetwork', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const', 'prefix')], is_static=True) ## ipv6-address-generator.h (module 'internet'): static void ns3::Ipv6AddressGenerator::Reset() [member function] cls.add_method('Reset', 'void', [], is_static=True) ## ipv6-address-generator.h (module 'internet'): static void ns3::Ipv6AddressGenerator::TestMode() [member function] cls.add_method('TestMode', 'void', [], is_static=True) return def register_Ns3Ipv6AddressHelper_methods(root_module, cls): ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6AddressHelper::Ipv6AddressHelper(ns3::Ipv6AddressHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressHelper const &', 'arg0')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6AddressHelper::Ipv6AddressHelper() [constructor] cls.add_constructor([]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6InterfaceContainer ns3::Ipv6AddressHelper::Assign(ns3::NetDeviceContainer const & c) [member function] cls.add_method('Assign', 'ns3::Ipv6InterfaceContainer', [param('ns3::NetDeviceContainer const &', 'c')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6InterfaceContainer ns3::Ipv6AddressHelper::Assign(ns3::NetDeviceContainer const & c, std::vector<bool,std::allocator<bool> > withConfiguration) [member function] cls.add_method('Assign', 'ns3::Ipv6InterfaceContainer', [param('ns3::NetDeviceContainer const &', 'c'), param('std::vector< bool >', 'withConfiguration')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6InterfaceContainer ns3::Ipv6AddressHelper::AssignWithoutAddress(ns3::NetDeviceContainer const & c) [member function] cls.add_method('AssignWithoutAddress', 'ns3::Ipv6InterfaceContainer', [param('ns3::NetDeviceContainer const &', 'c')]) ## ipv6-address-helper.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6AddressHelper::NewAddress(ns3::Address addr) [member function] cls.add_method('NewAddress', 'ns3::Ipv6Address', [param('ns3::Address', 'addr')]) ## ipv6-address-helper.h (module 'internet'): void ns3::Ipv6AddressHelper::NewNetwork(ns3::Ipv6Address network, ns3::Ipv6Prefix prefix) [member function] cls.add_method('NewNetwork', 'void', [param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'prefix')]) return def register_Ns3Ipv6InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6Address address, ns3::Ipv6Prefix prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'prefix')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Ipv6InterfaceAddress(ns3::Ipv6InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv6InterfaceAddress const &', 'o')]) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceAddress::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): uint32_t ns3::Ipv6InterfaceAddress::GetNsDadUid() const [member function] cls.add_method('GetNsDadUid', 'uint32_t', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6Prefix ns3::Ipv6InterfaceAddress::GetPrefix() const [member function] cls.add_method('GetPrefix', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::Scope_e ns3::Ipv6InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv6InterfaceAddress::Scope_e', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): ns3::Ipv6InterfaceAddress::State_e ns3::Ipv6InterfaceAddress::GetState() const [member function] cls.add_method('GetState', 'ns3::Ipv6InterfaceAddress::State_e', [], is_const=True) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetAddress(ns3::Ipv6Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Ipv6Address', 'address')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetNsDadUid(uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('uint32_t', 'uid')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetScope(ns3::Ipv6InterfaceAddress::Scope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv6InterfaceAddress::Scope_e', 'scope')]) ## ipv6-interface-address.h (module 'internet'): void ns3::Ipv6InterfaceAddress::SetState(ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) return def register_Ns3Ipv6InterfaceContainer_methods(root_module, cls): ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6InterfaceContainer::Ipv6InterfaceContainer(ns3::Ipv6InterfaceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6InterfaceContainer const &', 'arg0')]) ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6InterfaceContainer::Ipv6InterfaceContainer() [constructor] cls.add_constructor([]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::Add(ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::Add(ns3::Ipv6InterfaceContainer & c) [member function] cls.add_method('Add', 'void', [param('ns3::Ipv6InterfaceContainer &', 'c')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::Add(std::string ipv6Name, uint32_t interface) [member function] cls.add_method('Add', 'void', [param('std::string', 'ipv6Name'), param('uint32_t', 'interface')]) ## ipv6-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int> > > > ns3::Ipv6InterfaceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv6 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv6 >, unsigned int > > >', [], is_const=True) ## ipv6-interface-container.h (module 'internet'): __gnu_cxx::__normal_iterator<const std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int>*,std::vector<std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int>, std::allocator<std::pair<ns3::Ptr<ns3::Ipv6>, unsigned int> > > > ns3::Ipv6InterfaceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< std::pair< ns3::Ptr< ns3::Ipv6 >, unsigned int > const, std::vector< std::pair< ns3::Ptr< ns3::Ipv6 >, unsigned int > > >', [], is_const=True) ## ipv6-interface-container.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6InterfaceContainer::GetAddress(uint32_t i, uint32_t j) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6Address', [param('uint32_t', 'i'), param('uint32_t', 'j')], is_const=True) ## ipv6-interface-container.h (module 'internet'): uint32_t ns3::Ipv6InterfaceContainer::GetInterfaceIndex(uint32_t i) const [member function] cls.add_method('GetInterfaceIndex', 'uint32_t', [param('uint32_t', 'i')], is_const=True) ## ipv6-interface-container.h (module 'internet'): uint32_t ns3::Ipv6InterfaceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::SetDefaultRoute(uint32_t i, uint32_t router) [member function] cls.add_method('SetDefaultRoute', 'void', [param('uint32_t', 'i'), param('uint32_t', 'router')]) ## ipv6-interface-container.h (module 'internet'): void ns3::Ipv6InterfaceContainer::SetRouter(uint32_t i, bool router) [member function] cls.add_method('SetRouter', 'void', [param('uint32_t', 'i'), param('bool', 'router')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3NetDeviceContainer_methods(root_module, cls): ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'arg0')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer() [constructor] cls.add_constructor([]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::Ptr<ns3::NetDevice> dev) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice >', 'dev')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(std::string devName) [constructor] cls.add_constructor([param('std::string', 'devName')]) ## net-device-container.h (module 'network'): ns3::NetDeviceContainer::NetDeviceContainer(ns3::NetDeviceContainer const & a, ns3::NetDeviceContainer const & b) [constructor] cls.add_constructor([param('ns3::NetDeviceContainer const &', 'a'), param('ns3::NetDeviceContainer const &', 'b')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::NetDeviceContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NetDeviceContainer', 'other')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## net-device-container.h (module 'network'): void ns3::NetDeviceContainer::Add(std::string deviceName) [member function] cls.add_method('Add', 'void', [param('std::string', 'deviceName')]) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::NetDevice>*,std::vector<ns3::Ptr<ns3::NetDevice>, std::allocator<ns3::Ptr<ns3::NetDevice> > > > ns3::NetDeviceContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::NetDevice > const, std::vector< ns3::Ptr< ns3::NetDevice > > >', [], is_const=True) ## net-device-container.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::NetDeviceContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True) ## net-device-container.h (module 'network'): uint32_t ns3::NetDeviceContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PcapFile_methods(root_module, cls): ## pcap-file.h (module 'network'): ns3::PcapFile::PcapFile() [constructor] cls.add_constructor([]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file.h (module 'network'): static bool ns3::PcapFile::Diff(std::string const & f1, std::string const & f2, uint32_t & sec, uint32_t & usec, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT) [member function] cls.add_method('Diff', 'bool', [param('std::string const &', 'f1'), param('std::string const &', 'f2'), param('uint32_t &', 'sec'), param('uint32_t &', 'usec'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT')], is_static=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): bool ns3::PcapFile::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file.h (module 'network'): uint32_t ns3::PcapFile::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file.h (module 'network'): bool ns3::PcapFile::GetSwapMode() [member function] cls.add_method('GetSwapMode', 'bool', []) ## pcap-file.h (module 'network'): int32_t ns3::PcapFile::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file.h (module 'network'): uint16_t ns3::PcapFile::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file.h (module 'network'): void ns3::PcapFile::Init(uint32_t dataLinkType, uint32_t snapLen=ns3::PcapFile::SNAPLEN_DEFAULT, int32_t timeZoneCorrection=ns3::PcapFile::ZONE_DEFAULT, bool swapMode=false) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='ns3::PcapFile::SNAPLEN_DEFAULT'), param('int32_t', 'timeZoneCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT'), param('bool', 'swapMode', default_value='false')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Open(std::string const & filename, std::_Ios_Openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Read(uint8_t * const data, uint32_t maxBytes, uint32_t & tsSec, uint32_t & tsUsec, uint32_t & inclLen, uint32_t & origLen, uint32_t & readLen) [member function] cls.add_method('Read', 'void', [param('uint8_t * const', 'data'), param('uint32_t', 'maxBytes'), param('uint32_t &', 'tsSec'), param('uint32_t &', 'tsUsec'), param('uint32_t &', 'inclLen'), param('uint32_t &', 'origLen'), param('uint32_t &', 'readLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, uint8_t const * const data, uint32_t totalLen) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('uint8_t const * const', 'data'), param('uint32_t', 'totalLen')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): void ns3::PcapFile::Write(uint32_t tsSec, uint32_t tsUsec, ns3::Header & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('uint32_t', 'tsSec'), param('uint32_t', 'tsUsec'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file.h (module 'network'): ns3::PcapFile::SNAPLEN_DEFAULT [variable] cls.add_static_attribute('SNAPLEN_DEFAULT', 'uint32_t const', is_const=True) ## pcap-file.h (module 'network'): ns3::PcapFile::ZONE_DEFAULT [variable] cls.add_static_attribute('ZONE_DEFAULT', 'int32_t const', is_const=True) return def register_Ns3PcapHelper_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper(ns3::PcapHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelper const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelper::PcapHelper() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): ns3::Ptr<ns3::PcapFileWrapper> ns3::PcapHelper::CreateFile(std::string filename, std::_Ios_Openmode filemode, uint32_t dataLinkType, uint32_t snapLen=65535, int32_t tzCorrection=0) [member function] cls.add_method('CreateFile', 'ns3::Ptr< ns3::PcapFileWrapper >', [param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode'), param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='65535'), param('int32_t', 'tzCorrection', default_value='0')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromDevice(std::string prefix, ns3::Ptr<ns3::NetDevice> device, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromDevice', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'useObjectNames', default_value='true')]) ## trace-helper.h (module 'network'): std::string ns3::PcapHelper::GetFilenameFromInterfacePair(std::string prefix, ns3::Ptr<ns3::Object> object, uint32_t interface, bool useObjectNames=true) [member function] cls.add_method('GetFilenameFromInterfacePair', 'std::string', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Object >', 'object'), param('uint32_t', 'interface'), param('bool', 'useObjectNames', default_value='true')]) return def register_Ns3PcapHelperForDevice_methods(root_module, cls): ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice(ns3::PcapHelperForDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelperForDevice const &', 'arg0')]) ## trace-helper.h (module 'network'): ns3::PcapHelperForDevice::PcapHelperForDevice() [constructor] cls.add_constructor([]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, std::string ndName, bool promiscuous=false, bool explicitFilename=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('std::string', 'ndName'), param('bool', 'promiscuous', default_value='false'), param('bool', 'explicitFilename', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NetDeviceContainer d, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NetDeviceContainer', 'd'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, ns3::NodeContainer n, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcap(std::string prefix, uint32_t nodeid, uint32_t deviceid, bool promiscuous=false) [member function] cls.add_method('EnablePcap', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'deviceid'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapAll(std::string prefix, bool promiscuous=false) [member function] cls.add_method('EnablePcapAll', 'void', [param('std::string', 'prefix'), param('bool', 'promiscuous', default_value='false')]) ## trace-helper.h (module 'network'): void ns3::PcapHelperForDevice::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3PcapHelperForIpv4_methods(root_module, cls): ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv4::PcapHelperForIpv4(ns3::PcapHelperForIpv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelperForIpv4 const &', 'arg0')]) ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv4::PcapHelperForIpv4() [constructor] cls.add_constructor([]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, std::string ipv4Name, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('std::string', 'ipv4Name'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, ns3::Ipv4InterfaceContainer c) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('ns3::Ipv4InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4(std::string prefix, uint32_t nodeid, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv4', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4All(std::string prefix) [member function] cls.add_method('EnablePcapIpv4All', 'void', [param('std::string', 'prefix')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv4::EnablePcapIpv4Internal(std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv4Internal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3PcapHelperForIpv6_methods(root_module, cls): ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv6::PcapHelperForIpv6(ns3::PcapHelperForIpv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::PcapHelperForIpv6 const &', 'arg0')]) ## internet-trace-helper.h (module 'internet'): ns3::PcapHelperForIpv6::PcapHelperForIpv6() [constructor] cls.add_constructor([]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, std::string ipv6Name, uint32_t interface, bool explicitFilename=false) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('std::string', 'ipv6Name'), param('uint32_t', 'interface'), param('bool', 'explicitFilename', default_value='false')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, ns3::Ipv6InterfaceContainer c) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('ns3::Ipv6InterfaceContainer', 'c')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, ns3::NodeContainer n) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('ns3::NodeContainer', 'n')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6(std::string prefix, uint32_t nodeid, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv6', 'void', [param('std::string', 'prefix'), param('uint32_t', 'nodeid'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6All(std::string prefix) [member function] cls.add_method('EnablePcapIpv6All', 'void', [param('std::string', 'prefix')]) ## internet-trace-helper.h (module 'internet'): void ns3::PcapHelperForIpv6::EnablePcapIpv6Internal(std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv6Internal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], is_pure_virtual=True, is_virtual=True) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3Timer_methods(root_module, cls): ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Timer const &', 'arg0')]) ## timer.h (module 'core'): ns3::Timer::Timer() [constructor] cls.add_constructor([]) ## timer.h (module 'core'): ns3::Timer::Timer(ns3::Timer::DestroyPolicy destroyPolicy) [constructor] cls.add_constructor([param('ns3::Timer::DestroyPolicy', 'destroyPolicy')]) ## timer.h (module 'core'): void ns3::Timer::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelay() const [member function] cls.add_method('GetDelay', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Time ns3::Timer::GetDelayLeft() const [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [], is_const=True) ## timer.h (module 'core'): ns3::Timer::State ns3::Timer::GetState() const [member function] cls.add_method('GetState', 'ns3::Timer::State', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## timer.h (module 'core'): bool ns3::Timer::IsSuspended() const [member function] cls.add_method('IsSuspended', 'bool', [], is_const=True) ## timer.h (module 'core'): void ns3::Timer::Remove() [member function] cls.add_method('Remove', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Resume() [member function] cls.add_method('Resume', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule() [member function] cls.add_method('Schedule', 'void', []) ## timer.h (module 'core'): void ns3::Timer::Schedule(ns3::Time delay) [member function] cls.add_method('Schedule', 'void', [param('ns3::Time', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::SetDelay(ns3::Time const & delay) [member function] cls.add_method('SetDelay', 'void', [param('ns3::Time const &', 'delay')]) ## timer.h (module 'core'): void ns3::Timer::Suspend() [member function] cls.add_method('Suspend', 'void', []) return def register_Ns3TimerImpl_methods(root_module, cls): ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl() [constructor] cls.add_constructor([]) ## timer-impl.h (module 'core'): ns3::TimerImpl::TimerImpl(ns3::TimerImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimerImpl const &', 'arg0')]) ## timer-impl.h (module 'core'): void ns3::TimerImpl::Invoke() [member function] cls.add_method('Invoke', 'void', [], is_pure_virtual=True, is_virtual=True) ## timer-impl.h (module 'core'): ns3::EventId ns3::TimerImpl::Schedule(ns3::Time const & delay) [member function] cls.add_method('Schedule', 'ns3::EventId', [param('ns3::Time const &', 'delay')], is_pure_virtual=True, is_virtual=True) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): 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::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CsmaHelper_methods(root_module, cls): ## csma-helper.h (module 'csma'): ns3::CsmaHelper::CsmaHelper(ns3::CsmaHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::CsmaHelper const &', 'arg0')]) ## csma-helper.h (module 'csma'): ns3::CsmaHelper::CsmaHelper() [constructor] cls.add_constructor([]) ## csma-helper.h (module 'csma'): ns3::NetDeviceContainer ns3::CsmaHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## csma-helper.h (module 'csma'): ns3::NetDeviceContainer ns3::CsmaHelper::Install(std::string name) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'name')], is_const=True) ## csma-helper.h (module 'csma'): ns3::NetDeviceContainer ns3::CsmaHelper::Install(ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::CsmaChannel> channel) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::CsmaChannel >', 'channel')], is_const=True) ## csma-helper.h (module 'csma'): ns3::NetDeviceContainer ns3::CsmaHelper::Install(ns3::Ptr<ns3::Node> node, std::string channelName) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::Ptr< ns3::Node >', 'node'), param('std::string', 'channelName')], is_const=True) ## csma-helper.h (module 'csma'): ns3::NetDeviceContainer ns3::CsmaHelper::Install(std::string nodeName, ns3::Ptr<ns3::CsmaChannel> channel) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'nodeName'), param('ns3::Ptr< ns3::CsmaChannel >', 'channel')], is_const=True) ## csma-helper.h (module 'csma'): ns3::NetDeviceContainer ns3::CsmaHelper::Install(std::string nodeName, std::string channelName) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('std::string', 'nodeName'), param('std::string', 'channelName')], is_const=True) ## csma-helper.h (module 'csma'): ns3::NetDeviceContainer ns3::CsmaHelper::Install(ns3::NodeContainer const & c) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer const &', 'c')], is_const=True) ## csma-helper.h (module 'csma'): ns3::NetDeviceContainer ns3::CsmaHelper::Install(ns3::NodeContainer const & c, ns3::Ptr<ns3::CsmaChannel> channel) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer const &', 'c'), param('ns3::Ptr< ns3::CsmaChannel >', 'channel')], is_const=True) ## csma-helper.h (module 'csma'): ns3::NetDeviceContainer ns3::CsmaHelper::Install(ns3::NodeContainer const & c, std::string channelName) const [member function] cls.add_method('Install', 'ns3::NetDeviceContainer', [param('ns3::NodeContainer const &', 'c'), param('std::string', 'channelName')], is_const=True) ## csma-helper.h (module 'csma'): void ns3::CsmaHelper::SetChannelAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetChannelAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## csma-helper.h (module 'csma'): void ns3::CsmaHelper::SetDeviceAttribute(std::string n1, ns3::AttributeValue const & v1) [member function] cls.add_method('SetDeviceAttribute', 'void', [param('std::string', 'n1'), param('ns3::AttributeValue const &', 'v1')]) ## csma-helper.h (module 'csma'): void ns3::CsmaHelper::SetQueue(std::string type, std::string n1="", ns3::AttributeValue const & v1=ns3::EmptyAttributeValue(), std::string n2="", ns3::AttributeValue const & v2=ns3::EmptyAttributeValue(), std::string n3="", ns3::AttributeValue const & v3=ns3::EmptyAttributeValue(), std::string n4="", ns3::AttributeValue const & v4=ns3::EmptyAttributeValue()) [member function] cls.add_method('SetQueue', 'void', [param('std::string', 'type'), param('std::string', 'n1', default_value='""'), param('ns3::AttributeValue const &', 'v1', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n2', default_value='""'), param('ns3::AttributeValue const &', 'v2', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n3', default_value='""'), param('ns3::AttributeValue const &', 'v3', default_value='ns3::EmptyAttributeValue()'), param('std::string', 'n4', default_value='""'), param('ns3::AttributeValue const &', 'v4', default_value='ns3::EmptyAttributeValue()')]) ## csma-helper.h (module 'csma'): void ns3::CsmaHelper::EnableAsciiInternal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool explicitFilename) [member function] cls.add_method('EnableAsciiInternal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## csma-helper.h (module 'csma'): void ns3::CsmaHelper::EnablePcapInternal(std::string prefix, ns3::Ptr<ns3::NetDevice> nd, bool promiscuous, bool explicitFilename) [member function] cls.add_method('EnablePcapInternal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::NetDevice >', 'nd'), param('bool', 'promiscuous'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3InternetStackHelper_methods(root_module, cls): ## internet-stack-helper.h (module 'internet'): ns3::InternetStackHelper::InternetStackHelper() [constructor] cls.add_constructor([]) ## internet-stack-helper.h (module 'internet'): ns3::InternetStackHelper::InternetStackHelper(ns3::InternetStackHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::InternetStackHelper const &', 'arg0')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::Install(std::string nodeName) const [member function] cls.add_method('Install', 'void', [param('std::string', 'nodeName')], is_const=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::Install(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Install', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::Install(ns3::NodeContainer c) const [member function] cls.add_method('Install', 'void', [param('ns3::NodeContainer', 'c')], is_const=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::InstallAll() const [member function] cls.add_method('InstallAll', 'void', [], is_const=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::Reset() [member function] cls.add_method('Reset', 'void', []) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetIpv4StackInstall(bool enable) [member function] cls.add_method('SetIpv4StackInstall', 'void', [param('bool', 'enable')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetIpv6StackInstall(bool enable) [member function] cls.add_method('SetIpv6StackInstall', 'void', [param('bool', 'enable')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetRoutingHelper(ns3::Ipv4RoutingHelper const & routing) [member function] cls.add_method('SetRoutingHelper', 'void', [param('ns3::Ipv4RoutingHelper const &', 'routing')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetRoutingHelper(ns3::Ipv6RoutingHelper const & routing) [member function] cls.add_method('SetRoutingHelper', 'void', [param('ns3::Ipv6RoutingHelper const &', 'routing')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetTcp(std::string tid) [member function] cls.add_method('SetTcp', 'void', [param('std::string', 'tid')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::SetTcp(std::string tid, std::string attr, ns3::AttributeValue const & val) [member function] cls.add_method('SetTcp', 'void', [param('std::string', 'tid'), param('std::string', 'attr'), param('ns3::AttributeValue const &', 'val')]) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::EnableAsciiIpv4Internal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv4Internal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::EnableAsciiIpv6Internal(ns3::Ptr<ns3::OutputStreamWrapper> stream, std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnableAsciiIpv6Internal', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream'), param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::EnablePcapIpv4Internal(std::string prefix, ns3::Ptr<ns3::Ipv4> ipv4, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv4Internal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv4 >', 'ipv4'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) ## internet-stack-helper.h (module 'internet'): void ns3::InternetStackHelper::EnablePcapIpv6Internal(std::string prefix, ns3::Ptr<ns3::Ipv6> ipv6, uint32_t interface, bool explicitFilename) [member function] cls.add_method('EnablePcapIpv6Internal', 'void', [param('std::string', 'prefix'), param('ns3::Ptr< ns3::Ipv6 >', 'ipv6'), param('uint32_t', 'interface'), param('bool', 'explicitFilename')], visibility='private', is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Ipv6Header_methods(root_module, cls): ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header(ns3::Ipv6Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Header const &', 'arg0')]) ## ipv6-header.h (module 'internet'): ns3::Ipv6Header::Ipv6Header() [constructor] cls.add_constructor([]) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetDestinationAddress() const [member function] cls.add_method('GetDestinationAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetFlowLabel() const [member function] cls.add_method('GetFlowLabel', 'uint32_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): ns3::TypeId ns3::Ipv6Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetNextHeader() const [member function] cls.add_method('GetNextHeader', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint16_t ns3::Ipv6Header::GetPayloadLength() const [member function] cls.add_method('GetPayloadLength', 'uint16_t', [], is_const=True) ## ipv6-header.h (module 'internet'): uint32_t ns3::Ipv6Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): ns3::Ipv6Address ns3::Ipv6Header::GetSourceAddress() const [member function] cls.add_method('GetSourceAddress', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-header.h (module 'internet'): uint8_t ns3::Ipv6Header::GetTrafficClass() const [member function] cls.add_method('GetTrafficClass', 'uint8_t', [], is_const=True) ## ipv6-header.h (module 'internet'): static ns3::TypeId ns3::Ipv6Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetDestinationAddress(ns3::Ipv6Address dst) [member function] cls.add_method('SetDestinationAddress', 'void', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetFlowLabel(uint32_t flow) [member function] cls.add_method('SetFlowLabel', 'void', [param('uint32_t', 'flow')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetHopLimit(uint8_t limit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'limit')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetNextHeader(uint8_t next) [member function] cls.add_method('SetNextHeader', 'void', [param('uint8_t', 'next')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetPayloadLength(uint16_t len) [member function] cls.add_method('SetPayloadLength', 'void', [param('uint16_t', 'len')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetSourceAddress(ns3::Ipv6Address src) [member function] cls.add_method('SetSourceAddress', 'void', [param('ns3::Ipv6Address', 'src')]) ## ipv6-header.h (module 'internet'): void ns3::Ipv6Header::SetTrafficClass(uint8_t traffic) [member function] cls.add_method('SetTrafficClass', 'void', [param('uint8_t', 'traffic')]) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Start() [member function] cls.add_method('Start', '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::DoStart() [member function] cls.add_method('DoStart', '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_Ns3PcapFileWrapper_methods(root_module, cls): ## pcap-file-wrapper.h (module 'network'): static ns3::TypeId ns3::PcapFileWrapper::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## pcap-file-wrapper.h (module 'network'): ns3::PcapFileWrapper::PcapFileWrapper() [constructor] cls.add_constructor([]) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Fail() const [member function] cls.add_method('Fail', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): bool ns3::PcapFileWrapper::Eof() const [member function] cls.add_method('Eof', 'bool', [], is_const=True) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Clear() [member function] cls.add_method('Clear', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Open(std::string const & filename, std::_Ios_Openmode mode) [member function] cls.add_method('Open', 'void', [param('std::string const &', 'filename'), param('std::_Ios_Openmode', 'mode')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Close() [member function] cls.add_method('Close', 'void', []) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Init(uint32_t dataLinkType, uint32_t snapLen=std::numeric_limits<unsigned int>::max(), int32_t tzCorrection=ns3::PcapFile::ZONE_DEFAULT) [member function] cls.add_method('Init', 'void', [param('uint32_t', 'dataLinkType'), param('uint32_t', 'snapLen', default_value='std::numeric_limits<unsigned int>::max()'), param('int32_t', 'tzCorrection', default_value='ns3::PcapFile::ZONE_DEFAULT')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, ns3::Header & header, ns3::Ptr<const ns3::Packet> p) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('ns3::Header &', 'header'), param('ns3::Ptr< ns3::Packet const >', 'p')]) ## pcap-file-wrapper.h (module 'network'): void ns3::PcapFileWrapper::Write(ns3::Time t, uint8_t const * buffer, uint32_t length) [member function] cls.add_method('Write', 'void', [param('ns3::Time', 't'), param('uint8_t const *', 'buffer'), param('uint32_t', 'length')]) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetMagic() [member function] cls.add_method('GetMagic', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMajor() [member function] cls.add_method('GetVersionMajor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): uint16_t ns3::PcapFileWrapper::GetVersionMinor() [member function] cls.add_method('GetVersionMinor', 'uint16_t', []) ## pcap-file-wrapper.h (module 'network'): int32_t ns3::PcapFileWrapper::GetTimeZoneOffset() [member function] cls.add_method('GetTimeZoneOffset', 'int32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSigFigs() [member function] cls.add_method('GetSigFigs', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetSnapLen() [member function] cls.add_method('GetSnapLen', 'uint32_t', []) ## pcap-file-wrapper.h (module 'network'): uint32_t ns3::PcapFileWrapper::GetDataLinkType() [member function] cls.add_method('GetDataLinkType', 'uint32_t', []) return def register_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__Ns3Ipv4MulticastRoute_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4MulticastRoute__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4MulticastRoute > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4MulticastRoute, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4MulticastRoute> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Ipv4Route_Ns3Empty_Ns3DefaultDeleter__lt__ns3Ipv4Route__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter< ns3::Ipv4Route > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Ipv4Route, ns3::empty, ns3::DefaultDeleter<ns3::Ipv4Route> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3OutputStreamWrapper_Ns3Empty_Ns3DefaultDeleter__lt__ns3OutputStreamWrapper__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::SimpleRefCount(ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter< ns3::OutputStreamWrapper > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::OutputStreamWrapper, ns3::empty, ns3::DefaultDeleter<ns3::OutputStreamWrapper> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Socket_methods(root_module, cls): ## socket.h (module 'network'): ns3::Socket::Socket(ns3::Socket const & arg0) [copy constructor] cls.add_constructor([param('ns3::Socket const &', 'arg0')]) ## socket.h (module 'network'): ns3::Socket::Socket() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): int ns3::Socket::Bind(ns3::Address const & address) [member function] cls.add_method('Bind', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind() [member function] cls.add_method('Bind', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Bind6() [member function] cls.add_method('Bind6', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::BindToNetDevice(ns3::Ptr<ns3::NetDevice> netdevice) [member function] cls.add_method('BindToNetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'netdevice')], is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Close() [member function] cls.add_method('Close', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Connect(ns3::Address const & address) [member function] cls.add_method('Connect', 'int', [param('ns3::Address const &', 'address')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): static ns3::Ptr<ns3::Socket> ns3::Socket::CreateSocket(ns3::Ptr<ns3::Node> node, ns3::TypeId tid) [member function] cls.add_method('CreateSocket', 'ns3::Ptr< ns3::Socket >', [param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::TypeId', 'tid')], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::GetAllowBroadcast() const [member function] cls.add_method('GetAllowBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Socket::GetBoundNetDevice() [member function] cls.add_method('GetBoundNetDevice', 'ns3::Ptr< ns3::NetDevice >', []) ## socket.h (module 'network'): ns3::Socket::SocketErrno ns3::Socket::GetErrno() const [member function] cls.add_method('GetErrno', 'ns3::Socket::SocketErrno', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetRxAvailable() const [member function] cls.add_method('GetRxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::GetSockName(ns3::Address & address) const [member function] cls.add_method('GetSockName', 'int', [param('ns3::Address &', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): ns3::Socket::SocketType ns3::Socket::GetSocketType() const [member function] cls.add_method('GetSocketType', 'ns3::Socket::SocketType', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::Socket::GetTxAvailable() const [member function] cls.add_method('GetTxAvailable', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::Socket::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_Ns3SocketAddressTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag(ns3::SocketAddressTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketAddressTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketAddressTag::SocketAddressTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketAddressTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::Address ns3::SocketAddressTag::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketAddressTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketAddressTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketAddressTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketAddressTag::SetAddress(ns3::Address addr) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'addr')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::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 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'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3Channel_methods(root_module, cls): ## channel.h (module 'network'): ns3::Channel::Channel(ns3::Channel const & arg0) [copy constructor] cls.add_constructor([param('ns3::Channel const &', 'arg0')]) ## channel.h (module 'network'): ns3::Channel::Channel() [constructor] cls.add_constructor([]) ## channel.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Channel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## channel.h (module 'network'): uint32_t ns3::Channel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## channel.h (module 'network'): static ns3::TypeId ns3::Channel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return def register_Ns3CsmaChannel_methods(root_module, cls): ## csma-channel.h (module 'csma'): static ns3::TypeId ns3::CsmaChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## csma-channel.h (module 'csma'): ns3::CsmaChannel::CsmaChannel() [constructor] cls.add_constructor([]) ## csma-channel.h (module 'csma'): int32_t ns3::CsmaChannel::Attach(ns3::Ptr<ns3::CsmaNetDevice> device) [member function] cls.add_method('Attach', 'int32_t', [param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')]) ## csma-channel.h (module 'csma'): bool ns3::CsmaChannel::Detach(ns3::Ptr<ns3::CsmaNetDevice> device) [member function] cls.add_method('Detach', 'bool', [param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')]) ## csma-channel.h (module 'csma'): bool ns3::CsmaChannel::Detach(uint32_t deviceId) [member function] cls.add_method('Detach', 'bool', [param('uint32_t', 'deviceId')]) ## csma-channel.h (module 'csma'): bool ns3::CsmaChannel::Reattach(uint32_t deviceId) [member function] cls.add_method('Reattach', 'bool', [param('uint32_t', 'deviceId')]) ## csma-channel.h (module 'csma'): bool ns3::CsmaChannel::Reattach(ns3::Ptr<ns3::CsmaNetDevice> device) [member function] cls.add_method('Reattach', 'bool', [param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')]) ## csma-channel.h (module 'csma'): bool ns3::CsmaChannel::TransmitStart(ns3::Ptr<ns3::Packet> p, uint32_t srcId) [member function] cls.add_method('TransmitStart', 'bool', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'srcId')]) ## csma-channel.h (module 'csma'): bool ns3::CsmaChannel::TransmitEnd() [member function] cls.add_method('TransmitEnd', 'bool', []) ## csma-channel.h (module 'csma'): void ns3::CsmaChannel::PropagationCompleteEvent() [member function] cls.add_method('PropagationCompleteEvent', 'void', []) ## csma-channel.h (module 'csma'): int32_t ns3::CsmaChannel::GetDeviceNum(ns3::Ptr<ns3::CsmaNetDevice> device) [member function] cls.add_method('GetDeviceNum', 'int32_t', [param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')]) ## csma-channel.h (module 'csma'): ns3::WireState ns3::CsmaChannel::GetState() [member function] cls.add_method('GetState', 'ns3::WireState', []) ## csma-channel.h (module 'csma'): bool ns3::CsmaChannel::IsBusy() [member function] cls.add_method('IsBusy', 'bool', []) ## csma-channel.h (module 'csma'): bool ns3::CsmaChannel::IsActive(uint32_t deviceId) [member function] cls.add_method('IsActive', 'bool', [param('uint32_t', 'deviceId')]) ## csma-channel.h (module 'csma'): uint32_t ns3::CsmaChannel::GetNumActDevices() [member function] cls.add_method('GetNumActDevices', 'uint32_t', []) ## csma-channel.h (module 'csma'): uint32_t ns3::CsmaChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## csma-channel.h (module 'csma'): ns3::Ptr<ns3::NetDevice> ns3::CsmaChannel::GetDevice(uint32_t i) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## csma-channel.h (module 'csma'): ns3::Ptr<ns3::CsmaNetDevice> ns3::CsmaChannel::GetCsmaDevice(uint32_t i) const [member function] cls.add_method('GetCsmaDevice', 'ns3::Ptr< ns3::CsmaNetDevice >', [param('uint32_t', 'i')], is_const=True) ## csma-channel.h (module 'csma'): ns3::DataRate ns3::CsmaChannel::GetDataRate() [member function] cls.add_method('GetDataRate', 'ns3::DataRate', []) ## csma-channel.h (module 'csma'): ns3::Time ns3::CsmaChannel::GetDelay() [member function] cls.add_method('GetDelay', 'ns3::Time', []) return def register_Ns3DataRateChecker_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateChecker::DataRateChecker(ns3::DataRateChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateChecker const &', 'arg0')]) return def register_Ns3DataRateValue_methods(root_module, cls): ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue() [constructor] cls.add_constructor([]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRateValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::DataRateValue const &', 'arg0')]) ## data-rate.h (module 'network'): ns3::DataRateValue::DataRateValue(ns3::DataRate const & value) [constructor] cls.add_constructor([param('ns3::DataRate const &', 'value')]) ## data-rate.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::DataRateValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## data-rate.h (module 'network'): bool ns3::DataRateValue::DeserializeFromString(std::string value, ns3::Ptr<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) ## data-rate.h (module 'network'): ns3::DataRate ns3::DataRateValue::Get() const [member function] cls.add_method('Get', 'ns3::DataRate', [], is_const=True) ## data-rate.h (module 'network'): std::string ns3::DataRateValue::SerializeToString(ns3::Ptr<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) ## data-rate.h (module 'network'): void ns3::DataRateValue::Set(ns3::DataRate const & value) [member function] cls.add_method('Set', 'void', [param('ns3::DataRate const &', 'value')]) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3IpL4Protocol_methods(root_module, cls): ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol() [constructor] cls.add_constructor([]) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::IpL4Protocol(ns3::IpL4Protocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::IpL4Protocol const &', 'arg0')]) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget() const [member function] cls.add_method('GetDownTarget', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::IpL4Protocol::GetDownTarget6() const [member function] cls.add_method('GetDownTarget6', 'ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): int ns3::IpL4Protocol::GetProtocolNumber() const [member function] cls.add_method('GetProtocolNumber', 'int', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): static ns3::TypeId ns3::IpL4Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::Ipv4Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::Ipv4Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): ns3::IpL4Protocol::RxStatus ns3::IpL4Protocol::Receive(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address & src, ns3::Ipv6Address & dst, ns3::Ptr<ns3::Ipv6Interface> incomingInterface) [member function] cls.add_method('Receive', 'ns3::IpL4Protocol::RxStatus', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address &', 'src'), param('ns3::Ipv6Address &', 'dst'), param('ns3::Ptr< ns3::Ipv6Interface >', 'incomingInterface')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv4Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv4Address payloadSource, ns3::Ipv4Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv4Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv4Address', 'payloadSource'), param('ns3::Ipv4Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::ReceiveIcmp(ns3::Ipv6Address icmpSource, uint8_t icmpTtl, uint8_t icmpType, uint8_t icmpCode, uint32_t icmpInfo, ns3::Ipv6Address payloadSource, ns3::Ipv6Address payloadDestination, uint8_t const * payload) [member function] cls.add_method('ReceiveIcmp', 'void', [param('ns3::Ipv6Address', 'icmpSource'), param('uint8_t', 'icmpTtl'), param('uint8_t', 'icmpType'), param('uint8_t', 'icmpCode'), param('uint32_t', 'icmpInfo'), param('ns3::Ipv6Address', 'payloadSource'), param('ns3::Ipv6Address', 'payloadDestination'), param('uint8_t const *', 'payload')], is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv4Address,ns3::Ipv4Address,unsigned char,ns3::Ptr<ns3::Ipv4Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv4Address, ns3::Ipv4Address, unsigned char, ns3::Ptr< ns3::Ipv4Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## ip-l4-protocol.h (module 'internet'): void ns3::IpL4Protocol::SetDownTarget6(ns3::Callback<void,ns3::Ptr<ns3::Packet>,ns3::Ipv6Address,ns3::Ipv6Address,unsigned char,ns3::Ptr<ns3::Ipv6Route>,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetDownTarget6', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Packet >, ns3::Ipv6Address, ns3::Ipv6Address, unsigned char, ns3::Ptr< ns3::Ipv6Route >, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): static ns3::TypeId ns3::Ipv4::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsForwarding(uint32_t interface) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::IsUp(uint32_t interface) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): bool ns3::Ipv4::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4L3Protocol_methods(root_module, cls): ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::Ipv4L3Protocol() [constructor] cls.add_constructor([]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::AddAddress(uint32_t i, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', []) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')]) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Interface> ns3::Ipv4L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv4Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForAddress(ns3::Ipv4Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'addr')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): int32_t ns3::Ipv4L3Protocol::GetInterfaceForPrefix(ns3::Ipv4Address addr, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'addr'), param('ns3::Ipv4Mask', 'mask')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv4L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv4L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsDestinationAddress(ns3::Ipv4Address address, uint32_t iif) const [member function] cls.add_method('IsDestinationAddress', 'bool', [param('ns3::Ipv4Address', 'address'), param('uint32_t', 'iif')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')]) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4L3Protocol::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): ns3::Ipv4L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): bool ns3::Ipv4L3Protocol::GetWeakEsModel() const [member function] cls.add_method('GetWeakEsModel', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv4-l3-protocol.h (module 'internet'): void ns3::Ipv4L3Protocol::SetWeakEsModel(bool model) [member function] cls.add_method('SetWeakEsModel', 'void', [param('bool', 'model')], visibility='private', is_virtual=True) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv4MulticastRoute_methods(root_module, cls): ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute(ns3::Ipv4MulticastRoute const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MulticastRoute const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::Ipv4MulticastRoute() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetGroup() const [member function] cls.add_method('GetGroup', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4MulticastRoute::GetOrigin() const [member function] cls.add_method('GetOrigin', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetOutputTtl(uint32_t oif) [member function] cls.add_method('GetOutputTtl', 'uint32_t', [param('uint32_t', 'oif')], deprecated=True) ## ipv4-route.h (module 'internet'): std::map<unsigned int, unsigned int, std::less<unsigned int>, std::allocator<std::pair<unsigned int const, unsigned int> > > ns3::Ipv4MulticastRoute::GetOutputTtlMap() const [member function] cls.add_method('GetOutputTtlMap', 'std::map< unsigned int, unsigned int >', [], is_const=True) ## ipv4-route.h (module 'internet'): uint32_t ns3::Ipv4MulticastRoute::GetParent() const [member function] cls.add_method('GetParent', 'uint32_t', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetGroup(ns3::Ipv4Address const group) [member function] cls.add_method('SetGroup', 'void', [param('ns3::Ipv4Address const', 'group')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOrigin(ns3::Ipv4Address const origin) [member function] cls.add_method('SetOrigin', 'void', [param('ns3::Ipv4Address const', 'origin')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetOutputTtl(uint32_t oif, uint32_t ttl) [member function] cls.add_method('SetOutputTtl', 'void', [param('uint32_t', 'oif'), param('uint32_t', 'ttl')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4MulticastRoute::SetParent(uint32_t iif) [member function] cls.add_method('SetParent', 'void', [param('uint32_t', 'iif')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_INTERFACES [variable] cls.add_static_attribute('MAX_INTERFACES', 'uint32_t const', is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4MulticastRoute::MAX_TTL [variable] cls.add_static_attribute('MAX_TTL', 'uint32_t const', is_const=True) return def register_Ns3Ipv4Route_methods(root_module, cls): cls.add_output_stream_operator() ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route(ns3::Ipv4Route const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Route const &', 'arg0')]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Route::Ipv4Route() [constructor] cls.add_constructor([]) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetGateway() const [member function] cls.add_method('GetGateway', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4Route::GetOutputDevice() const [member function] cls.add_method('GetOutputDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True) ## ipv4-route.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Route::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetDestination(ns3::Ipv4Address dest) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'dest')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetGateway(ns3::Ipv4Address gw) [member function] cls.add_method('SetGateway', 'void', [param('ns3::Ipv4Address', 'gw')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetOutputDevice(ns3::Ptr<ns3::NetDevice> outputDevice) [member function] cls.add_method('SetOutputDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'outputDevice')]) ## ipv4-route.h (module 'internet'): void ns3::Ipv4Route::SetSource(ns3::Ipv4Address src) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'src')]) return def register_Ns3Ipv4RoutingProtocol_methods(root_module, cls): ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol() [constructor] cls.add_constructor([]) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ipv4RoutingProtocol::Ipv4RoutingProtocol(ns3::Ipv4RoutingProtocol const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingProtocol const &', 'arg0')]) ## ipv4-routing-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv4RoutingProtocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): bool ns3::Ipv4RoutingProtocol::RouteInput(ns3::Ptr<const ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<const ns3::NetDevice> idev, ns3::Callback<void,ns3::Ptr<ns3::Ipv4Route>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ucb, ns3::Callback<void,ns3::Ptr<ns3::Ipv4MulticastRoute>,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> mcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,unsigned int,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> lcb, ns3::Callback<void,ns3::Ptr<const ns3::Packet>,const ns3::Ipv4Header&,ns3::Socket::SocketErrno,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ecb) [member function] cls.add_method('RouteInput', 'bool', [param('ns3::Ptr< ns3::Packet const >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice const >', 'idev'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4Route >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ucb'), param('ns3::Callback< void, ns3::Ptr< ns3::Ipv4MulticastRoute >, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'mcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'lcb'), param('ns3::Callback< void, ns3::Ptr< ns3::Packet const >, ns3::Ipv4Header const &, ns3::Socket::SocketErrno, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'ecb')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4RoutingProtocol::RouteOutput(ns3::Ptr<ns3::Packet> p, ns3::Ipv4Header const & header, ns3::Ptr<ns3::NetDevice> oif, ns3::Socket::SocketErrno & sockerr) [member function] cls.add_method('RouteOutput', 'ns3::Ptr< ns3::Ipv4Route >', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv4Header const &', 'header'), param('ns3::Ptr< ns3::NetDevice >', 'oif'), param('ns3::Socket::SocketErrno &', 'sockerr')], is_pure_virtual=True, is_virtual=True) ## ipv4-routing-protocol.h (module 'internet'): void ns3::Ipv4RoutingProtocol::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_pure_virtual=True, is_virtual=True) return def register_Ns3Ipv6_methods(root_module, cls): ## ipv6.h (module 'internet'): ns3::Ipv6::Ipv6(ns3::Ipv6 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6 const &', 'arg0')]) ## ipv6.h (module 'internet'): ns3::Ipv6::Ipv6() [constructor] cls.add_constructor([]) ## ipv6.h (module 'internet'): bool ns3::Ipv6::AddAddress(uint32_t interface, ns3::Ipv6InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv6InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): uint32_t ns3::Ipv6::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): int32_t ns3::Ipv6::GetInterfaceForAddress(ns3::Ipv6Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv6Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): int32_t ns3::Ipv6::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): int32_t ns3::Ipv6::GetInterfaceForPrefix(ns3::Ipv6Address address, ns3::Ipv6Prefix mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6Prefix', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): uint16_t ns3::Ipv6::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): uint16_t ns3::Ipv6::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): uint32_t ns3::Ipv6::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): uint32_t ns3::Ipv6::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ptr<ns3::Ipv6RoutingProtocol> ns3::Ipv6::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv6RoutingProtocol >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): static ns3::TypeId ns3::Ipv6::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::IsForwarding(uint32_t interface) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::IsUp(uint32_t interface) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::RegisterExtensions() [member function] cls.add_method('RegisterExtensions', 'void', [], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::RegisterOptions() [member function] cls.add_method('RegisterOptions', 'void', [], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::RemoveAddress(uint32_t interface, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetRoutingProtocol(ns3::Ptr<ns3::Ipv6RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv6RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv6.h (module 'internet'): ns3::Ipv6::IF_ANY [variable] cls.add_static_attribute('IF_ANY', 'uint32_t const', is_const=True) ## ipv6.h (module 'internet'): bool ns3::Ipv6::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## ipv6.h (module 'internet'): void ns3::Ipv6::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6Interface_methods(root_module, cls): ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface(ns3::Ipv6Interface const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6Interface const &', 'arg0')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6Interface::Ipv6Interface() [constructor] cls.add_constructor([]) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::AddAddress(ns3::Ipv6InterfaceAddress iface) [member function] cls.add_method('AddAddress', 'bool', [param('ns3::Ipv6InterfaceAddress', 'iface')]) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddress(uint32_t index) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetAddressMatchingDestination(ns3::Ipv6Address dst) [member function] cls.add_method('GetAddressMatchingDestination', 'ns3::Ipv6InterfaceAddress', [param('ns3::Ipv6Address', 'dst')]) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetBaseReachableTime() const [member function] cls.add_method('GetBaseReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint8_t ns3::Ipv6Interface::GetCurHopLimit() const [member function] cls.add_method('GetCurHopLimit', 'uint8_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6Interface::GetDevice() const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [], is_const=True, is_virtual=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::GetLinkLocalAddress() const [member function] cls.add_method('GetLinkLocalAddress', 'ns3::Ipv6InterfaceAddress', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetMetric() const [member function] cls.add_method('GetMetric', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint32_t ns3::Ipv6Interface::GetNAddresses() const [member function] cls.add_method('GetNAddresses', 'uint32_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetReachableTime() const [member function] cls.add_method('GetReachableTime', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): uint16_t ns3::Ipv6Interface::GetRetransTimer() const [member function] cls.add_method('GetRetransTimer', 'uint16_t', [], is_const=True) ## ipv6-interface.h (module 'internet'): static ns3::TypeId ns3::Ipv6Interface::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsDown() const [member function] cls.add_method('IsDown', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsForwarding() const [member function] cls.add_method('IsForwarding', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): bool ns3::Ipv6Interface::IsUp() const [member function] cls.add_method('IsUp', 'bool', [], is_const=True) ## ipv6-interface.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6Interface::RemoveAddress(uint32_t index) [member function] cls.add_method('RemoveAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'index')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::Send(ns3::Ptr<ns3::Packet> p, ns3::Ipv6Address dest) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'p'), param('ns3::Ipv6Address', 'dest')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetBaseReachableTime(uint16_t baseReachableTime) [member function] cls.add_method('SetBaseReachableTime', 'void', [param('uint16_t', 'baseReachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetCurHopLimit(uint8_t curHopLimit) [member function] cls.add_method('SetCurHopLimit', 'void', [param('uint8_t', 'curHopLimit')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('SetDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetDown() [member function] cls.add_method('SetDown', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetForwarding(bool forward) [member function] cls.add_method('SetForwarding', 'void', [param('bool', 'forward')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetMetric(uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint16_t', 'metric')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetNsDadUid(ns3::Ipv6Address address, uint32_t uid) [member function] cls.add_method('SetNsDadUid', 'void', [param('ns3::Ipv6Address', 'address'), param('uint32_t', 'uid')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetReachableTime(uint16_t reachableTime) [member function] cls.add_method('SetReachableTime', 'void', [param('uint16_t', 'reachableTime')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetRetransTimer(uint16_t retransTimer) [member function] cls.add_method('SetRetransTimer', 'void', [param('uint16_t', 'retransTimer')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetState(ns3::Ipv6Address address, ns3::Ipv6InterfaceAddress::State_e state) [member function] cls.add_method('SetState', 'void', [param('ns3::Ipv6Address', 'address'), param('ns3::Ipv6InterfaceAddress::State_e', 'state')]) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::SetUp() [member function] cls.add_method('SetUp', 'void', []) ## ipv6-interface.h (module 'internet'): void ns3::Ipv6Interface::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv6L3Protocol_methods(root_module, cls): ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol::PROT_NUMBER [variable] cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) ## ipv6-l3-protocol.h (module 'internet'): static ns3::TypeId ns3::Ipv6L3Protocol::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6L3Protocol::Ipv6L3Protocol() [constructor] cls.add_constructor([]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Insert(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Insert', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Remove(ns3::Ptr<ns3::IpL4Protocol> protocol) [member function] cls.add_method('Remove', 'void', [param('ns3::Ptr< ns3::IpL4Protocol >', 'protocol')]) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv6L3Protocol::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_const=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv6L3Protocol::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', []) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetDefaultTtl(uint8_t ttl) [member function] cls.add_method('SetDefaultTtl', 'void', [param('uint8_t', 'ttl')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Receive(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> p, uint16_t protocol, ns3::Address const & from, ns3::Address const & to, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('Receive', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'p'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'from'), param('ns3::Address const &', 'to'), param('ns3::NetDevice::PacketType', 'packetType')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv6Address source, ns3::Ipv6Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv6Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv6Address', 'source'), param('ns3::Ipv6Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv6Route >', 'route')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetRoutingProtocol(ns3::Ptr<ns3::Ipv6RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv6RoutingProtocol >', 'routingProtocol')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv6RoutingProtocol> ns3::Ipv6L3Protocol::GetRoutingProtocol() const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv6RoutingProtocol >', [], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv6L3Protocol::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Ipv6Interface> ns3::Ipv6L3Protocol::GetInterface(uint32_t i) const [member function] cls.add_method('GetInterface', 'ns3::Ptr< ns3::Ipv6Interface >', [param('uint32_t', 'i')], is_const=True) ## ipv6-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv6L3Protocol::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): int32_t ns3::Ipv6L3Protocol::GetInterfaceForAddress(ns3::Ipv6Address addr) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): int32_t ns3::Ipv6L3Protocol::GetInterfaceForPrefix(ns3::Ipv6Address addr, ns3::Ipv6Prefix mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv6Address', 'addr'), param('ns3::Ipv6Prefix', 'mask')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): int32_t ns3::Ipv6L3Protocol::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::AddAddress(uint32_t i, ns3::Ipv6InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'i'), param('ns3::Ipv6InterfaceAddress', 'address')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ipv6InterfaceAddress ns3::Ipv6L3Protocol::GetAddress(uint32_t interfaceIndex, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv6InterfaceAddress', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint32_t ns3::Ipv6L3Protocol::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::RemoveAddress(uint32_t interfaceIndex, uint32_t addressIndex) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interfaceIndex'), param('uint32_t', 'addressIndex')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetMetric(uint32_t i, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'i'), param('uint16_t', 'metric')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv6L3Protocol::GetMetric(uint32_t i) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): uint16_t ns3::Ipv6L3Protocol::GetMtu(uint32_t i) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::IsUp(uint32_t i) const [member function] cls.add_method('IsUp', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetUp(uint32_t i) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetDown(uint32_t i) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'i')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::IsForwarding(uint32_t i) const [member function] cls.add_method('IsForwarding', 'bool', [param('uint32_t', 'i')], is_const=True, is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetForwarding(uint32_t i, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'i'), param('bool', 'val')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv6L3Protocol::GetNetDevice(uint32_t i) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'i')], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): ns3::Ptr<ns3::Icmpv6L4Protocol> ns3::Ipv6L3Protocol::GetIcmpv6() const [member function] cls.add_method('GetIcmpv6', 'ns3::Ptr< ns3::Icmpv6L4Protocol >', [], is_const=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::AddAutoconfiguredAddress(uint32_t interface, ns3::Ipv6Address network, ns3::Ipv6Prefix mask, uint8_t flags, uint32_t validTime, uint32_t preferredTime, ns3::Ipv6Address defaultRouter=ns3::Ipv6Address::GetZero( )) [member function] cls.add_method('AddAutoconfiguredAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'mask'), param('uint8_t', 'flags'), param('uint32_t', 'validTime'), param('uint32_t', 'preferredTime'), param('ns3::Ipv6Address', 'defaultRouter', default_value='ns3::Ipv6Address::GetZero( )')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RemoveAutoconfiguredAddress(uint32_t interface, ns3::Ipv6Address network, ns3::Ipv6Prefix mask, ns3::Ipv6Address defaultRouter) [member function] cls.add_method('RemoveAutoconfiguredAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv6Address', 'network'), param('ns3::Ipv6Prefix', 'mask'), param('ns3::Ipv6Address', 'defaultRouter')]) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RegisterExtensions() [member function] cls.add_method('RegisterExtensions', 'void', [], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::RegisterOptions() [member function] cls.add_method('RegisterOptions', 'void', [], is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetIpForward(bool forward) [member function] cls.add_method('SetIpForward', 'void', [param('bool', 'forward')], visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::GetIpForward() const [member function] cls.add_method('GetIpForward', 'bool', [], is_const=True, visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): void ns3::Ipv6L3Protocol::SetSendIcmpv6Redirect(bool sendIcmpv6Redirect) [member function] cls.add_method('SetSendIcmpv6Redirect', 'void', [param('bool', 'sendIcmpv6Redirect')], visibility='private', is_virtual=True) ## ipv6-l3-protocol.h (module 'internet'): bool ns3::Ipv6L3Protocol::GetSendIcmpv6Redirect() const [member function] cls.add_method('GetSendIcmpv6Redirect', 'bool', [], is_const=True, visibility='private', is_virtual=True) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3OutputStreamWrapper_methods(root_module, cls): ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(ns3::OutputStreamWrapper const & arg0) [copy constructor] cls.add_constructor([param('ns3::OutputStreamWrapper const &', 'arg0')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::string filename, std::_Ios_Openmode filemode) [constructor] cls.add_constructor([param('std::string', 'filename'), param('std::_Ios_Openmode', 'filemode')]) ## output-stream-wrapper.h (module 'network'): ns3::OutputStreamWrapper::OutputStreamWrapper(std::ostream * os) [constructor] cls.add_constructor([param('std::ostream *', 'os')]) ## output-stream-wrapper.h (module 'network'): std::ostream * ns3::OutputStreamWrapper::GetStream() [member function] cls.add_method('GetStream', 'std::ostream *', []) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) return def register_Ns3TimeChecker_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker(ns3::TimeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeChecker const &', 'arg0')]) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) return def register_functions_ns3_FatalImpl(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-3.0
-8,632,934,393,277,049,000
65.711069
934
0.60958
false
engdan77/edoAutoHomeMobile
twisted/internet/test/test_inotify.py
10
16534
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for the inotify wrapper in L{twisted.internet.inotify}. """ from twisted.internet import defer, reactor from twisted.python import filepath, runtime from twisted.python.reflect import requireModule from twisted.trial import unittest if requireModule('twisted.python._inotify') is not None: from twisted.internet import inotify else: inotify = None class INotifyTests(unittest.TestCase): """ Define all the tests for the basic functionality exposed by L{inotify.INotify}. """ if not runtime.platform.supportsINotify(): skip = "This platform doesn't support INotify." def setUp(self): self.dirname = filepath.FilePath(self.mktemp()) self.dirname.createDirectory() self.inotify = inotify.INotify() self.inotify.startReading() self.addCleanup(self.inotify.loseConnection) def test_initializationErrors(self): """ L{inotify.INotify} emits a C{RuntimeError} when initialized in an environment that doesn't support inotify as we expect it. We just try to raise an exception for every possible case in the for loop in L{inotify.INotify._inotify__init__}. """ class FakeINotify: def init(self): raise inotify.INotifyError() self.patch(inotify.INotify, '_inotify', FakeINotify()) self.assertRaises(inotify.INotifyError, inotify.INotify) def _notificationTest(self, mask, operation, expectedPath=None): """ Test notification from some filesystem operation. @param mask: The event mask to use when setting up the watch. @param operation: A function which will be called with the name of a file in the watched directory and which should trigger the event. @param expectedPath: Optionally, the name of the path which is expected to come back in the notification event; this will also be passed to C{operation} (primarily useful when the operation is being done to the directory itself, not a file in it). @return: A L{Deferred} which fires successfully when the expected event has been received or fails otherwise. """ if expectedPath is None: expectedPath = self.dirname.child("foo.bar") notified = defer.Deferred() def cbNotified((watch, filename, events)): self.assertEqual(filename, expectedPath) self.assertTrue(events & mask) notified.addCallback(cbNotified) self.inotify.watch( self.dirname, mask=mask, callbacks=[lambda *args: notified.callback(args)]) operation(expectedPath) return notified def test_access(self): """ Reading from a file in a monitored directory sends an C{inotify.IN_ACCESS} event to the callback. """ def operation(path): path.setContent("foo") path.getContent() return self._notificationTest(inotify.IN_ACCESS, operation) def test_modify(self): """ Writing to a file in a monitored directory sends an C{inotify.IN_MODIFY} event to the callback. """ def operation(path): fObj = path.open("w") fObj.write('foo') fObj.close() return self._notificationTest(inotify.IN_MODIFY, operation) def test_attrib(self): """ Changing the metadata of a file in a monitored directory sends an C{inotify.IN_ATTRIB} event to the callback. """ def operation(path): path.touch() path.touch() return self._notificationTest(inotify.IN_ATTRIB, operation) def test_closeWrite(self): """ Closing a file which was open for writing in a monitored directory sends an C{inotify.IN_CLOSE_WRITE} event to the callback. """ def operation(path): fObj = path.open("w") fObj.close() return self._notificationTest(inotify.IN_CLOSE_WRITE, operation) def test_closeNoWrite(self): """ Closing a file which was open for reading but not writing in a monitored directory sends an C{inotify.IN_CLOSE_NOWRITE} event to the callback. """ def operation(path): path.touch() fObj = path.open("r") fObj.close() return self._notificationTest(inotify.IN_CLOSE_NOWRITE, operation) def test_open(self): """ Opening a file in a monitored directory sends an C{inotify.IN_OPEN} event to the callback. """ def operation(path): fObj = path.open("w") fObj.close() return self._notificationTest(inotify.IN_OPEN, operation) def test_movedFrom(self): """ Moving a file out of a monitored directory sends an C{inotify.IN_MOVED_FROM} event to the callback. """ def operation(path): fObj = path.open("w") fObj.close() path.moveTo(filepath.FilePath(self.mktemp())) return self._notificationTest(inotify.IN_MOVED_FROM, operation) def test_movedTo(self): """ Moving a file into a monitored directory sends an C{inotify.IN_MOVED_TO} event to the callback. """ def operation(path): p = filepath.FilePath(self.mktemp()) p.touch() p.moveTo(path) return self._notificationTest(inotify.IN_MOVED_TO, operation) def test_create(self): """ Creating a file in a monitored directory sends an C{inotify.IN_CREATE} event to the callback. """ def operation(path): fObj = path.open("w") fObj.close() return self._notificationTest(inotify.IN_CREATE, operation) def test_delete(self): """ Deleting a file in a monitored directory sends an C{inotify.IN_DELETE} event to the callback. """ def operation(path): path.touch() path.remove() return self._notificationTest(inotify.IN_DELETE, operation) def test_deleteSelf(self): """ Deleting the monitored directory itself sends an C{inotify.IN_DELETE_SELF} event to the callback. """ def operation(path): path.remove() return self._notificationTest( inotify.IN_DELETE_SELF, operation, expectedPath=self.dirname) def test_moveSelf(self): """ Renaming the monitored directory itself sends an C{inotify.IN_MOVE_SELF} event to the callback. """ def operation(path): path.moveTo(filepath.FilePath(self.mktemp())) return self._notificationTest( inotify.IN_MOVE_SELF, operation, expectedPath=self.dirname) def test_simpleSubdirectoryAutoAdd(self): """ L{inotify.INotify} when initialized with autoAdd==True adds also adds the created subdirectories to the watchlist. """ def _callback(wp, filename, mask): # We are notified before we actually process new # directories, so we need to defer this check. def _(): try: self.assertTrue(self.inotify._isWatched(subdir)) d.callback(None) except Exception: d.errback() reactor.callLater(0, _) checkMask = inotify.IN_ISDIR | inotify.IN_CREATE self.inotify.watch( self.dirname, mask=checkMask, autoAdd=True, callbacks=[_callback]) subdir = self.dirname.child('test') d = defer.Deferred() subdir.createDirectory() return d def test_simpleDeleteDirectory(self): """ L{inotify.INotify} removes a directory from the watchlist when it's removed from the filesystem. """ calls = [] def _callback(wp, filename, mask): # We are notified before we actually process new # directories, so we need to defer this check. def _(): try: self.assertTrue(self.inotify._isWatched(subdir)) subdir.remove() except Exception: d.errback() def _eb(): # second call, we have just removed the subdir try: self.assertTrue(not self.inotify._isWatched(subdir)) d.callback(None) except Exception: d.errback() if not calls: # first call, it's the create subdir calls.append(filename) reactor.callLater(0, _) else: reactor.callLater(0, _eb) checkMask = inotify.IN_ISDIR | inotify.IN_CREATE self.inotify.watch( self.dirname, mask=checkMask, autoAdd=True, callbacks=[_callback]) subdir = self.dirname.child('test') d = defer.Deferred() subdir.createDirectory() return d def test_ignoreDirectory(self): """ L{inotify.INotify.ignore} removes a directory from the watchlist """ self.inotify.watch(self.dirname, autoAdd=True) self.assertTrue(self.inotify._isWatched(self.dirname)) self.inotify.ignore(self.dirname) self.assertFalse(self.inotify._isWatched(self.dirname)) def test_humanReadableMask(self): """ L{inotify.humaReadableMask} translates all the possible event masks to a human readable string. """ for mask, value in inotify._FLAG_TO_HUMAN: self.assertEqual(inotify.humanReadableMask(mask)[0], value) checkMask = ( inotify.IN_CLOSE_WRITE | inotify.IN_ACCESS | inotify.IN_OPEN) self.assertEqual( set(inotify.humanReadableMask(checkMask)), set(['close_write', 'access', 'open'])) def test_recursiveWatch(self): """ L{inotify.INotify.watch} with recursive==True will add all the subdirectories under the given path to the watchlist. """ subdir = self.dirname.child('test') subdir2 = subdir.child('test2') subdir3 = subdir2.child('test3') subdir3.makedirs() dirs = [subdir, subdir2, subdir3] self.inotify.watch(self.dirname, recursive=True) # let's even call this twice so that we test that nothing breaks self.inotify.watch(self.dirname, recursive=True) for d in dirs: self.assertTrue(self.inotify._isWatched(d)) def test_connectionLostError(self): """ L{inotify.INotify.connectionLost} if there's a problem while closing the fd shouldn't raise the exception but should log the error """ import os in_ = inotify.INotify() os.close(in_._fd) in_.loseConnection() self.flushLoggedErrors() def test_noAutoAddSubdirectory(self): """ L{inotify.INotify.watch} with autoAdd==False will stop inotify from watching subdirectories created under the watched one. """ def _callback(wp, fp, mask): # We are notified before we actually process new # directories, so we need to defer this check. def _(): try: self.assertFalse(self.inotify._isWatched(subdir.path)) d.callback(None) except Exception: d.errback() reactor.callLater(0, _) checkMask = inotify.IN_ISDIR | inotify.IN_CREATE self.inotify.watch( self.dirname, mask=checkMask, autoAdd=False, callbacks=[_callback]) subdir = self.dirname.child('test') d = defer.Deferred() subdir.createDirectory() return d def test_seriesOfWatchAndIgnore(self): """ L{inotify.INotify} will watch a filepath for events even if the same path is repeatedly added/removed/re-added to the watchpoints. """ expectedPath = self.dirname.child("foo.bar2") expectedPath.touch() notified = defer.Deferred() def cbNotified((ignored, filename, events)): self.assertEqual(filename, expectedPath) self.assertTrue(events & inotify.IN_DELETE_SELF) def callIt(*args): notified.callback(args) # Watch, ignore, watch again to get into the state being tested. self.assertTrue(self.inotify.watch(expectedPath, callbacks=[callIt])) self.inotify.ignore(expectedPath) self.assertTrue( self.inotify.watch( expectedPath, mask=inotify.IN_DELETE_SELF, callbacks=[callIt])) notified.addCallback(cbNotified) # Apparently in kernel version < 2.6.25, inofify has a bug in the way # similar events are coalesced. So, be sure to generate a different # event here than the touch() at the top of this method might have # generated. expectedPath.remove() return notified def test_ignoreFilePath(self): """ L{inotify.INotify} will ignore a filepath after it has been removed from the watch list. """ expectedPath = self.dirname.child("foo.bar2") expectedPath.touch() expectedPath2 = self.dirname.child("foo.bar3") expectedPath2.touch() notified = defer.Deferred() def cbNotified((ignored, filename, events)): self.assertEqual(filename, expectedPath2) self.assertTrue(events & inotify.IN_DELETE_SELF) def callIt(*args): notified.callback(args) self.assertTrue( self.inotify.watch( expectedPath, inotify.IN_DELETE_SELF, callbacks=[callIt])) notified.addCallback(cbNotified) self.assertTrue( self.inotify.watch( expectedPath2, inotify.IN_DELETE_SELF, callbacks=[callIt])) self.inotify.ignore(expectedPath) expectedPath.remove() expectedPath2.remove() return notified def test_ignoreNonWatchedFile(self): """ L{inotify.INotify} will raise KeyError if a non-watched filepath is ignored. """ expectedPath = self.dirname.child("foo.ignored") expectedPath.touch() self.assertRaises(KeyError, self.inotify.ignore, expectedPath) def test_complexSubdirectoryAutoAdd(self): """ L{inotify.INotify} with autoAdd==True for a watched path generates events for every file or directory already present in a newly created subdirectory under the watched one. This tests that we solve a race condition in inotify even though we may generate duplicate events. """ calls = set() def _callback(wp, filename, mask): calls.add(filename) if len(calls) == 6: try: self.assertTrue(self.inotify._isWatched(subdir)) self.assertTrue(self.inotify._isWatched(subdir2)) self.assertTrue(self.inotify._isWatched(subdir3)) created = someFiles + [subdir, subdir2, subdir3] self.assertEqual(len(calls), len(created)) self.assertEqual(calls, set(created)) except Exception: d.errback() else: d.callback(None) checkMask = inotify.IN_ISDIR | inotify.IN_CREATE self.inotify.watch( self.dirname, mask=checkMask, autoAdd=True, callbacks=[_callback]) subdir = self.dirname.child('test') subdir2 = subdir.child('test2') subdir3 = subdir2.child('test3') d = defer.Deferred() subdir3.makedirs() someFiles = [subdir.child('file1.dat'), subdir2.child('file2.dat'), subdir3.child('file3.dat')] # Add some files in pretty much all the directories so that we # see that we process all of them. for i, filename in enumerate(someFiles): filename.setContent(filename.path) return d
mit
8,347,262,096,192,893,000
31.870775
80
0.59169
false
BlueBrain/deap
deap/tools/indicator.py
10
3372
# Copyright (C) 2010 Simon Wessing # TU Dortmund University # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import numpy try: # try importing the C version from ._hypervolume import hv as hv except ImportError: # fallback on python version from ._hypervolume import pyhv as hv def hypervolume(front, **kargs): """Returns the index of the individual with the least the hypervolume contribution. The provided *front* should be a set of non-dominated individuals having each a :attr:`fitness` attribute. """ # Must use wvalues * -1 since hypervolume use implicit minimization # And minimization in deap use max on -obj wobj = numpy.array([ind.fitness.wvalues for ind in front]) * -1 ref = kargs.get("ref", None) if ref is None: ref = numpy.max(wobj, axis=0) + 1 def contribution(i): # The contribution of point p_i in point set P # is the hypervolume of P without p_i return hv.hypervolume(numpy.concatenate((wobj[:i], wobj[i+1:])), ref) # Parallelization note: Cannot pickle local function contrib_values = map(contribution, range(len(front))) # Select the maximum hypervolume value (correspond to the minimum difference) return numpy.argmax(contrib_values) def additive_epsilon(front, **kargs): """Returns the index of the individual with the least the additive epsilon contribution. The provided *front* should be a set of non-dominated individuals having each a :attr:`fitness` attribute. .. warning:: This function has not been tested. """ wobj = numpy.array([ind.fitness.wvalues for ind in front]) * -1 def contribution(i): mwobj = numpy.ma.array(wobj) mwobj[i] = numpy.ma.masked return numpy.min(numpy.max(wobj[i] - mwobj, axis=1)) contrib_values = map(contribution, range(len(front))) # Select the minimum contribution value return numpy.argmin(contrib_values) def multiplicative_epsilon(front, **kargs): """Returns the index of the individual with the least the multiplicative epsilon contribution. The provided *front* should be a set of non-dominated individuals having each a :attr:`fitness` attribute. .. warning:: This function has not been tested. """ wobj = numpy.array([ind.fitness.wvalues for ind in front]) * -1 def contribution(i): mwobj = numpy.ma.array(wobj) mwobj[i] = numpy.ma.masked return numpy.min(numpy.max(wobj[i] / mwobj, axis=1)) contrib_values = map(contribution, range(len(front))) # Select the minimum contribution value return numpy.argmin(contrib_values) __all__ = ["hypervolume", "additive_epsilon", "multiplicative_epsilon"]
lgpl-3.0
4,887,505,473,405,924,000
34.882979
84
0.685943
false
dulems/hue
desktop/core/ext-py/Paste-1.7.2/paste/wsgilib.py
27
20134
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """ A module of many disparate routines. """ # functions which moved to paste.request and paste.response # Deprecated around 15 Dec 2005 from paste.request import get_cookies, parse_querystring, parse_formvars from paste.request import construct_url, path_info_split, path_info_pop from paste.response import HeaderDict, has_header, header_value, remove_header from paste.response import error_body_response, error_response, error_response_app from traceback import print_exception import urllib from cStringIO import StringIO import sys from urlparse import urlsplit import warnings __all__ = ['add_close', 'add_start_close', 'capture_output', 'catch_errors', 'catch_errors_app', 'chained_app_iters', 'construct_url', 'dump_environ', 'encode_unicode_app_iter', 'error_body_response', 'error_response', 'get_cookies', 'has_header', 'header_value', 'interactive', 'intercept_output', 'path_info_pop', 'path_info_split', 'raw_interactive', 'send_file'] class add_close(object): """ An an iterable that iterates over app_iter, then calls close_func. """ def __init__(self, app_iterable, close_func): self.app_iterable = app_iterable self.app_iter = iter(app_iterable) self.close_func = close_func self._closed = False def __iter__(self): return self def next(self): return self.app_iter.next() def close(self): self._closed = True if hasattr(self.app_iterable, 'close'): self.app_iterable.close() self.close_func() def __del__(self): if not self._closed: # We can't raise an error or anything at this stage print >> sys.stderr, ( "Error: app_iter.close() was not called when finishing " "WSGI request. finalization function %s not called" % self.close_func) class add_start_close(object): """ An an iterable that iterates over app_iter, calls start_func before the first item is returned, then calls close_func at the end. """ def __init__(self, app_iterable, start_func, close_func=None): self.app_iterable = app_iterable self.app_iter = iter(app_iterable) self.first = True self.start_func = start_func self.close_func = close_func self._closed = False def __iter__(self): return self def next(self): if self.first: self.start_func() self.first = False return self.app_iter.next() def close(self): self._closed = True if hasattr(self.app_iterable, 'close'): self.app_iterable.close() if self.close_func is not None: self.close_func() def __del__(self): if not self._closed: # We can't raise an error or anything at this stage print >> sys.stderr, ( "Error: app_iter.close() was not called when finishing " "WSGI request. finalization function %s not called" % self.close_func) class chained_app_iters(object): """ Chains several app_iters together, also delegating .close() to each of them. """ def __init__(self, *chained): self.app_iters = chained self.chained = [iter(item) for item in chained] self._closed = False def __iter__(self): return self def next(self): if len(self.chained) == 1: return self.chained[0].next() else: try: return self.chained[0].next() except StopIteration: self.chained.pop(0) return self.next() def close(self): self._closed = True got_exc = None for app_iter in self.app_iters: try: if hasattr(app_iter, 'close'): app_iter.close() except: got_exc = sys.exc_info() if got_exc: raise got_exc[0], got_exc[1], got_exc[2] def __del__(self): if not self._closed: # We can't raise an error or anything at this stage print >> sys.stderr, ( "Error: app_iter.close() was not called when finishing " "WSGI request. finalization function %s not called" % self.close_func) class encode_unicode_app_iter(object): """ Encodes an app_iterable's unicode responses as strings """ def __init__(self, app_iterable, encoding=sys.getdefaultencoding(), errors='strict'): self.app_iterable = app_iterable self.app_iter = iter(app_iterable) self.encoding = encoding self.errors = errors def __iter__(self): return self def next(self): content = self.app_iter.next() if isinstance(content, unicode): content = content.encode(self.encoding, self.errors) return content def close(self): if hasattr(self.app_iterable, 'close'): self.app_iterable.close() def catch_errors(application, environ, start_response, error_callback, ok_callback=None): """ Runs the application, and returns the application iterator (which should be passed upstream). If an error occurs then error_callback will be called with exc_info as its sole argument. If no errors occur and ok_callback is given, then it will be called with no arguments. """ try: app_iter = application(environ, start_response) except: error_callback(sys.exc_info()) raise if type(app_iter) in (list, tuple): # These won't produce exceptions if ok_callback: ok_callback() return app_iter else: return _wrap_app_iter(app_iter, error_callback, ok_callback) class _wrap_app_iter(object): def __init__(self, app_iterable, error_callback, ok_callback): self.app_iterable = app_iterable self.app_iter = iter(app_iterable) self.error_callback = error_callback self.ok_callback = ok_callback if hasattr(self.app_iterable, 'close'): self.close = self.app_iterable.close def __iter__(self): return self def next(self): try: return self.app_iter.next() except StopIteration: if self.ok_callback: self.ok_callback() raise except: self.error_callback(sys.exc_info()) raise def catch_errors_app(application, environ, start_response, error_callback_app, ok_callback=None, catch=Exception): """ Like ``catch_errors``, except error_callback_app should be a callable that will receive *three* arguments -- ``environ``, ``start_response``, and ``exc_info``. It should call ``start_response`` (*with* the exc_info argument!) and return an iterator. """ try: app_iter = application(environ, start_response) except catch: return error_callback_app(environ, start_response, sys.exc_info()) if type(app_iter) in (list, tuple): # These won't produce exceptions if ok_callback is not None: ok_callback() return app_iter else: return _wrap_app_iter_app( environ, start_response, app_iter, error_callback_app, ok_callback, catch=catch) class _wrap_app_iter_app(object): def __init__(self, environ, start_response, app_iterable, error_callback_app, ok_callback, catch=Exception): self.environ = environ self.start_response = start_response self.app_iterable = app_iterable self.app_iter = iter(app_iterable) self.error_callback_app = error_callback_app self.ok_callback = ok_callback self.catch = catch if hasattr(self.app_iterable, 'close'): self.close = self.app_iterable.close def __iter__(self): return self def next(self): try: return self.app_iter.next() except StopIteration: if self.ok_callback: self.ok_callback() raise except self.catch: if hasattr(self.app_iterable, 'close'): try: self.app_iterable.close() except: # @@: Print to wsgi.errors? pass new_app_iterable = self.error_callback_app( self.environ, self.start_response, sys.exc_info()) app_iter = iter(new_app_iterable) if hasattr(new_app_iterable, 'close'): self.close = new_app_iterable.close self.next = app_iter.next return self.next() def raw_interactive(application, path='', raise_on_wsgi_error=False, **environ): """ Runs the application in a fake environment. """ assert "path_info" not in environ, "argument list changed" if raise_on_wsgi_error: errors = ErrorRaiser() else: errors = StringIO() basic_environ = { # mandatory CGI variables 'REQUEST_METHOD': 'GET', # always mandatory 'SCRIPT_NAME': '', # may be empty if app is at the root 'PATH_INFO': '', # may be empty if at root of app 'SERVER_NAME': 'localhost', # always mandatory 'SERVER_PORT': '80', # always mandatory 'SERVER_PROTOCOL': 'HTTP/1.0', # mandatory wsgi variables 'wsgi.version': (1, 0), 'wsgi.url_scheme': 'http', 'wsgi.input': StringIO(''), 'wsgi.errors': errors, 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, } if path: (_, _, path_info, query, fragment) = urlsplit(str(path)) path_info = urllib.unquote(path_info) # urlsplit returns unicode so coerce it back to str path_info, query = str(path_info), str(query) basic_environ['PATH_INFO'] = path_info if query: basic_environ['QUERY_STRING'] = query for name, value in environ.items(): name = name.replace('__', '.') basic_environ[name] = value if ('SERVER_NAME' in basic_environ and 'HTTP_HOST' not in basic_environ): basic_environ['HTTP_HOST'] = basic_environ['SERVER_NAME'] istream = basic_environ['wsgi.input'] if isinstance(istream, str): basic_environ['wsgi.input'] = StringIO(istream) basic_environ['CONTENT_LENGTH'] = len(istream) data = {} output = [] headers_set = [] headers_sent = [] def start_response(status, headers, exc_info=None): if exc_info: try: if headers_sent: # Re-raise original exception only if headers sent raise exc_info[0], exc_info[1], exc_info[2] finally: # avoid dangling circular reference exc_info = None elif headers_set: # You cannot set the headers more than once, unless the # exc_info is provided. raise AssertionError("Headers already set and no exc_info!") headers_set.append(True) data['status'] = status data['headers'] = headers return output.append app_iter = application(basic_environ, start_response) try: try: for s in app_iter: if not isinstance(s, str): raise ValueError( "The app_iter response can only contain str (not " "unicode); got: %r" % s) headers_sent.append(True) if not headers_set: raise AssertionError("Content sent w/o headers!") output.append(s) except TypeError, e: # Typically "iteration over non-sequence", so we want # to give better debugging information... e.args = ((e.args[0] + ' iterable: %r' % app_iter),) + e.args[1:] raise finally: if hasattr(app_iter, 'close'): app_iter.close() return (data['status'], data['headers'], ''.join(output), errors.getvalue()) class ErrorRaiser(object): def flush(self): pass def write(self, value): if not value: return raise AssertionError( "No errors should be written (got: %r)" % value) def writelines(self, seq): raise AssertionError( "No errors should be written (got lines: %s)" % list(seq)) def getvalue(self): return '' def interactive(*args, **kw): """ Runs the application interatively, wrapping `raw_interactive` but returning the output in a formatted way. """ status, headers, content, errors = raw_interactive(*args, **kw) full = StringIO() if errors: full.write('Errors:\n') full.write(errors.strip()) full.write('\n----------end errors\n') full.write(status + '\n') for name, value in headers: full.write('%s: %s\n' % (name, value)) full.write('\n') full.write(content) return full.getvalue() interactive.proxy = 'raw_interactive' def dump_environ(environ, start_response): """ Application which simply dumps the current environment variables out as a plain text response. """ output = [] keys = environ.keys() keys.sort() for k in keys: v = str(environ[k]).replace("\n","\n ") output.append("%s: %s\n" % (k, v)) output.append("\n") content_length = environ.get("CONTENT_LENGTH", '') if content_length: output.append(environ['wsgi.input'].read(int(content_length))) output.append("\n") output = "".join(output) headers = [('Content-Type', 'text/plain'), ('Content-Length', str(len(output)))] start_response("200 OK", headers) return [output] def send_file(filename): warnings.warn( "wsgilib.send_file has been moved to paste.fileapp.FileApp", DeprecationWarning, 2) from paste import fileapp return fileapp.FileApp(filename) def capture_output(environ, start_response, application): """ Runs application with environ and start_response, and captures status, headers, and body. Sends status and header, but *not* body. Returns (status, headers, body). Typically this is used like: .. code-block:: python def dehtmlifying_middleware(application): def replacement_app(environ, start_response): status, headers, body = capture_output( environ, start_response, application) content_type = header_value(headers, 'content-type') if (not content_type or not content_type.startswith('text/html')): return [body] body = re.sub(r'<.*?>', '', body) return [body] return replacement_app """ warnings.warn( 'wsgilib.capture_output has been deprecated in favor ' 'of wsgilib.intercept_output', DeprecationWarning, 2) data = [] output = StringIO() def replacement_start_response(status, headers, exc_info=None): if data: data[:] = [] data.append(status) data.append(headers) start_response(status, headers, exc_info) return output.write app_iter = application(environ, replacement_start_response) try: for item in app_iter: output.write(item) finally: if hasattr(app_iter, 'close'): app_iter.close() if not data: data.append(None) if len(data) < 2: data.append(None) data.append(output.getvalue()) return data def intercept_output(environ, application, conditional=None, start_response=None): """ Runs application with environ and captures status, headers, and body. None are sent on; you must send them on yourself (unlike ``capture_output``) Typically this is used like: .. code-block:: python def dehtmlifying_middleware(application): def replacement_app(environ, start_response): status, headers, body = intercept_output( environ, application) start_response(status, headers) content_type = header_value(headers, 'content-type') if (not content_type or not content_type.startswith('text/html')): return [body] body = re.sub(r'<.*?>', '', body) return [body] return replacement_app A third optional argument ``conditional`` should be a function that takes ``conditional(status, headers)`` and returns False if the request should not be intercepted. In that case ``start_response`` will be called and ``(None, None, app_iter)`` will be returned. You must detect that in your code and return the app_iter, like: .. code-block:: python def dehtmlifying_middleware(application): def replacement_app(environ, start_response): status, headers, body = intercept_output( environ, application, lambda s, h: header_value(headers, 'content-type').startswith('text/html'), start_response) if status is None: return body start_response(status, headers) body = re.sub(r'<.*?>', '', body) return [body] return replacement_app """ if conditional is not None and start_response is None: raise TypeError( "If you provide conditional you must also provide " "start_response") data = [] output = StringIO() def replacement_start_response(status, headers, exc_info=None): if conditional is not None and not conditional(status, headers): data.append(None) return start_response(status, headers, exc_info) if data: data[:] = [] data.append(status) data.append(headers) return output.write app_iter = application(environ, replacement_start_response) if data[0] is None: return (None, None, app_iter) try: for item in app_iter: output.write(item) finally: if hasattr(app_iter, 'close'): app_iter.close() if not data: data.append(None) if len(data) < 2: data.append(None) data.append(output.getvalue()) return data ## Deprecation warning wrapper: class ResponseHeaderDict(HeaderDict): def __init__(self, *args, **kw): warnings.warn( "The class wsgilib.ResponseHeaderDict has been moved " "to paste.response.HeaderDict", DeprecationWarning, 2) HeaderDict.__init__(self, *args, **kw) def _warn_deprecated(new_func): new_name = new_func.func_name new_path = new_func.func_globals['__name__'] + '.' + new_name def replacement(*args, **kw): warnings.warn( "The function wsgilib.%s has been moved to %s" % (new_name, new_path), DeprecationWarning, 2) return new_func(*args, **kw) try: replacement.func_name = new_func.func_name except: pass return replacement # Put warnings wrapper in place for all public functions that # were imported from elsewhere: for _name in __all__: _func = globals()[_name] if (hasattr(_func, 'func_globals') and _func.func_globals['__name__'] != __name__): globals()[_name] = _warn_deprecated(_func) if __name__ == '__main__': import doctest doctest.testmod()
apache-2.0
3,644,816,129,580,292,600
32.725293
95
0.576289
false
hltbra/pyhistorian
specs/story.py
1
1089
''' >>> story.run() True >>> print output.getvalue() Story: Faked Story #1 In order to write specifications As a python developer I want to write them in Python language <BLANKLINE> Scenario 1: Fake scenario Given I run it ... OK When I type X ... OK Then it shows me X ... OK <BLANKLINE> Ran 1 scenario with 0 failures, 0 errors and 0 pending steps <BLANKLINE> ''' from pyhistorian import Story from cStringIO import StringIO output = StringIO() class FakeScenario(object): _givens = _whens = _thens = [] title = 'Fake scenario' def __init__(self, story): """default interface (should do nothing)""" def run(self): output.write(' Given I run it ... OK\n') output.write(' When I type X ... OK\n') output.write(' Then it shows me X ... OK\n') return [], [], [] class FakedStory(Story): """In order to write specifications As a python developer I want to write them in Python language""" output = output scenarios = [FakeScenario] title = 'Faked Story #1' story = FakedStory()
mit
5,868,556,030,415,097,000
23.2
60
0.630854
false
lukeiwanski/tensorflow-opencl
tensorflow/contrib/legacy_seq2seq/python/kernel_tests/seq2seq_test.py
5
43745
# 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. # ============================================================================== """Tests for functional style sequence-to-sequence models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import math import random import sys # TODO: #6568 Remove this hack that makes dlopen() not crash. if hasattr(sys, "getdlopenflags") and hasattr(sys, "setdlopenflags"): import ctypes sys.setdlopenflags(sys.getdlopenflags() | ctypes.RTLD_GLOBAL) import numpy as np from tensorflow.contrib.legacy_seq2seq.python.ops import seq2seq as seq2seq_lib from tensorflow.contrib.rnn.python.ops import core_rnn from tensorflow.contrib.rnn.python.ops import core_rnn_cell_impl from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.ops import array_ops from tensorflow.python.ops import clip_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import init_ops from tensorflow.python.ops import nn_impl from tensorflow.python.ops import rnn from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import test from tensorflow.python.training import adam class Seq2SeqTest(test.TestCase): def testRNNDecoder(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 _, enc_state = core_rnn.static_rnn( core_rnn_cell_impl.GRUCell(2), inp, dtype=dtypes.float32) dec_inp = [constant_op.constant(0.4, shape=[2, 2])] * 3 cell = core_rnn_cell_impl.OutputProjectionWrapper( core_rnn_cell_impl.GRUCell(2), 4) dec, mem = seq2seq_lib.rnn_decoder(dec_inp, enc_state, cell) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testBasicRNNSeq2Seq(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 dec_inp = [constant_op.constant(0.4, shape=[2, 2])] * 3 cell = core_rnn_cell_impl.OutputProjectionWrapper( core_rnn_cell_impl.GRUCell(2), 4) dec, mem = seq2seq_lib.basic_rnn_seq2seq(inp, dec_inp, cell) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testTiedRNNSeq2Seq(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 dec_inp = [constant_op.constant(0.4, shape=[2, 2])] * 3 cell = core_rnn_cell_impl.OutputProjectionWrapper( core_rnn_cell_impl.GRUCell(2), 4) dec, mem = seq2seq_lib.tied_rnn_seq2seq(inp, dec_inp, cell) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual(1, len(res)) self.assertEqual((2, 2), res[0].shape) def testEmbeddingRNNDecoder(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 cell_fn = lambda: core_rnn_cell_impl.BasicLSTMCell(2) cell = cell_fn() _, enc_state = core_rnn.static_rnn(cell, inp, dtype=dtypes.float32) dec_inp = [ constant_op.constant( i, dtypes.int32, shape=[2]) for i in range(3) ] # Use a new cell instance since the attention decoder uses a # different variable scope. dec, mem = seq2seq_lib.embedding_rnn_decoder( dec_inp, enc_state, cell_fn(), num_symbols=4, embedding_size=2) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) res = sess.run([mem]) self.assertEqual(1, len(res)) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) def testEmbeddingRNNSeq2Seq(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): enc_inp = [ constant_op.constant( 1, dtypes.int32, shape=[2]) for i in range(2) ] dec_inp = [ constant_op.constant( i, dtypes.int32, shape=[2]) for i in range(3) ] cell_fn = lambda: core_rnn_cell_impl.BasicLSTMCell(2) cell = cell_fn() dec, mem = seq2seq_lib.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test with state_is_tuple=False. with variable_scope.variable_scope("no_tuple"): cell_nt = core_rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=False) dec, mem = seq2seq_lib.embedding_rnn_seq2seq( enc_inp, dec_inp, cell_nt, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 4), res[0].shape) # Test externally provided output projection. w = variable_scope.get_variable("proj_w", [2, 5]) b = variable_scope.get_variable("proj_b", [5]) with variable_scope.variable_scope("proj_seq2seq"): dec, _ = seq2seq_lib.embedding_rnn_seq2seq( enc_inp, dec_inp, cell_fn(), num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [ constant_op.constant( 0, dtypes.int32, shape=[2]) for _ in range(3) ] with variable_scope.variable_scope("other"): d3, _ = seq2seq_lib.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell_fn(), num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=constant_op.constant(True)) with variable_scope.variable_scope("other_2"): d1, _ = seq2seq_lib.embedding_rnn_seq2seq( enc_inp, dec_inp, cell_fn(), num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) with variable_scope.variable_scope("other_3"): d2, _ = seq2seq_lib.embedding_rnn_seq2seq( enc_inp, dec_inp2, cell_fn(), num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, feed_previous=True) sess.run([variables.global_variables_initializer()]) res1 = sess.run(d1) res2 = sess.run(d2) res3 = sess.run(d3) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3) def testEmbeddingTiedRNNSeq2Seq(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): enc_inp = [ constant_op.constant( 1, dtypes.int32, shape=[2]) for i in range(2) ] dec_inp = [ constant_op.constant( i, dtypes.int32, shape=[2]) for i in range(3) ] cell = functools.partial( core_rnn_cell_impl.BasicLSTMCell, 2, state_is_tuple=True) dec, mem = seq2seq_lib.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell(), num_symbols=5, embedding_size=2) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test when num_decoder_symbols is provided, the size of decoder output # is num_decoder_symbols. with variable_scope.variable_scope("decoder_symbols_seq2seq"): dec, mem = seq2seq_lib.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell(), num_symbols=5, num_decoder_symbols=3, embedding_size=2) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 3), res[0].shape) # Test externally provided output projection. w = variable_scope.get_variable("proj_w", [2, 5]) b = variable_scope.get_variable("proj_b", [5]) with variable_scope.variable_scope("proj_seq2seq"): dec, _ = seq2seq_lib.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell(), num_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # Test that previous-feeding model ignores inputs after the first. dec_inp2 = [constant_op.constant(0, dtypes.int32, shape=[2])] * 3 with variable_scope.variable_scope("other"): d3, _ = seq2seq_lib.embedding_tied_rnn_seq2seq( enc_inp, dec_inp2, cell(), num_symbols=5, embedding_size=2, feed_previous=constant_op.constant(True)) with variable_scope.variable_scope("other_2"): d1, _ = seq2seq_lib.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell(), num_symbols=5, embedding_size=2, feed_previous=True) with variable_scope.variable_scope("other_3"): d2, _ = seq2seq_lib.embedding_tied_rnn_seq2seq( enc_inp, dec_inp2, cell(), num_symbols=5, embedding_size=2, feed_previous=True) sess.run([variables.global_variables_initializer()]) res1 = sess.run(d1) res2 = sess.run(d2) res3 = sess.run(d3) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3) def testAttentionDecoder1(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): cell_fn = lambda: core_rnn_cell_impl.GRUCell(2) cell = cell_fn() inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = core_rnn.static_rnn( cell, inp, dtype=dtypes.float32) attn_states = array_ops.concat([ array_ops.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs ], 1) dec_inp = [constant_op.constant(0.4, shape=[2, 2])] * 3 # Create a new cell instance for the decoder, since it uses a # different variable scope dec, mem = seq2seq_lib.attention_decoder( dec_inp, enc_state, attn_states, cell_fn(), output_size=4) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testAttentionDecoder2(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): cell_fn = lambda: core_rnn_cell_impl.GRUCell(2) cell = cell_fn() inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = core_rnn.static_rnn( cell, inp, dtype=dtypes.float32) attn_states = array_ops.concat([ array_ops.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs ], 1) dec_inp = [constant_op.constant(0.4, shape=[2, 2])] * 3 # Use a new cell instance since the attention decoder uses a # different variable scope. dec, mem = seq2seq_lib.attention_decoder( dec_inp, enc_state, attn_states, cell_fn(), output_size=4, num_heads=2) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testDynamicAttentionDecoder1(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): cell_fn = lambda: core_rnn_cell_impl.GRUCell(2) cell = cell_fn() inp = constant_op.constant(0.5, shape=[2, 2, 2]) enc_outputs, enc_state = rnn.dynamic_rnn( cell, inp, dtype=dtypes.float32) attn_states = enc_outputs dec_inp = [constant_op.constant(0.4, shape=[2, 2])] * 3 # Use a new cell instance since the attention decoder uses a # different variable scope. dec, mem = seq2seq_lib.attention_decoder( dec_inp, enc_state, attn_states, cell_fn(), output_size=4) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testDynamicAttentionDecoder2(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): cell_fn = lambda: core_rnn_cell_impl.GRUCell(2) cell = cell_fn() inp = constant_op.constant(0.5, shape=[2, 2, 2]) enc_outputs, enc_state = rnn.dynamic_rnn( cell, inp, dtype=dtypes.float32) attn_states = enc_outputs dec_inp = [constant_op.constant(0.4, shape=[2, 2])] * 3 # Use a new cell instance since the attention decoder uses a # different variable scope. dec, mem = seq2seq_lib.attention_decoder( dec_inp, enc_state, attn_states, cell_fn(), output_size=4, num_heads=2) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testAttentionDecoderStateIsTuple(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): single_cell = lambda: core_rnn_cell_impl.BasicLSTMCell( # pylint: disable=g-long-lambda 2, state_is_tuple=True) cell_fn = lambda: core_rnn_cell_impl.MultiRNNCell( # pylint: disable=g-long-lambda cells=[single_cell() for _ in range(2)], state_is_tuple=True) cell = cell_fn() inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 enc_outputs, enc_state = core_rnn.static_rnn( cell, inp, dtype=dtypes.float32) attn_states = array_ops.concat([ array_ops.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs ], 1) dec_inp = [constant_op.constant(0.4, shape=[2, 2])] * 3 # Use a new cell instance since the attention decoder uses a # different variable scope. dec, mem = seq2seq_lib.attention_decoder( dec_inp, enc_state, attn_states, cell_fn(), output_size=4) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual(2, len(res[0])) self.assertEqual((2, 2), res[0][0].c.shape) self.assertEqual((2, 2), res[0][0].h.shape) self.assertEqual((2, 2), res[0][1].c.shape) self.assertEqual((2, 2), res[0][1].h.shape) def testDynamicAttentionDecoderStateIsTuple(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): cell_fn = lambda: core_rnn_cell_impl.MultiRNNCell( # pylint: disable=g-long-lambda cells=[core_rnn_cell_impl.BasicLSTMCell(2) for _ in range(2)]) cell = cell_fn() inp = constant_op.constant(0.5, shape=[2, 2, 2]) enc_outputs, enc_state = core_rnn.static_rnn( cell, inp, dtype=dtypes.float32) attn_states = array_ops.concat([ array_ops.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs ], 1) dec_inp = [constant_op.constant(0.4, shape=[2, 2])] * 3 # Use a new cell instance since the attention decoder uses a # different variable scope. dec, mem = seq2seq_lib.attention_decoder( dec_inp, enc_state, attn_states, cell_fn(), output_size=4) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 4), res[0].shape) res = sess.run([mem]) self.assertEqual(2, len(res[0])) self.assertEqual((2, 2), res[0][0].c.shape) self.assertEqual((2, 2), res[0][0].h.shape) self.assertEqual((2, 2), res[0][1].c.shape) self.assertEqual((2, 2), res[0][1].h.shape) def testEmbeddingAttentionDecoder(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): inp = [constant_op.constant(0.5, shape=[2, 2])] * 2 cell_fn = lambda: core_rnn_cell_impl.GRUCell(2) cell = cell_fn() enc_outputs, enc_state = core_rnn.static_rnn( cell, inp, dtype=dtypes.float32) attn_states = array_ops.concat([ array_ops.reshape(e, [-1, 1, cell.output_size]) for e in enc_outputs ], 1) dec_inp = [ constant_op.constant( i, dtypes.int32, shape=[2]) for i in range(3) ] # Use a new cell instance since the attention decoder uses a # different variable scope. dec, mem = seq2seq_lib.embedding_attention_decoder( dec_inp, enc_state, attn_states, cell_fn(), num_symbols=4, embedding_size=2, output_size=3) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 3), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].shape) def testEmbeddingAttentionSeq2Seq(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): enc_inp = [ constant_op.constant( 1, dtypes.int32, shape=[2]) for i in range(2) ] dec_inp = [ constant_op.constant( i, dtypes.int32, shape=[2]) for i in range(3) ] cell_fn = lambda: core_rnn_cell_impl.BasicLSTMCell(2) cell = cell_fn() dec, mem = seq2seq_lib.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test with state_is_tuple=False. with variable_scope.variable_scope("no_tuple"): cell_fn = functools.partial( core_rnn_cell_impl.BasicLSTMCell, 2, state_is_tuple=False) cell_nt = cell_fn() dec, mem = seq2seq_lib.embedding_attention_seq2seq( enc_inp, dec_inp, cell_nt, num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run([mem]) self.assertEqual((2, 4), res[0].shape) # Test externally provided output projection. w = variable_scope.get_variable("proj_w", [2, 5]) b = variable_scope.get_variable("proj_b", [5]) with variable_scope.variable_scope("proj_seq2seq"): dec, _ = seq2seq_lib.embedding_attention_seq2seq( enc_inp, dec_inp, cell_fn(), num_encoder_symbols=2, num_decoder_symbols=5, embedding_size=2, output_projection=(w, b)) sess.run([variables.global_variables_initializer()]) res = sess.run(dec) self.assertEqual(3, len(res)) self.assertEqual((2, 2), res[0].shape) # TODO(ebrevdo, lukaszkaiser): Re-enable once RNNCells allow reuse # within a variable scope that already has a weights tensor. # # # Test that previous-feeding model ignores inputs after the first. # dec_inp2 = [ # constant_op.constant( # 0, dtypes.int32, shape=[2]) for _ in range(3) # ] # with variable_scope.variable_scope("other"): # d3, _ = seq2seq_lib.embedding_attention_seq2seq( # enc_inp, # dec_inp2, # cell_fn(), # num_encoder_symbols=2, # num_decoder_symbols=5, # embedding_size=2, # feed_previous=constant_op.constant(True)) # sess.run([variables.global_variables_initializer()]) # variable_scope.get_variable_scope().reuse_variables() # cell = cell_fn() # d1, _ = seq2seq_lib.embedding_attention_seq2seq( # enc_inp, # dec_inp, # cell, # num_encoder_symbols=2, # num_decoder_symbols=5, # embedding_size=2, # feed_previous=True) # d2, _ = seq2seq_lib.embedding_attention_seq2seq( # enc_inp, # dec_inp2, # cell, # num_encoder_symbols=2, # num_decoder_symbols=5, # embedding_size=2, # feed_previous=True) # res1 = sess.run(d1) # res2 = sess.run(d2) # res3 = sess.run(d3) # self.assertAllClose(res1, res2) # self.assertAllClose(res1, res3) def testOne2ManyRNNSeq2Seq(self): with self.test_session() as sess: with variable_scope.variable_scope( "root", initializer=init_ops.constant_initializer(0.5)): enc_inp = [ constant_op.constant( 1, dtypes.int32, shape=[2]) for i in range(2) ] dec_inp_dict = {} dec_inp_dict["0"] = [ constant_op.constant( i, dtypes.int32, shape=[2]) for i in range(3) ] dec_inp_dict["1"] = [ constant_op.constant( i, dtypes.int32, shape=[2]) for i in range(4) ] dec_symbols_dict = {"0": 5, "1": 6} def EncCellFn(): return core_rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=True) def DecCellsFn(): return dict( (k, core_rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=True)) for k in dec_symbols_dict) outputs_dict, state_dict = (seq2seq_lib.one2many_rnn_seq2seq( enc_inp, dec_inp_dict, EncCellFn(), DecCellsFn(), 2, dec_symbols_dict, embedding_size=2)) sess.run([variables.global_variables_initializer()]) res = sess.run(outputs_dict["0"]) self.assertEqual(3, len(res)) self.assertEqual((2, 5), res[0].shape) res = sess.run(outputs_dict["1"]) self.assertEqual(4, len(res)) self.assertEqual((2, 6), res[0].shape) res = sess.run([state_dict["0"]]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) res = sess.run([state_dict["1"]]) self.assertEqual((2, 2), res[0].c.shape) self.assertEqual((2, 2), res[0].h.shape) # Test that previous-feeding model ignores inputs after the first, i.e. # dec_inp_dict2 has different inputs from dec_inp_dict after the first # time-step. dec_inp_dict2 = {} dec_inp_dict2["0"] = [ constant_op.constant( 0, dtypes.int32, shape=[2]) for _ in range(3) ] dec_inp_dict2["1"] = [ constant_op.constant( 0, dtypes.int32, shape=[2]) for _ in range(4) ] with variable_scope.variable_scope("other"): outputs_dict3, _ = seq2seq_lib.one2many_rnn_seq2seq( enc_inp, dec_inp_dict2, EncCellFn(), DecCellsFn(), 2, dec_symbols_dict, embedding_size=2, feed_previous=constant_op.constant(True)) with variable_scope.variable_scope("other_2"): outputs_dict1, _ = seq2seq_lib.one2many_rnn_seq2seq( enc_inp, dec_inp_dict, EncCellFn(), DecCellsFn(), 2, dec_symbols_dict, embedding_size=2, feed_previous=True) with variable_scope.variable_scope("other_3"): outputs_dict2, _ = seq2seq_lib.one2many_rnn_seq2seq( enc_inp, dec_inp_dict2, EncCellFn(), DecCellsFn(), 2, dec_symbols_dict, embedding_size=2, feed_previous=True) sess.run([variables.global_variables_initializer()]) res1 = sess.run(outputs_dict1["0"]) res2 = sess.run(outputs_dict2["0"]) res3 = sess.run(outputs_dict3["0"]) self.assertAllClose(res1, res2) self.assertAllClose(res1, res3) def testSequenceLoss(self): with self.test_session() as sess: logits = [constant_op.constant(i + 0.5, shape=[2, 5]) for i in range(3)] targets = [ constant_op.constant( i, dtypes.int32, shape=[2]) for i in range(3) ] weights = [constant_op.constant(1.0, shape=[2]) for i in range(3)] average_loss_per_example = seq2seq_lib.sequence_loss( logits, targets, weights, average_across_timesteps=True, average_across_batch=True) res = sess.run(average_loss_per_example) self.assertAllClose(1.60944, res) average_loss_per_sequence = seq2seq_lib.sequence_loss( logits, targets, weights, average_across_timesteps=False, average_across_batch=True) res = sess.run(average_loss_per_sequence) self.assertAllClose(4.828314, res) total_loss = seq2seq_lib.sequence_loss( logits, targets, weights, average_across_timesteps=False, average_across_batch=False) res = sess.run(total_loss) self.assertAllClose(9.656628, res) def testSequenceLossByExample(self): with self.test_session() as sess: output_classes = 5 logits = [ constant_op.constant( i + 0.5, shape=[2, output_classes]) for i in range(3) ] targets = [ constant_op.constant( i, dtypes.int32, shape=[2]) for i in range(3) ] weights = [constant_op.constant(1.0, shape=[2]) for i in range(3)] average_loss_per_example = (seq2seq_lib.sequence_loss_by_example( logits, targets, weights, average_across_timesteps=True)) res = sess.run(average_loss_per_example) self.assertAllClose(np.asarray([1.609438, 1.609438]), res) loss_per_sequence = seq2seq_lib.sequence_loss_by_example( logits, targets, weights, average_across_timesteps=False) res = sess.run(loss_per_sequence) self.assertAllClose(np.asarray([4.828314, 4.828314]), res) # TODO(ebrevdo, lukaszkaiser): Re-enable once RNNCells allow reuse # within a variable scope that already has a weights tensor. # # def testModelWithBucketsScopeAndLoss(self): # """Test variable scope reuse is not reset after model_with_buckets.""" # classes = 10 # buckets = [(4, 4), (8, 8)] # with self.test_session(): # # Here comes a sample Seq2Seq model using GRU cells. # def SampleGRUSeq2Seq(enc_inp, dec_inp, weights, per_example_loss): # """Example sequence-to-sequence model that uses GRU cells.""" # def GRUSeq2Seq(enc_inp, dec_inp): # cell = core_rnn_cell_impl.MultiRNNCell( # [core_rnn_cell_impl.GRUCell(24) for _ in range(2)]) # return seq2seq_lib.embedding_attention_seq2seq( # enc_inp, # dec_inp, # cell, # num_encoder_symbols=classes, # num_decoder_symbols=classes, # embedding_size=24) # targets = [dec_inp[i + 1] for i in range(len(dec_inp) - 1)] + [0] # return seq2seq_lib.model_with_buckets( # enc_inp, # dec_inp, # targets, # weights, # buckets, # GRUSeq2Seq, # per_example_loss=per_example_loss) # # Now we construct the copy model. # inp = [ # array_ops.placeholder( # dtypes.int32, shape=[None]) for _ in range(8) # ] # out = [ # array_ops.placeholder( # dtypes.int32, shape=[None]) for _ in range(8) # ] # weights = [ # array_ops.ones_like( # inp[0], dtype=dtypes.float32) for _ in range(8) # ] # with variable_scope.variable_scope("root"): # _, losses1 = SampleGRUSeq2Seq( # inp, out, weights, per_example_loss=False) # # Now check that we did not accidentally set reuse. # self.assertEqual(False, variable_scope.get_variable_scope().reuse) # with variable_scope.variable_scope("new"): # _, losses2 = SampleGRUSeq2Seq # inp, out, weights, per_example_loss=True) # # First loss is scalar, the second one is a 1-dimensinal tensor. # self.assertEqual([], losses1[0].get_shape().as_list()) # self.assertEqual([None], losses2[0].get_shape().as_list()) def testModelWithBuckets(self): """Larger tests that does full sequence-to-sequence model training.""" # We learn to copy 10 symbols in 2 buckets: length 4 and length 8. classes = 10 buckets = [(4, 4), (8, 8)] perplexities = [[], []] # Results for each bucket. random_seed.set_random_seed(111) random.seed(111) np.random.seed(111) with self.test_session() as sess: # We use sampled softmax so we keep output projection separate. w = variable_scope.get_variable("proj_w", [24, classes]) w_t = array_ops.transpose(w) b = variable_scope.get_variable("proj_b", [classes]) # Here comes a sample Seq2Seq model using GRU cells. def SampleGRUSeq2Seq(enc_inp, dec_inp, weights): """Example sequence-to-sequence model that uses GRU cells.""" def GRUSeq2Seq(enc_inp, dec_inp): cell = core_rnn_cell_impl.MultiRNNCell( [core_rnn_cell_impl.GRUCell(24) for _ in range(2)], state_is_tuple=True) return seq2seq_lib.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols=classes, num_decoder_symbols=classes, embedding_size=24, output_projection=(w, b)) targets = [dec_inp[i + 1] for i in range(len(dec_inp) - 1)] + [0] def SampledLoss(labels, inputs): labels = array_ops.reshape(labels, [-1, 1]) return nn_impl.sampled_softmax_loss( weights=w_t, biases=b, labels=labels, inputs=inputs, num_sampled=8, num_classes=classes) return seq2seq_lib.model_with_buckets( enc_inp, dec_inp, targets, weights, buckets, GRUSeq2Seq, softmax_loss_function=SampledLoss) # Now we construct the copy model. batch_size = 8 inp = [ array_ops.placeholder( dtypes.int32, shape=[None]) for _ in range(8) ] out = [ array_ops.placeholder( dtypes.int32, shape=[None]) for _ in range(8) ] weights = [ array_ops.ones_like( inp[0], dtype=dtypes.float32) for _ in range(8) ] with variable_scope.variable_scope("root"): _, losses = SampleGRUSeq2Seq(inp, out, weights) updates = [] params = variables.all_variables() optimizer = adam.AdamOptimizer(0.03, epsilon=1e-5) for i in range(len(buckets)): full_grads = gradients_impl.gradients(losses[i], params) grads, _ = clip_ops.clip_by_global_norm(full_grads, 30.0) update = optimizer.apply_gradients(zip(grads, params)) updates.append(update) sess.run([variables.global_variables_initializer()]) steps = 6 for _ in range(steps): bucket = random.choice(np.arange(len(buckets))) length = buckets[bucket][0] i = [ np.array( [np.random.randint(9) + 1 for _ in range(batch_size)], dtype=np.int32) for _ in range(length) ] # 0 is our "GO" symbol here. o = [np.array([0] * batch_size, dtype=np.int32)] + i feed = {} for i1, i2, o1, o2 in zip(inp[:length], i[:length], out[:length], o[:length]): feed[i1.name] = i2 feed[o1.name] = o2 if length < 8: # For the 4-bucket, we need the 5th as target. feed[out[length].name] = o[length] res = sess.run([updates[bucket], losses[bucket]], feed) perplexities[bucket].append(math.exp(float(res[1]))) for bucket in range(len(buckets)): if len(perplexities[bucket]) > 1: # Assert that perplexity went down. self.assertLess(perplexities[bucket][-1], # 10% margin of error. 1.1 * perplexities[bucket][0]) def testModelWithBooleanFeedPrevious(self): """Test the model behavior when feed_previous is True. For example, the following two cases have the same effect: - Train `embedding_rnn_seq2seq` with `feed_previous=True`, which contains a `embedding_rnn_decoder` with `feed_previous=True` and `update_embedding_for_previous=True`. The decoder is fed with "<Go>" and outputs "A, B, C". - Train `embedding_rnn_seq2seq` with `feed_previous=False`. The decoder is fed with "<Go>, A, B". """ num_encoder_symbols = 3 num_decoder_symbols = 5 batch_size = 2 num_enc_timesteps = 2 num_dec_timesteps = 3 def TestModel(seq2seq): with self.test_session(graph=ops.Graph()) as sess: random_seed.set_random_seed(111) random.seed(111) np.random.seed(111) enc_inp = [ constant_op.constant( i + 1, dtypes.int32, shape=[batch_size]) for i in range(num_enc_timesteps) ] dec_inp_fp_true = [ constant_op.constant( i, dtypes.int32, shape=[batch_size]) for i in range(num_dec_timesteps) ] dec_inp_holder_fp_false = [ array_ops.placeholder( dtypes.int32, shape=[batch_size]) for _ in range(num_dec_timesteps) ] targets = [ constant_op.constant( i + 1, dtypes.int32, shape=[batch_size]) for i in range(num_dec_timesteps) ] weights = [ constant_op.constant( 1.0, shape=[batch_size]) for i in range(num_dec_timesteps) ] def ForwardBackward(enc_inp, dec_inp, feed_previous): scope_name = "fp_{}".format(feed_previous) with variable_scope.variable_scope(scope_name): dec_op, _ = seq2seq(enc_inp, dec_inp, feed_previous=feed_previous) net_variables = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES, scope_name) optimizer = adam.AdamOptimizer(0.03, epsilon=1e-5) update_op = optimizer.minimize( seq2seq_lib.sequence_loss(dec_op, targets, weights), var_list=net_variables) return dec_op, update_op, net_variables dec_op_fp_true, update_fp_true, variables_fp_true = ForwardBackward( enc_inp, dec_inp_fp_true, feed_previous=True) dec_op_fp_false, update_fp_false, variables_fp_false = ForwardBackward( enc_inp, dec_inp_holder_fp_false, feed_previous=False) sess.run(variables.global_variables_initializer()) # We only check consistencies between the variables existing in both # the models with True and False feed_previous. Variables created by # the loop_function in the model with True feed_previous are ignored. v_false_name_dict = { v.name.split("/", 1)[-1]: v for v in variables_fp_false } matched_variables = [(v, v_false_name_dict[v.name.split("/", 1)[-1]]) for v in variables_fp_true] for v_true, v_false in matched_variables: sess.run(state_ops.assign(v_false, v_true)) # Take the symbols generated by the decoder with feed_previous=True as # the true input symbols for the decoder with feed_previous=False. dec_fp_true = sess.run(dec_op_fp_true) output_symbols_fp_true = np.argmax(dec_fp_true, axis=2) dec_inp_fp_false = np.vstack((dec_inp_fp_true[0].eval(), output_symbols_fp_true[:-1])) sess.run(update_fp_true) sess.run(update_fp_false, { holder: inp for holder, inp in zip(dec_inp_holder_fp_false, dec_inp_fp_false) }) for v_true, v_false in matched_variables: self.assertAllClose(v_true.eval(), v_false.eval()) def EmbeddingRNNSeq2SeqF(enc_inp, dec_inp, feed_previous): cell = core_rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=True) return seq2seq_lib.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingRNNSeq2SeqNoTupleF(enc_inp, dec_inp, feed_previous): cell = core_rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=False) return seq2seq_lib.embedding_rnn_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingTiedRNNSeq2Seq(enc_inp, dec_inp, feed_previous): cell = core_rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=True) return seq2seq_lib.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingTiedRNNSeq2SeqNoTuple(enc_inp, dec_inp, feed_previous): cell = core_rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=False) return seq2seq_lib.embedding_tied_rnn_seq2seq( enc_inp, dec_inp, cell, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingAttentionSeq2Seq(enc_inp, dec_inp, feed_previous): cell = core_rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=True) return seq2seq_lib.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) def EmbeddingAttentionSeq2SeqNoTuple(enc_inp, dec_inp, feed_previous): cell = core_rnn_cell_impl.BasicLSTMCell(2, state_is_tuple=False) return seq2seq_lib.embedding_attention_seq2seq( enc_inp, dec_inp, cell, num_encoder_symbols, num_decoder_symbols, embedding_size=2, feed_previous=feed_previous) for model in (EmbeddingRNNSeq2SeqF, EmbeddingRNNSeq2SeqNoTupleF, EmbeddingTiedRNNSeq2Seq, EmbeddingTiedRNNSeq2SeqNoTuple, EmbeddingAttentionSeq2Seq, EmbeddingAttentionSeq2SeqNoTuple): TestModel(model) if __name__ == "__main__": test.main()
apache-2.0
5,806,019,406,498,299,000
38.09294
96
0.573048
false
Danisan/pyafipws
wsfexv1.py
8
33017
#!/usr/bin/python # -*- coding: latin-1 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 3, 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 MERCHANTIBILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. """Módulo para obtener CAE, código de autorización de impresión o electrónico, del web service WSFEXv1 de AFIP (Factura Electrónica Exportación Versión 1) según RG2758/2010 (Registros Especiales Aduaneros) y RG3689/14 (servicios) http://www.sistemasagiles.com.ar/trac/wiki/FacturaElectronicaExportacion """ __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2011-2015 Mariano Reingart" __license__ = "GPL 3.0" __version__ = "1.08e" import datetime import decimal import os import sys from utils import inicializar_y_capturar_excepciones, BaseWS, get_install_dir HOMO = False WSDL="https://wswhomo.afip.gov.ar/wsfexv1/service.asmx?WSDL" class WSFEXv1(BaseWS): "Interfaz para el WebService de Factura Electrónica Exportación Versión 1" _public_methods_ = ['CrearFactura', 'AgregarItem', 'Authorize', 'GetCMP', 'AgregarPermiso', 'AgregarCmpAsoc', 'GetParamMon', 'GetParamTipoCbte', 'GetParamTipoExpo', 'GetParamIdiomas', 'GetParamUMed', 'GetParamIncoterms', 'GetParamDstPais','GetParamDstCUIT', 'GetParamIdiomas', 'GetParamIncoterms', 'GetParamDstCUIT', 'GetParamPtosVenta', 'GetParamCtz', 'LoadTestXML', 'AnalizarXml', 'ObtenerTagXml', 'DebugLog', 'SetParametros', 'SetTicketAcceso', 'GetParametro', 'GetLastCMP', 'GetLastID', 'Dummy', 'Conectar', 'SetTicketAcceso'] _public_attrs_ = ['Token', 'Sign', 'Cuit', 'AppServerStatus', 'DbServerStatus', 'AuthServerStatus', 'XmlRequest', 'XmlResponse', 'Version', 'Resultado', 'Obs', 'Reproceso', 'CAE','Vencimiento', 'Eventos', 'ErrCode', 'ErrMsg', 'FchVencCAE', 'Excepcion', 'LanzarExcepciones', 'Traceback', "InstallDir", 'PuntoVenta', 'CbteNro', 'FechaCbte', 'ImpTotal'] _reg_progid_ = "WSFEXv1" _reg_clsid_ = "{8106F039-D132-4F87-8AFE-ADE47B5503D4}" # Variables globales para BaseWS: HOMO = HOMO WSDL = WSDL Version = "%s %s" % (__version__, HOMO and 'Homologación' or '') factura = None def inicializar(self): BaseWS.inicializar(self) self.AppServerStatus = self.DbServerStatus = self.AuthServerStatus = None self.Resultado = self.Motivo = self.Reproceso = '' self.LastID = self.LastCMP = self.CAE = self.Vencimiento = '' self.CbteNro = self.FechaCbte = self.PuntoVenta = self.ImpTotal = None self.InstallDir = INSTALL_DIR self.FchVencCAE = "" # retrocompatibilidad def __analizar_errores(self, ret): "Comprueba y extrae errores si existen en la respuesta XML" if 'FEXErr' in ret: errores = [ret['FEXErr']] for error in errores: self.Errores.append("%s: %s" % ( error['ErrCode'], error['ErrMsg'], )) self.ErrCode = ' '.join([str(error['ErrCode']) for error in errores]) self.ErrMsg = '\n'.join(self.Errores) if 'FEXEvents' in ret: events = [ret['FEXEvents']] self.Eventos = ['%s: %s' % (evt['EventCode'], evt.get('EventMsg',"")) for evt in events] def CrearFactura(self, tipo_cbte=19, punto_vta=1, cbte_nro=0, fecha_cbte=None, imp_total=0.0, tipo_expo=1, permiso_existente="N", pais_dst_cmp=None, nombre_cliente="", cuit_pais_cliente="", domicilio_cliente="", id_impositivo="", moneda_id="PES", moneda_ctz=1.0, obs_comerciales="", obs_generales="", forma_pago="", incoterms="", idioma_cbte=7, incoterms_ds=None, **kwargs): "Creo un objeto factura (interna)" # Creo una factura electronica de exportación fact = {'tipo_cbte': tipo_cbte, 'punto_vta': punto_vta, 'cbte_nro': cbte_nro, 'fecha_cbte': fecha_cbte, 'tipo_doc': 80, 'nro_doc': cuit_pais_cliente, 'imp_total': imp_total, 'permiso_existente': permiso_existente, 'pais_dst_cmp': pais_dst_cmp, 'nombre_cliente': nombre_cliente, 'domicilio_cliente': domicilio_cliente, 'id_impositivo': id_impositivo, 'moneda_id': moneda_id, 'moneda_ctz': moneda_ctz, 'obs_comerciales': obs_comerciales, 'obs_generales': obs_generales, 'forma_pago': forma_pago, 'incoterms': incoterms, 'incoterms_ds': incoterms_ds, 'tipo_expo': tipo_expo, 'idioma_cbte': idioma_cbte, 'cbtes_asoc': [], 'permisos': [], 'detalles': [], } self.factura = fact return True def AgregarItem(self, codigo, ds, qty, umed, precio, importe, bonif=None, **kwargs): "Agrego un item a una factura (interna)" # Nota: no se calcula total (debe venir calculado!) self.factura['detalles'].append({ 'codigo': codigo, 'ds': ds, 'qty': qty, 'umed': umed, 'precio': precio, 'bonif': bonif, 'importe': importe, }) return True def AgregarPermiso(self, id_permiso, dst_merc, **kwargs): "Agrego un permiso a una factura (interna)" self.factura['permisos'].append({ 'id_permiso': id_permiso, 'dst_merc': dst_merc, }) return True def AgregarCmpAsoc(self, cbte_tipo=19, cbte_punto_vta=0, cbte_nro=0, cbte_cuit=None, **kwargs): "Agrego un comprobante asociado a una factura (interna)" self.factura['cbtes_asoc'].append({ 'cbte_tipo': cbte_tipo, 'cbte_punto_vta': cbte_punto_vta, 'cbte_nro': cbte_nro, 'cbte_cuit': cbte_cuit}) return True @inicializar_y_capturar_excepciones def Authorize(self, id): "Autoriza la factura cargada en memoria" f = self.factura ret = self.client.FEXAuthorize( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit}, Cmp={ 'Id': id, 'Fecha_cbte': f['fecha_cbte'], 'Cbte_Tipo': f['tipo_cbte'], 'Punto_vta': f['punto_vta'], 'Cbte_nro': f['cbte_nro'], 'Tipo_expo': f['tipo_expo'], 'Permiso_existente': f['permiso_existente'], 'Permisos': f['permisos'] and [ {'Permiso': { 'Id_permiso': p['id_permiso'], 'Dst_merc': p['dst_merc'], }} for p in f['permisos']] or None, 'Dst_cmp': f['pais_dst_cmp'], 'Cliente': f['nombre_cliente'], 'Cuit_pais_cliente': f['nro_doc'], 'Domicilio_cliente': f['domicilio_cliente'], 'Id_impositivo': f['id_impositivo'], 'Moneda_Id': f['moneda_id'], 'Moneda_ctz': f['moneda_ctz'], 'Obs_comerciales': f['obs_comerciales'], 'Imp_total': f['imp_total'], 'Obs': f['obs_generales'], 'Cmps_asoc': f['cbtes_asoc'] and [ {'Cmp_asoc': { 'Cbte_tipo': c['cbte_tipo'], 'Cbte_punto_vta': c['cbte_punto_vta'], 'Cbte_nro': c['cbte_nro'], 'Cbte_cuit': c['cbte_cuit'], }} for c in f['cbtes_asoc']] or None, 'Forma_pago': f['forma_pago'], 'Incoterms': f['incoterms'], 'Incoterms_Ds': f['incoterms_ds'], 'Idioma_cbte': f['idioma_cbte'], 'Items': [ {'Item': { 'Pro_codigo': d['codigo'], 'Pro_ds': d['ds'], 'Pro_qty': d['qty'], 'Pro_umed': d['umed'], 'Pro_precio_uni': d['precio'], 'Pro_bonificacion': d['bonif'], 'Pro_total_item': d['importe'], }} for d in f['detalles']], }) result = ret['FEXAuthorizeResult'] self.__analizar_errores(result) if 'FEXResultAuth' in result: auth = result['FEXResultAuth'] # Resultado: A: Aceptado, R: Rechazado self.Resultado = auth.get('Resultado', "") # Obs: self.Obs = auth.get('Motivos_Obs', "") self.Reproceso = auth.get('Reproceso', "") self.CAE = auth.get('Cae', "") self.CbteNro = auth.get('Cbte_nro', "") vto = str(auth.get('Fch_venc_Cae', "")) self.FchVencCAE = vto self.Vencimiento = "%s/%s/%s" % (vto[6:8], vto[4:6], vto[0:4]) return self.CAE @inicializar_y_capturar_excepciones def Dummy(self): "Obtener el estado de los servidores de la AFIP" result = self.client.FEXDummy()['FEXDummyResult'] self.__analizar_errores(result) self.AppServerStatus = str(result['AppServer']) self.DbServerStatus = str(result['DbServer']) self.AuthServerStatus = str(result['AuthServer']) return True @inicializar_y_capturar_excepciones def GetCMP(self, tipo_cbte, punto_vta, cbte_nro): "Recuperar los datos completos de un comprobante ya autorizado" ret = self.client.FEXGetCMP( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit}, Cmp={ 'Cbte_tipo': tipo_cbte, 'Punto_vta': punto_vta, 'Cbte_nro': cbte_nro, }) result = ret['FEXGetCMPResult'] self.__analizar_errores(result) if 'FEXResultGet' in result: resultget = result['FEXResultGet'] # Obs, cae y fecha cae self.Obs = resultget.get('Obs') and resultget['Obs'].strip(" ") or '' self.CAE = resultget.get('Cae', '') vto = str(resultget.get('Fch_venc_Cae', '')) self.Vencimiento = "%s/%s/%s" % (vto[6:8], vto[4:6], vto[0:4]) self.FechaCbte = resultget.get('Fecha_cbte', '') #.strftime("%Y/%m/%d") self.PuntoVenta = resultget['Punto_vta'] # 4000 self.Resultado = resultget.get('Resultado', '') self.CbteNro =resultget['Cbte_nro'] self.ImpTotal = str(resultget['Imp_total']) return self.CAE else: return 0 @inicializar_y_capturar_excepciones def GetLastCMP(self, tipo_cbte, punto_vta): "Recuperar último número de comprobante emitido" ret = self.client.FEXGetLast_CMP( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, 'Cbte_Tipo': tipo_cbte, 'Pto_venta': punto_vta, }) result = ret['FEXGetLast_CMPResult'] self.__analizar_errores(result) if 'FEXResult_LastCMP' in result: resultget = result['FEXResult_LastCMP'] self.CbteNro =resultget.get('Cbte_nro') self.FechaCbte = resultget.get('Cbte_fecha') #.strftime("%Y/%m/%d") return self.CbteNro @inicializar_y_capturar_excepciones def GetLastID(self): "Recuperar último número de transacción (ID)" ret = self.client.FEXGetLast_ID( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, }) result = ret['FEXGetLast_IDResult'] self.__analizar_errores(result) if 'FEXResultGet' in result: resultget = result['FEXResultGet'] return resultget.get('Id') @inicializar_y_capturar_excepciones def GetParamUMed(self, sep="|"): ret = self.client.FEXGetPARAM_UMed( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, }) result = ret['FEXGetPARAM_UMedResult'] self.__analizar_errores(result) umeds = [] # unidades de medida for u in result['FEXResultGet']: u = u['ClsFEXResponse_UMed'] try: umed = {'id': u.get('Umed_Id'), 'ds': u.get('Umed_Ds'), 'vig_desde': u.get('Umed_vig_desde'), 'vig_hasta': u.get('Umed_vig_hasta')} except Exception, e: print e if u is None: # <ClsFEXResponse_UMed xsi:nil="true"/> WTF! umed = {'id':'', 'ds':'','vig_desde':'','vig_hasta':''} #import pdb; pdb.set_trace() #print u umeds.append(umed) if sep: return [("\t%(id)s\t%(ds)s\t%(vig_desde)s\t%(vig_hasta)s\t" % it).replace("\t", sep) for it in umeds] else: return umeds @inicializar_y_capturar_excepciones def GetParamMon(self, sep="|"): ret = self.client.FEXGetPARAM_MON( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, }) result = ret['FEXGetPARAM_MONResult'] self.__analizar_errores(result) mons = [] # monedas for u in result['FEXResultGet']: u = u['ClsFEXResponse_Mon'] try: mon = {'id': u.get('Mon_Id'), 'ds': u.get('Mon_Ds'), 'vig_desde': u.get('Mon_vig_desde'), 'vig_hasta': u.get('Mon_vig_hasta')} except Exception, e: print e if u is None: # <ClsFEXResponse_UMed xsi:nil="true"/> WTF! mon = {'id':'', 'ds':'','vig_desde':'','vig_hasta':''} #import pdb; pdb.set_trace() #print u mons.append(mon) if sep: return [("\t%(id)s\t%(ds)s\t%(vig_desde)s\t%(vig_hasta)s\t" % it).replace("\t", sep) for it in mons] else: return mons @inicializar_y_capturar_excepciones def GetParamDstPais(self, sep="|"): "Recuperador de valores referenciales de códigos de Países" ret = self.client.FEXGetPARAM_DST_pais( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, }) result = ret['FEXGetPARAM_DST_paisResult'] self.__analizar_errores(result) ret = [] for u in result['FEXResultGet']: u = u['ClsFEXResponse_DST_pais'] try: r = {'codigo': u.get('DST_Codigo'), 'ds': u.get('DST_Ds'), } except Exception, e: print e ret.append(r) if sep: return [("\t%(codigo)s\t%(ds)s\t" % it).replace("\t", sep) for it in ret] else: return ret @inicializar_y_capturar_excepciones def GetParamDstCUIT(self, sep="|"): "Recuperar lista de valores referenciales de CUIT de Países" ret = self.client.FEXGetPARAM_DST_CUIT( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, }) result = ret['FEXGetPARAM_DST_CUITResult'] self.__analizar_errores(result) ret = [] for u in result['FEXResultGet']: u = u['ClsFEXResponse_DST_cuit'] try: r = {'codigo': u.get('DST_CUIT'), 'ds': u.get('DST_Ds'), } except Exception, e: print e ret.append(r) if sep: return [("\t%(codigo)s\t%(ds)s\t" % it).replace("\t", sep) for it in ret] else: return ret @inicializar_y_capturar_excepciones def GetParamTipoCbte(self, sep="|"): "Recuperador de valores referenciales de códigos de Tipo de comprobantes" ret = self.client.FEXGetPARAM_Cbte_Tipo( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, }) result = ret['FEXGetPARAM_Cbte_TipoResult'] self.__analizar_errores(result) ret = [] for u in result['FEXResultGet']: u = u['ClsFEXResponse_Cbte_Tipo'] try: r = {'codigo': u.get('Cbte_Id'), 'ds': u.get('Cbte_Ds').replace('\n', '').replace('\r', ''), 'vig_desde': u.get('Cbte_vig_desde'), 'vig_hasta': u.get('Cbte_vig_hasta')} except Exception, e: print e ret.append(r) if sep: return [("\t%(codigo)s\t%(ds)s\t%(vig_desde)s\t%(vig_hasta)s\t" % it).replace("\t", sep) for it in ret] else: return ret @inicializar_y_capturar_excepciones def GetParamTipoExpo(self, sep="|"): "Recuperador de valores referenciales de códigos de Tipo de exportación" ret = self.client.FEXGetPARAM_Tipo_Expo( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, }) result = ret['FEXGetPARAM_Tipo_ExpoResult'] self.__analizar_errores(result) ret = [] for u in result['FEXResultGet']: u = u['ClsFEXResponse_Tex'] try: r = {'codigo': u.get('Tex_Id'), 'ds': u.get('Tex_Ds'), 'vig_desde': u.get('Tex_vig_desde'), 'vig_hasta': u.get('Tex_vig_hasta')} except Exception, e: print e ret.append(r) if sep: return [("\t%(codigo)s\t%(ds)s\t%(vig_desde)s\t%(vig_hasta)s\t" % it).replace("\t", sep) for it in ret] else: return ret @inicializar_y_capturar_excepciones def GetParamIdiomas(self, sep="|"): "Recuperar lista de valores referenciales de códigos de Idiomas" ret = self.client.FEXGetPARAM_Idiomas( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, }) result = ret['FEXGetPARAM_IdiomasResult'] self.__analizar_errores(result) ret = [] for u in result['FEXResultGet']: u = u['ClsFEXResponse_Idi'] try: r = {'codigo': u.get('Idi_Id'), 'ds': u.get('Idi_Ds'), 'vig_desde': u.get('Idi_vig_hasta'), 'vig_hasta': u.get('Idi_vig_desde')} except Exception, e: print e ret.append(r) if sep: return [("\t%(codigo)s\t%(ds)s\t%(vig_desde)s\t%(vig_hasta)s\t" % it).replace("\t", sep) for it in ret] else: return ret def GetParamIncoterms(self, sep="|"): "Recuperar lista de valores referenciales de Incoterms" ret = self.client.FEXGetPARAM_Incoterms( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit, }) result = ret['FEXGetPARAM_IncotermsResult'] self.__analizar_errores(result) ret = [] for u in result['FEXResultGet']: u = u['ClsFEXResponse_Inc'] try: r = {'codigo': u.get('Inc_Id'), 'ds': u.get('Inc_Ds'), 'vig_desde': u.get('Inc_vig_hasta'), 'vig_hasta': u.get('Inc_vig_desde')} except Exception, e: print e ret.append(r) if sep: return [("\t%(codigo)s\t%(ds)s\t%(vig_desde)s\t%(vig_hasta)s\t" % it).replace("\t", sep) for it in ret] else: return ret @inicializar_y_capturar_excepciones def GetParamCtz(self, moneda_id): "Recuperador de cotización de moneda" ret = self.client.FEXGetPARAM_Ctz( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit}, Mon_id=moneda_id, ) self.__analizar_errores(ret['FEXGetPARAM_CtzResult']) res = ret['FEXGetPARAM_CtzResult'].get('FEXResultGet') if res: ctz = str(res.get('Mon_ctz',"")) else: ctz = '' return ctz @inicializar_y_capturar_excepciones def GetParamPtosVenta(self): "Recupera el listado de los puntos de venta para exportacion y estado" ret = self.client.FEXGetPARAM_PtoVenta( Auth={'Token': self.Token, 'Sign': self.Sign, 'Cuit': self.Cuit}, ) self.__analizar_errores(ret['FEXGetPARAM_PtoVentaResult']) res = ret['FEXGetPARAM_PtoVentaResult'].get('FEXResultGet') ret = [] for pu in res: p = pu['ClsFEXResponse_PtoVenta'] try: r = {'nro': u.get('Pve_Nro'), 'baja': u.get('Pve_FchBaj'), 'bloqueado': u.get('Pve_Bloqueado'), } except Exception, e: print e ret.append(r) return [(u"%(nro)s\tBloqueado:%(bloqueado)s\tFchBaja:%(baja)s" % r).replace("\t", sep) for r in ret] class WSFEX(WSFEXv1): "Wrapper para retrocompatibilidad con WSFEX" _reg_progid_ = "WSFEX" _reg_clsid_ = "{B3C8D3D3-D5DA-44C9-B003-11845803B2BD}" def __init__(self): WSFEXv1.__init__(self) self.Version = "%s %s WSFEXv1" % (__version__, HOMO and 'Homologación' or '') def Conectar(self, url="", proxy=""): # Ajustar URL de V0 a V1: if url in ("https://wswhomo.afip.gov.ar/wsfex/service.asmx", "http://wswhomo.afip.gov.ar/WSFEX/service.asmx"): url = "https://wswhomo.afip.gov.ar/wsfexv1/service.asmx" elif url in ("https://servicios1.afip.gov.ar/wsfex/service.asmx", "http://servicios1.afip.gov.ar/WSFEX/service.asmx"): url = "https://servicios1.afip.gov.ar/wsfexv1/service.asmx" return WSFEXv1.Conectar(self, cache=None, wsdl=url, proxy=proxy) # busco el directorio de instalación (global para que no cambie si usan otra dll) INSTALL_DIR = WSFEXv1.InstallDir = get_install_dir() def p_assert_eq(a,b): print a, a==b and '==' or '!=', b if __name__ == "__main__": if "--register" in sys.argv or "--unregister" in sys.argv: import win32com.server.register win32com.server.register.UseCommandLine(WSFEXv1) if '--wsfex' in sys.argv: win32com.server.register.UseCommandLine(WSFEX) #elif "/Automate" in sys.argv: # # MS seems to like /automate to run the class factories. # import win32com.server.localserver # #win32com.server.localserver.main() # # start the server. # win32com.server.localserver.serve([WSFEXv1._reg_clsid_]) else: # Crear objeto interface Web Service de Factura Electrónica de Exportación wsfexv1 = WSFEXv1() # Setear token y sing de autorización (pasos previos) # obteniendo el TA para pruebas from wsaa import WSAA ta = WSAA().Autenticar("wsfex", "reingart.crt", "reingart.key") wsfexv1.SetTicketAcceso(ta) # CUIT del emisor (debe estar registrado en la AFIP) wsfexv1.Cuit = "20267565393" # Conectar al Servicio Web de Facturación (homologación) wsdl = "http://wswhomo.afip.gov.ar/WSFEXv1/service.asmx" cache = proxy = "" wrapper = "httplib2" cacert = open("conf/afip_ca_info.crt").read() ok = wsfexv1.Conectar(cache, wsdl, proxy, wrapper, cacert) if '--dummy' in sys.argv: #wsfexv1.LanzarExcepciones = False print wsfexv1.Dummy() print wsfexv1.XmlRequest print wsfexv1.XmlResponse if "--prueba" in sys.argv: try: # Establezco los valores de la factura a autorizar: tipo_cbte = '--nc' in sys.argv and 21 or 19 # FC/NC Expo (ver tabla de parámetros) punto_vta = 7 # Obtengo el último número de comprobante y le agrego 1 cbte_nro = int(wsfexv1.GetLastCMP(tipo_cbte, punto_vta)) + 1 fecha_cbte = datetime.datetime.now().strftime("%Y%m%d") tipo_expo = 1 # tipo de exportación (ver tabla de parámetros) permiso_existente = (tipo_cbte not in (20, 21) or tipo_expo!=1) and "S" or "" print "permiso_existente", permiso_existente dst_cmp = 203 # país destino cliente = "Joao Da Silva" cuit_pais_cliente = "50000000016" domicilio_cliente = u"Rúa Ñ°76 km 34.5 Alagoas" id_impositivo = "PJ54482221-l" moneda_id = "DOL" # para reales, "DOL" o "PES" (ver tabla de parámetros) moneda_ctz = "8.00" # wsfexv1.GetParamCtz('DOL') <- no funciona obs_comerciales = "Observaciones comerciales" obs = "Sin observaciones" forma_pago = "30 dias" incoterms = "FOB" # (ver tabla de parámetros) incoterms_ds = "Flete a Bordo" idioma_cbte = 1 # (ver tabla de parámetros) imp_total = "250.00" # Creo una factura (internamente, no se llama al WebService): ok = wsfexv1.CrearFactura(tipo_cbte, punto_vta, cbte_nro, fecha_cbte, imp_total, tipo_expo, permiso_existente, dst_cmp, cliente, cuit_pais_cliente, domicilio_cliente, id_impositivo, moneda_id, moneda_ctz, obs_comerciales, obs, forma_pago, incoterms, idioma_cbte, incoterms_ds) # Agrego un item: codigo = "PRO1" ds = "Producto Tipo 1 Exportacion MERCOSUR ISO 9001" qty = 2 precio = "150.00" umed = 1 # Ver tabla de parámetros (unidades de medida) bonif = "50.00" imp_total = "250.00" # importe total final del artículo # lo agrego a la factura (internamente, no se llama al WebService): ok = wsfexv1.AgregarItem(codigo, ds, qty, umed, precio, imp_total, bonif) ok = wsfexv1.AgregarItem(codigo, ds, qty, umed, precio, imp_total, bonif) ok = wsfexv1.AgregarItem(codigo, ds, 0, 99, 0, -float(imp_total), 0) # Agrego un permiso (ver manual para el desarrollador) if permiso_existente: id = "99999AAXX999999A" dst = 225 # país destino de la mercaderia ok = wsfexv1.AgregarPermiso(id, dst) # Agrego un comprobante asociado (solo para N/C o N/D) if tipo_cbte in (20,21): cbteasoc_tipo = 19 cbteasoc_pto_vta = 2 cbteasoc_nro = 1234 cbteasoc_cuit = 20111111111 wsfexv1.AgregarCmpAsoc(cbteasoc_tipo, cbteasoc_pto_vta, cbteasoc_nro, cbteasoc_cuit) ##id = "99000000000100" # número propio de transacción # obtengo el último ID y le adiciono 1 # (advertencia: evitar overflow y almacenar!) id = long(wsfexv1.GetLastID()) + 1 # Llamo al WebService de Autorización para obtener el CAE cae = wsfexv1.Authorize(id) print "Comprobante", tipo_cbte, wsfexv1.CbteNro print "Resultado", wsfexv1.Resultado print "CAE", wsfexv1.CAE print "Vencimiento", wsfexv1.Vencimiento if wsfexv1.Resultado and False: print wsfexv1.client.help("FEXGetCMP").encode("latin1") wsfexv1.GetCMP(tipo_cbte, punto_vta, cbte_nro) print "CAE consulta", wsfexv1.CAE, wsfexv1.CAE==cae print "NRO consulta", wsfexv1.CbteNro, wsfexv1.CbteNro==cbte_nro print "TOTAL consulta", wsfexv1.ImpTotal, wsfexv1.ImpTotal==imp_total except Exception, e: print wsfexv1.XmlRequest print wsfexv1.XmlResponse print wsfexv1.ErrCode print wsfexv1.ErrMsg print wsfexv1.Excepcion print wsfexv1.Traceback raise if "--get" in sys.argv: wsfexv1.client.help("FEXGetCMP") tipo_cbte = 19 punto_vta = 7 cbte_nro = wsfexv1.GetLastCMP(tipo_cbte, punto_vta) wsfexv1.GetCMP(tipo_cbte, punto_vta, cbte_nro) print "FechaCbte = ", wsfexv1.FechaCbte print "CbteNro = ", wsfexv1.CbteNro print "PuntoVenta = ", wsfexv1.PuntoVenta print "ImpTotal =", wsfexv1.ImpTotal print "CAE = ", wsfexv1.CAE print "Vencimiento = ", wsfexv1.Vencimiento wsfexv1.AnalizarXml("XmlResponse") p_assert_eq(wsfexv1.ObtenerTagXml('Cae'), str(wsfexv1.CAE)) p_assert_eq(wsfexv1.ObtenerTagXml('Fecha_cbte'), wsfexv1.FechaCbte) p_assert_eq(wsfexv1.ObtenerTagXml('Moneda_Id'), "DOL") p_assert_eq(wsfexv1.ObtenerTagXml('Moneda_ctz'), "8") p_assert_eq(wsfexv1.ObtenerTagXml('Id_impositivo'), "PJ54482221-l") if "--params" in sys.argv: import codecs, locale sys.stdout = codecs.getwriter('latin1')(sys.stdout); print "=== Incoterms ===" idiomas = wsfexv1.GetParamIncoterms(sep="||") for idioma in idiomas: print idioma print "=== Idiomas ===" idiomas = wsfexv1.GetParamIdiomas(sep="||") for idioma in idiomas: print idioma print "=== Tipos Comprobantes ===" tipos = wsfexv1.GetParamTipoCbte(sep=False) for t in tipos: print "||%(codigo)s||%(ds)s||" % t print "=== Tipos Expo ===" tipos = wsfexv1.GetParamTipoExpo(sep=False) for t in tipos: print "||%(codigo)s||%(ds)s||%(vig_desde)s||%(vig_hasta)s||" % t #umeds = dict([(u.get('id', ""),u.get('ds', "")) for u in umedidas]) print "=== Monedas ===" mons = wsfexv1.GetParamMon(sep=False) for m in mons: print "||%(id)s||%(ds)s||%(vig_desde)s||%(vig_hasta)s||" % m #umeds = dict([(u.get('id', ""),u.get('ds', "")) for u in umedidas]) print "=== Unidades de medida ===" umedidas = wsfexv1.GetParamUMed(sep=False) for u in umedidas: print "||%(id)s||%(ds)s||%(vig_desde)s||%(vig_hasta)s||" % u umeds = dict([(u.get('id', ""),u.get('ds', "")) for u in umedidas]) print u"=== Código Pais Destino ===" ret = wsfexv1.GetParamDstPais(sep=False) for r in ret: print "||%(codigo)s||%(ds)s||" % r print u"=== CUIT Pais Destino ===" ret = wsfexv1.GetParamDstCUIT(sep=False) for r in ret: print "||%(codigo)s||%(ds)s||" % r if "--ctz" in sys.argv: print wsfexv1.GetParamCtz('DOL') if "--ptosventa" in sys.argv: print wsfexv1.GetParamPtosVenta()
gpl-3.0
9,018,860,600,986,043,000
41.500659
104
0.507678
false
belltailjp/scikit-learn
sklearn/decomposition/base.py
313
5647
"""Principal Component Analysis Base Classes""" # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Olivier Grisel <olivier.grisel@ensta.org> # Mathieu Blondel <mathieu@mblondel.org> # Denis A. Engemann <d.engemann@fz-juelich.de> # Kyle Kastner <kastnerkyle@gmail.com> # # License: BSD 3 clause import numpy as np from scipy import linalg from ..base import BaseEstimator, TransformerMixin from ..utils import check_array from ..utils.extmath import fast_dot from ..utils.validation import check_is_fitted from ..externals import six from abc import ABCMeta, abstractmethod class _BasePCA(six.with_metaclass(ABCMeta, BaseEstimator, TransformerMixin)): """Base class for PCA methods. Warning: This class should not be used directly. Use derived classes instead. """ def get_covariance(self): """Compute data covariance with the generative model. ``cov = components_.T * S**2 * components_ + sigma2 * eye(n_features)`` where S**2 contains the explained variances, and sigma2 contains the noise variances. Returns ------- cov : array, shape=(n_features, n_features) Estimated covariance of data. """ components_ = self.components_ exp_var = self.explained_variance_ if self.whiten: components_ = components_ * np.sqrt(exp_var[:, np.newaxis]) exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) cov = np.dot(components_.T * exp_var_diff, components_) cov.flat[::len(cov) + 1] += self.noise_variance_ # modify diag inplace return cov def get_precision(self): """Compute data precision matrix with the generative model. Equals the inverse of the covariance but computed with the matrix inversion lemma for efficiency. Returns ------- precision : array, shape=(n_features, n_features) Estimated precision of data. """ n_features = self.components_.shape[1] # handle corner cases first if self.n_components_ == 0: return np.eye(n_features) / self.noise_variance_ if self.n_components_ == n_features: return linalg.inv(self.get_covariance()) # Get precision using matrix inversion lemma components_ = self.components_ exp_var = self.explained_variance_ if self.whiten: components_ = components_ * np.sqrt(exp_var[:, np.newaxis]) exp_var_diff = np.maximum(exp_var - self.noise_variance_, 0.) precision = np.dot(components_, components_.T) / self.noise_variance_ precision.flat[::len(precision) + 1] += 1. / exp_var_diff precision = np.dot(components_.T, np.dot(linalg.inv(precision), components_)) precision /= -(self.noise_variance_ ** 2) precision.flat[::len(precision) + 1] += 1. / self.noise_variance_ return precision @abstractmethod def fit(X, y=None): """Placeholder for fit. Subclasses should implement this method! Fit the model with X. Parameters ---------- X : array-like, shape (n_samples, n_features) Training data, where n_samples is the number of samples and n_features is the number of features. Returns ------- self : object Returns the instance itself. """ def transform(self, X, y=None): """Apply dimensionality reduction to X. X is projected on the first principal components previously extracted from a training set. Parameters ---------- X : array-like, shape (n_samples, n_features) New data, where n_samples is the number of samples and n_features is the number of features. Returns ------- X_new : array-like, shape (n_samples, n_components) Examples -------- >>> import numpy as np >>> from sklearn.decomposition import IncrementalPCA >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> ipca = IncrementalPCA(n_components=2, batch_size=3) >>> ipca.fit(X) IncrementalPCA(batch_size=3, copy=True, n_components=2, whiten=False) >>> ipca.transform(X) # doctest: +SKIP """ check_is_fitted(self, ['mean_', 'components_'], all_or_any=all) X = check_array(X) if self.mean_ is not None: X = X - self.mean_ X_transformed = fast_dot(X, self.components_.T) if self.whiten: X_transformed /= np.sqrt(self.explained_variance_) return X_transformed def inverse_transform(self, X, y=None): """Transform data back to its original space. In other words, return an input X_original whose transform would be X. Parameters ---------- X : array-like, shape (n_samples, n_components) New data, where n_samples is the number of samples and n_components is the number of components. Returns ------- X_original array-like, shape (n_samples, n_features) Notes ----- If whitening is enabled, inverse_transform will compute the exact inverse operation, which includes reversing whitening. """ if self.whiten: return fast_dot(X, np.sqrt(self.explained_variance_[:, np.newaxis]) * self.components_) + self.mean_ else: return fast_dot(X, self.components_) + self.mean_
bsd-3-clause
-5,669,231,022,497,587,000
33.858025
81
0.59359
false
WinterNis/sqlalchemy
test/sql/test_ddlemit.py
27
8886
from sqlalchemy.testing import fixtures from sqlalchemy.sql.ddl import SchemaGenerator, SchemaDropper from sqlalchemy import MetaData, Table, Column, Integer, Sequence, ForeignKey from sqlalchemy import schema from sqlalchemy.testing.mock import Mock class EmitDDLTest(fixtures.TestBase): def _mock_connection(self, item_exists): def has_item(connection, name, schema): return item_exists(name) return Mock(dialect=Mock( supports_sequences=True, has_table=Mock(side_effect=has_item), has_sequence=Mock(side_effect=has_item) ) ) def _mock_create_fixture(self, checkfirst, tables, item_exists=lambda item: False): connection = self._mock_connection(item_exists) return SchemaGenerator(connection.dialect, connection, checkfirst=checkfirst, tables=tables) def _mock_drop_fixture(self, checkfirst, tables, item_exists=lambda item: True): connection = self._mock_connection(item_exists) return SchemaDropper(connection.dialect, connection, checkfirst=checkfirst, tables=tables) def _table_fixture(self): m = MetaData() return (m, ) + tuple( Table('t%d' % i, m, Column('x', Integer)) for i in range(1, 6) ) def _use_alter_fixture_one(self): m = MetaData() t1 = Table( 't1', m, Column('id', Integer, primary_key=True), Column('t2id', Integer, ForeignKey('t2.id')) ) t2 = Table( 't2', m, Column('id', Integer, primary_key=True), Column('t1id', Integer, ForeignKey('t1.id')) ) return m, t1, t2 def _fk_fixture_one(self): m = MetaData() t1 = Table( 't1', m, Column('id', Integer, primary_key=True), Column('t2id', Integer, ForeignKey('t2.id')) ) t2 = Table( 't2', m, Column('id', Integer, primary_key=True), ) return m, t1, t2 def _table_seq_fixture(self): m = MetaData() s1 = Sequence('s1') s2 = Sequence('s2') t1 = Table('t1', m, Column("x", Integer, s1, primary_key=True)) t2 = Table('t2', m, Column("x", Integer, s2, primary_key=True)) return m, t1, t2, s1, s2 def test_create_seq_checkfirst(self): m, t1, t2, s1, s2 = self._table_seq_fixture() generator = self._mock_create_fixture( True, [ t1, t2], item_exists=lambda t: t not in ( "t1", "s1")) self._assert_create([t1, s1], generator, m) def test_drop_seq_checkfirst(self): m, t1, t2, s1, s2 = self._table_seq_fixture() generator = self._mock_drop_fixture( True, [ t1, t2], item_exists=lambda t: t in ( "t1", "s1")) self._assert_drop([t1, s1], generator, m) def test_create_collection_checkfirst(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_create_fixture( True, [ t2, t3, t4], item_exists=lambda t: t not in ( "t2", "t4")) self._assert_create_tables([t2, t4], generator, m) def test_drop_collection_checkfirst(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_drop_fixture( True, [ t2, t3, t4], item_exists=lambda t: t in ( "t2", "t4")) self._assert_drop_tables([t2, t4], generator, m) def test_create_collection_nocheck(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_create_fixture( False, [ t2, t3, t4], item_exists=lambda t: t not in ( "t2", "t4")) self._assert_create_tables([t2, t3, t4], generator, m) def test_create_empty_collection(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_create_fixture( True, [], item_exists=lambda t: t not in ( "t2", "t4")) self._assert_create_tables([], generator, m) def test_drop_empty_collection(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_drop_fixture( True, [], item_exists=lambda t: t in ( "t2", "t4")) self._assert_drop_tables([], generator, m) def test_drop_collection_nocheck(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_drop_fixture( False, [ t2, t3, t4], item_exists=lambda t: t in ( "t2", "t4")) self._assert_drop_tables([t2, t3, t4], generator, m) def test_create_metadata_checkfirst(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_create_fixture( True, None, item_exists=lambda t: t not in ( "t2", "t4")) self._assert_create_tables([t2, t4], generator, m) def test_drop_metadata_checkfirst(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_drop_fixture( True, None, item_exists=lambda t: t in ( "t2", "t4")) self._assert_drop_tables([t2, t4], generator, m) def test_create_metadata_nocheck(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_create_fixture( False, None, item_exists=lambda t: t not in ( "t2", "t4")) self._assert_create_tables([t1, t2, t3, t4, t5], generator, m) def test_drop_metadata_nocheck(self): m, t1, t2, t3, t4, t5 = self._table_fixture() generator = self._mock_drop_fixture( False, None, item_exists=lambda t: t in ( "t2", "t4")) self._assert_drop_tables([t1, t2, t3, t4, t5], generator, m) def test_create_metadata_auto_alter_fk(self): m, t1, t2 = self._use_alter_fixture_one() generator = self._mock_create_fixture( False, [t1, t2] ) self._assert_create_w_alter( [t1, t2] + list(t1.foreign_key_constraints) + list(t2.foreign_key_constraints), generator, m ) def test_create_metadata_inline_fk(self): m, t1, t2 = self._fk_fixture_one() generator = self._mock_create_fixture( False, [t1, t2] ) self._assert_create_w_alter( [t1, t2] + list(t1.foreign_key_constraints) + list(t2.foreign_key_constraints), generator, m ) def _assert_create_tables(self, elements, generator, argument): self._assert_ddl(schema.CreateTable, elements, generator, argument) def _assert_drop_tables(self, elements, generator, argument): self._assert_ddl(schema.DropTable, elements, generator, argument) def _assert_create(self, elements, generator, argument): self._assert_ddl( (schema.CreateTable, schema.CreateSequence), elements, generator, argument) def _assert_drop(self, elements, generator, argument): self._assert_ddl( (schema.DropTable, schema.DropSequence), elements, generator, argument) def _assert_create_w_alter(self, elements, generator, argument): self._assert_ddl( (schema.CreateTable, schema.CreateSequence, schema.AddConstraint), elements, generator, argument) def _assert_drop_w_alter(self, elements, generator, argument): self._assert_ddl( (schema.DropTable, schema.DropSequence, schema.DropConstraint), elements, generator, argument) def _assert_ddl(self, ddl_cls, elements, generator, argument): generator.traverse_single(argument) for call_ in generator.connection.execute.mock_calls: c = call_[1][0] assert isinstance(c, ddl_cls) assert c.element in elements, "element %r was not expected"\ % c.element elements.remove(c.element) if getattr(c, 'include_foreign_key_constraints', None) is not None: elements[:] = [ e for e in elements if e not in set(c.include_foreign_key_constraints)] assert not elements, "elements remain in list: %r" % elements
mit
-915,979,538,789,082,900
32.659091
79
0.530948
false
overtherain/scriptfile
software/googleAppEngine/lib/django_1_3/django/utils/daemonize.py
452
1907
import os import sys if os.name == 'posix': def become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null', umask=022): "Robustly turn into a UNIX daemon, running in our_home_dir." # First fork try: if os.fork() > 0: sys.exit(0) # kill off parent except OSError, e: sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror)) sys.exit(1) os.setsid() os.chdir(our_home_dir) os.umask(umask) # Second fork try: if os.fork() > 0: os._exit(0) except OSError, e: sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror)) os._exit(1) si = open('/dev/null', 'r') so = open(out_log, 'a+', 0) se = open(err_log, 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # Set custom file descriptors so that they get proper buffering. sys.stdout, sys.stderr = so, se else: def become_daemon(our_home_dir='.', out_log=None, err_log=None, umask=022): """ If we're not running under a POSIX system, just simulate the daemon mode by doing redirections and directory changing. """ os.chdir(our_home_dir) os.umask(umask) sys.stdin.close() sys.stdout.close() sys.stderr.close() if err_log: sys.stderr = open(err_log, 'a', 0) else: sys.stderr = NullDevice() if out_log: sys.stdout = open(out_log, 'a', 0) else: sys.stdout = NullDevice() class NullDevice: "A writeable object that writes to nowhere -- like /dev/null." def write(self, s): pass
mit
1,644,142,384,879,278,800
31.87931
81
0.513896
false
jmiseikis/HomeAutomation
node_modules/socket.io/node_modules/engine.io/node_modules/engine.io-parser/node_modules/utf8/tests/generate-test-data.py
2214
1347
#!/usr/bin/env python import re import json # http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae # http://stackoverflow.com/a/13436167/96656 def unisymbol(codePoint): if codePoint >= 0x0000 and codePoint <= 0xFFFF: return unichr(codePoint) elif codePoint >= 0x010000 and codePoint <= 0x10FFFF: highSurrogate = int((codePoint - 0x10000) / 0x400) + 0xD800 lowSurrogate = int((codePoint - 0x10000) % 0x400) + 0xDC00 return unichr(highSurrogate) + unichr(lowSurrogate) else: return 'Error' def hexify(codePoint): return 'U+' + hex(codePoint)[2:].upper().zfill(6) def writeFile(filename, contents): print filename with open(filename, 'w') as f: f.write(contents.strip() + '\n') data = [] for codePoint in range(0x000000, 0x10FFFF + 1): symbol = unisymbol(codePoint) # http://stackoverflow.com/a/17199950/96656 bytes = symbol.encode('utf8').decode('latin1') data.append({ 'codePoint': codePoint, 'decoded': symbol, 'encoded': bytes }); jsonData = json.dumps(data, sort_keys=False, indent=2, separators=(',', ': ')) # Use tabs instead of double spaces for indentation jsonData = jsonData.replace(' ', '\t') # Escape hexadecimal digits in escape sequences jsonData = re.sub( r'\\u([a-fA-F0-9]{4})', lambda match: r'\u{}'.format(match.group(1).upper()), jsonData ) writeFile('data.json', jsonData)
mit
3,808,997,447,876,716,000
27.659574
78
0.703786
false
dphiggs01/ask_amy
ask_amy/cli/cli_deploy.py
1
10749
import json from subprocess import Popen, PIPE import os import shutil import sys from ask_amy.cli.code_gen.code_generator import CodeGenerator from time import sleep class DeployCLI(object): def create_template(self, skill_name, aws_role='', intent_schema_nm=None): with open(intent_schema_nm) as json_data: intent_schema = json.load(json_data) code_generator = CodeGenerator(skill_name, aws_role, intent_schema) code_generator.create_cli_config() code_generator.create_skill_config() code_generator.create_skill_py() def create_role(self, role_name): base_dir = self.module_path() role_json = 'file://' + base_dir + '/code_gen/templates/alexa_lambda_role.json' iam_create_role = self.run(self.iam_create_role, role_name, role_json) iam_attach_policy_cloud_watch = self.run(self.iam_attach_role_policy, role_name, 'arn:aws:iam::aws:policy/CloudWatchLogsFullAccess') iam_attach_policy_dynamo = self.run(self.iam_attach_role_policy, role_name, 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess') response_dict = {'iam_create_role': iam_create_role, 'iam_attach_policy_dynamo': iam_attach_policy_dynamo, 'iam_attach_policy_cloud_watch': iam_attach_policy_cloud_watch} return json.dumps(response_dict, indent=4) def deploy_lambda(self, config_file_name): deploy_dict = self.stage_to_dist(config_file_name) aws_region = deploy_dict['aws_region'] skill_name = deploy_dict['skill_name'] lambda_zip = 'fileb://' + deploy_dict['skill_home_dir'] + '/' + deploy_dict['lambda_zip'] aws_profile = deploy_dict['aws_profile'] deploy_response = self.run(self.lamabda_update_function, aws_region, skill_name, lambda_zip, aws_profile) return json.dumps(deploy_response, indent=4) def create_lambda(self, config_file_name): deploy_dict = self.stage_to_dist(config_file_name) skill_name = deploy_dict['skill_name'] lambda_runtime = deploy_dict['lambda_runtime'] aws_role = deploy_dict['aws_role'] lambda_handler = deploy_dict['lambda_handler'] lambda_timeout = deploy_dict['lambda_timeout'] lambda_memory = deploy_dict['lambda_memory'] lambda_zip = 'fileb://' + deploy_dict['skill_home_dir'] + '/' + deploy_dict['lambda_zip'] create_function_out = self.run(self.lambda_create_function, skill_name, lambda_runtime, aws_role, lambda_handler, skill_name, lambda_timeout, lambda_memory, lambda_zip) add_trigger_out = self.run(self.lambda_add_trigger, skill_name) response_dict = {'create_function': create_function_out, 'add_trigger': add_trigger_out} return json.dumps(response_dict, indent=4) def stage_to_dist(self, config_file_name): deploy_dict = self.load_json_file(config_file_name) skill_home_dir = deploy_dict['skill_home_dir'] distribution_dir = skill_home_dir + '/dist' ask_amy_impl = None if 'ask_amy_dev' in deploy_dict: if deploy_dict['ask_amy_dev']: # set to true ask_amy_home_dir = deploy_dict['ask_amy_home_dir'] ask_amy_impl = ask_amy_home_dir + '/ask_amy' self.install_ask_amy(distribution_dir, ask_amy_impl) self.copy_skill_to_dist(skill_home_dir, distribution_dir) self.make_zipfile(deploy_dict['lambda_zip'], distribution_dir) return deploy_dict def log(self, log_group_name, log_stream_name=None, next_forward_token=None): if log_stream_name is None: log_stream_name = self.latest_log_stream_for_log_group(log_group_name) if next_forward_token is None: log_events_dict = self.run(self.cloudwatch_get_log_events, log_group_name, log_stream_name) else: log_events_dict = self.run(self.cloudwatch_get_log_events, log_group_name, log_stream_name, next_forward_token) next_forward_token = log_events_dict['nextForwardToken'] log_events_lst = log_events_dict['events'] for event_dict in log_events_lst: message = event_dict['message'] sys.stdout.write(message) return next_forward_token, log_stream_name def latest_log_stream_for_log_group(self, log_group_name): log_streams_dict = self.run(self.cloudwatch_latest_log_stream, log_group_name) log_streams = log_streams_dict['logStreams'] latest_stream = log_streams[-1] log_stream_name = latest_stream['logStreamName'] return log_stream_name def log_tail(self, log_group_name): next_forward_token, log_stream_name = self.log(log_group_name) not_done = True try: while not_done: sleep(1) next_forward_token, log_stream_name = self.log(log_group_name, log_stream_name, next_forward_token) except KeyboardInterrupt: pass return def install_ask_amy(self, destination_dir, source_dir=None): ask_amy_dist = destination_dir + '/ask_amy' try: shutil.rmtree(ask_amy_dist, ignore_errors=True) if source_dir is not None: shutil.copytree(source_dir, ask_amy_dist) else: #pip.main(['install', '--upgrade', 'ask_amy', '-t', destination_dir]) self.run(self.install_ask_amy_for_upload, destination_dir) except FileNotFoundError: sys.stderr.write("ERROR: path not found {}\n".format(source_dir)) sys.exit(-1) def copy_skill_to_dist(self, source_dir, destination_dir): files = os.listdir(source_dir) try: for file in files: full_path = source_dir + os.sep + file if file.endswith(".py"): shutil.copy(full_path, destination_dir) if file.endswith(".json"): shutil.copy(full_path, destination_dir) except FileNotFoundError: sys.stderr.write("ERROR: filename not found\n") sys.exit(-1) def make_zipfile(self, output_filename, source_dir): output_filename = output_filename[:-4] shutil.make_archive(output_filename, 'zip', source_dir) install_ask_amy_for_upload = ('pip', 'install', '--upgrade', 'ask_amy', '-t', 0 ) lamabda_update_function = ('aws', '--output', 'json', 'lambda', 'update-function-code', '--region', 0, '--function-name', 1, '--zip-file', 2, '--profile', 3 ) lambda_create_function = ('aws', '--output', 'json', 'lambda', 'create-function', '--function-name', 0, '--runtime', 1, '--role', 2, '--handler', 3, '--description', 4, '--timeout', 5, '--memory-size', 6, '--zip-file', 7 ) lambda_add_trigger = ('aws', '--output', 'json', 'lambda', 'add-permission', '--function-name', 0, '--statement-id', 'alexa_trigger', '--action', 'lambda:InvokeFunction', '--principal', 'alexa-appkit.amazon.com' ) cloudwatch_latest_log_stream = ('aws', '--output', 'json', 'logs', 'describe-log-streams', '--log-group-name', 0, '--order-by', 'LastEventTime' ) iam_create_role = ('aws', '--output', 'json', 'iam', 'create-role', '--role-name', 0, '--assume-role-policy-document', 1 ) iam_attach_role_policy = ('aws', '--output', 'json', 'iam', 'attach-role-policy', '--role-name', 0, '--policy-arn', 1 ) cloudwatch_get_log_events = ('aws', '--output', 'json', 'logs', 'get-log-events', '--log-group-name', 0, '--log-stream-name', 1, '--next-token', 2 ) def load_json_file(self, config_file_name): try: file_ptr_r = open(config_file_name, 'r') deploy_dict = json.load(file_ptr_r) file_ptr_r.close() except FileNotFoundError: sys.stderr.write("ERROR: filename not found {}\n".format(config_file_name)) sys.exit(-1) return deploy_dict def module_path(self): try: modpath = os.path.dirname(os.path.abspath(__file__)) except AttributeError: sys.stderr.write("ERROR: could not find the path to module") sys.exit(-1) # Turn pyc files into py files if we can if modpath.endswith('.pyc') and os.path.exists(modpath[:-1]): modpath = modpath[:-1] # Sort out symlinks modpath = os.path.realpath(modpath) return modpath def run(self, arg_list, *args): try: processed_args = self.process_args(arg_list, *args) process = Popen(processed_args, stdout=PIPE) out, err = process.communicate() out = str(out, 'utf-8') if not out: out = '{}' try: json_out = json.loads(out) except Exception: json_out = {} return json_out except Exception as e: sys.stderr.write("ERROR: command line error %s\n" % args) sys.stderr.write("ERROR: %s\n" % e) sys.exit(-1) def process_args(self, arg_tuple, *args): # process the arg arg_list = list(arg_tuple) for index in range(0, len(arg_list)): if type(arg_list[index]) == int: # substitue for args passed in if arg_list[index] < len(args): arg_list[index] = args[arg_list[index]] # if we have more substitutions than args passed delete the extras else: del arg_list[index - 1:] break return arg_list
apache-2.0
3,663,360,728,587,405,000
43.60166
140
0.533817
false
bewest/amforth
core/devices/at90usb647/device.py
5
13009
# Partname: AT90USB647 # generated automatically, do not edit MCUREGS = { 'WDTCSR': '&96', 'WDTCSR_WDIF': '$80', 'WDTCSR_WDIE': '$40', 'WDTCSR_WDP': '$27', 'WDTCSR_WDCE': '$10', 'WDTCSR_WDE': '$08', 'PORTA': '&34', 'DDRA': '&33', 'PINA': '&32', 'PORTB': '&37', 'DDRB': '&36', 'PINB': '&35', 'PORTC': '&40', 'DDRC': '&39', 'PINC': '&38', 'PORTD': '&43', 'DDRD': '&42', 'PIND': '&41', 'PORTE': '&46', 'DDRE': '&45', 'PINE': '&44', 'PORTF': '&49', 'DDRF': '&48', 'PINF': '&47', 'SREG': '&95', 'SREG_I': '$80', 'SREG_T': '$40', 'SREG_H': '$20', 'SREG_S': '$10', 'SREG_V': '$08', 'SREG_N': '$04', 'SREG_Z': '$02', 'SREG_C': '$01', 'SP': '&93', 'MCUCR': '&85', 'MCUCR_JTD': '$80', 'MCUCR_PUD': '$10', 'MCUCR_IVSEL': '$02', 'MCUCR_IVCE': '$01', 'MCUSR': '&84', 'MCUSR_JTRF': '$10', 'MCUSR_WDRF': '$08', 'MCUSR_BORF': '$04', 'MCUSR_EXTRF': '$02', 'MCUSR_PORF': '$01', 'XMCRA': '&116', 'XMCRA_SRE': '$80', 'XMCRA_SRL': '$70', 'XMCRA_SRW1': '$0C', 'XMCRA_SRW0': '$03', 'XMCRB': '&117', 'XMCRB_XMBK': '$80', 'XMCRB_XMM': '$07', 'OSCCAL': '&102', 'CLKPR': '&97', 'CLKPR_CLKPCE': '$80', 'CLKPR_CLKPS': '$0F', 'SMCR': '&83', 'SMCR_SM': '$0E', 'SMCR_SE': '$01', 'EIND': '&92', 'RAMPZ': '&91', 'GPIOR2': '&75', 'GPIOR2_GPIOR': '$FF', 'GPIOR1': '&74', 'GPIOR1_GPIOR': '$FF', 'GPIOR0': '&62', 'GPIOR0_GPIOR07': '$80', 'GPIOR0_GPIOR06': '$40', 'GPIOR0_GPIOR05': '$20', 'GPIOR0_GPIOR04': '$10', 'GPIOR0_GPIOR03': '$08', 'GPIOR0_GPIOR02': '$04', 'GPIOR0_GPIOR01': '$02', 'GPIOR0_GPIOR00': '$01', 'PRR1': '&101', 'PRR1_PRUSB': '$80', 'PRR1_PRTIM3': '$08', 'PRR1_PRUSART1': '$01', 'PRR0': '&100', 'PRR0_PRTWI': '$80', 'PRR0_PRTIM2': '$40', 'PRR0_PRTIM0': '$20', 'PRR0_PRTIM1': '$08', 'PRR0_PRSPI': '$04', 'PRR0_PRADC': '$01', 'TWAMR': '&189', 'TWAMR_TWAM': '$FE', 'TWBR': '&184', 'TWCR': '&188', 'TWCR_TWINT': '$80', 'TWCR_TWEA': '$40', 'TWCR_TWSTA': '$20', 'TWCR_TWSTO': '$10', 'TWCR_TWWC': '$08', 'TWCR_TWEN': '$04', 'TWCR_TWIE': '$01', 'TWSR': '&185', 'TWSR_TWS': '$F8', 'TWSR_TWPS': '$03', 'TWDR': '&187', 'TWAR': '&186', 'TWAR_TWA': '$FE', 'TWAR_TWGCE': '$01', 'SPCR': '&76', 'SPCR_SPIE': '$80', 'SPCR_SPE': '$40', 'SPCR_DORD': '$20', 'SPCR_MSTR': '$10', 'SPCR_CPOL': '$08', 'SPCR_CPHA': '$04', 'SPCR_SPR': '$03', 'SPSR': '&77', 'SPSR_SPIF': '$80', 'SPSR_WCOL': '$40', 'SPSR_SPI2X': '$01', 'SPDR': '&78', 'UDR1': '&206', 'UCSR1A': '&200', 'UCSR1A_RXC1': '$80', 'UCSR1A_TXC1': '$40', 'UCSR1A_UDRE1': '$20', 'UCSR1A_FE1': '$10', 'UCSR1A_DOR1': '$08', 'UCSR1A_UPE1': '$04', 'UCSR1A_U2X1': '$02', 'UCSR1A_MPCM1': '$01', 'UCSR1B': '&201', 'UCSR1B_RXCIE1': '$80', 'UCSR1B_TXCIE1': '$40', 'UCSR1B_UDRIE1': '$20', 'UCSR1B_RXEN1': '$10', 'UCSR1B_TXEN1': '$08', 'UCSR1B_UCSZ12': '$04', 'UCSR1B_RXB81': '$02', 'UCSR1B_TXB81': '$01', 'UCSR1C': '&202', 'UCSR1C_UMSEL1': '$C0', 'UCSR1C_UPM1': '$30', 'UCSR1C_USBS1': '$08', 'UCSR1C_UCSZ1': '$06', 'UCSR1C_UCPOL1': '$01', 'UBRR1': '&204', 'UEINT': '&244', 'UEBCHX': '&243', 'UEBCLX': '&242', 'UEDATX': '&241', 'UEIENX': '&240', 'UEIENX_FLERRE': '$80', 'UEIENX_NAKINE': '$40', 'UEIENX_NAKOUTE': '$10', 'UEIENX_RXSTPE': '$08', 'UEIENX_RXOUTE': '$04', 'UEIENX_STALLEDE': '$02', 'UEIENX_TXINE': '$01', 'UESTA1X': '&239', 'UESTA1X_CTRLDIR': '$04', 'UESTA1X_CURRBK': '$03', 'UESTA0X': '&238', 'UESTA0X_CFGOK': '$80', 'UESTA0X_OVERFI': '$40', 'UESTA0X_UNDERFI': '$20', 'UESTA0X_DTSEQ': '$0C', 'UESTA0X_NBUSYBK': '$03', 'UECFG1X': '&237', 'UECFG1X_EPSIZE': '$70', 'UECFG1X_EPBK': '$0C', 'UECFG1X_ALLOC': '$02', 'UECFG0X': '&236', 'UECFG0X_EPTYPE': '$C0', 'UECFG0X_EPDIR': '$01', 'UECONX': '&235', 'UECONX_STALLRQ': '$20', 'UECONX_STALLRQC': '$10', 'UECONX_RSTDT': '$08', 'UECONX_EPEN': '$01', 'UERST': '&234', 'UERST_EPRST': '$7F', 'UENUM': '&233', 'UEINTX': '&232', 'UEINTX_FIFOCON': '$80', 'UEINTX_NAKINI': '$40', 'UEINTX_RWAL': '$20', 'UEINTX_NAKOUTI': '$10', 'UEINTX_RXSTPI': '$08', 'UEINTX_RXOUTI': '$04', 'UEINTX_STALLEDI': '$02', 'UEINTX_TXINI': '$01', 'UDMFN': '&230', 'UDMFN_FNCERR': '$10', 'UDFNUM': '&228', 'UDADDR': '&227', 'UDADDR_ADDEN': '$80', 'UDADDR_UADD': '$7F', 'UDIEN': '&226', 'UDIEN_UPRSME': '$40', 'UDIEN_EORSME': '$20', 'UDIEN_WAKEUPE': '$10', 'UDIEN_EORSTE': '$08', 'UDIEN_SOFE': '$04', 'UDIEN_SUSPE': '$01', 'UDINT': '&225', 'UDINT_UPRSMI': '$40', 'UDINT_EORSMI': '$20', 'UDINT_WAKEUPI': '$10', 'UDINT_EORSTI': '$08', 'UDINT_SOFI': '$04', 'UDINT_SUSPI': '$01', 'UDCON': '&224', 'UDCON_LSM': '$04', 'UDCON_RMWKUP': '$02', 'UDCON_DETACH': '$01', 'OTGINT': '&223', 'OTGINT_STOI': '$20', 'OTGINT_HNPERRI': '$10', 'OTGINT_ROLEEXI': '$08', 'OTGINT_BCERRI': '$04', 'OTGINT_VBERRI': '$02', 'OTGINT_SRPI': '$01', 'OTGIEN': '&222', 'OTGIEN_STOE': '$20', 'OTGIEN_HNPERRE': '$10', 'OTGIEN_ROLEEXE': '$08', 'OTGIEN_BCERRE': '$04', 'OTGIEN_VBERRE': '$02', 'OTGIEN_SRPE': '$01', 'OTGCON': '&221', 'OTGCON_HNPREQ': '$20', 'OTGCON_SRPREQ': '$10', 'OTGCON_SRPSEL': '$08', 'OTGCON_VBUSHWC': '$04', 'OTGCON_VBUSREQ': '$02', 'OTGCON_VBUSRQC': '$01', 'OTGTCON': '&249', 'OTGTCON_OTGTCON_7': '$80', 'OTGTCON_PAGE': '$60', 'OTGTCON_VALUE_2': '$07', 'USBINT': '&218', 'USBINT_IDTI': '$02', 'USBINT_VBUSTI': '$01', 'USBSTA': '&217', 'USBSTA_SPEED': '$08', 'USBSTA_ID': '$02', 'USBSTA_VBUS': '$01', 'USBCON': '&216', 'USBCON_USBE': '$80', 'USBCON_HOST': '$40', 'USBCON_FRZCLK': '$20', 'USBCON_OTGPADE': '$10', 'USBCON_IDTE': '$02', 'USBCON_VBUSTE': '$01', 'UHWCON': '&215', 'UHWCON_UIMOD': '$80', 'UHWCON_UIDE': '$40', 'UHWCON_UVCONE': '$10', 'UHWCON_UVREGE': '$01', 'UPERRX': '&245', 'UPERRX_COUNTER': '$60', 'UPERRX_CRC16': '$10', 'UPERRX_TIMEOUT': '$08', 'UPERRX_PID': '$04', 'UPERRX_DATAPID': '$02', 'UPERRX_DATATGL': '$01', 'UPINT': '&248', 'UPBCHX': '&247', 'UPBCLX': '&246', 'UPDATX': '&175', 'UPIENX': '&174', 'UPIENX_FLERRE': '$80', 'UPIENX_NAKEDE': '$40', 'UPIENX_PERRE': '$10', 'UPIENX_TXSTPE': '$08', 'UPIENX_TXOUTE': '$04', 'UPIENX_RXSTALLE': '$02', 'UPIENX_RXINE': '$01', 'UPCFG2X': '&173', 'UPSTAX': '&172', 'UPSTAX_CFGOK': '$80', 'UPSTAX_OVERFI': '$40', 'UPSTAX_UNDERFI': '$20', 'UPSTAX_DTSEQ': '$0C', 'UPSTAX_NBUSYK': '$03', 'UPCFG1X': '&171', 'UPCFG1X_PSIZE': '$70', 'UPCFG1X_PBK': '$0C', 'UPCFG1X_ALLOC': '$02', 'UPCFG0X': '&170', 'UPCFG0X_PTYPE': '$C0', 'UPCFG0X_PTOKEN': '$30', 'UPCFG0X_PEPNUM': '$0F', 'UPCONX': '&169', 'UPCONX_PFREEZE': '$40', 'UPCONX_INMODE': '$20', 'UPCONX_RSTDT': '$08', 'UPCONX_PEN': '$01', 'UPRST': '&168', 'UPRST_PRST': '$7F', 'UPNUM': '&167', 'UPINTX': '&166', 'UPINTX_FIFOCON': '$80', 'UPINTX_NAKEDI': '$40', 'UPINTX_RWAL': '$20', 'UPINTX_PERRI': '$10', 'UPINTX_TXSTPI': '$08', 'UPINTX_TXOUTI': '$04', 'UPINTX_RXSTALLI': '$02', 'UPINTX_RXINI': '$01', 'UPINRQX': '&165', 'UHFLEN': '&164', 'UHFNUM': '&162', 'UHADDR': '&161', 'UHIEN': '&160', 'UHIEN_HWUPE': '$40', 'UHIEN_HSOFE': '$20', 'UHIEN_RXRSME': '$10', 'UHIEN_RSMEDE': '$08', 'UHIEN_RSTE': '$04', 'UHIEN_DDISCE': '$02', 'UHIEN_DCONNE': '$01', 'UHINT': '&159', 'UHINT_UHUPI': '$40', 'UHINT_HSOFI': '$20', 'UHINT_RXRSMI': '$10', 'UHINT_RSMEDI': '$08', 'UHINT_RSTI': '$04', 'UHINT_DDISCI': '$02', 'UHINT_DCONNI': '$01', 'UHCON': '&158', 'UHCON_RESUME': '$04', 'UHCON_RESET': '$02', 'UHCON_SOFEN': '$01', 'SPMCSR': '&87', 'SPMCSR_SPMIE': '$80', 'SPMCSR_RWWSB': '$40', 'SPMCSR_SIGRD': '$20', 'SPMCSR_RWWSRE': '$10', 'SPMCSR_BLBSET': '$08', 'SPMCSR_PGWRT': '$04', 'SPMCSR_PGERS': '$02', 'SPMCSR_SPMEN': '$01', 'EEAR': '&65', 'EEDR': '&64', 'EECR': '&63', 'EECR_EEPM': '$30', 'EECR_EERIE': '$08', 'EECR_EEMPE': '$04', 'EECR_EEPE': '$02', 'EECR_EERE': '$01', 'OCR0B': '&72', 'OCR0A': '&71', 'TCNT0': '&70', 'TCCR0B': '&69', 'TCCR0B_FOC0A': '$80', 'TCCR0B_FOC0B': '$40', 'TCCR0B_WGM02': '$08', 'TCCR0B_CS0': '$07', 'TCCR0A': '&68', 'TCCR0A_COM0A': '$C0', 'TCCR0A_COM0B': '$30', 'TCCR0A_WGM0': '$03', 'TIMSK0': '&110', 'TIMSK0_OCIE0B': '$04', 'TIMSK0_OCIE0A': '$02', 'TIMSK0_TOIE0': '$01', 'TIFR0': '&53', 'TIFR0_OCF0B': '$04', 'TIFR0_OCF0A': '$02', 'TIFR0_TOV0': '$01', 'GTCCR': '&67', 'GTCCR_TSM': '$80', 'GTCCR_PSRSYNC': '$01', 'TIMSK2': '&112', 'TIMSK2_OCIE2B': '$04', 'TIMSK2_OCIE2A': '$02', 'TIMSK2_TOIE2': '$01', 'TIFR2': '&55', 'TIFR2_OCF2B': '$04', 'TIFR2_OCF2A': '$02', 'TIFR2_TOV2': '$01', 'TCCR2A': '&176', 'TCCR2A_COM2A': '$C0', 'TCCR2A_COM2B': '$30', 'TCCR2A_WGM2': '$03', 'TCCR2B': '&177', 'TCCR2B_FOC2A': '$80', 'TCCR2B_FOC2B': '$40', 'TCCR2B_WGM22': '$08', 'TCCR2B_CS2': '$07', 'TCNT2': '&178', 'OCR2B': '&180', 'OCR2A': '&179', 'ASSR': '&182', 'ASSR_EXCLK': '$40', 'ASSR_AS2': '$20', 'ASSR_TCN2UB': '$10', 'ASSR_OCR2AUB': '$08', 'ASSR_OCR2BUB': '$04', 'ASSR_TCR2AUB': '$02', 'ASSR_TCR2BUB': '$01', 'TCCR3A': '&144', 'TCCR3A_COM3A': '$C0', 'TCCR3A_COM3B': '$30', 'TCCR3A_COM3C': '$0C', 'TCCR3A_WGM3': '$03', 'TCCR3B': '&145', 'TCCR3B_ICNC3': '$80', 'TCCR3B_ICES3': '$40', 'TCCR3B_WGM3': '$18', 'TCCR3B_CS3': '$07', 'TCCR3C': '&146', 'TCCR3C_FOC3A': '$80', 'TCCR3C_FOC3B': '$40', 'TCCR3C_FOC3C': '$20', 'TCNT3': '&148', 'OCR3A': '&152', 'OCR3B': '&154', 'OCR3C': '&156', 'ICR3': '&150', 'TIMSK3': '&113', 'TIMSK3_ICIE3': '$20', 'TIMSK3_OCIE3C': '$08', 'TIMSK3_OCIE3B': '$04', 'TIMSK3_OCIE3A': '$02', 'TIMSK3_TOIE3': '$01', 'TIFR3': '&56', 'TIFR3_ICF3': '$20', 'TIFR3_OCF3C': '$08', 'TIFR3_OCF3B': '$04', 'TIFR3_OCF3A': '$02', 'TIFR3_TOV3': '$01', 'TCCR1A': '&128', 'TCCR1A_COM1A': '$C0', 'TCCR1A_COM1B': '$30', 'TCCR1A_COM1C': '$0C', 'TCCR1A_WGM1': '$03', 'TCCR1B': '&129', 'TCCR1B_ICNC1': '$80', 'TCCR1B_ICES1': '$40', 'TCCR1B_WGM1': '$18', 'TCCR1B_CS1': '$07', 'TCCR1C': '&130', 'TCCR1C_FOC1A': '$80', 'TCCR1C_FOC1B': '$40', 'TCCR1C_FOC1C': '$20', 'TCNT1': '&132', 'OCR1A': '&136', 'OCR1B': '&138', 'OCR1C': '&140', 'ICR1': '&134', 'TIMSK1': '&111', 'TIMSK1_ICIE1': '$20', 'TIMSK1_OCIE1C': '$08', 'TIMSK1_OCIE1B': '$04', 'TIMSK1_OCIE1A': '$02', 'TIMSK1_TOIE1': '$01', 'TIFR1': '&54', 'TIFR1_ICF1': '$20', 'TIFR1_OCF1C': '$08', 'TIFR1_OCF1B': '$04', 'TIFR1_OCF1A': '$02', 'TIFR1_TOV1': '$01', 'OCDR': '&81', 'EICRA': '&105', 'EICRA_ISC3': '$C0', 'EICRA_ISC2': '$30', 'EICRA_ISC1': '$0C', 'EICRA_ISC0': '$03', 'EICRB': '&106', 'EICRB_ISC7': '$C0', 'EICRB_ISC6': '$30', 'EICRB_ISC5': '$0C', 'EICRB_ISC4': '$03', 'EIMSK': '&61', 'EIMSK_INT': '$FF', 'EIFR': '&60', 'EIFR_INTF': '$FF', 'PCMSK0': '&107', 'PCIFR': '&59', 'PCIFR_PCIF0': '$01', 'PCICR': '&104', 'PCICR_PCIE0': '$01', 'ADMUX': '&124', 'ADMUX_REFS': '$C0', 'ADMUX_ADLAR': '$20', 'ADMUX_MUX': '$1F', 'ADCSRA': '&122', 'ADCSRA_ADEN': '$80', 'ADCSRA_ADSC': '$40', 'ADCSRA_ADATE': '$20', 'ADCSRA_ADIF': '$10', 'ADCSRA_ADIE': '$08', 'ADCSRA_ADPS': '$07', 'ADC': '&120', 'ADCSRB': '&123', 'ADCSRB_ADHSM': '$80', 'ADCSRB_ADTS': '$07', 'DIDR0': '&126', 'DIDR0_ADC7D': '$80', 'DIDR0_ADC6D': '$40', 'DIDR0_ADC5D': '$20', 'DIDR0_ADC4D': '$10', 'DIDR0_ADC3D': '$08', 'DIDR0_ADC2D': '$04', 'DIDR0_ADC1D': '$02', 'DIDR0_ADC0D': '$01', 'ACSR': '&80', 'ACSR_ACD': '$80', 'ACSR_ACBG': '$40', 'ACSR_ACO': '$20', 'ACSR_ACI': '$10', 'ACSR_ACIE': '$08', 'ACSR_ACIC': '$04', 'ACSR_ACIS': '$03', 'DIDR1': '&127', 'DIDR1_AIN1D': '$02', 'DIDR1_AIN0D': '$01', 'PLLCSR': '&73', 'PLLCSR_PLLP': '$1C', 'PLLCSR_PLLE': '$02', 'PLLCSR_PLOCK': '$01', 'INT0Addr': '2', 'INT1Addr': '4', 'INT2Addr': '6', 'INT3Addr': '8', 'INT4Addr': '10', 'INT5Addr': '12', 'INT6Addr': '14', 'INT7Addr': '16', 'PCINT0Addr': '18', 'USB_GENAddr': '20', 'USB_COMAddr': '22', 'WDTAddr': '24', 'TIMER2_COMPAAddr': '26', 'TIMER2_COMPBAddr': '28', 'TIMER2_OVFAddr': '30', 'TIMER1_CAPTAddr': '32', 'TIMER1_COMPAAddr': '34', 'TIMER1_COMPBAddr': '36', 'TIMER1_COMPCAddr': '38', 'TIMER1_OVFAddr': '40', 'TIMER0_COMPAAddr': '42', 'TIMER0_COMPBAddr': '44', 'TIMER0_OVFAddr': '46', 'SPI__STCAddr': '48', 'USART1__RXAddr': '50', 'USART1__UDREAddr': '52', 'USART1__TXAddr': '54', 'ANALOG_COMPAddr': '56', 'ADCAddr': '58', 'EE_READYAddr': '60', 'TIMER3_CAPTAddr': '62', 'TIMER3_COMPAAddr': '64', 'TIMER3_COMPBAddr': '66', 'TIMER3_COMPCAddr': '68', 'TIMER3_OVFAddr': '70', 'TWIAddr': '72', 'SPM_READYAddr': '74' }
gpl-2.0
5,561,276,221,375,628,000
22.190731
38
0.486202
false
debasishm89/OpenXMolar
ExtDepLibs/autoit/__init__.py
1
4371
# -*- coding: utf-8 -*- __author__ = 'Jace Xu' __version__ = "0.3" from .autoit import options, properties, commands from .autoit import AutoItError from .autoit import error from .autoit import auto_it_set_option from .autoit import clip_get from .autoit import clip_put from .autoit import is_admin from .autoit import drive_map_add from .autoit import drive_map_del from .autoit import drive_map_get from .autoit import mouse_click from .autoit import mouse_click_drag from .autoit import mouse_down from .autoit import mouse_get_cursor from .autoit import mouse_get_pos from .autoit import mouse_move from .autoit import mouse_up from .autoit import mouse_wheel from .autoit import opt from .autoit import pixel_checksum from .autoit import pixel_get_color from .autoit import pixel_search from .autoit import send from .autoit import tooltip from .process import run from .process import run_wait from .process import process_close from .process import process_exists from .process import process_set_priority from .process import process_wait from .process import process_wait_close from .process import run_as from .process import run_as_wait from .process import shutdown from .win import win_activate from .win import win_activate_by_handle from .win import win_active from .win import win_active_by_handle from .win import win_close from .win import win_close_by_handle from .win import win_exists from .win import win_exists_by_handle from .win import win_get_caret_pos from .win import win_get_class_list from .win import win_get_class_list_by_handle from .win import win_get_client_size from .win import win_get_client_size_by_handle from .win import win_get_handle from .win import win_get_handle_as_text from .win import win_get_pos from .win import win_get_pos_by_handle from .win import win_get_process from .win import win_get_process_by_handle from .win import win_get_state from .win import win_get_state_by_handle from .win import win_get_text from .win import win_get_text_by_handle from .win import win_get_title from .win import win_get_title_by_handle from .win import win_kill from .win import win_kill_by_handle from .win import win_menu_select_item from .win import win_menu_select_item_by_handle from .win import win_minimize_all from .win import win_minimize_all_undo from .win import win_move from .win import win_move_by_handle from .win import win_set_on_top from .win import win_set_on_top_by_handle from .win import win_set_state from .win import win_set_state_by_handle from .win import win_set_title from .win import win_set_title_by_handle from .win import win_set_trans from .win import win_set_trans_by_handle from .win import win_wait from .win import win_wait_by_handle from .win import win_wait_active from .win import win_wait_active_by_handle from .win import win_wait_close from .win import win_wait_close_by_handle from .win import win_wait_not_active from .win import win_wait_not_active_by_handle from .control import control_click from .control import control_click_by_handle from .control import control_command from .control import control_command_by_handle from .control import control_list_view from .control import control_list_view_by_handle from .control import control_disable from .control import control_disable_by_handle from .control import control_enable from .control import control_enable_by_handle from .control import control_focus from .control import control_focus_by_handle from .control import control_get_focus from .control import control_get_focus_by_handle from .control import control_get_handle from .control import control_get_handle_as_text from .control import control_get_pos from .control import control_get_pos_by_handle from .control import control_get_text from .control import control_get_text_by_handle from .control import control_hide from .control import control_hide_by_handle from .control import control_move from .control import control_move_by_handle from .control import control_send from .control import control_send_by_handle from .control import control_set_text from .control import control_set_text_by_handle from .control import control_show from .control import control_show_by_handle from .control import control_tree_view from .control import control_tree_view_by_handle from .control import statusbar_get_text from .control import statusbar_get_text_by_handle
bsd-3-clause
3,863,321,307,305,719,300
33.698413
49
0.79547
false
MartynShaw/audacity
lib-src/lv2/lv2/plugins/eg-midigate.lv2/waflib/Options.py
330
5458
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import os,tempfile,optparse,sys,re from waflib import Logs,Utils,Context cmds='distclean configure build install clean uninstall check dist distcheck'.split() options={} commands=[] lockfile=os.environ.get('WAFLOCK','.lock-waf_%s_build'%sys.platform) try:cache_global=os.path.abspath(os.environ['WAFCACHE']) except KeyError:cache_global='' platform=Utils.unversioned_sys_platform() class opt_parser(optparse.OptionParser): def __init__(self,ctx): optparse.OptionParser.__init__(self,conflict_handler="resolve",version='waf %s (%s)'%(Context.WAFVERSION,Context.WAFREVISION)) self.formatter.width=Logs.get_term_cols() p=self.add_option self.ctx=ctx jobs=ctx.jobs() p('-j','--jobs',dest='jobs',default=jobs,type='int',help='amount of parallel jobs (%r)'%jobs) p('-k','--keep',dest='keep',default=0,action='count',help='keep running happily even if errors are found') p('-v','--verbose',dest='verbose',default=0,action='count',help='verbosity level -v -vv or -vvv [default: 0]') p('--nocache',dest='nocache',default=False,action='store_true',help='ignore the WAFCACHE (if set)') p('--zones',dest='zones',default='',action='store',help='debugging zones (task_gen, deps, tasks, etc)') gr=optparse.OptionGroup(self,'configure options') self.add_option_group(gr) gr.add_option('-o','--out',action='store',default='',help='build dir for the project',dest='out') gr.add_option('-t','--top',action='store',default='',help='src dir for the project',dest='top') default_prefix=os.environ.get('PREFIX') if not default_prefix: if platform=='win32': d=tempfile.gettempdir() default_prefix=d[0].upper()+d[1:] else: default_prefix='/usr/local/' gr.add_option('--prefix',dest='prefix',default=default_prefix,help='installation prefix [default: %r]'%default_prefix) gr.add_option('--download',dest='download',default=False,action='store_true',help='try to download the tools if missing') gr=optparse.OptionGroup(self,'build and install options') self.add_option_group(gr) gr.add_option('-p','--progress',dest='progress_bar',default=0,action='count',help='-p: progress bar; -pp: ide output') gr.add_option('--targets',dest='targets',default='',action='store',help='task generators, e.g. "target1,target2"') gr=optparse.OptionGroup(self,'step options') self.add_option_group(gr) gr.add_option('--files',dest='files',default='',action='store',help='files to process, by regexp, e.g. "*/main.c,*/test/main.o"') default_destdir=os.environ.get('DESTDIR','') gr=optparse.OptionGroup(self,'install/uninstall options') self.add_option_group(gr) gr.add_option('--destdir',help='installation root [default: %r]'%default_destdir,default=default_destdir,dest='destdir') gr.add_option('-f','--force',dest='force',default=False,action='store_true',help='force file installation') gr.add_option('--distcheck-args',help='arguments to pass to distcheck',default=None,action='store') def get_usage(self): cmds_str={} for cls in Context.classes: if not cls.cmd or cls.cmd=='options': continue s=cls.__doc__ or'' cmds_str[cls.cmd]=s if Context.g_module: for(k,v)in Context.g_module.__dict__.items(): if k in['options','init','shutdown']: continue if type(v)is type(Context.create_context): if v.__doc__ and not k.startswith('_'): cmds_str[k]=v.__doc__ just=0 for k in cmds_str: just=max(just,len(k)) lst=[' %s: %s'%(k.ljust(just),v)for(k,v)in cmds_str.items()] lst.sort() ret='\n'.join(lst) return'''waf [commands] [options] Main commands (example: ./waf build -j4) %s '''%ret class OptionsContext(Context.Context): cmd='options' fun='options' def __init__(self,**kw): super(OptionsContext,self).__init__(**kw) self.parser=opt_parser(self) self.option_groups={} def jobs(self): count=int(os.environ.get('JOBS',0)) if count<1: if'NUMBER_OF_PROCESSORS'in os.environ: count=int(os.environ.get('NUMBER_OF_PROCESSORS',1)) else: if hasattr(os,'sysconf_names'): if'SC_NPROCESSORS_ONLN'in os.sysconf_names: count=int(os.sysconf('SC_NPROCESSORS_ONLN')) elif'SC_NPROCESSORS_CONF'in os.sysconf_names: count=int(os.sysconf('SC_NPROCESSORS_CONF')) if not count and os.name not in('nt','java'): try: tmp=self.cmd_and_log(['sysctl','-n','hw.ncpu'],quiet=0) except Exception: pass else: if re.match('^[0-9]+$',tmp): count=int(tmp) if count<1: count=1 elif count>1024: count=1024 return count def add_option(self,*k,**kw): return self.parser.add_option(*k,**kw) def add_option_group(self,*k,**kw): try: gr=self.option_groups[k[0]] except KeyError: gr=self.parser.add_option_group(*k,**kw) self.option_groups[k[0]]=gr return gr def get_option_group(self,opt_str): try: return self.option_groups[opt_str] except KeyError: for group in self.parser.option_groups: if group.title==opt_str: return group return None def parse_args(self,_args=None): global options,commands (options,leftover_args)=self.parser.parse_args(args=_args) commands=leftover_args if options.destdir: options.destdir=os.path.abspath(os.path.expanduser(options.destdir)) if options.verbose>=1: self.load('errcheck') def execute(self): super(OptionsContext,self).execute() self.parse_args()
gpl-2.0
8,558,848,824,587,358,000
39.42963
131
0.685233
false
omazapa/root
interpreter/llvm/src/bindings/python/llvm/tests/test_object.py
95
2143
from .base import TestBase from ..object import ObjectFile from ..object import Relocation from ..object import Section from ..object import Symbol class TestObjectFile(TestBase): def get_object_file(self): source = self.get_test_binary() return ObjectFile(filename=source) def test_create_from_file(self): self.get_object_file() def test_get_sections(self): o = self.get_object_file() count = 0 for section in o.get_sections(): count += 1 assert isinstance(section, Section) assert isinstance(section.name, str) assert isinstance(section.size, long) assert isinstance(section.contents, str) assert isinstance(section.address, long) assert len(section.contents) == section.size self.assertGreater(count, 0) for section in o.get_sections(): section.cache() def test_get_symbols(self): o = self.get_object_file() count = 0 for symbol in o.get_symbols(): count += 1 assert isinstance(symbol, Symbol) assert isinstance(symbol.name, str) assert isinstance(symbol.address, long) assert isinstance(symbol.size, long) self.assertGreater(count, 0) for symbol in o.get_symbols(): symbol.cache() def test_symbol_section_accessor(self): o = self.get_object_file() for symbol in o.get_symbols(): section = symbol.section assert isinstance(section, Section) break def test_get_relocations(self): o = self.get_object_file() for section in o.get_sections(): for relocation in section.get_relocations(): assert isinstance(relocation, Relocation) assert isinstance(relocation.address, long) assert isinstance(relocation.offset, long) assert isinstance(relocation.type_number, long) assert isinstance(relocation.type_name, str) assert isinstance(relocation.value_string, str)
lgpl-2.1
-8,599,541,845,863,039,000
30.985075
63
0.604293
false
jngeist/hyde
hyde/tests/ext/test_auto_extend.py
3
2111
# -*- coding: utf-8 -*- """ Use nose `$ pip install nose` `$ nosetests` """ from hyde.fs import File, Folder from hyde.generator import Generator from hyde.site import Site from pyquery import PyQuery from nose.tools import nottest TEST_SITE = File(__file__).parent.parent.child_folder('_test') class TestAutoExtend(object): def setUp(self): TEST_SITE.make() TEST_SITE.parent.child_folder( 'sites/test_jinja').copy_contents_to(TEST_SITE) def tearDown(self): TEST_SITE.delete() @nottest def assert_extended(self, s, txt, templ): content = (templ.strip() % txt).strip() bd = File(TEST_SITE.child('content/auto_extend.html')) bd.write(content) gen = Generator(s) gen.generate_resource_at_path(bd.path) res = s.content.resource_from_path(bd.path) target = File(s.config.deploy_root_path.child(res.relative_deploy_path)) assert target.exists text = target.read_all() q = PyQuery(text) assert q('title').text().strip() == txt.strip() def test_can_auto_extend(self): s = Site(TEST_SITE) s.config.plugins = ['hyde.ext.plugins.meta.MetaPlugin', 'hyde.ext.plugins.auto_extend.AutoExtendPlugin', 'hyde.ext.plugins.blockdown.BlockdownPlugin'] txt ="This template tests to make sure blocks can be replaced with markdownish syntax." templ = """ --- extends: base.html --- =====title======== %s ====/title========""" self.assert_extended(s, txt, templ) def test_can_auto_extend_with_default_blocks(self): s = Site(TEST_SITE) s.config.plugins = ['hyde.ext.plugins.meta.MetaPlugin', 'hyde.ext.plugins.auto_extend.AutoExtendPlugin', 'hyde.ext.plugins.blockdown.BlockdownPlugin'] txt ="This template tests to make sure blocks can be replaced with markdownish syntax." templ = """ --- extends: base.html default_block: title --- %s """ self.assert_extended(s, txt, templ)
mit
-9,195,950,221,603,894,000
28.333333
95
0.602558
false
Glasgow2015/team-10
env/lib/python2.7/site-packages/cms/tests/signals.py
23
2433
# -*- coding: utf-8 -*- from __future__ import with_statement from contextlib import contextmanager from django.test import TestCase from cms.api import create_page from cms.signals import urls_need_reloading class SignalTester(object): def __init__(self): self.call_count = 0 self.calls = [] def __call__(self, *args, **kwargs): self.call_count += 1 self.calls.append((args, kwargs)) @contextmanager def signal_tester(signal): env = SignalTester() signal.connect(env, weak=True) try: yield env finally: signal.disconnect(env, weak=True) class SignalTests(TestCase): def test_urls_need_reloading_signal_create(self): with signal_tester(urls_need_reloading) as env: self.client.get('/') self.assertEqual(env.call_count, 0) create_page( "apphooked-page", "nav_playground.html", "en", published=True, apphook="SampleApp", apphook_namespace="test" ) self.client.get('/') self.assertEqual(env.call_count, 1) def test_urls_need_reloading_signal_delete(self): with signal_tester(urls_need_reloading) as env: self.client.get('/') self.assertEqual(env.call_count, 0) page = create_page( "apphooked-page", "nav_playground.html", "en", published=True, apphook="SampleApp", apphook_namespace="test" ) page.delete() self.client.get('/') self.assertEqual(env.call_count, 1) def test_urls_need_reloading_signal_change_slug(self): with signal_tester(urls_need_reloading) as env: self.assertEqual(env.call_count, 0) page = create_page( "apphooked-page", "nav_playground.html", "en", published=True, apphook="SampleApp", apphook_namespace="test" ) self.client.get('/') self.assertEqual(env.call_count, 1) title = page.title_set.get(language="en") title.slug += 'test' title.save() page.publish('en') self.client.get('/') self.assertEqual(env.call_count, 2)
apache-2.0
2,484,821,567,090,287,600
29.4125
58
0.531032
false
KitKatXperience/platform_external_chromium_org
win8/util/check_sdk_patch.py
68
1559
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Script to check that the Windows 8 SDK has been appropriately patched so that it can be used with VS 2010. In practice, this checks for the presence of 'enum class' in asyncinfo.h. Changing that to 'enum' is the only thing needed to build with the WinRT headers in VS 2010. """ import os import sys def main(argv): if len(argv) < 2: print "Usage: check_sdk_patch.py path_to_windows_8_sdk [dummy_output_file]" return 1 # Look for asyncinfo.h async_info_path = os.path.join(argv[1], 'Include/winrt/asyncinfo.h') if not os.path.exists(async_info_path): print ("Could not find %s in provided SDK path. Please check input." % async_info_path) print "CWD: %s" % os.getcwd() return 2 else: if 'enum class' in open(async_info_path).read(): print ("\nERROR: You are using an unpatched Windows 8 SDK located at %s." "\nPlease see instructions at" "\nhttp://www.chromium.org/developers/how-tos/" "build-instructions-windows\nfor how to apply the patch to build " "with VS2010.\n" % argv[1]) return 3 else: if len(argv) > 2: with open(argv[2], 'w') as dummy_file: dummy_file.write('Windows 8 SDK has been patched!') # Patched Windows 8 SDK found. return 0 if '__main__' == __name__: sys.exit(main(sys.argv))
bsd-3-clause
-73,301,774,088,960,400
31.479167
80
0.644644
false
hahalml/bigcouch
couchjs/scons/scons-local-2.0.1/SCons/Tool/ifl.py
61
2810
"""SCons.Tool.ifl Tool-specific initialization for the Intel Fortran compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/ifl.py 5134 2010/08/16 23:02:40 bdeegan" import SCons.Defaults from SCons.Scanner.Fortran import FortranScan from FortranCommon import add_all_to_env def generate(env): """Add Builders and construction variables for ifl to an Environment.""" fscan = FortranScan("FORTRANPATH") SCons.Tool.SourceFileScanner.add_scanner('.i', fscan) SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan) if 'FORTRANFILESUFFIXES' not in env: env['FORTRANFILESUFFIXES'] = ['.i'] else: env['FORTRANFILESUFFIXES'].append('.i') if 'F90FILESUFFIXES' not in env: env['F90FILESUFFIXES'] = ['.i90'] else: env['F90FILESUFFIXES'].append('.i90') add_all_to_env(env) env['FORTRAN'] = 'ifl' env['SHFORTRAN'] = '$FORTRAN' env['FORTRANCOM'] = '$FORTRAN $FORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' env['FORTRANPPCOM'] = '$FORTRAN $FORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' env['SHFORTRANCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' env['SHFORTRANPPCOM'] = '$SHFORTRAN $SHFORTRANFLAGS $CPPFLAGS $_CPPDEFFLAGS $_FORTRANINCFLAGS /c $SOURCES /Fo$TARGET' def exists(env): return env.Detect('ifl') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
apache-2.0
-9,216,190,532,521,528,000
38.027778
121
0.724199
false
syci/OCB
addons/l10n_sg/__openerp__.py
27
1438
# -*- encoding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # Copyright (C) 2014 Tech Receptives (<http://techreceptives.com>) { 'name': 'Singapore - Accounting', 'version': '1.0', 'author': 'Tech Receptives', 'website': 'http://www.techreceptives.com', 'category': 'Localization/Account Charts', 'description': """ Singapore accounting chart and localization. ======================================================= After installing this module, the Configuration wizard for accounting is launched. * The Chart of Accounts consists of the list of all the general ledger accounts required to maintain the transactions of Singapore. * On that particular wizard, you will be asked to pass the name of the company, the chart template to follow, the no. of digits to generate, the code for your account and bank account, currency to create journals. * The Chart of Taxes would display the different types/groups of taxes such as Standard Rates, Zeroed, Exempted, MES and Out of Scope. * The tax codes are specified considering the Tax Group and for easy accessibility of submission of GST Tax Report. """, 'depends': ['base', 'account'], 'demo': [ ], 'data': [ 'l10n_sg_chart.xml', 'l10n_sg_chart_tax.xml', 'account_chart_template.yml', ], 'installable': True, }
agpl-3.0
2,928,132,745,244,388,400
37.864865
89
0.64395
false
onlyjus/pyqtgraph
doc/extensions/qt_doc.py
28
4791
""" Extension for building Qt-like documentation. - Method lists preceding the actual method documentation - Inherited members documented separately - Members inherited from Qt have links to qt-project documentation - Signal documentation """ def setup(app): # probably we will be making a wrapper around autodoc app.setup_extension('sphinx.ext.autodoc') # would it be useful to define a new domain? #app.add_domain(QtDomain) ## Add new configuration options app.add_config_value('todo_include_todos', False, False) ## Nodes are the basic objects representing documentation directives ## and roles app.add_node(Todolist) app.add_node(Todo, html=(visit_todo_node, depart_todo_node), latex=(visit_todo_node, depart_todo_node), text=(visit_todo_node, depart_todo_node)) ## New directives like ".. todo:" app.add_directive('todo', TodoDirective) app.add_directive('todolist', TodolistDirective) ## Connect callbacks to specific hooks in the build process app.connect('doctree-resolved', process_todo_nodes) app.connect('env-purge-doc', purge_todos) from docutils import nodes from sphinx.util.compat import Directive from sphinx.util.compat import make_admonition # Just a general node class Todolist(nodes.General, nodes.Element): pass # .. and its directive class TodolistDirective(Directive): # all directives have 'run' method that returns a list of nodes def run(self): return [Todolist('')] # Admonition classes are like notes or warnings class Todo(nodes.Admonition, nodes.Element): pass def visit_todo_node(self, node): self.visit_admonition(node) def depart_todo_node(self, node): self.depart_admonition(node) class TodoDirective(Directive): # this enables content in the directive has_content = True def run(self): env = self.state.document.settings.env # create a new target node for linking to targetid = "todo-%d" % env.new_serialno('todo') targetnode = nodes.target('', '', ids=[targetid]) # make the admonition node ad = make_admonition(Todo, self.name, [('Todo')], self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine) # store a handle in a global list of all todos if not hasattr(env, 'todo_all_todos'): env.todo_all_todos = [] env.todo_all_todos.append({ 'docname': env.docname, 'lineno': self.lineno, 'todo': ad[0].deepcopy(), 'target': targetnode, }) # return both the linking target and the node itself return [targetnode] + ad # env data is persistent across source files so we purge whenever the source file has changed. def purge_todos(app, env, docname): if not hasattr(env, 'todo_all_todos'): return env.todo_all_todos = [todo for todo in env.todo_all_todos if todo['docname'] != docname] # called at the end of resolving phase; we will convert temporary nodes # into finalized nodes def process_todo_nodes(app, doctree, fromdocname): if not app.config.todo_include_todos: for node in doctree.traverse(Todo): node.parent.remove(node) # Replace all todolist nodes with a list of the collected todos. # Augment each todo with a backlink to the original location. env = app.builder.env for node in doctree.traverse(Todolist): if not app.config.todo_include_todos: node.replace_self([]) continue content = [] for todo_info in env.todo_all_todos: para = nodes.paragraph() filename = env.doc2path(todo_info['docname'], base=None) description = ( ('(The original entry is located in %s, line %d and can be found ') % (filename, todo_info['lineno'])) para += nodes.Text(description, description) # Create a reference newnode = nodes.reference('', '') innernode = nodes.emphasis(('here'), ('here')) newnode['refdocname'] = todo_info['docname'] newnode['refuri'] = app.builder.get_relative_uri( fromdocname, todo_info['docname']) newnode['refuri'] += '#' + todo_info['target']['refid'] newnode.append(innernode) para += newnode para += nodes.Text('.)', '.)') # Insert into the todolist content.append(todo_info['todo']) content.append(para) node.replace_self(content)
mit
6,174,758,800,019,132,000
31.154362
94
0.617199
false
bev-a-tron/pledge_service
lib/validictory/__init__.py
14
2300
#!/usr/bin/env python from validictory.validator import (SchemaValidator, FieldValidationError, ValidationError, SchemaError) __all__ = ['validate', 'SchemaValidator', 'FieldValidationError', 'ValidationError', 'SchemaError'] __version__ = '0.9.3' def validate(data, schema, validator_cls=SchemaValidator, format_validators=None, required_by_default=True, blank_by_default=False, disallow_unknown_properties=False, apply_default_to_data=False): ''' Validates a parsed json document against the provided schema. If an error is found a :class:`ValidationError` is raised. If there is an issue in the schema a :class:`SchemaError` will be raised. :param data: python data to validate :param schema: python dictionary representing the schema (see `schema format`_) :param validator_cls: optional validator class (default is :class:`SchemaValidator`) :param format_validators: optional dictionary of custom format validators :param required_by_default: defaults to True, set to False to make ``required`` schema attribute False by default. :param disallow_unknown_properties: defaults to False, set to True to disallow properties not listed in the schema definition :param apply_default_to_data: defaults to False, set to True to modify the data in case the schema definition includes a "default" property ''' v = validator_cls(format_validators, required_by_default, blank_by_default, disallow_unknown_properties, apply_default_to_data) return v.validate(data, schema) if __name__ == '__main__': import sys import json if len(sys.argv) == 2: if sys.argv[1] == "--help": raise SystemExit("%s SCHEMAFILE [INFILE]" % (sys.argv[0],)) schemafile = open(sys.argv[1], 'rb') infile = sys.stdin elif len(sys.argv) == 3: schemafile = open(sys.argv[1], 'rb') infile = open(sys.argv[2], 'rb') else: raise SystemExit("%s SCHEMAFILE [INFILE]" % (sys.argv[0],)) try: obj = json.load(infile) schema = json.load(schemafile) validate(obj, schema) except ValueError as e: raise SystemExit(e)
apache-2.0
-7,516,891,790,587,058,000
40.071429
79
0.647826
false
vvw/deep_q_rl
deep_q_rl/ale_data_set.py
4
12078
"""This class stores all of the samples for training. It is able to construct randomly selected batches of phi's from the stored history. It allocates more memory than necessary, then shifts all of the data back to 0 when the samples reach the end of the allocated memory. """ import pyximport import numpy as np pyximport.install(setup_args={'include_dirs': np.get_include()}) import shift import time import theano floatX = theano.config.floatX class DataSet(object): """ Class represents a data set that stores a fixed-length history. """ def __init__(self, width, height, rng, max_steps=1000, phi_length=4, capacity=None): """ Construct a DataSet. Arguments: width,height - image size max_steps - the length of history to store. phi_length - number of images to concatenate into a state. rng - initialized numpy random number generator. capacity - amount of memory to allocate (just for debugging.) """ self.rng = rng self.count = 0 self.max_steps = max_steps self.phi_length = phi_length if capacity == None: self.capacity = max_steps + int(np.ceil(max_steps * .1)) else: self.capacity = capacity self.states = np.zeros((self.capacity, height, width), dtype='uint8') self.actions = np.zeros(self.capacity, dtype='int32') self.rewards = np.zeros(self.capacity, dtype=floatX) self.terminal = np.zeros(self.capacity, dtype='bool') def _min_index(self): return max(0, self.count - self.max_steps) def _max_index(self): return self.count - (self.phi_length + 1) def __len__(self): """ Return the total number of avaible data items. """ return max(0, (self._max_index() - self._min_index()) + 1) def add_sample(self, state, action, reward, terminal): self.states[self.count, ...] = state self.actions[self.count] = action self.rewards[self.count] = reward self.terminal[self.count] = terminal self.count += 1 # Shift the final max_steps back to the beginning. if self.count == self.capacity: roll_amount = self.capacity - self.max_steps shift.shift3d_uint8(self.states, roll_amount) self.actions = np.roll(self.actions, -roll_amount) self.rewards = np.roll(self.rewards, -roll_amount) self.terminal = np.roll(self.terminal, -roll_amount) self.count = self.max_steps def single_episode(self, start, end): """ Make sure that a possible phi does not cross a trial boundary. """ return np.alltrue(np.logical_not(self.terminal[start:end])) def last_phi(self): """ Return the most recent phi. """ phi = self._make_phi(self.count - self.phi_length) return np.array(phi, dtype=floatX) def phi(self, state): """ Return a phi based on the latest image, by grabbing enough history from the data set to fill it out. """ phi = np.empty((self.phi_length, self.states.shape[1], self.states.shape[2]), dtype=floatX) phi[0:(self.phi_length-1), ...] = self.last_phi()[1::] phi[self.phi_length-1, ...] = state return phi def _make_phi(self, index): end_index = index + self.phi_length - 1 #assert self.single_episode(index, end_index) return self.states[index:end_index + 1, ...] def _empty_batch(self, batch_size): # Set aside memory for the batch states = np.empty((batch_size, self.phi_length, self.states.shape[1], self.states.shape[2]), dtype=floatX) actions = np.empty((batch_size, 1), dtype='int32') rewards = np.empty((batch_size, 1), dtype=floatX) terminals = np.empty((batch_size, 1), dtype=bool) next_states = np.empty((batch_size, self.phi_length, self.states.shape[1], self.states.shape[2]), dtype=floatX) return states, actions, rewards, terminals, next_states def batch_iterator(self, batch_size): """ Generator for iterating over all valid batches. """ index = self._min_index() batch_count = 0 states, actions, rewards, terminals, next_states = \ self._empty_batch(batch_size) while index <= self._max_index(): end_index = index + self.phi_length - 1 if self.single_episode(index, end_index): states[batch_count, ...] = self._make_phi(index) actions[batch_count, 0] = self.actions[end_index] rewards[batch_count, 0] = self.rewards[end_index] terminals[batch_count, 0] = self.terminal[end_index] next_states[batch_count, ...] = self._make_phi(index + 1) batch_count += 1 index += 1 if batch_count == batch_size: yield states, actions, rewards, terminals, next_states batch_count = 0 states, actions, rewards, terminals, next_states = \ self._empty_batch(batch_size) def random_batch(self, batch_size): count = 0 states, actions, rewards, terminals, next_states = \ self._empty_batch(batch_size) # Grab random samples until we have enough while count < batch_size: index = self.rng.randint(self._min_index(), self._max_index()+1) end_index = index + self.phi_length - 1 if self.single_episode(index, end_index): states[count, ...] = self._make_phi(index) actions[count, 0] = self.actions[end_index] rewards[count, 0] = self.rewards[end_index] terminals[count, 0] = self.terminal[end_index] next_states[count, ...] = self._make_phi(index + 1) count += 1 return states, actions, rewards, next_states, terminals # TESTING CODE BELOW THIS POINT... def simple_tests(): np.random.seed(222) dataset = DataSet(width=2, height=3, max_steps=6, phi_length=4, capacity=7) for i in range(10): img = np.random.randint(0, 256, size=(3, 2)) action = np.random.randint(16) reward = np.random.random() terminal = False if np.random.random() < .05: terminal = True print 'img', img dataset.add_sample(img, action, reward, terminal) print "S", dataset.states print "A", dataset.actions print "R", dataset.rewards print "T", dataset.terminal print "COUNT", "CAPACITY", dataset.count, dataset.capacity print print "LAST PHI", dataset.last_phi() print print 'BATCH', dataset.random_batch(2) def speed_tests(): dataset = DataSet(width=80, height=80, max_steps=20000, phi_length=4) img = np.random.randint(0, 256, size=(80, 80)) action = np.random.randint(16) reward = np.random.random() start = time.time() for i in range(100000): terminal = False if np.random.random() < .05: terminal = True dataset.add_sample(img, action, reward, terminal) print "samples per second: ", 100000 / (time.time() - start) start = time.time() for i in range(200): a = dataset.random_batch(32) print "batches per second: ", 200 / (time.time() - start) print dataset.last_phi() def trivial_tests(): dataset = DataSet(width=2, height=1, max_steps=3, phi_length=2) img1 = np.array([[1, 1]], dtype='uint8') img2 = np.array([[2, 2]], dtype='uint8') img3 = np.array([[3, 3]], dtype='uint8') dataset.add_sample(img1, 1, 1, False) dataset.add_sample(img2, 2, 2, False) dataset.add_sample(img3, 2, 2, True) print "last", dataset.last_phi() print "random", dataset.random_batch(1) def max_size_tests(): dataset1 = DataSet(width=3, height=4, max_steps=10, phi_length=4) dataset2 = DataSet(width=3, height=4, max_steps=1000, phi_length=4) for i in range(100): img = np.random.randint(0, 256, size=(4, 3)) action = np.random.randint(16) reward = np.random.random() terminal = False if np.random.random() < .05: terminal = True dataset1.add_sample(img, action, reward, terminal) dataset2.add_sample(img, action, reward, terminal) np.testing.assert_array_almost_equal(dataset1.last_phi(), dataset2.last_phi()) print "passed" def test_iterator(): dataset = DataSet(width=2, height=1, max_steps=10, phi_length=2) img1 = np.array([[1, 1]], dtype='uint8') img2 = np.array([[2, 2]], dtype='uint8') img3 = np.array([[3, 3]], dtype='uint8') img4 = np.array([[3, 3]], dtype='uint8') dataset.add_sample(img1, 1, 1, False) dataset.add_sample(img2, 2, 2, False) dataset.add_sample(img3, 3, 3, False) dataset.add_sample(img4, 4, 4, True) for s, a, r, t, ns in dataset.batch_iterator(2): print "s ", s, "a ",a, "r ",r,"t ", t,"ns ", ns def test_random_batch(): dataset1 = DataSet(width=3, height=4, max_steps=50, phi_length=4) dataset2 = DataSet(width=3, height=4, max_steps=50, phi_length=4, capacity=2000) np.random.seed(hash(time.time())) for i in range(100): img = np.random.randint(0, 256, size=(4, 3)) action = np.random.randint(16) reward = np.random.random() terminal = False if np.random.random() < .05: terminal = True dataset1.add_sample(img, action, reward, terminal) dataset2.add_sample(img, action, reward, terminal) if i > 10: np.random.seed(i*11 * i) states1, actions1, rewards1, next_states1, terminals1 = \ dataset1.random_batch(10) np.random.seed(i*11 * i) states2, actions2, rewards2, next_states2, terminals2 = \ dataset2.random_batch(10) np.testing.assert_array_almost_equal(states1, states2) np.testing.assert_array_almost_equal(actions1, actions2) np.testing.assert_array_almost_equal(rewards1, rewards2) np.testing.assert_array_almost_equal(next_states1, next_states2) np.testing.assert_array_almost_equal(terminals1, terminals2) # if not np.array_equal(states1, states2): # print states1,"\n", states2 # if not np.array_equal(actions1, actions2): # print actions1, "\n",actions2 # if not np.array_equal(rewards1, rewards2): # print rewards1, "\n",rewards2 # if not np.array_equal(next_states1, next_states2): # print next_states1, "\n",next_states2 # if not np.array_equal(terminals1, terminals2): # print terminals1, "\n",terminals2 np.random.seed(hash(time.time())) def test_memory_usage_ok(): import memory_profiler dataset = DataSet(width=80, height=80, max_steps=100000, phi_length=4) last = time.time() for i in xrange(1000000000): if (i % 100000) == 0: print i dataset.add_sample(np.random.random((80, 80)), 1, 1, False) if i > 200000: states, actions, rewards, next_states, terminals = \ dataset.random_batch(32) if (i % 10007) == 0: print time.time() - last mem_usage = memory_profiler.memory_usage(-1) print len(dataset), mem_usage last = time.time() def main(): #speed_tests() test_memory_usage_ok() #test_random_batch() #max_size_tests() #simple_tests() #test_iterator() if __name__ == "__main__": main()
bsd-3-clause
-8,620,320,135,838,170,000
35.379518
79
0.573025
false
hypermindr/barbante
barbante/maintenance/tests/TestTasks.py
1
3272
""" Tests for barbante.maintenance.tasks.py. """ import datetime as dt import nose.tools import barbante.maintenance.tasks as tasks from barbante.maintenance.tests.fixtures.MaintenanceFixture import MaintenanceFixture import barbante.tests as tests class TestTasks(MaintenanceFixture): """ Test class for maintenance tasks. """ def __init__(self): super().__init__() def test_increment_product_popularity(self): product_1 = "p_mus_1" product_2 = "p_empty" product_ids = [product_1, product_2] popularity_map = self.session_context.data_proxy.fetch_product_popularity(product_ids=product_ids) # sanity check nose.tools.eq_(popularity_map[product_1], 3, "Wrong initial popularity") nose.tools.eq_(popularity_map.get(product_2), None, "Popularity should be None since no one consumed it") activity = {"external_user_id": "u_eco_1", "external_product_id": product_1, "activity": "buy", "created_at": self.session_context.get_present_date() - dt.timedelta(2)} tasks.update_summaries(self.session_context, activity) popularity_map = self.session_context.data_proxy.fetch_product_popularity(product_ids=product_ids) nose.tools.ok_(abs(popularity_map[product_1] - 2) < tests.FLOAT_DELTA, "Wrong popularity") # another activity by the same user, without extending the date range activity = {"external_user_id": "u_eco_1", "external_product_id": product_1, "activity": "buy", "created_at": self.session_context.get_present_date() - dt.timedelta(2)} tasks.update_summaries(self.session_context, activity) popularity_map = self.session_context.data_proxy.fetch_product_popularity(product_ids=product_ids) nose.tools.ok_(abs(popularity_map[product_1] - 2) < tests.FLOAT_DELTA, "Wrong popularity") # another activity by the same user, now extending the date range activity = {"external_user_id": "u_eco_1", "external_product_id": product_1, "activity": "buy", "created_at": self.session_context.get_present_date() - dt.timedelta(3)} tasks.update_summaries(self.session_context, activity) popularity_map = self.session_context.data_proxy.fetch_product_popularity(product_ids=product_ids) nose.tools.ok_(abs(popularity_map[product_1] - 4/3) < tests.FLOAT_DELTA, "Wrong popularity") def test_delete_product(self): product_id = "p_mus_1" tasks.delete_product(self.session_context, product_id) product_models = self.db_proxy.fetch_product_models() tf_map = self.db_proxy.fetch_tf_map("full_content", [product_id]) tfidf_map = self.db_proxy.fetch_tfidf_map("full_content", [product_id]) nose.tools.ok_(product_id not in product_models, "Product model should have been physically deleted") nose.tools.ok_(product_id not in tf_map, "TF's should have been physically deleted") nose.tools.ok_(product_id not in tfidf_map, "TFIDF's should have been physically deleted")
mit
4,051,082,729,903,806,500
43.821918
113
0.636919
false
wnoc-drexel/gem5-stable
src/cpu/kvm/BaseKvmCPU.py
39
3087
# Copyright (c) 2012 ARM Limited # All rights reserved. # # The license below extends only to copyright in the software and shall # not be construed as granting a license to any other intellectual # property including but not limited to intellectual property relating # to a hardware implementation of the functionality of the software # licensed hereunder. You may use the software subject to the license # terms below provided that you ensure that this notice is replicated # unmodified and in its entirety in all distributions of the software, # modified or unmodified, in source code or in binary form. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Andreas Sandberg from m5.params import * from m5.proxy import * from BaseCPU import BaseCPU from KvmVM import KvmVM class BaseKvmCPU(BaseCPU): type = 'BaseKvmCPU' cxx_header = "cpu/kvm/base.hh" abstract = True @classmethod def export_method_cxx_predecls(cls, code): code('#include "cpu/kvm/base.hh"') @classmethod def export_methods(cls, code): code(''' void dump(); ''') @classmethod def memory_mode(cls): return 'atomic_noncaching' @classmethod def require_caches(cls): return False @classmethod def support_take_over(cls): return True kvmVM = Param.KvmVM(Parent.any, 'KVM VM (i.e., shared memory domain)') useCoalescedMMIO = Param.Bool(False, "Use coalesced MMIO (EXPERIMENTAL)") usePerfOverflow = Param.Bool(False, "Use perf event overflow counters (EXPERIMENTAL)") hostFreq = Param.Clock("2GHz", "Host clock frequency") hostFactor = Param.Float(1.0, "Cycle scale factor")
bsd-3-clause
7,443,840,767,391,245,000
39.618421
90
0.751863
false
Drooids/odoo
addons/web/doc/conf.py
494
8552
# -*- coding: utf-8 -*- # # OpenERP Technical Documentation configuration file, created by # sphinx-quickstart on Fri Feb 17 16:14:06 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(os.path.abspath('_themes')) sys.path.insert(0, os.path.abspath('../addons')) sys.path.insert(0, os.path.abspath('..')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.viewcode', 'patchqueue' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'OpenERP Web Developers Documentation' copyright = u'2012, OpenERP s.a.' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '7.0' # The full version, including alpha/beta/rc tags. release = '7.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'flask' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'], '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'] } # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'openerp-web-doc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'openerp-web-doc.tex', u'OpenERP Web Developers Documentation', u'OpenERP s.a.', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'openerp-web-doc', u'OpenERP Web Developers Documentation', [u'OpenERP s.a.'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'OpenERPWebDocumentation', u'OpenERP Web Developers Documentation', u'OpenERP s.a.', 'OpenERPWebDocumentation', 'Developers documentation for the openerp-web project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' todo_include_todos = True # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'python': ('http://docs.python.org/', None), 'openerpserver': ('http://doc.openerp.com/trunk/developers/server', None), }
agpl-3.0
-1,367,210,753,899,688,200
31.892308
103
0.702175
false
thiriel/maps
django/contrib/localflavor/pl/pl_administrativeunits.py
433
13194
# -*- coding: utf-8 -*- """ Polish administrative units as in http://pl.wikipedia.org/wiki/Podzia%C5%82_administracyjny_Polski """ ADMINISTRATIVE_UNIT_CHOICES = ( ('wroclaw', u'Wrocław'), ('jeleniagora', u'Jelenia Góra'), ('legnica', u'Legnica'), ('boleslawiecki', u'bolesławiecki'), ('dzierzoniowski', u'dzierżoniowski'), ('glogowski', u'głogowski'), ('gorowski', u'górowski'), ('jaworski', u'jaworski'), ('jeleniogorski', u'jeleniogórski'), ('kamiennogorski', u'kamiennogórski'), ('klodzki', u'kłodzki'), ('legnicki', u'legnicki'), ('lubanski', u'lubański'), ('lubinski', u'lubiński'), ('lwowecki', u'lwówecki'), ('milicki', u'milicki'), ('olesnicki', u'oleśnicki'), ('olawski', u'oławski'), ('polkowicki', u'polkowicki'), ('strzelinski', u'strzeliński'), ('sredzki', u'średzki'), ('swidnicki', u'świdnicki'), ('trzebnicki', u'trzebnicki'), ('walbrzyski', u'wałbrzyski'), ('wolowski', u'wołowski'), ('wroclawski', u'wrocławski'), ('zabkowicki', u'ząbkowicki'), ('zgorzelecki', u'zgorzelecki'), ('zlotoryjski', u'złotoryjski'), ('bydgoszcz', u'Bydgoszcz'), ('torun', u'Toruń'), ('wloclawek', u'Włocławek'), ('grudziadz', u'Grudziądz'), ('aleksandrowski', u'aleksandrowski'), ('brodnicki', u'brodnicki'), ('bydgoski', u'bydgoski'), ('chelminski', u'chełmiński'), ('golubsko-dobrzynski', u'golubsko-dobrzyński'), ('grudziadzki', u'grudziądzki'), ('inowroclawski', u'inowrocławski'), ('lipnowski', u'lipnowski'), ('mogilenski', u'mogileński'), ('nakielski', u'nakielski'), ('radziejowski', u'radziejowski'), ('rypinski', u'rypiński'), ('sepolenski', u'sępoleński'), ('swiecki', u'świecki'), ('torunski', u'toruński'), ('tucholski', u'tucholski'), ('wabrzeski', u'wąbrzeski'), ('wloclawski', u'wrocławski'), ('zninski', u'źniński'), ('lublin', u'Lublin'), ('biala-podlaska', u'Biała Podlaska'), ('chelm', u'Chełm'), ('zamosc', u'Zamość'), ('bialski', u'bialski'), ('bilgorajski', u'biłgorajski'), ('chelmski', u'chełmski'), ('hrubieszowski', u'hrubieszowski'), ('janowski', u'janowski'), ('krasnostawski', u'krasnostawski'), ('krasnicki', u'kraśnicki'), ('lubartowski', u'lubartowski'), ('lubelski', u'lubelski'), ('leczynski', u'łęczyński'), ('lukowski', u'łukowski'), ('opolski', u'opolski'), ('parczewski', u'parczewski'), ('pulawski', u'puławski'), ('radzynski', u'radzyński'), ('rycki', u'rycki'), ('swidnicki', u'świdnicki'), ('tomaszowski', u'tomaszowski'), ('wlodawski', u'włodawski'), ('zamojski', u'zamojski'), ('gorzow-wielkopolski', u'Gorzów Wielkopolski'), ('zielona-gora', u'Zielona Góra'), ('gorzowski', u'gorzowski'), ('krosnienski', u'krośnieński'), ('miedzyrzecki', u'międzyrzecki'), ('nowosolski', u'nowosolski'), ('slubicki', u'słubicki'), ('strzelecko-drezdenecki', u'strzelecko-drezdenecki'), ('sulecinski', u'suleńciński'), ('swiebodzinski', u'świebodziński'), ('wschowski', u'wschowski'), ('zielonogorski', u'zielonogórski'), ('zaganski', u'żagański'), ('zarski', u'żarski'), ('lodz', u'Łódź'), ('piotrkow-trybunalski', u'Piotrków Trybunalski'), ('skierniewice', u'Skierniewice'), ('belchatowski', u'bełchatowski'), ('brzezinski', u'brzeziński'), ('kutnowski', u'kutnowski'), ('laski', u'łaski'), ('leczycki', u'łęczycki'), ('lowicki', u'łowicki'), ('lodzki wschodni', u'łódzki wschodni'), ('opoczynski', u'opoczyński'), ('pabianicki', u'pabianicki'), ('pajeczanski', u'pajęczański'), ('piotrkowski', u'piotrkowski'), ('poddebicki', u'poddębicki'), ('radomszczanski', u'radomszczański'), ('rawski', u'rawski'), ('sieradzki', u'sieradzki'), ('skierniewicki', u'skierniewicki'), ('tomaszowski', u'tomaszowski'), ('wielunski', u'wieluński'), ('wieruszowski', u'wieruszowski'), ('zdunskowolski', u'zduńskowolski'), ('zgierski', u'zgierski'), ('krakow', u'Kraków'), ('tarnow', u'Tarnów'), ('nowy-sacz', u'Nowy Sącz'), ('bochenski', u'bocheński'), ('brzeski', u'brzeski'), ('chrzanowski', u'chrzanowski'), ('dabrowski', u'dąbrowski'), ('gorlicki', u'gorlicki'), ('krakowski', u'krakowski'), ('limanowski', u'limanowski'), ('miechowski', u'miechowski'), ('myslenicki', u'myślenicki'), ('nowosadecki', u'nowosądecki'), ('nowotarski', u'nowotarski'), ('olkuski', u'olkuski'), ('oswiecimski', u'oświęcimski'), ('proszowicki', u'proszowicki'), ('suski', u'suski'), ('tarnowski', u'tarnowski'), ('tatrzanski', u'tatrzański'), ('wadowicki', u'wadowicki'), ('wielicki', u'wielicki'), ('warszawa', u'Warszawa'), ('ostroleka', u'Ostrołęka'), ('plock', u'Płock'), ('radom', u'Radom'), ('siedlce', u'Siedlce'), ('bialobrzeski', u'białobrzeski'), ('ciechanowski', u'ciechanowski'), ('garwolinski', u'garwoliński'), ('gostyninski', u'gostyniński'), ('grodziski', u'grodziski'), ('grojecki', u'grójecki'), ('kozienicki', u'kozenicki'), ('legionowski', u'legionowski'), ('lipski', u'lipski'), ('losicki', u'łosicki'), ('makowski', u'makowski'), ('minski', u'miński'), ('mlawski', u'mławski'), ('nowodworski', u'nowodworski'), ('ostrolecki', u'ostrołęcki'), ('ostrowski', u'ostrowski'), ('otwocki', u'otwocki'), ('piaseczynski', u'piaseczyński'), ('plocki', u'płocki'), ('plonski', u'płoński'), ('pruszkowski', u'pruszkowski'), ('przasnyski', u'przasnyski'), ('przysuski', u'przysuski'), ('pultuski', u'pułtuski'), ('radomski', u'radomski'), ('siedlecki', u'siedlecki'), ('sierpecki', u'sierpecki'), ('sochaczewski', u'sochaczewski'), ('sokolowski', u'sokołowski'), ('szydlowiecki', u'szydłowiecki'), ('warszawski-zachodni', u'warszawski zachodni'), ('wegrowski', u'węgrowski'), ('wolominski', u'wołomiński'), ('wyszkowski', u'wyszkowski'), ('zwolenski', u'zwoleński'), ('zurominski', u'żuromiński'), ('zyrardowski', u'żyrardowski'), ('opole', u'Opole'), ('brzeski', u'brzeski'), ('glubczycki', u'głubczyski'), ('kedzierzynsko-kozielski', u'kędzierzyński-kozielski'), ('kluczborski', u'kluczborski'), ('krapkowicki', u'krapkowicki'), ('namyslowski', u'namysłowski'), ('nyski', u'nyski'), ('oleski', u'oleski'), ('opolski', u'opolski'), ('prudnicki', u'prudnicki'), ('strzelecki', u'strzelecki'), ('rzeszow', u'Rzeszów'), ('krosno', u'Krosno'), ('przemysl', u'Przemyśl'), ('tarnobrzeg', u'Tarnobrzeg'), ('bieszczadzki', u'bieszczadzki'), ('brzozowski', u'brzozowski'), ('debicki', u'dębicki'), ('jaroslawski', u'jarosławski'), ('jasielski', u'jasielski'), ('kolbuszowski', u'kolbuszowski'), ('krosnienski', u'krośnieński'), ('leski', u'leski'), ('lezajski', u'leżajski'), ('lubaczowski', u'lubaczowski'), ('lancucki', u'łańcucki'), ('mielecki', u'mielecki'), ('nizanski', u'niżański'), ('przemyski', u'przemyski'), ('przeworski', u'przeworski'), ('ropczycko-sedziszowski', u'ropczycko-sędziszowski'), ('rzeszowski', u'rzeszowski'), ('sanocki', u'sanocki'), ('stalowowolski', u'stalowowolski'), ('strzyzowski', u'strzyżowski'), ('tarnobrzeski', u'tarnobrzeski'), ('bialystok', u'Białystok'), ('lomza', u'Łomża'), ('suwalki', u'Suwałki'), ('augustowski', u'augustowski'), ('bialostocki', u'białostocki'), ('bielski', u'bielski'), ('grajewski', u'grajewski'), ('hajnowski', u'hajnowski'), ('kolnenski', u'kolneński'), ('łomzynski', u'łomżyński'), ('moniecki', u'moniecki'), ('sejnenski', u'sejneński'), ('siemiatycki', u'siematycki'), ('sokolski', u'sokólski'), ('suwalski', u'suwalski'), ('wysokomazowiecki', u'wysokomazowiecki'), ('zambrowski', u'zambrowski'), ('gdansk', u'Gdańsk'), ('gdynia', u'Gdynia'), ('slupsk', u'Słupsk'), ('sopot', u'Sopot'), ('bytowski', u'bytowski'), ('chojnicki', u'chojnicki'), ('czluchowski', u'człuchowski'), ('kartuski', u'kartuski'), ('koscierski', u'kościerski'), ('kwidzynski', u'kwidzyński'), ('leborski', u'lęborski'), ('malborski', u'malborski'), ('nowodworski', u'nowodworski'), ('gdanski', u'gdański'), ('pucki', u'pucki'), ('slupski', u'słupski'), ('starogardzki', u'starogardzki'), ('sztumski', u'sztumski'), ('tczewski', u'tczewski'), ('wejherowski', u'wejcherowski'), ('katowice', u'Katowice'), ('bielsko-biala', u'Bielsko-Biała'), ('bytom', u'Bytom'), ('chorzow', u'Chorzów'), ('czestochowa', u'Częstochowa'), ('dabrowa-gornicza', u'Dąbrowa Górnicza'), ('gliwice', u'Gliwice'), ('jastrzebie-zdroj', u'Jastrzębie Zdrój'), ('jaworzno', u'Jaworzno'), ('myslowice', u'Mysłowice'), ('piekary-slaskie', u'Piekary Śląskie'), ('ruda-slaska', u'Ruda Śląska'), ('rybnik', u'Rybnik'), ('siemianowice-slaskie', u'Siemianowice Śląskie'), ('sosnowiec', u'Sosnowiec'), ('swietochlowice', u'Świętochłowice'), ('tychy', u'Tychy'), ('zabrze', u'Zabrze'), ('zory', u'Żory'), ('bedzinski', u'będziński'), ('bielski', u'bielski'), ('bierunsko-ledzinski', u'bieruńsko-lędziński'), ('cieszynski', u'cieszyński'), ('czestochowski', u'częstochowski'), ('gliwicki', u'gliwicki'), ('klobucki', u'kłobucki'), ('lubliniecki', u'lubliniecki'), ('mikolowski', u'mikołowski'), ('myszkowski', u'myszkowski'), ('pszczynski', u'pszczyński'), ('raciborski', u'raciborski'), ('rybnicki', u'rybnicki'), ('tarnogorski', u'tarnogórski'), ('wodzislawski', u'wodzisławski'), ('zawiercianski', u'zawierciański'), ('zywiecki', u'żywiecki'), ('kielce', u'Kielce'), ('buski', u'buski'), ('jedrzejowski', u'jędrzejowski'), ('kazimierski', u'kazimierski'), ('kielecki', u'kielecki'), ('konecki', u'konecki'), ('opatowski', u'opatowski'), ('ostrowiecki', u'ostrowiecki'), ('pinczowski', u'pińczowski'), ('sandomierski', u'sandomierski'), ('skarzyski', u'skarżyski'), ('starachowicki', u'starachowicki'), ('staszowski', u'staszowski'), ('wloszczowski', u'włoszczowski'), ('olsztyn', u'Olsztyn'), ('elblag', u'Elbląg'), ('bartoszycki', u'bartoszycki'), ('braniewski', u'braniewski'), ('dzialdowski', u'działdowski'), ('elblaski', u'elbląski'), ('elcki', u'ełcki'), ('gizycki', u'giżycki'), ('goldapski', u'gołdapski'), ('ilawski', u'iławski'), ('ketrzynski', u'kętrzyński'), ('lidzbarski', u'lidzbarski'), ('mragowski', u'mrągowski'), ('nidzicki', u'nidzicki'), ('nowomiejski', u'nowomiejski'), ('olecki', u'olecki'), ('olsztynski', u'olsztyński'), ('ostrodzki', u'ostródzki'), ('piski', u'piski'), ('szczycienski', u'szczycieński'), ('wegorzewski', u'węgorzewski'), ('poznan', u'Poznań'), ('kalisz', u'Kalisz'), ('konin', u'Konin'), ('leszno', u'Leszno'), ('chodzieski', u'chodziejski'), ('czarnkowsko-trzcianecki', u'czarnkowsko-trzcianecki'), ('gnieznienski', u'gnieźnieński'), ('gostynski', u'gostyński'), ('grodziski', u'grodziski'), ('jarocinski', u'jarociński'), ('kaliski', u'kaliski'), ('kepinski', u'kępiński'), ('kolski', u'kolski'), ('koninski', u'koniński'), ('koscianski', u'kościański'), ('krotoszynski', u'krotoszyński'), ('leszczynski', u'leszczyński'), ('miedzychodzki', u'międzychodzki'), ('nowotomyski', u'nowotomyski'), ('obornicki', u'obornicki'), ('ostrowski', u'ostrowski'), ('ostrzeszowski', u'ostrzeszowski'), ('pilski', u'pilski'), ('pleszewski', u'pleszewski'), ('poznanski', u'poznański'), ('rawicki', u'rawicki'), ('slupecki', u'słupecki'), ('szamotulski', u'szamotulski'), ('sredzki', u'średzki'), ('sremski', u'śremski'), ('turecki', u'turecki'), ('wagrowiecki', u'wągrowiecki'), ('wolsztynski', u'wolsztyński'), ('wrzesinski', u'wrzesiński'), ('zlotowski', u'złotowski'), ('bialogardzki', u'białogardzki'), ('choszczenski', u'choszczeński'), ('drawski', u'drawski'), ('goleniowski', u'goleniowski'), ('gryficki', u'gryficki'), ('gryfinski', u'gryfiński'), ('kamienski', u'kamieński'), ('kolobrzeski', u'kołobrzeski'), ('koszalinski', u'koszaliński'), ('lobeski', u'łobeski'), ('mysliborski', u'myśliborski'), ('policki', u'policki'), ('pyrzycki', u'pyrzycki'), ('slawienski', u'sławieński'), ('stargardzki', u'stargardzki'), ('szczecinecki', u'szczecinecki'), ('swidwinski', u'świdwiński'), ('walecki', u'wałecki'), )
bsd-3-clause
-2,675,467,900,154,316,300
32.631169
98
0.5865
false
JohnReid/seqan
util/py_lib/seqan/pyclangcheck/simple_checks.py
26
4137
#!/usr/bin/env python """Simple source code checks, e.g. trailing whitespace.""" from __future__ import with_statement import bisect import re import sys import violations RULE_TRAILING_WHITESPACE = 'whitespace.trailing' RULE_TEXT_TRAILING_WHITESPACE = 'Trailing whitespace is not allowed.' RULE_TODO_ONE_SPACE = 'whitespace.todo' RULE_TEXT_TODO_ONE_SPACE= 'There should be exactly one space before TODO.' RULE_TODO_USERNAME = 'readability.todo' RULE_TEXT_TODO_USERNAME = 'TODO comments should look like this: "// TODO(username): Text".' RULE_TODO_SPACE_AFTER = 'whitespace.todo' RULE_TEXT_TODO_SPACE_AFTER = '"TODO (username):" should be followed by a space.' RE_TODO = r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?' class WhitespaceChecker(object): """Performs simple white space checks.""" # TODO(holtgrew): Do not allow tabs. def check(self, filename): vs = [] with open(filename, 'rb') as f: line_no = 0 for line in f: line_no += 1 if line.rstrip() == line.rstrip('\r\n'): continue v = violations.SimpleRuleViolation( RULE_TRAILING_WHITESPACE, filename, line_no, len(line.rstrip()) + 1, RULE_TEXT_TRAILING_WHITESPACE) vs.append(v) return dict([(v.key(), v) for v in vs]) class SourceFile(object): def __init__(self, name): self.name = name class SourceLocation(object): def __init__(self, filename, line, column, offset): self.file = SourceFile(filename) self.line = line self.column = column self.offset = offset def __str__(self): return '%s:%d/%d (@%d)' % (self.file.name, self.line, self.column, self.offset) def __repr__(self): return str(self) def enumerateComments(filename): # Read file. with open (filename, 'rb') as f: lines = f.readlines() fcontents = ''.join(lines) # Build line break index. line_starts = [0] for line in lines: line_starts.append(line_starts[-1] + len(line)) #print line_starts # Search for all comments. pattern = re.compile( r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"', re.DOTALL | re.MULTILINE) for match in re.finditer(pattern, fcontents): line_start = bisect.bisect(line_starts, match.start(0)) line_end = bisect.bisect(line_starts, match.end(0) - 1) column_start = match.start(0) - line_starts[line_start - 1] column_end = match.end(0) - line_starts[line_end - 1] yield (SourceLocation(filename, line_start, column_start + 1, match.start(0)), SourceLocation(filename, line_end, column_end + 1, match.end(0)), match.group(0)) class CommentChecker(object): """Performs the checks on comments.""" def check(self, filename): vs = [] for cstart, cend, comment in enumerateComments(filename): if comment.startswith('//'): # Check TODO comments. match = re.match(RE_TODO, comment) if match: if len(match.group(1)) > 1: print comment v = violations.SimpleRuleViolation( RULE_TODO_ONE_SPACE, filename, cstart.line, cstart.column, RULE_TEXT_TODO_ONE_SPACE) vs.append(v) if not match.group(2): v = violations.SimpleRuleViolation( RULE_TODO_USERNAME, filename, cstart.line, cstart.column, RULE_TEXT_TODO_USERNAME) vs.append(v) if match.group(3) != ' ' and match.group(3) != '': v = violations.SimpleRuleViolation( RULE_TODO_SPACE_AFTER, filename, cstart.line, cstart.column, RULE_TEXT_TODO_SPACE_AFTER) vs.append(v) return dict([(v.key(), v) for v in vs])
bsd-3-clause
-2,441,971,052,331,757,600
34.358974
91
0.544598
false
lidavidm/sympy
sympy/polys/tests/test_densebasic.py
3
21443
"""Tests for dense recursive polynomials' basic tools. """ from sympy.polys.densebasic import ( dup_LC, dmp_LC, dup_TC, dmp_TC, dmp_ground_LC, dmp_ground_TC, dmp_true_LT, dup_degree, dmp_degree, dmp_degree_in, dmp_degree_list, dup_strip, dmp_strip, dmp_validate, dup_reverse, dup_copy, dmp_copy, dup_normal, dmp_normal, dup_convert, dmp_convert, dup_from_sympy, dmp_from_sympy, dup_nth, dmp_nth, dmp_ground_nth, dmp_zero_p, dmp_zero, dmp_one_p, dmp_one, dmp_ground_p, dmp_ground, dmp_negative_p, dmp_positive_p, dmp_zeros, dmp_grounds, dup_from_dict, dup_from_raw_dict, dup_to_dict, dup_to_raw_dict, dmp_from_dict, dmp_to_dict, dmp_swap, dmp_permute, dmp_nest, dmp_raise, dup_deflate, dmp_deflate, dup_multi_deflate, dmp_multi_deflate, dup_inflate, dmp_inflate, dmp_exclude, dmp_include, dmp_inject, dmp_eject, dup_terms_gcd, dmp_terms_gcd, dmp_list_terms, dmp_apply_pairs, dup_slice, dmp_slice, dmp_slice_in, dup_random, ) from sympy.polys.specialpolys import f_polys from sympy.polys.polyclasses import DMP from sympy.polys.domains import ZZ, QQ from sympy.polys.rings import ring from sympy.core.singleton import S from sympy.utilities.pytest import raises f_0, f_1, f_2, f_3, f_4, f_5, f_6 = [ f.to_dense() for f in f_polys() ] def test_dup_LC(): assert dup_LC([], ZZ) == 0 assert dup_LC([2, 3, 4, 5], ZZ) == 2 def test_dup_TC(): assert dup_TC([], ZZ) == 0 assert dup_TC([2, 3, 4, 5], ZZ) == 5 def test_dmp_LC(): assert dmp_LC([[]], ZZ) == [] assert dmp_LC([[2, 3, 4], [5]], ZZ) == [2, 3, 4] assert dmp_LC([[[]]], ZZ) == [[]] assert dmp_LC([[[2], [3, 4]], [[5]]], ZZ) == [[2], [3, 4]] def test_dmp_TC(): assert dmp_TC([[]], ZZ) == [] assert dmp_TC([[2, 3, 4], [5]], ZZ) == [5] assert dmp_TC([[[]]], ZZ) == [[]] assert dmp_TC([[[2], [3, 4]], [[5]]], ZZ) == [[5]] def test_dmp_ground_LC(): assert dmp_ground_LC([[]], 1, ZZ) == 0 assert dmp_ground_LC([[2, 3, 4], [5]], 1, ZZ) == 2 assert dmp_ground_LC([[[]]], 2, ZZ) == 0 assert dmp_ground_LC([[[2], [3, 4]], [[5]]], 2, ZZ) == 2 def test_dmp_ground_TC(): assert dmp_ground_TC([[]], 1, ZZ) == 0 assert dmp_ground_TC([[2, 3, 4], [5]], 1, ZZ) == 5 assert dmp_ground_TC([[[]]], 2, ZZ) == 0 assert dmp_ground_TC([[[2], [3, 4]], [[5]]], 2, ZZ) == 5 def test_dmp_true_LT(): assert dmp_true_LT([[]], 1, ZZ) == ((0, 0), 0) assert dmp_true_LT([[7]], 1, ZZ) == ((0, 0), 7) assert dmp_true_LT([[1, 0]], 1, ZZ) == ((0, 1), 1) assert dmp_true_LT([[1], []], 1, ZZ) == ((1, 0), 1) assert dmp_true_LT([[1, 0], []], 1, ZZ) == ((1, 1), 1) def test_dup_degree(): assert dup_degree([]) == -1 assert dup_degree([1]) == 0 assert dup_degree([1, 0]) == 1 assert dup_degree([1, 0, 0, 0, 1]) == 4 def test_dmp_degree(): assert dmp_degree([[]], 1) == -1 assert dmp_degree([[[]]], 2) == -1 assert dmp_degree([[1]], 1) == 0 assert dmp_degree([[2], [1]], 1) == 1 def test_dmp_degree_in(): assert dmp_degree_in([[[]]], 0, 2) == -1 assert dmp_degree_in([[[]]], 1, 2) == -1 assert dmp_degree_in([[[]]], 2, 2) == -1 assert dmp_degree_in([[[1]]], 0, 2) == 0 assert dmp_degree_in([[[1]]], 1, 2) == 0 assert dmp_degree_in([[[1]]], 2, 2) == 0 assert dmp_degree_in(f_4, 0, 2) == 9 assert dmp_degree_in(f_4, 1, 2) == 12 assert dmp_degree_in(f_4, 2, 2) == 8 assert dmp_degree_in(f_6, 0, 2) == 4 assert dmp_degree_in(f_6, 1, 2) == 4 assert dmp_degree_in(f_6, 2, 2) == 6 assert dmp_degree_in(f_6, 3, 3) == 3 raises(IndexError, lambda: dmp_degree_in([[1]], -5, 1)) def test_dmp_degree_list(): assert dmp_degree_list([[[[ ]]]], 3) == (-1, -1, -1, -1) assert dmp_degree_list([[[[1]]]], 3) == ( 0, 0, 0, 0) assert dmp_degree_list(f_0, 2) == (2, 2, 2) assert dmp_degree_list(f_1, 2) == (3, 3, 3) assert dmp_degree_list(f_2, 2) == (5, 3, 3) assert dmp_degree_list(f_3, 2) == (5, 4, 7) assert dmp_degree_list(f_4, 2) == (9, 12, 8) assert dmp_degree_list(f_5, 2) == (3, 3, 3) assert dmp_degree_list(f_6, 3) == (4, 4, 6, 3) def test_dup_strip(): assert dup_strip([]) == [] assert dup_strip([0]) == [] assert dup_strip([0, 0, 0]) == [] assert dup_strip([1]) == [1] assert dup_strip([0, 1]) == [1] assert dup_strip([0, 0, 0, 1]) == [1] assert dup_strip([1, 2, 0]) == [1, 2, 0] assert dup_strip([0, 1, 2, 0]) == [1, 2, 0] assert dup_strip([0, 0, 0, 1, 2, 0]) == [1, 2, 0] def test_dmp_strip(): assert dmp_strip([0, 1, 0], 0) == [1, 0] assert dmp_strip([[]], 1) == [[]] assert dmp_strip([[], []], 1) == [[]] assert dmp_strip([[], [], []], 1) == [[]] assert dmp_strip([[[]]], 2) == [[[]]] assert dmp_strip([[[]], [[]]], 2) == [[[]]] assert dmp_strip([[[]], [[]], [[]]], 2) == [[[]]] assert dmp_strip([[[1]]], 2) == [[[1]]] assert dmp_strip([[[]], [[1]]], 2) == [[[1]]] assert dmp_strip([[[]], [[1]], [[]]], 2) == [[[1]], [[]]] def test_dmp_validate(): assert dmp_validate([]) == ([], 0) assert dmp_validate([0, 0, 0, 1, 0]) == ([1, 0], 0) assert dmp_validate([[[]]]) == ([[[]]], 2) assert dmp_validate([[0], [], [0], [1], [0]]) == ([[1], []], 1) raises(ValueError, lambda: dmp_validate([[0], 0, [0], [1], [0]])) def test_dup_reverse(): assert dup_reverse([1, 2, 0, 3]) == [3, 0, 2, 1] assert dup_reverse([1, 2, 3, 0]) == [3, 2, 1] def test_dup_copy(): f = [ZZ(1), ZZ(0), ZZ(2)] g = dup_copy(f) g[0], g[2] = ZZ(7), ZZ(0) assert f != g def test_dmp_copy(): f = [[ZZ(1)], [ZZ(2), ZZ(0)]] g = dmp_copy(f, 1) g[0][0], g[1][1] = ZZ(7), ZZ(1) assert f != g def test_dup_normal(): assert dup_normal([0, 0, 2, 1, 0, 11, 0], ZZ) == \ [ZZ(2), ZZ(1), ZZ(0), ZZ(11), ZZ(0)] def test_dmp_normal(): assert dmp_normal([[0], [], [0, 2, 1], [0], [11], []], 1, ZZ) == \ [[ZZ(2), ZZ(1)], [], [ZZ(11)], []] def test_dup_convert(): K0, K1 = ZZ['x'], ZZ f = [K0(1), K0(2), K0(0), K0(3)] assert dup_convert(f, K0, K1) == \ [ZZ(1), ZZ(2), ZZ(0), ZZ(3)] def test_dmp_convert(): K0, K1 = ZZ['x'], ZZ f = [[K0(1)], [K0(2)], [], [K0(3)]] assert dmp_convert(f, 1, K0, K1) == \ [[ZZ(1)], [ZZ(2)], [], [ZZ(3)]] def test_dup_from_sympy(): assert dup_from_sympy([S(1), S(2)], ZZ) == \ [ZZ(1), ZZ(2)] assert dup_from_sympy([S(1)/2, S(3)], QQ) == \ [QQ(1, 2), QQ(3, 1)] def test_dmp_from_sympy(): assert dmp_from_sympy([[S(1), S(2)], [S(0)]], 1, ZZ) == \ [[ZZ(1), ZZ(2)], []] assert dmp_from_sympy([[S(1)/2, S(2)]], 1, QQ) == \ [[QQ(1, 2), QQ(2, 1)]] def test_dup_nth(): assert dup_nth([1, 2, 3], 0, ZZ) == 3 assert dup_nth([1, 2, 3], 1, ZZ) == 2 assert dup_nth([1, 2, 3], 2, ZZ) == 1 assert dup_nth([1, 2, 3], 9, ZZ) == 0 raises(IndexError, lambda: dup_nth([3, 4, 5], -1, ZZ)) def test_dmp_nth(): assert dmp_nth([[1], [2], [3]], 0, 1, ZZ) == [3] assert dmp_nth([[1], [2], [3]], 1, 1, ZZ) == [2] assert dmp_nth([[1], [2], [3]], 2, 1, ZZ) == [1] assert dmp_nth([[1], [2], [3]], 9, 1, ZZ) == [] raises(IndexError, lambda: dmp_nth([[3], [4], [5]], -1, 1, ZZ)) def test_dmp_ground_nth(): assert dmp_ground_nth([[1], [2], [3]], (0, 0), 1, ZZ) == 3 assert dmp_ground_nth([[1], [2], [3]], (1, 0), 1, ZZ) == 2 assert dmp_ground_nth([[1], [2], [3]], (2, 0), 1, ZZ) == 1 assert dmp_ground_nth([[1], [2], [3]], (2, 1), 1, ZZ) == 0 assert dmp_ground_nth([[1], [2], [3]], (3, 0), 1, ZZ) == 0 raises(IndexError, lambda: dmp_ground_nth([[3], [4], [5]], (2, -1), 1, ZZ)) def test_dmp_zero_p(): assert dmp_zero_p([], 0) is True assert dmp_zero_p([[]], 1) is True assert dmp_zero_p([[[]]], 2) is True assert dmp_zero_p([[[1]]], 2) is False def test_dmp_zero(): assert dmp_zero(0) == [] assert dmp_zero(2) == [[[]]] def test_dmp_one_p(): assert dmp_one_p([1], 0, ZZ) is True assert dmp_one_p([[1]], 1, ZZ) is True assert dmp_one_p([[[1]]], 2, ZZ) is True assert dmp_one_p([[[12]]], 2, ZZ) is False def test_dmp_one(): assert dmp_one(0, ZZ) == [ZZ(1)] assert dmp_one(2, ZZ) == [[[ZZ(1)]]] def test_dmp_ground_p(): assert dmp_ground_p([], 0, 0) is True assert dmp_ground_p([[]], 0, 1) is True assert dmp_ground_p([[]], 1, 1) is False assert dmp_ground_p([[ZZ(1)]], 1, 1) is True assert dmp_ground_p([[[ZZ(2)]]], 2, 2) is True assert dmp_ground_p([[[ZZ(2)]]], 3, 2) is False assert dmp_ground_p([[[ZZ(3)], []]], 3, 2) is False assert dmp_ground_p([], None, 0) is True assert dmp_ground_p([[]], None, 1) is True assert dmp_ground_p([ZZ(1)], None, 0) is True assert dmp_ground_p([[[ZZ(1)]]], None, 2) is True assert dmp_ground_p([[[ZZ(3)], []]], None, 2) is False def test_dmp_ground(): assert dmp_ground(ZZ(0), 2) == [[[]]] assert dmp_ground(ZZ(7), -1) == ZZ(7) assert dmp_ground(ZZ(7), 0) == [ZZ(7)] assert dmp_ground(ZZ(7), 2) == [[[ZZ(7)]]] def test_dmp_zeros(): assert dmp_zeros(4, 0, ZZ) == [[], [], [], []] assert dmp_zeros(0, 2, ZZ) == [] assert dmp_zeros(1, 2, ZZ) == [[[[]]]] assert dmp_zeros(2, 2, ZZ) == [[[[]]], [[[]]]] assert dmp_zeros(3, 2, ZZ) == [[[[]]], [[[]]], [[[]]]] assert dmp_zeros(3, -1, ZZ) == [0, 0, 0] def test_dmp_grounds(): assert dmp_grounds(ZZ(7), 0, 2) == [] assert dmp_grounds(ZZ(7), 1, 2) == [[[[7]]]] assert dmp_grounds(ZZ(7), 2, 2) == [[[[7]]], [[[7]]]] assert dmp_grounds(ZZ(7), 3, 2) == [[[[7]]], [[[7]]], [[[7]]]] assert dmp_grounds(ZZ(7), 3, -1) == [7, 7, 7] def test_dmp_negative_p(): assert dmp_negative_p([[[]]], 2, ZZ) is False assert dmp_negative_p([[[1], [2]]], 2, ZZ) is False assert dmp_negative_p([[[-1], [2]]], 2, ZZ) is True def test_dmp_positive_p(): assert dmp_positive_p([[[]]], 2, ZZ) is False assert dmp_positive_p([[[1], [2]]], 2, ZZ) is True assert dmp_positive_p([[[-1], [2]]], 2, ZZ) is False def test_dup_from_to_dict(): assert dup_from_raw_dict({}, ZZ) == [] assert dup_from_dict({}, ZZ) == [] assert dup_to_raw_dict([]) == {} assert dup_to_dict([]) == {} assert dup_to_raw_dict([], ZZ, zero=True) == {0: ZZ(0)} assert dup_to_dict([], ZZ, zero=True) == {(0,): ZZ(0)} f = [3, 0, 0, 2, 0, 0, 0, 0, 8] g = {8: 3, 5: 2, 0: 8} h = {(8,): 3, (5,): 2, (0,): 8} assert dup_from_raw_dict(g, ZZ) == f assert dup_from_dict(h, ZZ) == f assert dup_to_raw_dict(f) == g assert dup_to_dict(f) == h R, x,y = ring("x,y", ZZ) K = R.to_domain() f = [R(3), R(0), R(2), R(0), R(0), R(8)] g = {5: R(3), 3: R(2), 0: R(8)} h = {(5,): R(3), (3,): R(2), (0,): R(8)} assert dup_from_raw_dict(g, K) == f assert dup_from_dict(h, K) == f assert dup_to_raw_dict(f) == g assert dup_to_dict(f) == h def test_dmp_from_to_dict(): assert dmp_from_dict({}, 1, ZZ) == [[]] assert dmp_to_dict([[]], 1) == {} assert dmp_to_dict([], 0, ZZ, zero=True) == {(0,): ZZ(0)} assert dmp_to_dict([[]], 1, ZZ, zero=True) == {(0, 0): ZZ(0)} f = [[3], [], [], [2], [], [], [], [], [8]] g = {(8, 0): 3, (5, 0): 2, (0, 0): 8} assert dmp_from_dict(g, 1, ZZ) == f assert dmp_to_dict(f, 1) == g def test_dmp_swap(): f = dmp_normal([[1, 0, 0], [], [1, 0], [], [1]], 1, ZZ) g = dmp_normal([[1, 0, 0, 0, 0], [1, 0, 0], [1]], 1, ZZ) assert dmp_swap(f, 1, 1, 1, ZZ) == f assert dmp_swap(f, 0, 1, 1, ZZ) == g assert dmp_swap(g, 0, 1, 1, ZZ) == f raises(IndexError, lambda: dmp_swap(f, -1, -7, 1, ZZ)) def test_dmp_permute(): f = dmp_normal([[1, 0, 0], [], [1, 0], [], [1]], 1, ZZ) g = dmp_normal([[1, 0, 0, 0, 0], [1, 0, 0], [1]], 1, ZZ) assert dmp_permute(f, [0, 1], 1, ZZ) == f assert dmp_permute(g, [0, 1], 1, ZZ) == g assert dmp_permute(f, [1, 0], 1, ZZ) == g assert dmp_permute(g, [1, 0], 1, ZZ) == f def test_dmp_nest(): assert dmp_nest(ZZ(1), 2, ZZ) == [[[1]]] assert dmp_nest([[1]], 0, ZZ) == [[1]] assert dmp_nest([[1]], 1, ZZ) == [[[1]]] assert dmp_nest([[1]], 2, ZZ) == [[[[1]]]] def test_dmp_raise(): assert dmp_raise([], 2, 0, ZZ) == [[[]]] assert dmp_raise([[1]], 0, 1, ZZ) == [[1]] assert dmp_raise([[1, 2, 3], [], [2, 3]], 2, 1, ZZ) == \ [[[[1]], [[2]], [[3]]], [[[]]], [[[2]], [[3]]]] def test_dup_deflate(): assert dup_deflate([], ZZ) == (1, []) assert dup_deflate([2], ZZ) == (1, [2]) assert dup_deflate([1, 2, 3], ZZ) == (1, [1, 2, 3]) assert dup_deflate([1, 0, 2, 0, 3], ZZ) == (2, [1, 2, 3]) assert dup_deflate(dup_from_raw_dict({7: 1, 1: 1}, ZZ), ZZ) == \ (1, [1, 0, 0, 0, 0, 0, 1, 0]) assert dup_deflate(dup_from_raw_dict({7: 1, 0: 1}, ZZ), ZZ) == \ (7, [1, 1]) assert dup_deflate(dup_from_raw_dict({7: 1, 3: 1}, ZZ), ZZ) == \ (1, [1, 0, 0, 0, 1, 0, 0, 0]) assert dup_deflate(dup_from_raw_dict({7: 1, 4: 1}, ZZ), ZZ) == \ (1, [1, 0, 0, 1, 0, 0, 0, 0]) assert dup_deflate(dup_from_raw_dict({8: 1, 4: 1}, ZZ), ZZ) == \ (4, [1, 1, 0]) assert dup_deflate(dup_from_raw_dict({8: 1}, ZZ), ZZ) == \ (8, [1, 0]) assert dup_deflate(dup_from_raw_dict({7: 1}, ZZ), ZZ) == \ (7, [1, 0]) assert dup_deflate(dup_from_raw_dict({1: 1}, ZZ), ZZ) == \ (1, [1, 0]) def test_dmp_deflate(): assert dmp_deflate([[]], 1, ZZ) == ((1, 1), [[]]) assert dmp_deflate([[2]], 1, ZZ) == ((1, 1), [[2]]) f = [[1, 0, 0], [], [1, 0], [], [1]] assert dmp_deflate(f, 1, ZZ) == ((2, 1), [[1, 0, 0], [1, 0], [1]]) def test_dup_multi_deflate(): assert dup_multi_deflate(([2],), ZZ) == (1, ([2],)) assert dup_multi_deflate(([], []), ZZ) == (1, ([], [])) assert dup_multi_deflate(([1, 2, 3],), ZZ) == (1, ([1, 2, 3],)) assert dup_multi_deflate(([1, 0, 2, 0, 3],), ZZ) == (2, ([1, 2, 3],)) assert dup_multi_deflate(([1, 0, 2, 0, 3], [2, 0, 0]), ZZ) == \ (2, ([1, 2, 3], [2, 0])) assert dup_multi_deflate(([1, 0, 2, 0, 3], [2, 1, 0]), ZZ) == \ (1, ([1, 0, 2, 0, 3], [2, 1, 0])) def test_dmp_multi_deflate(): assert dmp_multi_deflate(([[]],), 1, ZZ) == \ ((1, 1), ([[]],)) assert dmp_multi_deflate(([[]], [[]]), 1, ZZ) == \ ((1, 1), ([[]], [[]])) assert dmp_multi_deflate(([[1]], [[]]), 1, ZZ) == \ ((1, 1), ([[1]], [[]])) assert dmp_multi_deflate(([[1]], [[2]]), 1, ZZ) == \ ((1, 1), ([[1]], [[2]])) assert dmp_multi_deflate(([[1]], [[2, 0]]), 1, ZZ) == \ ((1, 1), ([[1]], [[2, 0]])) assert dmp_multi_deflate(([[2, 0]], [[2, 0]]), 1, ZZ) == \ ((1, 1), ([[2, 0]], [[2, 0]])) assert dmp_multi_deflate( ([[2]], [[2, 0, 0]]), 1, ZZ) == ((1, 2), ([[2]], [[2, 0]])) assert dmp_multi_deflate( ([[2, 0, 0]], [[2, 0, 0]]), 1, ZZ) == ((1, 2), ([[2, 0]], [[2, 0]])) assert dmp_multi_deflate(([2, 0, 0], [1, 0, 4, 0, 1]), 0, ZZ) == \ ((2,), ([2, 0], [1, 4, 1])) f = [[1, 0, 0], [], [1, 0], [], [1]] g = [[1, 0, 1, 0], [], [1]] assert dmp_multi_deflate((f,), 1, ZZ) == \ ((2, 1), ([[1, 0, 0], [1, 0], [1]],)) assert dmp_multi_deflate((f, g), 1, ZZ) == \ ((2, 1), ([[1, 0, 0], [1, 0], [1]], [[1, 0, 1, 0], [1]])) def test_dup_inflate(): assert dup_inflate([], 17, ZZ) == [] assert dup_inflate([1, 2, 3], 1, ZZ) == [1, 2, 3] assert dup_inflate([1, 2, 3], 2, ZZ) == [1, 0, 2, 0, 3] assert dup_inflate([1, 2, 3], 3, ZZ) == [1, 0, 0, 2, 0, 0, 3] assert dup_inflate([1, 2, 3], 4, ZZ) == [1, 0, 0, 0, 2, 0, 0, 0, 3] raises(IndexError, lambda: dup_inflate([1, 2, 3], 0, ZZ)) def test_dmp_inflate(): assert dmp_inflate([1], (3,), 0, ZZ) == [1] assert dmp_inflate([[]], (3, 7), 1, ZZ) == [[]] assert dmp_inflate([[2]], (1, 2), 1, ZZ) == [[2]] assert dmp_inflate([[2, 0]], (1, 1), 1, ZZ) == [[2, 0]] assert dmp_inflate([[2, 0]], (1, 2), 1, ZZ) == [[2, 0, 0]] assert dmp_inflate([[2, 0]], (1, 3), 1, ZZ) == [[2, 0, 0, 0]] assert dmp_inflate([[1, 0, 0], [1], [1, 0]], (2, 1), 1, ZZ) == \ [[1, 0, 0], [], [1], [], [1, 0]] raises(IndexError, lambda: dmp_inflate([[]], (-3, 7), 1, ZZ)) def test_dmp_exclude(): assert dmp_exclude([[[]]], 2, ZZ) == ([], [[[]]], 2) assert dmp_exclude([[[7]]], 2, ZZ) == ([], [[[7]]], 2) assert dmp_exclude([1, 2, 3], 0, ZZ) == ([], [1, 2, 3], 0) assert dmp_exclude([[1], [2, 3]], 1, ZZ) == ([], [[1], [2, 3]], 1) assert dmp_exclude([[1, 2, 3]], 1, ZZ) == ([0], [1, 2, 3], 0) assert dmp_exclude([[1], [2], [3]], 1, ZZ) == ([1], [1, 2, 3], 0) assert dmp_exclude([[[1, 2, 3]]], 2, ZZ) == ([0, 1], [1, 2, 3], 0) assert dmp_exclude([[[1]], [[2]], [[3]]], 2, ZZ) == ([1, 2], [1, 2, 3], 0) def test_dmp_include(): assert dmp_include([1, 2, 3], [], 0, ZZ) == [1, 2, 3] assert dmp_include([1, 2, 3], [0], 0, ZZ) == [[1, 2, 3]] assert dmp_include([1, 2, 3], [1], 0, ZZ) == [[1], [2], [3]] assert dmp_include([1, 2, 3], [0, 1], 0, ZZ) == [[[1, 2, 3]]] assert dmp_include([1, 2, 3], [1, 2], 0, ZZ) == [[[1]], [[2]], [[3]]] def test_dmp_inject(): R, x,y = ring("x,y", ZZ) K = R.to_domain() assert dmp_inject([], 0, K) == ([[[]]], 2) assert dmp_inject([[]], 1, K) == ([[[[]]]], 3) assert dmp_inject([R(1)], 0, K) == ([[[1]]], 2) assert dmp_inject([[R(1)]], 1, K) == ([[[[1]]]], 3) assert dmp_inject([R(1), 2*x + 3*y + 4], 0, K) == ([[[1]], [[2], [3, 4]]], 2) f = [3*x**2 + 7*x*y + 5*y**2, 2*x, R(0), x*y**2 + 11] g = [[[3], [7, 0], [5, 0, 0]], [[2], []], [[]], [[1, 0, 0], [11]]] assert dmp_inject(f, 0, K) == (g, 2) def test_dmp_eject(): R, x,y = ring("x,y", ZZ) K = R.to_domain() assert dmp_eject([[[]]], 2, K) == [] assert dmp_eject([[[[]]]], 3, K) == [[]] assert dmp_eject([[[1]]], 2, K) == [R(1)] assert dmp_eject([[[[1]]]], 3, K) == [[R(1)]] assert dmp_eject([[[1]], [[2], [3, 4]]], 2, K) == [R(1), 2*x + 3*y + 4] f = [3*x**2 + 7*x*y + 5*y**2, 2*x, R(0), x*y**2 + 11] g = [[[3], [7, 0], [5, 0, 0]], [[2], []], [[]], [[1, 0, 0], [11]]] assert dmp_eject(g, 2, K) == f def test_dup_terms_gcd(): assert dup_terms_gcd([], ZZ) == (0, []) assert dup_terms_gcd([1, 0, 1], ZZ) == (0, [1, 0, 1]) assert dup_terms_gcd([1, 0, 1, 0], ZZ) == (1, [1, 0, 1]) def test_dmp_terms_gcd(): assert dmp_terms_gcd([[]], 1, ZZ) == ((0, 0), [[]]) assert dmp_terms_gcd([1, 0, 1, 0], 0, ZZ) == ((1,), [1, 0, 1]) assert dmp_terms_gcd([[1], [], [1], []], 1, ZZ) == ((1, 0), [[1], [], [1]]) assert dmp_terms_gcd( [[1, 0], [], [1]], 1, ZZ) == ((0, 0), [[1, 0], [], [1]]) assert dmp_terms_gcd( [[1, 0], [1, 0, 0], [], []], 1, ZZ) == ((2, 1), [[1], [1, 0]]) def test_dmp_list_terms(): assert dmp_list_terms([[[]]], 2, ZZ) == [((0, 0, 0), 0)] assert dmp_list_terms([[[1]]], 2, ZZ) == [((0, 0, 0), 1)] assert dmp_list_terms([1, 2, 4, 3, 5], 0, ZZ) == \ [((4,), 1), ((3,), 2), ((2,), 4), ((1,), 3), ((0,), 5)] assert dmp_list_terms([[1], [2, 4], [3, 5, 0]], 1, ZZ) == \ [((2, 0), 1), ((1, 1), 2), ((1, 0), 4), ((0, 2), 3), ((0, 1), 5)] f = [[2, 0, 0, 0], [1, 0, 0], []] assert dmp_list_terms(f, 1, ZZ, order='lex') == [((2, 3), 2), ((1, 2), 1)] assert dmp_list_terms( f, 1, ZZ, order='grlex') == [((2, 3), 2), ((1, 2), 1)] f = [[2, 0, 0, 0], [1, 0, 0, 0, 0, 0], []] assert dmp_list_terms(f, 1, ZZ, order='lex') == [((2, 3), 2), ((1, 5), 1)] assert dmp_list_terms( f, 1, ZZ, order='grlex') == [((1, 5), 1), ((2, 3), 2)] def test_dmp_apply_pairs(): h = lambda a, b: a*b assert dmp_apply_pairs([1, 2, 3], [4, 5, 6], h, [], 0, ZZ) == [4, 10, 18] assert dmp_apply_pairs([2, 3], [4, 5, 6], h, [], 0, ZZ) == [10, 18] assert dmp_apply_pairs([1, 2, 3], [5, 6], h, [], 0, ZZ) == [10, 18] assert dmp_apply_pairs( [[1, 2], [3]], [[4, 5], [6]], h, [], 1, ZZ) == [[4, 10], [18]] assert dmp_apply_pairs( [[1, 2], [3]], [[4], [5, 6]], h, [], 1, ZZ) == [[8], [18]] assert dmp_apply_pairs( [[1], [2, 3]], [[4, 5], [6]], h, [], 1, ZZ) == [[5], [18]] def test_dup_slice(): f = [1, 2, 3, 4] assert dup_slice(f, 0, 0, ZZ) == [] assert dup_slice(f, 0, 1, ZZ) == [4] assert dup_slice(f, 0, 2, ZZ) == [3, 4] assert dup_slice(f, 0, 3, ZZ) == [2, 3, 4] assert dup_slice(f, 0, 4, ZZ) == [1, 2, 3, 4] assert dup_slice(f, 0, 4, ZZ) == f assert dup_slice(f, 0, 9, ZZ) == f assert dup_slice(f, 1, 0, ZZ) == [] assert dup_slice(f, 1, 1, ZZ) == [] assert dup_slice(f, 1, 2, ZZ) == [3, 0] assert dup_slice(f, 1, 3, ZZ) == [2, 3, 0] assert dup_slice(f, 1, 4, ZZ) == [1, 2, 3, 0] assert dup_slice([1, 2], 0, 3, ZZ) == [1, 2] def test_dup_random(): f = dup_random(0, -10, 10, ZZ) assert dup_degree(f) == 0 assert all(-10 <= c <= 10 for c in f) f = dup_random(1, -20, 20, ZZ) assert dup_degree(f) == 1 assert all(-20 <= c <= 20 for c in f) f = dup_random(2, -30, 30, ZZ) assert dup_degree(f) == 2 assert all(-30 <= c <= 30 for c in f) f = dup_random(3, -40, 40, ZZ) assert dup_degree(f) == 3 assert all(-40 <= c <= 40 for c in f)
bsd-3-clause
-5,866,670,252,548,682,000
28.699446
81
0.449937
false
appneta/boto
boto/ec2/autoscale/activity.py
152
3058
# Copyright (c) 2009-2011 Reza Lotun http://reza.lotun.name/ # # 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 datetime import datetime class Activity(object): def __init__(self, connection=None): self.connection = connection self.start_time = None self.end_time = None self.activity_id = None self.progress = None self.status_code = None self.cause = None self.description = None self.status_message = None self.group_name = None def __repr__(self): return 'Activity<%s>: For group:%s, progress:%s, cause:%s' % (self.activity_id, self.group_name, self.status_message, self.cause) def startElement(self, name, attrs, connection): return None def endElement(self, name, value, connection): if name == 'ActivityId': self.activity_id = value elif name == 'AutoScalingGroupName': self.group_name = value elif name == 'StartTime': try: self.start_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ') except ValueError: self.start_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ') elif name == 'EndTime': try: self.end_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ') except ValueError: self.end_time = datetime.strptime(value, '%Y-%m-%dT%H:%M:%SZ') elif name == 'Progress': self.progress = value elif name == 'Cause': self.cause = value elif name == 'Description': self.description = value elif name == 'StatusMessage': self.status_message = value elif name == 'StatusCode': self.status_code = value else: setattr(self, name, value)
mit
-8,752,645,475,448,993,000
40.890411
90
0.590582
false
h3biomed/ansible
lib/ansible/modules/network/avi/avi_wafprofile.py
31
3819
#!/usr/bin/python # # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # # Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com> # 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': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_wafprofile author: Gaurav Rastogi (@grastogi23) <grastogi@avinetworks.com> short_description: Module for setup of WafProfile Avi RESTful Object description: - This module is used to configure WafProfile object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.5" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent", "present"] avi_api_update_method: description: - Default method for object update is HTTP PUT. - Setting to patch will override that behavior to use HTTP PATCH. version_added: "2.5" default: put choices: ["put", "patch"] avi_api_patch_op: description: - Patch operation to use when using avi_api_update_method as patch. version_added: "2.5" choices: ["add", "replace", "delete"] config: description: - Config params for waf. - Field introduced in 17.2.1. required: true description: description: - Field introduced in 17.2.1. files: description: - List of data files used for waf rules. - Field introduced in 17.2.1. name: description: - Field introduced in 17.2.1. required: true tenant_ref: description: - It is a reference to an object of type tenant. - Field introduced in 17.2.1. url: description: - Avi controller URL of the object. uuid: description: - Field introduced in 17.2.1. extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Example to create WafProfile object avi_wafprofile: controller: 10.10.25.42 username: admin password: something state: present name: sample_wafprofile """ RETURN = ''' obj: description: WafProfile (api/wafprofile) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.avi import ( avi_common_argument_spec, HAS_AVI, avi_ansible_api) except ImportError: HAS_AVI = False def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), config=dict(type='dict', required=True), description=dict(type='str',), files=dict(type='list',), name=dict(type='str', required=True), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'wafprofile', set([])) if __name__ == '__main__': main()
gpl-3.0
-676,973,080,193,106,200
29.309524
92
0.59911
false
vberaudi/scipy
scipy/weave/examples/swig2_example.py
100
1596
"""Simple example to show how to use weave.inline on SWIG2 wrapped objects. SWIG2 refers to SWIG versions >= 1.3. To run this example you must build the trivial SWIG2 extension called swig2_ext. To do this you need to do something like this:: $ swig -c++ -python -I. -o swig2_ext_wrap.cxx swig2_ext.i $ g++ -Wall -O2 -I/usr/include/python2.3 -fPIC -I. -c \ -o swig2_ext_wrap.os swig2_ext_wrap.cxx $ g++ -shared -o _swig2_ext.so swig2_ext_wrap.os \ -L/usr/lib/python2.3/config The files swig2_ext.i and swig2_ext.h are included in the same directory that contains this file. Note that weave's SWIG2 support works fine whether SWIG_COBJECT_TYPES are used or not. Author: Prabhu Ramachandran Copyright (c) 2004, Prabhu Ramachandran License: BSD Style. """ from __future__ import absolute_import, print_function # Import our SWIG2 wrapped library import swig2_ext import scipy.weave as weave from scipy.weave import swig2_spec, converters # SWIG2 support is not enabled by default. We do this by adding the # swig2 converter to the default list of converters. converters.default.insert(0, swig2_spec.swig2_converter()) def test(): """Instantiate the SWIG wrapped object and then call its method from C++ using weave.inline """ a = swig2_ext.A() b = swig2_ext.foo() # This will be an APtr instance. b.thisown = 1 # Prevent memory leaks. code = """a->f(); b->f(); """ weave.inline(code, ['a', 'b'], include_dirs=['.'], headers=['"swig2_ext.h"'], verbose=1) if __name__ == "__main__": test()
bsd-3-clause
-9,217,083,417,520,616,000
28.018182
69
0.672306
false
square/pants
src/python/pants/cache/artifact.py
2
4458
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) import errno import os import shutil import tarfile from pants.util.contextutil import open_tar from pants.util.dirutil import safe_mkdir, safe_mkdir_for, safe_walk class ArtifactError(Exception): pass class Artifact(object): """Represents a set of files in an artifact.""" def __init__(self, artifact_root): # All files must be under this root. self._artifact_root = artifact_root # The files known to be in this artifact, relative to artifact_root. self._relpaths = set() def get_paths(self): for relpath in self._relpaths: yield os.path.join(self._artifact_root, relpath) def override_paths(self, paths): # Use with care. self._relpaths = set([os.path.relpath(path, self._artifact_root) for path in paths]) def collect(self, paths): """Collect the paths (which must be under artifact root) into this artifact.""" raise NotImplementedError() def extract(self): """Extract the files in this artifact to their locations under artifact root.""" raise NotImplementedError() class DirectoryArtifact(Artifact): """An artifact stored as loose files under a directory.""" def __init__(self, artifact_root, directory): Artifact.__init__(self, artifact_root) self._directory = directory def collect(self, paths): for path in paths or (): relpath = os.path.relpath(path, self._artifact_root) dst = os.path.join(self._directory, relpath) safe_mkdir(os.path.dirname(dst)) if os.path.isdir(path): shutil.copytree(path, dst) else: shutil.copy(path, dst) self._relpaths.add(relpath) def extract(self): for dir_name, _, filenames in safe_walk(self._directory): for filename in filenames: filename = os.path.join(dir_name, filename) relpath = os.path.relpath(filename, self._directory) dst = os.path.join(self._artifact_root, relpath) safe_mkdir_for(dst) shutil.copy(filename, dst) self._relpaths.add(relpath) class TarballArtifact(Artifact): """An artifact stored in a tarball.""" def __init__(self, artifact_root, tarfile, compression=9): Artifact.__init__(self, artifact_root) self._tarfile = tarfile self._compression = compression def collect(self, paths): # In our tests, gzip is slightly less compressive than bzip2 on .class files, # but decompression times are much faster. mode = 'w:gz' if self._compression else 'w' tar_kwargs = {'dereference': True, 'errorlevel': 2} if self._compression: tar_kwargs['compresslevel'] = self._compression with open_tar(self._tarfile, mode, **tar_kwargs) as tarout: for path in paths or (): # Adds dirs recursively. relpath = os.path.relpath(path, self._artifact_root) tarout.add(path, relpath) self._relpaths.add(relpath) def extract(self): try: with open_tar(self._tarfile, 'r', errorlevel=2) as tarin: # Note: We create all needed paths proactively, even though extractall() can do this for us. # This is because we may be called concurrently on multiple artifacts that share directories, # and there will be a race condition inside extractall(): task T1 A) sees that a directory # doesn't exist and B) tries to create it. But in the gap between A) and B) task T2 creates # the same directory, so T1 throws "File exists" in B). # This actually happened, and was very hard to debug. # Creating the paths here up front allows us to squelch that "File exists" error. paths = [] dirs = set() for tarinfo in tarin.getmembers(): paths.append(tarinfo.name) if tarinfo.isdir(): dirs.add(tarinfo.name) else: dirs.add(os.path.dirname(tarinfo.name)) for d in dirs: try: os.makedirs(os.path.join(self._artifact_root, d)) except OSError as e: if e.errno != errno.EEXIST: raise tarin.extractall(self._artifact_root) self._relpaths.update(paths) except tarfile.ReadError as e: raise ArtifactError(e.message)
apache-2.0
-6,264,832,763,316,345,000
34.951613
101
0.658591
false
amisrs/one-eighty
venv2/lib/python2.7/site-packages/sqlalchemy/sql/elements.py
15
148811
# sql/elements.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Core SQL expression elements, including :class:`.ClauseElement`, :class:`.ColumnElement`, and derived classes. """ from __future__ import unicode_literals from .. import util, exc, inspection from . import type_api from . import operators from .visitors import Visitable, cloned_traverse, traverse from .annotation import Annotated import itertools from .base import Executable, PARSE_AUTOCOMMIT, Immutable, NO_ARG from .base import _generative import numbers import re import operator def _clone(element, **kw): return element._clone() def collate(expression, collation): """Return the clause ``expression COLLATE collation``. e.g.:: collate(mycolumn, 'utf8_bin') produces:: mycolumn COLLATE utf8_bin """ expr = _literal_as_binds(expression) return BinaryExpression( expr, _literal_as_text(collation), operators.collate, type_=expr.type) def between(expr, lower_bound, upper_bound, symmetric=False): """Produce a ``BETWEEN`` predicate clause. E.g.:: from sqlalchemy import between stmt = select([users_table]).where(between(users_table.c.id, 5, 7)) Would produce SQL resembling:: SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2 The :func:`.between` function is a standalone version of the :meth:`.ColumnElement.between` method available on all SQL expressions, as in:: stmt = select([users_table]).where(users_table.c.id.between(5, 7)) All arguments passed to :func:`.between`, including the left side column expression, are coerced from Python scalar values if a the value is not a :class:`.ColumnElement` subclass. For example, three fixed values can be compared as in:: print(between(5, 3, 7)) Which would produce:: :param_1 BETWEEN :param_2 AND :param_3 :param expr: a column expression, typically a :class:`.ColumnElement` instance or alternatively a Python scalar expression to be coerced into a column expression, serving as the left side of the ``BETWEEN`` expression. :param lower_bound: a column or Python scalar expression serving as the lower bound of the right side of the ``BETWEEN`` expression. :param upper_bound: a column or Python scalar expression serving as the upper bound of the right side of the ``BETWEEN`` expression. :param symmetric: if True, will render " BETWEEN SYMMETRIC ". Note that not all databases support this syntax. .. versionadded:: 0.9.5 .. seealso:: :meth:`.ColumnElement.between` """ expr = _literal_as_binds(expr) return expr.between(lower_bound, upper_bound, symmetric=symmetric) def literal(value, type_=None): r"""Return a literal clause, bound to a bind parameter. Literal clauses are created automatically when non- :class:`.ClauseElement` objects (such as strings, ints, dates, etc.) are used in a comparison operation with a :class:`.ColumnElement` subclass, such as a :class:`~sqlalchemy.schema.Column` object. Use this function to force the generation of a literal clause, which will be created as a :class:`BindParameter` with a bound value. :param value: the value to be bound. Can be any Python object supported by the underlying DB-API, or is translatable via the given type argument. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which will provide bind-parameter translation for this literal. """ return BindParameter(None, value, type_=type_, unique=True) def outparam(key, type_=None): """Create an 'OUT' parameter for usage in functions (stored procedures), for databases which support them. The ``outparam`` can be used like a regular function parameter. The "output" value will be available from the :class:`~sqlalchemy.engine.ResultProxy` object via its ``out_parameters`` attribute, which returns a dictionary containing the values. """ return BindParameter( key, None, type_=type_, unique=False, isoutparam=True) def not_(clause): """Return a negation of the given clause, i.e. ``NOT(clause)``. The ``~`` operator is also overloaded on all :class:`.ColumnElement` subclasses to produce the same result. """ return operators.inv(_literal_as_binds(clause)) @inspection._self_inspects class ClauseElement(Visitable): """Base class for elements of a programmatically constructed SQL expression. """ __visit_name__ = 'clause' _annotations = {} supports_execution = False _from_objects = [] bind = None _is_clone_of = None is_selectable = False is_clause_element = True description = None _order_by_label_element = None _is_from_container = False def _clone(self): """Create a shallow copy of this ClauseElement. This method may be used by a generative API. Its also used as part of the "deep" copy afforded by a traversal that combines the _copy_internals() method. """ c = self.__class__.__new__(self.__class__) c.__dict__ = self.__dict__.copy() ClauseElement._cloned_set._reset(c) ColumnElement.comparator._reset(c) # this is a marker that helps to "equate" clauses to each other # when a Select returns its list of FROM clauses. the cloning # process leaves around a lot of remnants of the previous clause # typically in the form of column expressions still attached to the # old table. c._is_clone_of = self return c @property def _constructor(self): """return the 'constructor' for this ClauseElement. This is for the purposes for creating a new object of this type. Usually, its just the element's __class__. However, the "Annotated" version of the object overrides to return the class of its proxied element. """ return self.__class__ @util.memoized_property def _cloned_set(self): """Return the set consisting all cloned ancestors of this ClauseElement. Includes this ClauseElement. This accessor tends to be used for FromClause objects to identify 'equivalent' FROM clauses, regardless of transformative operations. """ s = util.column_set() f = self while f is not None: s.add(f) f = f._is_clone_of return s def __getstate__(self): d = self.__dict__.copy() d.pop('_is_clone_of', None) return d def _annotate(self, values): """return a copy of this ClauseElement with annotations updated by the given dictionary. """ return Annotated(self, values) def _with_annotations(self, values): """return a copy of this ClauseElement with annotations replaced by the given dictionary. """ return Annotated(self, values) def _deannotate(self, values=None, clone=False): """return a copy of this :class:`.ClauseElement` with annotations removed. :param values: optional tuple of individual values to remove. """ if clone: # clone is used when we are also copying # the expression for a deep deannotation return self._clone() else: # if no clone, since we have no annotations we return # self return self def _execute_on_connection(self, connection, multiparams, params): if self.supports_execution: return connection._execute_clauseelement(self, multiparams, params) else: raise exc.ObjectNotExecutableError(self) def unique_params(self, *optionaldict, **kwargs): """Return a copy with :func:`bindparam()` elements replaced. Same functionality as ``params()``, except adds `unique=True` to affected bind parameters so that multiple statements can be used. """ return self._params(True, optionaldict, kwargs) def params(self, *optionaldict, **kwargs): """Return a copy with :func:`bindparam()` elements replaced. Returns a copy of this ClauseElement with :func:`bindparam()` elements replaced with values taken from the given dictionary:: >>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7} """ return self._params(False, optionaldict, kwargs) def _params(self, unique, optionaldict, kwargs): if len(optionaldict) == 1: kwargs.update(optionaldict[0]) elif len(optionaldict) > 1: raise exc.ArgumentError( "params() takes zero or one positional dictionary argument") def visit_bindparam(bind): if bind.key in kwargs: bind.value = kwargs[bind.key] bind.required = False if unique: bind._convert_to_unique() return cloned_traverse(self, {}, {'bindparam': visit_bindparam}) def compare(self, other, **kw): r"""Compare this ClauseElement to the given ClauseElement. Subclasses should override the default behavior, which is a straight identity comparison. \**kw are arguments consumed by subclass compare() methods and may be used to modify the criteria for comparison. (see :class:`.ColumnElement`) """ return self is other def _copy_internals(self, clone=_clone, **kw): """Reassign internal elements to be clones of themselves. Called during a copy-and-traverse operation on newly shallow-copied elements to create a deep copy. The given clone function should be used, which may be applying additional transformations to the element (i.e. replacement traversal, cloned traversal, annotations). """ pass def get_children(self, **kwargs): r"""Return immediate child elements of this :class:`.ClauseElement`. This is used for visit traversal. \**kwargs may contain flags that change the collection that is returned, for example to return a subset of items in order to cut down on larger traversals, or to return child items from a different context (such as schema-level collections instead of clause-level). """ return [] def self_group(self, against=None): """Apply a 'grouping' to this :class:`.ClauseElement`. This method is overridden by subclasses to return a "grouping" construct, i.e. parenthesis. In particular it's used by "binary" expressions to provide a grouping around themselves when placed into a larger expression, as well as by :func:`.select` constructs when placed into the FROM clause of another :func:`.select`. (Note that subqueries should be normally created using the :meth:`.Select.alias` method, as many platforms require nested SELECT statements to be named). As expressions are composed together, the application of :meth:`self_group` is automatic - end-user code should never need to use this method directly. Note that SQLAlchemy's clause constructs take operator precedence into account - so parenthesis might not be needed, for example, in an expression like ``x OR (y AND z)`` - AND takes precedence over OR. The base :meth:`self_group` method of :class:`.ClauseElement` just returns self. """ return self @util.dependencies("sqlalchemy.engine.default") def compile(self, default, bind=None, dialect=None, **kw): """Compile this SQL expression. The return value is a :class:`~.Compiled` object. Calling ``str()`` or ``unicode()`` on the returned value will yield a string representation of the result. The :class:`~.Compiled` object also can return a dictionary of bind parameter names and values using the ``params`` accessor. :param bind: An ``Engine`` or ``Connection`` from which a ``Compiled`` will be acquired. This argument takes precedence over this :class:`.ClauseElement`'s bound engine, if any. :param column_keys: Used for INSERT and UPDATE statements, a list of column names which should be present in the VALUES clause of the compiled statement. If ``None``, all columns from the target table object are rendered. :param dialect: A ``Dialect`` instance from which a ``Compiled`` will be acquired. This argument takes precedence over the `bind` argument as well as this :class:`.ClauseElement`'s bound engine, if any. :param inline: Used for INSERT statements, for a dialect which does not support inline retrieval of newly generated primary key columns, will force the expression used to create the new primary key value to be rendered inline within the INSERT statement's VALUES clause. This typically refers to Sequence execution but may also refer to any server-side default generation function associated with a primary key `Column`. :param compile_kwargs: optional dictionary of additional parameters that will be passed through to the compiler within all "visit" methods. This allows any custom flag to be passed through to a custom compilation construct, for example. It is also used for the case of passing the ``literal_binds`` flag through:: from sqlalchemy.sql import table, column, select t = table('t', column('x')) s = select([t]).where(t.c.x == 5) print s.compile(compile_kwargs={"literal_binds": True}) .. versionadded:: 0.9.0 .. seealso:: :ref:`faq_sql_expression_string` """ if not dialect: if bind: dialect = bind.dialect elif self.bind: dialect = self.bind.dialect bind = self.bind else: dialect = default.StrCompileDialect() return self._compiler(dialect, bind=bind, **kw) def _compiler(self, dialect, **kw): """Return a compiler appropriate for this ClauseElement, given a Dialect.""" return dialect.statement_compiler(dialect, self, **kw) def __str__(self): if util.py3k: return str(self.compile()) else: return unicode(self.compile()).encode('ascii', 'backslashreplace') def __and__(self, other): """'and' at the ClauseElement level. .. deprecated:: 0.9.5 - conjunctions are intended to be at the :class:`.ColumnElement`. level """ return and_(self, other) def __or__(self, other): """'or' at the ClauseElement level. .. deprecated:: 0.9.5 - conjunctions are intended to be at the :class:`.ColumnElement`. level """ return or_(self, other) def __invert__(self): if hasattr(self, 'negation_clause'): return self.negation_clause else: return self._negate() def _negate(self): return UnaryExpression( self.self_group(against=operators.inv), operator=operators.inv, negate=None) def __bool__(self): raise TypeError("Boolean value of this clause is not defined") __nonzero__ = __bool__ def __repr__(self): friendly = self.description if friendly is None: return object.__repr__(self) else: return '<%s.%s at 0x%x; %s>' % ( self.__module__, self.__class__.__name__, id(self), friendly) class ColumnElement(operators.ColumnOperators, ClauseElement): """Represent a column-oriented SQL expression suitable for usage in the "columns" clause, WHERE clause etc. of a statement. While the most familiar kind of :class:`.ColumnElement` is the :class:`.Column` object, :class:`.ColumnElement` serves as the basis for any unit that may be present in a SQL expression, including the expressions themselves, SQL functions, bound parameters, literal expressions, keywords such as ``NULL``, etc. :class:`.ColumnElement` is the ultimate base class for all such elements. A wide variety of SQLAlchemy Core functions work at the SQL expression level, and are intended to accept instances of :class:`.ColumnElement` as arguments. These functions will typically document that they accept a "SQL expression" as an argument. What this means in terms of SQLAlchemy usually refers to an input which is either already in the form of a :class:`.ColumnElement` object, or a value which can be **coerced** into one. The coercion rules followed by most, but not all, SQLAlchemy Core functions with regards to SQL expressions are as follows: * a literal Python value, such as a string, integer or floating point value, boolean, datetime, ``Decimal`` object, or virtually any other Python object, will be coerced into a "literal bound value". This generally means that a :func:`.bindparam` will be produced featuring the given value embedded into the construct; the resulting :class:`.BindParameter` object is an instance of :class:`.ColumnElement`. The Python value will ultimately be sent to the DBAPI at execution time as a paramterized argument to the ``execute()`` or ``executemany()`` methods, after SQLAlchemy type-specific converters (e.g. those provided by any associated :class:`.TypeEngine` objects) are applied to the value. * any special object value, typically ORM-level constructs, which feature a method called ``__clause_element__()``. The Core expression system looks for this method when an object of otherwise unknown type is passed to a function that is looking to coerce the argument into a :class:`.ColumnElement` expression. The ``__clause_element__()`` method, if present, should return a :class:`.ColumnElement` instance. The primary use of ``__clause_element__()`` within SQLAlchemy is that of class-bound attributes on ORM-mapped classes; a ``User`` class which contains a mapped attribute named ``.name`` will have a method ``User.name.__clause_element__()`` which when invoked returns the :class:`.Column` called ``name`` associated with the mapped table. * The Python ``None`` value is typically interpreted as ``NULL``, which in SQLAlchemy Core produces an instance of :func:`.null`. A :class:`.ColumnElement` provides the ability to generate new :class:`.ColumnElement` objects using Python expressions. This means that Python operators such as ``==``, ``!=`` and ``<`` are overloaded to mimic SQL operations, and allow the instantiation of further :class:`.ColumnElement` instances which are composed from other, more fundamental :class:`.ColumnElement` objects. For example, two :class:`.ColumnClause` objects can be added together with the addition operator ``+`` to produce a :class:`.BinaryExpression`. Both :class:`.ColumnClause` and :class:`.BinaryExpression` are subclasses of :class:`.ColumnElement`:: >>> from sqlalchemy.sql import column >>> column('a') + column('b') <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0> >>> print column('a') + column('b') a + b .. seealso:: :class:`.Column` :func:`.expression.column` """ __visit_name__ = 'column' primary_key = False foreign_keys = [] _label = None """The named label that can be used to target this column in a result set. This label is almost always the label used when rendering <expr> AS <label> in a SELECT statement. It also refers to a name that this column expression can be located from in a result set. For a regular Column bound to a Table, this is typically the label <tablename>_<columnname>. For other constructs, different rules may apply, such as anonymized labels and others. """ key = None """the 'key' that in some circumstances refers to this object in a Python namespace. This typically refers to the "key" of the column as present in the ``.c`` collection of a selectable, e.g. sometable.c["somekey"] would return a Column with a .key of "somekey". """ _key_label = None """A label-based version of 'key' that in some circumstances refers to this object in a Python namespace. _key_label comes into play when a select() statement is constructed with apply_labels(); in this case, all Column objects in the ``.c`` collection are rendered as <tablename>_<columnname> in SQL; this is essentially the value of ._label. But to locate those columns in the ``.c`` collection, the name is along the lines of <tablename>_<key>; that's the typical value of .key_label. """ _render_label_in_columns_clause = True """A flag used by select._columns_plus_names that helps to determine we are actually going to render in terms of "SELECT <col> AS <label>". This flag can be returned as False for some Column objects that want to be rendered as simple "SELECT <col>"; typically columns that don't have any parent table and are named the same as what the label would be in any case. """ _resolve_label = None """The name that should be used to identify this ColumnElement in a select() object when "label resolution" logic is used; this refers to using a string name in an expression like order_by() or group_by() that wishes to target a labeled expression in the columns clause. The name is distinct from that of .name or ._label to account for the case where anonymizing logic may be used to change the name that's actually rendered at compile time; this attribute should hold onto the original name that was user-assigned when producing a .label() construct. """ _allow_label_resolve = True """A flag that can be flipped to prevent a column from being resolvable by string label name.""" _alt_names = () def self_group(self, against=None): if (against in (operators.and_, operators.or_, operators._asbool) and self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity): return AsBoolean(self, operators.istrue, operators.isfalse) elif (against in (operators.any_op, operators.all_op)): return Grouping(self) else: return self def _negate(self): if self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity: # TODO: see the note in AsBoolean that it seems to assume # the element is the True_() / False_() constant, so this # is too broad return AsBoolean(self, operators.isfalse, operators.istrue) else: return super(ColumnElement, self)._negate() @util.memoized_property def type(self): return type_api.NULLTYPE @util.memoized_property def comparator(self): try: comparator_factory = self.type.comparator_factory except AttributeError: raise TypeError( "Object %r associated with '.type' attribute " "is not a TypeEngine class or object" % self.type) else: return comparator_factory(self) def __getattr__(self, key): try: return getattr(self.comparator, key) except AttributeError: raise AttributeError( 'Neither %r object nor %r object has an attribute %r' % ( type(self).__name__, type(self.comparator).__name__, key) ) def operate(self, op, *other, **kwargs): return op(self.comparator, *other, **kwargs) def reverse_operate(self, op, other, **kwargs): return op(other, self.comparator, **kwargs) def _bind_param(self, operator, obj, type_=None): return BindParameter(None, obj, _compared_to_operator=operator, type_=type_, _compared_to_type=self.type, unique=True) @property def expression(self): """Return a column expression. Part of the inspection interface; returns self. """ return self @property def _select_iterable(self): return (self, ) @util.memoized_property def base_columns(self): return util.column_set(c for c in self.proxy_set if not hasattr(c, '_proxies')) @util.memoized_property def proxy_set(self): s = util.column_set([self]) if hasattr(self, '_proxies'): for c in self._proxies: s.update(c.proxy_set) return s def shares_lineage(self, othercolumn): """Return True if the given :class:`.ColumnElement` has a common ancestor to this :class:`.ColumnElement`.""" return bool(self.proxy_set.intersection(othercolumn.proxy_set)) def _compare_name_for_result(self, other): """Return True if the given column element compares to this one when targeting within a result row.""" return hasattr(other, 'name') and hasattr(self, 'name') and \ other.name == self.name def _make_proxy( self, selectable, name=None, name_is_truncatable=False, **kw): """Create a new :class:`.ColumnElement` representing this :class:`.ColumnElement` as it appears in the select list of a descending selectable. """ if name is None: name = self.anon_label if self.key: key = self.key else: try: key = str(self) except exc.UnsupportedCompilationError: key = self.anon_label else: key = name co = ColumnClause( _as_truncated(name) if name_is_truncatable else name, type_=getattr(self, 'type', None), _selectable=selectable ) co._proxies = [self] if selectable._is_clone_of is not None: co._is_clone_of = \ selectable._is_clone_of.columns.get(key) selectable._columns[key] = co return co def compare(self, other, use_proxies=False, equivalents=None, **kw): """Compare this ColumnElement to another. Special arguments understood: :param use_proxies: when True, consider two columns that share a common base column as equivalent (i.e. shares_lineage()) :param equivalents: a dictionary of columns as keys mapped to sets of columns. If the given "other" column is present in this dictionary, if any of the columns in the corresponding set() pass the comparison test, the result is True. This is used to expand the comparison to other columns that may be known to be equivalent to this one via foreign key or other criterion. """ to_compare = (other, ) if equivalents and other in equivalents: to_compare = equivalents[other].union(to_compare) for oth in to_compare: if use_proxies and self.shares_lineage(oth): return True elif hash(oth) == hash(self): return True else: return False def cast(self, type_): """Produce a type cast, i.e. ``CAST(<expression> AS <type>)``. This is a shortcut to the :func:`~.expression.cast` function. .. versionadded:: 1.0.7 """ return Cast(self, type_) def label(self, name): """Produce a column label, i.e. ``<columnname> AS <name>``. This is a shortcut to the :func:`~.expression.label` function. if 'name' is None, an anonymous label name will be generated. """ return Label(name, self, self.type) @util.memoized_property def anon_label(self): """provides a constant 'anonymous label' for this ColumnElement. This is a label() expression which will be named at compile time. The same label() is returned each time anon_label is called so that expressions can reference anon_label multiple times, producing the same label name at compile time. the compiler uses this function automatically at compile time for expressions that are known to be 'unnamed' like binary expressions and function calls. """ while self._is_clone_of is not None: self = self._is_clone_of return _anonymous_label( '%%(%d %s)s' % (id(self), getattr(self, 'name', 'anon')) ) class BindParameter(ColumnElement): r"""Represent a "bound expression". :class:`.BindParameter` is invoked explicitly using the :func:`.bindparam` function, as in:: from sqlalchemy import bindparam stmt = select([users_table]).\ where(users_table.c.name == bindparam('username')) Detailed discussion of how :class:`.BindParameter` is used is at :func:`.bindparam`. .. seealso:: :func:`.bindparam` """ __visit_name__ = 'bindparam' _is_crud = False def __init__(self, key, value=NO_ARG, type_=None, unique=False, required=NO_ARG, quote=None, callable_=None, isoutparam=False, _compared_to_operator=None, _compared_to_type=None): r"""Produce a "bound expression". The return value is an instance of :class:`.BindParameter`; this is a :class:`.ColumnElement` subclass which represents a so-called "placeholder" value in a SQL expression, the value of which is supplied at the point at which the statement in executed against a database connection. In SQLAlchemy, the :func:`.bindparam` construct has the ability to carry along the actual value that will be ultimately used at expression time. In this way, it serves not just as a "placeholder" for eventual population, but also as a means of representing so-called "unsafe" values which should not be rendered directly in a SQL statement, but rather should be passed along to the :term:`DBAPI` as values which need to be correctly escaped and potentially handled for type-safety. When using :func:`.bindparam` explicitly, the use case is typically one of traditional deferment of parameters; the :func:`.bindparam` construct accepts a name which can then be referred to at execution time:: from sqlalchemy import bindparam stmt = select([users_table]).\ where(users_table.c.name == bindparam('username')) The above statement, when rendered, will produce SQL similar to:: SELECT id, name FROM user WHERE name = :username In order to populate the value of ``:username`` above, the value would typically be applied at execution time to a method like :meth:`.Connection.execute`:: result = connection.execute(stmt, username='wendy') Explicit use of :func:`.bindparam` is also common when producing UPDATE or DELETE statements that are to be invoked multiple times, where the WHERE criterion of the statement is to change on each invocation, such as:: stmt = (users_table.update(). where(user_table.c.name == bindparam('username')). values(fullname=bindparam('fullname')) ) connection.execute( stmt, [{"username": "wendy", "fullname": "Wendy Smith"}, {"username": "jack", "fullname": "Jack Jones"}, ] ) SQLAlchemy's Core expression system makes wide use of :func:`.bindparam` in an implicit sense. It is typical that Python literal values passed to virtually all SQL expression functions are coerced into fixed :func:`.bindparam` constructs. For example, given a comparison operation such as:: expr = users_table.c.name == 'Wendy' The above expression will produce a :class:`.BinaryExpression` construct, where the left side is the :class:`.Column` object representing the ``name`` column, and the right side is a :class:`.BindParameter` representing the literal value:: print(repr(expr.right)) BindParameter('%(4327771088 name)s', 'Wendy', type_=String()) The expression above will render SQL such as:: user.name = :name_1 Where the ``:name_1`` parameter name is an anonymous name. The actual string ``Wendy`` is not in the rendered string, but is carried along where it is later used within statement execution. If we invoke a statement like the following:: stmt = select([users_table]).where(users_table.c.name == 'Wendy') result = connection.execute(stmt) We would see SQL logging output as:: SELECT "user".id, "user".name FROM "user" WHERE "user".name = %(name_1)s {'name_1': 'Wendy'} Above, we see that ``Wendy`` is passed as a parameter to the database, while the placeholder ``:name_1`` is rendered in the appropriate form for the target database, in this case the PostgreSQL database. Similarly, :func:`.bindparam` is invoked automatically when working with :term:`CRUD` statements as far as the "VALUES" portion is concerned. The :func:`.insert` construct produces an ``INSERT`` expression which will, at statement execution time, generate bound placeholders based on the arguments passed, as in:: stmt = users_table.insert() result = connection.execute(stmt, name='Wendy') The above will produce SQL output as:: INSERT INTO "user" (name) VALUES (%(name)s) {'name': 'Wendy'} The :class:`.Insert` construct, at compilation/execution time, rendered a single :func:`.bindparam` mirroring the column name ``name`` as a result of the single ``name`` parameter we passed to the :meth:`.Connection.execute` method. :param key: the key (e.g. the name) for this bind param. Will be used in the generated SQL statement for dialects that use named parameters. This value may be modified when part of a compilation operation, if other :class:`BindParameter` objects exist with the same key, or if its length is too long and truncation is required. :param value: Initial value for this bind param. Will be used at statement execution time as the value for this parameter passed to the DBAPI, if no other value is indicated to the statement execution method for this particular parameter name. Defaults to ``None``. :param callable\_: A callable function that takes the place of "value". The function will be called at statement execution time to determine the ultimate value. Used for scenarios where the actual bind value cannot be determined at the point at which the clause construct is created, but embedded bind values are still desirable. :param type\_: A :class:`.TypeEngine` class or instance representing an optional datatype for this :func:`.bindparam`. If not passed, a type may be determined automatically for the bind, based on the given value; for example, trivial Python types such as ``str``, ``int``, ``bool`` may result in the :class:`.String`, :class:`.Integer` or :class:`.Boolean` types being autoamtically selected. The type of a :func:`.bindparam` is significant especially in that the type will apply pre-processing to the value before it is passed to the database. For example, a :func:`.bindparam` which refers to a datetime value, and is specified as holding the :class:`.DateTime` type, may apply conversion needed to the value (such as stringification on SQLite) before passing the value to the database. :param unique: if True, the key name of this :class:`.BindParameter` will be modified if another :class:`.BindParameter` of the same name already has been located within the containing expression. This flag is used generally by the internals when producing so-called "anonymous" bound expressions, it isn't generally applicable to explicitly-named :func:`.bindparam` constructs. :param required: If ``True``, a value is required at execution time. If not passed, it defaults to ``True`` if neither :paramref:`.bindparam.value` or :paramref:`.bindparam.callable` were passed. If either of these parameters are present, then :paramref:`.bindparam.required` defaults to ``False``. .. versionchanged:: 0.8 If the ``required`` flag is not specified, it will be set automatically to ``True`` or ``False`` depending on whether or not the ``value`` or ``callable`` parameters were specified. :param quote: True if this parameter name requires quoting and is not currently known as a SQLAlchemy reserved word; this currently only applies to the Oracle backend, where bound names must sometimes be quoted. :param isoutparam: if True, the parameter should be treated like a stored procedure "OUT" parameter. This applies to backends such as Oracle which support OUT parameters. .. seealso:: :ref:`coretutorial_bind_param` :ref:`coretutorial_insert_expressions` :func:`.outparam` """ if isinstance(key, ColumnClause): type_ = key.type key = key.key if required is NO_ARG: required = (value is NO_ARG and callable_ is None) if value is NO_ARG: value = None if quote is not None: key = quoted_name(key, quote) if unique: self.key = _anonymous_label('%%(%d %s)s' % (id(self), key or 'param')) else: self.key = key or _anonymous_label('%%(%d param)s' % id(self)) # identifying key that won't change across # clones, used to identify the bind's logical # identity self._identifying_key = self.key # key that was passed in the first place, used to # generate new keys self._orig_key = key or 'param' self.unique = unique self.value = value self.callable = callable_ self.isoutparam = isoutparam self.required = required if type_ is None: if _compared_to_type is not None: self.type = \ _compared_to_type.coerce_compared_value( _compared_to_operator, value) else: self.type = type_api._resolve_value_to_type(value) elif isinstance(type_, type): self.type = type_() else: self.type = type_ def _with_value(self, value): """Return a copy of this :class:`.BindParameter` with the given value set. """ cloned = self._clone() cloned.value = value cloned.callable = None cloned.required = False if cloned.type is type_api.NULLTYPE: cloned.type = type_api._resolve_value_to_type(value) return cloned @property def effective_value(self): """Return the value of this bound parameter, taking into account if the ``callable`` parameter was set. The ``callable`` value will be evaluated and returned if present, else ``value``. """ if self.callable: return self.callable() else: return self.value def _clone(self): c = ClauseElement._clone(self) if self.unique: c.key = _anonymous_label('%%(%d %s)s' % (id(c), c._orig_key or 'param')) return c def _convert_to_unique(self): if not self.unique: self.unique = True self.key = _anonymous_label( '%%(%d %s)s' % (id(self), self._orig_key or 'param')) def compare(self, other, **kw): """Compare this :class:`BindParameter` to the given clause.""" return isinstance(other, BindParameter) \ and self.type._compare_type_affinity(other.type) \ and self.value == other.value \ and self.callable == other.callable def __getstate__(self): """execute a deferred value for serialization purposes.""" d = self.__dict__.copy() v = self.value if self.callable: v = self.callable() d['callable'] = None d['value'] = v return d def __repr__(self): return 'BindParameter(%r, %r, type_=%r)' % (self.key, self.value, self.type) class TypeClause(ClauseElement): """Handle a type keyword in a SQL statement. Used by the ``Case`` statement. """ __visit_name__ = 'typeclause' def __init__(self, type): self.type = type class TextClause(Executable, ClauseElement): """Represent a literal SQL text fragment. E.g.:: from sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t) The :class:`.Text` construct is produced using the :func:`.text` function; see that function for full documentation. .. seealso:: :func:`.text` """ __visit_name__ = 'textclause' _bind_params_regex = re.compile(r'(?<![:\w\x5c]):(\w+)(?!:)', re.UNICODE) _execution_options = \ Executable._execution_options.union( {'autocommit': PARSE_AUTOCOMMIT}) @property def _select_iterable(self): return (self,) @property def selectable(self): # allows text() to be considered by # _interpret_as_from return self _hide_froms = [] # help in those cases where text() is # interpreted in a column expression situation key = _label = _resolve_label = None _allow_label_resolve = False def __init__( self, text, bind=None): self._bind = bind self._bindparams = {} def repl(m): self._bindparams[m.group(1)] = BindParameter(m.group(1)) return ':%s' % m.group(1) # scan the string and search for bind parameter names, add them # to the list of bindparams self.text = self._bind_params_regex.sub(repl, text) @classmethod def _create_text(self, text, bind=None, bindparams=None, typemap=None, autocommit=None): r"""Construct a new :class:`.TextClause` clause, representing a textual SQL string directly. E.g.:: from sqlalchemy import text t = text("SELECT * FROM users") result = connection.execute(t) The advantages :func:`.text` provides over a plain string are backend-neutral support for bind parameters, per-statement execution options, as well as bind parameter and result-column typing behavior, allowing SQLAlchemy type constructs to play a role when executing a statement that is specified literally. The construct can also be provided with a ``.c`` collection of column elements, allowing it to be embedded in other SQL expression constructs as a subquery. Bind parameters are specified by name, using the format ``:name``. E.g.:: t = text("SELECT * FROM users WHERE id=:user_id") result = connection.execute(t, user_id=12) For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape:: t = text("SELECT * FROM users WHERE name='\:username'") The :class:`.TextClause` construct includes methods which can provide information about the bound parameters as well as the column values which would be returned from the textual statement, assuming it's an executable SELECT type of statement. The :meth:`.TextClause.bindparams` method is used to provide bound parameter detail, and :meth:`.TextClause.columns` method allows specification of return columns including names and types:: t = text("SELECT * FROM users WHERE id=:user_id").\ bindparams(user_id=7).\ columns(id=Integer, name=String) for id, name in connection.execute(t): print(id, name) The :func:`.text` construct is used in cases when a literal string SQL fragment is specified as part of a larger query, such as for the WHERE clause of a SELECT statement:: s = select([users.c.id, users.c.name]).where(text("id=:user_id")) result = connection.execute(s, user_id=12) :func:`.text` is also used for the construction of a full, standalone statement using plain text. As such, SQLAlchemy refers to it as an :class:`.Executable` object, and it supports the :meth:`Executable.execution_options` method. For example, a :func:`.text` construct that should be subject to "autocommit" can be set explicitly so using the :paramref:`.Connection.execution_options.autocommit` option:: t = text("EXEC my_procedural_thing()").\ execution_options(autocommit=True) Note that SQLAlchemy's usual "autocommit" behavior applies to :func:`.text` constructs implicitly - that is, statements which begin with a phrase such as ``INSERT``, ``UPDATE``, ``DELETE``, or a variety of other phrases specific to certain backends, will be eligible for autocommit if no transaction is in progress. :param text: the text of the SQL statement to be created. use ``:<param>`` to specify bind parameters; they will be compiled to their engine-specific format. :param autocommit: Deprecated. Use .execution_options(autocommit=<True|False>) to set the autocommit option. :param bind: an optional connection or engine to be used for this text query. :param bindparams: Deprecated. A list of :func:`.bindparam` instances used to provide information about parameters embedded in the statement. This argument now invokes the :meth:`.TextClause.bindparams` method on the construct before returning it. E.g.:: stmt = text("SELECT * FROM table WHERE id=:id", bindparams=[bindparam('id', value=5, type_=Integer)]) Is equivalent to:: stmt = text("SELECT * FROM table WHERE id=:id").\ bindparams(bindparam('id', value=5, type_=Integer)) .. deprecated:: 0.9.0 the :meth:`.TextClause.bindparams` method supersedes the ``bindparams`` argument to :func:`.text`. :param typemap: Deprecated. A dictionary mapping the names of columns represented in the columns clause of a ``SELECT`` statement to type objects, which will be used to perform post-processing on columns within the result set. This parameter now invokes the :meth:`.TextClause.columns` method, which returns a :class:`.TextAsFrom` construct that gains a ``.c`` collection and can be embedded in other expressions. E.g.:: stmt = text("SELECT * FROM table", typemap={'id': Integer, 'name': String}, ) Is equivalent to:: stmt = text("SELECT * FROM table").columns(id=Integer, name=String) Or alternatively:: from sqlalchemy.sql import column stmt = text("SELECT * FROM table").columns( column('id', Integer), column('name', String) ) .. deprecated:: 0.9.0 the :meth:`.TextClause.columns` method supersedes the ``typemap`` argument to :func:`.text`. .. seealso:: :ref:`sqlexpression_text` - in the Core tutorial :ref:`orm_tutorial_literal_sql` - in the ORM tutorial """ stmt = TextClause(text, bind=bind) if bindparams: stmt = stmt.bindparams(*bindparams) if typemap: stmt = stmt.columns(**typemap) if autocommit is not None: util.warn_deprecated('autocommit on text() is deprecated. ' 'Use .execution_options(autocommit=True)') stmt = stmt.execution_options(autocommit=autocommit) return stmt @_generative def bindparams(self, *binds, **names_to_values): """Establish the values and/or types of bound parameters within this :class:`.TextClause` construct. Given a text construct such as:: from sqlalchemy import text stmt = text("SELECT id, name FROM user WHERE name=:name " "AND timestamp=:timestamp") the :meth:`.TextClause.bindparams` method can be used to establish the initial value of ``:name`` and ``:timestamp``, using simple keyword arguments:: stmt = stmt.bindparams(name='jack', timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)) Where above, new :class:`.BindParameter` objects will be generated with the names ``name`` and ``timestamp``, and values of ``jack`` and ``datetime.datetime(2012, 10, 8, 15, 12, 5)``, respectively. The types will be inferred from the values given, in this case :class:`.String` and :class:`.DateTime`. When specific typing behavior is needed, the positional ``*binds`` argument can be used in which to specify :func:`.bindparam` constructs directly. These constructs must include at least the ``key`` argument, then an optional value and type:: from sqlalchemy import bindparam stmt = stmt.bindparams( bindparam('name', value='jack', type_=String), bindparam('timestamp', type_=DateTime) ) Above, we specified the type of :class:`.DateTime` for the ``timestamp`` bind, and the type of :class:`.String` for the ``name`` bind. In the case of ``name`` we also set the default value of ``"jack"``. Additional bound parameters can be supplied at statement execution time, e.g.:: result = connection.execute(stmt, timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)) The :meth:`.TextClause.bindparams` method can be called repeatedly, where it will re-use existing :class:`.BindParameter` objects to add new information. For example, we can call :meth:`.TextClause.bindparams` first with typing information, and a second time with value information, and it will be combined:: stmt = text("SELECT id, name FROM user WHERE name=:name " "AND timestamp=:timestamp") stmt = stmt.bindparams( bindparam('name', type_=String), bindparam('timestamp', type_=DateTime) ) stmt = stmt.bindparams( name='jack', timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5) ) .. versionadded:: 0.9.0 The :meth:`.TextClause.bindparams` method supersedes the argument ``bindparams`` passed to :func:`~.expression.text`. """ self._bindparams = new_params = self._bindparams.copy() for bind in binds: try: existing = new_params[bind.key] except KeyError: raise exc.ArgumentError( "This text() construct doesn't define a " "bound parameter named %r" % bind.key) else: new_params[existing.key] = bind for key, value in names_to_values.items(): try: existing = new_params[key] except KeyError: raise exc.ArgumentError( "This text() construct doesn't define a " "bound parameter named %r" % key) else: new_params[key] = existing._with_value(value) @util.dependencies('sqlalchemy.sql.selectable') def columns(self, selectable, *cols, **types): """Turn this :class:`.TextClause` object into a :class:`.TextAsFrom` object that can be embedded into another statement. This function essentially bridges the gap between an entirely textual SELECT statement and the SQL expression language concept of a "selectable":: from sqlalchemy.sql import column, text stmt = text("SELECT id, name FROM some_table") stmt = stmt.columns(column('id'), column('name')).alias('st') stmt = select([mytable]).\ select_from( mytable.join(stmt, mytable.c.name == stmt.c.name) ).where(stmt.c.id > 5) Above, we pass a series of :func:`.column` elements to the :meth:`.TextClause.columns` method positionally. These :func:`.column` elements now become first class elements upon the :attr:`.TextAsFrom.c` column collection, just like any other selectable. The column expressions we pass to :meth:`.TextClause.columns` may also be typed; when we do so, these :class:`.TypeEngine` objects become the effective return type of the column, so that SQLAlchemy's result-set-processing systems may be used on the return values. This is often needed for types such as date or boolean types, as well as for unicode processing on some dialect configurations:: stmt = text("SELECT id, name, timestamp FROM some_table") stmt = stmt.columns( column('id', Integer), column('name', Unicode), column('timestamp', DateTime) ) for id, name, timestamp in connection.execute(stmt): print(id, name, timestamp) As a shortcut to the above syntax, keyword arguments referring to types alone may be used, if only type conversion is needed:: stmt = text("SELECT id, name, timestamp FROM some_table") stmt = stmt.columns( id=Integer, name=Unicode, timestamp=DateTime ) for id, name, timestamp in connection.execute(stmt): print(id, name, timestamp) The positional form of :meth:`.TextClause.columns` also provides the unique feature of **positional column targeting**, which is particularly useful when using the ORM with complex textual queries. If we specify the columns from our model to :meth:`.TextClause.columns`, the result set will match to those columns positionally, meaning the name or origin of the column in the textual SQL doesn't matter:: stmt = text("SELECT users.id, addresses.id, users.id, " "users.name, addresses.email_address AS email " "FROM users JOIN addresses ON users.id=addresses.user_id " "WHERE users.id = 1").columns( User.id, Address.id, Address.user_id, User.name, Address.email_address ) query = session.query(User).from_statement(stmt).options( contains_eager(User.addresses)) .. versionadded:: 1.1 the :meth:`.TextClause.columns` method now offers positional column targeting in the result set when the column expressions are passed purely positionally. The :meth:`.TextClause.columns` method provides a direct route to calling :meth:`.FromClause.alias` as well as :meth:`.SelectBase.cte` against a textual SELECT statement:: stmt = stmt.columns(id=Integer, name=String).cte('st') stmt = select([sometable]).where(sometable.c.id == stmt.c.id) .. versionadded:: 0.9.0 :func:`.text` can now be converted into a fully featured "selectable" construct using the :meth:`.TextClause.columns` method. This method supersedes the ``typemap`` argument to :func:`.text`. """ positional_input_cols = [ ColumnClause(col.key, types.pop(col.key)) if col.key in types else col for col in cols ] keyed_input_cols = [ ColumnClause(key, type_) for key, type_ in types.items()] return selectable.TextAsFrom( self, positional_input_cols + keyed_input_cols, positional=bool(positional_input_cols) and not keyed_input_cols) @property def type(self): return type_api.NULLTYPE @property def comparator(self): return self.type.comparator_factory(self) def self_group(self, against=None): if against is operators.in_op: return Grouping(self) else: return self def _copy_internals(self, clone=_clone, **kw): self._bindparams = dict((b.key, clone(b, **kw)) for b in self._bindparams.values()) def get_children(self, **kwargs): return list(self._bindparams.values()) def compare(self, other): return isinstance(other, TextClause) and other.text == self.text class Null(ColumnElement): """Represent the NULL keyword in a SQL statement. :class:`.Null` is accessed as a constant via the :func:`.null` function. """ __visit_name__ = 'null' @util.memoized_property def type(self): return type_api.NULLTYPE @classmethod def _instance(cls): """Return a constant :class:`.Null` construct.""" return Null() def compare(self, other): return isinstance(other, Null) class False_(ColumnElement): """Represent the ``false`` keyword, or equivalent, in a SQL statement. :class:`.False_` is accessed as a constant via the :func:`.false` function. """ __visit_name__ = 'false' @util.memoized_property def type(self): return type_api.BOOLEANTYPE def _negate(self): return True_() @classmethod def _instance(cls): """Return a :class:`.False_` construct. E.g.:: >>> from sqlalchemy import false >>> print select([t.c.x]).where(false()) SELECT x FROM t WHERE false A backend which does not support true/false constants will render as an expression against 1 or 0:: >>> print select([t.c.x]).where(false()) SELECT x FROM t WHERE 0 = 1 The :func:`.true` and :func:`.false` constants also feature "short circuit" operation within an :func:`.and_` or :func:`.or_` conjunction:: >>> print select([t.c.x]).where(or_(t.c.x > 5, true())) SELECT x FROM t WHERE true >>> print select([t.c.x]).where(and_(t.c.x > 5, false())) SELECT x FROM t WHERE false .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature better integrated behavior within conjunctions and on dialects that don't support true/false constants. .. seealso:: :func:`.true` """ return False_() def compare(self, other): return isinstance(other, False_) class True_(ColumnElement): """Represent the ``true`` keyword, or equivalent, in a SQL statement. :class:`.True_` is accessed as a constant via the :func:`.true` function. """ __visit_name__ = 'true' @util.memoized_property def type(self): return type_api.BOOLEANTYPE def _negate(self): return False_() @classmethod def _ifnone(cls, other): if other is None: return cls._instance() else: return other @classmethod def _instance(cls): """Return a constant :class:`.True_` construct. E.g.:: >>> from sqlalchemy import true >>> print select([t.c.x]).where(true()) SELECT x FROM t WHERE true A backend which does not support true/false constants will render as an expression against 1 or 0:: >>> print select([t.c.x]).where(true()) SELECT x FROM t WHERE 1 = 1 The :func:`.true` and :func:`.false` constants also feature "short circuit" operation within an :func:`.and_` or :func:`.or_` conjunction:: >>> print select([t.c.x]).where(or_(t.c.x > 5, true())) SELECT x FROM t WHERE true >>> print select([t.c.x]).where(and_(t.c.x > 5, false())) SELECT x FROM t WHERE false .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature better integrated behavior within conjunctions and on dialects that don't support true/false constants. .. seealso:: :func:`.false` """ return True_() def compare(self, other): return isinstance(other, True_) class ClauseList(ClauseElement): """Describe a list of clauses, separated by an operator. By default, is comma-separated, such as a column listing. """ __visit_name__ = 'clauselist' def __init__(self, *clauses, **kwargs): self.operator = kwargs.pop('operator', operators.comma_op) self.group = kwargs.pop('group', True) self.group_contents = kwargs.pop('group_contents', True) text_converter = kwargs.pop( '_literal_as_text', _expression_literal_as_text) if self.group_contents: self.clauses = [ text_converter(clause).self_group(against=self.operator) for clause in clauses] else: self.clauses = [ text_converter(clause) for clause in clauses] def __iter__(self): return iter(self.clauses) def __len__(self): return len(self.clauses) @property def _select_iterable(self): return iter(self) def append(self, clause): if self.group_contents: self.clauses.append(_literal_as_text(clause). self_group(against=self.operator)) else: self.clauses.append(_literal_as_text(clause)) def _copy_internals(self, clone=_clone, **kw): self.clauses = [clone(clause, **kw) for clause in self.clauses] def get_children(self, **kwargs): return self.clauses @property def _from_objects(self): return list(itertools.chain(*[c._from_objects for c in self.clauses])) def self_group(self, against=None): if self.group and operators.is_precedent(self.operator, against): return Grouping(self) else: return self def compare(self, other, **kw): """Compare this :class:`.ClauseList` to the given :class:`.ClauseList`, including a comparison of all the clause items. """ if not isinstance(other, ClauseList) and len(self.clauses) == 1: return self.clauses[0].compare(other, **kw) elif isinstance(other, ClauseList) and \ len(self.clauses) == len(other.clauses) and \ self.operator is other.operator: if self.operator in (operators.and_, operators.or_): completed = set() for clause in self.clauses: for other_clause in set(other.clauses).difference(completed): if clause.compare(other_clause, **kw): completed.add(other_clause) break return len(completed) == len(other.clauses) else: for i in range(0, len(self.clauses)): if not self.clauses[i].compare(other.clauses[i], **kw): return False else: return True else: return False class BooleanClauseList(ClauseList, ColumnElement): __visit_name__ = 'clauselist' def __init__(self, *arg, **kw): raise NotImplementedError( "BooleanClauseList has a private constructor") @classmethod def _construct(cls, operator, continue_on, skip_on, *clauses, **kw): convert_clauses = [] clauses = [ _expression_literal_as_text(clause) for clause in util.coerce_generator_arg(clauses) ] for clause in clauses: if isinstance(clause, continue_on): continue elif isinstance(clause, skip_on): return clause.self_group(against=operators._asbool) convert_clauses.append(clause) if len(convert_clauses) == 1: return convert_clauses[0].self_group(against=operators._asbool) elif not convert_clauses and clauses: return clauses[0].self_group(against=operators._asbool) convert_clauses = [c.self_group(against=operator) for c in convert_clauses] self = cls.__new__(cls) self.clauses = convert_clauses self.group = True self.operator = operator self.group_contents = True self.type = type_api.BOOLEANTYPE return self @classmethod def and_(cls, *clauses): """Produce a conjunction of expressions joined by ``AND``. E.g.:: from sqlalchemy import and_ stmt = select([users_table]).where( and_( users_table.c.name == 'wendy', users_table.c.enrolled == True ) ) The :func:`.and_` conjunction is also available using the Python ``&`` operator (though note that compound expressions need to be parenthesized in order to function with Python operator precedence behavior):: stmt = select([users_table]).where( (users_table.c.name == 'wendy') & (users_table.c.enrolled == True) ) The :func:`.and_` operation is also implicit in some cases; the :meth:`.Select.where` method for example can be invoked multiple times against a statement, which will have the effect of each clause being combined using :func:`.and_`:: stmt = select([users_table]).\ where(users_table.c.name == 'wendy').\ where(users_table.c.enrolled == True) .. seealso:: :func:`.or_` """ return cls._construct(operators.and_, True_, False_, *clauses) @classmethod def or_(cls, *clauses): """Produce a conjunction of expressions joined by ``OR``. E.g.:: from sqlalchemy import or_ stmt = select([users_table]).where( or_( users_table.c.name == 'wendy', users_table.c.name == 'jack' ) ) The :func:`.or_` conjunction is also available using the Python ``|`` operator (though note that compound expressions need to be parenthesized in order to function with Python operator precedence behavior):: stmt = select([users_table]).where( (users_table.c.name == 'wendy') | (users_table.c.name == 'jack') ) .. seealso:: :func:`.and_` """ return cls._construct(operators.or_, False_, True_, *clauses) @property def _select_iterable(self): return (self, ) def self_group(self, against=None): if not self.clauses: return self else: return super(BooleanClauseList, self).self_group(against=against) def _negate(self): return ClauseList._negate(self) and_ = BooleanClauseList.and_ or_ = BooleanClauseList.or_ class Tuple(ClauseList, ColumnElement): """Represent a SQL tuple.""" def __init__(self, *clauses, **kw): """Return a :class:`.Tuple`. Main usage is to produce a composite IN construct:: from sqlalchemy import tuple_ tuple_(table.c.col1, table.c.col2).in_( [(1, 2), (5, 12), (10, 19)] ) .. warning:: The composite IN construct is not supported by all backends, and is currently known to work on PostgreSQL and MySQL, but not SQLite. Unsupported backends will raise a subclass of :class:`~sqlalchemy.exc.DBAPIError` when such an expression is invoked. """ clauses = [_literal_as_binds(c) for c in clauses] self._type_tuple = [arg.type for arg in clauses] self.type = kw.pop('type_', self._type_tuple[0] if self._type_tuple else type_api.NULLTYPE) super(Tuple, self).__init__(*clauses, **kw) @property def _select_iterable(self): return (self, ) def _bind_param(self, operator, obj, type_=None): return Tuple(*[ BindParameter(None, o, _compared_to_operator=operator, _compared_to_type=compared_to_type, unique=True, type_=type_) for o, compared_to_type in zip(obj, self._type_tuple) ]).self_group() class Case(ColumnElement): """Represent a ``CASE`` expression. :class:`.Case` is produced using the :func:`.case` factory function, as in:: from sqlalchemy import case stmt = select([users_table]).\ where( case( [ (users_table.c.name == 'wendy', 'W'), (users_table.c.name == 'jack', 'J') ], else_='E' ) ) Details on :class:`.Case` usage is at :func:`.case`. .. seealso:: :func:`.case` """ __visit_name__ = 'case' def __init__(self, whens, value=None, else_=None): r"""Produce a ``CASE`` expression. The ``CASE`` construct in SQL is a conditional object that acts somewhat analogously to an "if/then" construct in other languages. It returns an instance of :class:`.Case`. :func:`.case` in its usual form is passed a list of "when" constructs, that is, a list of conditions and results as tuples:: from sqlalchemy import case stmt = select([users_table]).\ where( case( [ (users_table.c.name == 'wendy', 'W'), (users_table.c.name == 'jack', 'J') ], else_='E' ) ) The above statement will produce SQL resembling:: SELECT id, name FROM user WHERE CASE WHEN (name = :name_1) THEN :param_1 WHEN (name = :name_2) THEN :param_2 ELSE :param_3 END When simple equality expressions of several values against a single parent column are needed, :func:`.case` also has a "shorthand" format used via the :paramref:`.case.value` parameter, which is passed a column expression to be compared. In this form, the :paramref:`.case.whens` parameter is passed as a dictionary containing expressions to be compared against keyed to result expressions. The statement below is equivalent to the preceding statement:: stmt = select([users_table]).\ where( case( {"wendy": "W", "jack": "J"}, value=users_table.c.name, else_='E' ) ) The values which are accepted as result values in :paramref:`.case.whens` as well as with :paramref:`.case.else_` are coerced from Python literals into :func:`.bindparam` constructs. SQL expressions, e.g. :class:`.ColumnElement` constructs, are accepted as well. To coerce a literal string expression into a constant expression rendered inline, use the :func:`.literal_column` construct, as in:: from sqlalchemy import case, literal_column case( [ ( orderline.c.qty > 100, literal_column("'greaterthan100'") ), ( orderline.c.qty > 10, literal_column("'greaterthan10'") ) ], else_=literal_column("'lessthan10'") ) The above will render the given constants without using bound parameters for the result values (but still for the comparison values), as in:: CASE WHEN (orderline.qty > :qty_1) THEN 'greaterthan100' WHEN (orderline.qty > :qty_2) THEN 'greaterthan10' ELSE 'lessthan10' END :param whens: The criteria to be compared against, :paramref:`.case.whens` accepts two different forms, based on whether or not :paramref:`.case.value` is used. In the first form, it accepts a list of 2-tuples; each 2-tuple consists of ``(<sql expression>, <value>)``, where the SQL expression is a boolean expression and "value" is a resulting value, e.g.:: case([ (users_table.c.name == 'wendy', 'W'), (users_table.c.name == 'jack', 'J') ]) In the second form, it accepts a Python dictionary of comparison values mapped to a resulting value; this form requires :paramref:`.case.value` to be present, and values will be compared using the ``==`` operator, e.g.:: case( {"wendy": "W", "jack": "J"}, value=users_table.c.name ) :param value: An optional SQL expression which will be used as a fixed "comparison point" for candidate values within a dictionary passed to :paramref:`.case.whens`. :param else\_: An optional SQL expression which will be the evaluated result of the ``CASE`` construct if all expressions within :paramref:`.case.whens` evaluate to false. When omitted, most databases will produce a result of NULL if none of the "when" expressions evaluate to true. """ try: whens = util.dictlike_iteritems(whens) except TypeError: pass if value is not None: whenlist = [ (_literal_as_binds(c).self_group(), _literal_as_binds(r)) for (c, r) in whens ] else: whenlist = [ (_no_literals(c).self_group(), _literal_as_binds(r)) for (c, r) in whens ] if whenlist: type_ = list(whenlist[-1])[-1].type else: type_ = None if value is None: self.value = None else: self.value = _literal_as_binds(value) self.type = type_ self.whens = whenlist if else_ is not None: self.else_ = _literal_as_binds(else_) else: self.else_ = None def _copy_internals(self, clone=_clone, **kw): if self.value is not None: self.value = clone(self.value, **kw) self.whens = [(clone(x, **kw), clone(y, **kw)) for x, y in self.whens] if self.else_ is not None: self.else_ = clone(self.else_, **kw) def get_children(self, **kwargs): if self.value is not None: yield self.value for x, y in self.whens: yield x yield y if self.else_ is not None: yield self.else_ @property def _from_objects(self): return list(itertools.chain(*[x._from_objects for x in self.get_children()])) def literal_column(text, type_=None): r"""Produce a :class:`.ColumnClause` object that has the :paramref:`.column.is_literal` flag set to True. :func:`.literal_column` is similar to :func:`.column`, except that it is more often used as a "standalone" column expression that renders exactly as stated; while :func:`.column` stores a string name that will be assumed to be part of a table and may be quoted as such, :func:`.literal_column` can be that, or any other arbitrary column-oriented expression. :param text: the text of the expression; can be any SQL expression. Quoting rules will not be applied. To specify a column-name expression which should be subject to quoting rules, use the :func:`column` function. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` object which will provide result-set translation and additional expression semantics for this column. If left as None the type will be NullType. .. seealso:: :func:`.column` :func:`.text` :ref:`sqlexpression_literal_column` """ return ColumnClause(text, type_=type_, is_literal=True) class Cast(ColumnElement): """Represent a ``CAST`` expression. :class:`.Cast` is produced using the :func:`.cast` factory function, as in:: from sqlalchemy import cast, Numeric stmt = select([ cast(product_table.c.unit_price, Numeric(10, 4)) ]) Details on :class:`.Cast` usage is at :func:`.cast`. .. seealso:: :func:`.cast` """ __visit_name__ = 'cast' def __init__(self, expression, type_): """Produce a ``CAST`` expression. :func:`.cast` returns an instance of :class:`.Cast`. E.g.:: from sqlalchemy import cast, Numeric stmt = select([ cast(product_table.c.unit_price, Numeric(10, 4)) ]) The above statement will produce SQL resembling:: SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product The :func:`.cast` function performs two distinct functions when used. The first is that it renders the ``CAST`` expression within the resulting SQL string. The second is that it associates the given type (e.g. :class:`.TypeEngine` class or instance) with the column expression on the Python side, which means the expression will take on the expression operator behavior associated with that type, as well as the bound-value handling and result-row-handling behavior of the type. .. versionchanged:: 0.9.0 :func:`.cast` now applies the given type to the expression such that it takes effect on the bound-value, e.g. the Python-to-database direction, in addition to the result handling, e.g. database-to-Python, direction. An alternative to :func:`.cast` is the :func:`.type_coerce` function. This function performs the second task of associating an expression with a specific type, but does not render the ``CAST`` expression in SQL. :param expression: A SQL expression, such as a :class:`.ColumnElement` expression or a Python string which will be coerced into a bound literal value. :param type_: A :class:`.TypeEngine` class or instance indicating the type to which the ``CAST`` should apply. .. seealso:: :func:`.type_coerce` - Python-side type coercion without emitting CAST. """ self.type = type_api.to_instance(type_) self.clause = _literal_as_binds(expression, type_=self.type) self.typeclause = TypeClause(self.type) def _copy_internals(self, clone=_clone, **kw): self.clause = clone(self.clause, **kw) self.typeclause = clone(self.typeclause, **kw) def get_children(self, **kwargs): return self.clause, self.typeclause @property def _from_objects(self): return self.clause._from_objects class TypeCoerce(ColumnElement): """Represent a Python-side type-coercion wrapper. :class:`.TypeCoerce` supplies the :func:`.expression.type_coerce` function; see that function for usage details. .. versionchanged:: 1.1 The :func:`.type_coerce` function now produces a persistent :class:`.TypeCoerce` wrapper object rather than translating the given object in place. .. seealso:: :func:`.expression.type_coerce` """ __visit_name__ = 'type_coerce' def __init__(self, expression, type_): """Associate a SQL expression with a particular type, without rendering ``CAST``. E.g.:: from sqlalchemy import type_coerce stmt = select([ type_coerce(log_table.date_string, StringDateTime()) ]) The above construct will produce a :class:`.TypeCoerce` object, which renders SQL that labels the expression, but otherwise does not modify its value on the SQL side:: SELECT date_string AS anon_1 FROM log When result rows are fetched, the ``StringDateTime`` type will be applied to result rows on behalf of the ``date_string`` column. The rationale for the "anon_1" label is so that the type-coerced column remains separate in the list of result columns vs. other type-coerced or direct values of the target column. In order to provide a named label for the expression, use :meth:`.ColumnElement.label`:: stmt = select([ type_coerce( log_table.date_string, StringDateTime()).label('date') ]) A type that features bound-value handling will also have that behavior take effect when literal values or :func:`.bindparam` constructs are passed to :func:`.type_coerce` as targets. For example, if a type implements the :meth:`.TypeEngine.bind_expression` method or :meth:`.TypeEngine.bind_processor` method or equivalent, these functions will take effect at statement compilation/execution time when a literal value is passed, as in:: # bound-value handling of MyStringType will be applied to the # literal value "some string" stmt = select([type_coerce("some string", MyStringType)]) :func:`.type_coerce` is similar to the :func:`.cast` function, except that it does not render the ``CAST`` expression in the resulting statement. :param expression: A SQL expression, such as a :class:`.ColumnElement` expression or a Python string which will be coerced into a bound literal value. :param type_: A :class:`.TypeEngine` class or instance indicating the type to which the expression is coerced. .. seealso:: :func:`.cast` """ self.type = type_api.to_instance(type_) self.clause = _literal_as_binds(expression, type_=self.type) def _copy_internals(self, clone=_clone, **kw): self.clause = clone(self.clause, **kw) self.__dict__.pop('typed_expression', None) def get_children(self, **kwargs): return self.clause, @property def _from_objects(self): return self.clause._from_objects @util.memoized_property def typed_expression(self): if isinstance(self.clause, BindParameter): bp = self.clause._clone() bp.type = self.type return bp else: return self.clause class Extract(ColumnElement): """Represent a SQL EXTRACT clause, ``extract(field FROM expr)``.""" __visit_name__ = 'extract' def __init__(self, field, expr, **kwargs): """Return a :class:`.Extract` construct. This is typically available as :func:`.extract` as well as ``func.extract`` from the :data:`.func` namespace. """ self.type = type_api.INTEGERTYPE self.field = field self.expr = _literal_as_binds(expr, None) def _copy_internals(self, clone=_clone, **kw): self.expr = clone(self.expr, **kw) def get_children(self, **kwargs): return self.expr, @property def _from_objects(self): return self.expr._from_objects class _label_reference(ColumnElement): """Wrap a column expression as it appears in a 'reference' context. This expression is any that inclues an _order_by_label_element, which is a Label, or a DESC / ASC construct wrapping a Label. The production of _label_reference() should occur when an expression is added to this context; this includes the ORDER BY or GROUP BY of a SELECT statement, as well as a few other places, such as the ORDER BY within an OVER clause. """ __visit_name__ = 'label_reference' def __init__(self, element): self.element = element def _copy_internals(self, clone=_clone, **kw): self.element = clone(self.element, **kw) @property def _from_objects(self): return () class _textual_label_reference(ColumnElement): __visit_name__ = 'textual_label_reference' def __init__(self, element): self.element = element @util.memoized_property def _text_clause(self): return TextClause._create_text(self.element) class UnaryExpression(ColumnElement): """Define a 'unary' expression. A unary expression has a single column expression and an operator. The operator can be placed on the left (where it is called the 'operator') or right (where it is called the 'modifier') of the column expression. :class:`.UnaryExpression` is the basis for several unary operators including those used by :func:`.desc`, :func:`.asc`, :func:`.distinct`, :func:`.nullsfirst` and :func:`.nullslast`. """ __visit_name__ = 'unary' def __init__(self, element, operator=None, modifier=None, type_=None, negate=None, wraps_column_expression=False): self.operator = operator self.modifier = modifier self.element = element.self_group( against=self.operator or self.modifier) self.type = type_api.to_instance(type_) self.negate = negate self.wraps_column_expression = wraps_column_expression @classmethod def _create_nullsfirst(cls, column): """Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression. :func:`.nullsfirst` is intended to modify the expression produced by :func:`.asc` or :func:`.desc`, and indicates how NULL values should be handled when they are encountered during ordering:: from sqlalchemy import desc, nullsfirst stmt = select([users_table]).\ order_by(nullsfirst(desc(users_table.c.name))) The SQL expression from the above would resemble:: SELECT id, name FROM user ORDER BY name DESC NULLS FIRST Like :func:`.asc` and :func:`.desc`, :func:`.nullsfirst` is typically invoked from the column expression itself using :meth:`.ColumnElement.nullsfirst`, rather than as its standalone function version, as in:: stmt = (select([users_table]). order_by(users_table.c.name.desc().nullsfirst()) ) .. seealso:: :func:`.asc` :func:`.desc` :func:`.nullslast` :meth:`.Select.order_by` """ return UnaryExpression( _literal_as_label_reference(column), modifier=operators.nullsfirst_op, wraps_column_expression=False) @classmethod def _create_nullslast(cls, column): """Produce the ``NULLS LAST`` modifier for an ``ORDER BY`` expression. :func:`.nullslast` is intended to modify the expression produced by :func:`.asc` or :func:`.desc`, and indicates how NULL values should be handled when they are encountered during ordering:: from sqlalchemy import desc, nullslast stmt = select([users_table]).\ order_by(nullslast(desc(users_table.c.name))) The SQL expression from the above would resemble:: SELECT id, name FROM user ORDER BY name DESC NULLS LAST Like :func:`.asc` and :func:`.desc`, :func:`.nullslast` is typically invoked from the column expression itself using :meth:`.ColumnElement.nullslast`, rather than as its standalone function version, as in:: stmt = select([users_table]).\ order_by(users_table.c.name.desc().nullslast()) .. seealso:: :func:`.asc` :func:`.desc` :func:`.nullsfirst` :meth:`.Select.order_by` """ return UnaryExpression( _literal_as_label_reference(column), modifier=operators.nullslast_op, wraps_column_expression=False) @classmethod def _create_desc(cls, column): """Produce a descending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import desc stmt = select([users_table]).order_by(desc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name DESC The :func:`.desc` function is a standalone version of the :meth:`.ColumnElement.desc` method available on all SQL expressions, e.g.:: stmt = select([users_table]).order_by(users_table.c.name.desc()) :param column: A :class:`.ColumnElement` (e.g. scalar SQL expression) with which to apply the :func:`.desc` operation. .. seealso:: :func:`.asc` :func:`.nullsfirst` :func:`.nullslast` :meth:`.Select.order_by` """ return UnaryExpression( _literal_as_label_reference(column), modifier=operators.desc_op, wraps_column_expression=False) @classmethod def _create_asc(cls, column): """Produce an ascending ``ORDER BY`` clause element. e.g.:: from sqlalchemy import asc stmt = select([users_table]).order_by(asc(users_table.c.name)) will produce SQL as:: SELECT id, name FROM user ORDER BY name ASC The :func:`.asc` function is a standalone version of the :meth:`.ColumnElement.asc` method available on all SQL expressions, e.g.:: stmt = select([users_table]).order_by(users_table.c.name.asc()) :param column: A :class:`.ColumnElement` (e.g. scalar SQL expression) with which to apply the :func:`.asc` operation. .. seealso:: :func:`.desc` :func:`.nullsfirst` :func:`.nullslast` :meth:`.Select.order_by` """ return UnaryExpression( _literal_as_label_reference(column), modifier=operators.asc_op, wraps_column_expression=False) @classmethod def _create_distinct(cls, expr): """Produce an column-expression-level unary ``DISTINCT`` clause. This applies the ``DISTINCT`` keyword to an individual column expression, and is typically contained within an aggregate function, as in:: from sqlalchemy import distinct, func stmt = select([func.count(distinct(users_table.c.name))]) The above would produce an expression resembling:: SELECT COUNT(DISTINCT name) FROM user The :func:`.distinct` function is also available as a column-level method, e.g. :meth:`.ColumnElement.distinct`, as in:: stmt = select([func.count(users_table.c.name.distinct())]) The :func:`.distinct` operator is different from the :meth:`.Select.distinct` method of :class:`.Select`, which produces a ``SELECT`` statement with ``DISTINCT`` applied to the result set as a whole, e.g. a ``SELECT DISTINCT`` expression. See that method for further information. .. seealso:: :meth:`.ColumnElement.distinct` :meth:`.Select.distinct` :data:`.func` """ expr = _literal_as_binds(expr) return UnaryExpression( expr, operator=operators.distinct_op, type_=expr.type, wraps_column_expression=False) @property def _order_by_label_element(self): if self.modifier in (operators.desc_op, operators.asc_op): return self.element._order_by_label_element else: return None @property def _from_objects(self): return self.element._from_objects def _copy_internals(self, clone=_clone, **kw): self.element = clone(self.element, **kw) def get_children(self, **kwargs): return self.element, def compare(self, other, **kw): """Compare this :class:`UnaryExpression` against the given :class:`.ClauseElement`.""" return ( isinstance(other, UnaryExpression) and self.operator == other.operator and self.modifier == other.modifier and self.element.compare(other.element, **kw) ) def _negate(self): if self.negate is not None: return UnaryExpression( self.element, operator=self.negate, negate=self.operator, modifier=self.modifier, type_=self.type, wraps_column_expression=self.wraps_column_expression) elif self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity: return UnaryExpression( self.self_group(against=operators.inv), operator=operators.inv, type_=type_api.BOOLEANTYPE, wraps_column_expression=self.wraps_column_expression, negate=None) else: return ClauseElement._negate(self) def self_group(self, against=None): if self.operator and operators.is_precedent(self.operator, against): return Grouping(self) else: return self class CollectionAggregate(UnaryExpression): """Forms the basis for right-hand collection operator modifiers ANY and ALL. The ANY and ALL keywords are available in different ways on different backends. On PostgreSQL, they only work for an ARRAY type. On MySQL, they only work for subqueries. """ @classmethod def _create_any(cls, expr): """Produce an ANY expression. This may apply to an array type for some dialects (e.g. postgresql), or to a subquery for others (e.g. mysql). e.g.:: # postgresql '5 = ANY (somearray)' expr = 5 == any_(mytable.c.somearray) # mysql '5 = ANY (SELECT value FROM table)' expr = 5 == any_(select([table.c.value])) .. versionadded:: 1.1 .. seealso:: :func:`.expression.all_` """ expr = _literal_as_binds(expr) if expr.is_selectable and hasattr(expr, 'as_scalar'): expr = expr.as_scalar() expr = expr.self_group() return CollectionAggregate( expr, operator=operators.any_op, type_=type_api.NULLTYPE, wraps_column_expression=False) @classmethod def _create_all(cls, expr): """Produce an ALL expression. This may apply to an array type for some dialects (e.g. postgresql), or to a subquery for others (e.g. mysql). e.g.:: # postgresql '5 = ALL (somearray)' expr = 5 == all_(mytable.c.somearray) # mysql '5 = ALL (SELECT value FROM table)' expr = 5 == all_(select([table.c.value])) .. versionadded:: 1.1 .. seealso:: :func:`.expression.any_` """ expr = _literal_as_binds(expr) if expr.is_selectable and hasattr(expr, 'as_scalar'): expr = expr.as_scalar() expr = expr.self_group() return CollectionAggregate( expr, operator=operators.all_op, type_=type_api.NULLTYPE, wraps_column_expression=False) # operate and reverse_operate are hardwired to # dispatch onto the type comparator directly, so that we can # ensure "reversed" behavior. def operate(self, op, *other, **kwargs): if not operators.is_comparison(op): raise exc.ArgumentError( "Only comparison operators may be used with ANY/ALL") kwargs['reverse'] = True return self.comparator.operate(operators.mirror(op), *other, **kwargs) def reverse_operate(self, op, other, **kwargs): # comparison operators should never call reverse_operate assert not operators.is_comparison(op) raise exc.ArgumentError( "Only comparison operators may be used with ANY/ALL") class AsBoolean(UnaryExpression): def __init__(self, element, operator, negate): self.element = element self.type = type_api.BOOLEANTYPE self.operator = operator self.negate = negate self.modifier = None self.wraps_column_expression = True def self_group(self, against=None): return self def _negate(self): # TODO: this assumes the element is the True_() or False_() # object, but this assumption isn't enforced and # ColumnElement._negate() can send any number of expressions here return self.element._negate() class BinaryExpression(ColumnElement): """Represent an expression that is ``LEFT <operator> RIGHT``. A :class:`.BinaryExpression` is generated automatically whenever two column expressions are used in a Python binary expression:: >>> from sqlalchemy.sql import column >>> column('a') + column('b') <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0> >>> print column('a') + column('b') a + b """ __visit_name__ = 'binary' def __init__(self, left, right, operator, type_=None, negate=None, modifiers=None): # allow compatibility with libraries that # refer to BinaryExpression directly and pass strings if isinstance(operator, util.string_types): operator = operators.custom_op(operator) self._orig = (left, right) self.left = left.self_group(against=operator) self.right = right.self_group(against=operator) self.operator = operator self.type = type_api.to_instance(type_) self.negate = negate if modifiers is None: self.modifiers = {} else: self.modifiers = modifiers def __bool__(self): if self.operator in (operator.eq, operator.ne): return self.operator(hash(self._orig[0]), hash(self._orig[1])) else: raise TypeError("Boolean value of this clause is not defined") __nonzero__ = __bool__ @property def is_comparison(self): return operators.is_comparison(self.operator) @property def _from_objects(self): return self.left._from_objects + self.right._from_objects def _copy_internals(self, clone=_clone, **kw): self.left = clone(self.left, **kw) self.right = clone(self.right, **kw) def get_children(self, **kwargs): return self.left, self.right def compare(self, other, **kw): """Compare this :class:`BinaryExpression` against the given :class:`BinaryExpression`.""" return ( isinstance(other, BinaryExpression) and self.operator == other.operator and ( self.left.compare(other.left, **kw) and self.right.compare(other.right, **kw) or ( operators.is_commutative(self.operator) and self.left.compare(other.right, **kw) and self.right.compare(other.left, **kw) ) ) ) def self_group(self, against=None): if operators.is_precedent(self.operator, against): return Grouping(self) else: return self def _negate(self): if self.negate is not None: return BinaryExpression( self.left, self.right, self.negate, negate=self.operator, type_=self.type, modifiers=self.modifiers) else: return super(BinaryExpression, self)._negate() class Slice(ColumnElement): """Represent SQL for a Python array-slice object. This is not a specific SQL construct at this level, but may be interpreted by specific dialects, e.g. PostgreSQL. """ __visit_name__ = 'slice' def __init__(self, start, stop, step): self.start = start self.stop = stop self.step = step self.type = type_api.NULLTYPE def self_group(self, against=None): assert against is operator.getitem return self class IndexExpression(BinaryExpression): """Represent the class of expressions that are like an "index" operation. """ pass class Grouping(ColumnElement): """Represent a grouping within a column expression""" __visit_name__ = 'grouping' def __init__(self, element): self.element = element self.type = getattr(element, 'type', type_api.NULLTYPE) def self_group(self, against=None): return self @property def _key_label(self): return self._label @property def _label(self): return getattr(self.element, '_label', None) or self.anon_label def _copy_internals(self, clone=_clone, **kw): self.element = clone(self.element, **kw) def get_children(self, **kwargs): return self.element, @property def _from_objects(self): return self.element._from_objects def __getattr__(self, attr): return getattr(self.element, attr) def __getstate__(self): return {'element': self.element, 'type': self.type} def __setstate__(self, state): self.element = state['element'] self.type = state['type'] def compare(self, other, **kw): return isinstance(other, Grouping) and \ self.element.compare(other.element) RANGE_UNBOUNDED = util.symbol("RANGE_UNBOUNDED") RANGE_CURRENT = util.symbol("RANGE_CURRENT") class Over(ColumnElement): """Represent an OVER clause. This is a special operator against a so-called "window" function, as well as any aggregate function, which produces results relative to the result set itself. It's supported only by certain database backends. """ __visit_name__ = 'over' order_by = None partition_by = None def __init__( self, element, partition_by=None, order_by=None, range_=None, rows=None): """Produce an :class:`.Over` object against a function. Used against aggregate or so-called "window" functions, for database backends that support window functions. :func:`~.expression.over` is usually called using the :meth:`.FunctionElement.over` method, e.g.:: func.row_number().over(order_by=mytable.c.some_column) Would produce:: ROW_NUMBER() OVER(ORDER BY some_column) Ranges are also possible using the :paramref:`.expression.over.range_` and :paramref:`.expression.over.rows` parameters. These mutually-exclusive parameters each accept a 2-tuple, which contains a combination of integers and None:: func.row_number().over(order_by=my_table.c.some_column, range_=(None, 0)) The above would produce:: ROW_NUMBER() OVER(ORDER BY some_column RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) A value of None indicates "unbounded", a value of zero indicates "current row", and negative / positive integers indicate "preceding" and "following": * RANGE BETWEEN 5 PRECEDING AND 10 FOLLOWING:: func.row_number().over(order_by='x', range_=(-5, 10)) * ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW:: func.row_number().over(order_by='x', rows=(None, 0)) * RANGE BETWEEN 2 PRECEDING AND UNBOUNDED FOLLOWING:: func.row_number().over(order_by='x', range_=(-2, None)) .. versionadded:: 1.1 support for RANGE / ROWS within a window :param element: a :class:`.FunctionElement`, :class:`.WithinGroup`, or other compatible construct. :param partition_by: a column element or string, or a list of such, that will be used as the PARTITION BY clause of the OVER construct. :param order_by: a column element or string, or a list of such, that will be used as the ORDER BY clause of the OVER construct. :param range_: optional range clause for the window. This is a tuple value which can contain integer values or None, and will render a RANGE BETWEEN PRECEDING / FOLLOWING clause .. versionadded:: 1.1 :param rows: optional rows clause for the window. This is a tuple value which can contain integer values or None, and will render a ROWS BETWEEN PRECEDING / FOLLOWING clause. .. versionadded:: 1.1 This function is also available from the :data:`~.expression.func` construct itself via the :meth:`.FunctionElement.over` method. .. seealso:: :data:`.expression.func` :func:`.expression.within_group` """ self.element = element if order_by is not None: self.order_by = ClauseList( *util.to_list(order_by), _literal_as_text=_literal_as_label_reference) if partition_by is not None: self.partition_by = ClauseList( *util.to_list(partition_by), _literal_as_text=_literal_as_label_reference) if range_: self.range_ = self._interpret_range(range_) if rows: raise exc.ArgumentError( "'range_' and 'rows' are mutually exclusive") else: self.rows = None elif rows: self.rows = self._interpret_range(rows) self.range_ = None else: self.rows = self.range_ = None def _interpret_range(self, range_): if not isinstance(range_, tuple) or len(range_) != 2: raise exc.ArgumentError("2-tuple expected for range/rows") if range_[0] is None: preceding = RANGE_UNBOUNDED else: try: preceding = int(range_[0]) except ValueError: raise exc.ArgumentError( "Integer or None expected for preceding value") else: if preceding > 0: raise exc.ArgumentError( "Preceding value must be a " "negative integer, zero, or None") elif preceding < 0: preceding = literal(abs(preceding)) else: preceding = RANGE_CURRENT if range_[1] is None: following = RANGE_UNBOUNDED else: try: following = int(range_[1]) except ValueError: raise exc.ArgumentError( "Integer or None expected for following value") else: if following < 0: raise exc.ArgumentError( "Following value must be a positive " "integer, zero, or None") elif following > 0: following = literal(following) else: following = RANGE_CURRENT return preceding, following @property def func(self): """the element referred to by this :class:`.Over` clause. .. deprecated:: 1.1 the ``func`` element has been renamed to ``.element``. The two attributes are synonymous though ``.func`` is read-only. """ return self.element @util.memoized_property def type(self): return self.element.type def get_children(self, **kwargs): return [c for c in (self.element, self.partition_by, self.order_by) if c is not None] def _copy_internals(self, clone=_clone, **kw): self.element = clone(self.element, **kw) if self.partition_by is not None: self.partition_by = clone(self.partition_by, **kw) if self.order_by is not None: self.order_by = clone(self.order_by, **kw) @property def _from_objects(self): return list(itertools.chain( *[c._from_objects for c in (self.element, self.partition_by, self.order_by) if c is not None] )) class WithinGroup(ColumnElement): """Represent a WITHIN GROUP (ORDER BY) clause. This is a special operator against so-called so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including ``percentile_cont()``, ``rank()``, ``dense_rank()``, etc. It's supported only by certain database backends, such as PostgreSQL, Oracle and MS SQL Server. The :class:`.WithinGroup` consturct extracts its type from the method :meth:`.FunctionElement.within_group_type`. If this returns ``None``, the function's ``.type`` is used. """ __visit_name__ = 'withingroup' order_by = None def __init__(self, element, *order_by): r"""Produce a :class:`.WithinGroup` object against a function. Used against so-called "ordered set aggregate" and "hypothetical set aggregate" functions, including :class:`.percentile_cont`, :class:`.rank`, :class:`.dense_rank`, etc. :func:`~.expression.within_group` is usually called using the :meth:`.FunctionElement.within_group` method, e.g.:: from sqlalchemy import within_group stmt = select([ department.c.id, func.percentile_cont(0.5).within_group( department.c.salary.desc() ) ]) The above statement would produce SQL similar to ``SELECT department.id, percentile_cont(0.5) WITHIN GROUP (ORDER BY department.salary DESC)``. :param element: a :class:`.FunctionElement` construct, typically generated by :data:`~.expression.func`. :param \*order_by: one or more column elements that will be used as the ORDER BY clause of the WITHIN GROUP construct. .. versionadded:: 1.1 .. seealso:: :data:`.expression.func` :func:`.expression.over` """ self.element = element if order_by is not None: self.order_by = ClauseList( *util.to_list(order_by), _literal_as_text=_literal_as_label_reference) def over(self, partition_by=None, order_by=None): """Produce an OVER clause against this :class:`.WithinGroup` construct. This function has the same signature as that of :meth:`.FunctionElement.over`. """ return Over(self, partition_by=partition_by, order_by=order_by) @util.memoized_property def type(self): wgt = self.element.within_group_type(self) if wgt is not None: return wgt else: return self.element.type def get_children(self, **kwargs): return [c for c in (self.func, self.order_by) if c is not None] def _copy_internals(self, clone=_clone, **kw): self.element = clone(self.element, **kw) if self.order_by is not None: self.order_by = clone(self.order_by, **kw) @property def _from_objects(self): return list(itertools.chain( *[c._from_objects for c in (self.element, self.order_by) if c is not None] )) class FunctionFilter(ColumnElement): """Represent a function FILTER clause. This is a special operator against aggregate and window functions, which controls which rows are passed to it. It's supported only by certain database backends. Invocation of :class:`.FunctionFilter` is via :meth:`.FunctionElement.filter`:: func.count(1).filter(True) .. versionadded:: 1.0.0 .. seealso:: :meth:`.FunctionElement.filter` """ __visit_name__ = 'funcfilter' criterion = None def __init__(self, func, *criterion): """Produce a :class:`.FunctionFilter` object against a function. Used against aggregate and window functions, for database backends that support the "FILTER" clause. E.g.:: from sqlalchemy import funcfilter funcfilter(func.count(1), MyClass.name == 'some name') Would produce "COUNT(1) FILTER (WHERE myclass.name = 'some name')". This function is also available from the :data:`~.expression.func` construct itself via the :meth:`.FunctionElement.filter` method. .. versionadded:: 1.0.0 .. seealso:: :meth:`.FunctionElement.filter` """ self.func = func self.filter(*criterion) def filter(self, *criterion): """Produce an additional FILTER against the function. This method adds additional criteria to the initial criteria set up by :meth:`.FunctionElement.filter`. Multiple criteria are joined together at SQL render time via ``AND``. """ for criterion in list(criterion): criterion = _expression_literal_as_text(criterion) if self.criterion is not None: self.criterion = self.criterion & criterion else: self.criterion = criterion return self def over(self, partition_by=None, order_by=None): """Produce an OVER clause against this filtered function. Used against aggregate or so-called "window" functions, for database backends that support window functions. The expression:: func.rank().filter(MyClass.y > 5).over(order_by='x') is shorthand for:: from sqlalchemy import over, funcfilter over(funcfilter(func.rank(), MyClass.y > 5), order_by='x') See :func:`~.expression.over` for a full description. """ return Over(self, partition_by=partition_by, order_by=order_by) @util.memoized_property def type(self): return self.func.type def get_children(self, **kwargs): return [c for c in (self.func, self.criterion) if c is not None] def _copy_internals(self, clone=_clone, **kw): self.func = clone(self.func, **kw) if self.criterion is not None: self.criterion = clone(self.criterion, **kw) @property def _from_objects(self): return list(itertools.chain( *[c._from_objects for c in (self.func, self.criterion) if c is not None] )) class Label(ColumnElement): """Represents a column label (AS). Represent a label, as typically applied to any column-level element using the ``AS`` sql keyword. """ __visit_name__ = 'label' def __init__(self, name, element, type_=None): """Return a :class:`Label` object for the given :class:`.ColumnElement`. A label changes the name of an element in the columns clause of a ``SELECT`` statement, typically via the ``AS`` SQL keyword. This functionality is more conveniently available via the :meth:`.ColumnElement.label` method on :class:`.ColumnElement`. :param name: label name :param obj: a :class:`.ColumnElement`. """ if isinstance(element, Label): self._resolve_label = element._label while isinstance(element, Label): element = element.element if name: self.name = name self._resolve_label = self.name else: self.name = _anonymous_label( '%%(%d %s)s' % (id(self), getattr(element, 'name', 'anon')) ) self.key = self._label = self._key_label = self.name self._element = element self._type = type_ self._proxies = [element] def __reduce__(self): return self.__class__, (self.name, self._element, self._type) @util.memoized_property def _allow_label_resolve(self): return self.element._allow_label_resolve @property def _order_by_label_element(self): return self @util.memoized_property def type(self): return type_api.to_instance( self._type or getattr(self._element, 'type', None) ) @util.memoized_property def element(self): return self._element.self_group(against=operators.as_) def self_group(self, against=None): sub_element = self._element.self_group(against=against) if sub_element is not self._element: return Label(self.name, sub_element, type_=self._type) else: return self @property def primary_key(self): return self.element.primary_key @property def foreign_keys(self): return self.element.foreign_keys def get_children(self, **kwargs): return self.element, def _copy_internals(self, clone=_clone, anonymize_labels=False, **kw): self._element = clone(self._element, **kw) self.__dict__.pop('element', None) self.__dict__.pop('_allow_label_resolve', None) if anonymize_labels: self.name = self._resolve_label = _anonymous_label( '%%(%d %s)s' % ( id(self), getattr(self.element, 'name', 'anon')) ) self.key = self._label = self._key_label = self.name @property def _from_objects(self): return self.element._from_objects def _make_proxy(self, selectable, name=None, **kw): e = self.element._make_proxy(selectable, name=name if name else self.name) e._proxies.append(self) if self._type is not None: e.type = self._type return e class ColumnClause(Immutable, ColumnElement): """Represents a column expression from any textual string. The :class:`.ColumnClause`, a lightweight analogue to the :class:`.Column` class, is typically invoked using the :func:`.column` function, as in:: from sqlalchemy import column id, name = column("id"), column("name") stmt = select([id, name]).select_from("user") The above statement would produce SQL like:: SELECT id, name FROM user :class:`.ColumnClause` is the immediate superclass of the schema-specific :class:`.Column` object. While the :class:`.Column` class has all the same capabilities as :class:`.ColumnClause`, the :class:`.ColumnClause` class is usable by itself in those cases where behavioral requirements are limited to simple SQL expression generation. The object has none of the associations with schema-level metadata or with execution-time behavior that :class:`.Column` does, so in that sense is a "lightweight" version of :class:`.Column`. Full details on :class:`.ColumnClause` usage is at :func:`.column`. .. seealso:: :func:`.column` :class:`.Column` """ __visit_name__ = 'column' onupdate = default = server_default = server_onupdate = None _memoized_property = util.group_expirable_memoized_property() def __init__(self, text, type_=None, is_literal=False, _selectable=None): """Produce a :class:`.ColumnClause` object. The :class:`.ColumnClause` is a lightweight analogue to the :class:`.Column` class. The :func:`.column` function can be invoked with just a name alone, as in:: from sqlalchemy import column id, name = column("id"), column("name") stmt = select([id, name]).select_from("user") The above statement would produce SQL like:: SELECT id, name FROM user Once constructed, :func:`.column` may be used like any other SQL expression element such as within :func:`.select` constructs:: from sqlalchemy.sql import column id, name = column("id"), column("name") stmt = select([id, name]).select_from("user") The text handled by :func:`.column` is assumed to be handled like the name of a database column; if the string contains mixed case, special characters, or matches a known reserved word on the target backend, the column expression will render using the quoting behavior determined by the backend. To produce a textual SQL expression that is rendered exactly without any quoting, use :func:`.literal_column` instead, or pass ``True`` as the value of :paramref:`.column.is_literal`. Additionally, full SQL statements are best handled using the :func:`.text` construct. :func:`.column` can be used in a table-like fashion by combining it with the :func:`.table` function (which is the lightweight analogue to :class:`.Table`) to produce a working table construct with minimal boilerplate:: from sqlalchemy import table, column, select user = table("user", column("id"), column("name"), column("description"), ) stmt = select([user.c.description]).where(user.c.name == 'wendy') A :func:`.column` / :func:`.table` construct like that illustrated above can be created in an ad-hoc fashion and is not associated with any :class:`.schema.MetaData`, DDL, or events, unlike its :class:`.Table` counterpart. .. versionchanged:: 1.0.0 :func:`.expression.column` can now be imported from the plain ``sqlalchemy`` namespace like any other SQL element. :param text: the text of the element. :param type: :class:`.types.TypeEngine` object which can associate this :class:`.ColumnClause` with a type. :param is_literal: if True, the :class:`.ColumnClause` is assumed to be an exact expression that will be delivered to the output with no quoting rules applied regardless of case sensitive settings. the :func:`.literal_column()` function essentially invokes :func:`.column` while passing ``is_literal=True``. .. seealso:: :class:`.Column` :func:`.literal_column` :func:`.table` :func:`.text` :ref:`sqlexpression_literal_column` """ self.key = self.name = text self.table = _selectable self.type = type_api.to_instance(type_) self.is_literal = is_literal def _compare_name_for_result(self, other): if self.is_literal or \ self.table is None or self.table._textual or \ not hasattr(other, 'proxy_set') or ( isinstance(other, ColumnClause) and (other.is_literal or other.table is None or other.table._textual) ): return (hasattr(other, 'name') and self.name == other.name) or \ (hasattr(other, '_label') and self._label == other._label) else: return other.proxy_set.intersection(self.proxy_set) def _get_table(self): return self.__dict__['table'] def _set_table(self, table): self._memoized_property.expire_instance(self) self.__dict__['table'] = table table = property(_get_table, _set_table) @_memoized_property def _from_objects(self): t = self.table if t is not None: return [t] else: return [] @util.memoized_property def description(self): if util.py3k: return self.name else: return self.name.encode('ascii', 'backslashreplace') @_memoized_property def _key_label(self): if self.key != self.name: return self._gen_label(self.key) else: return self._label @_memoized_property def _label(self): return self._gen_label(self.name) @_memoized_property def _render_label_in_columns_clause(self): return self.table is not None def _gen_label(self, name): t = self.table if self.is_literal: return None elif t is not None and t.named_with_column: if getattr(t, 'schema', None): label = t.schema.replace('.', '_') + "_" + \ t.name + "_" + name else: label = t.name + "_" + name # propagate name quoting rules for labels. if getattr(name, "quote", None) is not None: if isinstance(label, quoted_name): label.quote = name.quote else: label = quoted_name(label, name.quote) elif getattr(t.name, "quote", None) is not None: # can't get this situation to occur, so let's # assert false on it for now assert not isinstance(label, quoted_name) label = quoted_name(label, t.name.quote) # ensure the label name doesn't conflict with that # of an existing column if label in t.c: _label = label counter = 1 while _label in t.c: _label = label + "_" + str(counter) counter += 1 label = _label return _as_truncated(label) else: return name def _bind_param(self, operator, obj, type_=None): return BindParameter(self.key, obj, _compared_to_operator=operator, _compared_to_type=self.type, type_=type_, unique=True) def _make_proxy(self, selectable, name=None, attach=True, name_is_truncatable=False, **kw): # propagate the "is_literal" flag only if we are keeping our name, # otherwise its considered to be a label is_literal = self.is_literal and (name is None or name == self.name) c = self._constructor( _as_truncated(name or self.name) if name_is_truncatable else (name or self.name), type_=self.type, _selectable=selectable, is_literal=is_literal ) if name is None: c.key = self.key c._proxies = [self] if selectable._is_clone_of is not None: c._is_clone_of = \ selectable._is_clone_of.columns.get(c.key) if attach: selectable._columns[c.key] = c return c class _IdentifiedClause(Executable, ClauseElement): __visit_name__ = 'identified' _execution_options = \ Executable._execution_options.union({'autocommit': False}) def __init__(self, ident): self.ident = ident class SavepointClause(_IdentifiedClause): __visit_name__ = 'savepoint' class RollbackToSavepointClause(_IdentifiedClause): __visit_name__ = 'rollback_to_savepoint' class ReleaseSavepointClause(_IdentifiedClause): __visit_name__ = 'release_savepoint' class quoted_name(util.MemoizedSlots, util.text_type): """Represent a SQL identifier combined with quoting preferences. :class:`.quoted_name` is a Python unicode/str subclass which represents a particular identifier name along with a ``quote`` flag. This ``quote`` flag, when set to ``True`` or ``False``, overrides automatic quoting behavior for this identifier in order to either unconditionally quote or to not quote the name. If left at its default of ``None``, quoting behavior is applied to the identifier on a per-backend basis based on an examination of the token itself. A :class:`.quoted_name` object with ``quote=True`` is also prevented from being modified in the case of a so-called "name normalize" option. Certain database backends, such as Oracle, Firebird, and DB2 "normalize" case-insensitive names as uppercase. The SQLAlchemy dialects for these backends convert from SQLAlchemy's lower-case-means-insensitive convention to the upper-case-means-insensitive conventions of those backends. The ``quote=True`` flag here will prevent this conversion from occurring to support an identifier that's quoted as all lower case against such a backend. The :class:`.quoted_name` object is normally created automatically when specifying the name for key schema constructs such as :class:`.Table`, :class:`.Column`, and others. The class can also be passed explicitly as the name to any function that receives a name which can be quoted. Such as to use the :meth:`.Engine.has_table` method with an unconditionally quoted name:: from sqlaclchemy import create_engine from sqlalchemy.sql.elements import quoted_name engine = create_engine("oracle+cx_oracle://some_dsn") engine.has_table(quoted_name("some_table", True)) The above logic will run the "has table" logic against the Oracle backend, passing the name exactly as ``"some_table"`` without converting to upper case. .. versionadded:: 0.9.0 """ __slots__ = 'quote', 'lower', 'upper' def __new__(cls, value, quote): if value is None: return None # experimental - don't bother with quoted_name # if quote flag is None. doesn't seem to make any dent # in performance however # elif not sprcls and quote is None: # return value elif isinstance(value, cls) and ( quote is None or value.quote == quote ): return value self = super(quoted_name, cls).__new__(cls, value) self.quote = quote return self def __reduce__(self): return quoted_name, (util.text_type(self), self.quote) def _memoized_method_lower(self): if self.quote: return self else: return util.text_type(self).lower() def _memoized_method_upper(self): if self.quote: return self else: return util.text_type(self).upper() def __repr__(self): backslashed = self.encode('ascii', 'backslashreplace') if not util.py2k: backslashed = backslashed.decode('ascii') return "'%s'" % backslashed class _truncated_label(quoted_name): """A unicode subclass used to identify symbolic " "names that may require truncation.""" __slots__ = () def __new__(cls, value, quote=None): quote = getattr(value, "quote", quote) # return super(_truncated_label, cls).__new__(cls, value, quote, True) return super(_truncated_label, cls).__new__(cls, value, quote) def __reduce__(self): return self.__class__, (util.text_type(self), self.quote) def apply_map(self, map_): return self class conv(_truncated_label): """Mark a string indicating that a name has already been converted by a naming convention. This is a string subclass that indicates a name that should not be subject to any further naming conventions. E.g. when we create a :class:`.Constraint` using a naming convention as follows:: m = MetaData(naming_convention={ "ck": "ck_%(table_name)s_%(constraint_name)s" }) t = Table('t', m, Column('x', Integer), CheckConstraint('x > 5', name='x5')) The name of the above constraint will be rendered as ``"ck_t_x5"``. That is, the existing name ``x5`` is used in the naming convention as the ``constraint_name`` token. In some situations, such as in migration scripts, we may be rendering the above :class:`.CheckConstraint` with a name that's already been converted. In order to make sure the name isn't double-modified, the new name is applied using the :func:`.schema.conv` marker. We can use this explicitly as follows:: m = MetaData(naming_convention={ "ck": "ck_%(table_name)s_%(constraint_name)s" }) t = Table('t', m, Column('x', Integer), CheckConstraint('x > 5', name=conv('ck_t_x5'))) Where above, the :func:`.schema.conv` marker indicates that the constraint name here is final, and the name will render as ``"ck_t_x5"`` and not ``"ck_t_ck_t_x5"`` .. versionadded:: 0.9.4 .. seealso:: :ref:`constraint_naming_conventions` """ __slots__ = () class _defer_name(_truncated_label): """mark a name as 'deferred' for the purposes of automated name generation. """ __slots__ = () def __new__(cls, value): if value is None: return _NONE_NAME elif isinstance(value, conv): return value else: return super(_defer_name, cls).__new__(cls, value) def __reduce__(self): return self.__class__, (util.text_type(self), ) class _defer_none_name(_defer_name): """indicate a 'deferred' name that was ultimately the value None.""" __slots__ = () _NONE_NAME = _defer_none_name("_unnamed_") # for backwards compatibility in case # someone is re-implementing the # _truncated_identifier() sequence in a custom # compiler _generated_label = _truncated_label class _anonymous_label(_truncated_label): """A unicode subclass used to identify anonymously generated names.""" __slots__ = () def __add__(self, other): return _anonymous_label( quoted_name( util.text_type.__add__(self, util.text_type(other)), self.quote) ) def __radd__(self, other): return _anonymous_label( quoted_name( util.text_type.__add__(util.text_type(other), self), self.quote) ) def apply_map(self, map_): if self.quote is not None: # preserve quoting only if necessary return quoted_name(self % map_, self.quote) else: # else skip the constructor call return self % map_ def _as_truncated(value): """coerce the given value to :class:`._truncated_label`. Existing :class:`._truncated_label` and :class:`._anonymous_label` objects are passed unchanged. """ if isinstance(value, _truncated_label): return value else: return _truncated_label(value) def _string_or_unprintable(element): if isinstance(element, util.string_types): return element else: try: return str(element) except Exception: return "unprintable element %r" % element def _expand_cloned(elements): """expand the given set of ClauseElements to be the set of all 'cloned' predecessors. """ return itertools.chain(*[x._cloned_set for x in elements]) def _select_iterables(elements): """expand tables into individual columns in the given list of column expressions. """ return itertools.chain(*[c._select_iterable for c in elements]) def _cloned_intersection(a, b): """return the intersection of sets a and b, counting any overlap between 'cloned' predecessors. The returned set is in terms of the entities present within 'a'. """ all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in a if all_overlap.intersection(elem._cloned_set)) def _cloned_difference(a, b): all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set(elem for elem in a if not all_overlap.intersection(elem._cloned_set)) @util.dependencies("sqlalchemy.sql.functions") def _labeled(functions, element): if not hasattr(element, 'name') or \ isinstance(element, functions.FunctionElement): return element.label(None) else: return element def _is_column(col): """True if ``col`` is an instance of :class:`.ColumnElement`.""" return isinstance(col, ColumnElement) def _find_columns(clause): """locate Column objects within the given expression.""" cols = util.column_set() traverse(clause, {}, {'column': cols.add}) return cols # there is some inconsistency here between the usage of # inspect() vs. checking for Visitable and __clause_element__. # Ideally all functions here would derive from inspect(), # however the inspect() versions add significant callcount # overhead for critical functions like _interpret_as_column_or_from(). # Generally, the column-based functions are more performance critical # and are fine just checking for __clause_element__(). It is only # _interpret_as_from() where we'd like to be able to receive ORM entities # that have no defined namespace, hence inspect() is needed there. def _column_as_key(element): if isinstance(element, util.string_types): return element if hasattr(element, '__clause_element__'): element = element.__clause_element__() try: return element.key except AttributeError: return None def _clause_element_as_expr(element): if hasattr(element, '__clause_element__'): return element.__clause_element__() else: return element def _literal_as_label_reference(element): if isinstance(element, util.string_types): return _textual_label_reference(element) elif hasattr(element, '__clause_element__'): element = element.__clause_element__() return _literal_as_text(element) def _literal_and_labels_as_label_reference(element): if isinstance(element, util.string_types): return _textual_label_reference(element) elif hasattr(element, '__clause_element__'): element = element.__clause_element__() if isinstance(element, ColumnElement) and \ element._order_by_label_element is not None: return _label_reference(element) else: return _literal_as_text(element) def _expression_literal_as_text(element): return _literal_as_text(element, warn=True) def _literal_as_text(element, warn=False): if isinstance(element, Visitable): return element elif hasattr(element, '__clause_element__'): return element.__clause_element__() elif isinstance(element, util.string_types): if warn: util.warn_limited( "Textual SQL expression %(expr)r should be " "explicitly declared as text(%(expr)r)", {"expr": util.ellipses_string(element)}) return TextClause(util.text_type(element)) elif isinstance(element, (util.NoneType, bool)): return _const_expr(element) else: raise exc.ArgumentError( "SQL expression object or string expected, got object of type %r " "instead" % type(element) ) def _no_literals(element): if hasattr(element, '__clause_element__'): return element.__clause_element__() elif not isinstance(element, Visitable): raise exc.ArgumentError("Ambiguous literal: %r. Use the 'text()' " "function to indicate a SQL expression " "literal, or 'literal()' to indicate a " "bound value." % element) else: return element def _is_literal(element): return not isinstance(element, Visitable) and \ not hasattr(element, '__clause_element__') def _only_column_elements_or_none(element, name): if element is None: return None else: return _only_column_elements(element, name) def _only_column_elements(element, name): if hasattr(element, '__clause_element__'): element = element.__clause_element__() if not isinstance(element, ColumnElement): raise exc.ArgumentError( "Column-based expression object expected for argument " "'%s'; got: '%s', type %s" % (name, element, type(element))) return element def _literal_as_binds(element, name=None, type_=None): if hasattr(element, '__clause_element__'): return element.__clause_element__() elif not isinstance(element, Visitable): if element is None: return Null() else: return BindParameter(name, element, type_=type_, unique=True) else: return element _guess_straight_column = re.compile(r'^\w\S*$', re.I) def _interpret_as_column_or_from(element): if isinstance(element, Visitable): return element elif hasattr(element, '__clause_element__'): return element.__clause_element__() insp = inspection.inspect(element, raiseerr=False) if insp is None: if isinstance(element, (util.NoneType, bool)): return _const_expr(element) elif hasattr(insp, "selectable"): return insp.selectable # be forgiving as this is an extremely common # and known expression if element == "*": guess_is_literal = True elif isinstance(element, (numbers.Number)): return ColumnClause(str(element), is_literal=True) else: element = str(element) # give into temptation, as this fact we are guessing about # is not one we've previously ever needed our users tell us; # but let them know we are not happy about it guess_is_literal = not _guess_straight_column.match(element) util.warn_limited( "Textual column expression %(column)r should be " "explicitly declared with text(%(column)r), " "or use %(literal_column)s(%(column)r) " "for more specificity", { "column": util.ellipses_string(element), "literal_column": "literal_column" if guess_is_literal else "column" }) return ColumnClause( element, is_literal=guess_is_literal) def _const_expr(element): if isinstance(element, (Null, False_, True_)): return element elif element is None: return Null() elif element is False: return False_() elif element is True: return True_() else: raise exc.ArgumentError( "Expected None, False, or True" ) def _type_from_args(args): for a in args: if not a.type._isnull: return a.type else: return type_api.NULLTYPE def _corresponding_column_or_error(fromclause, column, require_embedded=False): c = fromclause.corresponding_column(column, require_embedded=require_embedded) if c is None: raise exc.InvalidRequestError( "Given column '%s', attached to table '%s', " "failed to locate a corresponding column from table '%s'" % (column, getattr(column, 'table', None), fromclause.description) ) return c class AnnotatedColumnElement(Annotated): def __init__(self, element, values): Annotated.__init__(self, element, values) ColumnElement.comparator._reset(self) for attr in ('name', 'key', 'table'): if self.__dict__.get(attr, False) is None: self.__dict__.pop(attr) def _with_annotations(self, values): clone = super(AnnotatedColumnElement, self)._with_annotations(values) ColumnElement.comparator._reset(clone) return clone @util.memoized_property def name(self): """pull 'name' from parent, if not present""" return self._Annotated__element.name @util.memoized_property def table(self): """pull 'table' from parent, if not present""" return self._Annotated__element.table @util.memoized_property def key(self): """pull 'key' from parent, if not present""" return self._Annotated__element.key @util.memoized_property def info(self): return self._Annotated__element.info @util.memoized_property def anon_label(self): return self._Annotated__element.anon_label
mit
1,248,150,173,061,195,300
32.797638
101
0.593068
false
shubhamVerma/code-eval
Category - Easy/multiplicationTablesCodeEval.py
1
1412
''' tableCodeEval.py - Solution to Problem Multiplication Tables (Category - Easy) Copyright (C) 2013, Shubham Verma This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' ''' Description: Print out the grade school multiplication table upto 12 X 12. Input sample: None Output sample: Print out the table in a matrix like fashion, each number formatted to a width of 4 (The numbers are right-aligned and strip out leading/trailing spaces on each line). The first 3 line will look like: e.g. 1 2 3 4 5 6 7 8 9 10 11 12 2 4 6 8 10 12 14 16 18 20 22 24 3 6 9 12 15 18 21 24 27 30 33 36 ''' if __name__ == '__main__': for i in xrange(1, 13): tmp = [] for j in xrange(1, 13): tmp.append( '%4d' % (i * j)) print (''.join(tmp)).lstrip()
gpl-3.0
-4,420,376,842,689,809,400
27.836735
117
0.675637
false
moble/sympy
sympy/plotting/pygletplot/managed_window.py
120
3178
from __future__ import print_function, division from pyglet.gl import * from pyglet.window import Window from pyglet.clock import Clock from threading import Thread, Lock gl_lock = Lock() class ManagedWindow(Window): """ A pyglet window with an event loop which executes automatically in a separate thread. Behavior is added by creating a subclass which overrides setup, update, and/or draw. """ fps_limit = 30 default_win_args = dict(width=600, height=500, vsync=False, resizable=True) def __init__(self, **win_args): """ It is best not to override this function in the child class, unless you need to take additional arguments. Do any OpenGL initialization calls in setup(). """ # check if this is run from the doctester if win_args.get('runfromdoctester', False): return self.win_args = dict(self.default_win_args, **win_args) self.Thread = Thread(target=self.__event_loop__) self.Thread.start() def __event_loop__(self, **win_args): """ The event loop thread function. Do not override or call directly (it is called by __init__). """ gl_lock.acquire() try: try: super(ManagedWindow, self).__init__(**self.win_args) self.switch_to() self.setup() except Exception as e: print("Window initialization failed: %s" % (str(e))) self.has_exit = True finally: gl_lock.release() clock = Clock() clock.set_fps_limit(self.fps_limit) while not self.has_exit: dt = clock.tick() gl_lock.acquire() try: try: self.switch_to() self.dispatch_events() self.clear() self.update(dt) self.draw() self.flip() except Exception as e: print("Uncaught exception in event loop: %s" % str(e)) self.has_exit = True finally: gl_lock.release() super(ManagedWindow, self).close() def close(self): """ Closes the window. """ self.has_exit = True def setup(self): """ Called once before the event loop begins. Override this method in a child class. This is the best place to put things like OpenGL initialization calls. """ pass def update(self, dt): """ Called before draw during each iteration of the event loop. dt is the elapsed time in seconds since the last update. OpenGL rendering calls are best put in draw() rather than here. """ pass def draw(self): """ Called after update during each iteration of the event loop. Put OpenGL rendering calls here. """ pass if __name__ == '__main__': ManagedWindow()
bsd-3-clause
1,215,223,031,426,437,400
28.155963
74
0.525488
false
azureplus/hue
desktop/core/ext-py/Django-1.6.10/django/contrib/gis/db/models/sql/query.py
209
5406
from django.db import connections from django.db.models.query import sql from django.contrib.gis.db.models.fields import GeometryField from django.contrib.gis.db.models.sql import aggregates as gis_aggregates from django.contrib.gis.db.models.sql.conversion import AreaField, DistanceField, GeomField from django.contrib.gis.db.models.sql.where import GeoWhereNode from django.contrib.gis.geometry.backend import Geometry from django.contrib.gis.measure import Area, Distance ALL_TERMS = set([ 'bbcontains', 'bboverlaps', 'contained', 'contains', 'contains_properly', 'coveredby', 'covers', 'crosses', 'disjoint', 'distance_gt', 'distance_gte', 'distance_lt', 'distance_lte', 'dwithin', 'equals', 'exact', 'intersects', 'overlaps', 'relate', 'same_as', 'touches', 'within', 'left', 'right', 'overlaps_left', 'overlaps_right', 'overlaps_above', 'overlaps_below', 'strictly_above', 'strictly_below' ]) ALL_TERMS.update(sql.constants.QUERY_TERMS) class GeoQuery(sql.Query): """ A single spatial SQL query. """ # Overridding the valid query terms. query_terms = ALL_TERMS aggregates_module = gis_aggregates compiler = 'GeoSQLCompiler' #### Methods overridden from the base Query class #### def __init__(self, model, where=GeoWhereNode): super(GeoQuery, self).__init__(model, where) # The following attributes are customized for the GeoQuerySet. # The GeoWhereNode and SpatialBackend classes contain backend-specific # routines and functions. self.custom_select = {} self.transformed_srid = None self.extra_select_fields = {} def clone(self, *args, **kwargs): obj = super(GeoQuery, self).clone(*args, **kwargs) # Customized selection dictionary and transformed srid flag have # to also be added to obj. obj.custom_select = self.custom_select.copy() obj.transformed_srid = self.transformed_srid obj.extra_select_fields = self.extra_select_fields.copy() return obj def convert_values(self, value, field, connection): """ Using the same routines that Oracle does we can convert our extra selection objects into Geometry and Distance objects. TODO: Make converted objects 'lazy' for less overhead. """ if connection.ops.oracle: # Running through Oracle's first. value = super(GeoQuery, self).convert_values(value, field or GeomField(), connection) if value is None: # Output from spatial function is NULL (e.g., called # function on a geometry field with NULL value). pass elif isinstance(field, DistanceField): # Using the field's distance attribute, can instantiate # `Distance` with the right context. value = Distance(**{field.distance_att : value}) elif isinstance(field, AreaField): value = Area(**{field.area_att : value}) elif isinstance(field, (GeomField, GeometryField)) and value: value = Geometry(value) elif field is not None: return super(GeoQuery, self).convert_values(value, field, connection) return value def get_aggregation(self, using): # Remove any aggregates marked for reduction from the subquery # and move them to the outer AggregateQuery. connection = connections[using] for alias, aggregate in self.aggregate_select.items(): if isinstance(aggregate, gis_aggregates.GeoAggregate): if not getattr(aggregate, 'is_extent', False) or connection.ops.oracle: self.extra_select_fields[alias] = GeomField() return super(GeoQuery, self).get_aggregation(using) def resolve_aggregate(self, value, aggregate, connection): """ Overridden from GeoQuery's normalize to handle the conversion of GeoAggregate objects. """ if isinstance(aggregate, self.aggregates_module.GeoAggregate): if aggregate.is_extent: if aggregate.is_extent == '3D': return connection.ops.convert_extent3d(value) else: return connection.ops.convert_extent(value) else: return connection.ops.convert_geom(value, aggregate.source) else: return super(GeoQuery, self).resolve_aggregate(value, aggregate, connection) # Private API utilities, subject to change. def _geo_field(self, field_name=None): """ Returns the first Geometry field encountered; or specified via the `field_name` keyword. The `field_name` may be a string specifying the geometry field on this GeoQuery'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 fld in self.model._meta.fields: if isinstance(fld, GeometryField): return fld return False else: # Otherwise, check by the given field name -- which may be # a lookup to a _related_ geographic field. return GeoWhereNode._check_geo_field(self.model._meta, field_name)
apache-2.0
5,247,311,618,120,358,000
43.677686
97
0.637995
false
AISpace2/AISpace2
aispace2/jupyter/csp/csp_xml_to_python.py
1
3954
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 27 12:21:17 2019 @author: zijiazhang """ import itertools import xml.etree.ElementTree as ET from ast import literal_eval as make_tuple from string import Template def findcontain(elem, tag): for child in elem: if tag in child.tag: return child return None def findallcontain(elem, tag): temp = [] for child in elem: if tag in child.tag: temp.append(child.text.replace(' ', '_')) return temp def str2bool(v): return v.lower() in ("yes", "true", "t", "1") def xml_to_python(path): tree = ET.parse(path) root = tree.getroot() CSP = root.find('CSP') domains = {} positions = {} constraints = [] name = CSP.find('NAME').text.replace(' ', '_') for i in CSP: if i.tag == 'VARIABLE': mytype = i.get('TYPE') if(mytype == 'Integer'): pass elif(mytype == 'String'): pass elif(mytype == 'Boolean'): pass varDomain = [] for e in i: if e.tag == 'NAME': varName = e.text if e.tag == 'VALUE': if(mytype == 'Integer'): varDomain.append(int(e.text)) elif(mytype == 'String'): varDomain.append(e.text) elif(mytype == 'Boolean'): varDomain.append(str2bool(e.text)) if e.tag == 'PROPERTY': positions[varName] = make_tuple(e.text.split('=')[1][1:]) domains[varName] = varDomain elif i.tag == 'CONSTRAINT': if i.get('TYPE') == 'Custom': relatedvar = [] table = [] for e in i: if e.tag == 'GIVEN': relatedvar.append(e.text) elif e.tag == 'TABLE': table = e.text.split(" ") table = ['T' in x for x in table] trueTuples = [] targetlist = [domains[x] for x in relatedvar] allTuple = list(itertools.product(*targetlist)) for i in range(0, len(allTuple)): if table[i]: trueTuples.append(str(allTuple[i])) relatedvarName = ["'" + x + "'" for x in relatedvar] constraints.append(Template('Constraint(($var),lambda $vNames: ($vNames) in [$true])').substitute( var=','.join(relatedvarName), vNames=','.join(relatedvar), true=','.join(trueTuples) )) else: relatedvar = [] complement = False for e in i: if e.tag == 'GIVEN': relatedvar.append(e.text) elif e.tag == 'ARGS': if e.text != None and 'complement' in e.text: complement = True relatedvarName = ["'" + x + "'" for x in relatedvar] if complement: constraints.append(Template('Constraint(($var),NOT($function))').substitute( var=','.join(relatedvarName), function=i.get('TYPE') )) else: constraints.append(Template('Constraint(($var),$function)').substitute( var=','.join(relatedvarName), function=i.get('TYPE') )) template = """$name = CSP( domains=$domains, constraints=[$constraints], positions=$positions)""" print(Template(template).substitute( name=name, domains=domains, constraints=', '.join(constraints), positions=positions))
gpl-3.0
3,163,983,078,657,377,300
31.409836
114
0.452959
false
stefanlaheij/ha-buderus
buderus/__init__.py
1
5715
""" Support to communicate with a Buderus KM200 unit. """ import logging import base64 import json import binascii import urllib.request, urllib.error, urllib.parse import voluptuous as vol from io import StringIO from Crypto.Cipher import AES from homeassistant.helpers import config_validation as cv from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_NAME) DOMAIN = 'buderus' DEFAULT_NAME = 'Buderus' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }), }, extra=vol.ALLOW_EXTRA) def setup(hass, config): conf = config[DOMAIN] host = conf.get(CONF_HOST) name = conf.get(CONF_NAME) password = conf.get(CONF_PASSWORD) bridge = BuderusBridge(name, host, password) hass.data[DOMAIN] = bridge return True class BuderusBridge(object): BS = AES.block_size INTERRUPT = '\u0001' PAD = '\u0000' def __init__(self, name, host, password): self.logger = logging.getLogger(__name__) self.logger.info("Init Buderus") self.__ua = "TeleHeater/2.2.3" self.__content_type = "application/json" self._host = host self._key = binascii.unhexlify(password) self._ids = {} self.opener = urllib.request.build_opener() self.opener.addheaders = [('User-agent', self.__ua), ('Accept', self.__content_type)] self.name = name def _decrypt(self, enc): decobj = AES.new(self._key, AES.MODE_ECB) data = decobj.decrypt(base64.b64decode(enc)) data = data.rstrip(self.PAD.encode()).rstrip(self.INTERRUPT.encode()) return data def _encrypt(self, plain): plain = plain + (AES.block_size - len(plain) % self.BS) * self.PAD encobj = AES.new(self._key, AES.MODE_ECB) data = encobj.encrypt(plain.encode()) return base64.b64encode(data) def _get_data(self, path): try: url = 'http://' + self._host + path self.logger.debug("Buderus fetching data from {}".format(path)) resp = self.opener.open(url) plain = self._decrypt(resp.read()) self.logger.debug("Buderus data received from {}: {}".format(url, plain)) return plain except Exception as e: self.logger.error("Buderus error happened at {}: {}".format(url, e)) return None def _get_json(self, data): try: j = json.load(StringIO(data.decode())) return j except Exception as e: self.logger.error("Buderus error happened while reading JSON data {}: {}".format(data, e)) return False def _get_value(self, j): return j['value'] def _json_encode(self, value): d = {"value": value} return json.dumps(d) def _set_data(self, path, data): try: url = 'http://' + self._host + path self.logger.info("Buderus setting value for {}".format(path)) headers = {"User-Agent": self.__ua, "Content-Type": self.__content_type} request = urllib.request.Request(url, data=data, headers=headers, method='PUT') req = urllib.request.urlopen(request) self.logger.info("Buderus returned {}: {}".format(req.status, req.reason)) if not req.status == 204: self.logger.debug(req.read()) except Exception as e: self.logger.error("Buderus error happened at {}: {}".format(url, e)) return None def _submit_data(self, path, data): self.logger.info("Buderus SETTING {} to {}".format(path, data)) payload = self._json_encode(data) self.logger.debug(payload) req = self._set_data(path, self._encrypt(str(payload))) """ def _get_type(self, j): return j['type'] def _get_writeable(self, j): if j['writeable'] == 1: return True else: return False def _get_allowed_values(self, j, value_type): if value_type == "stringValue": try: return j['allowedValues'] except: return None elif value_type == "floatValue": return {"minValue": j['minValue'], "maxValue": j['maxValue']} def update_item(self, item, caller=None, source=None, dest=None): if caller != "Buderus": id = item.conf['km_id'] plain = self._get_data(id) data = self._get_json(plain) if self._get_writeable(data): value_type = self._get_type(data) allowed_values = self._get_allowed_values(data, value_type) if value_type == "stringValue" and item() in allowed_values or not allowed_values: self._submit_data(item, id) return elif value_type == "floatValue" and item() >= allowed_values['minValue'] and item() <= allowed_values[ 'maxValue']: self._submit_data(item, id) return else: self.logger.error("Buderus value {} not allowed [{}]".format(item(), allowed_values)) item(item.prev_value(), "Buderus") else: self.logger.error("Buderus item {} not writeable!".format(item)) item(item.prev_value(), "Buderus") """
gpl-3.0
-6,367,909,157,888,069,000
34.183544
118
0.549606
false
HybridF5/nova
nova/tests/unit/api/openstack/compute/test_flavors.py
7
25560
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import six import six.moves.urllib.parse as urlparse import webob from nova.api.openstack import common from nova.api.openstack.compute import flavors as flavors_v21 from nova.api.openstack.compute.legacy_v2 import flavors as flavors_v2 import nova.compute.flavors from nova import context from nova import db from nova import exception from nova import test from nova.tests.unit.api.openstack import fakes from nova.tests.unit import matchers NS = "{http://docs.openstack.org/compute/api/v1.1}" ATOMNS = "{http://www.w3.org/2005/Atom}" FAKE_FLAVORS = { 'flavor 1': { "flavorid": '1', "name": 'flavor 1', "memory_mb": '256', "root_gb": '10', "ephemeral_gb": '20', "swap": '10', "disabled": False, "vcpus": '', }, 'flavor 2': { "flavorid": '2', "name": 'flavor 2', "memory_mb": '512', "root_gb": '20', "ephemeral_gb": '10', "swap": '5', "disabled": False, "vcpus": '', }, } def fake_flavor_get_by_flavor_id(flavorid, ctxt=None): return FAKE_FLAVORS['flavor %s' % flavorid] def fake_get_all_flavors_sorted_list(context=None, inactive=False, filters=None, sort_key='flavorid', sort_dir='asc', limit=None, marker=None): if marker in ['99999']: raise exception.MarkerNotFound(marker) def reject_min(db_attr, filter_attr): return (filter_attr in filters and int(flavor[db_attr]) < int(filters[filter_attr])) filters = filters or {} res = [] for (flavor_name, flavor) in FAKE_FLAVORS.items(): if reject_min('memory_mb', 'min_memory_mb'): continue elif reject_min('root_gb', 'min_root_gb'): continue res.append(flavor) res = sorted(res, key=lambda item: item[sort_key]) output = [] marker_found = True if marker is None else False for flavor in res: if not marker_found and marker == flavor['flavorid']: marker_found = True elif marker_found: if limit is None or len(output) < int(limit): output.append(flavor) return output def fake_get_limit_and_marker(request, max_limit=1): params = common.get_pagination_params(request) limit = params.get('limit', max_limit) limit = min(max_limit, limit) marker = params.get('marker') return limit, marker def empty_get_all_flavors_sorted_list(context=None, inactive=False, filters=None, sort_key='flavorid', sort_dir='asc', limit=None, marker=None): return [] def return_flavor_not_found(flavor_id, ctxt=None): raise exception.FlavorNotFound(flavor_id=flavor_id) class FlavorsTestV21(test.TestCase): _prefix = "/v2/fake" Controller = flavors_v21.FlavorsController fake_request = fakes.HTTPRequestV21 _rspv = "v2/fake" _fake = "/fake" def setUp(self): super(FlavorsTestV21, self).setUp() self.flags(osapi_compute_extension=[]) fakes.stub_out_networking(self) fakes.stub_out_rate_limiting(self.stubs) self.stubs.Set(nova.compute.flavors, "get_all_flavors_sorted_list", fake_get_all_flavors_sorted_list) self.stubs.Set(nova.compute.flavors, "get_flavor_by_flavor_id", fake_flavor_get_by_flavor_id) self.controller = self.Controller() def _set_expected_body(self, expected, ephemeral, swap, disabled): # NOTE(oomichi): On v2.1 API, some extensions of v2.0 are merged # as core features and we can get the following parameters as the # default. expected['OS-FLV-EXT-DATA:ephemeral'] = ephemeral expected['OS-FLV-DISABLED:disabled'] = disabled expected['swap'] = swap def test_get_flavor_by_invalid_id(self): self.stubs.Set(nova.compute.flavors, "get_flavor_by_flavor_id", return_flavor_not_found) req = self.fake_request.blank(self._prefix + '/flavors/asdf') self.assertRaises(webob.exc.HTTPNotFound, self.controller.show, req, 'asdf') def test_get_flavor_by_id(self): req = self.fake_request.blank(self._prefix + '/flavors/1') flavor = self.controller.show(req, '1') expected = { "flavor": { "id": "1", "name": "flavor 1", "ram": "256", "disk": "10", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, } self._set_expected_body(expected['flavor'], ephemeral='20', swap='10', disabled=False) self.assertEqual(flavor, expected) def test_get_flavor_with_custom_link_prefix(self): self.flags(osapi_compute_link_prefix='http://zoo.com:42', osapi_glance_link_prefix='http://circus.com:34') req = self.fake_request.blank(self._prefix + '/flavors/1') flavor = self.controller.show(req, '1') expected = { "flavor": { "id": "1", "name": "flavor 1", "ram": "256", "disk": "10", "vcpus": "", "links": [ { "rel": "self", "href": "http://zoo.com:42/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://zoo.com:42" + self._fake + "/flavors/1", }, ], }, } self._set_expected_body(expected['flavor'], ephemeral='20', swap='10', disabled=False) self.assertEqual(expected, flavor) def test_get_flavor_list(self): req = self.fake_request.blank(self._prefix + '/flavors') flavor = self.controller.index(req) expected = { "flavors": [ { "id": "1", "name": "flavor 1", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self.assertEqual(flavor, expected) def test_get_flavor_list_with_marker(self): self.maxDiff = None url = self._prefix + '/flavors?limit=1&marker=1' req = self.fake_request.blank(url) flavor = self.controller.index(req) expected = { "flavors": [ { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], 'flavors_links': [ {'href': 'http://localhost/' + self._rspv + '/flavors?limit=1&marker=2', 'rel': 'next'} ] } self.assertThat(flavor, matchers.DictMatches(expected)) def test_get_flavor_list_with_invalid_marker(self): req = self.fake_request.blank(self._prefix + '/flavors?marker=99999') self.assertRaises(webob.exc.HTTPBadRequest, self.controller.index, req) def test_get_flavor_detail_with_limit(self): url = self._prefix + '/flavors/detail?limit=1' req = self.fake_request.blank(url) response = self.controller.detail(req) response_list = response["flavors"] response_links = response["flavors_links"] expected_flavors = [ { "id": "1", "name": "flavor 1", "ram": "256", "disk": "10", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, ] self._set_expected_body(expected_flavors[0], ephemeral='20', swap='10', disabled=False) self.assertEqual(response_list, expected_flavors) self.assertEqual(response_links[0]['rel'], 'next') href_parts = urlparse.urlparse(response_links[0]['href']) self.assertEqual('/' + self._rspv + '/flavors/detail', href_parts.path) params = urlparse.parse_qs(href_parts.query) self.assertThat({'limit': ['1'], 'marker': ['1']}, matchers.DictMatches(params)) def test_get_flavor_with_limit(self): req = self.fake_request.blank(self._prefix + '/flavors?limit=2') response = self.controller.index(req) response_list = response["flavors"] response_links = response["flavors_links"] expected_flavors = [ { "id": "1", "name": "flavor 1", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], } ] self.assertEqual(response_list, expected_flavors) self.assertEqual(response_links[0]['rel'], 'next') href_parts = urlparse.urlparse(response_links[0]['href']) self.assertEqual('/' + self._rspv + '/flavors', href_parts.path) params = urlparse.parse_qs(href_parts.query) self.assertThat({'limit': ['2'], 'marker': ['2']}, matchers.DictMatches(params)) def test_get_flavor_with_default_limit(self): self.stubs.Set(common, "get_limit_and_marker", fake_get_limit_and_marker) self.flags(osapi_max_limit=1) req = fakes.HTTPRequest.blank('/v2/fake/flavors?limit=2') response = self.controller.index(req) response_list = response["flavors"] response_links = response["flavors_links"] expected_flavors = [ { "id": "1", "name": "flavor 1", "links": [ { "rel": "self", "href": "http://localhost/v2/fake/flavors/1", }, { "rel": "bookmark", "href": "http://localhost/fake/flavors/1", } ] } ] self.assertEqual(response_list, expected_flavors) self.assertEqual(response_links[0]['rel'], 'next') href_parts = urlparse.urlparse(response_links[0]['href']) self.assertEqual('/v2/fake/flavors', href_parts.path) params = urlparse.parse_qs(href_parts.query) self.assertThat({'limit': ['2'], 'marker': ['1']}, matchers.DictMatches(params)) def test_get_flavor_list_detail(self): req = self.fake_request.blank(self._prefix + '/flavors/detail') flavor = self.controller.detail(req) expected = { "flavors": [ { "id": "1", "name": "flavor 1", "ram": "256", "disk": "10", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/1", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/1", }, ], }, { "id": "2", "name": "flavor 2", "ram": "512", "disk": "20", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self._set_expected_body(expected['flavors'][0], ephemeral='20', swap='10', disabled=False) self._set_expected_body(expected['flavors'][1], ephemeral='10', swap='5', disabled=False) self.assertEqual(expected, flavor) def test_get_empty_flavor_list(self): self.stubs.Set(nova.compute.flavors, "get_all_flavors_sorted_list", empty_get_all_flavors_sorted_list) req = self.fake_request.blank(self._prefix + '/flavors') flavors = self.controller.index(req) expected = {'flavors': []} self.assertEqual(flavors, expected) def test_get_flavor_list_filter_min_ram(self): # Flavor lists may be filtered by minRam. req = self.fake_request.blank(self._prefix + '/flavors?minRam=512') flavor = self.controller.index(req) expected = { "flavors": [ { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self.assertEqual(flavor, expected) def test_get_flavor_list_filter_invalid_min_ram(self): # Ensure you cannot list flavors with invalid minRam param. req = self.fake_request.blank(self._prefix + '/flavors?minRam=NaN') self.assertRaises(webob.exc.HTTPBadRequest, self.controller.index, req) def test_get_flavor_list_filter_min_disk(self): # Flavor lists may be filtered by minDisk. req = self.fake_request.blank(self._prefix + '/flavors?minDisk=20') flavor = self.controller.index(req) expected = { "flavors": [ { "id": "2", "name": "flavor 2", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self.assertEqual(flavor, expected) def test_get_flavor_list_filter_invalid_min_disk(self): # Ensure you cannot list flavors with invalid minDisk param. req = self.fake_request.blank(self._prefix + '/flavors?minDisk=NaN') self.assertRaises(webob.exc.HTTPBadRequest, self.controller.index, req) def test_get_flavor_list_detail_min_ram_and_min_disk(self): """Tests that filtering work on flavor details and that minRam and minDisk filters can be combined """ req = self.fake_request.blank(self._prefix + '/flavors/detail' '?minRam=256&minDisk=20') flavor = self.controller.detail(req) expected = { "flavors": [ { "id": "2", "name": "flavor 2", "ram": "512", "disk": "20", "vcpus": "", "links": [ { "rel": "self", "href": "http://localhost/" + self._rspv + "/flavors/2", }, { "rel": "bookmark", "href": "http://localhost" + self._fake + "/flavors/2", }, ], }, ], } self._set_expected_body(expected['flavors'][0], ephemeral='10', swap='5', disabled=False) self.assertEqual(expected, flavor) class FlavorsTestV20(FlavorsTestV21): Controller = flavors_v2.Controller fake_request = fakes.HTTPRequest def _set_expected_body(self, expected, ephemeral, swap, disabled): pass class DisabledFlavorsWithRealDBTestV21(test.TestCase): """Tests that disabled flavors should not be shown nor listed.""" Controller = flavors_v21.FlavorsController _prefix = "/v2" fake_request = fakes.HTTPRequestV21 def setUp(self): super(DisabledFlavorsWithRealDBTestV21, self).setUp() # Add a new disabled type to the list of flavors self.req = self.fake_request.blank(self._prefix + '/flavors') self.context = self.req.environ['nova.context'] self.admin_context = context.get_admin_context() self.disabled_type = self._create_disabled_instance_type() self.inst_types = db.flavor_get_all( self.admin_context) self.controller = self.Controller() def tearDown(self): db.flavor_destroy( self.admin_context, self.disabled_type['name']) super(DisabledFlavorsWithRealDBTestV21, self).tearDown() def _create_disabled_instance_type(self): inst_types = db.flavor_get_all(self.admin_context) inst_type = inst_types[0] del inst_type['id'] inst_type['name'] += '.disabled' inst_type['flavorid'] = six.text_type(max( [int(flavor['flavorid']) for flavor in inst_types]) + 1) inst_type['disabled'] = True disabled_type = db.flavor_create( self.admin_context, inst_type) return disabled_type def test_index_should_not_list_disabled_flavors_to_user(self): self.context.is_admin = False flavor_list = self.controller.index(self.req)['flavors'] api_flavorids = set(f['id'] for f in flavor_list) db_flavorids = set(i['flavorid'] for i in self.inst_types) disabled_flavorid = str(self.disabled_type['flavorid']) self.assertIn(disabled_flavorid, db_flavorids) self.assertEqual(db_flavorids - set([disabled_flavorid]), api_flavorids) def test_index_should_list_disabled_flavors_to_admin(self): self.context.is_admin = True flavor_list = self.controller.index(self.req)['flavors'] api_flavorids = set(f['id'] for f in flavor_list) db_flavorids = set(i['flavorid'] for i in self.inst_types) disabled_flavorid = str(self.disabled_type['flavorid']) self.assertIn(disabled_flavorid, db_flavorids) self.assertEqual(db_flavorids, api_flavorids) def test_show_should_include_disabled_flavor_for_user(self): """Counterintuitively we should show disabled flavors to all users and not just admins. The reason is that, when a user performs a server-show request, we want to be able to display the pretty flavor name ('512 MB Instance') and not just the flavor-id even if the flavor id has been marked disabled. """ self.context.is_admin = False flavor = self.controller.show( self.req, self.disabled_type['flavorid'])['flavor'] self.assertEqual(flavor['name'], self.disabled_type['name']) def test_show_should_include_disabled_flavor_for_admin(self): self.context.is_admin = True flavor = self.controller.show( self.req, self.disabled_type['flavorid'])['flavor'] self.assertEqual(flavor['name'], self.disabled_type['name']) class DisabledFlavorsWithRealDBTestV20(DisabledFlavorsWithRealDBTestV21): """Tests that disabled flavors should not be shown nor listed.""" Controller = flavors_v2.Controller _prefix = "/v2/fake" fake_request = fakes.HTTPRequest class ParseIsPublicTestV21(test.TestCase): Controller = flavors_v21.FlavorsController def setUp(self): super(ParseIsPublicTestV21, self).setUp() self.controller = self.Controller() def assertPublic(self, expected, is_public): self.assertIs(expected, self.controller._parse_is_public(is_public), '%s did not return %s' % (is_public, expected)) def test_None(self): self.assertPublic(True, None) def test_truthy(self): self.assertPublic(True, True) self.assertPublic(True, 't') self.assertPublic(True, 'true') self.assertPublic(True, 'yes') self.assertPublic(True, '1') def test_falsey(self): self.assertPublic(False, False) self.assertPublic(False, 'f') self.assertPublic(False, 'false') self.assertPublic(False, 'no') self.assertPublic(False, '0') def test_string_none(self): self.assertPublic(None, 'none') self.assertPublic(None, 'None') def test_other(self): self.assertRaises( webob.exc.HTTPBadRequest, self.assertPublic, None, 'other') class ParseIsPublicTestV20(ParseIsPublicTestV21): Controller = flavors_v2.Controller
apache-2.0
7,101,779,594,173,789,000
35
79
0.466628
false
salaria/odoo
addons/calendar/calendar.py
81
86439
# -*- coding: utf-8 -*- import pytz import re import time import openerp import openerp.service.report import uuid import collections import babel.dates from werkzeug.exceptions import BadRequest from datetime import datetime, timedelta from dateutil import parser from dateutil import rrule from dateutil.relativedelta import relativedelta from openerp import api from openerp import tools, SUPERUSER_ID from openerp.osv import fields, osv from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools.translate import _ from openerp.http import request from operator import itemgetter import logging _logger = logging.getLogger(__name__) def calendar_id2real_id(calendar_id=None, with_date=False): """ Convert a "virtual/recurring event id" (type string) into a real event id (type int). E.g. virtual/recurring event id is 4-20091201100000, so it will return 4. @param calendar_id: id of calendar @param with_date: if a value is passed to this param it will return dates based on value of withdate + calendar_id @return: real event id """ if calendar_id and isinstance(calendar_id, (basestring)): res = calendar_id.split('-') if len(res) >= 2: real_id = res[0] if with_date: real_date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT, time.strptime(res[1], "%Y%m%d%H%M%S")) start = datetime.strptime(real_date, DEFAULT_SERVER_DATETIME_FORMAT) end = start + timedelta(hours=with_date) return (int(real_id), real_date, end.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) return int(real_id) return calendar_id and int(calendar_id) or calendar_id def get_real_ids(ids): if isinstance(ids, (basestring, int, long)): return calendar_id2real_id(ids) if isinstance(ids, (list, tuple)): return [calendar_id2real_id(id) for id in ids] class calendar_attendee(osv.Model): """ Calendar Attendee Information """ _name = 'calendar.attendee' _rec_name = 'cn' _description = 'Attendee information' def _compute_data(self, cr, uid, ids, name, arg, context=None): """ Compute data on function fields for attendee values. @param ids: list of calendar attendee's IDs @param name: name of field @return: dictionary of form {id: {'field Name': value'}} """ name = name[0] result = {} for attdata in self.browse(cr, uid, ids, context=context): id = attdata.id result[id] = {} if name == 'cn': if attdata.partner_id: result[id][name] = attdata.partner_id.name or False else: result[id][name] = attdata.email or '' return result STATE_SELECTION = [ ('needsAction', 'Needs Action'), ('tentative', 'Uncertain'), ('declined', 'Declined'), ('accepted', 'Accepted'), ] _columns = { 'state': fields.selection(STATE_SELECTION, 'Status', readonly=True, help="Status of the attendee's participation"), 'cn': fields.function(_compute_data, string='Common name', type="char", multi='cn', store=True), 'partner_id': fields.many2one('res.partner', 'Contact', readonly="True"), 'email': fields.char('Email', help="Email of Invited Person"), 'availability': fields.selection([('free', 'Free'), ('busy', 'Busy')], 'Free/Busy', readonly="True"), 'access_token': fields.char('Invitation Token'), 'event_id': fields.many2one('calendar.event', 'Meeting linked', ondelete='cascade'), } _defaults = { 'state': 'needsAction', } def copy(self, cr, uid, id, default=None, context=None): raise osv.except_osv(_('Warning!'), _('You cannot duplicate a calendar attendee.')) def onchange_partner_id(self, cr, uid, ids, partner_id, context=None): """ Make entry on email and availability on change of partner_id field. @param partner_id: changed value of partner id """ if not partner_id: return {'value': {'email': ''}} partner = self.pool['res.partner'].browse(cr, uid, partner_id, context=context) return {'value': {'email': partner.email}} def get_ics_file(self, cr, uid, event_obj, context=None): """ Returns iCalendar file for the event invitation. @param event_obj: event object (browse record) @return: .ics file content """ res = None def ics_datetime(idate, allday=False): if idate: if allday: return openerp.fields.Date.from_string(idate) else: return openerp.fields.Datetime.from_string(idate).replace(tzinfo=pytz.timezone('UTC')) return False try: # FIXME: why isn't this in CalDAV? import vobject except ImportError: return res cal = vobject.iCalendar() event = cal.add('vevent') if not event_obj.start or not event_obj.stop: raise osv.except_osv(_('Warning!'), _("First you have to specify the date of the invitation.")) event.add('created').value = ics_datetime(time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)) event.add('dtstart').value = ics_datetime(event_obj.start, event_obj.allday) event.add('dtend').value = ics_datetime(event_obj.stop, event_obj.allday) event.add('summary').value = event_obj.name if event_obj.description: event.add('description').value = event_obj.description if event_obj.location: event.add('location').value = event_obj.location if event_obj.rrule: event.add('rrule').value = event_obj.rrule if event_obj.alarm_ids: for alarm in event_obj.alarm_ids: valarm = event.add('valarm') interval = alarm.interval duration = alarm.duration trigger = valarm.add('TRIGGER') trigger.params['related'] = ["START"] if interval == 'days': delta = timedelta(days=duration) elif interval == 'hours': delta = timedelta(hours=duration) elif interval == 'minutes': delta = timedelta(minutes=duration) trigger.value = delta valarm.add('DESCRIPTION').value = alarm.name or 'Odoo' for attendee in event_obj.attendee_ids: attendee_add = event.add('attendee') attendee_add.value = 'MAILTO:' + (attendee.email or '') res = cal.serialize() return res def _send_mail_to_attendees(self, cr, uid, ids, email_from=tools.config.get('email_from', False), template_xmlid='calendar_template_meeting_invitation', force=False, context=None): """ Send mail for event invitation to event attendees. @param email_from: email address for user sending the mail @param force: If set to True, email will be sent to user himself. Usefull for example for alert, ... """ res = False if self.pool['ir.config_parameter'].get_param(cr, uid, 'calendar.block_mail', default=False) or context.get("no_mail_to_attendees"): return res mail_ids = [] data_pool = self.pool['ir.model.data'] mailmess_pool = self.pool['mail.message'] mail_pool = self.pool['mail.mail'] template_pool = self.pool['email.template'] local_context = context.copy() color = { 'needsAction': 'grey', 'accepted': 'green', 'tentative': '#FFFF00', 'declined': 'red' } if not isinstance(ids, (tuple, list)): ids = [ids] dummy, template_id = data_pool.get_object_reference(cr, uid, 'calendar', template_xmlid) dummy, act_id = data_pool.get_object_reference(cr, uid, 'calendar', "view_calendar_event_calendar") local_context.update({ 'color': color, 'action_id': self.pool['ir.actions.act_window'].search(cr, uid, [('view_id', '=', act_id)], context=context)[0], 'dbname': cr.dbname, 'base_url': self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url', default='http://localhost:8069', context=context) }) for attendee in self.browse(cr, uid, ids, context=context): if attendee.email and email_from and (attendee.email != email_from or force): ics_file = self.get_ics_file(cr, uid, attendee.event_id, context=context) mail_id = template_pool.send_mail(cr, uid, template_id, attendee.id, context=local_context) vals = {} if ics_file: vals['attachment_ids'] = [(0, 0, {'name': 'invitation.ics', 'datas_fname': 'invitation.ics', 'datas': str(ics_file).encode('base64')})] vals['model'] = None # We don't want to have the mail in the tchatter while in queue! the_mailmess = mail_pool.browse(cr, uid, mail_id, context=context).mail_message_id mailmess_pool.write(cr, uid, [the_mailmess.id], vals, context=context) mail_ids.append(mail_id) if mail_ids: res = mail_pool.send(cr, uid, mail_ids, context=context) return res def onchange_user_id(self, cr, uid, ids, user_id, *args, **argv): """ Make entry on email and availability on change of user_id field. @param ids: list of attendee's IDs @param user_id: changed value of User id @return: dictionary of values which put value in email and availability fields """ if not user_id: return {'value': {'email': ''}} user = self.pool['res.users'].browse(cr, uid, user_id, *args) return {'value': {'email': user.email, 'availability': user.availability}} def do_tentative(self, cr, uid, ids, context=None, *args): """ Makes event invitation as Tentative. @param ids: list of attendee's IDs """ return self.write(cr, uid, ids, {'state': 'tentative'}, context) def do_accept(self, cr, uid, ids, context=None, *args): """ Marks event invitation as Accepted. @param ids: list of attendee's IDs """ if context is None: context = {} meeting_obj = self.pool['calendar.event'] res = self.write(cr, uid, ids, {'state': 'accepted'}, context) for attendee in self.browse(cr, uid, ids, context=context): meeting_obj.message_post(cr, uid, attendee.event_id.id, body=_(("%s has accepted invitation") % (attendee.cn)), subtype="calendar.subtype_invitation", context=context) return res def do_decline(self, cr, uid, ids, context=None, *args): """ Marks event invitation as Declined. @param ids: list of calendar attendee's IDs """ if context is None: context = {} meeting_obj = self.pool['calendar.event'] res = self.write(cr, uid, ids, {'state': 'declined'}, context) for attendee in self.browse(cr, uid, ids, context=context): meeting_obj.message_post(cr, uid, attendee.event_id.id, body=_(("%s has declined invitation") % (attendee.cn)), subtype="calendar.subtype_invitation", context=context) return res def create(self, cr, uid, vals, context=None): if context is None: context = {} if not vals.get("email") and vals.get("cn"): cnval = vals.get("cn").split(':') email = filter(lambda x: x.__contains__('@'), cnval) vals['email'] = email and email[0] or '' vals['cn'] = vals.get("cn") res = super(calendar_attendee, self).create(cr, uid, vals, context=context) return res class res_partner(osv.Model): _inherit = 'res.partner' _columns = { 'calendar_last_notif_ack': fields.datetime('Last notification marked as read from base Calendar'), } def get_attendee_detail(self, cr, uid, ids, meeting_id, context=None): """ Return a list of tuple (id, name, status) Used by web_calendar.js : Many2ManyAttendee """ datas = [] meeting = None if meeting_id: meeting = self.pool['calendar.event'].browse(cr, uid, get_real_ids(meeting_id), context=context) for partner in self.browse(cr, uid, ids, context=context): data = self.name_get(cr, uid, [partner.id], context)[0] if meeting: for attendee in meeting.attendee_ids: if attendee.partner_id.id == partner.id: data = (data[0], data[1], attendee.state) datas.append(data) return datas def _set_calendar_last_notif_ack(self, cr, uid, context=None): partner = self.pool['res.users'].browse(cr, uid, uid, context=context).partner_id self.write(cr, uid, partner.id, {'calendar_last_notif_ack': datetime.now()}, context=context) return class calendar_alarm_manager(osv.AbstractModel): _name = 'calendar.alarm_manager' def get_next_potential_limit_alarm(self, cr, uid, seconds, notif=True, mail=True, partner_id=None, context=None): res = {} base_request = """ SELECT cal.id, cal.start - interval '1' minute * calcul_delta.max_delta AS first_alarm, CASE WHEN cal.recurrency THEN cal.final_date - interval '1' minute * calcul_delta.min_delta ELSE cal.stop - interval '1' minute * calcul_delta.min_delta END as last_alarm, cal.start as first_event_date, CASE WHEN cal.recurrency THEN cal.final_date ELSE cal.stop END as last_event_date, calcul_delta.min_delta, calcul_delta.max_delta, cal.rrule AS rule FROM calendar_event AS cal RIGHT JOIN ( SELECT rel.calendar_event_id, max(alarm.duration_minutes) AS max_delta,min(alarm.duration_minutes) AS min_delta FROM calendar_alarm_calendar_event_rel AS rel LEFT JOIN calendar_alarm AS alarm ON alarm.id = rel.calendar_alarm_id WHERE alarm.type in %s GROUP BY rel.calendar_event_id ) AS calcul_delta ON calcul_delta.calendar_event_id = cal.id """ filter_user = """ RIGHT JOIN calendar_event_res_partner_rel AS part_rel ON part_rel.calendar_event_id = cal.id AND part_rel.res_partner_id = %s """ #Add filter on type type_to_read = () if notif: type_to_read += ('notification',) if mail: type_to_read += ('email',) tuple_params = (type_to_read,) # ADD FILTER ON PARTNER_ID if partner_id: base_request += filter_user tuple_params += (partner_id, ) #Add filter on hours tuple_params += (seconds,) cr.execute("""SELECT * FROM ( %s WHERE cal.active = True ) AS ALL_EVENTS WHERE ALL_EVENTS.first_alarm < (now() at time zone 'utc' + interval '%%s' second ) AND ALL_EVENTS.last_event_date > (now() at time zone 'utc') """ % base_request, tuple_params) for event_id, first_alarm, last_alarm, first_meeting, last_meeting, min_duration, max_duration, rule in cr.fetchall(): res[event_id] = { 'event_id': event_id, 'first_alarm': first_alarm, 'last_alarm': last_alarm, 'first_meeting': first_meeting, 'last_meeting': last_meeting, 'min_duration': min_duration, 'max_duration': max_duration, 'rrule': rule } return res def do_check_alarm_for_one_date(self, cr, uid, one_date, event, event_maxdelta, in_the_next_X_seconds, after=False, notif=True, mail=True, missing=False, context=None): # one_date: date of the event to check (not the same that in the event browse if recurrent) # event: Event browse record # event_maxdelta: biggest duration from alarms for this event # in_the_next_X_seconds: looking in the future (in seconds) # after: if not False: will return alert if after this date (date as string - todo: change in master) # missing: if not False: will return alert even if we are too late # notif: Looking for type notification # mail: looking for type email res = [] # TODO: replace notif and email in master by alarm_type + remove event_maxdelta and if using it alarm_type = [] if notif: alarm_type.append('notification') if mail: alarm_type.append('email') if one_date - timedelta(minutes=(missing and 0 or event_maxdelta)) < datetime.now() + timedelta(seconds=in_the_next_X_seconds): # if an alarm is possible for this date for alarm in event.alarm_ids: if alarm.type in alarm_type and \ one_date - timedelta(minutes=(missing and 0 or alarm.duration_minutes)) < datetime.now() + timedelta(seconds=in_the_next_X_seconds) and \ (not after or one_date - timedelta(minutes=alarm.duration_minutes) > openerp.fields.Datetime.from_string(after)): alert = { 'alarm_id': alarm.id, 'event_id': event.id, 'notify_at': one_date - timedelta(minutes=alarm.duration_minutes), } res.append(alert) return res def get_next_mail(self, cr, uid, context=None): now = openerp.fields.Datetime.to_string(datetime.now()) icp = self.pool['ir.config_parameter'] last_notif_mail = icp.get_param(cr, SUPERUSER_ID, 'calendar.last_notif_mail', default=False) or now try: cron = self.pool['ir.model.data'].get_object(cr, uid, 'calendar', 'ir_cron_scheduler_alarm', context=context) except ValueError: _logger.error("Cron for " + self._name + " can not be identified !") return False interval_to_second = { "weeks": 7 * 24 * 60 * 60, "days": 24 * 60 * 60, "hours": 60 * 60, "minutes": 60, "seconds": 1 } if cron.interval_type not in interval_to_second.keys(): _logger.error("Cron delay can not be computed !") return False cron_interval = cron.interval_number * interval_to_second[cron.interval_type] all_events = self.get_next_potential_limit_alarm(cr, uid, cron_interval, notif=False, context=context) for curEvent in self.pool.get('calendar.event').browse(cr, uid, all_events.keys(), context=context): max_delta = all_events[curEvent.id]['max_duration'] if curEvent.recurrency: at_least_one = False last_found = False for one_date in self.pool.get('calendar.event').get_recurrent_date_by_event(cr, uid, curEvent, context=context): in_date_format = one_date.replace(tzinfo=None) last_found = self.do_check_alarm_for_one_date(cr, uid, in_date_format, curEvent, max_delta, 0, after=last_notif_mail, notif=False, missing=True, context=context) for alert in last_found: self.do_mail_reminder(cr, uid, alert, context=context) at_least_one = True # if it's the first alarm for this recurrent event if at_least_one and not last_found: # if the precedent event had an alarm but not this one, we can stop the search for this event break else: in_date_format = datetime.strptime(curEvent.start, DEFAULT_SERVER_DATETIME_FORMAT) last_found = self.do_check_alarm_for_one_date(cr, uid, in_date_format, curEvent, max_delta, 0, after=last_notif_mail, notif=False, missing=True, context=context) for alert in last_found: self.do_mail_reminder(cr, uid, alert, context=context) icp.set_param(cr, SUPERUSER_ID, 'calendar.last_notif_mail', now) def get_next_notif(self, cr, uid, context=None): ajax_check_every_seconds = 300 partner = self.pool['res.users'].read(cr, SUPERUSER_ID, uid, ['partner_id', 'calendar_last_notif_ack'], context=context) all_notif = [] if not partner: return [] all_events = self.get_next_potential_limit_alarm(cr, uid, ajax_check_every_seconds, partner_id=partner['partner_id'][0], mail=False, context=context) for event in all_events: # .values() max_delta = all_events[event]['max_duration'] curEvent = self.pool.get('calendar.event').browse(cr, uid, event, context=context) if curEvent.recurrency: bFound = False LastFound = False for one_date in self.pool.get("calendar.event").get_recurrent_date_by_event(cr, uid, curEvent, context=context): in_date_format = one_date.replace(tzinfo=None) LastFound = self.do_check_alarm_for_one_date(cr, uid, in_date_format, curEvent, max_delta, ajax_check_every_seconds, after=partner['calendar_last_notif_ack'], mail=False, context=context) if LastFound: for alert in LastFound: all_notif.append(self.do_notif_reminder(cr, uid, alert, context=context)) if not bFound: # if it's the first alarm for this recurrent event bFound = True if bFound and not LastFound: # if the precedent event had alarm but not this one, we can stop the search fot this event break else: in_date_format = datetime.strptime(curEvent.start, DEFAULT_SERVER_DATETIME_FORMAT) LastFound = self.do_check_alarm_for_one_date(cr, uid, in_date_format, curEvent, max_delta, ajax_check_every_seconds, after=partner['calendar_last_notif_ack'], mail=False, context=context) if LastFound: for alert in LastFound: all_notif.append(self.do_notif_reminder(cr, uid, alert, context=context)) return all_notif def do_mail_reminder(self, cr, uid, alert, context=None): if context is None: context = {} res = False event = self.pool['calendar.event'].browse(cr, uid, alert['event_id'], context=context) alarm = self.pool['calendar.alarm'].browse(cr, uid, alert['alarm_id'], context=context) if alarm.type == 'email': res = self.pool['calendar.attendee']._send_mail_to_attendees( cr, uid, [att.id for att in event.attendee_ids], email_from=event.user_id.partner_id.email, template_xmlid='calendar_template_meeting_reminder', force=True, context=context ) return res def do_notif_reminder(self, cr, uid, alert, context=None): alarm = self.pool['calendar.alarm'].browse(cr, uid, alert['alarm_id'], context=context) event = self.pool['calendar.event'].browse(cr, uid, alert['event_id'], context=context) if alarm.type == 'notification': message = event.display_time delta = alert['notify_at'] - datetime.now() delta = delta.seconds + delta.days * 3600 * 24 return { 'event_id': event.id, 'title': event.name, 'message': message, 'timer': delta, 'notify_at': alert['notify_at'].strftime(DEFAULT_SERVER_DATETIME_FORMAT), } class calendar_alarm(osv.Model): _name = 'calendar.alarm' _description = 'Event alarm' def _get_duration(self, cr, uid, ids, field_name, arg, context=None): res = {} for alarm in self.browse(cr, uid, ids, context=context): if alarm.interval == "minutes": res[alarm.id] = alarm.duration elif alarm.interval == "hours": res[alarm.id] = alarm.duration * 60 elif alarm.interval == "days": res[alarm.id] = alarm.duration * 60 * 24 else: res[alarm.id] = 0 return res _columns = { 'name': fields.char('Name', required=True), 'type': fields.selection([('notification', 'Notification'), ('email', 'Email')], 'Type', required=True), 'duration': fields.integer('Amount', required=True), 'interval': fields.selection([('minutes', 'Minutes'), ('hours', 'Hours'), ('days', 'Days')], 'Unit', required=True), 'duration_minutes': fields.function(_get_duration, type='integer', string='Duration in minutes', store=True), } _defaults = { 'type': 'notification', 'duration': 1, 'interval': 'hours', } def _update_cron(self, cr, uid, context=None): try: cron = self.pool['ir.model.data'].get_object( cr, SUPERUSER_ID, 'calendar', 'ir_cron_scheduler_alarm', context=context) except ValueError: return False return cron.toggle(model=self._name, domain=[('type', '=', 'email')]) def create(self, cr, uid, values, context=None): res = super(calendar_alarm, self).create(cr, uid, values, context=context) self._update_cron(cr, uid, context=context) return res def write(self, cr, uid, ids, values, context=None): res = super(calendar_alarm, self).write(cr, uid, ids, values, context=context) self._update_cron(cr, uid, context=context) return res def unlink(self, cr, uid, ids, context=None): res = super(calendar_alarm, self).unlink(cr, uid, ids, context=context) self._update_cron(cr, uid, context=context) return res class ir_values(osv.Model): _inherit = 'ir.values' def set(self, cr, uid, key, key2, name, models, value, replace=True, isobject=False, meta=False, preserve_user=False, company=False): new_model = [] for data in models: if type(data) in (list, tuple): new_model.append((data[0], calendar_id2real_id(data[1]))) else: new_model.append(data) return super(ir_values, self).set(cr, uid, key, key2, name, new_model, value, replace, isobject, meta, preserve_user, company) def get(self, cr, uid, key, key2, models, meta=False, context=None, res_id_req=False, without_user=True, key2_req=True): if context is None: context = {} new_model = [] for data in models: if type(data) in (list, tuple): new_model.append((data[0], calendar_id2real_id(data[1]))) else: new_model.append(data) return super(ir_values, self).get(cr, uid, key, key2, new_model, meta, context, res_id_req, without_user, key2_req) class ir_model(osv.Model): _inherit = 'ir.model' def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): new_ids = isinstance(ids, (basestring, int, long)) and [ids] or ids if context is None: context = {} data = super(ir_model, self).read(cr, uid, new_ids, fields=fields, context=context, load=load) if data: for val in data: val['id'] = calendar_id2real_id(val['id']) return isinstance(ids, (basestring, int, long)) and data[0] or data original_exp_report = openerp.service.report.exp_report def exp_report(db, uid, object, ids, datas=None, context=None): """ Export Report """ if object == 'printscreen.list': original_exp_report(db, uid, object, ids, datas, context) new_ids = [] for id in ids: new_ids.append(calendar_id2real_id(id)) if datas.get('id', False): datas['id'] = calendar_id2real_id(datas['id']) return original_exp_report(db, uid, object, new_ids, datas, context) openerp.service.report.exp_report = exp_report class calendar_event_type(osv.Model): _name = 'calendar.event.type' _description = 'Meeting Type' _columns = { 'name': fields.char('Name', required=True, translate=True), } class calendar_event(osv.Model): """ Model for Calendar Event """ _name = 'calendar.event' _description = "Event" _order = "id desc" _inherit = ["mail.thread", "ir.needaction_mixin"] def do_run_scheduler(self, cr, uid, id, context=None): self.pool['calendar.alarm_manager'].get_next_mail(cr, uid, context=context) def get_recurrent_date_by_event(self, cr, uid, event, context=None): """Get recurrent dates based on Rule string and all event where recurrent_id is child """ def todate(date): val = parser.parse(''.join((re.compile('\d')).findall(date))) ## Dates are localized to saved timezone if any, else current timezone. if not val.tzinfo: val = pytz.UTC.localize(val) return val.astimezone(timezone) if context is None: context = {} timezone = pytz.timezone(context.get('tz') or 'UTC') startdate = pytz.UTC.localize(datetime.strptime(event.start, DEFAULT_SERVER_DATETIME_FORMAT)) # Add "+hh:mm" timezone if not startdate: startdate = datetime.now() ## Convert the start date to saved timezone (or context tz) as it'll ## define the correct hour/day asked by the user to repeat for recurrence. startdate = startdate.astimezone(timezone) # transform "+hh:mm" timezone rset1 = rrule.rrulestr(str(event.rrule), dtstart=startdate, forceset=True) ids_depending = self.search(cr, uid, [('recurrent_id', '=', event.id), '|', ('active', '=', False), ('active', '=', True)], context=context) all_events = self.browse(cr, uid, ids_depending, context=context) for ev in all_events: rset1._exdate.append(todate(ev.recurrent_id_date)) return [d.astimezone(pytz.UTC) for d in rset1] def _get_recurrency_end_date(self, cr, uid, id, context=None): data = self.read(cr, uid, id, ['final_date', 'recurrency', 'rrule_type', 'count', 'end_type', 'stop'], context=context) if not data.get('recurrency'): return False end_type = data.get('end_type') final_date = data.get('final_date') if end_type == 'count' and all(data.get(key) for key in ['count', 'rrule_type', 'stop']): count = data['count'] + 1 delay, mult = { 'daily': ('days', 1), 'weekly': ('days', 7), 'monthly': ('months', 1), 'yearly': ('years', 1), }[data['rrule_type']] deadline = datetime.strptime(data['stop'], tools.DEFAULT_SERVER_DATETIME_FORMAT) return deadline + relativedelta(**{delay: count * mult}) return final_date def _find_my_attendee(self, cr, uid, meeting_ids, context=None): """ Return the first attendee where the user connected has been invited from all the meeting_ids in parameters """ user = self.pool['res.users'].browse(cr, uid, uid, context=context) for meeting_id in meeting_ids: for attendee in self.browse(cr, uid, meeting_id, context).attendee_ids: if user.partner_id.id == attendee.partner_id.id: return attendee return False def get_date_formats(self, cr, uid, context): lang = context.get("lang") res_lang = self.pool.get('res.lang') lang_params = {} if lang: ids = res_lang.search(request.cr, uid, [("code", "=", lang)]) if ids: lang_params = res_lang.read(request.cr, uid, ids[0], ["date_format", "time_format"]) # formats will be used for str{f,p}time() which do not support unicode in Python 2, coerce to str format_date = lang_params.get("date_format", '%B-%d-%Y').encode('utf-8') format_time = lang_params.get("time_format", '%I-%M %p').encode('utf-8') return (format_date, format_time) def get_display_time_tz(self, cr, uid, ids, tz=False, context=None): context = dict(context or {}) if tz: context["tz"] = tz ev = self.browse(cr, uid, ids, context=context)[0] return self._get_display_time(cr, uid, ev.start, ev.stop, ev.duration, ev.allday, context=context) def _get_display_time(self, cr, uid, start, stop, zduration, zallday, context=None): """ Return date and time (from to from) based on duration with timezone in string : eg. 1) if user add duration for 2 hours, return : August-23-2013 at (04-30 To 06-30) (Europe/Brussels) 2) if event all day ,return : AllDay, July-31-2013 """ context = dict(context or {}) tz = context.get('tz', False) if not tz: # tz can have a value False, so dont do it in the default value of get ! context['tz'] = self.pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] tz = context['tz'] tz = tools.ustr(tz).encode('utf-8') # make safe for str{p,f}time() format_date, format_time = self.get_date_formats(cr, uid, context=context) date = fields.datetime.context_timestamp(cr, uid, datetime.strptime(start, tools.DEFAULT_SERVER_DATETIME_FORMAT), context=context) date_deadline = fields.datetime.context_timestamp(cr, uid, datetime.strptime(stop, tools.DEFAULT_SERVER_DATETIME_FORMAT), context=context) event_date = date.strftime(format_date) display_time = date.strftime(format_time) if zallday: time = _("AllDay , %s") % (event_date) elif zduration < 24: duration = date + timedelta(hours=zduration) time = ("%s at (%s To %s) (%s)") % (event_date, display_time, duration.strftime(format_time), tz) else: time = ("%s at %s To\n %s at %s (%s)") % (event_date, display_time, date_deadline.strftime(format_date), date_deadline.strftime(format_time), tz) return time def _compute(self, cr, uid, ids, fields, arg, context=None): res = {} if not isinstance(fields, list): fields = [fields] for meeting in self.browse(cr, uid, ids, context=context): meeting_data = {} res[meeting.id] = meeting_data attendee = self._find_my_attendee(cr, uid, [meeting.id], context) for field in fields: if field == 'is_attendee': meeting_data[field] = bool(attendee) elif field == 'attendee_status': meeting_data[field] = attendee.state if attendee else 'needsAction' elif field == 'display_time': meeting_data[field] = self._get_display_time(cr, uid, meeting.start, meeting.stop, meeting.duration, meeting.allday, context=context) elif field == "display_start": meeting_data[field] = meeting.start_date if meeting.allday else meeting.start_datetime elif field == 'start': meeting_data[field] = meeting.start_date if meeting.allday else meeting.start_datetime elif field == 'stop': meeting_data[field] = meeting.stop_date if meeting.allday else meeting.stop_datetime return res def _get_rulestring(self, cr, uid, ids, name, arg, context=None): """ Gets Recurrence rule string according to value type RECUR of iCalendar from the values given. @return: dictionary of rrule value. """ result = {} if not isinstance(ids, list): ids = [ids] #read these fields as SUPERUSER because if the record is private a normal search could raise an error events = self.read(cr, SUPERUSER_ID, ids, ['id', 'byday', 'recurrency', 'final_date', 'rrule_type', 'month_by', 'interval', 'count', 'end_type', 'mo', 'tu', 'we', 'th', 'fr', 'sa', 'su', 'day', 'week_list'], context=context) for event in events: if event['recurrency']: result[event['id']] = self.compute_rule_string(event) else: result[event['id']] = '' return result # retro compatibility function def _rrule_write(self, cr, uid, ids, field_name, field_value, args, context=None): return self._set_rulestring(self, cr, uid, ids, field_name, field_value, args, context=context) def _set_rulestring(self, cr, uid, ids, field_name, field_value, args, context=None): if not isinstance(ids, list): ids = [ids] data = self._get_empty_rrule_data() if field_value: data['recurrency'] = True for event in self.browse(cr, uid, ids, context=context): rdate = event.start update_data = self._parse_rrule(field_value, dict(data), rdate) data.update(update_data) self.write(cr, uid, ids, data, context=context) return True def _set_date(self, cr, uid, values, id=False, context=None): if context is None: context = {} if values.get('start_datetime') or values.get('start_date') or values.get('start') \ or values.get('stop_datetime') or values.get('stop_date') or values.get('stop'): allday = values.get("allday", None) event = self.browse(cr, uid, id, context=context) if allday is None: if id: allday = event.allday else: allday = False _logger.warning("Calendar - All day is not specified, arbitrarily set to False") #raise osv.except_osv(_('Error!'), ("Need to know if it's an allday or not...")) key = "date" if allday else "datetime" notkey = "datetime" if allday else "date" for fld in ('start', 'stop'): if values.get('%s_%s' % (fld, key)) or values.get(fld): values['%s_%s' % (fld, key)] = values.get('%s_%s' % (fld, key)) or values.get(fld) values['%s_%s' % (fld, notkey)] = None if fld not in values.keys(): values[fld] = values['%s_%s' % (fld, key)] diff = False if allday and (values.get('stop_date') or values.get('start_date')): stop_date = values.get('stop_date') or event.stop_date start_date = values.get('start_date') or event.start_date if stop_date and start_date: diff = openerp.fields.Date.from_string(stop_date) - openerp.fields.Date.from_string(start_date) elif values.get('stop_datetime') or values.get('start_datetime'): stop_datetime = values.get('stop_datetime') or event.stop_datetime start_datetime = values.get('start_datetime') or event.start_datetime if stop_datetime and start_datetime: diff = openerp.fields.Datetime.from_string(stop_datetime) - openerp.fields.Datetime.from_string(start_datetime) if diff: duration = float(diff.days) * 24 + (float(diff.seconds) / 3600) values['duration'] = round(duration, 2) _track = { 'location': { 'calendar.subtype_invitation': lambda self, cr, uid, obj, ctx=None: True, }, 'start': { 'calendar.subtype_invitation': lambda self, cr, uid, obj, ctx=None: True, }, } _columns = { 'id': fields.integer('ID', readonly=True), 'state': fields.selection([('draft', 'Unconfirmed'), ('open', 'Confirmed')], string='Status', readonly=True, track_visibility='onchange'), 'name': fields.char('Meeting Subject', required=True, states={'done': [('readonly', True)]}), 'is_attendee': fields.function(_compute, string='Attendee', type="boolean", multi='attendee'), 'attendee_status': fields.function(_compute, string='Attendee Status', type="selection", selection=calendar_attendee.STATE_SELECTION, multi='attendee'), 'display_time': fields.function(_compute, string='Event Time', type="char", multi='attendee'), 'display_start': fields.function(_compute, string='Date', type="char", multi='attendee', store=True), 'allday': fields.boolean('All Day', states={'done': [('readonly', True)]}), 'start': fields.function(_compute, string='Calculated start', type="datetime", multi='attendee', store=True, required=True), 'stop': fields.function(_compute, string='Calculated stop', type="datetime", multi='attendee', store=True, required=True), 'start_date': fields.date('Start Date', states={'done': [('readonly', True)]}, track_visibility='onchange'), 'start_datetime': fields.datetime('Start DateTime', states={'done': [('readonly', True)]}, track_visibility='onchange'), 'stop_date': fields.date('End Date', states={'done': [('readonly', True)]}, track_visibility='onchange'), 'stop_datetime': fields.datetime('End Datetime', states={'done': [('readonly', True)]}, track_visibility='onchange'), # old date_deadline 'duration': fields.float('Duration', states={'done': [('readonly', True)]}), 'description': fields.text('Description', states={'done': [('readonly', True)]}), 'class': fields.selection([('public', 'Public'), ('private', 'Private'), ('confidential', 'Public for Employees')], 'Privacy', states={'done': [('readonly', True)]}), 'location': fields.char('Location', help="Location of Event", track_visibility='onchange', states={'done': [('readonly', True)]}), 'show_as': fields.selection([('free', 'Free'), ('busy', 'Busy')], 'Show Time as', states={'done': [('readonly', True)]}), # RECURRENCE FIELD 'rrule': fields.function(_get_rulestring, type='char', fnct_inv=_set_rulestring, store=True, string='Recurrent Rule'), 'rrule_type': fields.selection([('daily', 'Day(s)'), ('weekly', 'Week(s)'), ('monthly', 'Month(s)'), ('yearly', 'Year(s)')], 'Recurrency', states={'done': [('readonly', True)]}, help="Let the event automatically repeat at that interval"), 'recurrency': fields.boolean('Recurrent', help="Recurrent Meeting"), 'recurrent_id': fields.integer('Recurrent ID'), 'recurrent_id_date': fields.datetime('Recurrent ID date'), 'end_type': fields.selection([('count', 'Number of repetitions'), ('end_date', 'End date')], 'Recurrence Termination'), 'interval': fields.integer('Repeat Every', help="Repeat every (Days/Week/Month/Year)"), 'count': fields.integer('Repeat', help="Repeat x times"), 'mo': fields.boolean('Mon'), 'tu': fields.boolean('Tue'), 'we': fields.boolean('Wed'), 'th': fields.boolean('Thu'), 'fr': fields.boolean('Fri'), 'sa': fields.boolean('Sat'), 'su': fields.boolean('Sun'), 'month_by': fields.selection([('date', 'Date of month'), ('day', 'Day of month')], 'Option', oldname='select1'), 'day': fields.integer('Date of month'), 'week_list': fields.selection([('MO', 'Monday'), ('TU', 'Tuesday'), ('WE', 'Wednesday'), ('TH', 'Thursday'), ('FR', 'Friday'), ('SA', 'Saturday'), ('SU', 'Sunday')], 'Weekday'), 'byday': fields.selection([('1', 'First'), ('2', 'Second'), ('3', 'Third'), ('4', 'Fourth'), ('5', 'Fifth'), ('-1', 'Last')], 'By day'), 'final_date': fields.date('Repeat Until'), # The last event of a recurrence 'user_id': fields.many2one('res.users', 'Responsible', states={'done': [('readonly', True)]}), 'color_partner_id': fields.related('user_id', 'partner_id', 'id', type="integer", string="colorize", store=False), # Color of creator 'active': fields.boolean('Active', help="If the active field is set to false, it will allow you to hide the event alarm information without removing it."), 'categ_ids': fields.many2many('calendar.event.type', 'meeting_category_rel', 'event_id', 'type_id', 'Tags'), 'attendee_ids': fields.one2many('calendar.attendee', 'event_id', 'Attendees', ondelete='cascade'), 'partner_ids': fields.many2many('res.partner', 'calendar_event_res_partner_rel', string='Attendees', states={'done': [('readonly', True)]}), 'alarm_ids': fields.many2many('calendar.alarm', 'calendar_alarm_calendar_event_rel', string='Reminders', ondelete="restrict", copy=False), } def _get_default_partners(self, cr, uid, ctx=None): ret = [self.pool['res.users'].browse(cr, uid, uid, context=ctx).partner_id.id] active_id = ctx.get('active_id') if ctx.get('active_model') == 'res.partner' and active_id: if active_id not in ret: ret.append(active_id) return ret _defaults = { 'end_type': 'count', 'count': 1, 'rrule_type': False, 'allday': False, 'state': 'draft', 'class': 'public', 'show_as': 'busy', 'month_by': 'date', 'interval': 1, 'active': 1, 'user_id': lambda self, cr, uid, ctx: uid, 'partner_ids': _get_default_partners, } def _check_closing_date(self, cr, uid, ids, context=None): for event in self.browse(cr, uid, ids, context=context): if event.start_datetime and event.stop_datetime < event.start_datetime: return False if event.start_date and event.stop_date < event.start_date: return False return True _constraints = [ (_check_closing_date, 'Error ! End date cannot be set before start date.', ['start_datetime', 'stop_datetime', 'start_date', 'stop_date']) ] def onchange_allday(self, cr, uid, ids, start=False, end=False, starttime=False, endtime=False, startdatetime=False, enddatetime=False, checkallday=False, context=None): value = {} if not ((starttime and endtime) or (start and end)): # At first intialize, we have not datetime return value if checkallday: # from datetime to date startdatetime = startdatetime or start if startdatetime: start = datetime.strptime(startdatetime, DEFAULT_SERVER_DATETIME_FORMAT) value['start_date'] = datetime.strftime(start, DEFAULT_SERVER_DATE_FORMAT) enddatetime = enddatetime or end if enddatetime: end = datetime.strptime(enddatetime, DEFAULT_SERVER_DATETIME_FORMAT) value['stop_date'] = datetime.strftime(end, DEFAULT_SERVER_DATE_FORMAT) else: # from date to datetime user = self.pool['res.users'].browse(cr, uid, uid, context) tz = pytz.timezone(user.tz) if user.tz else pytz.utc if starttime: start = openerp.fields.Datetime.from_string(starttime) startdate = tz.localize(start) # Add "+hh:mm" timezone startdate = startdate.replace(hour=8) # Set 8 AM in localtime startdate = startdate.astimezone(pytz.utc) # Convert to UTC value['start_datetime'] = datetime.strftime(startdate, DEFAULT_SERVER_DATETIME_FORMAT) elif start: value['start_datetime'] = start if endtime: end = datetime.strptime(endtime.split(' ')[0], DEFAULT_SERVER_DATE_FORMAT) enddate = tz.localize(end).replace(hour=18).astimezone(pytz.utc) value['stop_datetime'] = datetime.strftime(enddate, DEFAULT_SERVER_DATETIME_FORMAT) elif end: value['stop_datetime'] = end return {'value': value} def onchange_dates(self, cr, uid, ids, fromtype, start=False, end=False, checkallday=False, allday=False, context=None): """Returns duration and end date based on values passed @param ids: List of calendar event's IDs. """ value = {} if checkallday != allday: return value value['allday'] = checkallday # Force to be rewrited if allday: if fromtype == 'start' and start: start = datetime.strptime(start, DEFAULT_SERVER_DATE_FORMAT) value['start_datetime'] = datetime.strftime(start, DEFAULT_SERVER_DATETIME_FORMAT) value['start'] = datetime.strftime(start, DEFAULT_SERVER_DATETIME_FORMAT) if fromtype == 'stop' and end: end = datetime.strptime(end, DEFAULT_SERVER_DATE_FORMAT) value['stop_datetime'] = datetime.strftime(end, DEFAULT_SERVER_DATETIME_FORMAT) value['stop'] = datetime.strftime(end, DEFAULT_SERVER_DATETIME_FORMAT) else: if fromtype == 'start' and start: start = datetime.strptime(start, DEFAULT_SERVER_DATETIME_FORMAT) value['start_date'] = datetime.strftime(start, DEFAULT_SERVER_DATE_FORMAT) value['start'] = datetime.strftime(start, DEFAULT_SERVER_DATETIME_FORMAT) if fromtype == 'stop' and end: end = datetime.strptime(end, DEFAULT_SERVER_DATETIME_FORMAT) value['stop_date'] = datetime.strftime(end, DEFAULT_SERVER_DATE_FORMAT) value['stop'] = datetime.strftime(end, DEFAULT_SERVER_DATETIME_FORMAT) return {'value': value} def new_invitation_token(self, cr, uid, record, partner_id): return uuid.uuid4().hex def create_attendees(self, cr, uid, ids, context=None): if context is None: context = {} user_obj = self.pool['res.users'] current_user = user_obj.browse(cr, uid, uid, context=context) res = {} for event in self.browse(cr, uid, ids, context): attendees = {} for att in event.attendee_ids: attendees[att.partner_id.id] = True new_attendees = [] new_att_partner_ids = [] for partner in event.partner_ids: if partner.id in attendees: continue access_token = self.new_invitation_token(cr, uid, event, partner.id) values = { 'partner_id': partner.id, 'event_id': event.id, 'access_token': access_token, 'email': partner.email, } if partner.id == current_user.partner_id.id: values['state'] = 'accepted' att_id = self.pool['calendar.attendee'].create(cr, uid, values, context=context) new_attendees.append(att_id) new_att_partner_ids.append(partner.id) if not current_user.email or current_user.email != partner.email: mail_from = current_user.email or tools.config.get('email_from', False) if not context.get('no_email'): if self.pool['calendar.attendee']._send_mail_to_attendees(cr, uid, att_id, email_from=mail_from, context=context): self.message_post(cr, uid, event.id, body=_("An invitation email has been sent to attendee %s") % (partner.name,), subtype="calendar.subtype_invitation", context=context) if new_attendees: self.write(cr, uid, [event.id], {'attendee_ids': [(4, att) for att in new_attendees]}, context=context) if new_att_partner_ids: self.message_subscribe(cr, uid, [event.id], new_att_partner_ids, context=context) # We remove old attendees who are not in partner_ids now. all_partner_ids = [part.id for part in event.partner_ids] all_part_attendee_ids = [att.partner_id.id for att in event.attendee_ids] all_attendee_ids = [att.id for att in event.attendee_ids] partner_ids_to_remove = map(lambda x: x, set(all_part_attendee_ids + new_att_partner_ids) - set(all_partner_ids)) attendee_ids_to_remove = [] if partner_ids_to_remove: attendee_ids_to_remove = self.pool["calendar.attendee"].search(cr, uid, [('partner_id.id', 'in', partner_ids_to_remove), ('event_id.id', '=', event.id)], context=context) if attendee_ids_to_remove: self.pool['calendar.attendee'].unlink(cr, uid, attendee_ids_to_remove, context) res[event.id] = { 'new_attendee_ids': new_attendees, 'old_attendee_ids': all_attendee_ids, 'removed_attendee_ids': attendee_ids_to_remove } return res def get_search_fields(self, browse_event, order_fields, r_date=None): sort_fields = {} for ord in order_fields: if ord == 'id' and r_date: sort_fields[ord] = '%s-%s' % (browse_event[ord], r_date.strftime("%Y%m%d%H%M%S")) else: sort_fields[ord] = browse_event[ord] if type(browse_event[ord]) is openerp.osv.orm.browse_record: name_get = browse_event[ord].name_get() if len(name_get) and len(name_get[0]) >= 2: sort_fields[ord] = name_get[0][1] if r_date: sort_fields['sort_start'] = r_date.strftime("%Y%m%d%H%M%S") else: sort_fields['sort_start'] = browse_event['display_start'].replace(' ', '').replace('-', '') return sort_fields def get_recurrent_ids(self, cr, uid, event_id, domain, order=None, context=None): """Gives virtual event ids for recurring events This method gives ids of dates that comes between start date and end date of calendar views @param order: The fields (comma separated, format "FIELD {DESC|ASC}") on which the events should be sorted """ if not context: context = {} if isinstance(event_id, (basestring, int, long)): ids_to_browse = [event_id] # keep select for return else: ids_to_browse = event_id if order: order_fields = [field.split()[0] for field in order.split(',')] else: # fallback on self._order defined on the model order_fields = [field.split()[0] for field in self._order.split(',')] if 'id' not in order_fields: order_fields.append('id') result_data = [] result = [] for ev in self.browse(cr, uid, ids_to_browse, context=context): if not ev.recurrency or not ev.rrule: result.append(ev.id) result_data.append(self.get_search_fields(ev, order_fields)) continue rdates = self.get_recurrent_date_by_event(cr, uid, ev, context=context) for r_date in rdates: # fix domain evaluation # step 1: check date and replace expression by True or False, replace other expressions by True # step 2: evaluation of & and | # check if there are one False pile = [] ok = True for arg in domain: if str(arg[0]) in ('start', 'stop', 'final_date'): if (arg[1] == '='): ok = r_date.strftime('%Y-%m-%d') == arg[2] if (arg[1] == '>'): ok = r_date.strftime('%Y-%m-%d') > arg[2] if (arg[1] == '<'): ok = r_date.strftime('%Y-%m-%d') < arg[2] if (arg[1] == '>='): ok = r_date.strftime('%Y-%m-%d') >= arg[2] if (arg[1] == '<='): ok = r_date.strftime('%Y-%m-%d') <= arg[2] pile.append(ok) elif str(arg) == str('&') or str(arg) == str('|'): pile.append(arg) else: pile.append(True) pile.reverse() new_pile = [] for item in pile: if not isinstance(item, basestring): res = item elif str(item) == str('&'): first = new_pile.pop() second = new_pile.pop() res = first and second elif str(item) == str('|'): first = new_pile.pop() second = new_pile.pop() res = first or second new_pile.append(res) if [True for item in new_pile if not item]: continue result_data.append(self.get_search_fields(ev, order_fields, r_date=r_date)) if order_fields: uniq = lambda it: collections.OrderedDict((id(x), x) for x in it).values() def comparer(left, right): for fn, mult in comparers: result = cmp(fn(left), fn(right)) if result: return mult * result return 0 sort_params = [key.split()[0] if key[-4:].lower() != 'desc' else '-%s' % key.split()[0] for key in (order or self._order).split(',')] sort_params = uniq([comp if comp not in ['start', 'start_date', 'start_datetime'] else 'sort_start' for comp in sort_params]) sort_params = uniq([comp if comp not in ['-start', '-start_date', '-start_datetime'] else '-sort_start' for comp in sort_params]) comparers = [((itemgetter(col[1:]), -1) if col[0] == '-' else (itemgetter(col), 1)) for col in sort_params] ids = [r['id'] for r in sorted(result_data, cmp=comparer)] if isinstance(event_id, (basestring, int, long)): return ids and ids[0] or False else: return ids def compute_rule_string(self, data): """ Compute rule string according to value type RECUR of iCalendar from the values given. @param self: the object pointer @param data: dictionary of freq and interval value @return: string containing recurring rule (empty if no rule) """ if data['interval'] and data['interval'] < 0: raise osv.except_osv(_('warning!'), _('interval cannot be negative.')) if data['count'] and data['count'] <= 0: raise osv.except_osv(_('warning!'), _('count cannot be negative or 0.')) def get_week_string(freq, data): weekdays = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su'] if freq == 'weekly': byday = map(lambda x: x.upper(), filter(lambda x: data.get(x) and x in weekdays, data)) if byday: return ';BYDAY=' + ','.join(byday) return '' def get_month_string(freq, data): if freq == 'monthly': if data.get('month_by') == 'date' and (data.get('day') < 1 or data.get('day') > 31): raise osv.except_osv(_('Error!'), ("Please select a proper day of the month.")) if data.get('month_by') == 'day': # Eg : Second Monday of the month return ';BYDAY=' + data.get('byday') + data.get('week_list') elif data.get('month_by') == 'date': # Eg : 16th of the month return ';BYMONTHDAY=' + str(data.get('day')) return '' def get_end_date(data): if data.get('final_date'): data['end_date_new'] = ''.join((re.compile('\d')).findall(data.get('final_date'))) + 'T235959Z' return (data.get('end_type') == 'count' and (';COUNT=' + str(data.get('count'))) or '') +\ ((data.get('end_date_new') and data.get('end_type') == 'end_date' and (';UNTIL=' + data.get('end_date_new'))) or '') freq = data.get('rrule_type', False) # day/week/month/year res = '' if freq: interval_srting = data.get('interval') and (';INTERVAL=' + str(data.get('interval'))) or '' res = 'FREQ=' + freq.upper() + get_week_string(freq, data) + interval_srting + get_end_date(data) + get_month_string(freq, data) return res def _get_empty_rrule_data(self): return { 'byday': False, 'recurrency': False, 'final_date': False, 'rrule_type': False, 'month_by': False, 'interval': 0, 'count': False, 'end_type': False, 'mo': False, 'tu': False, 'we': False, 'th': False, 'fr': False, 'sa': False, 'su': False, 'day': False, 'week_list': False } def _parse_rrule(self, rule, data, date_start): day_list = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su'] rrule_type = ['yearly', 'monthly', 'weekly', 'daily'] r = rrule.rrulestr(rule, dtstart=datetime.strptime(date_start, DEFAULT_SERVER_DATETIME_FORMAT)) if r._freq > 0 and r._freq < 4: data['rrule_type'] = rrule_type[r._freq] data['count'] = r._count data['interval'] = r._interval data['final_date'] = r._until and r._until.strftime(DEFAULT_SERVER_DATETIME_FORMAT) #repeat weekly if r._byweekday: for i in xrange(0, 7): if i in r._byweekday: data[day_list[i]] = True data['rrule_type'] = 'weekly' #repeat monthly by nweekday ((weekday, weeknumber), ) if r._bynweekday: data['week_list'] = day_list[r._bynweekday[0][0]].upper() data['byday'] = str(r._bynweekday[0][1]) data['month_by'] = 'day' data['rrule_type'] = 'monthly' if r._bymonthday: data['day'] = r._bymonthday[0] data['month_by'] = 'date' data['rrule_type'] = 'monthly' #repeat yearly but for openerp it's monthly, take same information as monthly but interval is 12 times if r._bymonth: data['interval'] = data['interval'] * 12 #FIXEME handle forever case #end of recurrence #in case of repeat for ever that we do not support right now if not (data.get('count') or data.get('final_date')): data['count'] = 100 if data.get('count'): data['end_type'] = 'count' else: data['end_type'] = 'end_date' return data def message_get_subscription_data(self, cr, uid, ids, user_pid=None, context=None): res = {} for virtual_id in ids: real_id = calendar_id2real_id(virtual_id) result = super(calendar_event, self).message_get_subscription_data(cr, uid, [real_id], user_pid=None, context=context) res[virtual_id] = result[real_id] return res def onchange_partner_ids(self, cr, uid, ids, value, context=None): """ The basic purpose of this method is to check that destination partners effectively have email addresses. Otherwise a warning is thrown. :param value: value format: [[6, 0, [3, 4]]] """ res = {'value': {}} if not value or not value[0] or not value[0][0] == 6: return res.update(self.check_partners_email(cr, uid, value[0][2], context=context)) return res def check_partners_email(self, cr, uid, partner_ids, context=None): """ Verify that selected partner_ids have an email_address defined. Otherwise throw a warning. """ partner_wo_email_lst = [] for partner in self.pool['res.partner'].browse(cr, uid, partner_ids, context=context): if not partner.email: partner_wo_email_lst.append(partner) if not partner_wo_email_lst: return {} warning_msg = _('The following contacts have no email address :') for partner in partner_wo_email_lst: warning_msg += '\n- %s' % (partner.name) return {'warning': { 'title': _('Email addresses not found'), 'message': warning_msg, }} # shows events of the day for this user def _needaction_domain_get(self, cr, uid, context=None): return [ ('stop', '<=', time.strftime(DEFAULT_SERVER_DATE_FORMAT + ' 23:59:59')), ('start', '>=', time.strftime(DEFAULT_SERVER_DATE_FORMAT + ' 00:00:00')), ('user_id', '=', uid), ] @api.cr_uid_ids_context def message_post(self, cr, uid, thread_id, body='', subject=None, type='notification', subtype=None, parent_id=False, attachments=None, context=None, **kwargs): if isinstance(thread_id, basestring): thread_id = get_real_ids(thread_id) if context.get('default_date'): del context['default_date'] return super(calendar_event, self).message_post(cr, uid, thread_id, body=body, subject=subject, type=type, subtype=subtype, parent_id=parent_id, attachments=attachments, context=context, **kwargs) def message_subscribe(self, cr, uid, ids, partner_ids, subtype_ids=None, context=None): return super(calendar_event, self).message_subscribe(cr, uid, get_real_ids(ids), partner_ids, subtype_ids=subtype_ids, context=context) def message_unsubscribe(self, cr, uid, ids, partner_ids, context=None): return super(calendar_event, self).message_unsubscribe(cr, uid, get_real_ids(ids), partner_ids, context=context) def do_sendmail(self, cr, uid, ids, context=None): for event in self.browse(cr, uid, ids, context): current_user = self.pool['res.users'].browse(cr, uid, uid, context=context) if current_user.email: if self.pool['calendar.attendee']._send_mail_to_attendees(cr, uid, [att.id for att in event.attendee_ids], email_from=current_user.email, context=context): self.message_post(cr, uid, event.id, body=_("An invitation email has been sent to attendee(s)"), subtype="calendar.subtype_invitation", context=context) return def get_attendee(self, cr, uid, meeting_id, context=None): # Used for view in controller invitation = {'meeting': {}, 'attendee': []} meeting = self.browse(cr, uid, int(meeting_id), context=context) invitation['meeting'] = { 'event': meeting.name, 'where': meeting.location, 'when': meeting.display_time } for attendee in meeting.attendee_ids: invitation['attendee'].append({'name': attendee.cn, 'status': attendee.state}) return invitation def get_interval(self, cr, uid, ids, date, interval, tz=None, context=None): ''' Format and localize some dates to be used in email templates :param string date: date/time to be formatted :param string interval: Among 'day', 'month', 'dayname' and 'time' indicating the desired formatting :param string tz: Timezone indicator (optional) :return unicode: Formatted date or time (as unicode string, to prevent jinja2 crash) (Function used only in calendar_event_data.xml) ''' date = openerp.fields.Datetime.from_string(date) if tz: timezone = pytz.timezone(tz or 'UTC') date = date.replace(tzinfo=pytz.timezone('UTC')).astimezone(timezone) if interval == 'day': # Day number (1-31) res = unicode(date.day) elif interval == 'month': # Localized month name and year res = babel.dates.format_date(date=date, format='MMMM y', locale=context.get('lang', 'en_US')) elif interval == 'dayname': # Localized day name res = babel.dates.format_date(date=date, format='EEEE', locale=context.get('lang', 'en_US')) elif interval == 'time': # Localized time dummy, format_time = self.get_date_formats(cr, uid, context=context) res = tools.ustr(date.strftime(format_time + " %Z")) return res def search(self, cr, uid, args, offset=0, limit=0, order=None, context=None, count=False): if context is None: context = {} if context.get('mymeetings', False): partner_id = self.pool['res.users'].browse(cr, uid, uid, context).partner_id.id args += [('partner_ids', 'in', [partner_id])] new_args = [] for arg in args: new_arg = arg if arg[0] in ('start_date', 'start_datetime', 'start',) and arg[1] == ">=": if context.get('virtual_id', True): new_args += ['|', '&', ('recurrency', '=', 1), ('final_date', arg[1], arg[2])] elif arg[0] == "id": new_id = get_real_ids(arg[2]) new_arg = (arg[0], arg[1], new_id) new_args.append(new_arg) if not context.get('virtual_id', True): return super(calendar_event, self).search(cr, uid, new_args, offset=offset, limit=limit, order=order, count=count, context=context) # offset, limit, order and count must be treated separately as we may need to deal with virtual ids res = super(calendar_event, self).search(cr, uid, new_args, offset=0, limit=0, order=None, context=context, count=False) res = self.get_recurrent_ids(cr, uid, res, args, order=order, context=context) if count: return len(res) elif limit: return res[offset: offset + limit] return res def copy(self, cr, uid, id, default=None, context=None): default = default or {} self._set_date(cr, uid, default, id=default.get('id'), context=context) return super(calendar_event, self).copy(cr, uid, calendar_id2real_id(id), default, context) def _detach_one_event(self, cr, uid, id, values=dict(), context=None): real_event_id = calendar_id2real_id(id) data = self.read(cr, uid, id, ['allday', 'start', 'stop', 'rrule', 'duration']) data['start_date' if data['allday'] else 'start_datetime'] = data['start'] data['stop_date' if data['allday'] else 'stop_datetime'] = data['stop'] if data.get('rrule'): data.update( values, recurrent_id=real_event_id, recurrent_id_date=data.get('start'), rrule_type=False, rrule='', recurrency=False, final_date=datetime.strptime(data.get('start'), DEFAULT_SERVER_DATETIME_FORMAT if data['allday'] else DEFAULT_SERVER_DATETIME_FORMAT) + timedelta(hours=values.get('duration', False) or data.get('duration')) ) #do not copy the id if data.get('id'): del(data['id']) new_id = self.copy(cr, uid, real_event_id, default=data, context=context) return new_id def open_after_detach_event(self, cr, uid, ids, context=None): if context is None: context = {} new_id = self._detach_one_event(cr, uid, ids[0], context=context) return { 'type': 'ir.actions.act_window', 'res_model': 'calendar.event', 'view_mode': 'form', 'res_id': new_id, 'target': 'current', 'flags': {'form': {'action_buttons': True, 'options': {'mode': 'edit'}}} } def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None): for arg in args: if arg[0] == 'id': for n, calendar_id in enumerate(arg[2]): if isinstance(calendar_id, basestring): arg[2][n] = calendar_id.split('-')[0] return super(calendar_event, self)._name_search(cr, user, name=name, args=args, operator=operator, context=context, limit=limit, name_get_uid=name_get_uid) def write(self, cr, uid, ids, values, context=None): def _only_changes_to_apply_on_real_ids(field_names): ''' return True if changes are only to be made on the real ids''' for field in field_names: if field in ['start', 'start_date', 'start_datetime', 'stop', 'stop_date', 'stop_datetime', 'active']: return True return False if not isinstance(ids, (tuple, list)): ids = [ids] context = context or {} self._set_date(cr, uid, values, id=ids[0], context=context) for one_ids in ids: if isinstance(one_ids, (basestring, int, long)): if len(str(one_ids).split('-')) == 1: ids = [int(one_ids)] else: ids = [one_ids] res = False new_id = False # Special write of complex IDS for event_id in list(ids): if len(str(event_id).split('-')) == 1: continue ids.remove(event_id) real_event_id = calendar_id2real_id(event_id) # if we are setting the recurrency flag to False or if we are only changing fields that # should be only updated on the real ID and not on the virtual (like message_follower_ids): # then set real ids to be updated. if not values.get('recurrency', True) or not _only_changes_to_apply_on_real_ids(values.keys()): ids.append(real_event_id) continue else: data = self.read(cr, uid, event_id, ['start', 'stop', 'rrule', 'duration']) if data.get('rrule'): new_id = self._detach_one_event(cr, uid, event_id, values, context=None) res = super(calendar_event, self).write(cr, uid, [int(event_id) for event_id in ids], values, context=context) # set end_date for calendar searching if values.get('recurrency', True) and values.get('end_type', 'count') in ('count', unicode('count')) and \ (values.get('rrule_type') or values.get('count') or values.get('start') or values.get('stop')): for id in ids: final_date = self._get_recurrency_end_date(cr, uid, id, context=context) super(calendar_event, self).write(cr, uid, [id], {'final_date': final_date}, context=context) attendees_create = False if values.get('partner_ids', False): attendees_create = self.create_attendees(cr, uid, ids, context) if (values.get('start_date') or values.get('start_datetime', False)) and values.get('active', True): the_id = new_id or (ids and int(ids[0])) if the_id: if attendees_create: attendees_create = attendees_create[the_id] mail_to_ids = list(set(attendees_create['old_attendee_ids']) - set(attendees_create['removed_attendee_ids'])) else: mail_to_ids = [att.id for att in self.browse(cr, uid, the_id, context=context).attendee_ids] if mail_to_ids: current_user = self.pool['res.users'].browse(cr, uid, uid, context=context) if self.pool['calendar.attendee']._send_mail_to_attendees(cr, uid, mail_to_ids, template_xmlid='calendar_template_meeting_changedate', email_from=current_user.email, context=context): self.message_post(cr, uid, the_id, body=_("A email has been send to specify that the date has been changed !"), subtype="calendar.subtype_invitation", context=context) return res or True and False def create(self, cr, uid, vals, context=None): if context is None: context = {} self._set_date(cr, uid, vals, id=False, context=context) if not 'user_id' in vals: # Else bug with quick_create when we are filter on an other user vals['user_id'] = uid res = super(calendar_event, self).create(cr, uid, vals, context=context) final_date = self._get_recurrency_end_date(cr, uid, res, context=context) self.write(cr, uid, [res], {'final_date': final_date}, context=context) self.create_attendees(cr, uid, [res], context=context) return res def export_data(self, cr, uid, ids, *args, **kwargs): """ Override to convert virtual ids to ids """ real_ids = [] for real_id in get_real_ids(ids): if real_id not in real_ids: real_ids.append(real_id) return super(calendar_event, self).export_data(cr, uid, real_ids, *args, **kwargs) def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False, lazy=True): context = dict(context or {}) if 'date' in groupby: raise osv.except_osv(_('Warning!'), _('Group by date is not supported, use the calendar view instead.')) virtual_id = context.get('virtual_id', True) context.update({'virtual_id': False}) res = super(calendar_event, self).read_group(cr, uid, domain, fields, groupby, offset=offset, limit=limit, context=context, orderby=orderby, lazy=lazy) return res def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): if context is None: context = {} fields2 = fields and fields[:] or None EXTRAFIELDS = ('class', 'user_id', 'duration', 'allday', 'start', 'start_date', 'start_datetime', 'rrule') for f in EXTRAFIELDS: if fields and (f not in fields): fields2.append(f) if isinstance(ids, (basestring, int, long)): select = [ids] else: select = ids select = map(lambda x: (x, calendar_id2real_id(x)), select) result = [] real_data = super(calendar_event, self).read(cr, uid, [real_id for calendar_id, real_id in select], fields=fields2, context=context, load=load) real_data = dict(zip([x['id'] for x in real_data], real_data)) for calendar_id, real_id in select: res = real_data[real_id].copy() ls = calendar_id2real_id(calendar_id, with_date=res and res.get('duration', 0) > 0 and res.get('duration') or 1) if not isinstance(ls, (basestring, int, long)) and len(ls) >= 2: res['start'] = ls[1] res['stop'] = ls[2] if res['allday']: res['start_date'] = ls[1] res['stop_date'] = ls[2] else: res['start_datetime'] = ls[1] res['stop_datetime'] = ls[2] if 'display_time' in fields: res['display_time'] = self._get_display_time(cr, uid, ls[1], ls[2], res['duration'], res['allday'], context=context) res['id'] = calendar_id result.append(res) for r in result: if r['user_id']: user_id = type(r['user_id']) in (tuple, list) and r['user_id'][0] or r['user_id'] if user_id == uid: continue if r['class'] == 'private': for f in r.keys(): if f not in ('id', 'allday', 'start', 'stop', 'duration', 'user_id', 'state', 'interval', 'count', 'recurrent_id_date', 'rrule'): if isinstance(r[f], list): r[f] = [] else: r[f] = False if f == 'name': r[f] = _('Busy') for r in result: for k in EXTRAFIELDS: if (k in r) and (fields and (k not in fields)): del r[k] if isinstance(ids, (basestring, int, long)): return result and result[0] or False return result def unlink(self, cr, uid, ids, can_be_deleted=True, context=None): if not isinstance(ids, list): ids = [ids] res = False ids_to_exclure = [] ids_to_unlink = [] for event_id in ids: if can_be_deleted and len(str(event_id).split('-')) == 1: # if ID REAL if self.browse(cr, uid, int(event_id), context).recurrent_id: ids_to_exclure.append(event_id) else: ids_to_unlink.append(int(event_id)) else: ids_to_exclure.append(event_id) if ids_to_unlink: res = super(calendar_event, self).unlink(cr, uid, ids_to_unlink, context=context) if ids_to_exclure: for id_to_exclure in ids_to_exclure: res = self.write(cr, uid, id_to_exclure, {'active': False}, context=context) return res class mail_message(osv.Model): _inherit = "mail.message" def search(self, cr, uid, args, offset=0, limit=0, order=None, context=None, count=False): ''' convert the search on real ids in the case it was asked on virtual ids, then call super() ''' for index in range(len(args)): if args[index][0] == "res_id" and isinstance(args[index][2], basestring): args[index][2] = get_real_ids(args[index][2]) return super(mail_message, self).search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count) def _find_allowed_model_wise(self, cr, uid, doc_model, doc_dict, context=None): if context is None: context = {} if doc_model == 'calendar.event': order = context.get('order', self._order) for virtual_id in self.pool[doc_model].get_recurrent_ids(cr, uid, doc_dict.keys(), [], order=order, context=context): doc_dict.setdefault(virtual_id, doc_dict[get_real_ids(virtual_id)]) return super(mail_message, self)._find_allowed_model_wise(cr, uid, doc_model, doc_dict, context=context) class ir_attachment(osv.Model): _inherit = "ir.attachment" def search(self, cr, uid, args, offset=0, limit=0, order=None, context=None, count=False): ''' convert the search on real ids in the case it was asked on virtual ids, then call super() ''' for index in range(len(args)): if args[index][0] == "res_id" and isinstance(args[index][2], basestring): args[index][2] = get_real_ids(args[index][2]) return super(ir_attachment, self).search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count) def write(self, cr, uid, ids, vals, context=None): ''' when posting an attachment (new or not), convert the virtual ids in real ids. ''' if isinstance(vals.get('res_id'), basestring): vals['res_id'] = get_real_ids(vals.get('res_id')) return super(ir_attachment, self).write(cr, uid, ids, vals, context=context) class ir_http(osv.AbstractModel): _inherit = 'ir.http' def _auth_method_calendar(self): token = request.params['token'] db = request.params['db'] registry = openerp.modules.registry.RegistryManager.get(db) attendee_pool = registry.get('calendar.attendee') error_message = False with registry.cursor() as cr: attendee_id = attendee_pool.search(cr, openerp.SUPERUSER_ID, [('access_token', '=', token)]) if not attendee_id: error_message = """Invalid Invitation Token.""" elif request.session.uid and request.session.login != 'anonymous': # if valid session but user is not match attendee = attendee_pool.browse(cr, openerp.SUPERUSER_ID, attendee_id[0]) user = registry.get('res.users').browse(cr, openerp.SUPERUSER_ID, request.session.uid) if attendee.partner_id.id != user.partner_id.id: error_message = """Invitation cannot be forwarded via email. This event/meeting belongs to %s and you are logged in as %s. Please ask organizer to add you.""" % (attendee.email, user.email) if error_message: raise BadRequest(error_message) return True class invite_wizard(osv.osv_memory): _inherit = 'mail.wizard.invite' def default_get(self, cr, uid, fields, context=None): ''' in case someone clicked on 'invite others' wizard in the followers widget, transform virtual ids in real ids ''' if 'default_res_id' in context: context = dict(context, default_res_id=get_real_ids(context['default_res_id'])) result = super(invite_wizard, self).default_get(cr, uid, fields, context=context) if 'res_id' in result: result['res_id'] = get_real_ids(result['res_id']) return result
agpl-3.0
7,130,926,470,672,528,000
45.901248
246
0.56434
false
mancoast/CPythonPyc_test
fail/320_test_profile.py
91
7006
"""Test suite for the profile module.""" import sys import pstats import unittest from difflib import unified_diff from io import StringIO from test.support import run_unittest import profile from test.profilee import testfunc, timer class ProfileTest(unittest.TestCase): profilerclass = profile.Profile methodnames = ['print_stats', 'print_callers', 'print_callees'] expected_max_output = ':0(max)' def get_expected_output(self): return _ProfileOutput @classmethod def do_profiling(cls): results = [] prof = cls.profilerclass(timer, 0.001) start_timer = timer() prof.runctx("testfunc()", globals(), locals()) results.append(timer() - start_timer) for methodname in cls.methodnames: s = StringIO() stats = pstats.Stats(prof, stream=s) stats.strip_dirs().sort_stats("stdname") getattr(stats, methodname)() output = s.getvalue().splitlines() mod_name = testfunc.__module__.rsplit('.', 1)[1] # Only compare against stats originating from the test file. # Prevents outside code (e.g., the io module) from causing # unexpected output. output = [line.rstrip() for line in output if mod_name in line] results.append('\n'.join(output)) return results def test_cprofile(self): results = self.do_profiling() expected = self.get_expected_output() self.assertEqual(results[0], 1000) for i, method in enumerate(self.methodnames): if results[i+1] != expected[method]: print("Stats.%s output for %s doesn't fit expectation!" % (method, self.profilerclass.__name__)) print('\n'.join(unified_diff( results[i+1].split('\n'), expected[method].split('\n')))) def test_calling_conventions(self): # Issue #5330: profile and cProfile wouldn't report C functions called # with keyword arguments. We test all calling conventions. stmts = [ "max([0])", "max([0], key=int)", "max([0], **dict(key=int))", "max(*([0],))", "max(*([0],), key=int)", "max(*([0],), **dict(key=int))", ] for stmt in stmts: s = StringIO() prof = self.profilerclass(timer, 0.001) prof.runctx(stmt, globals(), locals()) stats = pstats.Stats(prof, stream=s) stats.print_stats() res = s.getvalue() self.assertIn(self.expected_max_output, res, "Profiling {0!r} didn't report max:\n{1}".format(stmt, res)) def regenerate_expected_output(filename, cls): filename = filename.rstrip('co') print('Regenerating %s...' % filename) results = cls.do_profiling() newfile = [] with open(filename, 'r') as f: for line in f: newfile.append(line) if line.startswith('#--cut'): break with open(filename, 'w') as f: f.writelines(newfile) f.write("_ProfileOutput = {}\n") for i, method in enumerate(cls.methodnames): f.write('_ProfileOutput[%r] = """\\\n%s"""\n' % ( method, results[i+1])) f.write('\nif __name__ == "__main__":\n main()\n') def test_main(): run_unittest(ProfileTest) def main(): if '-r' not in sys.argv: test_main() else: regenerate_expected_output(__file__, ProfileTest) # Don't remove this comment. Everything below it is auto-generated. #--cut-------------------------------------------------------------------------- _ProfileOutput = {} _ProfileOutput['print_stats'] = """\ 28 27.972 0.999 27.972 0.999 profilee.py:110(__getattr__) 1 269.996 269.996 999.769 999.769 profilee.py:25(testfunc) 23/3 149.937 6.519 169.917 56.639 profilee.py:35(factorial) 20 19.980 0.999 19.980 0.999 profilee.py:48(mul) 2 39.986 19.993 599.830 299.915 profilee.py:55(helper) 4 115.984 28.996 119.964 29.991 profilee.py:73(helper1) 2 -0.006 -0.003 139.946 69.973 profilee.py:84(helper2_indirect) 8 311.976 38.997 399.912 49.989 profilee.py:88(helper2) 8 63.976 7.997 79.960 9.995 profilee.py:98(subhelper)""" _ProfileOutput['print_callers'] = """\ :0(append) <- profilee.py:73(helper1)(4) 119.964 :0(exc_info) <- profilee.py:73(helper1)(4) 119.964 :0(hasattr) <- profilee.py:73(helper1)(4) 119.964 profilee.py:88(helper2)(8) 399.912 profilee.py:110(__getattr__) <- :0(hasattr)(12) 11.964 profilee.py:98(subhelper)(16) 79.960 profilee.py:25(testfunc) <- <string>:1(<module>)(1) 999.767 profilee.py:35(factorial) <- profilee.py:25(testfunc)(1) 999.769 profilee.py:35(factorial)(20) 169.917 profilee.py:84(helper2_indirect)(2) 139.946 profilee.py:48(mul) <- profilee.py:35(factorial)(20) 169.917 profilee.py:55(helper) <- profilee.py:25(testfunc)(2) 999.769 profilee.py:73(helper1) <- profilee.py:55(helper)(4) 599.830 profilee.py:84(helper2_indirect) <- profilee.py:55(helper)(2) 599.830 profilee.py:88(helper2) <- profilee.py:55(helper)(6) 599.830 profilee.py:84(helper2_indirect)(2) 139.946 profilee.py:98(subhelper) <- profilee.py:88(helper2)(8) 399.912""" _ProfileOutput['print_callees'] = """\ :0(hasattr) -> profilee.py:110(__getattr__)(12) 27.972 <string>:1(<module>) -> profilee.py:25(testfunc)(1) 999.769 profilee.py:110(__getattr__) -> profilee.py:25(testfunc) -> profilee.py:35(factorial)(1) 169.917 profilee.py:55(helper)(2) 599.830 profilee.py:35(factorial) -> profilee.py:35(factorial)(20) 169.917 profilee.py:48(mul)(20) 19.980 profilee.py:48(mul) -> profilee.py:55(helper) -> profilee.py:73(helper1)(4) 119.964 profilee.py:84(helper2_indirect)(2) 139.946 profilee.py:88(helper2)(6) 399.912 profilee.py:73(helper1) -> :0(append)(4) -0.004 profilee.py:84(helper2_indirect) -> profilee.py:35(factorial)(2) 169.917 profilee.py:88(helper2)(2) 399.912 profilee.py:88(helper2) -> :0(hasattr)(8) 11.964 profilee.py:98(subhelper)(8) 79.960 profilee.py:98(subhelper) -> profilee.py:110(__getattr__)(16) 27.972""" if __name__ == "__main__": main()
gpl-3.0
-6,049,563,263,557,726,000
42.7875
81
0.535826
false
tosolveit/scikit-learn
sklearn/ensemble/tests/test_partial_dependence.py
365
6996
""" Testing for the partial dependence module. """ import numpy as np from numpy.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import if_matplotlib from sklearn.ensemble.partial_dependence import partial_dependence from sklearn.ensemble.partial_dependence import plot_partial_dependence from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import GradientBoostingRegressor from sklearn import datasets # toy sample X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] y = [-1, -1, -1, 1, 1, 1] T = [[-1, -1], [2, 2], [3, 2]] true_result = [-1, 1, 1] # also load the boston dataset boston = datasets.load_boston() # also load the iris dataset iris = datasets.load_iris() def test_partial_dependence_classifier(): # Test partial dependence for classifier clf = GradientBoostingClassifier(n_estimators=10, random_state=1) clf.fit(X, y) pdp, axes = partial_dependence(clf, [0], X=X, grid_resolution=5) # only 4 grid points instead of 5 because only 4 unique X[:,0] vals assert pdp.shape == (1, 4) assert axes[0].shape[0] == 4 # now with our own grid X_ = np.asarray(X) grid = np.unique(X_[:, 0]) pdp_2, axes = partial_dependence(clf, [0], grid=grid) assert axes is None assert_array_equal(pdp, pdp_2) def test_partial_dependence_multiclass(): # Test partial dependence for multi-class classifier clf = GradientBoostingClassifier(n_estimators=10, random_state=1) clf.fit(iris.data, iris.target) grid_resolution = 25 n_classes = clf.n_classes_ pdp, axes = partial_dependence( clf, [0], X=iris.data, grid_resolution=grid_resolution) assert pdp.shape == (n_classes, grid_resolution) assert len(axes) == 1 assert axes[0].shape[0] == grid_resolution def test_partial_dependence_regressor(): # Test partial dependence for regressor clf = GradientBoostingRegressor(n_estimators=10, random_state=1) clf.fit(boston.data, boston.target) grid_resolution = 25 pdp, axes = partial_dependence( clf, [0], X=boston.data, grid_resolution=grid_resolution) assert pdp.shape == (1, grid_resolution) assert axes[0].shape[0] == grid_resolution def test_partial_dependecy_input(): # Test input validation of partial dependence. clf = GradientBoostingClassifier(n_estimators=10, random_state=1) clf.fit(X, y) assert_raises(ValueError, partial_dependence, clf, [0], grid=None, X=None) assert_raises(ValueError, partial_dependence, clf, [0], grid=[0, 1], X=X) # first argument must be an instance of BaseGradientBoosting assert_raises(ValueError, partial_dependence, {}, [0], X=X) # Gradient boosting estimator must be fit assert_raises(ValueError, partial_dependence, GradientBoostingClassifier(), [0], X=X) assert_raises(ValueError, partial_dependence, clf, [-1], X=X) assert_raises(ValueError, partial_dependence, clf, [100], X=X) # wrong ndim for grid grid = np.random.rand(10, 2, 1) assert_raises(ValueError, partial_dependence, clf, [0], grid=grid) @if_matplotlib def test_plot_partial_dependence(): # Test partial dependence plot function. clf = GradientBoostingRegressor(n_estimators=10, random_state=1) clf.fit(boston.data, boston.target) grid_resolution = 25 fig, axs = plot_partial_dependence(clf, boston.data, [0, 1, (0, 1)], grid_resolution=grid_resolution, feature_names=boston.feature_names) assert len(axs) == 3 assert all(ax.has_data for ax in axs) # check with str features and array feature names fig, axs = plot_partial_dependence(clf, boston.data, ['CRIM', 'ZN', ('CRIM', 'ZN')], grid_resolution=grid_resolution, feature_names=boston.feature_names) assert len(axs) == 3 assert all(ax.has_data for ax in axs) # check with list feature_names feature_names = boston.feature_names.tolist() fig, axs = plot_partial_dependence(clf, boston.data, ['CRIM', 'ZN', ('CRIM', 'ZN')], grid_resolution=grid_resolution, feature_names=feature_names) assert len(axs) == 3 assert all(ax.has_data for ax in axs) @if_matplotlib def test_plot_partial_dependence_input(): # Test partial dependence plot function input checks. clf = GradientBoostingClassifier(n_estimators=10, random_state=1) # not fitted yet assert_raises(ValueError, plot_partial_dependence, clf, X, [0]) clf.fit(X, y) assert_raises(ValueError, plot_partial_dependence, clf, np.array(X)[:, :0], [0]) # first argument must be an instance of BaseGradientBoosting assert_raises(ValueError, plot_partial_dependence, {}, X, [0]) # must be larger than -1 assert_raises(ValueError, plot_partial_dependence, clf, X, [-1]) # too large feature value assert_raises(ValueError, plot_partial_dependence, clf, X, [100]) # str feature but no feature_names assert_raises(ValueError, plot_partial_dependence, clf, X, ['foobar']) # not valid features value assert_raises(ValueError, plot_partial_dependence, clf, X, [{'foo': 'bar'}]) @if_matplotlib def test_plot_partial_dependence_multiclass(): # Test partial dependence plot function on multi-class input. clf = GradientBoostingClassifier(n_estimators=10, random_state=1) clf.fit(iris.data, iris.target) grid_resolution = 25 fig, axs = plot_partial_dependence(clf, iris.data, [0, 1], label=0, grid_resolution=grid_resolution) assert len(axs) == 2 assert all(ax.has_data for ax in axs) # now with symbol labels target = iris.target_names[iris.target] clf = GradientBoostingClassifier(n_estimators=10, random_state=1) clf.fit(iris.data, target) grid_resolution = 25 fig, axs = plot_partial_dependence(clf, iris.data, [0, 1], label='setosa', grid_resolution=grid_resolution) assert len(axs) == 2 assert all(ax.has_data for ax in axs) # label not in gbrt.classes_ assert_raises(ValueError, plot_partial_dependence, clf, iris.data, [0, 1], label='foobar', grid_resolution=grid_resolution) # label not provided assert_raises(ValueError, plot_partial_dependence, clf, iris.data, [0, 1], grid_resolution=grid_resolution)
bsd-3-clause
-229,281,754,264,315,600
32.961165
74
0.617067
false
felixma/nova
nova/tests/functional/api_sample_tests/test_security_group_default_rules.py
26
2374
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg from nova.tests.functional.api_sample_tests import api_sample_base CONF = cfg.CONF CONF.import_opt('osapi_compute_extension', 'nova.api.openstack.compute.legacy_v2.extensions') class SecurityGroupDefaultRulesSampleJsonTest( api_sample_base.ApiSampleTestBaseV21): ADMIN_API = True extension_name = 'os-security-group-default-rules' def _get_flags(self): f = super(SecurityGroupDefaultRulesSampleJsonTest, self)._get_flags() f['osapi_compute_extension'] = CONF.osapi_compute_extension[:] f['osapi_compute_extension'].append('nova.api.openstack.compute.' 'contrib.security_group_default_rules.' 'Security_group_default_rules') return f def test_security_group_default_rules_create(self): response = self._do_post('os-security-group-default-rules', 'security-group-default-rules-create-req', {}) self._verify_response('security-group-default-rules-create-resp', {}, response, 200) def test_security_group_default_rules_list(self): self.test_security_group_default_rules_create() response = self._do_get('os-security-group-default-rules') self._verify_response('security-group-default-rules-list-resp', {}, response, 200) def test_security_group_default_rules_show(self): self.test_security_group_default_rules_create() rule_id = '1' response = self._do_get('os-security-group-default-rules/%s' % rule_id) self._verify_response('security-group-default-rules-show-resp', {}, response, 200)
apache-2.0
4,859,057,978,577,465,000
42.163636
79
0.645746
false
caseyclements/bokeh
bokeh/compat/mplexporter/exporter.py
32
12403
""" Matplotlib Exporter =================== This submodule contains tools for crawling a matplotlib figure and exporting relevant pieces to a renderer. """ import warnings import io from . import utils import matplotlib from matplotlib import transforms from matplotlib.backends.backend_agg import FigureCanvasAgg class Exporter(object): """Matplotlib Exporter Parameters ---------- renderer : Renderer object The renderer object called by the exporter to create a figure visualization. See mplexporter.Renderer for information on the methods which should be defined within the renderer. close_mpl : bool If True (default), close the matplotlib figure as it is rendered. This is useful for when the exporter is used within the notebook, or with an interactive matplotlib backend. """ def __init__(self, renderer, close_mpl=True): self.close_mpl = close_mpl self.renderer = renderer def run(self, fig): """ Run the exporter on the given figure Parmeters --------- fig : matplotlib.Figure instance The figure to export """ # Calling savefig executes the draw() command, putting elements # in the correct place. if fig.canvas is None: fig.canvas = FigureCanvasAgg(fig) fig.savefig(io.BytesIO(), format='png', dpi=fig.dpi) if self.close_mpl: import matplotlib.pyplot as plt plt.close(fig) self.crawl_fig(fig) @staticmethod def process_transform(transform, ax=None, data=None, return_trans=False, force_trans=None): """Process the transform and convert data to figure or data coordinates Parameters ---------- transform : matplotlib Transform object The transform applied to the data ax : matplotlib Axes object (optional) The axes the data is associated with data : ndarray (optional) The array of data to be transformed. return_trans : bool (optional) If true, return the final transform of the data force_trans : matplotlib.transform instance (optional) If supplied, first force the data to this transform Returns ------- code : string Code is either "data", "axes", "figure", or "display", indicating the type of coordinates output. transform : matplotlib transform the transform used to map input data to output data. Returned only if return_trans is True new_data : ndarray Data transformed to match the given coordinate code. Returned only if data is specified """ if isinstance(transform, transforms.BlendedGenericTransform): warnings.warn("Blended transforms not yet supported. " "Zoom behavior may not work as expected.") if force_trans is not None: if data is not None: data = (transform - force_trans).transform(data) transform = force_trans code = "display" if ax is not None: for (c, trans) in [("data", ax.transData), ("axes", ax.transAxes), ("figure", ax.figure.transFigure), ("display", transforms.IdentityTransform())]: if transform.contains_branch(trans): code, transform = (c, transform - trans) break if data is not None: if return_trans: return code, transform.transform(data), transform else: return code, transform.transform(data) else: if return_trans: return code, transform else: return code def crawl_fig(self, fig): """Crawl the figure and process all axes""" with self.renderer.draw_figure(fig=fig, props=utils.get_figure_properties(fig)): for ax in fig.axes: self.crawl_ax(ax) def crawl_ax(self, ax): """Crawl the axes and process all elements within""" with self.renderer.draw_axes(ax=ax, props=utils.get_axes_properties(ax)): for line in ax.lines: self.draw_line(ax, line) for text in ax.texts: self.draw_text(ax, text) for (text, ttp) in zip([ax.xaxis.label, ax.yaxis.label, ax.title], ["xlabel", "ylabel", "title"]): if(hasattr(text, 'get_text') and text.get_text()): self.draw_text(ax, text, force_trans=ax.transAxes, text_type=ttp) for artist in ax.artists: # TODO: process other artists if isinstance(artist, matplotlib.text.Text): self.draw_text(ax, artist) for patch in ax.patches: self.draw_patch(ax, patch) for collection in ax.collections: self.draw_collection(ax, collection) for image in ax.images: self.draw_image(ax, image) legend = ax.get_legend() if legend is not None: props = utils.get_legend_properties(ax, legend) with self.renderer.draw_legend(legend=legend, props=props): if props['visible']: self.crawl_legend(ax, legend) def crawl_legend(self, ax, legend): """ Recursively look through objects in legend children """ legendElements = list(utils.iter_all_children(legend._legend_box, skipContainers=True)) legendElements.append(legend.legendPatch) for child in legendElements: # force a large zorder so it appears on top child.set_zorder(1E6 + child.get_zorder()) try: # What kind of object... if isinstance(child, matplotlib.patches.Patch): self.draw_patch(ax, child, force_trans=ax.transAxes) elif isinstance(child, matplotlib.text.Text): if not (child is legend.get_children()[-1] and child.get_text() == 'None'): self.draw_text(ax, child, force_trans=ax.transAxes) elif isinstance(child, matplotlib.lines.Line2D): self.draw_line(ax, child, force_trans=ax.transAxes) elif isinstance(child, matplotlib.collections.Collection): self.draw_collection(ax, child, force_pathtrans=ax.transAxes) else: warnings.warn("Legend element %s not impemented" % child) except NotImplementedError: warnings.warn("Legend element %s not impemented" % child) def draw_line(self, ax, line, force_trans=None): """Process a matplotlib line and call renderer.draw_line""" coordinates, data = self.process_transform(line.get_transform(), ax, line.get_xydata(), force_trans=force_trans) linestyle = utils.get_line_style(line) if linestyle['dasharray'] is None: linestyle = None markerstyle = utils.get_marker_style(line) if (markerstyle['marker'] in ['None', 'none', None] or markerstyle['markerpath'][0].size == 0): markerstyle = None label = line.get_label() if markerstyle or linestyle: self.renderer.draw_marked_line(data=data, coordinates=coordinates, linestyle=linestyle, markerstyle=markerstyle, label=label, mplobj=line) def draw_text(self, ax, text, force_trans=None, text_type=None): """Process a matplotlib text object and call renderer.draw_text""" content = text.get_text() if content: transform = text.get_transform() position = text.get_position() coords, position = self.process_transform(transform, ax, position, force_trans=force_trans) style = utils.get_text_style(text) self.renderer.draw_text(text=content, position=position, coordinates=coords, text_type=text_type, style=style, mplobj=text) def draw_patch(self, ax, patch, force_trans=None): """Process a matplotlib patch object and call renderer.draw_path""" vertices, pathcodes = utils.SVG_path(patch.get_path()) transform = patch.get_transform() coordinates, vertices = self.process_transform(transform, ax, vertices, force_trans=force_trans) linestyle = utils.get_path_style(patch, fill=patch.get_fill()) self.renderer.draw_path(data=vertices, coordinates=coordinates, pathcodes=pathcodes, style=linestyle, mplobj=patch) def draw_collection(self, ax, collection, force_pathtrans=None, force_offsettrans=None): """Process a matplotlib collection and call renderer.draw_collection""" (transform, transOffset, offsets, paths) = collection._prepare_points() offset_coords, offsets = self.process_transform( transOffset, ax, offsets, force_trans=force_offsettrans) path_coords = self.process_transform( transform, ax, force_trans=force_pathtrans) processed_paths = [utils.SVG_path(path) for path in paths] processed_paths = [(self.process_transform( transform, ax, path[0], force_trans=force_pathtrans)[1], path[1]) for path in processed_paths] path_transforms = collection.get_transforms() try: # matplotlib 1.3: path_transforms are transform objects. # Convert them to numpy arrays. path_transforms = [t.get_matrix() for t in path_transforms] except AttributeError: # matplotlib 1.4: path transforms are already numpy arrays. pass styles = {'linewidth': collection.get_linewidths(), 'facecolor': collection.get_facecolors(), 'edgecolor': collection.get_edgecolors(), 'alpha': collection._alpha, 'zorder': collection.get_zorder()} offset_dict = {"data": "before", "screen": "after"} offset_order = offset_dict[collection.get_offset_position()] self.renderer.draw_path_collection(paths=processed_paths, path_coordinates=path_coords, path_transforms=path_transforms, offsets=offsets, offset_coordinates=offset_coords, offset_order=offset_order, styles=styles, mplobj=collection) def draw_image(self, ax, image): """Process a matplotlib image object and call renderer.draw_image""" self.renderer.draw_image(imdata=utils.image_to_base64(image), extent=image.get_extent(), coordinates="data", style={"alpha": image.get_alpha(), "zorder": image.get_zorder()}, mplobj=image)
bsd-3-clause
4,762,143,605,527,384,000
43.13879
79
0.527776
false
nmercier/linux-cross-gcc
win32/bin/Lib/robotparser.py
2
7821
""" robotparser.py Copyright (C) 2000 Bastian Kleineidam You can choose between two licenses when using this package: 1) GNU GPLv2 2) PSF license for Python 2.2 The robots.txt Exclusion Protocol is implemented as specified in http://www.robotstxt.org/norobots-rfc.txt """ import urlparse import urllib __all__ = ["RobotFileParser"] class RobotFileParser: """ This class provides a set of methods to read, parse and answer questions about a single robots.txt file. """ def __init__(self, url=''): self.entries = [] self.default_entry = None self.disallow_all = False self.allow_all = False self.set_url(url) self.last_checked = 0 def mtime(self): """Returns the time the robots.txt file was last fetched. This is useful for long-running web spiders that need to check for new robots.txt files periodically. """ return self.last_checked def modified(self): """Sets the time the robots.txt file was last fetched to the current time. """ import time self.last_checked = time.time() def set_url(self, url): """Sets the URL referring to a robots.txt file.""" self.url = url self.host, self.path = urlparse.urlparse(url)[1:3] def read(self): """Reads the robots.txt URL and feeds it to the parser.""" opener = URLopener() f = opener.open(self.url) lines = [line.strip() for line in f] f.close() self.errcode = opener.errcode if self.errcode in (401, 403): self.disallow_all = True elif self.errcode >= 400 and self.errcode < 500: self.allow_all = True elif self.errcode == 200 and lines: self.parse(lines) def _add_entry(self, entry): if "*" in entry.useragents: # the default entry is considered last if self.default_entry is None: # the first default entry wins self.default_entry = entry else: self.entries.append(entry) def parse(self, lines): """parse the input lines from a robots.txt file. We allow that a user-agent: line is not preceded by one or more blank lines.""" # states: # 0: start state # 1: saw user-agent line # 2: saw an allow or disallow line state = 0 linenumber = 0 entry = Entry() self.modified() for line in lines: linenumber += 1 if not line: if state == 1: entry = Entry() state = 0 elif state == 2: self._add_entry(entry) entry = Entry() state = 0 # remove optional comment and strip line i = line.find('#') if i >= 0: line = line[:i] line = line.strip() if not line: continue line = line.split(':', 1) if len(line) == 2: line[0] = line[0].strip().lower() line[1] = urllib.unquote(line[1].strip()) if line[0] == "user-agent": if state == 2: self._add_entry(entry) entry = Entry() entry.useragents.append(line[1]) state = 1 elif line[0] == "disallow": if state != 0: entry.rulelines.append(RuleLine(line[1], False)) state = 2 elif line[0] == "allow": if state != 0: entry.rulelines.append(RuleLine(line[1], True)) state = 2 if state == 2: self._add_entry(entry) def can_fetch(self, useragent, url): """using the parsed robots.txt decide if useragent can fetch url""" if self.disallow_all: return False if self.allow_all: return True # Until the robots.txt file has been read or found not # to exist, we must assume that no url is allowable. # This prevents false positives when a user erronenously # calls can_fetch() before calling read(). if not self.last_checked: return False # search for given user agent matches # the first match counts parsed_url = urlparse.urlparse(urllib.unquote(url)) url = urlparse.urlunparse(('', '', parsed_url.path, parsed_url.params, parsed_url.query, parsed_url.fragment)) url = urllib.quote(url) if not url: url = "/" for entry in self.entries: if entry.applies_to(useragent): return entry.allowance(url) # try the default entry last if self.default_entry: return self.default_entry.allowance(url) # agent not found ==> access granted return True def __str__(self): return ''.join([str(entry) + "\n" for entry in self.entries]) class RuleLine: """A rule line is a single "Allow:" (allowance==True) or "Disallow:" (allowance==False) followed by a path.""" def __init__(self, path, allowance): if path == '' and not allowance: # an empty value means allow all allowance = True path = urlparse.urlunparse(urlparse.urlparse(path)) self.path = urllib.quote(path) self.allowance = allowance def applies_to(self, filename): return self.path == "*" or filename.startswith(self.path) def __str__(self): return (self.allowance and "Allow" or "Disallow") + ": " + self.path class Entry: """An entry has one or more user-agents and zero or more rulelines""" def __init__(self): self.useragents = [] self.rulelines = [] def __str__(self): ret = [] for agent in self.useragents: ret.extend(["User-agent: ", agent, "\n"]) for line in self.rulelines: ret.extend([str(line), "\n"]) return ''.join(ret) def applies_to(self, useragent): """check if this entry applies to the specified agent""" # split the name token and make it lower case useragent = useragent.split("/")[0].lower() for agent in self.useragents: if agent == '*': # we have the catch-all agent return True agent = agent.lower() if agent in useragent: return True return False def allowance(self, filename): """Preconditions: - our agent applies to this entry - filename is URL decoded""" for line in self.rulelines: if line.applies_to(filename): return line.allowance return True class URLopener(urllib.FancyURLopener): def __init__(self, *args): urllib.FancyURLopener.__init__(self, *args) self.errcode = 200 def prompt_user_passwd(self, host, realm): ## If robots.txt file is accessible only with a password, ## we act as if the file wasn't there. return None, None def http_error_default(self, url, fp, errcode, errmsg, headers): self.errcode = errcode return urllib.FancyURLopener.http_error_default(self, url, fp, errcode, errmsg, headers)
bsd-3-clause
6,720,270,426,358,403,000
31.566524
79
0.520394
false
zaheerm/gst-python
testsuite/common.py
1
5702
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # gst-python - Python bindings for GStreamer # Copyright (C) 2002 David I. Lehn # Copyright (C) 2004 Johan Dahlin # Copyright (C) 2005 Edward Hervey # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA try: from dl import RTLD_LAZY, RTLD_GLOBAL except ImportError: # dl doesn't seem to be available on 64bit systems try: from DLFCN import RTLD_LAZY, RTLD_GLOBAL except ImportError: pass import os import sys import gc import unittest import pygtk pygtk.require('2.0') import gobject try: gobject.threads_init() except: print "WARNING: gobject doesn't have threads_init, no threadsafety" # Detect the version of pygobject # In pygobject >= 2.13.0 the refcounting of objects has changed. pgmaj,pgmin,pgmac = gobject.pygobject_version if pgmaj >= 2 and pgmin >= 13: pygobject_2_13 = True else: pygobject_2_13 = False # Don't insert before . # sys.path.insert(1, os.path.join('..')) # Load GST and make sure we load it from the current build sys.setdlopenflags(RTLD_LAZY | RTLD_GLOBAL) topbuilddir = os.path.abspath(os.path.join('..')) topsrcdir = os.path.abspath(os.path.join('..')) if topsrcdir.endswith('_build'): topsrcdir = os.path.dirname(topsrcdir) # gst's __init__.py is in topsrcdir/gst path = os.path.abspath(os.path.join(topsrcdir, 'gst')) import gst file = gst.__file__ assert file.startswith(path), 'bad gst path: %s' % file # gst's interfaces is in topbuilddir/gst path = os.path.abspath(os.path.join(topbuilddir, 'gst')) try: import gst.interfaces except ImportError: # hack: we import it from our builddir/gst/.libs instead; ugly import interfaces gst.interfaces = interfaces file = gst.interfaces.__file__ assert file.startswith(path), 'bad gst.interfaces path: %s' % file # gst's pbutils is in topbuilddir/gst path = os.path.abspath(os.path.join(topbuilddir, 'gst')) try: import gst.pbutils except ImportError: # hack: we import it from our builddir/gst/.libs instead; ugly import pbutils gst.pbutils = pbutils file = gst.pbutils.__file__ assert file.startswith(path), 'bad gst.pbutils path: %s' % file # testhelper needs gstltihooks import gstltihooks import testhelper gstltihooks.uninstall() _stderr = None def disable_stderr(): global _stderr _stderr = file('/tmp/stderr', 'w+') sys.stderr = os.fdopen(os.dup(2), 'w') os.close(2) os.dup(_stderr.fileno()) def enable_stderr(): global _stderr os.close(2) os.dup(sys.stderr.fileno()) _stderr.seek(0, 0) data = _stderr.read() _stderr.close() os.remove('/tmp/stderr') return data def run_silent(function, *args, **kwargs): disable_stderr() try: function(*args, **kwargs) except Exception, exc: enable_stderr() raise exc output = enable_stderr() return output class TestCase(unittest.TestCase): _types = [gst.Object, gst.MiniObject] def gccollect(self): # run the garbage collector ret = 0 gst.debug('garbage collecting') while True: c = gc.collect() ret += c if c == 0: break gst.debug('done garbage collecting, %d objects' % ret) return ret def gctrack(self): # store all gst objects in the gc in a tracking dict # call before doing any allocation in your test, from setUp gst.debug('tracking gc GstObjects for types %r' % self._types) self.gccollect() self._tracked = {} for c in self._types: self._tracked[c] = [o for o in gc.get_objects() if isinstance(o, c)] def gcverify(self): # verify no new gst objects got added to the gc # call after doing all cleanup in your test, from tearDown gst.debug('verifying gc GstObjects for types %r' % self._types) new = [] for c in self._types: objs = [o for o in gc.get_objects() if isinstance(o, c)] new.extend([o for o in objs if o not in self._tracked[c]]) self.failIf(new, new) #self.failIf(new, ["%r:%d" % (type(o), id(o)) for o in new]) del self._tracked def setUp(self): """ Override me by chaining up to me at the start of your setUp. """ # Using private variables is BAD ! this variable changed name in # python 2.5 try: methodName = self.__testMethodName except: methodName = self._testMethodName gst.debug('%s.%s' % (self.__class__.__name__, methodName)) self.gctrack() def tearDown(self): """ Override me by chaining up to me at the end of your tearDown. """ # Using private variables is BAD ! this variable changed name in # python 2.5 try: methodName = self.__testMethodName except: methodName = self._testMethodName gst.debug('%s.%s' % (self.__class__.__name__, methodName)) self.gccollect() self.gcverify()
lgpl-2.1
-47,007,662,577,367,220
28.697917
80
0.647141
false
tvald/Jink
python/jink/extension.py
1
1038
import types class LazyFactory(object): def __init__(self, module_str, callable_str): self.module_str = module_str self.callable_str = callable_str self.factory = None def resolve(self): if self.factory == None: self.factory = reduce(lambda x, y: getattr(x, y), self.module_str.split('.')[1:] + self.callable_str.split('.'), __import__(self.module_str)) return self.factory def instantiate(self, *args, **kw): self.resolve() return self.factory(*args, **kw) def __call__(self, *args, **kw): self.instantiate(*args, **kw) class Registry(object): def __init__(self): self._registry = dict() def register(self, keys, factory): try: iter(keys) except TypeError, e: keys = (keys) for k in keys: self._registry[k] = factory def get(self, key): return self._registry[key] source = Registry() sink = Registry() __all__ = ['LazyFactory', 'source', 'sink', 'Registry']
mit
164,330,639,631,910,080
24.317073
60
0.570328
false
ARMmbed/yotta_osx_installer
workspace/lib/python2.7/site-packages/pip/_vendor/ipaddress.py
198
79659
# Copyright 2007 Google Inc. # Licensed to PSF under a Contributor Agreement. """A fast, lightweight IPv4/IPv6 manipulation library in Python. This library is used to create/poke/manipulate IPv4 and IPv6 addresses and networks. """ from __future__ import unicode_literals import itertools import struct __version__ = '1.0.14' # Compatibility functions _compat_int_types = (int,) try: _compat_int_types = (int, long) except NameError: pass try: _compat_str = unicode except NameError: _compat_str = str assert bytes != str if b'\0'[0] == 0: # Python 3 semantics def _compat_bytes_to_byte_vals(byt): return byt else: def _compat_bytes_to_byte_vals(byt): return [struct.unpack(b'!B', b)[0] for b in byt] try: _compat_int_from_byte_vals = int.from_bytes except AttributeError: def _compat_int_from_byte_vals(bytvals, endianess): assert endianess == 'big' res = 0 for bv in bytvals: assert isinstance(bv, _compat_int_types) res = (res << 8) + bv return res def _compat_to_bytes(intval, length, endianess): assert isinstance(intval, _compat_int_types) assert endianess == 'big' if length == 4: if intval < 0 or intval >= 2 ** 32: raise struct.error("integer out of range for 'I' format code") return struct.pack(b'!I', intval) elif length == 16: if intval < 0 or intval >= 2 ** 128: raise struct.error("integer out of range for 'QQ' format code") return struct.pack(b'!QQ', intval >> 64, intval & 0xffffffffffffffff) else: raise NotImplementedError() if hasattr(int, 'bit_length'): # Not int.bit_length , since that won't work in 2.7 where long exists def _compat_bit_length(i): return i.bit_length() else: def _compat_bit_length(i): for res in itertools.count(): if i >> res == 0: return res def _compat_range(start, end, step=1): assert step > 0 i = start while i < end: yield i i += step class _TotalOrderingMixin(object): __slots__ = () # Helper that derives the other comparison operations from # __lt__ and __eq__ # We avoid functools.total_ordering because it doesn't handle # NotImplemented correctly yet (http://bugs.python.org/issue10042) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not equal def __lt__(self, other): raise NotImplementedError def __le__(self, other): less = self.__lt__(other) if less is NotImplemented or not less: return self.__eq__(other) return less def __gt__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented equal = self.__eq__(other) if equal is NotImplemented: return NotImplemented return not (less or equal) def __ge__(self, other): less = self.__lt__(other) if less is NotImplemented: return NotImplemented return not less IPV4LENGTH = 32 IPV6LENGTH = 128 class AddressValueError(ValueError): """A Value Error related to the address.""" class NetmaskValueError(ValueError): """A Value Error related to the netmask.""" def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass if isinstance(address, bytes): raise AddressValueError( '%r does not appear to be an IPv4 or IPv6 address. ' 'Did you pass in a bytes (str in Python 2) instead of' ' a unicode object?' % address) raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address) def ip_network(address, strict=True): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Network or IPv6Network object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Or if the network has host bits set. """ try: return IPv4Network(address, strict) except (AddressValueError, NetmaskValueError): pass try: return IPv6Network(address, strict) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % address) def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Interface or IPv6Interface object. Raises: ValueError: if the string passed isn't either a v4 or a v6 address. Notes: The IPv?Interface classes describe an Address on a particular Network, so they're basically a combination of both the Address and Network classes. """ try: return IPv4Interface(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Interface(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % address) def v4_int_to_packed(address): """Represent an address as 4 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv4 IP address. Returns: The integer address packed as 4 bytes in network (big-endian) order. Raises: ValueError: If the integer is negative or too large to be an IPv4 IP address. """ try: return _compat_to_bytes(address, 4, 'big') except (struct.error, OverflowError): raise ValueError("Address negative or too large for IPv4") def v6_int_to_packed(address): """Represent an address as 16 packed bytes in network (big-endian) order. Args: address: An integer representation of an IPv6 IP address. Returns: The integer address packed as 16 bytes in network (big-endian) order. """ try: return _compat_to_bytes(address, 16, 'big') except (struct.error, OverflowError): raise ValueError("Address negative or too large for IPv6") def _split_optional_netmask(address): """Helper to split the netmask and raise AddressValueError if needed""" addr = _compat_str(address).split('/') if len(addr) > 2: raise AddressValueError("Only one '/' permitted in %r" % address) return addr def _find_address_range(addresses): """Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence. """ it = iter(addresses) first = last = next(it) for ip in it: if ip._ip != last._ip + 1: yield first, last first = ip last = ip yield first, last def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return bits return min(bits, _compat_bit_length(~number & (number - 1))) def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +NORMALIZE_WHITESPACE [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')] Args: first: the first IPv4Address or IPv6Address in the range. last: the last IPv4Address or IPv6Address in the range. Returns: An iterator of the summarized IPv(4|6) network objects. Raise: TypeError: If the first and last objects are not IP addresses. If the first and last objects are not the same version. ValueError: If the last object is not greater than the first. If the version of the first address is not 4 or 6. """ if (not (isinstance(first, _BaseAddress) and isinstance(last, _BaseAddress))): raise TypeError('first and last must be IP addresses, not networks') if first.version != last.version: raise TypeError("%s and %s are not of the same version" % ( first, last)) if first > last: raise ValueError('last IP address must be greater than first') if first.version == 4: ip = IPv4Network elif first.version == 6: ip = IPv6Network else: raise ValueError('unknown IP version') ip_bits = first._max_prefixlen first_int = first._ip last_int = last._ip while first_int <= last_int: nbits = min(_count_righthand_zero_bits(first_int, ip_bits), _compat_bit_length(last_int - first_int + 1) - 1) net = ip((first_int, ip_bits - nbits)) yield net first_int += 1 << nbits if first_int - 1 == ip._ALL_ONES: break def _collapse_addresses_internal(addresses): """Loops through the addresses, collapsing concurrent netblocks. Example: ip1 = IPv4Network('192.0.2.0/26') ip2 = IPv4Network('192.0.2.64/26') ip3 = IPv4Network('192.0.2.128/26') ip4 = IPv4Network('192.0.2.192/26') _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> [IPv4Network('192.0.2.0/24')] This shouldn't be called directly; it is called via collapse_addresses([]). Args: addresses: A list of IPv4Network's or IPv6Network's Returns: A list of IPv4Network's or IPv6Network's depending on what we were passed. """ # First merge to_merge = list(addresses) subnets = {} while to_merge: net = to_merge.pop() supernet = net.supernet() existing = subnets.get(supernet) if existing is None: subnets[supernet] = net elif existing != net: # Merge consecutive subnets del subnets[supernet] to_merge.append(supernet) # Then iterate over resulting networks, skipping subsumed subnets last = None for net in sorted(subnets.values()): if last is not None: # Since they are sorted, # last.network_address <= net.network_address is a given. if last.broadcast_address >= net.broadcast_address: continue yield net last = net def collapse_addresses(addresses): """Collapse a list of IP objects. Example: collapse_addresses([IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]) -> [IPv4Network('192.0.2.0/24')] Args: addresses: An iterator of IPv4Network or IPv6Network objects. Returns: An iterator of the collapsed IPv(4|6)Network objects. Raises: TypeError: If passed a list of mixed version objects. """ addrs = [] ips = [] nets = [] # split IP addresses and networks for ip in addresses: if isinstance(ip, _BaseAddress): if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) ips.append(ip) elif ip._prefixlen == ip._max_prefixlen: if ips and ips[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, ips[-1])) try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) else: if nets and nets[-1]._version != ip._version: raise TypeError("%s and %s are not of the same version" % ( ip, nets[-1])) nets.append(ip) # sort and dedup ips = sorted(set(ips)) # find consecutive address ranges in the sorted sequence and summarize them if ips: for first, last in _find_address_range(ips): addrs.extend(summarize_address_range(first, last)) return _collapse_addresses_internal(addrs + nets) def get_mixed_type_key(obj): """Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they're fundamentally different so the expression IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') doesn't make any sense. There are some times however, where you may wish to have ipaddress sort these for you anyway. If you need to do this, you can use this function as the key= argument to sorted(). Args: obj: either a Network or Address object. Returns: appropriate key. """ if isinstance(obj, _BaseNetwork): return obj._get_networks_key() elif isinstance(obj, _BaseAddress): return obj._get_address_key() return NotImplemented class _IPAddressBase(_TotalOrderingMixin): """The mother class.""" __slots__ = () @property def exploded(self): """Return the longhand version of the IP address as a string.""" return self._explode_shorthand_ip_string() @property def compressed(self): """Return the shorthand version of the IP address as a string.""" return _compat_str(self) @property def reverse_pointer(self): """The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer '1.0.0.127.in-addr.arpa' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa' """ return self._reverse_pointer() @property def version(self): msg = '%200s has no version specified' % (type(self),) raise NotImplementedError(msg) def _check_int_address(self, address): if address < 0: msg = "%d (< 0) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._version)) if address > self._ALL_ONES: msg = "%d (>= 2**%d) is not permitted as an IPv%d address" raise AddressValueError(msg % (address, self._max_prefixlen, self._version)) def _check_packed_address(self, address, expected_len): address_len = len(address) if address_len != expected_len: msg = ( '%r (len %d != %d) is not permitted as an IPv%d address. ' 'Did you pass in a bytes (str in Python 2) instead of' ' a unicode object?' ) raise AddressValueError(msg % (address, address_len, expected_len, self._version)) @classmethod def _ip_int_from_prefix(cls, prefixlen): """Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer. """ return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen) @classmethod def _prefix_from_ip_int(cls, ip_int): """Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones """ trailing_zeroes = _count_righthand_zero_bits(ip_int, cls._max_prefixlen) prefixlen = cls._max_prefixlen - trailing_zeroes leading_ones = ip_int >> trailing_zeroes all_ones = (1 << prefixlen) - 1 if leading_ones != all_ones: byteslen = cls._max_prefixlen // 8 details = _compat_to_bytes(ip_int, byteslen, 'big') msg = 'Netmask pattern %r mixes zeroes & ones' raise ValueError(msg % details) return prefixlen @classmethod def _report_invalid_netmask(cls, netmask_str): msg = '%r is not a valid netmask' % netmask_str raise NetmaskValueError(msg) @classmethod def _prefix_from_prefix_string(cls, prefixlen_str): """Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask """ # int allows a leading +/- as well as surrounding whitespace, # so we ensure that isn't the case if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): cls._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: cls._report_invalid_netmask(prefixlen_str) if not (0 <= prefixlen <= cls._max_prefixlen): cls._report_invalid_netmask(prefixlen_str) return prefixlen @classmethod def _prefix_from_ip_string(cls, ip_str): """Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask """ # Parse the netmask/hostmask like an IP address. try: ip_int = cls._ip_int_from_string(ip_str) except AddressValueError: cls._report_invalid_netmask(ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return cls._prefix_from_ip_int(ip_int) except ValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= cls._ALL_ONES try: return cls._prefix_from_ip_int(ip_int) except ValueError: cls._report_invalid_netmask(ip_str) def __reduce__(self): return self.__class__, (_compat_str(self),) class _BaseAddress(_IPAddressBase): """A generic IP object. This IP class contains the version independent methods which are used by single IP addresses. """ __slots__ = () def __int__(self): return self._ip def __eq__(self, other): try: return (self._ip == other._ip and self._version == other._version) except AttributeError: return NotImplemented def __lt__(self, other): if not isinstance(other, _IPAddressBase): return NotImplemented if not isinstance(other, _BaseAddress): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if self._ip != other._ip: return self._ip < other._ip return False # Shorthand for Integer addition and subtraction. This is not # meant to ever support addition/subtraction of addresses. def __add__(self, other): if not isinstance(other, _compat_int_types): return NotImplemented return self.__class__(int(self) + other) def __sub__(self, other): if not isinstance(other, _compat_int_types): return NotImplemented return self.__class__(int(self) - other) def __repr__(self): return '%s(%r)' % (self.__class__.__name__, _compat_str(self)) def __str__(self): return _compat_str(self._string_from_ip_int(self._ip)) def __hash__(self): return hash(hex(int(self._ip))) def _get_address_key(self): return (self._version, self) def __reduce__(self): return self.__class__, (self._ip,) class _BaseNetwork(_IPAddressBase): """A generic IP network object. This IP class contains the version independent methods which are used by networks. """ def __init__(self, address): self._cache = {} def __repr__(self): return '%s(%r)' % (self.__class__.__name__, _compat_str(self)) def __str__(self): return '%s/%d' % (self.network_address, self.prefixlen) def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the network or broadcast addresses. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in _compat_range(network + 1, broadcast): yield self._address_class(x) def __iter__(self): network = int(self.network_address) broadcast = int(self.broadcast_address) for x in _compat_range(network, broadcast + 1): yield self._address_class(x) def __getitem__(self, n): network = int(self.network_address) broadcast = int(self.broadcast_address) if n >= 0: if network + n > broadcast: raise IndexError return self._address_class(network + n) else: n += 1 if broadcast + n < network: raise IndexError return self._address_class(broadcast + n) def __lt__(self, other): if not isinstance(other, _IPAddressBase): return NotImplemented if not isinstance(other, _BaseNetwork): raise TypeError('%s and %s are not of the same type' % ( self, other)) if self._version != other._version: raise TypeError('%s and %s are not of the same version' % ( self, other)) if self.network_address != other.network_address: return self.network_address < other.network_address if self.netmask != other.netmask: return self.netmask < other.netmask return False def __eq__(self, other): try: return (self._version == other._version and self.network_address == other.network_address and int(self.netmask) == int(other.netmask)) except AttributeError: return NotImplemented def __hash__(self): return hash(int(self.network_address) ^ int(self.netmask)) def __contains__(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if isinstance(other, _BaseNetwork): return False # dealing with another address else: # address return (int(self.network_address) <= int(other._ip) <= int(self.broadcast_address)) def overlaps(self, other): """Tell if self is partly contained in other.""" return self.network_address in other or ( self.broadcast_address in other or ( other.network_address in self or ( other.broadcast_address in self))) @property def broadcast_address(self): x = self._cache.get('broadcast_address') if x is None: x = self._address_class(int(self.network_address) | int(self.hostmask)) self._cache['broadcast_address'] = x return x @property def hostmask(self): x = self._cache.get('hostmask') if x is None: x = self._address_class(int(self.netmask) ^ self._ALL_ONES) self._cache['hostmask'] = x return x @property def with_prefixlen(self): return '%s/%d' % (self.network_address, self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self.network_address, self.netmask) @property def with_hostmask(self): return '%s/%s' % (self.network_address, self.hostmask) @property def num_addresses(self): """Number of hosts in the current subnet.""" return int(self.broadcast_address) - int(self.network_address) + 1 @property def _address_class(self): # Returning bare address objects (rather than interfaces) allows for # more consistent behaviour across the network address, broadcast # address and individual host addresses. msg = '%200s has no associated address class' % (type(self),) raise NotImplementedError(msg) @property def prefixlen(self): return self._prefixlen def address_exclude(self, other): """Remove an address from a larger block. For example: addr1 = ip_network('192.0.2.0/28') addr2 = ip_network('192.0.2.1/32') addr1.address_exclude(addr2) = [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] or IPv6: addr1 = ip_network('2001:db8::1/32') addr2 = ip_network('2001:db8::1/128') addr1.address_exclude(addr2) = [ip_network('2001:db8::1/128'), ip_network('2001:db8::2/127'), ip_network('2001:db8::4/126'), ip_network('2001:db8::8/125'), ... ip_network('2001:db8:8000::/33')] Args: other: An IPv4Network or IPv6Network object of the same type. Returns: An iterator of the IPv(4|6)Network objects which is self minus other. Raises: TypeError: If self and other are of differing address versions, or if other is not a network object. ValueError: If other is not completely contained by self. """ if not self._version == other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) if not isinstance(other, _BaseNetwork): raise TypeError("%s is not a network object" % other) if not other.subnet_of(self): raise ValueError('%s not contained in %s' % (other, self)) if other == self: return # Make sure we're comparing the network of other. other = other.__class__('%s/%s' % (other.network_address, other.prefixlen)) s1, s2 = self.subnets() while s1 != other and s2 != other: if other.subnet_of(s1): yield s2 s1, s2 = s1.subnets() elif other.subnet_of(s2): yield s1 s1, s2 = s2.subnets() else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) if s1 == other: yield s2 elif s2 == other: yield s1 else: # If we got here, there's a bug somewhere. raise AssertionError('Error performing exclusion: ' 's1: %s s2: %s other: %s' % (s1, s2, other)) def compare_networks(self, other): """Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren't considered at all in this method. If you want to compare host bits, you can easily enough do a 'HostA._ip < HostB._ip' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') IPv6Network('2001:db8::1000/124') < IPv6Network('2001:db8::2000/124') 0 if self == other eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') IPv6Network('2001:db8::1000/124') == IPv6Network('2001:db8::1000/124') 1 if self > other eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') IPv6Network('2001:db8::2000/124') > IPv6Network('2001:db8::1000/124') Raises: TypeError if the IP versions are different. """ # does this need to raise a ValueError? if self._version != other._version: raise TypeError('%s and %s are not of the same type' % ( self, other)) # self._version == other._version below here: if self.network_address < other.network_address: return -1 if self.network_address > other.network_address: return 1 # self.network_address == other.network_address below here: if self.netmask < other.netmask: return -1 if self.netmask > other.netmask: return 1 return 0 def _get_networks_key(self): """Network-only key function. Returns an object that identifies this address' network and netmask. This function is a suitable "key" argument for sorted() and list.sort(). """ return (self._version, self.network_address, self.netmask) def subnets(self, prefixlen_diff=1, new_prefix=None): """The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network) """ if self._prefixlen == self._max_prefixlen: yield self return if new_prefix is not None: if new_prefix < self._prefixlen: raise ValueError('new prefix must be longer') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = new_prefix - self._prefixlen if prefixlen_diff < 0: raise ValueError('prefix length diff must be > 0') new_prefixlen = self._prefixlen + prefixlen_diff if new_prefixlen > self._max_prefixlen: raise ValueError( 'prefix length diff %d is invalid for netblock %s' % ( new_prefixlen, self)) start = int(self.network_address) end = int(self.broadcast_address) step = (int(self.hostmask) + 1) >> prefixlen_diff for new_addr in _compat_range(start, end, step): current = self.__class__((new_addr, new_prefixlen)) yield current def supernet(self, prefixlen_diff=1, new_prefix=None): """The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network) """ if self._prefixlen == 0: return self if new_prefix is not None: if new_prefix > self._prefixlen: raise ValueError('new prefix must be shorter') if prefixlen_diff != 1: raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = self._prefixlen - new_prefix new_prefixlen = self.prefixlen - prefixlen_diff if new_prefixlen < 0: raise ValueError( 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff)) return self.__class__(( int(self.network_address) & (int(self.netmask) << prefixlen_diff), new_prefixlen )) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return (self.network_address.is_multicast and self.broadcast_address.is_multicast) def subnet_of(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if (hasattr(other, 'network_address') and hasattr(other, 'broadcast_address')): return (other.network_address <= self.network_address and other.broadcast_address >= self.broadcast_address) # dealing with another address else: raise TypeError('Unable to test subnet containment with element ' 'of type %s' % type(other)) def supernet_of(self, other): # always false if one is v4 and the other is v6. if self._version != other._version: return False # dealing with another network. if (hasattr(other, 'network_address') and hasattr(other, 'broadcast_address')): return (other.network_address >= self.network_address and other.broadcast_address <= self.broadcast_address) # dealing with another address else: raise TypeError('Unable to test subnet containment with element ' 'of type %s' % type(other)) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return (self.network_address.is_reserved and self.broadcast_address.is_reserved) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return (self.network_address.is_link_local and self.broadcast_address.is_link_local) @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return (self.network_address.is_private and self.broadcast_address.is_private) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified) @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return (self.network_address.is_loopback and self.broadcast_address.is_loopback) class _BaseV4(object): """Base IPv4 object. The following methods are used by IPv4 objects in both single IP addresses and networks. """ __slots__ = () _version = 4 # Equivalent to 255.255.255.255 or 32 bits of 1's. _ALL_ONES = (2 ** IPV4LENGTH) - 1 _DECIMAL_DIGITS = frozenset('0123456789') # the valid octets for host and netmasks. only useful for IPv4. _valid_mask_octets = frozenset([255, 254, 252, 248, 240, 224, 192, 128, 0]) _max_prefixlen = IPV4LENGTH # There are only a handful of valid v4 netmasks, so we cache them all # when constructed (see _make_netmask()). _netmask_cache = {} def _explode_shorthand_ip_string(self): return _compat_str(self) @classmethod def _make_netmask(cls, arg): """Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0") """ if arg not in cls._netmask_cache: if isinstance(arg, _compat_int_types): prefixlen = arg else: try: # Check for a netmask in prefix length form prefixlen = cls._prefix_from_prefix_string(arg) except NetmaskValueError: # Check for a netmask or hostmask in dotted-quad form. # This may raise NetmaskValueError. prefixlen = cls._prefix_from_ip_string(arg) netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen)) cls._netmask_cache[arg] = netmask, prefixlen return cls._netmask_cache[arg] @classmethod def _ip_int_from_string(cls, ip_str): """Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn't a valid IPv4 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') octets = ip_str.split('.') if len(octets) != 4: raise AddressValueError("Expected 4 octets in %r" % ip_str) try: return _compat_int_from_byte_vals( map(cls._parse_octet, octets), 'big') except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) @classmethod def _parse_octet(cls, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not cls._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int @classmethod def _string_from_ip_int(cls, ip_int): """Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation. """ return '.'.join(_compat_str(struct.unpack(b'!B', b)[0] if isinstance(b, bytes) else b) for b in _compat_to_bytes(ip_int, 4, 'big')) def _is_hostmask(self, ip_str): """Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask. """ bits = ip_str.split('.') try: parts = [x for x in map(int, bits) if x in self._valid_mask_octets] except ValueError: return False if len(parts) != len(bits): return False if parts[0] < parts[-1]: return True return False def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5. """ reverse_octets = _compat_str(self).split('.')[::-1] return '.'.join(reverse_octets) + '.in-addr.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv4Address(_BaseV4, _BaseAddress): """Represent and manipulate single IPv4 Addresses.""" __slots__ = ('_ip', '__weakref__') def __init__(self, address): """ Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address('192.0.2.1') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address('192.0.2.1'))) == IPv4Address('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. """ # Efficient constructor from integer. if isinstance(address, _compat_int_types): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 4) bvs = _compat_bytes_to_byte_vals(address) self._ip = _compat_int_from_byte_vals(bvs, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = _compat_str(address) if '/' in addr_str: raise AddressValueError("Unexpected '/' in %r" % address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v4_int_to_packed(self._ip) @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range. """ return self in self._constants._reserved_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry. """ return any(self in net for net in self._constants._private_networks) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details. """ return self in self._constants._multicast_network @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3. """ return self == self._constants._unspecified_address @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330. """ return self in self._constants._loopback_network @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927. """ return self in self._constants._linklocal_network class IPv4Interface(IPv4Address): def __init__(self, address): if isinstance(address, (bytes, _compat_int_types)): IPv4Address.__init__(self, address) self.network = IPv4Network(self._ip) self._prefixlen = self._max_prefixlen return if isinstance(address, tuple): IPv4Address.__init__(self, address[0]) if len(address) > 1: self._prefixlen = int(address[1]) else: self._prefixlen = self._max_prefixlen self.network = IPv4Network(address, strict=False) self.netmask = self.network.netmask self.hostmask = self.network.hostmask return addr = _split_optional_netmask(address) IPv4Address.__init__(self, addr[0]) self.network = IPv4Network(address, strict=False) self._prefixlen = self.network._prefixlen self.netmask = self.network.netmask self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv4Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv4Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) __reduce__ = _IPAddressBase.__reduce__ @property def ip(self): return IPv4Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) class IPv4Network(_BaseV4, _BaseNetwork): """This class represents and manipulates 32-bit IPv4 network + addresses.. Attributes: [examples for IPv4Network('192.0.2.0/27')] .network_address: IPv4Address('192.0.2.0') .hostmask: IPv4Address('0.0.0.31') .broadcast_address: IPv4Address('192.0.2.32') .netmask: IPv4Address('255.255.255.224') .prefixlen: 27 """ # Class to use when creating address objects _address_class = IPv4Address def __init__(self, address, strict=True): """Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. '192.0.2.0/24' '192.0.2.0/255.255.255.0' '192.0.0.2/0.0.0.255' are all functionally the same in IPv4. Similarly, '192.0.2.1' '192.0.2.1/255.255.255.255' '192.0.2.1/32' are also functionally equivalent. That is to say, failing to provide a subnetmask will create an object with a mask of /32. If the mask (portion after the / in the argument) is given in dotted quad form, it is treated as a netmask if it starts with a non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it starts with a zero field (e.g. 0.255.255.255 == /8), with the single exception of an all-zero mask which is treated as a netmask == /0. If no mask is given, a default of /32 is used. Additionally, an integer can be passed, so IPv4Network('192.0.2.1') == IPv4Network(3221225985) or, more generally IPv4Interface(int(IPv4Interface('192.0.2.1'))) == IPv4Interface('192.0.2.1') Raises: AddressValueError: If ipaddress isn't a valid IPv4 address. NetmaskValueError: If the netmask isn't valid for an IPv4 address. ValueError: If strict is True and a network address is not supplied. """ _BaseNetwork.__init__(self, address) # Constructing from a packed address or integer if isinstance(address, (_compat_int_types, bytes)): self.network_address = IPv4Address(address) self.netmask, self._prefixlen = self._make_netmask( self._max_prefixlen) # fixme: address/network test here. return if isinstance(address, tuple): if len(address) > 1: arg = address[1] else: # We weren't given an address[1] arg = self._max_prefixlen self.network_address = IPv4Address(address[0]) self.netmask, self._prefixlen = self._make_netmask(arg) packed = int(self.network_address) if packed & int(self.netmask) != packed: if strict: raise ValueError('%s has host bits set' % self) else: self.network_address = IPv4Address(packed & int(self.netmask)) return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: arg = addr[1] else: arg = self._max_prefixlen self.netmask, self._prefixlen = self._make_netmask(arg) if strict: if (IPv4Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv4Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry. """ return (not (self.network_address in IPv4Network('100.64.0.0/10') and self.broadcast_address in IPv4Network('100.64.0.0/10')) and not self.is_private) class _IPv4Constants(object): _linklocal_network = IPv4Network('169.254.0.0/16') _loopback_network = IPv4Network('127.0.0.0/8') _multicast_network = IPv4Network('224.0.0.0/4') _private_networks = [ IPv4Network('0.0.0.0/8'), IPv4Network('10.0.0.0/8'), IPv4Network('127.0.0.0/8'), IPv4Network('169.254.0.0/16'), IPv4Network('172.16.0.0/12'), IPv4Network('192.0.0.0/29'), IPv4Network('192.0.0.170/31'), IPv4Network('192.0.2.0/24'), IPv4Network('192.168.0.0/16'), IPv4Network('198.18.0.0/15'), IPv4Network('198.51.100.0/24'), IPv4Network('203.0.113.0/24'), IPv4Network('240.0.0.0/4'), IPv4Network('255.255.255.255/32'), ] _reserved_network = IPv4Network('240.0.0.0/4') _unspecified_address = IPv4Address('0.0.0.0') IPv4Address._constants = _IPv4Constants class _BaseV6(object): """Base IPv6 object. The following methods are used by IPv6 objects in both single IP addresses and networks. """ __slots__ = () _version = 6 _ALL_ONES = (2 ** IPV6LENGTH) - 1 _HEXTET_COUNT = 8 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') _max_prefixlen = IPV6LENGTH # There are only a bunch of valid v6 netmasks, so we cache them all # when constructed (see _make_netmask()). _netmask_cache = {} @classmethod def _make_netmask(cls, arg): """Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0") """ if arg not in cls._netmask_cache: if isinstance(arg, _compat_int_types): prefixlen = arg else: prefixlen = cls._prefix_from_prefix_string(arg) netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen)) cls._netmask_cache[arg] = netmask, prefixlen return cls._netmask_cache[arg] @classmethod def _ip_int_from_string(cls, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ if not ip_str: raise AddressValueError('Address cannot be empty') parts = ip_str.split(':') # An IPv6 address needs at least 2 colons (3 parts). _min_parts = 3 if len(parts) < _min_parts: msg = "At least %d parts expected in %r" % (_min_parts, ip_str) raise AddressValueError(msg) # If the address has an IPv4-style suffix, convert it to hexadecimal. if '.' in parts[-1]: try: ipv4_int = IPv4Address(parts.pop())._ip except AddressValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) parts.append('%x' % (ipv4_int & 0xFFFF)) # An IPv6 address can't have more than 8 colons (9 parts). # The extra colon comes from using the "::" notation for a single # leading or trailing zero part. _max_parts = cls._HEXTET_COUNT + 1 if len(parts) > _max_parts: msg = "At most %d colons permitted in %r" % ( _max_parts - 1, ip_str) raise AddressValueError(msg) # Disregarding the endpoints, find '::' with nothing in between. # This indicates that a run of zeroes has been skipped. skip_index = None for i in _compat_range(1, len(parts) - 1): if not parts[i]: if skip_index is not None: # Can't have more than one '::' msg = "At most one '::' permitted in %r" % ip_str raise AddressValueError(msg) skip_index = i # parts_hi is the number of parts to copy from above/before the '::' # parts_lo is the number of parts to copy from below/after the '::' if skip_index is not None: # If we found a '::', then check if it also covers the endpoints. parts_hi = skip_index parts_lo = len(parts) - skip_index - 1 if not parts[0]: parts_hi -= 1 if parts_hi: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: parts_lo -= 1 if parts_lo: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo) if parts_skipped < 1: msg = "Expected at most %d other parts with '::' in %r" raise AddressValueError(msg % (cls._HEXTET_COUNT - 1, ip_str)) else: # Otherwise, allocate the entire address to parts_hi. The # endpoints could still be empty, but _parse_hextet() will check # for that. if len(parts) != cls._HEXTET_COUNT: msg = "Exactly %d parts expected without '::' in %r" raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str)) if not parts[0]: msg = "Leading ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # ^: requires ^:: if not parts[-1]: msg = "Trailing ':' only permitted as part of '::' in %r" raise AddressValueError(msg % ip_str) # :$ requires ::$ parts_hi = len(parts) parts_lo = 0 parts_skipped = 0 try: # Now, parse the hextets into a 128-bit integer. ip_int = 0 for i in range(parts_hi): ip_int <<= 16 ip_int |= cls._parse_hextet(parts[i]) ip_int <<= 16 * parts_skipped for i in range(-parts_lo, 0): ip_int <<= 16 ip_int |= cls._parse_hextet(parts[i]) return ip_int except ValueError as exc: raise AddressValueError("%s in %r" % (exc, ip_str)) @classmethod def _parse_hextet(cls, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not cls._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16) @classmethod def _compress_hextets(cls, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets: A list of strings, the hextets to compress. Returns: A list of strings. """ best_doublecolon_start = -1 best_doublecolon_len = 0 doublecolon_start = -1 doublecolon_len = 0 for index, hextet in enumerate(hextets): if hextet == '0': doublecolon_len += 1 if doublecolon_start == -1: # Start of a sequence of zeros. doublecolon_start = index if doublecolon_len > best_doublecolon_len: # This is the longest sequence of zeros so far. best_doublecolon_len = doublecolon_len best_doublecolon_start = doublecolon_start else: doublecolon_len = 0 doublecolon_start = -1 if best_doublecolon_len > 1: best_doublecolon_end = (best_doublecolon_start + best_doublecolon_len) # For zeros at the end of the address. if best_doublecolon_end == len(hextets): hextets += [''] hextets[best_doublecolon_start:best_doublecolon_end] = [''] # For zeros at the beginning of the address. if best_doublecolon_start == 0: hextets = [''] + hextets return hextets @classmethod def _string_from_ip_int(cls, ip_int=None): """Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones. """ if ip_int is None: ip_int = int(cls._ip) if ip_int > cls._ALL_ONES: raise ValueError('IPv6 address is too large') hex_str = '%032x' % ip_int hextets = ['%x' % int(hex_str[x:x + 4], 16) for x in range(0, 32, 4)] hextets = cls._compress_hextets(hextets) return ':'.join(hextets) def _explode_shorthand_ip_string(self): """Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address. """ if isinstance(self, IPv6Network): ip_str = _compat_str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = _compat_str(self.ip) else: ip_str = _compat_str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = '%032x' % ip_int parts = [hex_str[x:x + 4] for x in range(0, 32, 4)] if isinstance(self, (_BaseNetwork, IPv6Interface)): return '%s/%d' % (':'.join(parts), self._prefixlen) return ':'.join(parts) def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa' @property def max_prefixlen(self): return self._max_prefixlen @property def version(self): return self._version class IPv6Address(_BaseV6, _BaseAddress): """Represent and manipulate single IPv6 Addresses.""" __slots__ = ('_ip', '__weakref__') def __init__(self, address): """Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. """ # Efficient constructor from integer. if isinstance(address, _compat_int_types): self._check_int_address(address) self._ip = address return # Constructing from a packed address if isinstance(address, bytes): self._check_packed_address(address, 16) bvs = _compat_bytes_to_byte_vals(address) self._ip = _compat_int_from_byte_vals(bvs, 'big') return # Assume input argument to be string or any object representation # which converts into a formatted IP string. addr_str = _compat_str(address) if '/' in addr_str: raise AddressValueError("Unexpected '/' in %r" % address) self._ip = self._ip_int_from_string(addr_str) @property def packed(self): """The binary representation of this address.""" return v6_int_to_packed(self._ip) @property def is_multicast(self): """Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details. """ return self in self._constants._multicast_network @property def is_reserved(self): """Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges. """ return any(self in x for x in self._constants._reserved_networks) @property def is_link_local(self): """Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291. """ return self in self._constants._linklocal_network @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ return self in self._constants._sitelocal_network @property def is_private(self): """Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry. """ return any(self in net for net in self._constants._private_networks) @property def is_global(self): """Test if this address is allocated for public networks. Returns: A boolean, true if the address is not reserved per iana-ipv6-special-registry. """ return not self.is_private @property def is_unspecified(self): """Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2. """ return self._ip == 0 @property def is_loopback(self): """Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3. """ return self._ip == 1 @property def ipv4_mapped(self): """Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise. """ if (self._ip >> 32) != 0xFFFF: return None return IPv4Address(self._ip & 0xFFFFFFFF) @property def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF)) @property def sixtofour(self): """Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn't appear to contain a 6to4 embedded address. """ if (self._ip >> 112) != 0x2002: return None return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) class IPv6Interface(IPv6Address): def __init__(self, address): if isinstance(address, (bytes, _compat_int_types)): IPv6Address.__init__(self, address) self.network = IPv6Network(self._ip) self._prefixlen = self._max_prefixlen return if isinstance(address, tuple): IPv6Address.__init__(self, address[0]) if len(address) > 1: self._prefixlen = int(address[1]) else: self._prefixlen = self._max_prefixlen self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self.hostmask = self.network.hostmask return addr = _split_optional_netmask(address) IPv6Address.__init__(self, addr[0]) self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self._prefixlen = self.network._prefixlen self.hostmask = self.network.hostmask def __str__(self): return '%s/%d' % (self._string_from_ip_int(self._ip), self.network.prefixlen) def __eq__(self, other): address_equal = IPv6Address.__eq__(self, other) if not address_equal or address_equal is NotImplemented: return address_equal try: return self.network == other.network except AttributeError: # An interface with an associated network is NOT the # same as an unassociated address. That's why the hash # takes the extra info into account. return False def __lt__(self, other): address_less = IPv6Address.__lt__(self, other) if address_less is NotImplemented: return NotImplemented try: return self.network < other.network except AttributeError: # We *do* allow addresses and interfaces to be sorted. The # unassociated address is considered less than all interfaces. return False def __hash__(self): return self._ip ^ self._prefixlen ^ int(self.network.network_address) __reduce__ = _IPAddressBase.__reduce__ @property def ip(self): return IPv6Address(self._ip) @property def with_prefixlen(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self._prefixlen) @property def with_netmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.netmask) @property def with_hostmask(self): return '%s/%s' % (self._string_from_ip_int(self._ip), self.hostmask) @property def is_unspecified(self): return self._ip == 0 and self.network.is_unspecified @property def is_loopback(self): return self._ip == 1 and self.network.is_loopback class IPv6Network(_BaseV6, _BaseNetwork): """This class represents and manipulates 128-bit IPv6 networks. Attributes: [examples for IPv6('2001:db8::1000/124')] .network_address: IPv6Address('2001:db8::1000') .hostmask: IPv6Address('::f') .broadcast_address: IPv6Address('2001:db8::100f') .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') .prefixlen: 124 """ # Class to use when creating address objects _address_class = IPv6Address def __init__(self, address, strict=True): """Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. '2001:db8::/128' '2001:db8:0000:0000:0000:0000:0000:0000/128' '2001:db8::' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an object with a mask of /128. Additionally, an integer can be passed, so IPv6Network('2001:db8::') == IPv6Network(42540766411282592856903984951653826560) or, more generally IPv6Network(int(IPv6Network('2001:db8::'))) == IPv6Network('2001:db8::') strict: A boolean. If true, ensure that we have been passed A true network address, eg, 2001:db8::1000/124 and not an IP address on a network, eg, 2001:db8::1/124. Raises: AddressValueError: If address isn't a valid IPv6 address. NetmaskValueError: If the netmask isn't valid for an IPv6 address. ValueError: If strict was True and a network address was not supplied. """ _BaseNetwork.__init__(self, address) # Efficient constructor from integer or packed address if isinstance(address, (bytes, _compat_int_types)): self.network_address = IPv6Address(address) self.netmask, self._prefixlen = self._make_netmask( self._max_prefixlen) return if isinstance(address, tuple): if len(address) > 1: arg = address[1] else: arg = self._max_prefixlen self.netmask, self._prefixlen = self._make_netmask(arg) self.network_address = IPv6Address(address[0]) packed = int(self.network_address) if packed & int(self.netmask) != packed: if strict: raise ValueError('%s has host bits set' % self) else: self.network_address = IPv6Address(packed & int(self.netmask)) return # Assume input argument to be string or any object representation # which converts into a formatted IP prefix string. addr = _split_optional_netmask(address) self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) if len(addr) == 2: arg = addr[1] else: arg = self._max_prefixlen self.netmask, self._prefixlen = self._make_netmask(arg) if strict: if (IPv6Address(int(self.network_address) & int(self.netmask)) != self.network_address): raise ValueError('%s has host bits set' % self) self.network_address = IPv6Address(int(self.network_address) & int(self.netmask)) if self._prefixlen == (self._max_prefixlen - 1): self.hosts = self.__iter__ def hosts(self): """Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn't return the Subnet-Router anycast address. """ network = int(self.network_address) broadcast = int(self.broadcast_address) for x in _compat_range(network + 1, broadcast + 1): yield self._address_class(x) @property def is_site_local(self): """Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6. """ return (self.network_address.is_site_local and self.broadcast_address.is_site_local) class _IPv6Constants(object): _linklocal_network = IPv6Network('fe80::/10') _multicast_network = IPv6Network('ff00::/8') _private_networks = [ IPv6Network('::1/128'), IPv6Network('::/128'), IPv6Network('::ffff:0:0/96'), IPv6Network('100::/64'), IPv6Network('2001::/23'), IPv6Network('2001:2::/48'), IPv6Network('2001:db8::/32'), IPv6Network('2001:10::/28'), IPv6Network('fc00::/7'), IPv6Network('fe80::/10'), ] _reserved_networks = [ IPv6Network('::/8'), IPv6Network('100::/8'), IPv6Network('200::/7'), IPv6Network('400::/6'), IPv6Network('800::/5'), IPv6Network('1000::/4'), IPv6Network('4000::/3'), IPv6Network('6000::/3'), IPv6Network('8000::/3'), IPv6Network('A000::/3'), IPv6Network('C000::/3'), IPv6Network('E000::/4'), IPv6Network('F000::/5'), IPv6Network('F800::/6'), IPv6Network('FE00::/9'), ] _sitelocal_network = IPv6Network('fec0::/10') IPv6Address._constants = _IPv6Constants
apache-2.0
519,145,322,772,369,600
32.039818
86
0.568285
false
jancsarc/KIM-Online
src/accounts/views.py
1
2138
from __future__ import unicode_literals from django.core.urlresolvers import reverse_lazy from django.views import generic from django.shortcuts import redirect from django.contrib.auth import get_user_model from django.contrib import auth from django.contrib import messages from authtools import views as authviews from braces import views as bracesviews from django.conf import settings from . import forms User = get_user_model() class LoginView(bracesviews.AnonymousRequiredMixin, authviews.LoginView): template_name = "accounts/login.html" form_class = forms.LoginForm def form_valid(self, form): redirect = super(LoginView, self).form_valid(form) remember_me = form.cleaned_data.get('remember_me') if remember_me is True: ONE_MONTH = 30*24*60*60 expiry = getattr(settings, "KEEP_LOGGED_DURATION", ONE_MONTH) self.request.session.set_expiry(expiry) return redirect class LogoutView(authviews.LogoutView): url = reverse_lazy('home') class PasswordChangeView(authviews.PasswordChangeView): form_class = forms.PasswordChangeForm template_name = 'accounts/password-change.html' success_url = reverse_lazy('home') def form_valid(self, form): form.save() messages.success(self.request, "Your password was changed, " "hence you have been logged out. Please relogin") return redirect("home") class PasswordResetView(authviews.PasswordResetView): form_class = forms.PasswordResetForm template_name = 'accounts/password-reset.html' success_url = reverse_lazy('accounts:password-reset-done') subject_template_name = 'accounts/emails/password-reset-subject.txt' email_template_name = 'accounts/emails/password-reset-email.html' class PasswordResetDoneView(authviews.PasswordResetDoneView): template_name = 'accounts/password-reset-done.html' class PasswordResetConfirmView(authviews.PasswordResetConfirmAndLoginView): template_name = 'accounts/password-reset-confirm.html' form_class = forms.SetPasswordForm
mit
3,617,738,547,562,631,000
34.04918
75
0.721235
false
ibinti/intellij-community
python/lib/Lib/site-packages/django/utils/itercompat.py
294
1169
""" Providing iterator functions that are not in all version of Python we support. Where possible, we try to use the system-native version and only fall back to these implementations if necessary. """ import itertools # Fallback for Python 2.4, Python 2.5 def product(*args, **kwds): """ Taken from http://docs.python.org/library/itertools.html#itertools.product """ # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) if hasattr(itertools, 'product'): product = itertools.product def is_iterable(x): "A implementation independent way of checking for iterables" try: iter(x) except TypeError: return False else: return True def all(iterable): for item in iterable: if not item: return False return True def any(iterable): for item in iterable: if item: return True return False
apache-2.0
3,406,856,339,700,060,700
24.977778
78
0.635586
false