repo_name
stringlengths
5
100
path
stringlengths
4
254
copies
stringlengths
1
5
size
stringlengths
4
7
content
stringlengths
681
1M
license
stringclasses
15 values
hash
int64
-9,223,351,895,964,839,000
9,223,298,349B
line_mean
float64
3.5
100
line_max
int64
15
1k
alpha_frac
float64
0.25
0.97
autogenerated
bool
1 class
ratio
float64
1.5
8.15
config_test
bool
2 classes
has_no_keywords
bool
2 classes
few_assignments
bool
1 class
johndpope/tensorflow
tensorflow/tensorboard/backend/application.py
24
26886
# 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. # ============================================================================== """TensorBoard WSGI Application Logic. TensorBoardApplication constructs TensorBoard as a WSGI application. It handles serving static assets, and implements TensorBoard data APIs. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import imghdr import mimetypes import os import re import threading import time import six from six import StringIO from six.moves import urllib from six.moves import xrange # pylint: disable=redefined-builtin from six.moves.urllib import parse as urlparse from werkzeug import wrappers from tensorflow.python.platform import resource_loader from tensorflow.python.platform import tf_logging as logging from tensorflow.tensorboard.backend import http_util from tensorflow.tensorboard.backend import process_graph from tensorflow.tensorboard.backend.event_processing import event_accumulator from tensorflow.tensorboard.backend.event_processing import event_multiplexer DEFAULT_SIZE_GUIDANCE = { event_accumulator.COMPRESSED_HISTOGRAMS: 500, event_accumulator.IMAGES: 10, event_accumulator.AUDIO: 10, event_accumulator.SCALARS: 1000, event_accumulator.HEALTH_PILLS: 100, event_accumulator.HISTOGRAMS: 50, } DATA_PREFIX = '/data' LOGDIR_ROUTE = '/logdir' RUNS_ROUTE = '/runs' PLUGIN_PREFIX = '/plugin' PLUGINS_LISTING_ROUTE = '/plugins_listing' SCALARS_ROUTE = '/' + event_accumulator.SCALARS IMAGES_ROUTE = '/' + event_accumulator.IMAGES AUDIO_ROUTE = '/' + event_accumulator.AUDIO HISTOGRAMS_ROUTE = '/' + event_accumulator.HISTOGRAMS COMPRESSED_HISTOGRAMS_ROUTE = '/' + event_accumulator.COMPRESSED_HISTOGRAMS INDIVIDUAL_IMAGE_ROUTE = '/individualImage' INDIVIDUAL_AUDIO_ROUTE = '/individualAudio' GRAPH_ROUTE = '/' + event_accumulator.GRAPH RUN_METADATA_ROUTE = '/' + event_accumulator.RUN_METADATA TAB_ROUTES = ['', '/events', '/images', '/audio', '/graphs', '/histograms'] _IMGHDR_TO_MIMETYPE = { 'bmp': 'image/bmp', 'gif': 'image/gif', 'jpeg': 'image/jpeg', 'png': 'image/png' } _DEFAULT_IMAGE_MIMETYPE = 'application/octet-stream' def _content_type_for_image(encoded_image_string): image_type = imghdr.what(None, encoded_image_string) return _IMGHDR_TO_MIMETYPE.get(image_type, _DEFAULT_IMAGE_MIMETYPE) class _OutputFormat(object): """An enum used to list the valid output formats for API calls. Not all API calls support all formats (for example, only scalars and compressed histograms support CSV). """ JSON = 'json' CSV = 'csv' def standard_tensorboard_wsgi( logdir, purge_orphaned_data, reload_interval, plugins): """Construct a TensorBoardWSGIApp with standard plugins and multiplexer. Args: logdir: The path to the directory containing events files. purge_orphaned_data: Whether to purge orphaned data. reload_interval: The interval at which the backend reloads more data in seconds. plugins: A list of plugins for TensorBoard to initialize. Returns: The new TensorBoard WSGI application. """ multiplexer = event_multiplexer.EventMultiplexer( size_guidance=DEFAULT_SIZE_GUIDANCE, purge_orphaned_data=purge_orphaned_data) return TensorBoardWSGIApp(logdir, plugins, multiplexer, reload_interval) class TensorBoardWSGIApp(object): """The TensorBoard application, conforming to WSGI spec.""" # How many samples to include in sampling API calls by default. DEFAULT_SAMPLE_COUNT = 10 # NOTE TO MAINTAINERS: An accurate Content-Length MUST be specified on all # responses using send_header. protocol_version = 'HTTP/1.1' def __init__(self, logdir, plugins, multiplexer, reload_interval): """Constructs the TensorBoard application. Args: logdir: the logdir spec that describes where data will be loaded. may be a directory, or comma,separated list of directories, or colons can be used to provide named directories plugins: List of plugins that extend tensorboard.plugins.BasePlugin multiplexer: The EventMultiplexer with TensorBoard data to serve reload_interval: How often (in seconds) to reload the Multiplexer Returns: A WSGI application that implements the TensorBoard backend. Raises: ValueError: If some plugin has no plugin_name ValueError: If two plugins have the same plugin_name """ self._logdir = logdir self._plugins = plugins self._multiplexer = multiplexer self.tag = get_tensorboard_tag() path_to_run = parse_event_files_spec(self._logdir) if reload_interval: start_reloading_multiplexer(self._multiplexer, path_to_run, reload_interval) else: reload_multiplexer(self._multiplexer, path_to_run) self.data_applications = { '/app.js': self._serve_js, DATA_PREFIX + AUDIO_ROUTE: self._serve_audio, DATA_PREFIX + COMPRESSED_HISTOGRAMS_ROUTE: self._serve_compressed_histograms, DATA_PREFIX + GRAPH_ROUTE: self._serve_graph, DATA_PREFIX + HISTOGRAMS_ROUTE: self._serve_histograms, DATA_PREFIX + IMAGES_ROUTE: self._serve_images, DATA_PREFIX + INDIVIDUAL_AUDIO_ROUTE: self._serve_individual_audio, DATA_PREFIX + INDIVIDUAL_IMAGE_ROUTE: self._serve_image, DATA_PREFIX + LOGDIR_ROUTE: self._serve_logdir, # TODO(chizeng): Delete this RPC once we have skylark rules that obviate # the need for the frontend to determine which plugins are active. DATA_PREFIX + PLUGINS_LISTING_ROUTE: self._serve_plugins_listing, DATA_PREFIX + RUN_METADATA_ROUTE: self._serve_run_metadata, DATA_PREFIX + RUNS_ROUTE: self._serve_runs, DATA_PREFIX + SCALARS_ROUTE: self._serve_scalars, } # Serve the routes from the registered plugins using their name as the route # prefix. For example if plugin z has two routes /a and /b, they will be # served as /data/plugin/z/a and /data/plugin/z/b. plugin_names_encountered = set() for plugin in self._plugins: if plugin.plugin_name is None: raise ValueError('Plugin %s has no plugin_name' % plugin) if plugin.plugin_name in plugin_names_encountered: raise ValueError('Duplicate plugins for name %s' % plugin.plugin_name) plugin_names_encountered.add(plugin.plugin_name) try: plugin_apps = plugin.get_plugin_apps(self._multiplexer, self._logdir) except Exception as e: # pylint: disable=broad-except logging.warning('Plugin %s failed. Exception: %s', plugin.plugin_name, str(e)) continue for route, app in plugin_apps.items(): path = DATA_PREFIX + PLUGIN_PREFIX + '/' + plugin.plugin_name + route self.data_applications[path] = app # We use underscore_names for consistency with inherited methods. def _image_response_for_run(self, run_images, run, tag): """Builds a JSON-serializable object with information about run_images. Args: run_images: A list of event_accumulator.ImageValueEvent objects. run: The name of the run. tag: The name of the tag the images all belong to. Returns: A list of dictionaries containing the wall time, step, URL, width, and height for each image. """ response = [] for index, run_image in enumerate(run_images): response.append({ 'wall_time': run_image.wall_time, 'step': run_image.step, # We include the size so that the frontend can add that to the <img> # tag so that the page layout doesn't change when the image loads. 'width': run_image.width, 'height': run_image.height, 'query': self._query_for_individual_image(run, tag, index) }) return response def _audio_response_for_run(self, run_audio, run, tag): """Builds a JSON-serializable object with information about run_audio. Args: run_audio: A list of event_accumulator.AudioValueEvent objects. run: The name of the run. tag: The name of the tag the images all belong to. Returns: A list of dictionaries containing the wall time, step, URL, and content_type for each audio clip. """ response = [] for index, run_audio_clip in enumerate(run_audio): response.append({ 'wall_time': run_audio_clip.wall_time, 'step': run_audio_clip.step, 'content_type': run_audio_clip.content_type, 'query': self._query_for_individual_audio(run, tag, index) }) return response def _path_is_safe(self, path): """Check path is safe (stays within current directory). This is for preventing directory-traversal attacks. Args: path: The path to check for safety. Returns: True if the given path stays within the current directory, and false if it would escape to a higher directory. E.g. _path_is_safe('index.html') returns true, but _path_is_safe('../../../etc/password') returns false. """ base = os.path.abspath(os.curdir) absolute_path = os.path.abspath(path) prefix = os.path.commonprefix([base, absolute_path]) return prefix == base @wrappers.Request.application def _serve_logdir(self, request): """Respond with a JSON object containing this TensorBoard's logdir.""" return http_util.Respond( request, {'logdir': self._logdir}, 'application/json') @wrappers.Request.application def _serve_scalars(self, request): """Given a tag and single run, return array of ScalarEvents.""" # TODO(cassandrax): return HTTP status code for malformed requests tag = request.args.get('tag') run = request.args.get('run') values = self._multiplexer.Scalars(run, tag) if request.args.get('format') == _OutputFormat.CSV: string_io = StringIO() writer = csv.writer(string_io) writer.writerow(['Wall time', 'Step', 'Value']) writer.writerows(values) return http_util.Respond(request, string_io.getvalue(), 'text/csv') else: return http_util.Respond(request, values, 'application/json') @wrappers.Request.application def _serve_graph(self, request): """Given a single run, return the graph definition in json format.""" run = request.args.get('run', None) if run is None: return http_util.Respond( request, 'query parameter "run" is required', 'text/plain', 400) try: graph = self._multiplexer.Graph(run) except ValueError: return http_util.Respond( request, '404 Not Found', 'text/plain; charset=UTF-8', code=404) limit_attr_size = request.args.get('limit_attr_size', None) if limit_attr_size is not None: try: limit_attr_size = int(limit_attr_size) except ValueError: return http_util.Respond( request, 'query parameter `limit_attr_size` must be integer', 'text/plain', 400) large_attrs_key = request.args.get('large_attrs_key', None) try: process_graph.prepare_graph_for_ui(graph, limit_attr_size, large_attrs_key) except ValueError as e: return http_util.Respond(request, e.message, 'text/plain', 400) return http_util.Respond(request, str(graph), 'text/x-protobuf') # pbtxt @wrappers.Request.application def _serve_run_metadata(self, request): """Given a tag and a TensorFlow run, return the session.run() metadata.""" tag = request.args.get('tag', None) run = request.args.get('run', None) if tag is None: return http_util.Respond( request, 'query parameter "tag" is required', 'text/plain', 400) if run is None: return http_util.Respond( request, 'query parameter "run" is required', 'text/plain', 400) try: run_metadata = self._multiplexer.RunMetadata(run, tag) except ValueError: return http_util.Respond( request, '404 Not Found', 'text/plain; charset=UTF-8', code=404) return http_util.Respond( request, str(run_metadata), 'text/x-protobuf') # pbtxt @wrappers.Request.application def _serve_histograms(self, request): """Given a tag and single run, return an array of histogram values.""" tag = request.args.get('tag') run = request.args.get('run') values = self._multiplexer.Histograms(run, tag) return http_util.Respond(request, values, 'application/json') @wrappers.Request.application def _serve_compressed_histograms(self, request): """Given a tag and single run, return an array of compressed histograms.""" tag = request.args.get('tag') run = request.args.get('run') compressed_histograms = self._multiplexer.CompressedHistograms(run, tag) if request.args.get('format') == _OutputFormat.CSV: string_io = StringIO() writer = csv.writer(string_io) # Build the headers; we have two columns for timing and two columns for # each compressed histogram bucket. headers = ['Wall time', 'Step'] if compressed_histograms: bucket_count = len(compressed_histograms[0].compressed_histogram_values) for i in xrange(bucket_count): headers += ['Edge %d basis points' % i, 'Edge %d value' % i] writer.writerow(headers) for compressed_histogram in compressed_histograms: row = [compressed_histogram.wall_time, compressed_histogram.step] for value in compressed_histogram.compressed_histogram_values: row += [value.rank_in_bps, value.value] writer.writerow(row) return http_util.Respond(request, string_io.getvalue(), 'text/csv') else: return http_util.Respond( request, compressed_histograms, 'application/json') @wrappers.Request.application def _serve_images(self, request): """Given a tag and list of runs, serve a list of images. Note that the images themselves are not sent; instead, we respond with URLs to the images. The frontend should treat these URLs as opaque and should not try to parse information about them or generate them itself, as the format may change. Args: request: A werkzeug.wrappers.Request object. Returns: A werkzeug.Response application. """ tag = request.args.get('tag') run = request.args.get('run') images = self._multiplexer.Images(run, tag) response = self._image_response_for_run(images, run, tag) return http_util.Respond(request, response, 'application/json') @wrappers.Request.application def _serve_image(self, request): """Serves an individual image.""" tag = request.args.get('tag') run = request.args.get('run') index = int(request.args.get('index')) image = self._multiplexer.Images(run, tag)[index] encoded_image_string = image.encoded_image_string content_type = _content_type_for_image(encoded_image_string) return http_util.Respond(request, encoded_image_string, content_type) def _query_for_individual_image(self, run, tag, index): """Builds a URL for accessing the specified image. This should be kept in sync with _serve_image. Note that the URL is *not* guaranteed to always return the same image, since images may be unloaded from the reservoir as new images come in. Args: run: The name of the run. tag: The tag. index: The index of the image. Negative values are OK. Returns: A string representation of a URL that will load the index-th sampled image in the given run with the given tag. """ query_string = urllib.parse.urlencode({ 'run': run, 'tag': tag, 'index': index }) return query_string @wrappers.Request.application def _serve_audio(self, request): """Given a tag and list of runs, serve a list of audio. Note that the audio clips themselves are not sent; instead, we respond with URLs to the audio. The frontend should treat these URLs as opaque and should not try to parse information about them or generate them itself, as the format may change. Args: request: A werkzeug.wrappers.Request object. Returns: A werkzeug.Response application. """ tag = request.args.get('tag') run = request.args.get('run') audio_list = self._multiplexer.Audio(run, tag) response = self._audio_response_for_run(audio_list, run, tag) return http_util.Respond(request, response, 'application/json') @wrappers.Request.application def _serve_individual_audio(self, request): """Serves an individual audio clip.""" tag = request.args.get('tag') run = request.args.get('run') index = int(request.args.get('index')) audio = self._multiplexer.Audio(run, tag)[index] return http_util.Respond( request, audio.encoded_audio_string, audio.content_type) def _query_for_individual_audio(self, run, tag, index): """Builds a URL for accessing the specified audio. This should be kept in sync with _serve_individual_audio. Note that the URL is *not* guaranteed to always return the same audio, since audio may be unloaded from the reservoir as new audio comes in. Args: run: The name of the run. tag: The tag. index: The index of the audio. Negative values are OK. Returns: A string representation of a URL that will load the index-th sampled audio in the given run with the given tag. """ query_string = urllib.parse.urlencode({ 'run': run, 'tag': tag, 'index': index }) return query_string @wrappers.Request.application def _serve_plugins_listing(self, request): """Serves an object mapping plugin name to whether it is enabled. Args: request: The werkzeug.Request object. Returns: A werkzeug.Response object. """ return http_util.Respond( request, {plugin.plugin_name: plugin.is_active() for plugin in self._plugins}, 'application/json') @wrappers.Request.application def _serve_runs(self, request): """WSGI app serving a JSON object about runs and tags. Returns a mapping from runs to tagType to list of tags for that run. Args: request: A werkzeug request Returns: A werkzeug Response with the following content: {runName: {images: [tag1, tag2, tag3], audio: [tag4, tag5, tag6], scalars: [tagA, tagB, tagC], histograms: [tagX, tagY, tagZ], firstEventTimestamp: 123456.789}} """ runs = self._multiplexer.Runs() for run_name, run_data in runs.items(): try: run_data['firstEventTimestamp'] = self._multiplexer.FirstEventTimestamp( run_name) except ValueError: logging.warning('Unable to get first event timestamp for run %s', run_name) run_data['firstEventTimestamp'] = None return http_util.Respond(request, runs, 'application/json') @wrappers.Request.application def _serve_index(self, request): """Serves the index page (i.e., the tensorboard app itself).""" return self._serve_static_file(request, '/dist/index.html') @wrappers.Request.application def _serve_js(self, request): """Serves the JavaScript for the index page.""" return self._serve_static_file(request, '/dist/app.js') def _serve_static_file(self, request, path): """Serves the static file located at the given path. Args: request: A werkzeug Request path: The path of the static file, relative to the tensorboard/ directory. Returns: A werkzeug.Response application. """ # Strip off the leading forward slash. orig_path = path.lstrip('/') if not self._path_is_safe(orig_path): logging.warning('path not safe: %s', orig_path) return http_util.Respond(request, 'Naughty naughty!', 'text/plain', 400) # Resource loader wants a path relative to //WORKSPACE/tensorflow. path = os.path.join('tensorboard', orig_path) # Open the file and read it. try: contents = resource_loader.load_resource(path) except IOError: # For compatibility with latest version of Bazel, we renamed bower # packages to use '_' rather than '-' in their package name. # This means that the directory structure is changed too. # So that all our recursive imports work, we need to modify incoming # requests to map onto the new directory structure. path = orig_path components = path.split('/') components[0] = components[0].replace('-', '_') path = ('/').join(components) # Bazel keeps all the external dependencies in //WORKSPACE/external. # and resource loader wants a path relative to //WORKSPACE/tensorflow/. path = os.path.join('../external', path) try: contents = resource_loader.load_resource(path) except IOError: logging.warning('path %s not found, sending 404', path) return http_util.Respond(request, 'Not found', 'text/plain', code=404) mimetype, content_encoding = mimetypes.guess_type(path) mimetype = mimetype or 'application/octet-stream' return http_util.Respond( request, contents, mimetype, expires=3600, content_encoding=content_encoding) def __call__(self, environ, start_response): # pylint: disable=invalid-name """Central entry point for the TensorBoard application. This method handles routing to sub-applications. It does simple routing using regular expression matching. This __call__ method conforms to the WSGI spec, so that instances of this class are WSGI applications. Args: environ: See WSGI spec. start_response: See WSGI spec. Returns: A werkzeug Response. """ request = wrappers.Request(environ) parsed_url = urlparse.urlparse(request.path) # Remove a trailing slash, if present. clean_path = parsed_url.path if clean_path.endswith('/'): clean_path = clean_path[:-1] # pylint: disable=too-many-function-args if clean_path in self.data_applications: return self.data_applications[clean_path](environ, start_response) elif clean_path in TAB_ROUTES: return self._serve_index(environ, start_response) else: return self._serve_static_file(request, clean_path)(environ, start_response) # pylint: enable=too-many-function-args def parse_event_files_spec(logdir): """Parses `logdir` into a map from paths to run group names. The events files flag format is a comma-separated list of path specifications. A path specification either looks like 'group_name:/path/to/directory' or '/path/to/directory'; in the latter case, the group is unnamed. Group names cannot start with a forward slash: /foo:bar/baz will be interpreted as a spec with no name and path '/foo:bar/baz'. Globs are not supported. Args: logdir: A comma-separated list of run specifications. Returns: A dict mapping directory paths to names like {'/path/to/directory': 'name'}. Groups without an explicit name are named after their path. If logdir is None, returns an empty dict, which is helpful for testing things that don't require any valid runs. """ files = {} if logdir is None: return files # Make sure keeping consistent with ParseURI in core/lib/io/path.cc uri_pattern = re.compile('[a-zA-Z][0-9a-zA-Z.]*://.*') for specification in logdir.split(','): # Check if the spec contains group. A spec start with xyz:// is regarded as # URI path spec instead of group spec. If the spec looks like /foo:bar/baz, # then we assume it's a path with a colon. if (uri_pattern.match(specification) is None and ':' in specification and specification[0] != '/'): # We split at most once so run_name:/path:with/a/colon will work. run_name, _, path = specification.partition(':') else: run_name = None path = specification if uri_pattern.match(path) is None: path = os.path.realpath(path) files[path] = run_name return files def reload_multiplexer(multiplexer, path_to_run): """Loads all runs into the multiplexer. Args: multiplexer: The `EventMultiplexer` to add runs to and reload. path_to_run: A dict mapping from paths to run names, where `None` as the run name is interpreted as a run name equal to the path. """ start = time.time() logging.info('TensorBoard reload process beginning') for (path, name) in six.iteritems(path_to_run): multiplexer.AddRunsFromDirectory(path, name) logging.info('TensorBoard reload process: Reload the whole Multiplexer') multiplexer.Reload() duration = time.time() - start logging.info('TensorBoard done reloading. Load took %0.3f secs', duration) def start_reloading_multiplexer(multiplexer, path_to_run, load_interval): """Starts a thread to automatically reload the given multiplexer. The thread will reload the multiplexer by calling `ReloadMultiplexer` every `load_interval` seconds, starting immediately. Args: multiplexer: The `EventMultiplexer` to add runs to and reload. path_to_run: A dict mapping from paths to run names, where `None` as the run name is interpreted as a run name equal to the path. load_interval: How many seconds to wait after one load before starting the next load. Returns: A started `threading.Thread` that reloads the multiplexer. """ # We don't call multiplexer.Reload() here because that would make # AddRunsFromDirectory block until the runs have all loaded. def _reload_forever(): while True: reload_multiplexer(multiplexer, path_to_run) time.sleep(load_interval) thread = threading.Thread(target=_reload_forever) thread.daemon = True thread.start() return thread def get_tensorboard_tag(): """Read the TensorBoard TAG number, and return it or an empty string.""" tag = resource_loader.load_resource('tensorboard/TAG').strip() return tag
apache-2.0
-6,497,820,005,484,346,000
35.931319
80
0.673734
false
3.919242
false
false
false
slandis/InkCutter
inkcutter/app/bin/device.py
1
3171
#!/usr/bin/env python # InkCutter, Plot HPGL directly from Inkscape. # device.py # # Copyright 2010 Jairus Martin <frmdstryr@gmail.com> # Copyright 2013 Shaun Landis <slandis@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. import serial from lxml import etree import os if os.name != 'nt': import cups class Device: def __init__(self,config={}): #self.xml = etree.parse(filename).getroot() conf = {'width':0,'length':0,'name':'','interface':'serial','serial':{'port':'/dev/ttyUSB0','baud':9600}} conf.update(config) self.width = conf['width'] self.length = conf['length'] self.name = conf['name'] self.interface = conf['interface'] self.serial = conf['serial'] def getPrinters(self): con = cups.Connection() printers = con.getPrinters() self.printers = printers def save(self,id,attribs): # save settings to xml dev = self.xml.find('device[@id="%s"]'%id) err = [] # delete if exists? if len(dev): del dev[0] else: dev = etree.SubElement(self.xml,'device') dev.set('id',id) iface = etree.SubElement(d, "interface") for key,value in attribs.iteritems(): iface.set(key,value) def plot(self,filename): def toSerial(data,settings): assert type(data) == str, "input data must be a str type" import serial # set default settings set = {'baud':9600} set.update(settings); #create serial and set settings ser = serial.Serial() ser.baudrate = set['baud'] ser.port = set['port'] ser.open() if ser.isOpen(): #send data & return bits sent bits = ser.write(data); ser.close(); return True; else: return False; def toPrinter(data,printer): assert type(data) == str, "input data must be a str type" assert type(printer) == str, "printer name must be a string" printer = os.popen('lpr -P %s'%(printer),'w') printer.write(data) printer.close() return True; def toUSBPrinter(data,printer): assert type(data) == str, "input data must be a str type" assert type(printer) == str, "printer name must be a string" p = open(printer, 'w+') p.write(data) p.close() return True; f=open(filename,'r') if self.interface=='printer': toPrinter(f.read(),self.name) elif self.interface=='usb printer': toUSBPrinter(f.read(),self.name) elif self.interface=='serial': toSerial(f.read(),self.serial) else: raise AssertionError('Invalid interface type, only printers and serial connections are supported.')
gpl-3.0
8,242,678,511,675,439,000
26.336207
107
0.674866
false
3.239019
false
false
false
HackerTool/vivisect
vstruct/defs/pcap.py
2
16024
import vstruct import vstruct.defs.inet as vs_inet from vstruct.primitives import * PCAP_LINKTYPE_ETHER = 1 PCAP_LINKTYPE_RAW = 101 PCAPNG_BOM = 0x1A2B3C4D OPT_ENDOFOPT = 0 OPT_COMMENT = 1 #PCAPNG_BLOCKTYPE_SECTION_HEADER options OPT_SHB_HARDWARE = 2 OPT_SHB_OS = 3 OPT_SHB_USERAPPL = 4 #PCAPNG_INTERFACE_DESCRIPTION_BLOCK options OPT_IF_NAME = 2 OPT_IF_DESCRIPTION = 3 OPT_IF_IPV4ADDR = 4 OPT_IF_IPV6ADDR = 5 OPT_IF_MACADDR = 6 OPT_IF_EUIADDR = 7 OPT_IF_SPEED = 8 OPT_IF_TSRESOL = 9 OPT_IF_TZONE = 10 OPT_IF_FILTER = 11 OPT_IF_OS = 12 OPT_IF_FCSLEN = 13 OPT_IF_TSOFFSET = 14 # options for PCAPNG_ENHANCED_PACKET_BLOCK OPT_EPB_FLAGS = 2 OPT_EPB_HASH = 3 OPT_EPB_DROPCOUNT = 4 # values used in the blocktype field PCAPNG_BLOCKTYPE_INTERFACE_DESCRIPTION = 0x00000001 PCAPNG_BLOCKTYPE_PACKET = 0x00000002 PCAPNG_BLOCKTYPE_SIMPLE_PACKET = 0x00000003 PCAPNG_BLOCKTYPE_NAME_RESOLUTION = 0x00000004 PCAPNG_BLOCKTYPE_INTERFACE_STATS = 0x00000005 PCAPNG_BLOCKTYPE_ENHANCED_PACKET = 0x00000006 PCAPNG_BLOCKTYPE_SECTION_HEADER = 0x0a0d0d0a def pad4bytes(size): if (size % 4) == 0: return size return size + (4 -( size % 4)) class PCAP_FILE_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.magic = v_uint32() self.vers_maj = v_uint16() self.vers_min = v_uint16() self.thiszone = v_uint32() self.sigfigs = v_uint32() self.snaplen = v_uint32() self.linktype = v_uint32() class PCAP_PACKET_HEADER(vstruct.VStruct): def __init__(self): vstruct.VStruct.__init__(self) self.tvsec = v_uint32() self.tvusec = v_uint32() self.caplen = v_uint32() self.len = v_uint32() class PCAPNG_GENERIC_BLOCK_HEADER(vstruct.VStruct): ''' Used to read the block type & size when parsing the file ''' def __init__(self, bigend=False): vstruct.VStruct.__init__(self) self.blocktype = v_uint32(bigend=bigend) self.blocksize = v_uint32(bigend=bigend) class PCAPNG_BLOCK_PARENT(vstruct.VStruct): ''' Used to inherit the weird parsing style where there's variable length options at the end, followed by the duplicate block total length ''' def __init__(self, bigend=False): vstruct.VStruct.__init__(self) #non-vstruct field, set during checking BOM self.bigend = False def vsParse(self, bytez, offset=0): startoff = offset roff = vstruct.VStruct.vsParse(self, bytez, offset=offset) #(blocksize-4): because we still need the trailing blocksize2 # apparently blocks can completely omit the options list and not # even have the OPT_ENDOFOPT entry while (roff < len(bytez)) and ((roff-startoff) < (self.blocksize-4)): opt = PCAPNG_OPTION(bigend=self.bigend) roff = opt.vsParse(bytez, roff) if opt.code == OPT_ENDOFOPT: break self.options.vsAddElement(opt) # append trailing blocksize2 bs2 = v_uint32(bigend=self.bigend) self.vsAddField('blocksize2', bs2) roff = bs2.vsParse(bytez, roff) #pad, plus we skip return pad4bytes(roff) class PCAPNG_SECTION_HEADER_BLOCK(PCAPNG_BLOCK_PARENT): def __init__(self, bigend=False): PCAPNG_BLOCK_PARENT.__init__(self, bigend) self.blocktype = v_uint32(bigend=bigend) self.blocksize = v_uint32(bigend=bigend) self.bom = v_uint32(bigend=bigend) self.vers_maj = v_uint16(bigend=bigend) self.vers_min = v_uint16(bigend=bigend) self.sectionsize = v_uint64(bigend=bigend) self.options = vstruct.VArray([]) #blocksize2: dynamcally added in vsParse() #self.blocksize2 = v_uint32(bigend=bigend) def pcb_bom(self): bom = self.vsGetField('bom') if self.bom == PCAPNG_BOM: #if it matches, then the endian of bom is correct self.bigend = bom._vs_bigend else: self.bigend = not bom._vs_bigend class PCAPNG_OPTION(vstruct.VStruct): def __init__(self, bigend=False): vstruct.VStruct.__init__(self) self.code = v_uint16(bigend=bigend) self.optsize = v_uint16(bigend=bigend) self.bytes = v_bytes(0) def pcb_optsize(self): size = pad4bytes(self.optsize) self.vsGetField('bytes').vsSetLength(size) class PCAPNG_INTERFACE_DESCRIPTION_BLOCK(PCAPNG_BLOCK_PARENT): def __init__(self, bigend=False): PCAPNG_BLOCK_PARENT.__init__(self, bigend) self.blocktype = v_uint32(bigend=bigend) self.blocksize = v_uint32(bigend=bigend) self.linktype = v_uint16(bigend=bigend) self.reserved = v_uint16(bigend=bigend) self.snaplen = v_uint32(bigend=bigend) self.options = vstruct.VArray([]) #blocksize2: dynamcally added in vsParse() #self.blocksize2 = v_uint32(bigend=bigend) def vsParse(self, bytez, offset=0): ''' We need the tsresol value to adjust timestamp values, so pull it out here ''' ret = PCAPNG_BLOCK_PARENT.vsParse(self, bytez, offset=0) self.tsresol = None #default offset is 0 self.tsoffset = 0 #sys.stderr.write('PCAPNG_INTERFACE_DESCRIPTION_BLOCK: searching options') for i, opt in self.options: if opt.code == OPT_IF_TSRESOL: self.tsresol = ord(opt.bytes[0]) #sys.stderr.write('Got tsresol: 0x%x\n' % self.tsresol) elif opt.code == OPT_IF_TSOFFSET: fmt = '<Q' if self.bigend: fmt = '>Q' self.tsoffset = struct.unpack_from(fmt, opt.bytes)[0] #sys.stderr.write('Got tsoffset: 0x%x\n' % self.tsoffset) return ret class PCAPNG_ENHANCED_PACKET_BLOCK(PCAPNG_BLOCK_PARENT): def __init__(self, bigend=False): PCAPNG_BLOCK_PARENT.__init__(self, bigend) self.blocktype = v_uint32(bigend=bigend) self.blocksize = v_uint32(bigend=bigend) self.interfaceid = v_uint32(bigend=bigend) self.tstamphi = v_uint32(bigend=bigend) self.tstamplow = v_uint32(bigend=bigend) self.caplen = v_uint32(bigend=bigend) self.packetlen = v_uint32(bigend=bigend) self.data = v_bytes(0) self.options = vstruct.VArray([]) #blocksize2: dynamcally added in vsParse() #self.blocksize2 = v_uint32(bigend=bigend) def pcb_caplen(self): size = pad4bytes(self.caplen) self.vsGetField('data').vsSetLength(size) def setPcapTimestamp(self, idb): ''' Adds a libpcap compatible tvsec and tvusec fields, based on the pcapng timestamp ''' #orange left off here self.snaplen = idb.snaplen tstamp = (self.tstamphi << 32) | self.tstamplow scale = 1000000 if idb.tsresol is None: #if not set, capture assumes 10e-6 resolution pass elif (0x80 & idb.tsresol) == 0: # remaining bits are resolution, to a negative power of 10 scale = 10**(idb.tsresol & 0x7f) else: # remaining bits are resolution, to a negative power of 2 scale = 1 << (idb.tsresol & 0x7f) self.tvsec = (tstamp / scale) + idb.tsoffset self.tvusec = tstamp % scale class PCAPNG_SIMPLE_PACKET_BLOCK(vstruct.VStruct): ''' Note: no variable length options fields, so inheriting from vstruct directly ''' def __init__(self, bigend=False): vstruct.VStruct.__init__(self) self.blocktype = v_uint32(bigend=bigend) self.blocksize = v_uint32(bigend=bigend) self.packetlen = v_uint32(bigend=bigend) self.data = v_bytes(0) self.blocksize2 = v_uint32(bigend=bigend) def pcb_blocksize(self): self.caplen = pad4bytes(self.blocksize - 16) self.vsGetField('data').vsSetLength(self.caplen) def setPcapTimestamp(self, idb): #no timestamp in this type of block :( self.tvsec = idb.tsoffset self.tvusec = 0 def iterPcapFileName(filename, reuse=False): fd = file(filename, 'rb') for x in iterPcapFile(fd, reuse=reuse): yield x def iterPcapFile(fd, reuse=False): ''' Figure out if it's a tcpdump format, or pcapng ''' h = PCAP_FILE_HEADER() b = fd.read(len(h)) h.vsParse(b, fast=True) fd.seek(0) if h.magic == PCAPNG_BLOCKTYPE_SECTION_HEADER: return _iterPcapNgFile(fd, reuse) return _iterPcapFile(fd, reuse) def _iterPcapFile(fd, reuse=False): h = PCAP_FILE_HEADER() b = fd.read(len(h)) h.vsParse(b, fast=True) linktype = h.linktype if linktype not in (PCAP_LINKTYPE_ETHER, PCAP_LINKTYPE_RAW): raise Exception('PCAP Link Type %d Not Supported Yet!' % linktype) pkt = PCAP_PACKET_HEADER() eII = vs_inet.ETHERII() pktsize = len(pkt) eIIsize = len(eII) ipv4 = vs_inet.IPv4() ipv4size = 20 tcp_hdr = vs_inet.TCP() udp_hdr = vs_inet.UDP() icmp_hdr = vs_inet.ICMP() go = True while go: hdr = fd.read(pktsize) if len(hdr) != pktsize: break pkt.vsParse(hdr, fast=True) b = fd.read(pkt.caplen) offset = 0 if linktype == PCAP_LINKTYPE_ETHER: if len(b) < eIIsize: continue eII.vsParse(b, 0, fast=True) # No support for non-ip protocol yet... if eII.etype not in (vs_inet.ETH_P_IP,vs_inet.ETH_P_VLAN): continue offset += eIIsize if eII.etype == vs_inet.ETH_P_VLAN: offset += 4 elif linktype == PCAP_LINKTYPE_RAW: pass #print eII.tree() if not reuse: ipv4 = vs_inet.IPv4() if (len(b) - offset) < ipv4size: continue ipv4.vsParse(b, offset, fast=True) # Make b *only* the IP datagram bytes... b = b[offset:offset+ipv4.totlen] offset = 0 offset += len(ipv4) tsize = len(b) - offset if ipv4.proto == vs_inet.IPPROTO_TCP: if tsize < 20: continue if not reuse: tcp_hdr = vs_inet.TCP() tcp_hdr.vsParse(b, offset, fast=True) offset += len(tcp_hdr) pdata = b[offset:] yield pkt,ipv4,tcp_hdr,pdata elif ipv4.proto == vs_inet.IPPROTO_UDP: if tsize < 8: continue if not reuse: udp_hdr = vs_inet.UDP() udp_hdr.vsParse(b, offset, fast=True) offset += len(udp_hdr) pdata = b[offset:] yield pkt,ipv4,udp_hdr,pdata elif ipv4.proto == vs_inet.IPPROTO_ICMP: if tsize < 4: continue if not reuse: icmp_hdr = vs_inet.ICMP() icmp_hdr.vsParse(b, offset, fast=True) offset += len(icmp_hdr) pdata = b[offset:] yield pkt,ipv4,icmp_hdr,pdata else: pass #print 'UNHANDLED IP PROTOCOL: %d' % ipv4.proto def _iterPcapNgFile(fd, reuse=False): header = PCAPNG_GENERIC_BLOCK_HEADER() ifaceidx = 0 ifacedict = {} roff = 0 bigend = False curroff = fd.tell() b0 = fd.read(len(header)) fd.seek(curroff) while len(b0) == len(header): header.vsParse(b0, fast=True) body = fd.read(header.blocksize) if header.blocktype == PCAPNG_BLOCKTYPE_SECTION_HEADER: shb = PCAPNG_SECTION_HEADER_BLOCK() roff = shb.vsParse(body) bigend = shb.bigend #reset interface stuff since we're in a new section ifaceidx = 0 ifacedict = {} elif header.blocktype == PCAPNG_BLOCKTYPE_INTERFACE_DESCRIPTION: idb = PCAPNG_INTERFACE_DESCRIPTION_BLOCK(bigend) roff = idb.vsParse(body) #save off the interface for later reference ifacedict[ifaceidx] = idb ifaceidx += 1 elif header.blocktype == PCAPNG_BLOCKTYPE_SIMPLE_PACKET: spb = PCAPNG_SIMPLE_PACKET_BLOCK(bigend) roff = spb.vsParse(body) tup = _parsePcapngPacketBytes(iface.linktype, spb) if tup is not None: #if it is None, just fall through & read next block yield tup elif header.blocktype == PCAPNG_BLOCKTYPE_ENHANCED_PACKET: epb = PCAPNG_ENHANCED_PACKET_BLOCK(bigend) roff = epb.vsParse(body) iface = ifacedict.get(epb.interfaceid) epb.setPcapTimestamp(iface) tup = _parsePcapngPacketBytes(iface.linktype, epb) if tup is not None: #if tup is None, just fall through & read next block yield tup #TODO: other blocks needed? #PCAPNG_BLOCKTYPE_PACKET (obsolete) #PCAPNG_BLOCKTYPE_NAME_RESOLUTION: #PCAPNG_BLOCKTYPE_INTERFACE_STATS: else: #print 'Unknown block type: 0x%08x: 0x%08x 0x%08x bytes' % (roff, header.blocktype, header.blocksize) pass curroff = fd.tell() b0 = fd.read(len(header)) fd.seek(curroff) def _parsePcapngPacketBytes(linktype, pkt): ''' pkt is either a parsed PCAPNG_SIMPLE_PACKET_BLOCK or PCAPNG_ENHANCED_PACKET_BLOCK On success Returns tuple (pcapng_pkt, ipv4_vstruct, transport_vstruc, pdata) Returns None if the packet can't be parsed ''' if linktype not in (PCAP_LINKTYPE_ETHER, PCAP_LINKTYPE_RAW): raise Exception('PCAP Link Type %d Not Supported Yet!' % linktype) #pkt = PCAP_PACKET_HEADER() eII = vs_inet.ETHERII() eIIsize = len(eII) offset = 0 if linktype == PCAP_LINKTYPE_ETHER: if len(pkt.data) < eIIsize: return None eII.vsParse(pkt.data, 0, fast=True) # No support for non-ip protocol yet... if eII.etype not in (vs_inet.ETH_P_IP,vs_inet.ETH_P_VLAN): return None offset += eIIsize if eII.etype == vs_inet.ETH_P_VLAN: offset += 4 elif linktype == PCAP_LINKTYPE_RAW: pass ipv4 = vs_inet.IPv4() if (len(pkt.data) - offset) < len(ipv4): return None ipv4.vsParse(pkt.data, offset, fast=True) # Make b *only* the IP datagram bytes... b = pkt.data[offset:offset+ipv4.totlen] offset = 0 offset += len(ipv4) tsize = len(b) - offset if ipv4.proto == vs_inet.IPPROTO_TCP: if tsize < 20: return None tcp_hdr = vs_inet.TCP() tcp_hdr.vsParse(b, offset, fast=True) offset += len(tcp_hdr) pdata = b[offset:] return pkt,ipv4,tcp_hdr,pdata elif ipv4.proto == vs_inet.IPPROTO_UDP: if tsize < 8: return None udp_hdr = vs_inet.UDP() udp_hdr.vsParse(b, offset, fast=True) offset += len(udp_hdr) pdata = b[offset:] return pkt,ipv4,udp_hdr,pdata elif ipv4.proto == vs_inet.IPPROTO_ICMP: if tsize < 4: return None icmp_hdr = vs_inet.ICMP() icmp_hdr.vsParse(b, offset, fast=True) offset += len(icmp_hdr) pdata = b[offset:] return pkt,ipv4,icmp_hdr,pdata else: pass #print 'UNHANDLED IP PROTOCOL: %d' % ipv4.proto return None
apache-2.0
-2,379,434,446,897,924,000
31.503043
113
0.569958
false
3.328625
false
false
false
nemobis/BEIC
METS_fileSec_validator.py
1
1331
#!/usr/bin/python # -*- coding: utf-8 -*- """ Extractor to validate a METS file and check the existence and content of the files linked from each fileSec/fileGrp/file/FLocat tag, assumed to contain an MD5 checksum. The "md5sum" utility is required. """ # # (C) Federico Leva and Fondazione BEIC, 2018 # # Distributed under the terms of the MIT license. # __version__ = '0.1.0' from lxml import etree import os import subprocess # http://lxml.de/validation.html parser = etree.XMLParser(dtd_validation=True) digest = open('mets.md5sum', 'w') for dirpath, dirnames, filenames in os.walk('.'): for filename in [ each for each in filenames if each.endswith('.xml') ]: xml = os.path.join(dirpath, filename) try: mets = etree.parse(open(xml, 'r')) files = mets.xpath('//*[local-name()="file"]') for item in files: content = item.xpath( './*[local-name()="FLocat"]/@xlink:href', namespaces={"xlink": "http://www.w3.org/1999/xlink"} )[0] checksum = item.xpath('./@CHECKSUM')[0] digest.write("%s %s\n" % (checksum, os.path.normpath(os.path.join(dirpath, content)) ) ) except: pass check = subprocess.call(["md5sum", "-c", "--status", "mets.md5sum"]) if check == 0: print("SUCCESS: The METS content has been verified correctly.") else: print("ERROR: The checksum validation has failed.")
mit
3,287,267,885,847,843,000
31.463415
93
0.670173
false
3.05977
false
false
false
wizzomafizzo/flairbot
flairbot.py
1
5950
#!/usr/bin/env python3 """Reddit bot for updating user flairs via PM requests""" import sys import re import os import time import logging import logging.handlers import praw import OAuth2Util from config import cfg def setup_logging(): """Configure logging module for rotating logs and console output""" rotate_cfg = { "filename": cfg["log_file"], "maxBytes": 1024*1000, "backupCount": 5 } rotate_fmt = "%(asctime)s %(levelname)-8s %(message)s" console_fmt = "%(levelname)-8s %(message)s" if cfg["debug"]: level = logging.DEBUG else: level = logging.INFO logger = logging.getLogger() logger.setLevel(level) rotate = logging.handlers.RotatingFileHandler(**rotate_cfg) rotate.setFormatter(logging.Formatter(rotate_fmt)) logger.addHandler(rotate) console = logging.StreamHandler() console.setLevel(level) console.setFormatter(logging.Formatter(console_fmt)) logger.addHandler(console) def parse_wiki_flairs(content): regex = re.compile(cfg["wiki_format"]) matches = [] for line in content.splitlines(): match = regex.match(line) if match is not None: flair = match.groups() matches.append(flair[0]) return matches class FlairBot: def __init__(self): user_agent = cfg["user_agent"] % (cfg["version"], cfg["subreddit"]) self.r = praw.Reddit(user_agent=user_agent) self.o = OAuth2Util.OAuth2Util(self.r) self.processed = 0 self.flairs = [] self.login() def login(self): """Start a new reddit session""" logging.info("Logging in...") try: self.o.refresh() except: logging.exception("Login failed") sys.exit(1) def get_requests(self): """Fetch and return all new PMs matching configured subject""" logging.info("Fetching new messages...") pending = [] try: msgs = self.r.get_unread(limit=None) except: logging.exception("Failed to get new messages") return for msg in msgs: logging.debug(msg) if str(msg.subject) == cfg["subject"]: pending.append(msg) if not cfg["limit_read"]: msg.mark_as_read() pending.reverse() logging.info("Got %i new requests", len(pending)) return pending def process_request(self, subreddit, msg): """Read flair request message and set if possible""" user = str(msg.author) flair = str(msg.body) if user in cfg["blacklist"]: logging.warning("Skipping blacklisted user: %s", user) return if flair in self.flairs: try: subreddit.set_flair(user, "", flair) except: logging.exception("Error setting flair to %s for %s", flair, user) return self.processed += 1 logging.info("Flair changed to %s for %s", flair, user) try: self.r.send_message(user, cfg["msg_subject"], cfg["msg_success"] % (flair)) except: logging.exception("Error messaging user") else: logging.warning("Flair %s requested by %s doesn't exist", flair, user) wiki = "https://www.reddit.com/r/%s/wiki/%s" % (cfg["subreddit"], cfg["wiki_page"]) try: self.r.send_message(user, cfg["msg_subject"], cfg["msg_failure"] % (flair, wiki)) except: logging.exception("Error messaging user") if cfg["limit_read"]: msg.mark_as_read() def get_wiki_page(self, subreddit): logging.info("Fetching wiki page...") if not os.path.exists(cfg["cache_file"]): logging.warning("No cache file found") modified = 0 else: stat = os.stat(cfg["cache_file"]) modified = int(stat.st_mtime) now = int(time.time()) if modified > 0 and now - modified < cfg["cache_time"]: cache = open(cfg["cache_file"], "r") logging.debug("Using valid cache") wiki_page = cache.read() cache.close() return wiki_page try: logging.debug("Updating cache") wiki_page = subreddit.get_wiki_page(cfg["wiki_page"]).content_md except (praw.errors.NotFound): logging.error("Wiki page %s doesn't exist", cfg["wiki_page"]) return cache = open(cfg["cache_file"], "w") logging.debug("Writing cache") cache.write(wiki_page) cache.close() return wiki_page def run(self): """Process all new flair requests""" try: requests = self.get_requests() except (praw.errors.HTTPException): logging.error("OAuth access is invalid") return subreddit = self.r.get_subreddit(cfg["subreddit"]) wiki_page = self.get_wiki_page(subreddit) if wiki_page is None: return self.flairs = parse_wiki_flairs(wiki_page) logging.debug(self.flairs) if requests is None: logging.info("No new messages to process") return for msg in requests: self.process_request(subreddit, msg) setup_logging() if __name__ == "__main__": flair_bot = FlairBot() logging.info("Starting new run...") flair_bot.run() logging.info("Run complete! Processed %i requests.", flair_bot.processed)
mit
-8,983,526,375,439,880,000
28.455446
77
0.534118
false
4.225852
false
false
false
dllsf/odootest
addons/auth_signup/controllers/main.py
165
6011
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2012-today OpenERP SA (<http://www.openerp.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/> # ############################################################################## import logging import werkzeug import openerp from openerp.addons.auth_signup.res_users import SignupError from openerp.addons.web.controllers.main import ensure_db from openerp import http from openerp.http import request from openerp.tools.translate import _ _logger = logging.getLogger(__name__) class AuthSignupHome(openerp.addons.web.controllers.main.Home): @http.route() def web_login(self, *args, **kw): ensure_db() response = super(AuthSignupHome, self).web_login(*args, **kw) response.qcontext.update(self.get_auth_signup_config()) if request.httprequest.method == 'GET' and request.session.uid and request.params.get('redirect'): # Redirect if already logged in and redirect param is present return http.redirect_with_hash(request.params.get('redirect')) return response @http.route('/web/signup', type='http', auth='public', website=True) def web_auth_signup(self, *args, **kw): qcontext = self.get_auth_signup_qcontext() if not qcontext.get('token') and not qcontext.get('signup_enabled'): raise werkzeug.exceptions.NotFound() if 'error' not in qcontext and request.httprequest.method == 'POST': try: self.do_signup(qcontext) return super(AuthSignupHome, self).web_login(*args, **kw) except (SignupError, AssertionError), e: qcontext['error'] = _(e.message) return request.render('auth_signup.signup', qcontext) @http.route('/web/reset_password', type='http', auth='public', website=True) def web_auth_reset_password(self, *args, **kw): qcontext = self.get_auth_signup_qcontext() if not qcontext.get('token') and not qcontext.get('reset_password_enabled'): raise werkzeug.exceptions.NotFound() if 'error' not in qcontext and request.httprequest.method == 'POST': try: if qcontext.get('token'): self.do_signup(qcontext) return super(AuthSignupHome, self).web_login(*args, **kw) else: login = qcontext.get('login') assert login, "No login provided." res_users = request.registry.get('res.users') res_users.reset_password(request.cr, openerp.SUPERUSER_ID, login) qcontext['message'] = _("An email has been sent with credentials to reset your password") except SignupError: qcontext['error'] = _("Could not reset your password") _logger.exception('error when resetting password') except Exception, e: qcontext['error'] = _(e.message) return request.render('auth_signup.reset_password', qcontext) def get_auth_signup_config(self): """retrieve the module config (which features are enabled) for the login page""" icp = request.registry.get('ir.config_parameter') return { 'signup_enabled': icp.get_param(request.cr, openerp.SUPERUSER_ID, 'auth_signup.allow_uninvited') == 'True', 'reset_password_enabled': icp.get_param(request.cr, openerp.SUPERUSER_ID, 'auth_signup.reset_password') == 'True', } def get_auth_signup_qcontext(self): """ Shared helper returning the rendering context for signup and reset password """ qcontext = request.params.copy() qcontext.update(self.get_auth_signup_config()) if qcontext.get('token'): try: # retrieve the user info (name, login or email) corresponding to a signup token res_partner = request.registry.get('res.partner') token_infos = res_partner.signup_retrieve_info(request.cr, openerp.SUPERUSER_ID, qcontext.get('token')) for k, v in token_infos.items(): qcontext.setdefault(k, v) except: qcontext['error'] = _("Invalid signup token") return qcontext def do_signup(self, qcontext): """ Shared helper that creates a res.partner out of a token """ values = dict((key, qcontext.get(key)) for key in ('login', 'name', 'password')) assert any([k for k in values.values()]), "The form was not properly filled in." assert values.get('password') == qcontext.get('confirm_password'), "Passwords do not match; please retype them." self._signup_with_values(qcontext.get('token'), values) request.cr.commit() def _signup_with_values(self, token, values): db, login, password = request.registry['res.users'].signup(request.cr, openerp.SUPERUSER_ID, values, token) request.cr.commit() # as authenticate will use its own cursor we need to commit the current transaction uid = request.session.authenticate(db, login, password) if not uid: raise SignupError(_('Authentification Failed.')) # vim:expandtab:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
-4,256,783,637,298,582,000
46.330709
126
0.622359
false
4.162742
false
false
false
pkexcellent/luigi
examples/elasticsearch_index.py
57
3399
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import datetime import json import luigi from luigi.contrib.esindex import CopyToIndex class FakeDocuments(luigi.Task): """ Generates a local file containing 5 elements of data in JSON format. """ #: the date parameter. date = luigi.DateParameter(default=datetime.date.today()) def run(self): """ Writes data in JSON format into the task's output target. The data objects have the following attributes: * `_id` is the default Elasticsearch id field, * `text`: the text, * `date`: the day when the data was created. """ today = datetime.date.today() with self.output().open('w') as output: for i in range(5): output.write(json.dumps({'_id': i, 'text': 'Hi %s' % i, 'date': str(today)})) output.write('\n') def output(self): """ Returns the target output for this task. In this case, a successful execution of this task will create a file on the local filesystem. :return: the target output for this task. :rtype: object (:py:class:`luigi.target.Target`) """ return luigi.LocalTarget(path='/tmp/_docs-%s.ldj' % self.date) class IndexDocuments(CopyToIndex): """ This task loads JSON data contained in a :py:class:`luigi.target.Target` into an ElasticSearch index. This task's input will the target returned by :py:meth:`~.FakeDocuments.output`. This class uses :py:meth:`luigi.contrib.esindex.CopyToIndex.run`. After running this task you can run: .. code-block:: console $ curl "localhost:9200/example_index/_search?pretty" to see the indexed documents. To see the update log, run .. code-block:: console $ curl "localhost:9200/update_log/_search?q=target_index:example_index&pretty" To cleanup both indexes run: .. code-block:: console $ curl -XDELETE "localhost:9200/example_index" $ curl -XDELETE "localhost:9200/update_log/_query?q=target_index:example_index" """ #: date task parameter (default = today) date = luigi.DateParameter(default=datetime.date.today()) #: the name of the index in ElasticSearch to be updated. index = 'example_index' #: the name of the document type. doc_type = 'greetings' #: the host running the ElasticSearch service. host = 'localhost' #: the port used by the ElasticSearch service. port = 9200 def requires(self): """ This task's dependencies: * :py:class:`~.FakeDocuments` :return: object (:py:class:`luigi.task.Task`) """ return FakeDocuments() if __name__ == "__main__": luigi.run(['--task', 'IndexDocuments'])
apache-2.0
-6,298,217,546,386,609,000
28.556522
105
0.639894
false
4.041617
false
false
false
therealfakemoot/collections2
collections2/dicts.py
2
2578
from collections import MutableMapping class OrderedDict(MutableMapping): '''OrderedDict is a mapping object that allows for ordered access and insertion of keys. With the exception of the key_index, insert, and reorder_keys methods behavior is identical to stock dictionary objects.''' def __init__(self, items=None): '''OrderedDict accepts an optional iterable of two-tuples indicating keys and values.''' self._d = dict() self._keys = [] if items is None: return for key, value in items: self[key] = value def __len__(self): return len(self._d) def __iter__(self): for key in self._keys: yield key def __setitem__(self, key, value): if key not in self._keys: self._keys.append(key) self._d[key] = value def __getitem__(self, key): return self._d[key] def __delitem__(self, key): self._keys.remove(key) del self._d[key] def key_index(self, key): '''Accepts a parameter, :key:, and returns an integer value representing its index in the ordered list of keys.''' return self._keys.index(key) def insert(self, key, value, index): '''Accepts a :key:, :value:, and :index: parameter and inserts a new key, value member at the desired index. Note: Inserting with a negative index will have the following behavior: >>> l = [1, 2, 3, 4] >>> l.insert(-1, 5) >>> l [1, 2, 3, 5, 4] ''' if key in self._keys: self._keys.remove(key) self._keys.insert(index, key) self._d[key] = value def reorder_keys(self, keys): '''Accepts a :keys: parameter, an iterable of keys in the desired new order. The :keys: parameter must contain all existing keys.''' if len(keys) != len(self._keys): raise ValueError('The supplied number of keys does not match.') if set(keys) != set(self._d.keys()): raise ValueError('The supplied keys do not match the current set of keys.') self._keys = keys def __repr__(self): return str([(key, self[key]) for key in self]) def __eq__(self, other): if not isinstance(other, OrderedDict): return False return self.items() == other.items() def keys(self): """Return a copy of the _keys list instead of iterating over it as the MutableMapping does by default. """ return list(self._keys)
mit
-4,717,889,050,585,243,000
30.439024
110
0.576804
false
4.212418
false
false
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
4.209352
false
false
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
4.679039
false
false
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
3.907389
true
false
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
4.277548
false
false
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
3.985954
false
false
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
4.08722
false
false
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
3.827569
true
false
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
4.304734
false
false
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
4.030374
false
false
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
3.429497
false
false
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
4.453382
false
false
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
4.193846
false
false
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
4.304838
false
false
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
3.65738
false
false
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
3.986376
false
false
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
2.579051
false
false
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
4.005908
false
false
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
4.711864
true
false
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
4.751159
false
false
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
3.515106
false
false
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
3.735051
false
false
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
3.865746
true
false
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
3.719296
true
false
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
3.817669
false
false
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
4.181951
false
false
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
4.312444
false
false
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
4.011905
false
false
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
2.916798
false
false
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
3.595294
false
false
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
3.870879
false
false
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
4.087671
true
false
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
4.076456
false
false
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
3.8822
false
false
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
4.200396
false
false
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
4.215901
false
false
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
3.054598
true
false
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
3.737932
false
false
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
3.810169
false
false
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
4.135141
false
false
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
3.666667
false
false
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
3.160731
false
false
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
4.033571
false
false
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
3.51845
false
false
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
2.859873
false
false
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
2.945494
false
false
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
3.54798
false
false
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
4.005571
false
false
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
4.091375
false
false
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
4.078014
false
false
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
4.252066
false
false
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
3.775717
true
false
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
3.841226
false
false
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
2.468117
true
false
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
4.412698
false
false
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
3.885046
false
false
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
3.160396
false
false
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
3.917399
false
false
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
4.427318
false
false
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
4.639416
false
false
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
4.416667
false
false
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
4.349835
false
false
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
3.893052
false
false
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
3.85527
false
false
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
4.971142
false
false
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
4.379059
false
false
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
3.667845
false
false
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
4.177627
false
false
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
3.981378
false
false
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
3.795455
false
false
false
fritsvanveen/QGIS
python/ext-libs/pygments/formatters/html.py
21
31759
# -*- coding: utf-8 -*- """ pygments.formatters.html ~~~~~~~~~~~~~~~~~~~~~~~~ Formatter for HTML output. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from __future__ import print_function import os import sys import os.path from pygments.formatter import Formatter from pygments.token import Token, Text, STANDARD_TYPES from pygments.util import get_bool_opt, get_int_opt, get_list_opt, \ StringIO, string_types, iteritems try: import ctags except ImportError: ctags = None __all__ = ['HtmlFormatter'] _escape_html_table = { ord('&'): u'&amp;', ord('<'): u'&lt;', ord('>'): u'&gt;', ord('"'): u'&quot;', ord("'"): u'&#39;', } def escape_html(text, table=_escape_html_table): """Escape &, <, > as well as single and double quotes for HTML.""" return text.translate(table) def _get_ttype_class(ttype): fname = STANDARD_TYPES.get(ttype) if fname: return fname aname = '' while fname is None: aname = '-' + ttype[-1] + aname ttype = ttype.parent fname = STANDARD_TYPES.get(ttype) return fname + aname CSSFILE_TEMPLATE = '''\ td.linenos { background-color: #f0f0f0; padding-right: 10px; } span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } pre { line-height: 125%%; } %(styledefs)s ''' DOC_HEADER = '''\ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>%(title)s</title> <meta http-equiv="content-type" content="text/html; charset=%(encoding)s"> <style type="text/css"> ''' + CSSFILE_TEMPLATE + ''' </style> </head> <body> <h2>%(title)s</h2> ''' DOC_HEADER_EXTERNALCSS = '''\ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>%(title)s</title> <meta http-equiv="content-type" content="text/html; charset=%(encoding)s"> <link rel="stylesheet" href="%(cssfile)s" type="text/css"> </head> <body> <h2>%(title)s</h2> ''' DOC_FOOTER = '''\ </body> </html> ''' class HtmlFormatter(Formatter): r""" Format tokens as HTML 4 ``<span>`` tags within a ``<pre>`` tag, wrapped in a ``<div>`` tag. The ``<div>``'s CSS class can be set by the `cssclass` option. If the `linenos` option is set to ``"table"``, the ``<pre>`` is additionally wrapped inside a ``<table>`` which has one row and two cells: one containing the line numbers and one containing the code. Example: .. sourcecode:: html <div class="highlight" > <table><tr> <td class="linenos" title="click to toggle" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"> <pre>1 2</pre> </td> <td class="code"> <pre><span class="Ke">def </span><span class="NaFu">foo</span>(bar): <span class="Ke">pass</span> </pre> </td> </tr></table></div> (whitespace added to improve clarity). Wrapping can be disabled using the `nowrap` option. A list of lines can be specified using the `hl_lines` option to make these lines highlighted (as of Pygments 0.11). With the `full` option, a complete HTML 4 document is output, including the style definitions inside a ``<style>`` tag, or in a separate file if the `cssfile` option is given. When `tagsfile` is set to the path of a ctags index file, it is used to generate hyperlinks from names to their definition. You must enable `lineanchors` and run ctags with the `-n` option for this to work. The `python-ctags` module from PyPI must be installed to use this feature; otherwise a `RuntimeError` will be raised. The `get_style_defs(arg='')` method of a `HtmlFormatter` returns a string containing CSS rules for the CSS classes used by the formatter. The argument `arg` can be used to specify additional CSS selectors that are prepended to the classes. A call `fmter.get_style_defs('td .code')` would result in the following CSS classes: .. sourcecode:: css td .code .kw { font-weight: bold; color: #00FF00 } td .code .cm { color: #999999 } ... If you have Pygments 0.6 or higher, you can also pass a list or tuple to the `get_style_defs()` method to request multiple prefixes for the tokens: .. sourcecode:: python formatter.get_style_defs(['div.syntax pre', 'pre.syntax']) The output would then look like this: .. sourcecode:: css div.syntax pre .kw, pre.syntax .kw { font-weight: bold; color: #00FF00 } div.syntax pre .cm, pre.syntax .cm { color: #999999 } ... Additional options accepted: `nowrap` If set to ``True``, don't wrap the tokens at all, not even inside a ``<pre>`` tag. This disables most other options (default: ``False``). `full` Tells the formatter to output a "full" document, i.e. a complete self-contained document (default: ``False``). `title` If `full` is true, the title that should be used to caption the document (default: ``''``). `style` The style to use, can be a string or a Style subclass (default: ``'default'``). This option has no effect if the `cssfile` and `noclobber_cssfile` option are given and the file specified in `cssfile` exists. `noclasses` If set to true, token ``<span>`` tags will not use CSS classes, but inline styles. This is not recommended for larger pieces of code since it increases output size by quite a bit (default: ``False``). `classprefix` Since the token types use relatively short class names, they may clash with some of your own class names. In this case you can use the `classprefix` option to give a string to prepend to all Pygments-generated CSS class names for token types. Note that this option also affects the output of `get_style_defs()`. `cssclass` CSS class for the wrapping ``<div>`` tag (default: ``'highlight'``). If you set this option, the default selector for `get_style_defs()` will be this class. .. versionadded:: 0.9 If you select the ``'table'`` line numbers, the wrapping table will have a CSS class of this string plus ``'table'``, the default is accordingly ``'highlighttable'``. `cssstyles` Inline CSS styles for the wrapping ``<div>`` tag (default: ``''``). `prestyles` Inline CSS styles for the ``<pre>`` tag (default: ``''``). .. versionadded:: 0.11 `cssfile` If the `full` option is true and this option is given, it must be the name of an external file. If the filename does not include an absolute path, the file's path will be assumed to be relative to the main output file's path, if the latter can be found. The stylesheet is then written to this file instead of the HTML file. .. versionadded:: 0.6 `noclobber_cssfile` If `cssfile` is given and the specified file exists, the css file will not be overwritten. This allows the use of the `full` option in combination with a user specified css file. Default is ``False``. .. versionadded:: 1.1 `linenos` If set to ``'table'``, output line numbers as a table with two cells, one containing the line numbers, the other the whole code. This is copy-and-paste-friendly, but may cause alignment problems with some browsers or fonts. If set to ``'inline'``, the line numbers will be integrated in the ``<pre>`` tag that contains the code (that setting is *new in Pygments 0.8*). For compatibility with Pygments 0.7 and earlier, every true value except ``'inline'`` means the same as ``'table'`` (in particular, that means also ``True``). The default value is ``False``, which means no line numbers at all. **Note:** with the default ("table") line number mechanism, the line numbers and code can have different line heights in Internet Explorer unless you give the enclosing ``<pre>`` tags an explicit ``line-height`` CSS property (you get the default line spacing with ``line-height: 125%``). `hl_lines` Specify a list of lines to be highlighted. .. versionadded:: 0.11 `linenostart` The line number for the first line (default: ``1``). `linenostep` If set to a number n > 1, only every nth line number is printed. `linenospecial` If set to a number n > 0, every nth line number is given the CSS class ``"special"`` (default: ``0``). `nobackground` If set to ``True``, the formatter won't output the background color for the wrapping element (this automatically defaults to ``False`` when there is no wrapping element [eg: no argument for the `get_syntax_defs` method given]) (default: ``False``). .. versionadded:: 0.6 `lineseparator` This string is output between lines of code. It defaults to ``"\n"``, which is enough to break a line inside ``<pre>`` tags, but you can e.g. set it to ``"<br>"`` to get HTML line breaks. .. versionadded:: 0.7 `lineanchors` If set to a nonempty string, e.g. ``foo``, the formatter will wrap each output line in an anchor tag with a ``name`` of ``foo-linenumber``. This allows easy linking to certain lines. .. versionadded:: 0.9 `linespans` If set to a nonempty string, e.g. ``foo``, the formatter will wrap each output line in a span tag with an ``id`` of ``foo-linenumber``. This allows easy access to lines via javascript. .. versionadded:: 1.6 `anchorlinenos` If set to `True`, will wrap line numbers in <a> tags. Used in combination with `linenos` and `lineanchors`. `tagsfile` If set to the path of a ctags file, wrap names in anchor tags that link to their definitions. `lineanchors` should be used, and the tags file should specify line numbers (see the `-n` option to ctags). .. versionadded:: 1.6 `tagurlformat` A string formatting pattern used to generate links to ctags definitions. Available variables are `%(path)s`, `%(fname)s` and `%(fext)s`. Defaults to an empty string, resulting in just `#prefix-number` links. .. versionadded:: 1.6 `filename` A string used to generate a filename when rendering <pre> blocks, for example if displaying source code. .. versionadded:: 2.1 **Subclassing the HTML formatter** .. versionadded:: 0.7 The HTML formatter is now built in a way that allows easy subclassing, thus customizing the output HTML code. The `format()` method calls `self._format_lines()` which returns a generator that yields tuples of ``(1, line)``, where the ``1`` indicates that the ``line`` is a line of the formatted source code. If the `nowrap` option is set, the generator is the iterated over and the resulting HTML is output. Otherwise, `format()` calls `self.wrap()`, which wraps the generator with other generators. These may add some HTML code to the one generated by `_format_lines()`, either by modifying the lines generated by the latter, then yielding them again with ``(1, line)``, and/or by yielding other HTML code before or after the lines, with ``(0, html)``. The distinction between source lines and other code makes it possible to wrap the generator multiple times. The default `wrap()` implementation adds a ``<div>`` and a ``<pre>`` tag. A custom `HtmlFormatter` subclass could look like this: .. sourcecode:: python class CodeHtmlFormatter(HtmlFormatter): def wrap(self, source, outfile): return self._wrap_code(source) def _wrap_code(self, source): yield 0, '<code>' for i, t in source: if i == 1: # it's a line of formatted code t += '<br>' yield i, t yield 0, '</code>' This results in wrapping the formatted lines with a ``<code>`` tag, where the source lines are broken using ``<br>`` tags. After calling `wrap()`, the `format()` method also adds the "line numbers" and/or "full document" wrappers if the respective options are set. Then, all HTML yielded by the wrapped generator is output. """ name = 'HTML' aliases = ['html'] filenames = ['*.html', '*.htm'] def __init__(self, **options): Formatter.__init__(self, **options) self.title = self._decodeifneeded(self.title) self.nowrap = get_bool_opt(options, 'nowrap', False) self.noclasses = get_bool_opt(options, 'noclasses', False) self.classprefix = options.get('classprefix', '') self.cssclass = self._decodeifneeded(options.get('cssclass', 'highlight')) self.cssstyles = self._decodeifneeded(options.get('cssstyles', '')) self.prestyles = self._decodeifneeded(options.get('prestyles', '')) self.cssfile = self._decodeifneeded(options.get('cssfile', '')) self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile', False) self.tagsfile = self._decodeifneeded(options.get('tagsfile', '')) self.tagurlformat = self._decodeifneeded(options.get('tagurlformat', '')) self.filename = self._decodeifneeded(options.get('filename', '')) if self.tagsfile: if not ctags: raise RuntimeError('The "ctags" package must to be installed ' 'to be able to use the "tagsfile" feature.') self._ctags = ctags.CTags(self.tagsfile) linenos = options.get('linenos', False) if linenos == 'inline': self.linenos = 2 elif linenos: # compatibility with <= 0.7 self.linenos = 1 else: self.linenos = 0 self.linenostart = abs(get_int_opt(options, 'linenostart', 1)) self.linenostep = abs(get_int_opt(options, 'linenostep', 1)) self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0)) self.nobackground = get_bool_opt(options, 'nobackground', False) self.lineseparator = options.get('lineseparator', '\n') self.lineanchors = options.get('lineanchors', '') self.linespans = options.get('linespans', '') self.anchorlinenos = options.get('anchorlinenos', False) self.hl_lines = set() for lineno in get_list_opt(options, 'hl_lines', []): try: self.hl_lines.add(int(lineno)) except ValueError: pass self._create_stylesheet() def _get_css_class(self, ttype): """Return the css class of this token type prefixed with the classprefix option.""" ttypeclass = _get_ttype_class(ttype) if ttypeclass: return self.classprefix + ttypeclass return '' def _get_css_classes(self, ttype): """Return the css classes of this token type prefixed with the classprefix option.""" cls = self._get_css_class(ttype) while ttype not in STANDARD_TYPES: ttype = ttype.parent cls = self._get_css_class(ttype) + ' ' + cls return cls def _create_stylesheet(self): t2c = self.ttype2class = {Token: ''} c2s = self.class2style = {} for ttype, ndef in self.style: name = self._get_css_class(ttype) style = '' if ndef['color']: style += 'color: #%s; ' % ndef['color'] if ndef['bold']: style += 'font-weight: bold; ' if ndef['italic']: style += 'font-style: italic; ' if ndef['underline']: style += 'text-decoration: underline; ' if ndef['bgcolor']: style += 'background-color: #%s; ' % ndef['bgcolor'] if ndef['border']: style += 'border: 1px solid #%s; ' % ndef['border'] if style: t2c[ttype] = name # save len(ttype) to enable ordering the styles by # hierarchy (necessary for CSS cascading rules!) c2s[name] = (style[:-2], ttype, len(ttype)) def get_style_defs(self, arg=None): """ Return CSS style definitions for the classes produced by the current highlighting style. ``arg`` can be a string or list of selectors to insert before the token type classes. """ if arg is None: arg = ('cssclass' in self.options and '.'+self.cssclass or '') if isinstance(arg, string_types): args = [arg] else: args = list(arg) def prefix(cls): if cls: cls = '.' + cls tmp = [] for arg in args: tmp.append((arg and arg + ' ' or '') + cls) return ', '.join(tmp) styles = [(level, ttype, cls, style) for cls, (style, ttype, level) in iteritems(self.class2style) if cls and style] styles.sort() lines = ['%s { %s } /* %s */' % (prefix(cls), style, repr(ttype)[6:]) for (level, ttype, cls, style) in styles] if arg and not self.nobackground and \ self.style.background_color is not None: text_style = '' if Text in self.ttype2class: text_style = ' ' + self.class2style[self.ttype2class[Text]][0] lines.insert(0, '%s { background: %s;%s }' % (prefix(''), self.style.background_color, text_style)) if self.style.highlight_color is not None: lines.insert(0, '%s.hll { background-color: %s }' % (prefix(''), self.style.highlight_color)) return '\n'.join(lines) def _decodeifneeded(self, value): if isinstance(value, bytes): if self.encoding: return value.decode(self.encoding) return value.decode() return value def _wrap_full(self, inner, outfile): if self.cssfile: if os.path.isabs(self.cssfile): # it's an absolute filename cssfilename = self.cssfile else: try: filename = outfile.name if not filename or filename[0] == '<': # pseudo files, e.g. name == '<fdopen>' raise AttributeError cssfilename = os.path.join(os.path.dirname(filename), self.cssfile) except AttributeError: print('Note: Cannot determine output file name, ' 'using current directory as base for the CSS file name', file=sys.stderr) cssfilename = self.cssfile # write CSS file only if noclobber_cssfile isn't given as an option. try: if not os.path.exists(cssfilename) or not self.noclobber_cssfile: cf = open(cssfilename, "w") cf.write(CSSFILE_TEMPLATE % {'styledefs': self.get_style_defs('body')}) cf.close() except IOError as err: err.strerror = 'Error writing CSS file: ' + err.strerror raise yield 0, (DOC_HEADER_EXTERNALCSS % dict(title=self.title, cssfile=self.cssfile, encoding=self.encoding)) else: yield 0, (DOC_HEADER % dict(title=self.title, styledefs=self.get_style_defs('body'), encoding=self.encoding)) for t, line in inner: yield t, line yield 0, DOC_FOOTER def _wrap_tablelinenos(self, inner): dummyoutfile = StringIO() lncount = 0 for t, line in inner: if t: lncount += 1 dummyoutfile.write(line) fl = self.linenostart mw = len(str(lncount + fl - 1)) sp = self.linenospecial st = self.linenostep la = self.lineanchors aln = self.anchorlinenos nocls = self.noclasses if sp: lines = [] for i in range(fl, fl+lncount): if i % st == 0: if i % sp == 0: if aln: lines.append('<a href="#%s-%d" class="special">%*d</a>' % (la, i, mw, i)) else: lines.append('<span class="special">%*d</span>' % (mw, i)) else: if aln: lines.append('<a href="#%s-%d">%*d</a>' % (la, i, mw, i)) else: lines.append('%*d' % (mw, i)) else: lines.append('') ls = '\n'.join(lines) else: lines = [] for i in range(fl, fl+lncount): if i % st == 0: if aln: lines.append('<a href="#%s-%d">%*d</a>' % (la, i, mw, i)) else: lines.append('%*d' % (mw, i)) else: lines.append('') ls = '\n'.join(lines) # in case you wonder about the seemingly redundant <div> here: since the # content in the other cell also is wrapped in a div, some browsers in # some configurations seem to mess up the formatting... if nocls: yield 0, ('<table class="%stable">' % self.cssclass + '<tr><td><div class="linenodiv" ' 'style="background-color: #f0f0f0; padding-right: 10px">' '<pre style="line-height: 125%">' + ls + '</pre></div></td><td class="code">') else: yield 0, ('<table class="%stable">' % self.cssclass + '<tr><td class="linenos"><div class="linenodiv"><pre>' + ls + '</pre></div></td><td class="code">') yield 0, dummyoutfile.getvalue() yield 0, '</td></tr></table>' def _wrap_inlinelinenos(self, inner): # need a list of lines since we need the width of a single number :( lines = list(inner) sp = self.linenospecial st = self.linenostep num = self.linenostart mw = len(str(len(lines) + num - 1)) if self.noclasses: if sp: for t, line in lines: if num % sp == 0: style = 'background-color: #ffffc0; padding: 0 5px 0 5px' else: style = 'background-color: #f0f0f0; padding: 0 5px 0 5px' yield 1, '<span style="%s">%*s </span>' % ( style, mw, (num % st and ' ' or num)) + line num += 1 else: for t, line in lines: yield 1, ('<span style="background-color: #f0f0f0; ' 'padding: 0 5px 0 5px">%*s </span>' % ( mw, (num % st and ' ' or num)) + line) num += 1 elif sp: for t, line in lines: yield 1, '<span class="lineno%s">%*s </span>' % ( num % sp == 0 and ' special' or '', mw, (num % st and ' ' or num)) + line num += 1 else: for t, line in lines: yield 1, '<span class="lineno">%*s </span>' % ( mw, (num % st and ' ' or num)) + line num += 1 def _wrap_lineanchors(self, inner): s = self.lineanchors # subtract 1 since we have to increment i *before* yielding i = self.linenostart - 1 for t, line in inner: if t: i += 1 yield 1, '<a name="%s-%d"></a>' % (s, i) + line else: yield 0, line def _wrap_linespans(self, inner): s = self.linespans i = self.linenostart - 1 for t, line in inner: if t: i += 1 yield 1, '<span id="%s-%d">%s</span>' % (s, i, line) else: yield 0, line def _wrap_div(self, inner): style = [] if (self.noclasses and not self.nobackground and self.style.background_color is not None): style.append('background: %s' % (self.style.background_color,)) if self.cssstyles: style.append(self.cssstyles) style = '; '.join(style) yield 0, ('<div' + (self.cssclass and ' class="%s"' % self.cssclass) + (style and (' style="%s"' % style)) + '>') for tup in inner: yield tup yield 0, '</div>\n' def _wrap_pre(self, inner): style = [] if self.prestyles: style.append(self.prestyles) if self.noclasses: style.append('line-height: 125%') style = '; '.join(style) if self.filename: yield 0, ('<span class="filename">' + self.filename + '</span>') # the empty span here is to keep leading empty lines from being # ignored by HTML parsers yield 0, ('<pre' + (style and ' style="%s"' % style) + '><span></span>') for tup in inner: yield tup yield 0, '</pre>' def _format_lines(self, tokensource): """ Just format the tokens, without any wrapping tags. Yield individual lines. """ nocls = self.noclasses lsep = self.lineseparator # for <span style=""> lookup only getcls = self.ttype2class.get c2s = self.class2style escape_table = _escape_html_table tagsfile = self.tagsfile lspan = '' line = [] for ttype, value in tokensource: if nocls: cclass = getcls(ttype) while cclass is None: ttype = ttype.parent cclass = getcls(ttype) cspan = cclass and '<span style="%s">' % c2s[cclass][0] or '' else: cls = self._get_css_classes(ttype) cspan = cls and '<span class="%s">' % cls or '' parts = value.translate(escape_table).split('\n') if tagsfile and ttype in Token.Name: filename, linenumber = self._lookup_ctag(value) if linenumber: base, filename = os.path.split(filename) if base: base += '/' filename, extension = os.path.splitext(filename) url = self.tagurlformat % {'path': base, 'fname': filename, 'fext': extension} parts[0] = "<a href=\"%s#%s-%d\">%s" % \ (url, self.lineanchors, linenumber, parts[0]) parts[-1] = parts[-1] + "</a>" # for all but the last line for part in parts[:-1]: if line: if lspan != cspan: line.extend(((lspan and '</span>'), cspan, part, (cspan and '</span>'), lsep)) else: # both are the same line.extend((part, (lspan and '</span>'), lsep)) yield 1, ''.join(line) line = [] elif part: yield 1, ''.join((cspan, part, (cspan and '</span>'), lsep)) else: yield 1, lsep # for the last line if line and parts[-1]: if lspan != cspan: line.extend(((lspan and '</span>'), cspan, parts[-1])) lspan = cspan else: line.append(parts[-1]) elif parts[-1]: line = [cspan, parts[-1]] lspan = cspan # else we neither have to open a new span nor set lspan if line: line.extend(((lspan and '</span>'), lsep)) yield 1, ''.join(line) def _lookup_ctag(self, token): entry = ctags.TagEntry() if self._ctags.find(entry, token, 0): return entry['file'], entry['lineNumber'] else: return None, None def _highlight_lines(self, tokensource): """ Highlighted the lines specified in the `hl_lines` option by post-processing the token stream coming from `_format_lines`. """ hls = self.hl_lines for i, (t, value) in enumerate(tokensource): if t != 1: yield t, value if i + 1 in hls: # i + 1 because Python indexes start at 0 if self.noclasses: style = '' if self.style.highlight_color is not None: style = (' style="background-color: %s"' % (self.style.highlight_color,)) yield 1, '<span%s>%s</span>' % (style, value) else: yield 1, '<span class="hll">%s</span>' % value else: yield 1, value def wrap(self, source, outfile): """ Wrap the ``source``, which is a generator yielding individual lines, in custom generators. See docstring for `format`. Can be overridden. """ return self._wrap_div(self._wrap_pre(source)) def format_unencoded(self, tokensource, outfile): """ The formatting process uses several nested generators; which of them are used is determined by the user's options. Each generator should take at least one argument, ``inner``, and wrap the pieces of text generated by this. Always yield 2-tuples: (code, text). If "code" is 1, the text is part of the original tokensource being highlighted, if it's 0, the text is some piece of wrapping. This makes it possible to use several different wrappers that process the original source linewise, e.g. line number generators. """ source = self._format_lines(tokensource) if self.hl_lines: source = self._highlight_lines(source) if not self.nowrap: if self.linenos == 2: source = self._wrap_inlinelinenos(source) if self.lineanchors: source = self._wrap_lineanchors(source) if self.linespans: source = self._wrap_linespans(source) source = self.wrap(source, outfile) if self.linenos == 1: source = self._wrap_tablelinenos(source) if self.full: source = self._wrap_full(source, outfile) for t, piece in source: outfile.write(piece)
gpl-2.0
8,454,842,329,069,202,000
36.319624
86
0.537328
false
4.155849
false
false
false
sohail-aspose/Aspose_Slides_Cloud
SDKs/Aspose.Slides_Cloud_SDK_for_Python/asposeslidescloud/models/Image.py
4
1028
#!/usr/bin/env python class Image(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): """ Attributes: swaggerTypes (dict): The key is attribute name and the value is attribute type. attributeMap (dict): The key is attribute name and the value is json key in definition. """ self.swaggerTypes = { 'Width': 'int', 'Height': 'int', 'SelfUri': 'ResourceUri', 'AlternateLinks': 'list[ResourceUri]', 'Links': 'list[ResourceUri]' } self.attributeMap = { 'Width': 'Width','Height': 'Height','SelfUri': 'SelfUri','AlternateLinks': 'AlternateLinks','Links': 'Links'} self.Width = None # int self.Height = None # int self.SelfUri = None # ResourceUri self.AlternateLinks = None # list[ResourceUri] self.Links = None # list[ResourceUri]
mit
-5,682,097,692,297,491,000
32.16129
128
0.567121
false
4.283333
false
false
false
mluo613/osf.io
scripts/prereg/approve_draft_registrations.py
28
1260
""" A script for testing DraftRegistrationApprovals. Automatically approves all pending DraftRegistrationApprovals. """ import sys import logging from framework.celery_tasks.handlers import celery_teardown_request from website.app import init_app from website.project.model import DraftRegistration, Sanction logger = logging.getLogger(__name__) logging.basicConfig(level=logging.WARN) logging.disable(level=logging.INFO) def main(dry_run=True): if dry_run: logger.warn('DRY RUN mode') pending_approval_drafts = DraftRegistration.find() need_approval_drafts = [draft for draft in pending_approval_drafts if draft.approval and draft.requires_approval and draft.approval.state == Sanction.UNAPPROVED] for draft in need_approval_drafts: sanction = draft.approval try: if not dry_run: sanction.state = Sanction.APPROVED sanction._on_complete(None) sanction.save() logger.warn('Approved {0}'.format(draft._id)) except Exception as e: logger.error(e) if __name__ == '__main__': dry_run = 'dry' in sys.argv app = init_app(routes=False) main(dry_run=dry_run) celery_teardown_request()
apache-2.0
1,072,098,318,091,961,100
31.307692
122
0.670635
false
3.900929
false
false
false
RussellRiesJr/CoupleComeStatWithMe
ccswm/settings.py
1
3350
""" Django settings for ccswm project. Generated by 'django-admin startproject' using Django 1.10. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'b)2xn=0)bhu89x#@*eiwvce6+5*=2+n4((er3^1phiu7@qjgo4' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'ccswm.statApi', 'corsheaders' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'localhost:8080', 'apiUrl', 'couplescomestatwithme.co.uk', '138.68.146.190', ) ROOT_URLCONF = 'ccswm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ccswm.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/'
mit
952,352,824,490,474,600
24.18797
91
0.683284
false
3.435897
false
false
false
tillrohrmann/flink
flink-python/pyflink/ml/api/ml_environment.py
9
3953
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ from pyflink.dataset.execution_environment import ExecutionEnvironment from pyflink.datastream.stream_execution_environment import StreamExecutionEnvironment from pyflink.table.table_environment import BatchTableEnvironment, StreamTableEnvironment class MLEnvironment(object): """ The MLEnvironment stores the necessary context in Flink. Each MLEnvironment will be associated with a unique ID. The operations associated with the same MLEnvironment ID will share the same Flink job context. Both MLEnvironment ID and MLEnvironment can only be retrieved from MLEnvironmentFactory. .. versionadded:: 1.11.0 """ def __init__(self, exe_env=None, stream_exe_env=None, batch_tab_env=None, stream_tab_env=None): self._exe_env = exe_env self._stream_exe_env = stream_exe_env self._batch_tab_env = batch_tab_env self._stream_tab_env = stream_tab_env def get_execution_environment(self) -> ExecutionEnvironment: """ Get the ExecutionEnvironment. If the ExecutionEnvironment has not been set, it initial the ExecutionEnvironment with default Configuration. :return: the batch ExecutionEnvironment. .. versionadded:: 1.11.0 """ if self._exe_env is None: self._exe_env = ExecutionEnvironment.get_execution_environment() return self._exe_env def get_stream_execution_environment(self) -> StreamExecutionEnvironment: """ Get the StreamExecutionEnvironment. If the StreamExecutionEnvironment has not been set, it initial the StreamExecutionEnvironment with default Configuration. :return: the StreamExecutionEnvironment. .. versionadded:: 1.11.0 """ if self._stream_exe_env is None: self._stream_exe_env = StreamExecutionEnvironment.get_execution_environment() return self._stream_exe_env def get_batch_table_environment(self) -> BatchTableEnvironment: """ Get the BatchTableEnvironment. If the BatchTableEnvironment has not been set, it initial the BatchTableEnvironment with default Configuration. :return: the BatchTableEnvironment. .. versionadded:: 1.11.0 """ if self._batch_tab_env is None: self._batch_tab_env = BatchTableEnvironment.create( ExecutionEnvironment.get_execution_environment()) return self._batch_tab_env def get_stream_table_environment(self) -> StreamTableEnvironment: """ Get the StreamTableEnvironment. If the StreamTableEnvironment has not been set, it initial the StreamTableEnvironment with default Configuration. :return: the StreamTableEnvironment. .. versionadded:: 1.11.0 """ if self._stream_tab_env is None: self._stream_tab_env = StreamTableEnvironment.create( StreamExecutionEnvironment.get_execution_environment()) return self._stream_tab_env
apache-2.0
6,706,501,875,009,040,000
41.967391
99
0.676195
false
4.628806
false
false
false
prismskylabs/pycounters
src/pycounters/__init__.py
1
3969
""" PyCounters is a light weight library to monitor performance in production system. It is meant to be used in scenarios where using a profile is unrealistic due to the overhead it requires. Use PyCounters to get high level and concise overview of what's going on in your production code. See #### (read the docs) for more information """ import logging from pycounters.reporters.base import CollectingRole from shortcuts import _reporting_decorator_context_manager from . import reporters, base def report_start(name): """ reports an event's start. NOTE: you *must* fire off a corresponding event end with report_end """ base.THREAD_DISPATCHER.dispatch_event(name, "start", None) def report_end(name): """ reports an event's end. NOTE: you *must* have fired off a corresponding event start with report_start """ base.THREAD_DISPATCHER.dispatch_event(name, "end", None) def report_start_end(name=None): """ returns a function decorator and/or context manager which raises start and end events. If name is None events name is set to the name of the decorated function. In that case report_start_end can not be used as a context manager. """ return _reporting_decorator_context_manager(name) def report_value(name, value): """ reports a value event to the counters. """ base.THREAD_DISPATCHER.dispatch_event(name, "value", value) def register_counter(counter, throw_if_exists=True): """ Register a counter with PyCounters """ base.GLOBAL_REGISTRY.add_counter(counter, throw=throw_if_exists) def unregister_counter(counter=None, name=None): """ Removes a previously registered counter """ base.GLOBAL_REGISTRY.remove_counter(counter=counter, name=name) def output_report(): """ Manually cause the current values of all registered counters to be reported. """ reporters.base.GLOBAL_REPORTING_CONTROLLER.report() def start_auto_reporting(seconds=300): """ Start reporting in a background thread. Reporting frequency is set by seconds param. """ reporters.base.GLOBAL_REPORTING_CONTROLLER.start_auto_report(seconds=seconds) def stop_auto_reporting(): """ Stop auto reporting """ reporters.base.GLOBAL_REPORTING_CONTROLLER.stop_auto_report() def register_reporter(reporter=None): """ add a reporter to PyCounters. Registered reporters will output collected metrics """ reporters.base.GLOBAL_REPORTING_CONTROLLER.register_reporter(reporter) def unregister_reporter(reporter=None): """ remove a reporter from PyCounters. """ reporters.base.GLOBAL_REPORTING_CONTROLLER.unregister_reporter(reporter) def configure_multi_process_collection(collecting_address=[("", 60907), ("", 60906)], timeout_in_sec=120, role=CollectingRole.AUTO_ROLE): """ configures PyCounters to collect values from multiple processes :param collecting_address: a list of (address,port) tuples address of machines and ports data should be collected on. the extra tuples are used as backup in case the first address/port combination is (temporarily) unavailable. PyCounters would automatically start using the preferred address/port when it becomes available again. This behavior is handy when restarting the program and the old port is not yet freed by the OS. :param timeout_in_sec: timeout configuration for connections. Default should be good enough for pratically everyone. :param role: the role of this process. Leave at the default of AUTO_ROLE for pycounters to automatically choose a collecting leader. """ reporters.base.GLOBAL_REPORTING_CONTROLLER.configure_multi_process(collecting_address=collecting_address, timeout_in_sec=timeout_in_sec, debug_log=logging.getLogger(name="pycounters_multi_proc"), role=role)
apache-2.0
-7,862,069,303,668,941,000
34.756757
125
0.712522
false
4.12578
false
false
false
bitifirefly/edx-platform
common/djangoapps/microsite_configuration/templatetags/microsite.py
107
2058
""" Template tags and helper functions for displaying breadcrumbs in page titles based on the current micro site. """ from django import template from django.conf import settings from microsite_configuration import microsite from django.templatetags.static import static register = template.Library() def page_title_breadcrumbs(*crumbs, **kwargs): """ This function creates a suitable page title in the form: Specific | Less Specific | General | edX It will output the correct platform name for the request. Pass in a `separator` kwarg to override the default of " | " """ separator = kwargs.get("separator", " | ") if crumbs: return u'{}{}{}'.format(separator.join(crumbs), separator, platform_name()) else: return platform_name() @register.simple_tag(name="page_title_breadcrumbs", takes_context=True) def page_title_breadcrumbs_tag(context, *crumbs): """ Django template that creates breadcrumbs for page titles: {% page_title_breadcrumbs "Specific" "Less Specific" General %} """ return page_title_breadcrumbs(*crumbs) @register.simple_tag(name="platform_name") def platform_name(): """ Django template tag that outputs the current platform name: {% platform_name %} """ return microsite.get_value('platform_name', settings.PLATFORM_NAME) @register.simple_tag(name="favicon_path") def favicon_path(default=getattr(settings, 'FAVICON_PATH', 'images/favicon.ico')): """ Django template tag that outputs the configured favicon: {% favicon_path %} """ return static(microsite.get_value('favicon_path', default)) @register.simple_tag(name="microsite_css_overrides_file") def microsite_css_overrides_file(): """ Django template tag that outputs the css import for a: {% microsite_css_overrides_file %} """ file_path = microsite.get_value('css_overrides_file', None) if file_path is not None: return "<link href='{}' rel='stylesheet' type='text/css'>".format(static(file_path)) else: return ""
agpl-3.0
4,578,535,191,920,435,000
31.15625
92
0.691934
false
3.897727
false
false
false
selahssea/ggrc-core
src/ggrc_basic_permissions/migrations/versions/20130627032526_3bf5430a8c6f_add_roles_and_permis.py
7
1751
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Add roles and permissions tables Revision ID: 3bf5430a8c6f Revises: None Create Date: 2013-06-27 03:25:26.571232 """ # revision identifiers, used by Alembic. revision = '3bf5430a8c6f' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): op.create_table('roles', sa.Column('id', sa.Integer(), nullable=False, primary_key=True), sa.Column('name', sa.String(length=128), nullable=False), sa.Column('permissions_json', sa.Text(), nullable=False), sa.Column('description', sa.Text(), nullable=True), sa.Column('modified_by_id', sa.Integer()), sa.Column( 'created_at', sa.DateTime(), default=sa.text('current_timestamp')), sa.Column( 'updated_at', sa.DateTime(), default=sa.text('current_timestamp'), onupdate=sa.text('current_timestamp')), sa.Column('context_id', sa.Integer()), ) op.create_table('users_roles', sa.Column('id', sa.Integer(), nullable=False, primary_key=True), sa.Column('role_id', sa.Integer(), nullable=False), sa.Column('user_email', sa.String(length=128), nullable=False), sa.Column('target_context_id', sa.Integer(), nullable=False), sa.Column('modified_by_id', sa.Integer()), sa.Column( 'created_at', sa.DateTime(), default=sa.text('current_timestamp')), sa.Column( 'updated_at', sa.DateTime(), default=sa.text('current_timestamp'), onupdate=sa.text('current_timestamp')), sa.Column('context_id', sa.Integer()), sa.ForeignKeyConstraint(['role_id',], ['roles.id',]), ) def downgrade(): op.drop_table('users_roles') op.drop_table('roles')
apache-2.0
6,503,071,427,555,925,000
30.836364
78
0.657339
false
3.297552
false
false
false
shubhdev/edxOnBaadal
lms/djangoapps/commerce/tests/__init__.py
55
3551
# -*- coding: utf-8 -*- """ Commerce app tests package. """ import datetime import json from django.conf import settings from django.test import TestCase from django.test.utils import override_settings from freezegun import freeze_time import httpretty import jwt import mock from ecommerce_api_client import auth from commerce import ecommerce_api_client from student.tests.factories import UserFactory JSON = 'application/json' TEST_PUBLIC_URL_ROOT = 'http://www.example.com' TEST_API_URL = 'http://www-internal.example.com/api' TEST_API_SIGNING_KEY = 'edx' TEST_BASKET_ID = 7 TEST_ORDER_NUMBER = '100004' TEST_PAYMENT_DATA = { 'payment_processor_name': 'test-processor', 'payment_form_data': {}, 'payment_page_url': 'http://example.com/pay', } @override_settings(ECOMMERCE_API_SIGNING_KEY=TEST_API_SIGNING_KEY, ECOMMERCE_API_URL=TEST_API_URL) class EcommerceApiClientTest(TestCase): """ Tests to ensure the client is initialized properly. """ TEST_USER_EMAIL = 'test@example.com' TEST_CLIENT_ID = 'test-client-id' def setUp(self): super(EcommerceApiClientTest, self).setUp() self.user = UserFactory() self.user.email = self.TEST_USER_EMAIL self.user.save() # pylint: disable=no-member @httpretty.activate @freeze_time('2015-7-2') @override_settings(JWT_ISSUER='http://example.com/oauth', JWT_EXPIRATION=30) def test_tracking_context(self): """ Ensure the tracking context is set up in the api client correctly and automatically. """ # fake an ecommerce api request. httpretty.register_uri( httpretty.POST, '{}/baskets/1/'.format(TEST_API_URL), status=200, body='{}', adding_headers={'Content-Type': JSON} ) mock_tracker = mock.Mock() mock_tracker.resolve_context = mock.Mock(return_value={'client_id': self.TEST_CLIENT_ID}) with mock.patch('commerce.tracker.get_tracker', return_value=mock_tracker): ecommerce_api_client(self.user).baskets(1).post() # make sure the request's JWT token payload included correct tracking context values. actual_header = httpretty.last_request().headers['Authorization'] expected_payload = { 'username': self.user.username, 'full_name': self.user.profile.name, 'email': self.user.email, 'iss': settings.JWT_ISSUER, 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.JWT_EXPIRATION), 'tracking_context': { 'lms_user_id': self.user.id, # pylint: disable=no-member 'lms_client_id': self.TEST_CLIENT_ID, }, } expected_header = 'JWT {}'.format(jwt.encode(expected_payload, TEST_API_SIGNING_KEY)) self.assertEqual(actual_header, expected_header) @httpretty.activate def test_client_unicode(self): """ The client should handle json responses properly when they contain unicode character data. Regression test for ECOM-1606. """ expected_content = '{"result": "Préparatoire"}' httpretty.register_uri( httpretty.GET, '{}/baskets/1/order/'.format(TEST_API_URL), status=200, body=expected_content, adding_headers={'Content-Type': JSON}, ) actual_object = ecommerce_api_client(self.user).baskets(1).order.get() self.assertEqual(actual_object, {u"result": u"Préparatoire"})
agpl-3.0
3,852,776,131,936,167,400
34.49
100
0.641871
false
3.670114
true
false
false
saeedghsh/SSRR13
Andreas/slam6d/3rdparty/lastools/ArcGIS_toolbox/scripts/lasheight_classify.py
2
7125
# # lasheight_classify.py # # (c) 2012, Martin Isenburg # LASSO - rapid tools to catch reality # # uses lasheight to compute the height of LiDAR points above the ground # and uses the height information to classify the points. # # The LiDAR input can be in LAS/LAZ/BIN/TXT/SHP/... format. # The LiDAR output can be in LAS/LAZ/BIN/TXT format. # # for licensing details see http://rapidlasso.com/download/LICENSE.txt # import sys, os, arcgisscripting, subprocess def return_classification(classification): if (classification == "created, never classified (0)"): return "0" if (classification == "unclassified (1)"): return "1" if (classification == "ground (2)"): return "2" if (classification == "low vegetation (3)"): return "3" if (classification == "medium vegetation (4)"): return "4" if (classification == "high vegetation (5)"): return "5" if (classification == "building (6)"): return "6" if (classification == "low point (7)"): return "7" if (classification == "keypoint (8)"): return "8" if (classification == "water (9)"): return "9" if (classification == "high point (10)"): return "10" if (classification == "(11)"): return "11" if (classification == "overlap point (12)"): return "12" if (classification == "(13)"): return "13" if (classification == "(14)"): return "14" if (classification == "(15)"): return "15" if (classification == "(16)"): return "16" if (classification == "(17)"): return "17" if (classification == "(18)"): return "18" return "unknown" def check_output(command,console): if console == True: process = subprocess.Popen(command) else: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output,error = process.communicate() returncode = process.poll() return returncode,output ### create the geoprocessor object gp = arcgisscripting.create(9.3) ### report that something is happening gp.AddMessage("Starting lasheight ...") ### get number of arguments argc = len(sys.argv) ### report arguments (for debug) #gp.AddMessage("Arguments:") #for i in range(0, argc): # gp.AddMessage("[" + str(i) + "]" + sys.argv[i]) ### get the path to the LAStools binaries lastools_path = os.path.dirname(os.path.dirname(os.path.dirname(sys.argv[0])))+"\\bin" ### check if path exists if os.path.exists(lastools_path) == False: gp.AddMessage("Cannot find .\lastools\bin at " + lastools_path) sys.exit(1) else: gp.AddMessage("Found " + lastools_path + " ...") ### create the full path to the lasheight executable lasheight_path = lastools_path+"\\lasheight.exe" ### check if executable exists if os.path.exists(lastools_path) == False: gp.AddMessage("Cannot find lasheight.exe at " + lasheight_path) sys.exit(1) else: gp.AddMessage("Found " + lasheight_path + " ...") ### create the command string for lasheight.exe command = [lasheight_path] ### maybe use '-verbose' option if sys.argv[argc-1] == "true": command.append("-v") ### add input LiDAR command.append("-i") command.append(sys.argv[1]) ### maybe use ground points from external file if sys.argv[2] != "#": command.append("-ground_points") command.append(sys.argv[2]) ### else maybe use points with a different classification as ground elif sys.argv[3] != "#": command.append("-class") command.append(return_classification(sys.argv[3])) ### maybe we should ignore/preserve some existing classifications when classifying if sys.argv[4] != "#": command.append("-ignore_class") command.append(return_classification(sys.argv[4])) ### maybe we should ignore/preserve some more existing classifications when classifying if sys.argv[5] != "#": command.append("-ignore_class") command.append(return_classification(sys.argv[5])) ### maybe we classify points below if sys.argv[6] != "#": command.append("-classify_below") command.append(sys.argv[7]) command.append(return_classification(sys.argv[6])) ### maybe we classify points between [interval 1] if sys.argv[8] != "#": command.append("-classify_between") command.append(sys.argv[9]) command.append(sys.argv[10]) command.append(return_classification(sys.argv[8])) ### maybe we classify points between [interval 2] if sys.argv[11] != "#": command.append("-classify_between") command.append(sys.argv[12]) command.append(sys.argv[13]) command.append(return_classification(sys.argv[11])) ### maybe we classify points between [interval 3] if sys.argv[14] != "#": command.append("-classify_between") command.append(sys.argv[15]) command.append(sys.argv[16]) command.append(return_classification(sys.argv[14])) ### maybe we classify points below if sys.argv[17] != "#": command.append("-classify_above") command.append(sys.argv[18]) command.append(return_classification(sys.argv[17])) ### this is where the output arguments start out = 19 ### maybe an output format was selected if sys.argv[out] != "#": if sys.argv[out] == "las": command.append("-olas") elif sys.argv[out] == "laz": command.append("-olaz") elif sys.argv[out] == "bin": command.append("-obin") elif sys.argv[out] == "xyzc": command.append("-otxt") command.append("-oparse") command.append("xyzc") elif sys.argv[out] == "xyzci": command.append("-otxt") command.append("-oparse") command.append("xyzci") elif sys.argv[out] == "txyzc": command.append("-otxt") command.append("-oparse") command.append("txyzc") elif sys.argv[out] == "txyzci": command.append("-otxt") command.append("-oparse") command.append("txyzci") ### maybe an output file name was selected if sys.argv[out+1] != "#": command.append("-o") command.append(sys.argv[out+1]) ### maybe an output directory was selected if sys.argv[out+2] != "#": command.append("-odir") command.append(sys.argv[out+2]) ### maybe an output appendix was selected if sys.argv[out+3] != "#": command.append("-odix") command.append(sys.argv[out+3]) ### report command string gp.AddMessage("LAStools command line:") command_length = len(command) command_string = str(command[0]) for i in range(1, command_length): command_string = command_string + " " + str(command[i]) gp.AddMessage(command_string) ### run command returncode,output = check_output(command, False) ### report output of lasheight gp.AddMessage(str(output)) ### check return code if returncode != 0: gp.AddMessage("Error. lasheight failed.") sys.exit(1) ### report happy end gp.AddMessage("Success. lasheight done.")
bsd-3-clause
3,653,056,449,511,013,000
29.113537
130
0.624561
false
3.438707
false
false
false
pinireznik/antitude
agents/skynet/scripts/restart-proc.py
5
1943
#!/usr/bin/python -u import socket import time import os import sys from subprocess import call import random FILENAME_BREAK = "/tmp/break.tmp" FILENAME_OVERLOAD = "/tmp/load.tmp" IP_ADDRESS = socket.gethostbyname(socket.gethostname()) MEMORY_LIMIT = "50" FIXED_STRING = "event FIXED " + IP_ADDRESS LOG_FILE = "/tmp/logging/" + IP_ADDRESS + ".log" SIMULATION_DIRECTORY = "/tmp/simulation/" + IP_ADDRESS MEMORY_FILE = SIMULATION_DIRECTORY + "/memory.tmp" LAST_MEM = None while True: time.sleep(1) memory_use = None if os.path.isfile(FILENAME_BREAK): try: print "Restarting service and removing " + FILENAME_BREAK call(["serf", "event", "-coalesce=false", "FIXING", IP_ADDRESS]) time.sleep(random.randint(2, 4)) try: os.remove(FILENAME_BREAK) except: pass #don't care if it's already been deleted call(["serf", "event", "-coalesce=false", "FIXED", IP_ADDRESS]) except Exception as e: call(["serf", "event", "-coalesce=false", "EXCEPTION", "%s" % e]) if os.path.isfile(FILENAME_OVERLOAD): print "Restarting service and removing" + FILENAME_OVERLOAD try: os.remove(FILENAME_OVERLOAD) except: pass # don't care if it's already been deleted call(["serf", "event", "-coalesce=false", "OVERLOADED", IP_ADDRESS]) if os.path.isfile(MEMORY_FILE): print "Found memory file" with open(MEMORY_FILE, 'r') as f: memory_use = f.readline().rstrip() print "Memory use: " + memory_use if LAST_MEM != memory_use: print "Memory use changed, sending event" call(["serf", "event", "-coalesce=false", "MEMORY_LEVEL", "MEMORY_LEVEL=%s IP=%s" % (memory_use, IP_ADDRESS)]) global LAST_MEM LAST_MEM = memory_use
apache-2.0
1,522,895,349,766,216,200
36.365385
122
0.583119
false
3.611524
false
false
false
robwarm/gpaw-symm
gpaw/analyse/multipole.py
1
2669
import numpy as np from ase.units import Bohr from ase.parallel import paropen from ase.utils import prnt from gpaw.spherical_harmonics import Y from gpaw.utilities.tools import coordinates class Multipole: """Expand a function on the grid in multipole moments relative to a given center. center: Vector [Angstrom] """ def __init__(self, center, calculator=None, lmax=6): self.center = center / Bohr self.lmax = lmax self.gd = None self.y_Lg = None self.l_L = None if calculator is not None: self.initialize(calculator.density.finegd) def initialize(self, gd): """Initialize Y_L arrays""" self.gd = gd r_cg, r2_g = coordinates(gd, self.center, tiny=1.e-78) r_g = np.sqrt(r2_g) rhat_cg = r_cg / r_g self.l_L = [] self.y_Lg = [] npY = np.vectorize(Y, (float,), 'spherical harmonic') L = 0 for l in range(self.lmax + 1): for m in range(2 * l + 1): self.y_Lg.append( np.sqrt(4 * np.pi / (2 * l + 1)) * r_g**l * npY(L, rhat_cg[0], rhat_cg[1], rhat_cg[2]) ) self.l_L.append(l) L += 1 def expand(self, f_g): """Expand a function f_g in multipole moments units [e * Angstrom**l]""" assert(f_g.shape == self.gd.empty().shape) q_L = [] for L, y_g in enumerate(self.y_Lg): q_L.append(self.gd.integrate(f_g * y_g)) q_L[L] *= Bohr**self.l_L[L] return np.array(q_L) def to_file(self, calculator, filename='multipole.dat', mode='a'): """Expand the charge distribution in multipoles and write the result to a file""" if self.gd is None: self.initialize(calculator.density.finegd) q_L = self.expand(-calculator.density.rhot_g) f = paropen(filename, mode) prnt('# Multipole expansion of the charge density', file=f) prnt('# center =', self.center * Bohr, 'Angstrom', file=f) prnt('# lmax =', self.lmax, file=f) prnt(('# see https://trac.fysik.dtu.dk/projects/gpaw/browser/' + 'trunk/c/bmgs/sharmonic.py'), file=f) prnt('# for the definition of spherical harmonics', file=f) prnt('# l m q_lm[|e| Angstrom**l]', file=f) L = 0 for l in range(self.lmax + 1): for m in range(-l, l + 1): prnt('{0:2d} {1:3d} {2:g}'.format(l, m, q_L[L]), file=f) L += 1 f.close()
gpl-3.0
5,799,183,903,450,343,000
28.988764
72
0.517422
false
3.246959
false
false
false
coxmediagroup/googleads-python-lib
examples/dfp/v201408/report_service/run_inventory_report.py
4
2915
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This code example runs a report equal to the "Whole network report" on the DFP website. """ __author__ = ('Nicholas Chen', 'Joseph DiLallo') import tempfile # Import appropriate modules from the client library. from googleads import dfp from googleads import errors def main(client): # Initialize appropriate service. network_service = client.GetService('NetworkService', version='v201408') # Initialize a DataDownloader. report_downloader = client.GetDataDownloader(version='v201408') # Get root ad unit id for network. root_ad_unit_id = ( network_service.getCurrentNetwork()['effectiveRootAdUnitId']) # Set filter statement and bind value for reportQuery. values = [{ 'key': 'parent_ad_unit_id', 'value': { 'xsi_type': 'NumberValue', 'value': root_ad_unit_id } }] filter_statement = {'query': 'WHERE PARENT_AD_UNIT_ID = :parent_ad_unit_id', 'values': values} # Create report job. report_job = { 'reportQuery': { 'dimensions': ['DATE', 'AD_UNIT_NAME'], 'adUnitView': 'HIERARCHICAL', 'columns': ['AD_SERVER_IMPRESSIONS', 'AD_SERVER_CLICKS', 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_IMPRESSIONS', 'DYNAMIC_ALLOCATION_INVENTORY_LEVEL_CLICKS', 'TOTAL_INVENTORY_LEVEL_IMPRESSIONS', 'TOTAL_INVENTORY_LEVEL_CPM_AND_CPC_REVENUE'], 'dateRangeType': 'LAST_WEEK', 'statement': filter_statement } } try: # Run the report and wait for it to finish. report_job_id = report_downloader.WaitForReport(report_job) except errors.DfpReportError, e: print 'Failed to generate report. Error was: %s' % e # Change to your preferred export format. export_format = 'CSV_DUMP' report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False) # Download report data. report_downloader.DownloadReportToFile( report_job_id, export_format, report_file) report_file.close() # Display results. print 'Report job with id \'%s\' downloaded to:\n%s' % ( report_job_id, report_file.name) if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client)
apache-2.0
-6,839,245,679,299,968,000
31.388889
78
0.663808
false
3.727621
false
false
false
Multimac/ansible-modules-extras
notification/jabber.py
60
4555
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2015, Brian Coca <bcoca@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/> DOCUMENTATION = ''' --- version_added: "1.2" module: jabber short_description: Send a message to jabber user or chat room description: - Send a message to jabber options: user: description: - User as which to connect required: true password: description: - password for user to connect required: true to: description: - user ID or name of the room, when using room use a slash to indicate your nick. required: true msg: description: - The message body. required: true default: null host: description: - host to connect, overrides user info required: false port: description: - port to connect to, overrides default required: false default: 5222 encoding: description: - message encoding required: false # informational: requirements for nodes requirements: - python xmpp (xmpppy) author: "Brian Coca (@bcoca)" ''' EXAMPLES = ''' # send a message to a user - jabber: user=mybot@example.net password=secret to=friend@example.net msg="Ansible task finished" # send a message to a room - jabber: user=mybot@example.net password=secret to=mychaps@conference.example.net/ansiblebot msg="Ansible task finished" # send a message, specifying the host and port - jabber user=mybot@example.net host=talk.example.net port=5223 password=secret to=mychaps@example.net msg="Ansible task finished" ''' import os import re import time HAS_XMPP = True try: import xmpp except ImportError: HAS_XMPP = False def main(): module = AnsibleModule( argument_spec=dict( user=dict(required=True), password=dict(required=True), to=dict(required=True), msg=dict(required=True), host=dict(required=False), port=dict(required=False,default=5222), encoding=dict(required=False), ), supports_check_mode=True ) if not HAS_XMPP: module.fail_json(msg="The required python xmpp library (xmpppy) is not installed") jid = xmpp.JID(module.params['user']) user = jid.getNode() server = jid.getDomain() port = module.params['port'] password = module.params['password'] try: to, nick = module.params['to'].split('/', 1) except ValueError: to, nick = module.params['to'], None if module.params['host']: host = module.params['host'] else: host = server if module.params['encoding']: xmpp.simplexml.ENCODING = params['encoding'] msg = xmpp.protocol.Message(body=module.params['msg']) try: conn=xmpp.Client(server) if not conn.connect(server=(host,port)): module.fail_json(rc=1, msg='Failed to connect to server: %s' % (server)) if not conn.auth(user,password,'Ansible'): module.fail_json(rc=1, msg='Failed to authorize %s on: %s' % (user,server)) # some old servers require this, also the sleep following send conn.sendInitPresence(requestRoster=0) if nick: # sending to room instead of user, need to join msg.setType('groupchat') msg.setTag('x', namespace='http://jabber.org/protocol/muc#user') conn.send(xmpp.Presence(to=module.params['to'])) time.sleep(1) else: msg.setType('chat') msg.setTo(to) if not module.check_mode: conn.send(msg) time.sleep(1) conn.disconnect() except Exception, e: module.fail_json(msg="unable to send msg: %s" % e) module.exit_json(changed=False, to=to, user=user, msg=msg.getBody()) # import module snippets from ansible.module_utils.basic import * main()
gpl-3.0
2,556,304,043,178,934,000
26.606061
90
0.637761
false
3.783223
false
false
false
harlowja/networkx
examples/drawing/knuth_miles.py
50
2994
#!/usr/bin/env python """ An example using networkx.Graph(). miles_graph() returns an undirected graph over the 128 US cities from the datafile miles_dat.txt. The cities each have location and population data. The edges are labeled with the distance betwen the two cities. This example is described in Section 1.1 in Knuth's book [1,2]. References. ----------- [1] Donald E. Knuth, "The Stanford GraphBase: A Platform for Combinatorial Computing", ACM Press, New York, 1993. [2] http://www-cs-faculty.stanford.edu/~knuth/sgb.html """ __author__ = """Aric Hagberg (hagberg@lanl.gov)""" # Copyright (C) 2004-2015 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. import networkx as nx def miles_graph(): """ Return the cites example graph in miles_dat.txt from the Stanford GraphBase. """ # open file miles_dat.txt.gz (or miles_dat.txt) import gzip fh = gzip.open('knuth_miles.txt.gz','r') G=nx.Graph() G.position={} G.population={} cities=[] for line in fh.readlines(): line = line.decode() if line.startswith("*"): # skip comments continue numfind=re.compile("^\d+") if numfind.match(line): # this line is distances dist=line.split() for d in dist: G.add_edge(city,cities[i],weight=int(d)) i=i+1 else: # this line is a city, position, population i=1 (city,coordpop)=line.split("[") cities.insert(0,city) (coord,pop)=coordpop.split("]") (y,x)=coord.split(",") G.add_node(city) # assign position - flip x axis for matplotlib, shift origin G.position[city]=(-int(x)+7500,int(y)-3000) G.population[city]=float(pop)/1000.0 return G if __name__ == '__main__': import networkx as nx import re import sys G=miles_graph() print("Loaded miles_dat.txt containing 128 cities.") print("digraph has %d nodes with %d edges"\ %(nx.number_of_nodes(G),nx.number_of_edges(G))) # make new graph of cites, edge if less then 300 miles between them H=nx.Graph() for v in G: H.add_node(v) for (u,v,d) in G.edges(data=True): if d['weight'] < 300: H.add_edge(u,v) # draw with matplotlib/pylab try: import matplotlib.pyplot as plt plt.figure(figsize=(8,8)) # with nodes colored by degree sized by population node_color=[float(H.degree(v)) for v in H] nx.draw(H,G.position, node_size=[G.population[v] for v in H], node_color=node_color, with_labels=False) # scale the axes equally plt.xlim(-5000,500) plt.ylim(-2000,3500) plt.savefig("knuth_miles.png") except: pass
bsd-3-clause
-3,700,146,292,216,659,500
25.972973
72
0.579826
false
3.367829
false
false
false
MacCearain/HomeDetect
radio.py
1
18735
''' radio module ''' # pylint: disable=line-too-long # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-arguments # pylint: disable=trailing-whitespace import time import serial import sensor ONEBIT = 0b1 #------------------------------------------------------------------- # Let's Setup a couple of functions that make it easier to work with # HEX Bytes def get_bit(bit_mask, position): ''' Utility Function that extracts a bit from a byte Should probably check on length of the bit_mask and the number of positions we are shifting the position... possible future refactor ''' return (bit_mask >> position) & ONEBIT def hex_dump(random_integer): ''' hex_dump returns the hex representation of a number ''' return hex(random_integer)[2:].zfill(2).upper() class XBeeOnUSB(object): ''' XBee On USB models the interaction with the Xbee radio that is acting as the translator of ZigBee Messages to computer logic via a USB serial port ''' # Setup Context Manager on the Serial Port... Open / Close # Support a Configuration File # Maybe send the inbound raw data to a log @ debug level # Potentially deliver complete messages instead of raw bytes # It's ok to XBee/ZigBee specific this object is about getting Zigbee Packets off the USB port # These are part of the Xbee Radio Object -- Future Refactor STARTFRAMEBYTE = 0x7e DATAFRAMEBYTE = 0x92 #--------------------------------------------------------------------- # Let's Setup the Serial Port where the Coordinator Xbee is attached # This should be refactored into an ???? Class and consideration for Linux vs Windows... # Maybe externalize the port definition into the radio.cfg file.... - Future Refactor def __init__(self, port='/dev/ttyUSB0', baudrate=9600): ''' Initializes the XbeeOnUSB Class ''' self.port = port self.baud_rate = baudrate self.usb = serial.Serial() # This will be handle to the serial port self._start_frame = 0x7e # Just used as a constant self.frame_length = 0 # Indicates the length of the ZigBee Protocol Data Frame self._byte_count = 0 # Indicates how many bytes have been read self.actual_frame_type = 0x92 # Will be the frame type we read in the packet self.expected_frame_type = 0x92 # We are always hoping for the 0x92 data frame type in this program self.serial_number = '0013A20040B97414' # The serial number of the XBEE that sent the message self.network_address = '0000' # The network address self.receive_type = 'Broadcast' # Receive Type is either 'Acknowledge' or 'Broadcast' self.sample_set_count = 1 # The number of sample sets in the packet -- Limited to 1 currently self.digital_channel_mask = {'d00': 0, 'd01': 0, 'd02': 0, 'd03': 0, 'd04': 0, 'd05': 0, 'd06': 0, 'd07': 0, 'd10': 0, 'd11': 0, 'd12': 0} # Indicates the digital inputs that are enabled on the sending radio self.analog_channel_mask = {'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0} # Indicates the analog inputs that are enabled on the sending radio self.digital_data = {'d00': 0, 'd01': 0, 'd02': 0, 'd03': 0, 'd04': 0, 'd05': 0, 'd06': 0, 'd07': 0, 'd10': 0, 'd11': 0, 'd12': 0} # The actual digital data on the digital pins self.analog_data = {'a0': 0, 'a1': 0, 'a2': 0, 'a3': 0, 'vcc': 0} # The actual analog data from the packet self.analog_mV = {'a0': 0.0, 'a1': 0.0, 'a2': 0.0, 'a3': 0.0, 'vcc': 0.0} # The mV readings on the analog inputs from the remote radio self.check_sum = 0x00 # A Check sum -- to be calculated later def open(self): ''' open() attempts to open the serial port based on the current configuration settings of port and baud rate ''' self.usb.port = self.port self.usb.baudrate = self.baud_rate self.usb.open() def close(self): ''' close() attempts to close the serial port ''' self.usb.close() def __enter__(self): ''' __enter__ implements context manager features for the class ''' self.open() return self def __exit__(self, exc_ty, exc_val, tb): ''' __exit__ implements context manager features for the class ''' self.close() def __str__(self): return 'Some Text tbd' def __repr__(self): return 'radio.XBeeOnUSB()' def _dict(self): ''' Returns a Dictionary that summarizes the last frame read ''' return_val = {} return_val['frame_length'] = self.frame_length return_val['frame_type'] = self.actual_frame_type return_val['serial_number'] = self.serial_number return_val['network_address'] = self.network_address return_val['receive_type'] = self.receive_type return_val['digital_channel_mask'] = self.digital_channel_mask return_val['analog_channel_mask'] = self.analog_channel_mask return_val['digital_data'] = self.digital_data return_val['analog_data'] = self.analog_data return_val['analog_mV'] = self.analog_mV return return_val def _read_start_byte(self): ''' Let's read bytes until either 5 seconds has passed or we get a start byte ''' start_time = int(time.time()) if self.usb.is_open: self.usb.reset_input_buffer() start_ord = ord(self.usb.read()) while (start_time + 5) > int(time.time()) and start_ord != self._start_frame: start_ord = ord(self.usb.read()) if start_ord == self._start_frame: self._byte_count = 0 return else: print('You need to open the serial port before we can read from it.') def _read_frame_length(self): ''' Let's read the two bytes that indicate the frame length ''' msb_length_ord = ord(self.usb.read()) lsb_length_ord = ord(self.usb.read()) self.frame_length = (msb_length_ord * 256) + lsb_length_ord # print " Length: " + str(frameLength) self._byte_count = 0 def _read_frame_type(self): ''' Let's get the Frame Type Byte from the Frame... ''' self.actual_frame_type = ord(self.usb.read()) self._byte_count += 1 def _read_serial_number(self): ''' Let's get the Serial Number of the Sending Xbee from the Frame... ''' sn_ord8 = ord(self.usb.read()) sn_ord7 = ord(self.usb.read()) sn_ord6 = ord(self.usb.read()) sn_ord5 = ord(self.usb.read()) sn_ord4 = ord(self.usb.read()) sn_ord3 = ord(self.usb.read()) sn_ord2 = ord(self.usb.read()) sn_ord1 = ord(self.usb.read()) self._byte_count += 8 self.serial_number = hex_dump(sn_ord8) + hex_dump(sn_ord7) + hex_dump(sn_ord6) + hex_dump(sn_ord5) + hex_dump(sn_ord4) + hex_dump(sn_ord3) + hex_dump(sn_ord2) + hex_dump(sn_ord1) #print(" Sender Radio Serial Number: " + self.serial_number) def _read_network_address(self): ''' Let's get the Network Address within the packet ''' network_address_high_ord = ord(self.usb.read()) network_address_low_ord = ord(self.usb.read()) self._byte_count += 2 self.network_address = hex_dump(network_address_high_ord) + hex_dump(network_address_low_ord) #print(" Source Network Address: " + self.network_address) def _read_receive_type(self): ''' Let's get the Receive Type of the Packet. 0x01 = Acknoledge 0x02 = Broadcast 0x?? = Unknown ''' receive_type_ord = ord(self.usb.read()) self._byte_count += 1 if receive_type_ord == 0x01: self.receive_type = 'Acknowledge' #print(" Packet Acknowledged") elif receive_type_ord == 0x02: self.receive_type = 'Broadcast' #print(" Broadcast Packet") else: self.receive_type = 'Unknown' #print(" Unknown Receive Option") def _read_sample_set_count(self): ''' Let's get the number of Sample Sets from the Frame Content... I think the only valide value at this time is 1 ''' self.sample_set_count = ord(self.usb.read()) self._byte_count += 1 #print(" Number of Sample Sets: " + str(self.sample_set_count)) def _read_digital_channel_mask(self): ''' Let's get the Digital Channel Mask that describes which Digital Pins are Enabled on the Sending Xbee ''' digital_channel_mask_high = ord(self.usb.read()) digital_channel_mask_low = ord(self.usb.read()) self._byte_count += 2 #print(" Digital IO High Mask: " + bin(digitalChannelMaskHigh)[2:].zfill(8) + " (" + HexDump(digitalChannelMaskHigh) + ")") #print(" Digital IO Low Mask: " + bin(digitalChannelMaskLow)[2:].zfill(8) + " (" + HexDump(digitalChannelMaskLow) + ")") self.digital_channel_mask['d00'] = get_bit(digital_channel_mask_low, 0) self.digital_channel_mask['d01'] = get_bit(digital_channel_mask_low, 1) self.digital_channel_mask['d02'] = get_bit(digital_channel_mask_low, 2) self.digital_channel_mask['d03'] = get_bit(digital_channel_mask_low, 3) self.digital_channel_mask['d04'] = get_bit(digital_channel_mask_low, 4) self.digital_channel_mask['d05'] = get_bit(digital_channel_mask_low, 5) self.digital_channel_mask['d06'] = get_bit(digital_channel_mask_low, 6) self.digital_channel_mask['d07'] = get_bit(digital_channel_mask_low, 7) self.digital_channel_mask['d10'] = get_bit(digital_channel_mask_high, 2) self.digital_channel_mask['d11'] = get_bit(digital_channel_mask_high, 3) self.digital_channel_mask['d12'] = get_bit(digital_channel_mask_high, 4) def _read_analog_channel_mask(self): ''' Let's get the Analog Channel Mask that describes which Analog Pins are Enabled on the Sending Xbee ''' analog_channel_mask = ord(self.usb.read()) self._byte_count += 1 #print(" Analog IO Mask: " + bin(analogChannelMask)[2:].zfill(8) + " (" + hex(analogChannelMask)[2:].zfill(2) + ")") self.analog_channel_mask['a0'] = get_bit(analog_channel_mask, 0) self.analog_channel_mask['a1'] = get_bit(analog_channel_mask, 1) self.analog_channel_mask['a2'] = get_bit(analog_channel_mask, 2) self.analog_channel_mask['a3'] = get_bit(analog_channel_mask, 3) def _read_digital_data(self): ''' If any of the Digital Pins were Enabled -- Let's get the Digital Data the remote Xbee sent... ''' if any(self.digital_channel_mask['d00'], self.digital_channel_mask['d01'], self.digital_channel_mask['d02'], self.digital_channel_mask['d03'], self.digital_channel_mask['d04'], self.digital_channel_mask['d05'], self.digital_channel_mask['d06'], self.digital_channel_mask['d07'], self.digital_channel_mask['d10'], self.digital_channel_mask['d11'], self.digital_channel_mask['d12']): digital_channel_input_high = ord(self.usb.read()) digital_channel_input_low = ord(self.usb.read()) self._byte_count += 2 self.digital_data['d00'] = get_bit(digital_channel_input_low, 0) self.digital_data['d01'] = get_bit(digital_channel_input_low, 1) self.digital_data['d02'] = get_bit(digital_channel_input_low, 2) self.digital_data['d03'] = get_bit(digital_channel_input_low, 3) self.digital_data['d04'] = get_bit(digital_channel_input_low, 4) self.digital_data['d05'] = get_bit(digital_channel_input_low, 5) self.digital_data['d06'] = get_bit(digital_channel_input_low, 6) self.digital_data['d07'] = get_bit(digital_channel_input_low, 7) self.digital_data['d10'] = get_bit(digital_channel_input_high, 2) self.digital_data['d11'] = get_bit(digital_channel_input_high, 3) self.digital_data['d12'] = get_bit(digital_channel_input_high, 4) else: self.digital_data['d00'] = 0 self.digital_data['d01'] = 0 self.digital_data['d02'] = 0 self.digital_data['d03'] = 0 self.digital_data['d04'] = 0 self.digital_data['d05'] = 0 self.digital_data['d06'] = 0 self.digital_data['d07'] = 0 self.digital_data['d10'] = 0 self.digital_data['d11'] = 0 self.digital_data['d12'] = 0 def _read_analog_data(self, pin): ''' Let's read an analog data value and convert it to mV as well Used on Analog pins that are enabled and on VCC if enabled on the sending radio ''' analog_high_input = ord(self.usb.read()) analog_low_input = ord(self.usb.read()) self._byte_count += 2 self.analog_data[pin] = (analog_high_input * 256) + analog_low_input self.analog_mV[pin] = (self.analog_data[pin]/1023.0) * 1200.0 def _read_analog_channels(self): ''' Let's cycle over the analog pins, if the pin is enabled (in the analog channel mask) then let's read the data on the pin ''' for pin in self.analog_channel_mask: if self.analog_channel_mask[pin]: self._read_analog_data(pin) else: self.analog_data[pin] = 0 self.analog_mV[pin] = 0.0 # 15 -- Let's determine if the Radio Sent VCC pin = 'vcc' if (self._byte_count + 2) == self.frame_length: #print " The Remote Radio provided VCC in the Frame." # Let's Assume this is a report of the VCC as an analog Value self._read_analog_data(pin) elif self._byte_count == self.frame_length: self.analog_data[pin] = 0 self.analog_mV[pin] = 0.0 else: #print(" The byte count is: " + str(byteCount) + " the frame length is: " + str(frameLength)) self.analog_data[pin] = 0 self.analog_mV[pin] = 0.0 def _read_check_sum(self): ''' Let's read the checksum byte from the frame ''' self.check_sum = ord(self.usb.read()) #print " Check Sum : " + HexDump(checkSum) def read_frame(self): ''' This returns a dictionary that has the essence of the raw radio message received Typically a radio message will formatted as follows: Byte Example Description 0 0x7e Start Byte -- Indicates the beginning of a data frame 1 0x00 Length -- Number of Bytes (CheckSumByte# - 1 - 2) 2 0x14 3 0x92 Frame Type - 0x92 indicates this will be a broadcasted data sample 4 0x00 64-Bit Source Address (aka Serial Number of the Sending Radio) 5 0x13 Most Significant Byte is Byte 4 and the Least Significant Byte is Byte 11 6 0xA2 7 0x00 8 0x40 9 0x77 10 0x9C 11 0x49 12 0x36 Source Network Address -- 16 Bit 13 0x6A 14 0x01 Receive Options -- 01 = Packet Acknowledged -- 02 = Broadcast Packet 15 0x01 Number of Sample Sets (Always set to 1 due to XBEE Limitations) 16 0x00 Digital Channel Mask - Indicates which Digital Pins are enabled (See below for a mapping) 17 0x20 18 0x01 Analog Channel Mask - Indicates which Analog Pins are enabled (See below for a mapping) 19 0x00 Digital Sample Data (if any) - Maps the same as the Digital Channel Mask 20 0x14 21 0x04 Analog Sample Data (if any) 22 0x25 There will be two bytes here for every pin set for ADC 23 0xF5 Checksum(0xFF - the 8 bit sum of the bytes from byte 3 to this byte) Digital Channel Mask First Byte 0 1 2 3 4 5 6 7 n/a n/a D12 D11 D10 n/a n/a n/a Second Byte 0 1 2 3 4 5 6 7 D7 D6 D5 D4 D3 D2 D1 D0 Analog Channel Mask First Byte 0 1 2 3 4 5 6 7 n/a n/a n/a n/a A3 A2 A1 A0 ''' # 1 -- Let's read until we get a STARTFRAMEBYTE or 5 seconds has elapsed self._read_start_byte() # 2 -- Next lets get how long the frame should be... self._read_frame_length() # 3 -- Next lets get the dataframe type -- we are hoping for 0x92 data frames self._read_frame_type() # 4 -- Next lets get the serial number of the sending XBEE self._read_serial_number() # 5 -- Let's get the network Address self._read_network_address() # 6 -- Lets get the Receive Type of the Packet... Acknowledged or Broadbast self._read_receive_type() # 7 -- Let's get the number of sample sets self._read_sample_set_count() # 8 -- Let's get the Digital Channel Mask self._read_digital_channel_mask() # 9 -- Let's get the Analog Channel Mask self._read_analog_channel_mask() # 10 -- Let's get the actual digital data on the Digital Pins if any are enabled. self._read_digital_data() # 11 -- Analog Pin 0 Data, if it was enabled... self._read_analog_channels() # 12 -- Read the Checksum Byte self._read_check_sum() return self._dict()
mit
2,653,022,561,303,180,300
41.871854
186
0.555911
false
3.706231
false
false
false
holmes/intellij-community
python/lib/Lib/os.py
74
24851
r"""OS routines for Mac, NT, or Posix depending on what system we're on. This exports: - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc. - os.path is one of the modules posixpath, or ntpath - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos' - os.curdir is a string representing the current directory ('.' or ':') - os.pardir is a string representing the parent directory ('..' or '::') - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\') - os.extsep is the extension separator ('.' or '/') - os.altsep is the alternate pathname separator (None or '/') - os.pathsep is the component separator used in $PATH etc - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n') - os.defpath is the default search path for executables - os.devnull is the file path of the null device ('/dev/null', etc.) Programs that import and use 'os' stand a better chance of being portable between different platforms. Of course, they must then only use functions that are defined by all platforms (e.g., unlink and opendir), and leave all pathname manipulation to os.path (e.g., split and join). """ #' import sys, errno _names = sys.builtin_module_names # Note: more names are added to __all__ later. __all__ = ["altsep", "curdir", "pardir", "sep", "extsep", "pathsep", "linesep", "defpath", "name", "path", "devnull", "SEEK_SET", "SEEK_CUR", "SEEK_END"] def _get_exports_list(module): try: return list(module.__all__) except AttributeError: return [n for n in dir(module) if n[0] != '_'] name = 'java' if 'posix' in _names: _name = 'posix' linesep = '\n' from posix import * try: from posix import _exit except ImportError: pass import posixpath as path import posix __all__.extend(_get_exports_list(posix)) del posix elif 'nt' in _names: _name = 'nt' linesep = '\r\n' from nt import * try: from nt import _exit except ImportError: pass import ntpath as path import nt __all__.extend(_get_exports_list(nt)) del nt elif 'os2' in _names: _name = 'os2' linesep = '\r\n' from os2 import * try: from os2 import _exit except ImportError: pass if sys.version.find('EMX GCC') == -1: import ntpath as path else: import os2emxpath as path from _emx_link import link import os2 __all__.extend(_get_exports_list(os2)) del os2 elif 'ce' in _names: _name = 'ce' linesep = '\r\n' from ce import * try: from ce import _exit except ImportError: pass # We can use the standard Windows path. import ntpath as path import ce __all__.extend(_get_exports_list(ce)) del ce elif 'riscos' in _names: _name = 'riscos' linesep = '\n' from riscos import * try: from riscos import _exit except ImportError: pass import riscospath as path import riscos __all__.extend(_get_exports_list(riscos)) del riscos else: raise ImportError, 'no os specific module found' sys.modules['os.path'] = path from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, devnull) del _names # Python uses fixed values for the SEEK_ constants; they are mapped # to native constants if necessary in posixmodule.c SEEK_SET = 0 SEEK_CUR = 1 SEEK_END = 2 #' # Super directory utilities. # (Inspired by Eric Raymond; the doc strings are mostly his) def makedirs(name, mode=0777): """makedirs(path [, mode=0777]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive. """ head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs(head, mode) except OSError, e: # be happy if someone already created the path if e.errno != errno.EEXIST: raise if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists return mkdir(name, mode) def removedirs(name): """removedirs(path) Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is consumed or an error occurs. Errors during this latter phase are ignored -- they generally mean that a directory was not empty. """ rmdir(name) head, tail = path.split(name) if not tail: head, tail = path.split(head) while head and tail: try: rmdir(head) except error: break head, tail = path.split(head) def renames(old, new): """renames(old, new) Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned way until either the whole path is consumed or a nonempty directory is found. Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file. """ head, tail = path.split(new) if head and tail and not path.exists(head): makedirs(head) rename(old, new) head, tail = path.split(old) if head and tail: try: removedirs(head) except error: pass __all__.extend(["makedirs", "removedirs", "renames"]) def walk(top, topdown=True, onerror=None, followlinks=False): """Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up). When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false is ineffective, since the directories in dirnames have already been generated by the time dirnames itself is generated. By default errors from the os.listdir() call are ignored. If optional arg 'onerror' is specified, it should be a function; it will be called with one argument, an os.error instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. By default, os.walk does not follow symbolic links to subdirectories on systems that support them. In order to get this functionality, set the optional argument 'followlinks' to true. Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either. Example: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories """ from os.path import join, isdir, islink # We may not have read permission for top, in which case we can't # get a list of the files the directory contains. os.path.walk # always suppressed the exception then, rather than blow up for a # minor reason when (say) a thousand readable directories are still # left to visit. That logic is copied here. try: # Note that listdir and error are globals in this module due # to earlier import-*. names = listdir(top) except error, err: if onerror is not None: onerror(err) return dirs, nondirs = [], [] for name in names: if isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs for name in dirs: path = join(top, name) if followlinks or not islink(path): for x in walk(path, topdown, onerror, followlinks): yield x if not topdown: yield top, dirs, nondirs __all__.append("walk") # Make sure os.environ exists, at least try: environ except NameError: environ = {} def _exists(name): # CPython eval's the name, whereas looking in __all__ works for # Jython and is much faster return name in __all__ if _exists('execv'): def execl(file, *args): """execl(file, *args) Execute the executable file with argument list args, replacing the current process. """ execv(file, args) def execle(file, *args): """execle(file, *args, env) Execute the executable file with argument list args and environment env, replacing the current process. """ env = args[-1] execve(file, args[:-1], env) def execlp(file, *args): """execlp(file, *args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. """ execvp(file, args) def execlpe(file, *args): """execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process. """ env = args[-1] execvpe(file, args[:-1], env) def execvp(file, args): """execp(file, args) Execute the executable file (which is searched for along $PATH) with argument list args, replacing the current process. args may be a list or tuple of strings. """ _execvpe(file, args) def execvpe(file, args, env): """execvpe(file, args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env , replacing the current process. args may be a list or tuple of strings. """ _execvpe(file, args, env) __all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"]) def _execvpe(file, args, env=None): if env is not None: func = execve argrest = (args, env) else: func = execv argrest = (args,) env = environ head, tail = path.split(file) if head: func(file, *argrest) return if 'PATH' in env: envpath = env['PATH'] else: envpath = defpath PATH = envpath.split(pathsep) saved_exc = None saved_tb = None for dir in PATH: fullname = path.join(dir, file) try: func(fullname, *argrest) except error, e: tb = sys.exc_info()[2] if (e.errno != errno.ENOENT and e.errno != errno.ENOTDIR and saved_exc is None): saved_exc = e saved_tb = tb if saved_exc: raise error, saved_exc, saved_tb raise error, e, tb # Change environ to automatically call putenv() if it exists try: # This will fail if there's no putenv putenv except NameError: pass else: # Fake unsetenv() for Windows # not sure about os2 here but # I'm guessing they are the same. if name in ('os2', 'nt'): def unsetenv(key): putenv(key, "") if _name == "riscos": # On RISC OS, all env access goes through getenv and putenv from riscosenviron import _Environ elif _name in ('os2', 'nt'): # Where Env Var Names Must Be UPPERCASE import UserDict # But we store them as upper case class _Environ(UserDict.IterableUserDict): def __init__(self, environ): UserDict.UserDict.__init__(self) data = self.data for k, v in environ.items(): data[k.upper()] = v def __setitem__(self, key, item): self.data[key.upper()] = item def __getitem__(self, key): return self.data[key.upper()] def __delitem__(self, key): del self.data[key.upper()] def has_key(self, key): return key.upper() in self.data def __contains__(self, key): return key.upper() in self.data def get(self, key, failobj=None): return self.data.get(key.upper(), failobj) def update(self, dict=None, **kwargs): if dict: try: keys = dict.keys() except AttributeError: # List of (key, value) for k, v in dict: self[k] = v else: # got keys # cannot use items(), since mappings # may not have them. for k in keys: self[k] = dict[k] if kwargs: self.update(kwargs) def copy(self): return dict(self) environ = _Environ(environ) def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.""" return environ.get(key, default) __all__.append("getenv") # Supply spawn*() (probably only for Unix) if _exists("fork") and not _exists("spawnv") and _exists("execv"): P_WAIT = 0 P_NOWAIT = P_NOWAITO = 1 # XXX Should we support P_DETACH? I suppose it could fork()**2 # and close the std I/O streams. Also, P_OVERLAY is the same # as execv*()? def _spawnvef(mode, file, args, env, func): # Internal helper; func is the exec*() function to use pid = fork() if not pid: # Child try: if env is None: func(file, args) else: func(file, args, env) except: _exit(127) else: # Parent if mode == P_NOWAIT: return pid # Caller is responsible for waiting! while 1: wpid, sts = waitpid(pid, 0) if WIFSTOPPED(sts): continue elif WIFSIGNALED(sts): return -WTERMSIG(sts) elif WIFEXITED(sts): return WEXITSTATUS(sts) else: raise error, "Not stopped, signaled or exited???" def spawnv(mode, file, args): """spawnv(mode, file, args) -> integer Execute file with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return _spawnvef(mode, file, args, None, execv) def spawnve(mode, file, args, env): """spawnve(mode, file, args, env) -> integer Execute file with arguments from args in a subprocess with the specified environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return _spawnvef(mode, file, args, env, execve) # Note: spawnvp[e] is't currently supported on Windows def spawnvp(mode, file, args): """spawnvp(mode, file, args) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return _spawnvef(mode, file, args, None, execvp) def spawnvpe(mode, file, args, env): """spawnvpe(mode, file, args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return _spawnvef(mode, file, args, env, execvpe) if _exists("spawnv"): # These aren't supplied by the basic Windows code # but can be easily implemented in Python def spawnl(mode, file, *args): """spawnl(mode, file, *args) -> integer Execute file with arguments from args in a subprocess. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return spawnv(mode, file, args) def spawnle(mode, file, *args): """spawnle(mode, file, *args, env) -> integer Execute file with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ env = args[-1] return spawnve(mode, file, args[:-1], env) __all__.extend(["spawnv", "spawnve", "spawnl", "spawnle",]) if _exists("spawnvp"): # At the moment, Windows doesn't implement spawnvp[e], # so it won't have spawnlp[e] either. def spawnlp(mode, file, *args): """spawnlp(mode, file, *args) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ return spawnvp(mode, file, args) def spawnlpe(mode, file, *args): """spawnlpe(mode, file, *args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ env = args[-1] return spawnvpe(mode, file, args[:-1], env) __all__.extend(["spawnvp", "spawnvpe", "spawnlp", "spawnlpe",]) # Supply popen2 etc. (for Unix) if sys.platform.startswith('java') or _exists("fork"): if not _exists("popen2"): def popen2(cmd, mode="t", bufsize=-1): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout) are returned.""" import subprocess PIPE = subprocess.PIPE p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) return p.stdin, p.stdout __all__.append("popen2") if not _exists("popen3"): def popen3(cmd, mode="t", bufsize=-1): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout, child_stderr) are returned.""" import subprocess PIPE = subprocess.PIPE p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) return p.stdin, p.stdout, p.stderr __all__.append("popen3") if not _exists("popen4"): def popen4(cmd, mode="t", bufsize=-1): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout_stderr) are returned.""" import subprocess PIPE = subprocess.PIPE p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=subprocess.STDOUT, close_fds=True) return p.stdin, p.stdout __all__.append("popen4") if not _exists("urandom"): def urandom(n): """urandom(n) -> str Return a string of n random bytes suitable for cryptographic use. """ try: _urandomfd = open("/dev/urandom", O_RDONLY) except (OSError, IOError): raise NotImplementedError("/dev/urandom (or equivalent) not found") bytes = "" while len(bytes) < n: bytes += read(_urandomfd, n - len(bytes)) close(_urandomfd) return bytes # Supply os.popen() def popen(cmd, mode='r', bufsize=-1): """popen(command [, mode='r' [, bufsize]]) -> pipe Open a pipe to/from a command returning a file object. """ if not isinstance(cmd, (str, unicode)): raise TypeError('invalid cmd type (%s, expected string)' % type(cmd)) if mode not in ('r', 'w'): raise ValueError("invalid mode %r" % mode) import subprocess if mode == 'r': proc = subprocess.Popen(cmd, bufsize=bufsize, shell=True, stdout=subprocess.PIPE) fp = proc.stdout elif mode == 'w': proc = subprocess.Popen(cmd, bufsize=bufsize, shell=True, stdin=subprocess.PIPE) fp = proc.stdin # files from subprocess are in binary mode but popen needs text mode fp = fdopen(fp.fileno(), mode, bufsize) return _wrap_close(fp, proc) # Helper for popen() -- a proxy for a file whose close waits for the process class _wrap_close(object): def __init__(self, stream, proc): self._stream = stream self._proc = proc def close(self): self._stream.close() returncode = self._proc.wait() if returncode == 0: return None if _name == 'nt': return returncode else: return returncode def __getattr__(self, name): return getattr(self._stream, name) def __iter__(self): return iter(self._stream)
apache-2.0
1,187,429,907,938,893,000
34.149929
83
0.605529
false
4.040813
false
false
false
ioangogo/Suntimes
suntimes.py
1
1345
#! /bin/python # -*- coding: UTF-8 -*- import urllib2, json, datetime, time import dateutil.parser global latitude global longitude api=json.loads(urllib2.urlopen("http://freegeoip.net/json/").read().decode("UTF-8")) latitude=str(api['latitude']) longitude=str(api["longitude"]) def getsunrise(lat="", lng="", formatted=1): if lat=="" or lng == "": lat=latitude lng=longitude url="http://api.sunrise-sunset.org/json?lat=" + lat + "&lng=" + lng + "&formatted=" + str(formatted) print url sunapi=urllib2.urlopen(url) return json.loads(sunapi.read().decode("UTF-8"))['results']['sunrise'] def getsunset(lat="", lng="", formatted="1"): if lat=="" or lng == "": lat=latitude lng=longitude sunapi=urllib2.urlopen("http://api.sunrise-sunset.org/json?lat=" + lat + "&lng=" + lng + "&formatted=" + str(formatted)) return json.loads(sunapi.read().decode("UTF-8"))['results']['sunset'] def nighttrue(lat="", lng=""): sunrise = dateutil.parser.parse(getsunrise(lat, lng, 0).replace("+00:00","")) sunset = dateutil.parser.parse(getsunset(lat, lng, 0).replace("+00:00","")) timenow = datetime.datetime.now() if sunrise >= timenow >= sunset ==False: return False else: return True if __name__ == '__main__': bools=nighttrue() if bools == True: print "night time" elif bools == False: print "day" else: print bools
bsd-3-clause
-1,005,461,752,309,309,700
28.23913
121
0.657249
false
3.008949
false
false
false
feibaliang/blog
node_modules/pygmentize-bundled/vendor/pygments/ez_setup.py
181
9709
#!python """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import sys DEFAULT_VERSION = "0.6c9" DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb', 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b', 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a', 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618', 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac', 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5', 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4', 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c', 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b', 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27', 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277', 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20', 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab', 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53', 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902', 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de', 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b', 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03', 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a', 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6', 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', } import sys, os try: from hashlib import md5 except ImportError: from md5 import md5 def _validate_md5(egg_name, data): if egg_name in md5_data: digest = md5(data).hexdigest() if digest != md5_data[egg_name]: print >>sys.stderr, ( "md5 validation of %s failed! (Possible download problem?)" % egg_name ) sys.exit(2) return data def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg try: import pkg_resources except ImportError: return do_download() try: pkg_resources.require("setuptools>="+version); return except pkg_resources.VersionConflict, e: if was_imported: print >>sys.stderr, ( "The required version of setuptools (>=%s) is not available, and\n" "can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" ) % (version, e.args[0]) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return do_download() except pkg_resources.DistributionNotFound: return do_download() def download_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay = 15 ): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ import urllib2, shutil egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) url = download_base + egg_name saveto = os.path.join(to_dir, egg_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: from distutils import log if delay: log.warn(""" --------------------------------------------------------------------------- This script requires setuptools version %s to run (even to display help). I will attempt to download it for you (from %s), but you may need to enable firewall access for this script first. I will start the download in %d seconds. (Note: if this machine does not have network access, please obtain the file %s and place it in this directory before rerunning this script.) ---------------------------------------------------------------------------""", version, download_base, delay, url ); from time import sleep; sleep(delay) log.warn("Downloading %s", url) src = urllib2.urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = _validate_md5(egg_name, src.read()) dst = open(saveto,"wb"); dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" try: import setuptools except ImportError: egg = None try: egg = download_setuptools(version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here finally: if egg and os.path.exists(egg): os.unlink(egg) else: if setuptools.__version__ == '0.0.1': print >>sys.stderr, ( "You have an obsolete version of setuptools installed. Please\n" "remove it from your system entirely before rerunning this script." ) sys.exit(2) req = "setuptools>="+version import pkg_resources try: pkg_resources.require(req) except pkg_resources.VersionConflict: try: from setuptools.command.easy_install import main except ImportError: from easy_install import main main(list(argv)+[download_setuptools(delay=0)]) sys.exit(0) # try to force an exit else: if argv: from setuptools.command.easy_install import main main(argv) else: print "Setuptools version",version,"or greater has been installed." print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = inspect.getsourcefile(sys.modules[__name__]) f = open(srcfile, 'rb'); src = f.read(); f.close() match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: print >>sys.stderr, "Internal error!" sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] f = open(srcfile,'w') f.write(src) f.close() if __name__=='__main__': if len(sys.argv)>2 and sys.argv[1]=='--md5update': update_md5(sys.argv[2:]) else: main(sys.argv[1:])
mit
7,574,363,057,419,971,000
34.177536
86
0.645896
false
3.110862
false
false
false
GustavoHennig/ansible
lib/ansible/modules/network/nxos/nxos_vxlan_vtep_vni.py
21
15423
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: nxos_vxlan_vtep_vni extends_documentation_fragment: nxos version_added: "2.2" short_description: Creates a Virtual Network Identifier member (VNI) description: - Creates a Virtual Network Identifier member (VNI) for an NVE overlay interface. author: Gabriele Gerbino (@GGabriele) notes: - default, where supported, restores params default value. options: interface: description: - Interface name for the VXLAN Network Virtualization Endpoint. required: true vni: description: - ID of the Virtual Network Identifier. required: true assoc_vrf: description: - This attribute is used to identify and separate processing VNIs that are associated with a VRF and used for routing. The VRF and VNI specified with this command must match the configuration of the VNI under the VRF. required: false choices: ['true','false'] default: null ingress_replication: description: - Specifies mechanism for host reachability advertisement. required: false choices: ['bgp','static'] default: null multicast_group: description: - The multicast group (range) of the VNI. Valid values are string and keyword 'default'. required: false default: null peer_list: description: - Set the ingress-replication static peer list. Valid values are an array, a space-separated string of ip addresses, or the keyword 'default'. required: false default: null suppress_arp: description: - Suppress arp under layer 2 VNI. required: false choices: ['true','false'] default: null state: description: - Determines whether the config should be present or not on the device. required: false default: present choices: ['present','absent'] include_defaults: description: - Specify to use or not the complete running configuration for module operations. required: false default: true choices: ['true','true'] config: description: - Configuration string to be used for module operations. If not specified, the module will use the current running configuration. required: false default: null save: description: - Specify to save the running configuration after module operations. required: false default: false choices: ['true','false'] ''' EXAMPLES = ''' - nxos_vxlan_vtep_vni: interface: nve1 vni: 6000 ingress_replication: default username: "{{ un }}" password: "{{ pwd }}" host: "{{ inventory_hostname }}" ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: verbose mode type: dict sample: {"ingress_replication": "default", "interface": "nve1", "vni": "6000"} existing: description: k/v pairs of existing configuration returned: verbose mode type: dict sample: {} end_state: description: k/v pairs of configuration after module execution returned: verbose mode type: dict sample: {"assoc_vrf": false, "ingress_replication": "", "interface": "nve1", "multicast_group": "", "peer_list": [], "suppress_arp": false, "vni": "6000"} updates: description: commands sent to the device returned: always type: list sample: ["interface nve1", "member vni 6000"] changed: description: check to see if a change was made on the device returned: always type: boolean sample: true ''' import re from ansible.module_utils.nxos import get_config, load_config, run_commands from ansible.module_utils.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.netcfg import CustomNetworkConfig BOOL_PARAMS = ['suppress_arp'] PARAM_TO_COMMAND_KEYMAP = { 'assoc_vrf': 'associate-vrf', 'interface': 'interface', 'vni': 'member vni', 'ingress_replication': 'ingress-replication protocol', 'multicast_group': 'mcast-group', 'peer_list': 'peer-ip', 'suppress_arp': 'suppress-arp' } PARAM_TO_DEFAULT_KEYMAP = {} WARNINGS = [] def invoke(name, *args, **kwargs): func = globals().get(name) if func: return func(*args, **kwargs) def get_value(arg, config, module): if arg in BOOL_PARAMS: REGEX = re.compile(r'\s+{0}\s*$'.format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M) value = False try: if REGEX.search(config): value = True except TypeError: value = False else: REGEX = re.compile(r'(?:{0}\s)(?P<value>.*)$'.format(PARAM_TO_COMMAND_KEYMAP[arg]), re.M) value = '' if PARAM_TO_COMMAND_KEYMAP[arg] in config: value = REGEX.search(config).group('value') return value def check_interface(module, netcfg): config = str(netcfg) REGEX = re.compile(r'(?:interface nve)(?P<value>.*)$', re.M) value = '' if 'interface nve' in config: value = 'nve{0}'.format(REGEX.search(config).group('value')) return value def get_custom_value(arg, config, module): splitted_config = config.splitlines() if arg == 'assoc_vrf': value = False if 'associate-vrf' in config: value = True elif arg == 'peer_list': value = [] REGEX = re.compile(r'(?:peer-ip\s)(?P<peer_value>.*)$', re.M) for line in splitted_config: peer_value = '' if PARAM_TO_COMMAND_KEYMAP[arg] in line: peer_value = REGEX.search(line).group('peer_value') if peer_value: value.append(peer_value) return value def get_existing(module, args): existing = {} netcfg = get_config(module) custom = [ 'assoc_vrf', 'peer_list' ] interface_exist = check_interface(module, netcfg) if interface_exist: parents = ['interface {0}'.format(interface_exist)] temp_config = netcfg.get_section(parents) if 'member vni {0} associate-vrf'.format(module.params['vni']) in temp_config: parents.append('member vni {0} associate-vrf'.format( module.params['vni'])) config = netcfg.get_section(parents) elif "member vni {0}".format(module.params['vni']) in temp_config: parents.append('member vni {0}'.format(module.params['vni'])) config = netcfg.get_section(parents) else: config = {} if config: for arg in args: if arg not in ['interface', 'vni']: if arg in custom: existing[arg] = get_custom_value(arg, config, module) else: existing[arg] = get_value(arg, config, module) existing['interface'] = interface_exist existing['vni'] = module.params['vni'] return existing, interface_exist def apply_key_map(key_map, table): new_dict = {} for key, value in table.items(): new_key = key_map.get(key) if new_key: value = table.get(key) if value: new_dict[new_key] = value else: new_dict[new_key] = value return new_dict def state_present(module, existing, proposed, candidate): commands = list() proposed_commands = apply_key_map(PARAM_TO_COMMAND_KEYMAP, proposed) existing_commands = apply_key_map(PARAM_TO_COMMAND_KEYMAP, existing) for key, value in proposed_commands.items(): if key == 'associate-vrf': command = 'member vni {0} {1}'.format(module.params['vni'], key) if value: commands.append(command) else: commands.append('no {0}'.format(command)) elif key == 'peer-ip' and value != 'default': for peer in value: commands.append('{0} {1}'.format(key, peer)) elif value is True: commands.append(key) elif value is False: commands.append('no {0}'.format(key)) elif value == 'default': if existing_commands.get(key): existing_value = existing_commands.get(key) if key == 'peer-ip': for peer in existing_value: commands.append('no {0} {1}'.format(key, peer)) else: commands.append('no {0} {1}'.format(key, existing_value)) else: if key.replace(' ', '_').replace('-', '_') in BOOL_PARAMS: commands.append('no {0}'.format(key.lower())) else: command = '{0} {1}'.format(key, value.lower()) commands.append(command) if commands: vni_command = 'member vni {0}'.format(module.params['vni']) ingress_replication_command = 'ingress-replication protocol static' interface_command = 'interface {0}'.format(module.params['interface']) if ingress_replication_command in commands: static_level_cmds = [cmd for cmd in commands if 'peer' in cmd] parents = [interface_command, vni_command, ingress_replication_command] candidate.add(static_level_cmds, parents=parents) commands = [cmd for cmd in commands if 'peer' not in cmd] if vni_command in commands: parents = [interface_command] commands.remove(vni_command) if module.params['assoc_vrf'] is None: parents.append(vni_command) candidate.add(commands, parents=parents) def state_absent(module, existing, proposed, candidate): if existing['assoc_vrf']: commands = ['no member vni {0} associate-vrf'.format( module.params['vni'])] else: commands = ['no member vni {0}'.format(module.params['vni'])] parents = ['interface {0}'.format(module.params['interface'])] candidate.add(commands, parents=parents) def main(): argument_spec = dict( interface=dict(required=True, type='str'), vni=dict(required=True, type='str'), assoc_vrf=dict(required=False, type='bool'), multicast_group=dict(required=False, type='str'), peer_list=dict(required=False, type='list'), suppress_arp=dict(required=False, type='bool'), ingress_replication=dict(required=False, type='str', choices=['bgp', 'static', 'default']), state=dict(choices=['present', 'absent'], default='present', required=False), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False) ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) if module.params['assoc_vrf']: mutually_exclusive_params = ['multicast_group', 'suppress_arp', 'ingress_replication'] for param in mutually_exclusive_params: if module.params[param]: module.fail_json(msg='assoc_vrf cannot be used with ' '{0} param'.format(param)) if module.params['peer_list']: if module.params['ingress_replication'] != 'static': module.fail_json(msg='ingress_replication=static is required ' 'when using peer_list param') else: peer_list = module.params['peer_list'] if peer_list[0] == 'default': module.params['peer_list'] = 'default' else: stripped_peer_list = map(str.strip, peer_list) module.params['peer_list'] = stripped_peer_list state = module.params['state'] args = [ 'assoc_vrf', 'interface', 'vni', 'ingress_replication', 'multicast_group', 'peer_list', 'suppress_arp' ] existing, interface_exist = invoke('get_existing', module, args) end_state = existing proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) proposed = {} for key, value in proposed_args.items(): if key != 'interface': if str(value).lower() == 'default': value = PARAM_TO_DEFAULT_KEYMAP.get(key) if value is None: value = 'default' if existing.get(key) or (not existing.get(key) and value): proposed[key] = value result = {} if state == 'present' or (state == 'absent' and existing): if not interface_exist: WARNINGS.append("The proposed NVE interface does not exist. " "Use nxos_interface to create it first.") elif interface_exist != module.params['interface']: module.fail_json(msg='Only 1 NVE interface is allowed on ' 'the switch.') elif (existing and state == 'absent' and existing['vni'] != module.params['vni']): module.fail_json(msg="ERROR: VNI delete failed: Could not find" " vni node for {0}".format( module.params['vni']), existing_vni=existing['vni']) else: candidate = CustomNetworkConfig(indent=3) invoke('state_%s' % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result['updates'] = [] if module._verbosity > 0: end_state, interface_exist = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed_args if WARNINGS: result['warnings'] = WARNINGS module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
-8,924,721,179,718,513,000
33.349666
97
0.575569
false
4.183076
true
false
false
CMPUT410W15T02/CMPUT410W15-project
testenv/lib/python2.7/site-packages/distribute-0.6.24-py2.7.egg/site.py
108
2362
def __boot(): import sys, imp, os, os.path PYTHONPATH = os.environ.get('PYTHONPATH') if PYTHONPATH is None or (sys.platform=='win32' and not PYTHONPATH): PYTHONPATH = [] else: PYTHONPATH = PYTHONPATH.split(os.pathsep) pic = getattr(sys,'path_importer_cache',{}) stdpath = sys.path[len(PYTHONPATH):] mydir = os.path.dirname(__file__) #print "searching",stdpath,sys.path for item in stdpath: if item==mydir or not item: continue # skip if current dir. on Windows, or my own directory importer = pic.get(item) if importer is not None: loader = importer.find_module('site') if loader is not None: # This should actually reload the current module loader.load_module('site') break else: try: stream, path, descr = imp.find_module('site',[item]) except ImportError: continue if stream is None: continue try: # This should actually reload the current module imp.load_module('site',stream,path,descr) finally: stream.close() break else: raise ImportError("Couldn't find the real 'site' module") #print "loaded", __file__ known_paths = dict([(makepath(item)[1],1) for item in sys.path]) # 2.2 comp oldpos = getattr(sys,'__egginsert',0) # save old insertion position sys.__egginsert = 0 # and reset the current one for item in PYTHONPATH: addsitedir(item) sys.__egginsert += oldpos # restore effective old position d,nd = makepath(stdpath[0]) insert_at = None new_path = [] for item in sys.path: p,np = makepath(item) if np==nd and insert_at is None: # We've hit the first 'system' path entry, so added entries go here insert_at = len(new_path) if np in known_paths or insert_at is None: new_path.append(item) else: # new path after the insert point, back-insert it new_path.insert(insert_at, item) insert_at += 1 sys.path[:] = new_path if __name__=='site': __boot() del __boot
gpl-2.0
-2,014,626,685,309,833,700
27.804878
79
0.542337
false
4.187943
false
false
false
mammadori/asteroids
game/physicalobject.py
2
4916
# -*- coding: utf-8 *-* import pyglet from . import util, resources # update and collision helper functions def process_sprite_group(group, dt): """ calls update for the whole group and removes after who returns True """ for item in set(group): try: if item.update(dt): # remove expired items group.remove(item) item.delete() except AttributeError: try: group.remove(item) except KeyError: pass continue def group_collide(group, other_object): """ Check collision between a group and another object returns how many object collided removes the collided object in the group and calls method "destroy" in them """ collided = set() for item in set(group): try: if item.collide(other_object): collided.add(item.destroy()) group.remove(item) item.delete() # free batch except AttributeError: continue # remove collide objects from group return collided def group_group_collide(group1, group2): """ For each item in group1 calls group collide if a collision happened destroy the item """ collided = set() for item in set(group1): c = group_collide(group2, item) if len(c) > 0: # do not destroy collided.update(c) try: group1.remove(item) item.delete() # free batch except AttributeError: continue return collided class MovingSprite(pyglet.sprite.Sprite): """A sprite with physical properties such as velocity, and angle velocity""" def __init__(self, rotation=0, vel=(0,0), rotation_speed=0, screensize=(800, 600), *args, **kwargs): super().__init__(*args, **kwargs) self.screensize = screensize # Velocity self.vel = list(vel) # Angle (pyglet uses negative degrees) self.rotation = rotation self.rotation_speed = rotation_speed self.should_delete = False def update(self, dt): if self.should_delete: self.delete() return True # rotate object self.rotation += self.rotation_speed * dt # Update position according to velocity and time self.x = (self.x + self.vel[0] * dt) % (self.screensize[0] + self.width) self.y = (self.y + self.vel[1] * dt) % (self.screensize[1] + self.height) # update methods could be checked for expiring return False class ScaledMovingSprite(MovingSprite): """A Fullscreen Moving sprite""" def __init__(self, radius=None, lifespan=float("inf"), *args, **kwargs): """ Interesting super() params: rotation=0, vel=(0,0), rotation_speed=0, screensize=(800, 600) """ super().__init__(*args, **kwargs) self.scale = self.screensize[0] / self.image.width class PhysicalObject(MovingSprite): """A Moving sprite with collision and expiring""" def __init__(self, radius=None, lifespan="inf", *args, **kwargs): """ Interesting super() params: rotation=0, vel=(0,0), rotation_speed=0, screensize=(800, 600) """ super().__init__(*args, **kwargs) # collision radius if radius: self.radius = radius else: self.radius = (max(self.width, self.height) / 2) * self.scale # track how much it should last before disappearing self.lifespan = float(lifespan) self.age = float(0) def update(self, dt): self.age += dt # age the object return super().update(dt) or (self.age > self.lifespan) # update could be checked for expiring def collide(self, other_object): """Determine if this object collides with another""" # Calculate distance between object centers that would be a collision, # assuming circular images collision_distance = self.radius * self.scale + other_object.radius * other_object.scale # Get distance using position tuples actual_distance = util.distance(self.position, other_object.position) # update methods could be checked for expiring return (actual_distance <= collision_distance) def destroy(self): pos = list(self.position) vel = (self.vel[0]/2, self.vel[1] / 2) explosion = MovingSprite(img=resources.explosion_animation, vel=vel, screensize=self.screensize, x=pos[0], y=pos[1], batch=self.batch, group=self.group) # monkey patching done well @explosion.event def on_animation_end(): explosion.visible = False explosion.should_delete = True resources.explosion_sound.play() return explosion
bsd-3-clause
-5,002,630,723,919,972,000
29.345679
104
0.58991
false
4.103506
false
false
false
andreaso/ansible
lib/ansible/modules/cloud/amazon/ec2_ami.py
51
21956
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['stableinterface'], 'supported_by': 'curated'} DOCUMENTATION = ''' --- module: ec2_ami version_added: "1.3" short_description: create or destroy an image in ec2 description: - Creates or deletes ec2 images. options: instance_id: description: - Instance ID to create the AMI from. required: false default: null name: description: - The name of the new AMI. required: false default: null architecture: version_added: "2.3" description: - The target architecture of the image to register required: false default: null kernel_id: version_added: "2.3" description: - The target kernel id of the image to register required: false default: null virtualization_type: version_added: "2.3" description: - The virtualization type of the image to register required: false default: null root_device_name: version_added: "2.3" description: - The root device name of the image to register required: false default: null wait: description: - Wait for the AMI to be in state 'available' before returning. required: false default: "no" choices: [ "yes", "no" ] wait_timeout: description: - How long before wait gives up, in seconds. default: 300 state: description: - Create or deregister/delete AMI. required: false default: 'present' choices: [ "absent", "present" ] description: description: - Human-readable string describing the contents and purpose of the AMI. required: false default: null no_reboot: description: - Flag indicating that the bundling process should not attempt to shutdown the instance before bundling. If this flag is True, the responsibility of maintaining file system integrity is left to the owner of the instance. required: false default: no choices: [ "yes", "no" ] image_id: description: - Image ID to be deregistered. required: false default: null device_mapping: version_added: "2.0" description: - List of device hashes/dictionaries with custom configurations (same block-device-mapping parameters) - > Valid properties include: device_name, volume_type, size (in GB), delete_on_termination (boolean), no_device (boolean), snapshot_id, iops (for io1 volume_type) required: false default: null delete_snapshot: description: - Delete snapshots when deregistering the AMI. required: false default: "no" choices: [ "yes", "no" ] tags: description: - A dictionary of tags to add to the new image; '{"key":"value"}' and '{"key":"value","key":"value"}' required: false default: null version_added: "2.0" launch_permissions: description: - Users and groups that should be able to launch the AMI. Expects dictionary with a key of user_ids and/or group_names. user_ids should be a list of account ids. group_name should be a list of groups, "all" is the only acceptable value currently. required: false default: null version_added: "2.0" author: - "Evan Duffield (@scicoin-project) <eduffield@iacquire.com>" - "Constantin Bugneac (@Constantin07) <constantin.bugneac@endava.com>" - "Ross Williams (@gunzy83) <gunzy83au@gmail.com>" extends_documentation_fragment: - aws - ec2 ''' # Thank you to iAcquire for sponsoring development of this module. EXAMPLES = ''' # Basic AMI Creation - ec2_ami: aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx instance_id: i-xxxxxx wait: yes name: newtest tags: Name: newtest Service: TestService register: image # Basic AMI Creation, without waiting - ec2_ami: aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx region: xxxxxx instance_id: i-xxxxxx wait: no name: newtest register: image # AMI Registration from EBS Snapshot - ec2_ami: aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx region: xxxxxx name: newtest state: present architecture: x86_64 virtualization_type: hvm root_device_name: /dev/xvda device_mapping: - device_name: /dev/xvda size: 8 snapshot_id: snap-xxxxxxxx delete_on_termination: true volume_type: gp2 register: image # AMI Creation, with a custom root-device size and another EBS attached - ec2_ami: aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx instance_id: i-xxxxxx name: newtest device_mapping: - device_name: /dev/sda1 size: XXX delete_on_termination: true volume_type: gp2 - device_name: /dev/sdb size: YYY delete_on_termination: false volume_type: gp2 register: image # AMI Creation, excluding a volume attached at /dev/sdb - ec2_ami: aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx instance_id: i-xxxxxx name: newtest device_mapping: - device_name: /dev/sda1 size: XXX delete_on_termination: true volume_type: gp2 - device_name: /dev/sdb no_device: yes register: image # Deregister/Delete AMI (keep associated snapshots) - ec2_ami: aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx region: xxxxxx image_id: "{{ instance.image_id }}" delete_snapshot: False state: absent # Deregister AMI (delete associated snapshots too) - ec2_ami: aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx region: xxxxxx image_id: "{{ instance.image_id }}" delete_snapshot: True state: absent # Update AMI Launch Permissions, making it public - ec2_ami: aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx region: xxxxxx image_id: "{{ instance.image_id }}" state: present launch_permissions: group_names: ['all'] # Allow AMI to be launched by another account - ec2_ami: aws_access_key: xxxxxxxxxxxxxxxxxxxxxxx aws_secret_key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx region: xxxxxx image_id: "{{ instance.image_id }}" state: present launch_permissions: user_ids: ['123456789012'] ''' RETURN = ''' architecture: description: architecture of image returned: when AMI is created or already exists type: string sample: "x86_64" block_device_mapping: description: block device mapping associated with image returned: when AMI is created or already exists type: dict sample: { "/dev/sda1": { "delete_on_termination": true, "encrypted": false, "size": 10, "snapshot_id": "snap-1a03b80e7", "volume_type": "standard" } } creationDate: description: creation date of image returned: when AMI is created or already exists type: string sample: "2015-10-15T22:43:44.000Z" description: description: description of image returned: when AMI is created or already exists type: string sample: "nat-server" hypervisor: description: type of hypervisor returned: when AMI is created or already exists type: string sample: "xen" image_id: description: id of the image returned: when AMI is created or already exists type: string sample: "ami-1234abcd" is_public: description: whether image is public returned: when AMI is created or already exists type: bool sample: false location: description: location of image returned: when AMI is created or already exists type: string sample: "315210894379/nat-server" name: description: ami name of image returned: when AMI is created or already exists type: string sample: "nat-server" ownerId: description: owner of image returned: when AMI is created or already exists type: string sample: "435210894375" platform: description: platform of image returned: when AMI is created or already exists type: string sample: null root_device_name: description: root device name of image returned: when AMI is created or already exists type: string sample: "/dev/sda1" root_device_type: description: root device type of image returned: when AMI is created or already exists type: string sample: "ebs" state: description: state of image returned: when AMI is created or already exists type: string sample: "available" tags: description: a dictionary of tags assigned to image returned: when AMI is created or already exists type: dict sample: { "Env": "devel", "Name": "nat-server" } virtualization_type: description: image virtualization type returned: when AMI is created or already exists type: string sample: "hvm" snapshots_deleted: description: a list of snapshot ids deleted after deregistering image returned: after AMI is deregistered, if 'delete_snapshot' is set to 'yes' type: list sample: [ "snap-fbcccb8f", "snap-cfe7cdb4" ] ''' import sys import time try: import boto import boto.ec2 from boto.ec2.blockdevicemapping import BlockDeviceType, BlockDeviceMapping HAS_BOTO = True except ImportError: HAS_BOTO = False def get_block_device_mapping(image): """ Retrieves block device mapping from AMI """ bdm_dict = dict() if image is not None and hasattr(image, 'block_device_mapping'): bdm = getattr(image,'block_device_mapping') for device_name in bdm.keys(): bdm_dict[device_name] = { 'size': bdm[device_name].size, 'snapshot_id': bdm[device_name].snapshot_id, 'volume_type': bdm[device_name].volume_type, 'encrypted': bdm[device_name].encrypted, 'delete_on_termination': bdm[device_name].delete_on_termination } return bdm_dict def get_ami_info(image): return dict( image_id=image.id, state=image.state, architecture=image.architecture, block_device_mapping=get_block_device_mapping(image), creationDate=image.creationDate, description=image.description, hypervisor=image.hypervisor, is_public=image.is_public, location=image.location, ownerId=image.ownerId, root_device_name=image.root_device_name, root_device_type=image.root_device_type, tags=image.tags, virtualization_type = image.virtualization_type ) def create_image(module, ec2): """ Creates new AMI module : AnsibleModule object ec2: authenticated ec2 connection object """ instance_id = module.params.get('instance_id') name = module.params.get('name') wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) description = module.params.get('description') architecture = module.params.get('architecture') kernel_id = module.params.get('kernel_id') root_device_name = module.params.get('root_device_name') virtualization_type = module.params.get('virtualization_type') no_reboot = module.params.get('no_reboot') device_mapping = module.params.get('device_mapping') tags = module.params.get('tags') launch_permissions = module.params.get('launch_permissions') try: params = {'name': name, 'description': description} images = ec2.get_all_images(filters={'name': name}) if images and images[0]: # ensure that launch_permissions are up to date update_image(module, ec2, images[0].id) bdm = None if device_mapping: bdm = BlockDeviceMapping() for device in device_mapping: if 'device_name' not in device: module.fail_json(msg = 'Device name must be set for volume') device_name = device['device_name'] del device['device_name'] bd = BlockDeviceType(**device) bdm[device_name] = bd if instance_id: params['instance_id'] = instance_id params['no_reboot'] = no_reboot if bdm: params['block_device_mapping'] = bdm image_id = ec2.create_image(**params) else: params['architecture'] = architecture params['virtualization_type'] = virtualization_type if kernel_id: params['kernel_id'] = kernel_id if root_device_name: params['root_device_name'] = root_device_name if bdm: params['block_device_map'] = bdm image_id = ec2.register_image(**params) except boto.exception.BotoServerError as e: module.fail_json(msg="%s: %s" % (e.error_code, e.error_message)) # Wait until the image is recognized. EC2 API has eventual consistency, # such that a successful CreateImage API call doesn't guarantee the success # of subsequent DescribeImages API call using the new image id returned. for i in range(wait_timeout): try: img = ec2.get_image(image_id) if img.state == 'available': break elif img.state == 'failed': module.fail_json(msg="AMI creation failed, please see the AWS console for more details") except boto.exception.EC2ResponseError as e: if ('InvalidAMIID.NotFound' not in e.error_code and 'InvalidAMIID.Unavailable' not in e.error_code) and wait and i == wait_timeout - 1: module.fail_json(msg="Error while trying to find the new image. Using wait=yes and/or a longer " "wait_timeout may help. %s: %s" % (e.error_code, e.error_message)) finally: time.sleep(1) if img.state != 'available': module.fail_json(msg="Error while trying to find the new image. Using wait=yes and/or a longer wait_timeout may help.") if tags: try: ec2.create_tags(image_id, tags) except boto.exception.EC2ResponseError as e: module.fail_json(msg = "Image tagging failed => %s: %s" % (e.error_code, e.error_message)) if launch_permissions: try: img = ec2.get_image(image_id) img.set_launch_permissions(**launch_permissions) except boto.exception.BotoServerError as e: module.fail_json(msg="%s: %s" % (e.error_code, e.error_message), image_id=image_id) module.exit_json(msg="AMI creation operation complete", changed=True, **get_ami_info(img)) def deregister_image(module, ec2): """ Deregisters AMI """ image_id = module.params.get('image_id') delete_snapshot = module.params.get('delete_snapshot') wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) img = ec2.get_image(image_id) if img is None: module.fail_json(msg = "Image %s does not exist" % image_id, changed=False) # Get all associated snapshot ids before deregistering image otherwise this information becomes unavailable snapshots = [] if hasattr(img, 'block_device_mapping'): for key in img.block_device_mapping: snapshots.append(img.block_device_mapping[key].snapshot_id) # When trying to re-delete already deleted image it doesn't raise an exception # It just returns an object without image attributes if hasattr(img, 'id'): try: params = {'image_id': image_id, 'delete_snapshot': delete_snapshot} res = ec2.deregister_image(**params) except boto.exception.BotoServerError as e: module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message)) else: module.exit_json(msg = "Image %s has already been deleted" % image_id, changed=False) # wait here until the image is gone img = ec2.get_image(image_id) wait_timeout = time.time() + wait_timeout while wait and wait_timeout > time.time() and img is not None: img = ec2.get_image(image_id) time.sleep(3) if wait and wait_timeout <= time.time(): # waiting took too long module.fail_json(msg = "timed out waiting for image to be deregistered/deleted") # Boto library has hardcoded the deletion of the snapshot for the root volume mounted as '/dev/sda1' only # Make it possible to delete all snapshots which belong to image, including root block device mapped as '/dev/xvda' if delete_snapshot: try: for snapshot_id in snapshots: ec2.delete_snapshot(snapshot_id) except boto.exception.BotoServerError as e: if e.error_code == 'InvalidSnapshot.NotFound': # Don't error out if root volume snapshot was already deleted as part of deregister_image pass module.exit_json(msg="AMI deregister/delete operation complete", changed=True, snapshots_deleted=snapshots) else: module.exit_json(msg="AMI deregister/delete operation complete", changed=True) def update_image(module, ec2, image_id): """ Updates AMI """ launch_permissions = module.params.get('launch_permissions') or [] if 'user_ids' in launch_permissions: launch_permissions['user_ids'] = [str(user_id) for user_id in launch_permissions['user_ids']] img = ec2.get_image(image_id) if img is None: module.fail_json(msg = "Image %s does not exist" % image_id, changed=False) try: set_permissions = img.get_launch_permissions() if set_permissions != launch_permissions: if (('user_ids' in launch_permissions and launch_permissions['user_ids']) or ('group_names' in launch_permissions and launch_permissions['group_names'])): res = img.set_launch_permissions(**launch_permissions) elif ('user_ids' in set_permissions and set_permissions['user_ids']) or ('group_names' in set_permissions and set_permissions['group_names']): res = img.remove_launch_permissions(**set_permissions) else: module.exit_json(msg="AMI not updated", launch_permissions=set_permissions, changed=False) module.exit_json(msg="AMI launch permissions updated", launch_permissions=launch_permissions, set_perms=set_permissions, changed=True) else: module.exit_json(msg="AMI not updated", launch_permissions=set_permissions, changed=False) except boto.exception.BotoServerError as e: module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message)) def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( instance_id = dict(), image_id = dict(), architecture = dict(default="x86_64"), kernel_id = dict(), virtualization_type = dict(default="hvm"), root_device_name = dict(), delete_snapshot = dict(default=False, type='bool'), name = dict(), wait = dict(type='bool', default=False), wait_timeout = dict(default=900), description = dict(default=""), no_reboot = dict(default=False, type='bool'), state = dict(default='present'), device_mapping = dict(type='list'), tags = dict(type='dict'), launch_permissions = dict(type='dict') ) ) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto required for this module') try: ec2 = ec2_connect(module) except Exception as e: module.fail_json(msg="Error while connecting to aws: %s" % str(e)) if module.params.get('state') == 'absent': if not module.params.get('image_id'): module.fail_json(msg='image_id needs to be an ami image to registered/delete') deregister_image(module, ec2) elif module.params.get('state') == 'present': if module.params.get('image_id') and module.params.get('launch_permissions'): # Update image's launch permissions update_image(module, ec2,module.params.get('image_id')) # Changed is always set to true when provisioning new AMI if not module.params.get('instance_id') and not module.params.get('device_mapping'): module.fail_json(msg='instance_id or device_mapping (register from ebs snapshot) parameter is required for new image') if not module.params.get('name'): module.fail_json(msg='name parameter is required for new image') create_image(module, ec2) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * if __name__ == '__main__': main()
gpl-3.0
1,892,413,080,744,189,400
33.04031
154
0.64857
false
3.96604
false
false
false