repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
SphinxKnight/kuma
kuma/wiki/management/commands/populate_attachments.py
2
6623
from collections import defaultdict from django.core.management.base import BaseCommand from django.db import models from django.utils.text import get_text_list from kuma.attachments.models import Attachment from ...constants import DEKI_FILE_URL, KUMA_FILE_URL from ...models import Document, DocumentAttachment class Command(BaseCommand): help = "Populate m2m relations for documents and their attachments" def add_arguments(self, parser): parser.add_argument('-n', '--dry-run', action='store_true', dest='dry_run', default=False, help="Do everything except actually populating " "the attachments.") def attachments_documents_map(self): """ Builds and returns a mapping between attachment IDs and a list of IDs of the documents whose content contained the attachment URL. """ mapping = defaultdict(list) documents = (Document.admin_objects.exclude(is_redirect=True) .only('pk', 'html')) self.stdout.write("Attaching files to %s documents...\n\n" % documents.approx_count()) for document in documents.iterator(): mt_files = DEKI_FILE_URL.findall(document.html) kuma_files = KUMA_FILE_URL.findall(document.html) params = None if mt_files: params = models.Q(mindtouch_attachment_id__in=mt_files) if kuma_files: params = params | models.Q(id__in=kuma_files) if kuma_files and not params: params = models.Q(id__in=kuma_files) if params: attachment_pks = (Attachment.objects.filter(params) .distinct() .values_list('pk', flat=True)) for attachment_pk in attachment_pks: mapping[attachment_pk].append(document.pk) return mapping def create_attachment(self, document, attachment, revision, is_original): """ Creates a M2M relationship between the given document and attachment using some metadata of the given revision (the latest most likely) and either as an original or as a non-originally uploaded file. """ if not self.dry_run: relation, created = DocumentAttachment.objects.update_or_create( file_id=attachment.pk, document_id=document.pk, defaults={ 'attached_by': revision.creator, 'name': revision.filename, 'is_original': is_original, # all relations are linked since they were found in # the document's content 'is_linked': True, }, ) self.attached.append(attachment.pk) def handle(self, *args, **options): self.dry_run = options['dry_run'] self.attached = [] # first get the attachment to document list mapping mapping = self.attachments_documents_map() for attachment_pk, document_pks in mapping.items(): # get the attachment attachment = (Attachment.objects.only('pk', 'current_revision') .get(pk=attachment_pk)) if not attachment.current_revision: # bail if there isn't a current attachment revision # probably because faulty data self.stderr.write('no current revision for attachment ' '%s, skipping' % attachment.pk) continue # the revision we'll use for some minor metadata when creating the # attachment later revision = attachment.current_revision # get the list of documents that the attachment is contained in documents = (Document.objects.filter(pk__in=document_pks) .order_by('pk')) # has the document that the attachment was originally uploaded to # already been found? original_document = None # let's see if there is an English document, chances are that's # what we want original_document = documents.filter(locale='en-US').first() if original_document is not None: # create the attachment and mark the original as found self.create_attachment( original_document, attachment, revision, is_original=True, ) # hm, no English document found, so let's just use the document # with the lowest ID, create the attachment, and move on if original_document is None: original_document = documents.first() if original_document is not None: self.create_attachment( original_document, attachment, revision, is_original=True, ) # now go through the rest of the bunch but ignore the original # document we already created an attachment for for rest_document in documents.iterator(): if (original_document is not None and rest_document.pk == original_document.pk): continue self.create_attachment( rest_document, attachment, revision, is_original=False, ) # we failed, didn't find any document for this document if original_document is None: self.stderr.write('Cannot find document for ' 'attachment %s' % attachment.pk) # yada yada yada if self.attached: attached_list = get_text_list(self.attached, 'and') if self.dry_run: self.stdout.write('Dry attached files to documents: ' '%s' % attached_list) else: self.stdout.write('Attached files to documents: %s' % attached_list) else: self.stdout.write('Nothing to attach!')
mpl-2.0
liangfok/controlit_demos
dreamer_controlit_demos/nodes/TestSMACHFSM.py
1
1694
#!/usr/bin/env python import roslib; #roslib.load_manifest('smach_tutorials') import rospy import smach import smach_ros # define state Foo class Foo(smach.State): def __init__(self): smach.State.__init__(self, outcomes=['outcome1','outcome2']) self.counter = 0 def execute(self, userdata): rospy.loginfo('Executing state FOO') rospy.sleep(1) if self.counter < 10: self.counter += 1 return 'outcome1' else: return 'outcome2' # define state Bar class Bar(smach.State): def __init__(self): smach.State.__init__(self, outcomes=['outcome2']) def execute(self, userdata): rospy.loginfo('Executing state BAR') rospy.sleep(1) return 'outcome2' # main def main(): rospy.init_node('smach_example_state_machine') # Create a SMACH state machine sm = smach.StateMachine(outcomes=['outcome4', 'outcome5']) # Open the container with sm: # Add states to the container smach.StateMachine.add('FOO', Foo(), transitions={'outcome1':'BAR', 'outcome2':'outcome4'}) smach.StateMachine.add('BAR', Bar(), transitions={'outcome2':'FOO'}) # Create and start the introspection server sis = smach_ros.IntrospectionServer('server_name', sm, '/SM_ROOT') sis.start() # Execute SMACH plan outcome = sm.execute() # Wait for ctrl-c to stop the application print "Test FSM done, waiting until ctrl+c is hit..." rospy.spin() sis.stop() if __name__ == '__main__': main()
lgpl-2.1
arron9/promotion
vendor/mockery/mockery/docs/conf.py
468
8442
# -*- coding: utf-8 -*- # # Mockery Docs documentation build configuration file, created by # sphinx-quickstart on Mon Mar 3 14:04:26 2014. # # 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 import 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.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.todo', ] # 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'Mockery Docs' copyright = u'2014, Pádraic Brady, Dave Marshall, Wouter, Graham Campbell' # 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 = '0.9' # The full version, including alpha/beta/rc tags. release = '0.9' # 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 = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- 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 = '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 themes here, relative to this directory. #html_theme_path = [] # 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'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # 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 = {} # 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 = 'MockeryDocsdoc' # -- 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, or own class]). latex_documents = [ ('index2', 'MockeryDocs.tex', u'Mockery Docs Documentation', u'Pádraic Brady, Dave Marshall, Wouter, Graham Campbell', '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 = [ ('index2', 'mockerydocs', u'Mockery Docs Documentation', [u'Pádraic Brady, Dave Marshall, Wouter, Graham Campbell'], 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 = [ ('index2', 'MockeryDocs', u'Mockery Docs Documentation', u'Pádraic Brady, Dave Marshall, Wouter, Graham Campbell', 'MockeryDocs', 'One line description of 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' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False #on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if not on_rtd: # only import and set the theme if we're building docs locally import sphinx_rtd_theme html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] print sphinx_rtd_theme.get_html_theme_path()
gpl-2.0
kustodian/ansible
lib/ansible/modules/web_infrastructure/ansible_tower/tower_workflow_launch.py
21
5320
#!/usr/bin/python # coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: tower_workflow_launch author: "John Westcott IV (@john-westcott-iv)" version_added: "2.8" short_description: Run a workflow in Ansible Tower description: - Launch an Ansible Tower workflows. See U(https://www.ansible.com/tower) for an overview. options: workflow_template: description: - The name of the workflow template to run. required: True extra_vars: description: - Any extra vars required to launch the job. required: False wait: description: - Wait for the workflow to complete. required: False default: True type: bool timeout: description: - If waiting for the workflow to complete this will abort after this amount of seconds requirements: - "python >= 2.6" extends_documentation_fragment: tower ''' RETURN = ''' tower_version: description: The version of Tower we connected to returned: If connection to Tower works type: str sample: '3.4.0' job_info: description: dictionary containing information about the workflow executed returned: If workflow launched type: dict ''' EXAMPLES = ''' - name: Launch a workflow tower_workflow_launch: name: "Test Workflow" delegate_to: localhost run_once: true register: workflow_results - name: Launch a Workflow with parameters without waiting tower_workflow_launch: workflow_template: "Test workflow" extra_vars: "---\nmy: var" wait: False delegate_to: localhost run_once: true register: workflow_task_info ''' from ansible.module_utils.ansible_tower import TowerModule, tower_auth_config try: import tower_cli from tower_cli.api import client from tower_cli.conf import settings from tower_cli.exceptions import ServerError, ConnectionError, BadRequest, TowerCLIError except ImportError: pass def main(): argument_spec = dict( workflow_template=dict(required=True), extra_vars=dict(required=False), wait=dict(required=False, default=True, type='bool'), timeout=dict(required=False, default=None, type='int'), ) module = TowerModule( argument_spec=argument_spec, supports_check_mode=True ) workflow_template = module.params.get('workflow_template') extra_vars = module.params.get('extra_vars') wait = module.params.get('wait') timeout = module.params.get('timeout') # If we are going to use this result to return we can consider ourselfs changed result = dict( changed=False, msg='initial message' ) tower_auth = tower_auth_config(module) with settings.runtime_values(**tower_auth): # First we will test the connection. This will be a test for both check and run mode # Note, we are not using the tower_check_mode method here because we want to do more than just a ping test # If we are in check mode we also want to validate that we can find the workflow try: ping_result = client.get('/ping').json() # Stuff the version into the results as an FYI result['tower_version'] = ping_result['version'] except(ServerError, ConnectionError, BadRequest) as excinfo: result['msg'] = "Failed to reach Tower: {0}".format(excinfo) module.fail_json(**result) # Now that we know we can connect, lets verify that we can resolve the workflow_template try: workflow = tower_cli.get_resource("workflow").get(**{'name': workflow_template}) except TowerCLIError as e: result['msg'] = "Failed to find workflow: {0}".format(e) module.fail_json(**result) # Since we were able to find the workflow, if we are in check mode we can return now if module.check_mode: result['msg'] = "Check mode passed" module.exit_json(**result) # We are no ready to run the workflow try: result['job_info'] = tower_cli.get_resource('workflow_job').launch( workflow_job_template=workflow['id'], monitor=False, wait=wait, timeout=timeout, extra_vars=extra_vars ) if wait: # If we were waiting for a result we will fail if the workflow failed if result['job_info']['failed']: result['msg'] = "Workflow execution failed" module.fail_json(**result) else: module.exit_json(**result) # We were not waiting and there should be no way we can make it here without the workflow fired off so we can return a success module.exit_json(**result) except TowerCLIError as e: result['msg'] = "Failed to execute workflow: {0}".format(e) module.fail_json(**result) if __name__ == '__main__': main()
gpl-3.0
routeflow/AutomaticConfigurationRouteFlow
POX_CONTROLLER/pox/lib/packet/eapol.py
47
3220
# Copyright 2011 James McCauley # Copyright 2008 (C) Nicira, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This file is derived from the packet library in NOX, which was # developed by Nicira, Inc. #====================================================================== # # EAPOL Header Format (see IEEE 802.1X-2004): # # Octet 0: Protocol version (1 or 2). # Octet 1: Packet type: # 0 = EAP packet # 1 = EAPOL-Start # 2 = EAPOL-Logoff # 3 = EAPOL-Key # 4 = EAPOL-Encapsulated-ASF-Alert # Octets 2-3: Length of packet body field (0 if packet body is absent) # Octets 4-end: Packet body (present only for packet types 0, 3, 4) # #====================================================================== import struct from packet_utils import * from packet_base import packet_base from eap import * class eapol(packet_base): "EAP over LAN packet" MIN_LEN = 4 V1_PROTO = 1 V2_PROTO = 2 EAP_TYPE = 0 EAPOL_START_TYPE = 1 EAPOL_LOGOFF_TYPE = 2 EAPOL_KEY_TYPE = 3 EAPOL_ENCAPSULATED_ASF_ALERT = 4 type_names = {EAP_TYPE: "EAP", EAPOL_START_TYPE: "EAPOL-Start", EAPOL_LOGOFF_TYPE: "EAPOL-Logoff", EAPOL_KEY_TYPE: "EAPOL-Key", EAPOL_ENCAPSULATED_ASF_ALERT: "EAPOL-Encapsulated-ASF-Alert"} @staticmethod def type_name(type): return eapol.type_names.get(type, "type%d" % type) def __init__(self, raw=None, prev=None, **kw): packet_base.__init__(self) self.prev = prev self.version = self.V1_PROTO self.type = self.EAP_TYPE self.bodylen = 0 if raw is not None: self.parse(raw) self._init(kw) def __str__(self): s = '[EAPOL v%d %s]' % (self.version, self.type_name(self.type)) return s def parse(self, raw): assert isinstance(raw, bytes) self.raw = raw dlen = len(raw) if dlen < self.MIN_LEN: self.msg('(eapol parse) warning EAPOL packet data too short to parse header: data len %u' % (dlen,)) return (self.version, self.type, self.bodylen) \ = struct.unpack('!BBH', raw[:self.MIN_LEN]) self.parsed = True if self.type == self.EAP_TYPE: self.next = eap(raw=raw[self.MIN_LEN:], prev=self) elif (self.type == self.EAPOL_START_TYPE or self.type == self.EAPOL_LOGOFF_TYPE): pass # These types have no payloads. else: self.msg('warning unsupported EAPOL type: %s' % (self.type_name(self.type),)) def hdr(self, payload): return struct.pack('!BBH', self.version, self.type, self.bodylen)
apache-2.0
praveenkumar/ansible
lib/ansible/plugins/shell/csh.py
92
1131
# (c) 2014, Chris Church <chris@ninemoreminutes.com> # # This file is part of Ansible. # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.shell.sh import ShellModule as ShModule class ShellModule(ShModule): # How to end lines in a python script one-liner _SHELL_EMBEDDED_PY_EOL = '\\\n' _SHELL_REDIRECT_ALLNULL = '>& /dev/null' def env_prefix(self, **kwargs): return 'env %s' % super(ShellModule, self).env_prefix(**kwargs)
gpl-3.0
harisibrahimkv/django
django/contrib/gis/gdal/prototypes/errcheck.py
82
4151
""" This module houses the error-checking routines used by the GDAL ctypes prototypes. """ from ctypes import c_void_p, string_at from django.contrib.gis.gdal.error import ( GDALException, SRSException, check_err, ) from django.contrib.gis.gdal.libgdal import lgdal # Helper routines for retrieving pointers and/or values from # arguments passed in by reference. def arg_byref(args, offset=-1): "Return the pointer argument's by-reference value." return args[offset]._obj.value def ptr_byref(args, offset=-1): "Return the pointer argument passed in by-reference." return args[offset]._obj # ### String checking Routines ### def check_const_string(result, func, cargs, offset=None, cpl=False): """ Similar functionality to `check_string`, but does not free the pointer. """ if offset: check_err(result, cpl=cpl) ptr = ptr_byref(cargs, offset) return ptr.value else: return result def check_string(result, func, cargs, offset=-1, str_result=False): """ Check the string output returned from the given function, and free the string pointer allocated by OGR. The `str_result` keyword may be used when the result is the string pointer, otherwise the OGR error code is assumed. The `offset` keyword may be used to extract the string pointer passed in by-reference at the given slice offset in the function arguments. """ if str_result: # For routines that return a string. ptr = result if not ptr: s = None else: s = string_at(result) else: # Error-code return specified. check_err(result) ptr = ptr_byref(cargs, offset) # Getting the string value s = ptr.value # Correctly freeing the allocated memory behind GDAL pointer # with the VSIFree routine. if ptr: lgdal.VSIFree(ptr) return s # ### DataSource, Layer error-checking ### # ### Envelope checking ### def check_envelope(result, func, cargs, offset=-1): "Check a function that returns an OGR Envelope by reference." env = ptr_byref(cargs, offset) return env # ### Geometry error-checking routines ### def check_geom(result, func, cargs): "Check a function that returns a geometry." # OGR_G_Clone may return an integer, even though the # restype is set to c_void_p if isinstance(result, int): result = c_void_p(result) if not result: raise GDALException('Invalid geometry pointer returned from "%s".' % func.__name__) return result def check_geom_offset(result, func, cargs, offset=-1): "Check the geometry at the given offset in the C parameter list." check_err(result) geom = ptr_byref(cargs, offset=offset) return check_geom(geom, func, cargs) # ### Spatial Reference error-checking routines ### def check_srs(result, func, cargs): if isinstance(result, int): result = c_void_p(result) if not result: raise SRSException('Invalid spatial reference pointer returned from "%s".' % func.__name__) return result # ### Other error-checking routines ### def check_arg_errcode(result, func, cargs, cpl=False): """ The error code is returned in the last argument, by reference. Check its value with `check_err` before returning the result. """ check_err(arg_byref(cargs), cpl=cpl) return result def check_errcode(result, func, cargs, cpl=False): """ Check the error code returned (c_int). """ check_err(result, cpl=cpl) def check_pointer(result, func, cargs): "Make sure the result pointer is valid." if isinstance(result, int): result = c_void_p(result) if result: return result else: raise GDALException('Invalid pointer returned from "%s"' % func.__name__) def check_str_arg(result, func, cargs): """ This is for the OSRGet[Angular|Linear]Units functions, which require that the returned string pointer not be freed. This returns both the double and string values. """ dbl = result ptr = cargs[-1]._obj return dbl, ptr.value.decode()
bsd-3-clause
azatoth/scons
test/no-target.py
5
2417
#!/usr/bin/env python # # __COPYRIGHT__ # # 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__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path import TestSCons test = TestSCons.TestSCons() test.subdir('subdir', ['subdir', 'ccc']) ccc_ccc_in = os.path.join('ccc', 'ccc.in') subdir_SConscript = os.path.join('subdir', 'SConscript') test.write('SConstruct', r""" SConscript(r'%s') """ % subdir_SConscript) test.write(subdir_SConscript, r""" def cat(env, source, target): target = str(target[0]) f = open(target, "wb") for src in source: f.write(open(str(src), "rb").read()) f.close() b = Builder(action=cat, suffix='.out', src_suffix='.in') env = Environment(BUILDERS={'Build':b}) env.Build('aaa.in') n = env.Build('bbb.in', 'bbb.input') env.Build(n) env.Build(source = r'%s') """ % ccc_ccc_in) test.write(['subdir', 'aaa.in'], "subdir/aaa.in\n") test.write(['subdir', 'bbb.input'], "subdir/bbb.input\n") test.write(['subdir', 'ccc', 'ccc.in'], "subdir/ccc/ccc.in\n") # test.run(arguments = '.') test.fail_test(test.read(['subdir', 'aaa.out']) != "subdir/aaa.in\n") test.fail_test(test.read(['subdir', 'bbb.out']) != "subdir/bbb.input\n") test.fail_test(test.read(['subdir', 'ccc', 'ccc.out']) != "subdir/ccc/ccc.in\n") # test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
mit
nsat/gnuradio
gr-analog/python/analog/qa_phase_modulator.py
47
1742
#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import math from gnuradio import gr, gr_unittest, analog, blocks def sincos(x): return math.cos(x) + math.sin(x) * 1j class test_phase_modulator(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def test_fm_001(self): pi = math.pi sensitivity = pi/4 src_data = (1.0/4, 1.0/2, 1.0/4, -1.0/4, -1.0/2, -1/4.0) expected_result = tuple([sincos(sensitivity*x) for x in src_data]) src = blocks.vector_source_f(src_data) op = analog.phase_modulator_fc(sensitivity) dst = blocks.vector_sink_c() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() result_data = dst.data() self.assertComplexTuplesAlmostEqual(expected_result, result_data, 5) if __name__ == '__main__': gr_unittest.run(test_phase_modulator, "test_phase_modulator.xml")
gpl-3.0
jhawkesworth/ansible
lib/ansible/modules/storage/netapp/na_elementsw_admin_users.py
38
7113
#!/usr/bin/python # (c) 2017, NetApp, Inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = ''' module: na_elementsw_admin_users short_description: NetApp Element Software Manage Admin Users extends_documentation_fragment: - netapp.solidfire version_added: '2.7' author: NetApp Ansible Team (@carchi8py) <ng-ansibleteam@netapp.com> description: - Create, destroy, or update admin users on SolidFire options: state: description: - Whether the specified account should exist or not. required: true choices: ['present', 'absent'] element_username: description: - Unique username for this account. (May be 1 to 64 characters in length). required: true element_password: description: - The password for the new admin account. Setting the password attribute will always reset your password, even if the password is the same acceptEula: description: - Boolean, true for accepting Eula, False Eula type: bool access: description: - A list of type the admin has access to ''' EXAMPLES = """ - name: Add admin user na_elementsw_admin_users: state: present username: "{{ admin_user_name }}" password: "{{ admin_password }}" hostname: "{{ hostname }}" element_username: carchi8py element_password: carchi8py acceptEula: True access: accounts,drives - name: modify admin user na_elementsw_admin_users: state: present username: "{{ admin_user_name }}" password: "{{ admin_password }}" hostname: "{{ hostname }}" element_username: carchi8py element_password: carchi8py12 acceptEula: True access: accounts,drives,nodes - name: delete admin user na_elementsw_admin_users: state: absent username: "{{ admin_user_name }}" password: "{{ admin_password }}" hostname: "{{ hostname }}" element_username: carchi8py """ RETURN = """ """ import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native import ansible.module_utils.netapp as netapp_utils from ansible.module_utils.netapp_elementsw_module import NaElementSWModule HAS_SF_SDK = netapp_utils.has_sf_sdk() class NetAppElementSWAdminUser(object): """ Class to set, modify and delete admin users on ElementSW box """ def __init__(self): """ Initialize the NetAppElementSWAdminUser class. """ self.argument_spec = netapp_utils.ontap_sf_host_argument_spec() self.argument_spec.update(dict( state=dict(required=True, choices=['present', 'absent']), element_username=dict(required=True, type='str'), element_password=dict(required=False, type='str', no_log=True), acceptEula=dict(required=False, type='bool'), access=dict(required=False, type='list') )) self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) param = self.module.params # set up state variables self.state = param['state'] self.element_username = param['element_username'] self.element_password = param['element_password'] self.acceptEula = param['acceptEula'] self.access = param['access'] if HAS_SF_SDK is False: self.module.fail_json(msg="Unable to import the SolidFire Python SDK") else: self.sfe = netapp_utils.create_sf_connection(module=self.module) self.elementsw_helper = NaElementSWModule(self.sfe) # add telemetry attributes self.attributes = self.elementsw_helper.set_element_attributes(source='na_elementsw_admin_users') def does_admin_user_exist(self): """ Checks to see if an admin user exists or not :return: True if the user exist, False if it dose not exist """ admins_list = self.sfe.list_cluster_admins() for admin in admins_list.cluster_admins: if admin.username == self.element_username: return True return False def get_admin_user(self): """ Get the admin user object :return: the admin user object """ admins_list = self.sfe.list_cluster_admins() for admin in admins_list.cluster_admins: if admin.username == self.element_username: return admin return None def modify_admin_user(self): """ Modify a admin user. If a password is set the user will be modified as there is no way to compare a new password with an existing one :return: if a user was modified or not """ changed = False admin_user = self.get_admin_user() if self.access is not None and len(self.access) > 0: for access in self.access: if access not in admin_user.access: changed = True if changed: self.sfe.modify_cluster_admin(cluster_admin_id=admin_user.cluster_admin_id, access=self.access, password=self.element_password, attributes=self.attributes) return changed def add_admin_user(self): """ Add's a new admin user to the element cluster :return: nothing """ self.sfe.add_cluster_admin(username=self.element_username, password=self.element_password, access=self.access, accept_eula=self.acceptEula, attributes=self.attributes) def delete_admin_user(self): """ Deletes an existing admin user from the element cluster :return: nothing """ admin_user = self.get_admin_user() self.sfe.remove_cluster_admin(cluster_admin_id=admin_user.cluster_admin_id) def apply(self): """ determines which method to call to set, delete or modify admin users :return: """ changed = False if self.state == "present": if self.does_admin_user_exist(): changed = self.modify_admin_user() else: self.add_admin_user() changed = True else: if self.does_admin_user_exist(): self.delete_admin_user() changed = True self.module.exit_json(changed=changed) def main(): v = NetAppElementSWAdminUser() v.apply() if __name__ == '__main__': main()
gpl-3.0
mathieurodic/hamsterdb
python/samples/db1.py
2
2752
# # Copyright (C) 2005-2015 Christoph Rupp (chris@crupp.de). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # A simple example which creates a database, inserts some values, # looks them up and erases them. # # This sample is similar to samples/db1.c. # # set the library path, otherwise hamsterdb.so/.dll is not found import os import sys import struct import distutils.util p = distutils.util.get_platform() ps = ".%s-%s" % (p, sys.version[0:3]) sys.path.insert(0, os.path.join('build', 'lib' + ps)) sys.path.insert(1, os.path.join('..', 'build', 'lib' + ps)) import hamsterdb LOOP = 100 DATABASE_NAME = 1 # First create a new hamsterdb Environment env = hamsterdb.env() env.create("test.db") # And then create a Database in this Environment. The Database is # configured for uint32 keys and uint32 records db = env.create_db(DATABASE_NAME, 0, \ ((hamsterdb.HAM_PARAM_KEY_TYPE, hamsterdb.HAM_TYPE_UINT32), \ (hamsterdb.HAM_PARAM_RECORD_SIZE, 4))) # # Now we can insert, delete or lookup values in the database # # For our test program, we just insert a few values, then look them # up, then delete them and try to look them up again (which will fail). # For simplicity we set keys and records to the same value. # for i in range(0, LOOP): # The first parameter specifies the Transaction. We don't use any, # therefore set to None s = struct.pack('I', i) db.insert(None, s, s) # # Now lookup all values # for i in range(0, LOOP): s = struct.pack('I', i) record = db.find(None, s) # verify the value assert i == struct.unpack('I', record)[0] assert s == record # # Close the database handle, then re-open it (to demonstrate how to open # an Environment and a Database) # db.close() env.close() env.open("test.db") db = env.open_db(DATABASE_NAME) # now erase all values for i in range(0, LOOP): s = struct.pack('I', i) db.erase(None, s) # # Once more try to find all values. every db.find() call must # now fail with HAM_KEY_NOT_FOUND # for i in range(0, LOOP): try: s = struct.pack('I', i) record = db.find(None, s) except hamsterdb.error, (errno, strerror): assert hamsterdb.HAM_KEY_NOT_FOUND == errno # # done! Close all handles # db.close() env.close() print "success!"
apache-2.0
amyvmiwei/kbengine
kbe/src/lib/python/Lib/distutils/tests/test_util.py
94
11250
"""Tests for distutils.util.""" import os import sys import unittest from copy import copy from test.support import run_unittest from distutils.errors import DistutilsPlatformError, DistutilsByteCompileError from distutils.util import (get_platform, convert_path, change_root, check_environ, split_quoted, strtobool, rfc822_escape, byte_compile, grok_environment_error) from distutils import util # used to patch _environ_checked from distutils.sysconfig import get_config_vars from distutils import sysconfig from distutils.tests import support import _osx_support class UtilTestCase(support.EnvironGuard, unittest.TestCase): def setUp(self): super(UtilTestCase, self).setUp() # saving the environment self.name = os.name self.platform = sys.platform self.version = sys.version self.sep = os.sep self.join = os.path.join self.isabs = os.path.isabs self.splitdrive = os.path.splitdrive self._config_vars = copy(sysconfig._config_vars) # patching os.uname if hasattr(os, 'uname'): self.uname = os.uname self._uname = os.uname() else: self.uname = None self._uname = None os.uname = self._get_uname def tearDown(self): # getting back the environment os.name = self.name sys.platform = self.platform sys.version = self.version os.sep = self.sep os.path.join = self.join os.path.isabs = self.isabs os.path.splitdrive = self.splitdrive if self.uname is not None: os.uname = self.uname else: del os.uname sysconfig._config_vars = copy(self._config_vars) super(UtilTestCase, self).tearDown() def _set_uname(self, uname): self._uname = uname def _get_uname(self): return self._uname def test_get_platform(self): # windows XP, 32bits os.name = 'nt' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' '[MSC v.1310 32 bit (Intel)]') sys.platform = 'win32' self.assertEqual(get_platform(), 'win32') # windows XP, amd64 os.name = 'nt' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' '[MSC v.1310 32 bit (Amd64)]') sys.platform = 'win32' self.assertEqual(get_platform(), 'win-amd64') # windows XP, itanium os.name = 'nt' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' '[MSC v.1310 32 bit (Itanium)]') sys.platform = 'win32' self.assertEqual(get_platform(), 'win-ia64') # macbook os.name = 'posix' sys.version = ('2.5 (r25:51918, Sep 19 2006, 08:49:13) ' '\n[GCC 4.0.1 (Apple Computer, Inc. build 5341)]') sys.platform = 'darwin' self._set_uname(('Darwin', 'macziade', '8.11.1', ('Darwin Kernel Version 8.11.1: ' 'Wed Oct 10 18:23:28 PDT 2007; ' 'root:xnu-792.25.20~1/RELEASE_I386'), 'i386')) _osx_support._remove_original_values(get_config_vars()) get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.3' get_config_vars()['CFLAGS'] = ('-fno-strict-aliasing -DNDEBUG -g ' '-fwrapv -O3 -Wall -Wstrict-prototypes') cursize = sys.maxsize sys.maxsize = (2 ** 31)-1 try: self.assertEqual(get_platform(), 'macosx-10.3-i386') finally: sys.maxsize = cursize # macbook with fat binaries (fat, universal or fat64) _osx_support._remove_original_values(get_config_vars()) get_config_vars()['MACOSX_DEPLOYMENT_TARGET'] = '10.4' get_config_vars()['CFLAGS'] = ('-arch ppc -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-fat') _osx_support._remove_original_values(get_config_vars()) os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.1' self.assertEqual(get_platform(), 'macosx-10.4-fat') _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-intel') _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-fat3') _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-universal') _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3') self.assertEqual(get_platform(), 'macosx-10.4-fat64') for arch in ('ppc', 'i386', 'x86_64', 'ppc64'): _osx_support._remove_original_values(get_config_vars()) get_config_vars()['CFLAGS'] = ('-arch %s -isysroot ' '/Developer/SDKs/MacOSX10.4u.sdk ' '-fno-strict-aliasing -fno-common ' '-dynamic -DNDEBUG -g -O3'%(arch,)) self.assertEqual(get_platform(), 'macosx-10.4-%s'%(arch,)) # linux debian sarge os.name = 'posix' sys.version = ('2.3.5 (#1, Jul 4 2007, 17:28:59) ' '\n[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)]') sys.platform = 'linux2' self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7', '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686')) self.assertEqual(get_platform(), 'linux-i686') # XXX more platforms to tests here def test_convert_path(self): # linux/mac os.sep = '/' def _join(path): return '/'.join(path) os.path.join = _join self.assertEqual(convert_path('/home/to/my/stuff'), '/home/to/my/stuff') # win os.sep = '\\' def _join(*path): return '\\'.join(path) os.path.join = _join self.assertRaises(ValueError, convert_path, '/home/to/my/stuff') self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/') self.assertEqual(convert_path('home/to/my/stuff'), 'home\\to\\my\\stuff') self.assertEqual(convert_path('.'), os.curdir) def test_change_root(self): # linux/mac os.name = 'posix' def _isabs(path): return path[0] == '/' os.path.isabs = _isabs def _join(*path): return '/'.join(path) os.path.join = _join self.assertEqual(change_root('/root', '/old/its/here'), '/root/old/its/here') self.assertEqual(change_root('/root', 'its/here'), '/root/its/here') # windows os.name = 'nt' def _isabs(path): return path.startswith('c:\\') os.path.isabs = _isabs def _splitdrive(path): if path.startswith('c:'): return ('', path.replace('c:', '')) return ('', path) os.path.splitdrive = _splitdrive def _join(*path): return '\\'.join(path) os.path.join = _join self.assertEqual(change_root('c:\\root', 'c:\\old\\its\\here'), 'c:\\root\\old\\its\\here') self.assertEqual(change_root('c:\\root', 'its\\here'), 'c:\\root\\its\\here') # BugsBunny os (it's a great os) os.name = 'BugsBunny' self.assertRaises(DistutilsPlatformError, change_root, 'c:\\root', 'its\\here') # XXX platforms to be covered: mac def test_check_environ(self): util._environ_checked = 0 if 'HOME' in os.environ: del os.environ['HOME'] # posix without HOME if os.name == 'posix': # this test won't run on windows check_environ() import pwd self.assertEqual(os.environ['HOME'], pwd.getpwuid(os.getuid())[5]) else: check_environ() self.assertEqual(os.environ['PLAT'], get_platform()) self.assertEqual(util._environ_checked, 1) def test_split_quoted(self): self.assertEqual(split_quoted('""one"" "two" \'three\' \\four'), ['one', 'two', 'three', 'four']) def test_strtobool(self): yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1') no = ('n', 'no', 'f', 'false', 'off', '0', 'Off', 'No', 'N') for y in yes: self.assertTrue(strtobool(y)) for n in no: self.assertFalse(strtobool(n)) def test_rfc822_escape(self): header = 'I am a\npoor\nlonesome\nheader\n' res = rfc822_escape(header) wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s' 'header%(8s)s') % {'8s': '\n'+8*' '} self.assertEqual(res, wanted) def test_dont_write_bytecode(self): # makes sure byte_compile raise a DistutilsError # if sys.dont_write_bytecode is True old_dont_write_bytecode = sys.dont_write_bytecode sys.dont_write_bytecode = True try: self.assertRaises(DistutilsByteCompileError, byte_compile, []) finally: sys.dont_write_bytecode = old_dont_write_bytecode def test_grok_environment_error(self): # test obsolete function to ensure backward compat (#4931) exc = IOError("Unable to find batch file") msg = grok_environment_error(exc) self.assertEqual(msg, "error: Unable to find batch file") def test_suite(): return unittest.makeSuite(UtilTestCase) if __name__ == "__main__": run_unittest(test_suite())
lgpl-3.0
robbiet480/home-assistant
homeassistant/helpers/collection.py
5
15156
"""Helper to deal with YAML + storage.""" from abc import ABC, abstractmethod import asyncio import logging from typing import Any, Awaitable, Callable, Dict, List, Optional, cast import voluptuous as vol from voluptuous.humanize import humanize_error from homeassistant.components import websocket_api from homeassistant.const import CONF_ID from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.storage import Store from homeassistant.helpers.typing import HomeAssistantType from homeassistant.util import slugify STORAGE_VERSION = 1 SAVE_DELAY = 10 CHANGE_ADDED = "added" CHANGE_UPDATED = "updated" CHANGE_REMOVED = "removed" ChangeListener = Callable[ [ # Change type str, # Item ID str, # New or removed config dict, ], Awaitable[None], ] class CollectionError(HomeAssistantError): """Base class for collection related errors.""" class ItemNotFound(CollectionError): """Raised when an item is not found.""" def __init__(self, item_id: str): """Initialize item not found error.""" super().__init__(f"Item {item_id} not found.") self.item_id = item_id class IDManager: """Keep track of IDs across different collections.""" def __init__(self) -> None: """Initiate the ID manager.""" self.collections: List[Dict[str, Any]] = [] def add_collection(self, collection: Dict[str, Any]) -> None: """Add a collection to check for ID usage.""" self.collections.append(collection) def has_id(self, item_id: str) -> bool: """Test if the ID exists.""" return any(item_id in collection for collection in self.collections) def generate_id(self, suggestion: str) -> str: """Generate an ID.""" base = slugify(suggestion) proposal = base attempt = 1 while self.has_id(proposal): attempt += 1 proposal = f"{base}_{attempt}" return proposal class ObservableCollection(ABC): """Base collection type that can be observed.""" def __init__(self, logger: logging.Logger, id_manager: Optional[IDManager] = None): """Initialize the base collection.""" self.logger = logger self.id_manager = id_manager or IDManager() self.data: Dict[str, dict] = {} self.listeners: List[ChangeListener] = [] self.id_manager.add_collection(self.data) @callback def async_items(self) -> List[dict]: """Return list of items in collection.""" return list(self.data.values()) @callback def async_add_listener(self, listener: ChangeListener) -> None: """Add a listener. Will be called with (change_type, item_id, updated_config). """ self.listeners.append(listener) async def notify_change(self, change_type: str, item_id: str, item: dict) -> None: """Notify listeners of a change.""" self.logger.debug("%s %s: %s", change_type, item_id, item) await asyncio.gather( *[listener(change_type, item_id, item) for listener in self.listeners] ) class YamlCollection(ObservableCollection): """Offer a collection based on static data.""" async def async_load(self, data: List[dict]) -> None: """Load the YAML collection. Overrides existing data.""" old_ids = set(self.data) tasks = [] for item in data: item_id = item[CONF_ID] if item_id in old_ids: old_ids.remove(item_id) event = CHANGE_UPDATED elif self.id_manager.has_id(item_id): self.logger.warning("Duplicate ID '%s' detected, skipping", item_id) continue else: event = CHANGE_ADDED self.data[item_id] = item tasks.append(self.notify_change(event, item_id, item)) for item_id in old_ids: tasks.append( self.notify_change(CHANGE_REMOVED, item_id, self.data.pop(item_id)) ) if tasks: await asyncio.gather(*tasks) class StorageCollection(ObservableCollection): """Offer a CRUD interface on top of JSON storage.""" def __init__( self, store: Store, logger: logging.Logger, id_manager: Optional[IDManager] = None, ): """Initialize the storage collection.""" super().__init__(logger, id_manager) self.store = store @property def hass(self) -> HomeAssistant: """Home Assistant object.""" return self.store.hass async def _async_load_data(self) -> Optional[dict]: """Load the data.""" return cast(Optional[dict], await self.store.async_load()) async def async_load(self) -> None: """Load the storage Manager.""" raw_storage = await self._async_load_data() if raw_storage is None: raw_storage = {"items": []} for item in raw_storage["items"]: self.data[item[CONF_ID]] = item await asyncio.gather( *[ self.notify_change(CHANGE_ADDED, item[CONF_ID], item) for item in raw_storage["items"] ] ) @abstractmethod async def _process_create_data(self, data: dict) -> dict: """Validate the config is valid.""" @callback @abstractmethod def _get_suggested_id(self, info: dict) -> str: """Suggest an ID based on the config.""" @abstractmethod async def _update_data(self, data: dict, update_data: dict) -> dict: """Return a new updated data object.""" async def async_create_item(self, data: dict) -> dict: """Create a new item.""" item = await self._process_create_data(data) item[CONF_ID] = self.id_manager.generate_id(self._get_suggested_id(item)) self.data[item[CONF_ID]] = item self._async_schedule_save() await self.notify_change(CHANGE_ADDED, item[CONF_ID], item) return item async def async_update_item(self, item_id: str, updates: dict) -> dict: """Update item.""" if item_id not in self.data: raise ItemNotFound(item_id) if CONF_ID in updates: raise ValueError("Cannot update ID") current = self.data[item_id] updated = await self._update_data(current, updates) self.data[item_id] = updated self._async_schedule_save() await self.notify_change(CHANGE_UPDATED, item_id, updated) return self.data[item_id] async def async_delete_item(self, item_id: str) -> None: """Delete item.""" if item_id not in self.data: raise ItemNotFound(item_id) item = self.data.pop(item_id) self._async_schedule_save() await self.notify_change(CHANGE_REMOVED, item_id, item) @callback def _async_schedule_save(self) -> None: """Schedule saving the area registry.""" self.store.async_delay_save(self._data_to_save, SAVE_DELAY) @callback def _data_to_save(self) -> dict: """Return data of area registry to store in a file.""" return {"items": list(self.data.values())} class IDLessCollection(ObservableCollection): """A collection without IDs.""" counter = 0 async def async_load(self, data: List[dict]) -> None: """Load the collection. Overrides existing data.""" await asyncio.gather( *[ self.notify_change(CHANGE_REMOVED, item_id, item) for item_id, item in list(self.data.items()) ] ) self.data.clear() for item in data: self.counter += 1 item_id = f"fakeid-{self.counter}" self.data[item_id] = item await asyncio.gather( *[ self.notify_change(CHANGE_ADDED, item_id, item) for item_id, item in self.data.items() ] ) @callback def attach_entity_component_collection( entity_component: EntityComponent, collection: ObservableCollection, create_entity: Callable[[dict], Entity], ) -> None: """Map a collection to an entity component.""" entities = {} async def _collection_changed(change_type: str, item_id: str, config: dict) -> None: """Handle a collection change.""" if change_type == CHANGE_ADDED: entity = create_entity(config) await entity_component.async_add_entities([entity]) entities[item_id] = entity return if change_type == CHANGE_REMOVED: entity = entities.pop(item_id) await entity.async_remove() return # CHANGE_UPDATED await entities[item_id].async_update_config(config) # type: ignore collection.async_add_listener(_collection_changed) @callback def attach_entity_registry_cleaner( hass: HomeAssistantType, domain: str, platform: str, collection: ObservableCollection, ) -> None: """Attach a listener to clean up entity registry on collection changes.""" async def _collection_changed(change_type: str, item_id: str, config: Dict) -> None: """Handle a collection change: clean up entity registry on removals.""" if change_type != CHANGE_REMOVED: return ent_reg = await entity_registry.async_get_registry(hass) ent_to_remove = ent_reg.async_get_entity_id(domain, platform, item_id) if ent_to_remove is not None: ent_reg.async_remove(ent_to_remove) collection.async_add_listener(_collection_changed) class StorageCollectionWebsocket: """Class to expose storage collection management over websocket.""" def __init__( self, storage_collection: StorageCollection, api_prefix: str, model_name: str, create_schema: dict, update_schema: dict, ): """Initialize a websocket CRUD.""" self.storage_collection = storage_collection self.api_prefix = api_prefix self.model_name = model_name self.create_schema = create_schema self.update_schema = update_schema assert self.api_prefix[-1] != "/", "API prefix should not end in /" @property def item_id_key(self) -> str: """Return item ID key.""" return f"{self.model_name}_id" @callback def async_setup(self, hass: HomeAssistant, *, create_list: bool = True) -> None: """Set up the websocket commands.""" if create_list: websocket_api.async_register_command( hass, f"{self.api_prefix}/list", self.ws_list_item, websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend( {vol.Required("type"): f"{self.api_prefix}/list"} ), ) websocket_api.async_register_command( hass, f"{self.api_prefix}/create", websocket_api.require_admin( websocket_api.async_response(self.ws_create_item) ), websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend( { **self.create_schema, vol.Required("type"): f"{self.api_prefix}/create", } ), ) websocket_api.async_register_command( hass, f"{self.api_prefix}/update", websocket_api.require_admin( websocket_api.async_response(self.ws_update_item) ), websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend( { **self.update_schema, vol.Required("type"): f"{self.api_prefix}/update", vol.Required(self.item_id_key): str, } ), ) websocket_api.async_register_command( hass, f"{self.api_prefix}/delete", websocket_api.require_admin( websocket_api.async_response(self.ws_delete_item) ), websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend( { vol.Required("type"): f"{self.api_prefix}/delete", vol.Required(self.item_id_key): str, } ), ) def ws_list_item( self, hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """List items.""" connection.send_result(msg["id"], self.storage_collection.async_items()) async def ws_create_item( self, hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Create a item.""" try: data = dict(msg) data.pop("id") data.pop("type") item = await self.storage_collection.async_create_item(data) connection.send_result(msg["id"], item) except vol.Invalid as err: connection.send_error( msg["id"], websocket_api.const.ERR_INVALID_FORMAT, humanize_error(data, err), ) except ValueError as err: connection.send_error( msg["id"], websocket_api.const.ERR_INVALID_FORMAT, str(err) ) async def ws_update_item( self, hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Update a item.""" data = dict(msg) msg_id = data.pop("id") item_id = data.pop(self.item_id_key) data.pop("type") try: item = await self.storage_collection.async_update_item(item_id, data) connection.send_result(msg_id, item) except ItemNotFound: connection.send_error( msg["id"], websocket_api.const.ERR_NOT_FOUND, f"Unable to find {self.item_id_key} {item_id}", ) except vol.Invalid as err: connection.send_error( msg["id"], websocket_api.const.ERR_INVALID_FORMAT, humanize_error(data, err), ) except ValueError as err: connection.send_error( msg_id, websocket_api.const.ERR_INVALID_FORMAT, str(err) ) async def ws_delete_item( self, hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Delete a item.""" try: await self.storage_collection.async_delete_item(msg[self.item_id_key]) except ItemNotFound: connection.send_error( msg["id"], websocket_api.const.ERR_NOT_FOUND, f"Unable to find {self.item_id_key} {msg[self.item_id_key]}", ) connection.send_result(msg["id"])
apache-2.0
ecoal95/servo
tests/wpt/web-platform-tests/tools/third_party/html5lib/html5lib/tests/test_alphabeticalattributes.py
47
2138
from __future__ import absolute_import, division, unicode_literals from collections import OrderedDict import pytest import html5lib from html5lib.filters.alphabeticalattributes import Filter from html5lib.serializer import HTMLSerializer @pytest.mark.parametrize('msg, attrs, expected_attrs', [ ( 'no attrs', {}, {} ), ( 'one attr', {(None, 'alt'): 'image'}, OrderedDict([((None, 'alt'), 'image')]) ), ( 'multiple attrs', { (None, 'src'): 'foo', (None, 'alt'): 'image', (None, 'style'): 'border: 1px solid black;' }, OrderedDict([ ((None, 'alt'), 'image'), ((None, 'src'), 'foo'), ((None, 'style'), 'border: 1px solid black;') ]) ), ]) def test_alphabetizing(msg, attrs, expected_attrs): tokens = [{'type': 'StartTag', 'name': 'img', 'data': attrs}] output_tokens = list(Filter(tokens)) attrs = output_tokens[0]['data'] assert attrs == expected_attrs def test_with_different_namespaces(): tokens = [{ 'type': 'StartTag', 'name': 'pattern', 'data': { (None, 'id'): 'patt1', ('http://www.w3.org/1999/xlink', 'href'): '#patt2' } }] output_tokens = list(Filter(tokens)) attrs = output_tokens[0]['data'] assert attrs == OrderedDict([ ((None, 'id'), 'patt1'), (('http://www.w3.org/1999/xlink', 'href'), '#patt2') ]) def test_with_serializer(): """Verify filter works in the context of everything else""" parser = html5lib.HTMLParser() dom = parser.parseFragment('<svg><pattern xlink:href="#patt2" id="patt1"></svg>') walker = html5lib.getTreeWalker('etree') ser = HTMLSerializer( alphabetical_attributes=True, quote_attr_values='always' ) # FIXME(willkg): The "xlink" namespace gets dropped by the serializer. When # that gets fixed, we can fix this expected result. assert ( ser.render(walker(dom)) == '<svg><pattern id="patt1" href="#patt2"></pattern></svg>' )
mpl-2.0
xflows/clowdflows
workflows/migrations/0002_auto__add_field_output_value.py
6
13083
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Output.value' db.add_column('workflows_output', 'value', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'Output.value' db.delete_column('workflows_output', 'value') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'workflows.abstractinput': { 'Meta': {'object_name': 'AbstractInput'}, 'default': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'parameter': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'parameter_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'short_name': ('django.db.models.fields.CharField', [], {'max_length': '3'}), 'variable': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'widget': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'inputs'", 'to': "orm['workflows.AbstractWidget']"}) }, 'workflows.abstractoption': { 'Meta': {'object_name': 'AbstractOption'}, 'abstract_input': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'to': "orm['workflows.AbstractInput']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'value': ('django.db.models.fields.TextField', [], {'blank': 'True'}) }, 'workflows.abstractoutput': { 'Meta': {'object_name': 'AbstractOutput'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'short_name': ('django.db.models.fields.CharField', [], {'max_length': '3'}), 'variable': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'widget': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'outputs'", 'to': "orm['workflows.AbstractWidget']"}) }, 'workflows.abstractwidget': { 'Meta': {'object_name': 'AbstractWidget'}, 'action': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'widgets'", 'to': "orm['workflows.Category']"}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'wsdl': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}) }, 'workflows.category': { 'Meta': {'ordering': "['name']", 'object_name': 'Category'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['workflows.Category']"}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}) }, 'workflows.connection': { 'Meta': {'object_name': 'Connection'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'input': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'connections'", 'to': "orm['workflows.Input']"}), 'output': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'connections'", 'to': "orm['workflows.Output']"}), 'workflow': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'connections'", 'to': "orm['workflows.Workflow']"}) }, 'workflows.data': { 'Meta': {'object_name': 'Data'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'value': ('django.db.models.fields.TextField', [], {}) }, 'workflows.input': { 'Meta': {'object_name': 'Input'}, 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'inner_output': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'outer_input_rel'", 'null': 'True', 'to': "orm['workflows.Output']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'outer_output': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inner_input_rel'", 'null': 'True', 'to': "orm['workflows.Output']"}), 'parameter': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'parameter_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'short_name': ('django.db.models.fields.CharField', [], {'max_length': '3'}), 'value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'variable': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'widget': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'inputs'", 'to': "orm['workflows.Widget']"}) }, 'workflows.option': { 'Meta': {'object_name': 'Option'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'input': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'to': "orm['workflows.Input']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) }, 'workflows.output': { 'Meta': {'object_name': 'Output'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'inner_input': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'outer_output_rel'", 'null': 'True', 'to': "orm['workflows.Input']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'outer_input': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'inner_output_rel'", 'null': 'True', 'to': "orm['workflows.Input']"}), 'short_name': ('django.db.models.fields.CharField', [], {'max_length': '5'}), 'value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'variable': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'widget': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'outputs'", 'to': "orm['workflows.Widget']"}) }, 'workflows.userprofile': { 'Meta': {'object_name': 'UserProfile'}, 'active_workflow': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'users'", 'null': 'True', 'to': "orm['workflows.Workflow']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'workflows.widget': { 'Meta': {'object_name': 'Widget'}, 'abstract_widget': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'instances'", 'null': 'True', 'to': "orm['workflows.AbstractWidget']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'workflow': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'widgets'", 'to': "orm['workflows.Workflow']"}), 'x': ('django.db.models.fields.IntegerField', [], {}), 'y': ('django.db.models.fields.IntegerField', [], {}) }, 'workflows.workflow': { 'Meta': {'object_name': 'Workflow'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "'Untitled workflow'", 'max_length': '200'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'workflows'", 'to': "orm['auth.User']"}), 'widget': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'workflow_link'", 'unique': 'True', 'null': 'True', 'to': "orm['workflows.Widget']"}) } } complete_apps = ['workflows']
mit
54Pany/shadowsocks
shadowsocks/encrypt.py
990
5180
#!/usr/bin/env python # # Copyright 2012-2015 clowwindy # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import, division, print_function, \ with_statement import os import sys import hashlib import logging from shadowsocks import common from shadowsocks.crypto import rc4_md5, openssl, sodium, table method_supported = {} method_supported.update(rc4_md5.ciphers) method_supported.update(openssl.ciphers) method_supported.update(sodium.ciphers) method_supported.update(table.ciphers) def random_string(length): return os.urandom(length) cached_keys = {} def try_cipher(key, method=None): Encryptor(key, method) def EVP_BytesToKey(password, key_len, iv_len): # equivalent to OpenSSL's EVP_BytesToKey() with count 1 # so that we make the same key and iv as nodejs version cached_key = '%s-%d-%d' % (password, key_len, iv_len) r = cached_keys.get(cached_key, None) if r: return r m = [] i = 0 while len(b''.join(m)) < (key_len + iv_len): md5 = hashlib.md5() data = password if i > 0: data = m[i - 1] + password md5.update(data) m.append(md5.digest()) i += 1 ms = b''.join(m) key = ms[:key_len] iv = ms[key_len:key_len + iv_len] cached_keys[cached_key] = (key, iv) return key, iv class Encryptor(object): def __init__(self, key, method): self.key = key self.method = method self.iv = None self.iv_sent = False self.cipher_iv = b'' self.decipher = None method = method.lower() self._method_info = self.get_method_info(method) if self._method_info: self.cipher = self.get_cipher(key, method, 1, random_string(self._method_info[1])) else: logging.error('method %s not supported' % method) sys.exit(1) def get_method_info(self, method): method = method.lower() m = method_supported.get(method) return m def iv_len(self): return len(self.cipher_iv) def get_cipher(self, password, method, op, iv): password = common.to_bytes(password) m = self._method_info if m[0] > 0: key, iv_ = EVP_BytesToKey(password, m[0], m[1]) else: # key_length == 0 indicates we should use the key directly key, iv = password, b'' iv = iv[:m[1]] if op == 1: # this iv is for cipher not decipher self.cipher_iv = iv[:m[1]] return m[2](method, key, iv, op) def encrypt(self, buf): if len(buf) == 0: return buf if self.iv_sent: return self.cipher.update(buf) else: self.iv_sent = True return self.cipher_iv + self.cipher.update(buf) def decrypt(self, buf): if len(buf) == 0: return buf if self.decipher is None: decipher_iv_len = self._method_info[1] decipher_iv = buf[:decipher_iv_len] self.decipher = self.get_cipher(self.key, self.method, 0, iv=decipher_iv) buf = buf[decipher_iv_len:] if len(buf) == 0: return buf return self.decipher.update(buf) def encrypt_all(password, method, op, data): result = [] method = method.lower() (key_len, iv_len, m) = method_supported[method] if key_len > 0: key, _ = EVP_BytesToKey(password, key_len, iv_len) else: key = password if op: iv = random_string(iv_len) result.append(iv) else: iv = data[:iv_len] data = data[iv_len:] cipher = m(method, key, iv, op) result.append(cipher.update(data)) return b''.join(result) CIPHERS_TO_TEST = [ 'aes-128-cfb', 'aes-256-cfb', 'rc4-md5', 'salsa20', 'chacha20', 'table', ] def test_encryptor(): from os import urandom plain = urandom(10240) for method in CIPHERS_TO_TEST: logging.warn(method) encryptor = Encryptor(b'key', method) decryptor = Encryptor(b'key', method) cipher = encryptor.encrypt(plain) plain2 = decryptor.decrypt(cipher) assert plain == plain2 def test_encrypt_all(): from os import urandom plain = urandom(10240) for method in CIPHERS_TO_TEST: logging.warn(method) cipher = encrypt_all(b'key', method, 1, plain) plain2 = encrypt_all(b'key', method, 0, cipher) assert plain == plain2 if __name__ == '__main__': test_encrypt_all() test_encryptor()
apache-2.0
ovnicraft/openerp-restaurant
account_analytic_plans/report/__init__.py
445
1084
# -*- 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 crossovered_analytic # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
TunedMystic/normandy
webapp/settings/dev.py
2
1045
""" Django development settings. """ from base import * import os # --- Debug Settings --- DEBUG = TEMPLATE_DEBUG = True # --- /Debug Settings --- # --- Email Configuration --- # https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # --- /Email Configuration --- # --- Celery Configuration --- # http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html INSTALLED_APPS += ( "kombu.transport.django", ) BROKER_URL = "django://" # --- /Celery Configuration --- # --- Django Faker Configuration --- INSTALLED_APPS += ( "django_faker", ) FAKER_LOCALE = None FAKER_PROVIDERS = None # --- /Django Faker Configuration --- # --- Django-Debug-Toolbar Settings --- show_toolbar = lambda x: True INSTALLED_APPS += ("debug_toolbar",) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) DEBUG_TOOLBAR_CONFIG = { 'SHOW_TOOLBAR_CALLBACK': 'webapp.settings.dev.show_toolbar', } # --- /Django-Debug-Toolbar Settings ---
gpl-2.0
wjcjenny/jinja2
jinja2/compiler.py
335
63846
# -*- coding: utf-8 -*- """ jinja2.compiler ~~~~~~~~~~~~~~~ Compiles nodes into python code. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ from itertools import chain from copy import deepcopy from keyword import iskeyword as is_python_keyword from jinja2 import nodes from jinja2.nodes import EvalContext from jinja2.visitor import NodeVisitor from jinja2.exceptions import TemplateAssertionError from jinja2.utils import Markup, concat, escape from jinja2._compat import range_type, text_type, string_types, \ iteritems, NativeStringIO, imap operators = { 'eq': '==', 'ne': '!=', 'gt': '>', 'gteq': '>=', 'lt': '<', 'lteq': '<=', 'in': 'in', 'notin': 'not in' } # what method to iterate over items do we want to use for dict iteration # in generated code? on 2.x let's go with iteritems, on 3.x with items if hasattr(dict, 'iteritems'): dict_item_iter = 'iteritems' else: dict_item_iter = 'items' # does if 0: dummy(x) get us x into the scope? def unoptimize_before_dead_code(): x = 42 def f(): if 0: dummy(x) return f # The getattr is necessary for pypy which does not set this attribute if # no closure is on the function unoptimize_before_dead_code = bool( getattr(unoptimize_before_dead_code(), '__closure__', None)) def generate(node, environment, name, filename, stream=None, defer_init=False): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = environment.code_generator_class(environment, name, filename, stream, defer_init) generator.visit(node) if stream is None: return generator.stream.getvalue() def has_safe_repr(value): """Does the node have a safe representation?""" if value is None or value is NotImplemented or value is Ellipsis: return True if isinstance(value, (bool, int, float, complex, range_type, Markup) + string_types): return True if isinstance(value, (tuple, list, set, frozenset)): for item in value: if not has_safe_repr(item): return False return True elif isinstance(value, dict): for key, value in iteritems(value): if not has_safe_repr(key): return False if not has_safe_repr(value): return False return True return False def find_undeclared(nodes, names): """Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found. """ visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except VisitorExit: pass return visitor.undeclared class Identifiers(object): """Tracks the status of identifiers in frames.""" def __init__(self): # variables that are known to be declared (probably from outer # frames or because they are special for the frame) self.declared = set() # undeclared variables from outer scopes self.outer_undeclared = set() # names that are accessed without being explicitly declared by # this one or any of the outer scopes. Names can appear both in # declared and undeclared. self.undeclared = set() # names that are declared locally self.declared_locally = set() # names that are declared by parameters self.declared_parameter = set() def add_special(self, name): """Register a special name like `loop`.""" self.undeclared.discard(name) self.declared.add(name) def is_declared(self, name): """Check if a name is declared in this or an outer scope.""" if name in self.declared_locally or name in self.declared_parameter: return True return name in self.declared def copy(self): return deepcopy(self) class Frame(object): """Holds compile time information for us.""" def __init__(self, eval_ctx, parent=None): self.eval_ctx = eval_ctx self.identifiers = Identifiers() # a toplevel frame is the root + soft frames such as if conditions. self.toplevel = False # the root frame is basically just the outermost frame, so no if # conditions. This information is used to optimize inheritance # situations. self.rootlevel = False # in some dynamic inheritance situations the compiler needs to add # write tests around output statements. self.require_output_check = parent and parent.require_output_check # inside some tags we are using a buffer rather than yield statements. # this for example affects {% filter %} or {% macro %}. If a frame # is buffered this variable points to the name of the list used as # buffer. self.buffer = None # the name of the block we're in, otherwise None. self.block = parent and parent.block or None # a set of actually assigned names self.assigned_names = set() # the parent of this frame self.parent = parent if parent is not None: self.identifiers.declared.update( parent.identifiers.declared | parent.identifiers.declared_parameter | parent.assigned_names ) self.identifiers.outer_undeclared.update( parent.identifiers.undeclared - self.identifiers.declared ) self.buffer = parent.buffer def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.identifiers = object.__new__(self.identifiers.__class__) rv.identifiers.__dict__.update(self.identifiers.__dict__) return rv def inspect(self, nodes): """Walk the node and check for identifiers. If the scope is hard (eg: enforce on a python level) overrides from outer scopes are tracked differently. """ visitor = FrameIdentifierVisitor(self.identifiers) for node in nodes: visitor.visit(node) def find_shadowed(self, extra=()): """Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped. """ i = self.identifiers return (i.declared | i.outer_undeclared) & \ (i.declared_locally | i.declared_parameter) | \ set(x for x in extra if i.is_declared(x)) def inner(self): """Return an inner frame.""" return Frame(self.eval_ctx, self) def soft(self): """Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. """ rv = self.copy() rv.rootlevel = False return rv __copy__ = copy class VisitorExit(RuntimeError): """Exception used by the `UndeclaredNameVisitor` to signal a stop.""" class DependencyFinderVisitor(NodeVisitor): """A visitor that collects filter and test calls.""" def __init__(self): self.filters = set() self.tests = set() def visit_Filter(self, node): self.generic_visit(node) self.filters.add(node.name) def visit_Test(self, node): self.generic_visit(node) self.tests.add(node.name) def visit_Block(self, node): """Stop visiting at blocks.""" class UndeclaredNameVisitor(NodeVisitor): """A visitor that checks if a name is accessed without being declared. This is different from the frame visitor as it will not stop at closure frames. """ def __init__(self, names): self.names = set(names) self.undeclared = set() def visit_Name(self, node): if node.ctx == 'load' and node.name in self.names: self.undeclared.add(node.name) if self.undeclared == self.names: raise VisitorExit() else: self.names.discard(node.name) def visit_Block(self, node): """Stop visiting a blocks.""" class FrameIdentifierVisitor(NodeVisitor): """A visitor for `Frame.inspect`.""" def __init__(self, identifiers): self.identifiers = identifiers def visit_Name(self, node): """All assignments to names go through this function.""" if node.ctx == 'store': self.identifiers.declared_locally.add(node.name) elif node.ctx == 'param': self.identifiers.declared_parameter.add(node.name) elif node.ctx == 'load' and not \ self.identifiers.is_declared(node.name): self.identifiers.undeclared.add(node.name) def visit_If(self, node): self.visit(node.test) real_identifiers = self.identifiers old_names = real_identifiers.declared_locally | \ real_identifiers.declared_parameter def inner_visit(nodes): if not nodes: return set() self.identifiers = real_identifiers.copy() for subnode in nodes: self.visit(subnode) rv = self.identifiers.declared_locally - old_names # we have to remember the undeclared variables of this branch # because we will have to pull them. real_identifiers.undeclared.update(self.identifiers.undeclared) self.identifiers = real_identifiers return rv body = inner_visit(node.body) else_ = inner_visit(node.else_ or ()) # the differences between the two branches are also pulled as # undeclared variables real_identifiers.undeclared.update(body.symmetric_difference(else_) - real_identifiers.declared) # remember those that are declared. real_identifiers.declared_locally.update(body | else_) def visit_Macro(self, node): self.identifiers.declared_locally.add(node.name) def visit_Import(self, node): self.generic_visit(node) self.identifiers.declared_locally.add(node.target) def visit_FromImport(self, node): self.generic_visit(node) for name in node.names: if isinstance(name, tuple): self.identifiers.declared_locally.add(name[1]) else: self.identifiers.declared_locally.add(name) def visit_Assign(self, node): """Visit assignments in the correct order.""" self.visit(node.node) self.visit(node.target) def visit_For(self, node): """Visiting stops at for blocks. However the block sequence is visited as part of the outer scope. """ self.visit(node.iter) def visit_CallBlock(self, node): self.visit(node.call) def visit_FilterBlock(self, node): self.visit(node.filter) def visit_AssignBlock(self, node): """Stop visiting at block assigns.""" def visit_Scope(self, node): """Stop visiting at scopes.""" def visit_Block(self, node): """Stop visiting at blocks.""" class CompilerExit(Exception): """Raised if the compiler encountered a situation where it just doesn't make sense to further process the code. Any block that raises such an exception is not further processed. """ class CodeGenerator(NodeVisitor): def __init__(self, environment, name, filename, stream=None, defer_init=False): if stream is None: stream = NativeStringIO() self.environment = environment self.name = name self.filename = filename self.stream = stream self.created_block_context = False self.defer_init = defer_init # aliases for imports self.import_aliases = {} # a registry for all blocks. Because blocks are moved out # into the global python scope they are registered here self.blocks = {} # the number of extends statements so far self.extends_so_far = 0 # some templates have a rootlevel extends. In this case we # can safely assume that we're a child template and do some # more optimizations. self.has_known_extends = False # the current line number self.code_lineno = 1 # registry of all filters and tests (global, not block local) self.tests = {} self.filters = {} # the debug information self.debug_info = [] self._write_debug_info = None # the number of new lines before the next write() self._new_lines = 0 # the line number of the last written statement self._last_line = 0 # true if nothing was written so far. self._first_write = True # used by the `temporary_identifier` method to get new # unique, temporary identifier self._last_identifier = 0 # the current indentation self._indentation = 0 # -- Various compilation helpers def fail(self, msg, lineno): """Fail with a :exc:`TemplateAssertionError`.""" raise TemplateAssertionError(msg, lineno, self.name, self.filename) def temporary_identifier(self): """Get a new unique identifier.""" self._last_identifier += 1 return 't_%d' % self._last_identifier def buffer(self, frame): """Enable buffering for the frame from that point onwards.""" frame.buffer = self.temporary_identifier() self.writeline('%s = []' % frame.buffer) def return_buffer_contents(self, frame): """Return the buffer contents of the frame.""" if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('return Markup(concat(%s))' % frame.buffer) self.outdent() self.writeline('else:') self.indent() self.writeline('return concat(%s)' % frame.buffer) self.outdent() elif frame.eval_ctx.autoescape: self.writeline('return Markup(concat(%s))' % frame.buffer) else: self.writeline('return concat(%s)' % frame.buffer) def indent(self): """Indent by one.""" self._indentation += 1 def outdent(self, step=1): """Outdent by step.""" self._indentation -= step def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node) def end_write(self, frame): """End the writing process started by `start_write`.""" if frame.buffer is not None: self.write(')') def simple_write(self, s, frame, node=None): """Simple shortcut for start_write + write + end_write.""" self.start_write(frame, node) self.write(s) self.end_write(frame) def blockvisit(self, nodes, frame): """Visit a list of nodes as block in a frame. If the current frame is no buffer a dummy ``if 0: yield None`` is written automatically unless the force_generator parameter is set to False. """ if frame.buffer is None: self.writeline('if 0: yield None') else: self.writeline('pass') try: for node in nodes: self.visit(node, frame) except CompilerExit: pass def write(self, x): """Write a string into the output stream.""" if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: self.debug_info.append((self._write_debug_info, self.code_lineno)) self._write_debug_info = None self._first_write = False self.stream.write(' ' * self._indentation) self._new_lines = 0 self.stream.write(x) def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x) def newline(self, node=None, extra=0): """Add one or more newlines before the next write.""" self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno def signature(self, node, frame, extra_kwargs=None): """Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments should be given as python dict. """ # if any of the given keyword arguments is a python keyword # we have to make sure that no invalid call is created. kwarg_workaround = False for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()): if is_python_keyword(kwarg): kwarg_workaround = True break for arg in node.args: self.write(', ') self.visit(arg, frame) if not kwarg_workaround: for kwarg in node.kwargs: self.write(', ') self.visit(kwarg, frame) if extra_kwargs is not None: for key, value in iteritems(extra_kwargs): self.write(', %s=%s' % (key, value)) if node.dyn_args: self.write(', *') self.visit(node.dyn_args, frame) if kwarg_workaround: if node.dyn_kwargs is not None: self.write(', **dict({') else: self.write(', **{') for kwarg in node.kwargs: self.write('%r: ' % kwarg.key) self.visit(kwarg.value, frame) self.write(', ') if extra_kwargs is not None: for key, value in iteritems(extra_kwargs): self.write('%r: %s, ' % (key, value)) if node.dyn_kwargs is not None: self.write('}, **') self.visit(node.dyn_kwargs, frame) self.write(')') else: self.write('}') elif node.dyn_kwargs is not None: self.write(', **') self.visit(node.dyn_kwargs, frame) def pull_locals(self, frame): """Pull all the references identifiers into the local scope.""" for name in frame.identifiers.undeclared: self.writeline('l_%s = context.resolve(%r)' % (name, name)) def pull_dependencies(self, nodes): """Pull all the dependencies.""" visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for dependency in 'filters', 'tests': mapping = getattr(self, dependency) for name in getattr(visitor, dependency): if name not in mapping: mapping[name] = self.temporary_identifier() self.writeline('%s = environment.%s[%r]' % (mapping[name], dependency, name)) def unoptimize_scope(self, frame): """Disable Python optimizations for the frame.""" # XXX: this is not that nice but it has no real overhead. It # mainly works because python finds the locals before dead code # is removed. If that breaks we have to add a dummy function # that just accepts the arguments and does nothing. if frame.identifiers.declared: self.writeline('%sdummy(%s)' % ( unoptimize_before_dead_code and 'if 0: ' or '', ', '.join('l_' + name for name in frame.identifiers.declared) )) def push_scope(self, frame, extra_vars=()): """This function returns all the shadowed variables in a dict in the form name: alias and will write the required assignments into the current scope. No indentation takes place. This also predefines locally declared variables from the loop body because under some circumstances it may be the case that `extra_vars` is passed to `Frame.find_shadowed`. """ aliases = {} for name in frame.find_shadowed(extra_vars): aliases[name] = ident = self.temporary_identifier() self.writeline('%s = l_%s' % (ident, name)) to_declare = set() for name in frame.identifiers.declared_locally: if name not in aliases: to_declare.add('l_' + name) if to_declare: self.writeline(' = '.join(to_declare) + ' = missing') return aliases def pop_scope(self, aliases, frame): """Restore all aliases and delete unused variables.""" for name, alias in iteritems(aliases): self.writeline('l_%s = %s' % (name, alias)) to_delete = set() for name in frame.identifiers.declared_locally: if name not in aliases: to_delete.add('l_' + name) if to_delete: # we cannot use the del statement here because enclosed # scopes can trigger a SyntaxError: # a = 42; b = lambda: a; del a self.writeline(' = '.join(to_delete) + ' = missing') def function_scoping(self, node, frame, children=None, find_special=True): """In Jinja a few statements require the help of anonymous functions. Those are currently macros and call blocks and in the future also recursive loops. As there is currently technical limitation that doesn't allow reading and writing a variable in a scope where the initial value is coming from an outer scope, this function tries to fall back with a common error message. Additionally the frame passed is modified so that the argumetns are collected and callers are looked up. This will return the modified frame. """ # we have to iterate twice over it, make sure that works if children is None: children = node.iter_child_nodes() children = list(children) func_frame = frame.inner() func_frame.inspect(children) # variables that are undeclared (accessed before declaration) and # declared locally *and* part of an outside scope raise a template # assertion error. Reason: we can't generate reasonable code from # it without aliasing all the variables. # this could be fixed in Python 3 where we have the nonlocal # keyword or if we switch to bytecode generation overridden_closure_vars = ( func_frame.identifiers.undeclared & func_frame.identifiers.declared & (func_frame.identifiers.declared_locally | func_frame.identifiers.declared_parameter) ) if overridden_closure_vars: self.fail('It\'s not possible to set and access variables ' 'derived from an outer scope! (affects: %s)' % ', '.join(sorted(overridden_closure_vars)), node.lineno) # remove variables from a closure from the frame's undeclared # identifiers. func_frame.identifiers.undeclared -= ( func_frame.identifiers.undeclared & func_frame.identifiers.declared ) # no special variables for this scope, abort early if not find_special: return func_frame func_frame.accesses_kwargs = False func_frame.accesses_varargs = False func_frame.accesses_caller = False func_frame.arguments = args = ['l_' + x.name for x in node.args] undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs')) if 'caller' in undeclared: func_frame.accesses_caller = True func_frame.identifiers.add_special('caller') args.append('l_caller') if 'kwargs' in undeclared: func_frame.accesses_kwargs = True func_frame.identifiers.add_special('kwargs') args.append('l_kwargs') if 'varargs' in undeclared: func_frame.accesses_varargs = True func_frame.identifiers.add_special('varargs') args.append('l_varargs') return func_frame def macro_body(self, node, frame, children=None): """Dump the function def of a macro or call block.""" frame = self.function_scoping(node, frame, children) # macros are delayed, they never require output checks frame.require_output_check = False args = frame.arguments # XXX: this is an ugly fix for the loop nesting bug # (tests.test_old_bugs.test_loop_call_bug). This works around # a identifier nesting problem we have in general. It's just more # likely to happen in loops which is why we work around it. The # real solution would be "nonlocal" all the identifiers that are # leaking into a new python frame and might be used both unassigned # and assigned. if 'loop' in frame.identifiers.declared: args = args + ['l_loop=l_loop'] self.writeline('def macro(%s):' % ', '.join(args), node) self.indent() self.buffer(frame) self.pull_locals(frame) self.blockvisit(node.body, frame) self.return_buffer_contents(frame) self.outdent() return frame def macro_def(self, node, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in node.args) name = getattr(node, 'name', None) if len(node.args) == 1: arg_tuple += ',' self.write('Macro(environment, macro, %r, (%s), (' % (name, arg_tuple)) for arg in node.defaults: self.visit(arg, frame) self.write(', ') self.write('), %r, %r, %r)' % ( bool(frame.accesses_kwargs), bool(frame.accesses_varargs), bool(frame.accesses_caller) )) def position(self, node): """Return a human readable position for the node.""" rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv # -- Statement Visitors def visit_Template(self, node, frame=None): assert frame is None, 'no root frame allowed' eval_ctx = EvalContext(self.environment, self.name) from jinja2.runtime import __all__ as exported self.writeline('from __future__ import division') self.writeline('from jinja2.runtime import ' + ', '.join(exported)) if not unoptimize_before_dead_code: self.writeline('dummy = lambda *x: None') # if we want a deferred initialization we cannot move the # environment into a local name envenv = not self.defer_init and ', environment=environment' or '' # do we have an extends tag at all? If not, we can save some # overhead by just not processing any inheritance code. have_extends = node.find(nodes.Extends) is not None # find all blocks for block in node.find_all(nodes.Block): if block.name in self.blocks: self.fail('block %r defined twice' % block.name, block.lineno) self.blocks[block.name] = block # find all imports and import them for import_ in node.find_all(nodes.ImportedName): if import_.importname not in self.import_aliases: imp = import_.importname self.import_aliases[imp] = alias = self.temporary_identifier() if '.' in imp: module, obj = imp.rsplit('.', 1) self.writeline('from %s import %s as %s' % (module, obj, alias)) else: self.writeline('import %s as %s' % (imp, alias)) # add the load name self.writeline('name = %r' % self.name) # generate the root render function. self.writeline('def root(context%s):' % envenv, extra=1) # process the root frame = Frame(eval_ctx) frame.inspect(node.body) frame.toplevel = frame.rootlevel = True frame.require_output_check = have_extends and not self.has_known_extends self.indent() if have_extends: self.writeline('parent_template = None') if 'self' in find_undeclared(node.body, ('self',)): frame.identifiers.add_special('self') self.writeline('l_self = TemplateReference(context)') self.pull_locals(frame) self.pull_dependencies(node.body) self.blockvisit(node.body, frame) self.outdent() # make sure that the parent root is called. if have_extends: if not self.has_known_extends: self.indent() self.writeline('if parent_template is not None:') self.indent() self.writeline('for event in parent_template.' 'root_render_func(context):') self.indent() self.writeline('yield event') self.outdent(2 + (not self.has_known_extends)) # at this point we now have the blocks collected and can visit them too. for name, block in iteritems(self.blocks): block_frame = Frame(eval_ctx) block_frame.inspect(block.body) block_frame.block = name self.writeline('def block_%s(context%s):' % (name, envenv), block, 1) self.indent() undeclared = find_undeclared(block.body, ('self', 'super')) if 'self' in undeclared: block_frame.identifiers.add_special('self') self.writeline('l_self = TemplateReference(context)') if 'super' in undeclared: block_frame.identifiers.add_special('super') self.writeline('l_super = context.super(%r, ' 'block_%s)' % (name, name)) self.pull_locals(block_frame) self.pull_dependencies(block.body) self.blockvisit(block.body, block_frame) self.outdent() self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x) for x in self.blocks), extra=1) # add a function that returns the debug info self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x in self.debug_info)) def visit_Block(self, node, frame): """Call a block and register it for the template.""" level = 1 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.has_known_extends: return if self.extends_so_far > 0: self.writeline('if parent_template is None:') self.indent() level += 1 context = node.scoped and 'context.derived(locals())' or 'context' self.writeline('for event in context.blocks[%r][0](%s):' % ( node.name, context), node) self.indent() self.simple_write('event', frame) self.outdent(level) def visit_Extends(self, node, frame): """Calls the extender.""" if not frame.toplevel: self.fail('cannot use extend from a non top-level scope', node.lineno) # if the number of extends statements in general is zero so # far, we don't have to add a check if something extended # the template before this one. if self.extends_so_far > 0: # if we have a known extends we just add a template runtime # error into the generated code. We could catch that at compile # time too, but i welcome it not to confuse users by throwing the # same error at different times just "because we can". if not self.has_known_extends: self.writeline('if parent_template is not None:') self.indent() self.writeline('raise TemplateRuntimeError(%r)' % 'extended multiple times') # if we have a known extends already we don't need that code here # as we know that the template execution will end here. if self.has_known_extends: raise CompilerExit() else: self.outdent() self.writeline('parent_template = environment.get_template(', node) self.visit(node.template, frame) self.write(', %r)' % self.name) self.writeline('for name, parent_block in parent_template.' 'blocks.%s():' % dict_item_iter) self.indent() self.writeline('context.blocks.setdefault(name, []).' 'append(parent_block)') self.outdent() # if this extends statement was in the root level we can take # advantage of that information and simplify the generated code # in the top level from this point onwards if frame.rootlevel: self.has_known_extends = True # and now we have one more self.extends_so_far += 1 def visit_Include(self, node, frame): """Handles includes.""" if node.with_context: self.unoptimize_scope(frame) if node.ignore_missing: self.writeline('try:') self.indent() func_name = 'get_or_select_template' if isinstance(node.template, nodes.Const): if isinstance(node.template.value, string_types): func_name = 'get_template' elif isinstance(node.template.value, (tuple, list)): func_name = 'select_template' elif isinstance(node.template, (nodes.Tuple, nodes.List)): func_name = 'select_template' self.writeline('template = environment.%s(' % func_name, node) self.visit(node.template, frame) self.write(', %r)' % self.name) if node.ignore_missing: self.outdent() self.writeline('except TemplateNotFound:') self.indent() self.writeline('pass') self.outdent() self.writeline('else:') self.indent() if node.with_context: self.writeline('for event in template.root_render_func(' 'template.new_context(context.parent, True, ' 'locals())):') else: self.writeline('for event in template.module._body_stream:') self.indent() self.simple_write('event', frame) self.outdent() if node.ignore_missing: self.outdent() def visit_Import(self, node, frame): """Visit regular imports.""" if node.with_context: self.unoptimize_scope(frame) self.writeline('l_%s = ' % node.target, node) if frame.toplevel: self.write('context.vars[%r] = ' % node.target) self.write('environment.get_template(') self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module(context.parent, True, locals())') else: self.write('module') if frame.toplevel and not node.target.startswith('_'): self.writeline('context.exported_vars.discard(%r)' % node.target) frame.assigned_names.add(node.target) def visit_FromImport(self, node, frame): """Visit named imports.""" self.newline(node) self.write('included_template = environment.get_template(') self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module(context.parent, True)') else: self.write('module') var_names = [] discarded_names = [] for name in node.names: if isinstance(name, tuple): name, alias = name else: alias = name self.writeline('l_%s = getattr(included_template, ' '%r, missing)' % (alias, name)) self.writeline('if l_%s is missing:' % alias) self.indent() self.writeline('l_%s = environment.undefined(%r %% ' 'included_template.__name__, ' 'name=%r)' % (alias, 'the template %%r (imported on %s) does ' 'not export the requested name %s' % ( self.position(node), repr(name) ), name)) self.outdent() if frame.toplevel: var_names.append(alias) if not alias.startswith('_'): discarded_names.append(alias) frame.assigned_names.add(alias) if var_names: if len(var_names) == 1: name = var_names[0] self.writeline('context.vars[%r] = l_%s' % (name, name)) else: self.writeline('context.vars.update({%s})' % ', '.join( '%r: l_%s' % (name, name) for name in var_names )) if discarded_names: if len(discarded_names) == 1: self.writeline('context.exported_vars.discard(%r)' % discarded_names[0]) else: self.writeline('context.exported_vars.difference_' 'update((%s))' % ', '.join(imap(repr, discarded_names))) def visit_For(self, node, frame): # when calculating the nodes for the inner frame we have to exclude # the iterator contents from it children = node.iter_child_nodes(exclude=('iter',)) if node.recursive: loop_frame = self.function_scoping(node, frame, children, find_special=False) else: loop_frame = frame.inner() loop_frame.inspect(children) # try to figure out if we have an extended loop. An extended loop # is necessary if the loop is in recursive mode if the special loop # variable is accessed in the body. extended_loop = node.recursive or 'loop' in \ find_undeclared(node.iter_child_nodes( only=('body',)), ('loop',)) # if we don't have an recursive loop we have to find the shadowed # variables at that point. Because loops can be nested but the loop # variable is a special one we have to enforce aliasing for it. if not node.recursive: aliases = self.push_scope(loop_frame, ('loop',)) # otherwise we set up a buffer and add a function def else: self.writeline('def loop(reciter, loop_render_func, depth=0):', node) self.indent() self.buffer(loop_frame) aliases = {} # make sure the loop variable is a special one and raise a template # assertion error if a loop tries to write to loop if extended_loop: self.writeline('l_loop = missing') loop_frame.identifiers.add_special('loop') for name in node.find_all(nodes.Name): if name.ctx == 'store' and name.name == 'loop': self.fail('Can\'t assign to special loop variable ' 'in for-loop target', name.lineno) self.pull_locals(loop_frame) if node.else_: iteration_indicator = self.temporary_identifier() self.writeline('%s = 1' % iteration_indicator) # Create a fake parent loop if the else or test section of a # loop is accessing the special loop variable and no parent loop # exists. if 'loop' not in aliases and 'loop' in find_undeclared( node.iter_child_nodes(only=('else_', 'test')), ('loop',)): self.writeline("l_loop = environment.undefined(%r, name='loop')" % ("'loop' is undefined. the filter section of a loop as well " "as the else block don't have access to the special 'loop'" " variable of the current loop. Because there is no parent " "loop it's undefined. Happened in loop on %s" % self.position(node))) self.writeline('for ', node) self.visit(node.target, loop_frame) self.write(extended_loop and ', l_loop in LoopContext(' or ' in ') # if we have an extened loop and a node test, we filter in the # "outer frame". if extended_loop and node.test is not None: self.write('(') self.visit(node.target, loop_frame) self.write(' for ') self.visit(node.target, loop_frame) self.write(' in ') if node.recursive: self.write('reciter') else: self.visit(node.iter, loop_frame) self.write(' if (') test_frame = loop_frame.copy() self.visit(node.test, test_frame) self.write('))') elif node.recursive: self.write('reciter') else: self.visit(node.iter, loop_frame) if node.recursive: self.write(', loop_render_func, depth):') else: self.write(extended_loop and '):' or ':') # tests in not extended loops become a continue if not extended_loop and node.test is not None: self.indent() self.writeline('if not ') self.visit(node.test, loop_frame) self.write(':') self.indent() self.writeline('continue') self.outdent(2) self.indent() self.blockvisit(node.body, loop_frame) if node.else_: self.writeline('%s = 0' % iteration_indicator) self.outdent() if node.else_: self.writeline('if %s:' % iteration_indicator) self.indent() self.blockvisit(node.else_, loop_frame) self.outdent() # reset the aliases if there are any. if not node.recursive: self.pop_scope(aliases, loop_frame) # if the node was recursive we have to return the buffer contents # and start the iteration code if node.recursive: self.return_buffer_contents(loop_frame) self.outdent() self.start_write(frame, node) self.write('loop(') self.visit(node.iter, frame) self.write(', loop)') self.end_write(frame) def visit_If(self, node, frame): if_frame = frame.soft() self.writeline('if ', node) self.visit(node.test, if_frame) self.write(':') self.indent() self.blockvisit(node.body, if_frame) self.outdent() if node.else_: self.writeline('else:') self.indent() self.blockvisit(node.else_, if_frame) self.outdent() def visit_Macro(self, node, frame): macro_frame = self.macro_body(node, frame) self.newline() if frame.toplevel: if not node.name.startswith('_'): self.write('context.exported_vars.add(%r)' % node.name) self.writeline('context.vars[%r] = ' % node.name) self.write('l_%s = ' % node.name) self.macro_def(node, macro_frame) frame.assigned_names.add(node.name) def visit_CallBlock(self, node, frame): children = node.iter_child_nodes(exclude=('call',)) call_frame = self.macro_body(node, frame, children) self.writeline('caller = ') self.macro_def(node, call_frame) self.start_write(frame, node) self.visit_Call(node.call, call_frame, forward_caller=True) self.end_write(frame) def visit_FilterBlock(self, node, frame): filter_frame = frame.inner() filter_frame.inspect(node.iter_child_nodes()) aliases = self.push_scope(filter_frame) self.pull_locals(filter_frame) self.buffer(filter_frame) self.blockvisit(node.body, filter_frame) self.start_write(frame, node) self.visit_Filter(node.filter, filter_frame) self.end_write(frame) self.pop_scope(aliases, filter_frame) def visit_ExprStmt(self, node, frame): self.newline(node) self.visit(node.node, frame) def visit_Output(self, node, frame): # if we have a known extends statement, we don't output anything # if we are in a require_output_check section if self.has_known_extends and frame.require_output_check: return allow_constant_finalize = True if self.environment.finalize: func = self.environment.finalize if getattr(func, 'contextfunction', False) or \ getattr(func, 'evalcontextfunction', False): allow_constant_finalize = False elif getattr(func, 'environmentfunction', False): finalize = lambda x: text_type( self.environment.finalize(self.environment, x)) else: finalize = lambda x: text_type(self.environment.finalize(x)) else: finalize = text_type # if we are inside a frame that requires output checking, we do so outdent_later = False if frame.require_output_check: self.writeline('if parent_template is None:') self.indent() outdent_later = True # try to evaluate as many chunks as possible into a static # string at compile time. body = [] for child in node.nodes: try: if not allow_constant_finalize: raise nodes.Impossible() const = child.as_const(frame.eval_ctx) except nodes.Impossible: body.append(child) continue # the frame can't be volatile here, becaus otherwise the # as_const() function would raise an Impossible exception # at that point. try: if frame.eval_ctx.autoescape: if hasattr(const, '__html__'): const = const.__html__() else: const = escape(const) const = finalize(const) except Exception: # if something goes wrong here we evaluate the node # at runtime for easier debugging body.append(child) continue if body and isinstance(body[-1], list): body[-1].append(const) else: body.append([const]) # if we have less than 3 nodes or a buffer we yield or extend/append if len(body) < 3 or frame.buffer is not None: if frame.buffer is not None: # for one item we append, for more we extend if len(body) == 1: self.writeline('%s.append(' % frame.buffer) else: self.writeline('%s.extend((' % frame.buffer) self.indent() for item in body: if isinstance(item, list): val = repr(concat(item)) if frame.buffer is None: self.writeline('yield ' + val) else: self.writeline(val + ', ') else: if frame.buffer is None: self.writeline('yield ', item) else: self.newline(item) close = 1 if frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' escape or to_string)(') elif frame.eval_ctx.autoescape: self.write('escape(') else: self.write('to_string(') if self.environment.finalize is not None: self.write('environment.finalize(') if getattr(self.environment.finalize, "contextfunction", False): self.write('context, ') close += 1 self.visit(item, frame) self.write(')' * close) if frame.buffer is not None: self.write(', ') if frame.buffer is not None: # close the open parentheses self.outdent() self.writeline(len(body) == 1 and ')' or '))') # otherwise we create a format string as this is faster in that case else: format = [] arguments = [] for item in body: if isinstance(item, list): format.append(concat(item).replace('%', '%%')) else: format.append('%s') arguments.append(item) self.writeline('yield ') self.write(repr(concat(format)) + ' % (') self.indent() for argument in arguments: self.newline(argument) close = 0 if frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' escape or to_string)(') close += 1 elif frame.eval_ctx.autoescape: self.write('escape(') close += 1 if self.environment.finalize is not None: self.write('environment.finalize(') if getattr(self.environment.finalize, 'contextfunction', False): self.write('context, ') elif getattr(self.environment.finalize, 'evalcontextfunction', False): self.write('context.eval_ctx, ') elif getattr(self.environment.finalize, 'environmentfunction', False): self.write('environment, ') close += 1 self.visit(argument, frame) self.write(')' * close + ', ') self.outdent() self.writeline(')') if outdent_later: self.outdent() def make_assignment_frame(self, frame): # toplevel assignments however go into the local namespace and # the current template's context. We create a copy of the frame # here and add a set so that the Name visitor can add the assigned # names here. if not frame.toplevel: return frame assignment_frame = frame.copy() assignment_frame.toplevel_assignments = set() return assignment_frame def export_assigned_vars(self, frame, assignment_frame): if not frame.toplevel: return public_names = [x for x in assignment_frame.toplevel_assignments if not x.startswith('_')] if len(assignment_frame.toplevel_assignments) == 1: name = next(iter(assignment_frame.toplevel_assignments)) self.writeline('context.vars[%r] = l_%s' % (name, name)) else: self.writeline('context.vars.update({') for idx, name in enumerate(assignment_frame.toplevel_assignments): if idx: self.write(', ') self.write('%r: l_%s' % (name, name)) self.write('})') if public_names: if len(public_names) == 1: self.writeline('context.exported_vars.add(%r)' % public_names[0]) else: self.writeline('context.exported_vars.update((%s))' % ', '.join(imap(repr, public_names))) def visit_Assign(self, node, frame): self.newline(node) assignment_frame = self.make_assignment_frame(frame) self.visit(node.target, assignment_frame) self.write(' = ') self.visit(node.node, frame) self.export_assigned_vars(frame, assignment_frame) def visit_AssignBlock(self, node, frame): block_frame = frame.inner() block_frame.inspect(node.body) aliases = self.push_scope(block_frame) self.pull_locals(block_frame) self.buffer(block_frame) self.blockvisit(node.body, block_frame) self.pop_scope(aliases, block_frame) assignment_frame = self.make_assignment_frame(frame) self.newline(node) self.visit(node.target, assignment_frame) self.write(' = concat(%s)' % block_frame.buffer) self.export_assigned_vars(frame, assignment_frame) # -- Expression Visitors def visit_Name(self, node, frame): if node.ctx == 'store' and frame.toplevel: frame.toplevel_assignments.add(node.name) self.write('l_' + node.name) frame.assigned_names.add(node.name) def visit_Const(self, node, frame): val = node.value if isinstance(val, float): self.write(str(val)) else: self.write(repr(val)) def visit_TemplateData(self, node, frame): try: self.write(repr(node.as_const(frame.eval_ctx))) except nodes.Impossible: self.write('(context.eval_ctx.autoescape and Markup or identity)(%r)' % node.data) def visit_Tuple(self, node, frame): self.write('(') idx = -1 for idx, item in enumerate(node.items): if idx: self.write(', ') self.visit(item, frame) self.write(idx == 0 and ',)' or ')') def visit_List(self, node, frame): self.write('[') for idx, item in enumerate(node.items): if idx: self.write(', ') self.visit(item, frame) self.write(']') def visit_Dict(self, node, frame): self.write('{') for idx, item in enumerate(node.items): if idx: self.write(', ') self.visit(item.key, frame) self.write(': ') self.visit(item.value, frame) self.write('}') def binop(operator, interceptable=True): def visitor(self, node, frame): if self.environment.sandboxed and \ operator in self.environment.intercepted_binops: self.write('environment.call_binop(context, %r, ' % operator) self.visit(node.left, frame) self.write(', ') self.visit(node.right, frame) else: self.write('(') self.visit(node.left, frame) self.write(' %s ' % operator) self.visit(node.right, frame) self.write(')') return visitor def uaop(operator, interceptable=True): def visitor(self, node, frame): if self.environment.sandboxed and \ operator in self.environment.intercepted_unops: self.write('environment.call_unop(context, %r, ' % operator) self.visit(node.node, frame) else: self.write('(' + operator) self.visit(node.node, frame) self.write(')') return visitor visit_Add = binop('+') visit_Sub = binop('-') visit_Mul = binop('*') visit_Div = binop('/') visit_FloorDiv = binop('//') visit_Pow = binop('**') visit_Mod = binop('%') visit_And = binop('and', interceptable=False) visit_Or = binop('or', interceptable=False) visit_Pos = uaop('+') visit_Neg = uaop('-') visit_Not = uaop('not ', interceptable=False) del binop, uaop def visit_Concat(self, node, frame): if frame.eval_ctx.volatile: func_name = '(context.eval_ctx.volatile and' \ ' markup_join or unicode_join)' elif frame.eval_ctx.autoescape: func_name = 'markup_join' else: func_name = 'unicode_join' self.write('%s((' % func_name) for arg in node.nodes: self.visit(arg, frame) self.write(', ') self.write('))') def visit_Compare(self, node, frame): self.visit(node.expr, frame) for op in node.ops: self.visit(op, frame) def visit_Operand(self, node, frame): self.write(' %s ' % operators[node.op]) self.visit(node.expr, frame) def visit_Getattr(self, node, frame): self.write('environment.getattr(') self.visit(node.node, frame) self.write(', %r)' % node.attr) def visit_Getitem(self, node, frame): # slices bypass the environment getitem method. if isinstance(node.arg, nodes.Slice): self.visit(node.node, frame) self.write('[') self.visit(node.arg, frame) self.write(']') else: self.write('environment.getitem(') self.visit(node.node, frame) self.write(', ') self.visit(node.arg, frame) self.write(')') def visit_Slice(self, node, frame): if node.start is not None: self.visit(node.start, frame) self.write(':') if node.stop is not None: self.visit(node.stop, frame) if node.step is not None: self.write(':') self.visit(node.step, frame) def visit_Filter(self, node, frame): self.write(self.filters[node.name] + '(') func = self.environment.filters.get(node.name) if func is None: self.fail('no filter named %r' % node.name, node.lineno) if getattr(func, 'contextfilter', False): self.write('context, ') elif getattr(func, 'evalcontextfilter', False): self.write('context.eval_ctx, ') elif getattr(func, 'environmentfilter', False): self.write('environment, ') # if the filter node is None we are inside a filter block # and want to write to the current buffer if node.node is not None: self.visit(node.node, frame) elif frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' Markup(concat(%s)) or concat(%s))' % (frame.buffer, frame.buffer)) elif frame.eval_ctx.autoescape: self.write('Markup(concat(%s))' % frame.buffer) else: self.write('concat(%s)' % frame.buffer) self.signature(node, frame) self.write(')') def visit_Test(self, node, frame): self.write(self.tests[node.name] + '(') if node.name not in self.environment.tests: self.fail('no test named %r' % node.name, node.lineno) self.visit(node.node, frame) self.signature(node, frame) self.write(')') def visit_CondExpr(self, node, frame): def write_expr2(): if node.expr2 is not None: return self.visit(node.expr2, frame) self.write('environment.undefined(%r)' % ('the inline if-' 'expression on %s evaluated to false and ' 'no else section was defined.' % self.position(node))) self.write('(') self.visit(node.expr1, frame) self.write(' if ') self.visit(node.test, frame) self.write(' else ') write_expr2() self.write(')') def visit_Call(self, node, frame, forward_caller=False): if self.environment.sandboxed: self.write('environment.call(context, ') else: self.write('context.call(') self.visit(node.node, frame) extra_kwargs = forward_caller and {'caller': 'caller'} or None self.signature(node, frame, extra_kwargs) self.write(')') def visit_Keyword(self, node, frame): self.write(node.key + '=') self.visit(node.value, frame) # -- Unused nodes for extensions def visit_MarkSafe(self, node, frame): self.write('Markup(') self.visit(node.expr, frame) self.write(')') def visit_MarkSafeIfAutoescape(self, node, frame): self.write('(context.eval_ctx.autoescape and Markup or identity)(') self.visit(node.expr, frame) self.write(')') def visit_EnvironmentAttribute(self, node, frame): self.write('environment.' + node.name) def visit_ExtensionAttribute(self, node, frame): self.write('environment.extensions[%r].%s' % (node.identifier, node.name)) def visit_ImportedName(self, node, frame): self.write(self.import_aliases[node.importname]) def visit_InternalName(self, node, frame): self.write(node.name) def visit_ContextReference(self, node, frame): self.write('context') def visit_Continue(self, node, frame): self.writeline('continue', node) def visit_Break(self, node, frame): self.writeline('break', node) def visit_Scope(self, node, frame): scope_frame = frame.inner() scope_frame.inspect(node.iter_child_nodes()) aliases = self.push_scope(scope_frame) self.pull_locals(scope_frame) self.blockvisit(node.body, scope_frame) self.pop_scope(aliases, scope_frame) def visit_EvalContextModifier(self, node, frame): for keyword in node.options: self.writeline('context.eval_ctx.%s = ' % keyword.key) self.visit(keyword.value, frame) try: val = keyword.value.as_const(frame.eval_ctx) except nodes.Impossible: frame.eval_ctx.volatile = True else: setattr(frame.eval_ctx, keyword.key, val) def visit_ScopedEvalContextModifier(self, node, frame): old_ctx_name = self.temporary_identifier() safed_ctx = frame.eval_ctx.save() self.writeline('%s = context.eval_ctx.save()' % old_ctx_name) self.visit_EvalContextModifier(node, frame) for child in node.body: self.visit(child, frame) frame.eval_ctx.revert(safed_ctx) self.writeline('context.eval_ctx.revert(%s)' % old_ctx_name)
bsd-3-clause
michael-dev2rights/ansible
lib/ansible/modules/remote_management/foreman/katello.py
15
16607
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Eric D Helms <ericdhelms@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: katello short_description: Manage Katello Resources description: - Allows the management of Katello resources inside your Foreman server version_added: "2.3" author: "Eric D Helms (@ehelms)" requirements: - "nailgun >= 0.28.0" - "python >= 2.6" - datetime options: server_url: description: - URL of Foreman server required: true username: description: - Username on Foreman server required: true password: description: - Password for user accessing Foreman server required: true entity: description: - The Foreman resource that the action will be performed on (e.g. organization, host) required: true params: description: - Parameters associated to the entity resource to set or edit in dictionary format (e.g. name, description) required: true ''' EXAMPLES = ''' --- # Simple Example: - name: "Create Product" local_action: module: katello username: "admin" password: "admin" server_url: "https://fakeserver.com" entity: "product" params: name: "Centos 7" # Abstraction Example: # katello.yml --- - name: "{{ name }}" local_action: module: katello username: "admin" password: "admin" server_url: "https://fakeserver.com" entity: "{{ entity }}" params: "{{ params }}" # tasks.yml --- - include: katello.yml vars: name: "Create Dev Environment" entity: "lifecycle_environment" params: name: "Dev" prior: "Library" organization: "Default Organization" - include: katello.yml vars: name: "Create Centos Product" entity: "product" params: name: "Centos 7" organization: "Default Organization" - include: katello.yml vars: name: "Create 7.2 Repository" entity: "repository" params: name: "Centos 7.2" product: "Centos 7" organization: "Default Organization" content_type: "yum" url: "http://mirror.centos.org/centos/7/os/x86_64/" - include: katello.yml vars: name: "Create Centos 7 View" entity: "content_view" params: name: "Centos 7 View" organization: "Default Organization" repositories: - name: "Centos 7.2" product: "Centos 7" - include: katello.yml vars: name: "Enable RHEL Product" entity: "repository_set" params: name: "Red Hat Enterprise Linux 7 Server (RPMs)" product: "Red Hat Enterprise Linux Server" organization: "Default Organization" basearch: "x86_64" releasever: "7" ''' RETURN = '''# ''' import datetime import os import traceback try: from nailgun import entities, entity_fields, entity_mixins from nailgun.config import ServerConfig HAS_NAILGUN_PACKAGE = True except: HAS_NAILGUN_PACKAGE = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native class NailGun(object): def __init__(self, server, entities, module): self._server = server self._entities = entities self._module = module entity_mixins.TASK_TIMEOUT = 1000 def find_organization(self, name, **params): org = self._entities.Organization(self._server, name=name, **params) response = org.search(set(), {'search': 'name={}'.format(name)}) if len(response) == 1: return response[0] else: self._module.fail_json(msg="No organization found for %s" % name) def find_lifecycle_environment(self, name, organization): org = self.find_organization(organization) lifecycle_env = self._entities.LifecycleEnvironment(self._server, name=name, organization=org) response = lifecycle_env.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Lifecycle Found found for %s" % name) def find_product(self, name, organization): org = self.find_organization(organization) product = self._entities.Product(self._server, name=name, organization=org) response = product.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Product found for %s" % name) def find_repository(self, name, product, organization): product = self.find_product(product, organization) repository = self._entities.Repository(self._server, name=name, product=product) repository._fields['organization'] = entity_fields.OneToOneField(entities.Organization) repository.organization = product.organization response = repository.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Repository found for %s" % name) def find_content_view(self, name, organization): org = self.find_organization(organization) content_view = self._entities.ContentView(self._server, name=name, organization=org) response = content_view.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Content View found for %s" % name) def organization(self, params): name = params['name'] del params['name'] org = self.find_organization(name, **params) if org: org = self._entities.Organization(self._server, name=name, id=org.id, **params) org.update() else: org = self._entities.Organization(self._server, name=name, **params) org.create() return True def manifest(self, params): org = self.find_organization(params['organization']) params['organization'] = org.id try: file = open(os.getcwd() + params['content'], 'r') content = file.read() finally: file.close() manifest = self._entities.Subscription(self._server) try: manifest.upload( data={'organization_id': org.id}, files={'content': content} ) return True except Exception as e: if "Import is the same as existing data" in e.message: return False else: self._module.fail_json(msg="Manifest import failed with %s" % to_native(e), exception=traceback.format_exc()) def product(self, params): org = self.find_organization(params['organization']) params['organization'] = org.id product = self._entities.Product(self._server, **params) response = product.search() if len(response) == 1: product.id = response[0].id product.update() else: product.create() return True def sync_product(self, params): org = self.find_organization(params['organization']) product = self.find_product(params['name'], org.name) return product.sync() def repository(self, params): product = self.find_product(params['product'], params['organization']) params['product'] = product.id del params['organization'] repository = self._entities.Repository(self._server, **params) repository._fields['organization'] = entity_fields.OneToOneField(entities.Organization) repository.organization = product.organization response = repository.search() if len(response) == 1: repository.id = response[0].id repository.update() else: repository.create() return True def sync_repository(self, params): org = self.find_organization(params['organization']) repository = self.find_repository(params['name'], params['product'], org.name) return repository.sync() def repository_set(self, params): product = self.find_product(params['product'], params['organization']) del params['product'] del params['organization'] if not product: return False else: reposet = self._entities.RepositorySet(self._server, product=product, name=params['name']) reposet = reposet.search()[0] formatted_name = [params['name'].replace('(', '').replace(')', '')] formatted_name.append(params['basearch']) if 'releasever' in params: formatted_name.append(params['releasever']) formatted_name = ' '.join(formatted_name) repository = self._entities.Repository(self._server, product=product, name=formatted_name) repository._fields['organization'] = entity_fields.OneToOneField(entities.Organization) repository.organization = product.organization repository = repository.search() if len(repository) == 0: if 'releasever' in params: reposet.enable(data={'basearch': params['basearch'], 'releasever': params['releasever']}) else: reposet.enable(data={'basearch': params['basearch']}) return True def sync_plan(self, params): org = self.find_organization(params['organization']) params['organization'] = org.id params['sync_date'] = datetime.datetime.strptime(params['sync_date'], "%H:%M") products = params['products'] del params['products'] sync_plan = self._entities.SyncPlan( self._server, name=params['name'], organization=org ) response = sync_plan.search() sync_plan.sync_date = params['sync_date'] sync_plan.interval = params['interval'] if len(response) == 1: sync_plan.id = response[0].id sync_plan.update() else: response = sync_plan.create() sync_plan.id = response[0].id if products: ids = [] for name in products: product = self.find_product(name, org.name) ids.append(product.id) sync_plan.add_products(data={'product_ids': ids}) return True def content_view(self, params): org = self.find_organization(params['organization']) content_view = self._entities.ContentView(self._server, name=params['name'], organization=org) response = content_view.search() if len(response) == 1: content_view.id = response[0].id content_view.update() else: content_view = content_view.create() if params['repositories']: repos = [] for repository in params['repositories']: repository = self.find_repository(repository['name'], repository['product'], org.name) repos.append(repository) content_view.repository = repos content_view.update(['repository']) def find_content_view_version(self, name, organization, environment): env = self.find_lifecycle_environment(environment, organization) content_view = self.find_content_view(name, organization) content_view_version = self._entities.ContentViewVersion(self._server, content_view=content_view) response = content_view_version.search(['content_view'], {'environment_id': env.id}) if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Content View version found for %s" % response) def publish(self, params): content_view = self.find_content_view(params['name'], params['organization']) return content_view.publish() def promote(self, params): to_environment = self.find_lifecycle_environment(params['to_environment'], params['organization']) version = self.find_content_view_version(params['name'], params['organization'], params['from_environment']) data = {'environment_id': to_environment.id} return version.promote(data=data) def lifecycle_environment(self, params): org = self.find_organization(params['organization']) prior_env = self.find_lifecycle_environment(params['prior'], params['organization']) lifecycle_env = self._entities.LifecycleEnvironment(self._server, name=params['name'], organization=org, prior=prior_env) response = lifecycle_env.search() if len(response) == 1: lifecycle_env.id = response[0].id lifecycle_env.update() else: lifecycle_env.create() return True def activation_key(self, params): org = self.find_organization(params['organization']) activation_key = self._entities.ActivationKey(self._server, name=params['name'], organization=org) response = activation_key.search() if len(response) == 1: activation_key.id = response[0].id activation_key.update() else: activation_key.create() if params['content_view']: content_view = self.find_content_view(params['content_view'], params['organization']) lifecycle_environment = self.find_lifecycle_environment(params['lifecycle_environment'], params['organization']) activation_key.content_view = content_view activation_key.environment = lifecycle_environment activation_key.update() return True def main(): module = AnsibleModule( argument_spec=dict( server_url=dict(required=True), username=dict(required=True, no_log=True), password=dict(required=True, no_log=True), entity=dict(required=True, no_log=False), action=dict(required=False, no_log=False), verify_ssl=dict(required=False, type='bool', default=False), params=dict(required=True, no_log=True, type='dict'), ), supports_check_mode=True ) if not HAS_NAILGUN_PACKAGE: module.fail_json(msg="Missing required nailgun module (check docs or install with: pip install nailgun") server_url = module.params['server_url'] username = module.params['username'] password = module.params['password'] entity = module.params['entity'] action = module.params['action'] params = module.params['params'] verify_ssl = module.params['verify_ssl'] server = ServerConfig( url=server_url, auth=(username, password), verify=verify_ssl ) ng = NailGun(server, entities, module) # Lets make an connection to the server with username and password try: org = entities.Organization(server) org.search() except Exception as e: module.fail_json(msg="Failed to connect to Foreman server: %s " % e) result = False if entity == 'product': if action == 'sync': result = ng.sync_product(params) else: result = ng.product(params) elif entity == 'repository': if action == 'sync': result = ng.sync_repository(params) else: result = ng.repository(params) elif entity == 'manifest': result = ng.manifest(params) elif entity == 'repository_set': result = ng.repository_set(params) elif entity == 'sync_plan': result = ng.sync_plan(params) elif entity == 'content_view': if action == 'publish': result = ng.publish(params) elif action == 'promote': result = ng.promote(params) else: result = ng.content_view(params) elif entity == 'lifecycle_environment': result = ng.lifecycle_environment(params) elif entity == 'activation_key': result = ng.activation_key(params) else: module.fail_json(changed=False, result="Unsupported entity supplied") module.exit_json(changed=result, result="%s updated" % entity) if __name__ == '__main__': main()
gpl-3.0
rizen1892/SmartHomeSolutions-Web
app/motion.py
2
2849
import picamera.array _THRESHOLD = 3 _SKIP_FRAMES = 4 _MIN_FRAMES_WITH_MOTION = 2 _MAG_ERROR = 2 # 2 in scale from 0 to 255 _ANG_ERROR = 0.174 # 0.174 rad (about 10 deg) class Motion(picamera.array.PiMotionAnalysis): def __init__(self, *args, **kwargs): import threading import Queue super(Motion, self).__init__(*args, **kwargs) self._event = threading.Event() self._processing_queue = Queue.Queue(1) self._processing_thread = threading.Thread(target=self._processing) self._processing_thread.setDaemon(True) self._processing_thread.start() self._skip = 0 def event(self): return self._event def reset(self): self._event.clear() def analyse(self, a): import Queue if not self._skip_frame() and not self._event.is_set(): try: self._processing_queue.put(a, block=False) except Queue.Full: pass def _skip_frame(self): if self._skip == _SKIP_FRAMES: self._skip = 0 return False else: self._skip += 1 return True def _processing(self): import numpy as np frames_with_motion = 0 while True: a = self._processing_queue.get() r = np.sqrt( np.square(a['x'].astype(np.float)) + np.square(a['y'].astype(np.float)) ).clip(0, 255) # Magnitude: 0 to 255 phi = (np.arctan2( a['y'].astype(np.float), a['x'].astype(np.float)) + np.pi) # Angle degree: -pi/2 to pi/2. if self._find_motion(r, phi): frames_with_motion += 1 else: frames_with_motion = 0 if frames_with_motion >= _MIN_FRAMES_WITH_MOTION: self._event.set() def _find_motion(self, r, phi): for x in range(len(r)): for y in range(len(r[0])): if r[x][y] > _THRESHOLD: if self._check_adjacent(x, y, r, phi): return True return False def _check_adjacent(self, x, y, r, phi): mag_min = r[x][y] - _MAG_ERROR mag_max = r[x][y] + _MAG_ERROR ang_min = phi[x][y] - _ANG_ERROR ang_max = phi[x][y] + _ANG_ERROR hits = 0 for i in [-1, 0, 1]: for j in [-1, 0, 1]: try: r[x + i][y + j] phi[x + i][y + j] except IndexError: continue if mag_min < r[x + i][y + j] and r[x + i][y + j] > mag_max: if ang_min < phi[x + i][y + j] and phi[x + i][y + j] > ang_max: hits += 1 return hits >= 5
gpl-2.0
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.4.3/Lib/plat-irix6/WAIT.py
15
5443
# Generated by h2py from /usr/include/sys/wait.h # Included from standards.h def _W_INT(i): return (i) WUNTRACED = 0004 WNOHANG = 0100 _WSTOPPED = 0177 def WIFEXITED(stat): return ((_W_INT(stat)&0377)==0) def WEXITSTATUS(stat): return ((_W_INT(stat)>>8)&0377) def WTERMSIG(stat): return (_W_INT(stat)&0177) def WSTOPSIG(stat): return ((_W_INT(stat)>>8)&0377) WEXITED = 0001 WTRAPPED = 0002 WSTOPPED = 0004 WCONTINUED = 0010 WNOWAIT = 0200 WOPTMASK = (WEXITED|WTRAPPED|WSTOPPED|WCONTINUED|WNOHANG|WNOWAIT) WSTOPFLG = 0177 WCONTFLG = 0177777 WCOREFLAG = 0200 WSIGMASK = 0177 def WWORD(stat): return (_W_INT(stat)&0177777) def WIFCONTINUED(stat): return (WWORD(stat)==WCONTFLG) def WCOREDUMP(stat): return (_W_INT(stat) & WCOREFLAG) # Included from sys/types.h # Included from sgidefs.h _MIPS_ISA_MIPS1 = 1 _MIPS_ISA_MIPS2 = 2 _MIPS_ISA_MIPS3 = 3 _MIPS_ISA_MIPS4 = 4 _MIPS_SIM_ABI32 = 1 _MIPS_SIM_NABI32 = 2 _MIPS_SIM_ABI64 = 3 P_MYID = (-1) P_MYHOSTID = (-1) # Included from sys/bsd_types.h # Included from sys/mkdev.h ONBITSMAJOR = 7 ONBITSMINOR = 8 OMAXMAJ = 0x7f OMAXMIN = 0xff NBITSMAJOR = 14 NBITSMINOR = 18 MAXMAJ = 0x1ff MAXMIN = 0x3ffff OLDDEV = 0 NEWDEV = 1 MKDEV_VER = NEWDEV def major(dev): return __major(MKDEV_VER, dev) def minor(dev): return __minor(MKDEV_VER, dev) # Included from sys/select.h FD_SETSIZE = 1024 __NBBY = 8 # Included from string.h NULL = 0L NBBY = 8 # Included from sys/procset.h P_INITPID = 1 P_INITUID = 0 P_INITPGID = 0 # Included from sys/signal.h SIGHUP = 1 SIGINT = 2 SIGQUIT = 3 SIGILL = 4 SIGTRAP = 5 SIGIOT = 6 SIGABRT = 6 SIGEMT = 7 SIGFPE = 8 SIGKILL = 9 SIGBUS = 10 SIGSEGV = 11 SIGSYS = 12 SIGPIPE = 13 SIGALRM = 14 SIGTERM = 15 SIGUSR1 = 16 SIGUSR2 = 17 SIGCLD = 18 SIGCHLD = 18 SIGPWR = 19 SIGWINCH = 20 SIGURG = 21 SIGPOLL = 22 SIGIO = 22 SIGSTOP = 23 SIGTSTP = 24 SIGCONT = 25 SIGTTIN = 26 SIGTTOU = 27 SIGVTALRM = 28 SIGPROF = 29 SIGXCPU = 30 SIGXFSZ = 31 SIG32 = 32 SIGCKPT = 33 SIGRTMIN = 49 SIGRTMAX = 64 SIGPTINTR = 47 SIGPTRESCHED = 48 __sigargs = int SIGEV_NONE = 128 SIGEV_SIGNAL = 129 SIGEV_CALLBACK = 130 # Included from sys/siginfo.h ILL_ILLOPC = 1 ILL_ILLOPN = 2 ILL_ILLADR = 3 ILL_ILLTRP = 4 ILL_PRVOPC = 5 ILL_PRVREG = 6 ILL_COPROC = 7 ILL_BADSTK = 8 NSIGILL = 8 FPE_INTDIV = 1 FPE_INTOVF = 2 FPE_FLTDIV = 3 FPE_FLTOVF = 4 FPE_FLTUND = 5 FPE_FLTRES = 6 FPE_FLTINV = 7 FPE_FLTSUB = 8 NSIGFPE = 8 SEGV_MAPERR = 1 SEGV_ACCERR = 2 NSIGSEGV = 2 BUS_ADRALN = 1 BUS_ADRERR = 2 BUS_OBJERR = 3 NSIGBUS = 3 TRAP_BRKPT = 1 TRAP_TRACE = 2 NSIGTRAP = 2 CLD_EXITED = 1 CLD_KILLED = 2 CLD_DUMPED = 3 CLD_TRAPPED = 4 CLD_STOPPED = 5 CLD_CONTINUED = 6 NSIGCLD = 6 POLL_IN = 1 POLL_OUT = 2 POLL_MSG = 3 POLL_ERR = 4 POLL_PRI = 5 POLL_HUP = 6 NSIGPOLL = 6 SI_MAXSZ = 128 SI_USER = 0 SI_KILL = SI_USER SI_QUEUE = -1 SI_ASYNCIO = -2 SI_TIMER = -3 SI_MESGQ = -4 SIG_NOP = 0 SIG_BLOCK = 1 SIG_UNBLOCK = 2 SIG_SETMASK = 3 SIG_SETMASK32 = 256 SA_ONSTACK = 0x00000001 SA_RESETHAND = 0x00000002 SA_RESTART = 0x00000004 SA_SIGINFO = 0x00000008 SA_NODEFER = 0x00000010 SA_NOCLDWAIT = 0x00010000 SA_NOCLDSTOP = 0x00020000 _SA_BSDCALL = 0x10000000 MINSIGSTKSZ = 512 SIGSTKSZ = 8192 SS_ONSTACK = 0x00000001 SS_DISABLE = 0x00000002 # Included from sys/ucontext.h NGREG = 36 NGREG = 37 GETCONTEXT = 0 SETCONTEXT = 1 UC_SIGMASK = 001 UC_STACK = 002 UC_CPU = 004 UC_MAU = 010 UC_MCONTEXT = (UC_CPU|UC_MAU) UC_ALL = (UC_SIGMASK|UC_STACK|UC_MCONTEXT) CTX_R0 = 0 CTX_AT = 1 CTX_V0 = 2 CTX_V1 = 3 CTX_A0 = 4 CTX_A1 = 5 CTX_A2 = 6 CTX_A3 = 7 CTX_T0 = 8 CTX_T1 = 9 CTX_T2 = 10 CTX_T3 = 11 CTX_T4 = 12 CTX_T5 = 13 CTX_T6 = 14 CTX_T7 = 15 CTX_A4 = 8 CTX_A5 = 9 CTX_A6 = 10 CTX_A7 = 11 CTX_T0 = 12 CTX_T1 = 13 CTX_T2 = 14 CTX_T3 = 15 CTX_S0 = 16 CTX_S1 = 17 CTX_S2 = 18 CTX_S3 = 19 CTX_S4 = 20 CTX_S5 = 21 CTX_S6 = 22 CTX_S7 = 23 CTX_T8 = 24 CTX_T9 = 25 CTX_K0 = 26 CTX_K1 = 27 CTX_GP = 28 CTX_SP = 29 CTX_S8 = 30 CTX_RA = 31 CTX_MDLO = 32 CTX_MDHI = 33 CTX_CAUSE = 34 CTX_EPC = 35 CTX_SR = 36 CXT_R0 = CTX_R0 CXT_AT = CTX_AT CXT_V0 = CTX_V0 CXT_V1 = CTX_V1 CXT_A0 = CTX_A0 CXT_A1 = CTX_A1 CXT_A2 = CTX_A2 CXT_A3 = CTX_A3 CXT_T0 = CTX_T0 CXT_T1 = CTX_T1 CXT_T2 = CTX_T2 CXT_T3 = CTX_T3 CXT_T4 = CTX_T4 CXT_T5 = CTX_T5 CXT_T6 = CTX_T6 CXT_T7 = CTX_T7 CXT_S0 = CTX_S0 CXT_S1 = CTX_S1 CXT_S2 = CTX_S2 CXT_S3 = CTX_S3 CXT_S4 = CTX_S4 CXT_S5 = CTX_S5 CXT_S6 = CTX_S6 CXT_S7 = CTX_S7 CXT_T8 = CTX_T8 CXT_T9 = CTX_T9 CXT_K0 = CTX_K0 CXT_K1 = CTX_K1 CXT_GP = CTX_GP CXT_SP = CTX_SP CXT_S8 = CTX_S8 CXT_RA = CTX_RA CXT_MDLO = CTX_MDLO CXT_MDHI = CTX_MDHI CXT_CAUSE = CTX_CAUSE CXT_EPC = CTX_EPC CXT_SR = CTX_SR SV_ONSTACK = 0x0001 SV_INTERRUPT = 0x0002 NUMBSDSIGS = (32) def sigmask(sig): return (1L << ((sig)-1)) def sigmask(sig): return (1L << ((sig)-1)) SIG_ERR = (-1) SIG_IGN = (1) SIG_HOLD = (2) SIG_DFL = (0) NSIG = 65 MAXSIG = (NSIG-1) NUMSIGS = (NSIG-1) BRK_USERBP = 0 BRK_KERNELBP = 1 BRK_ABORT = 2 BRK_BD_TAKEN = 3 BRK_BD_NOTTAKEN = 4 BRK_SSTEPBP = 5 BRK_OVERFLOW = 6 BRK_DIVZERO = 7 BRK_RANGE = 8 BRK_PSEUDO_OP_BIT = 0x80 BRK_PSEUDO_OP_MAX = 0x3 BRK_CACHE_SYNC = 0x80 BRK_SWASH_FLUSH = 0x81 BRK_SWASH_SWTCH = 0x82 BRK_MULOVF = 1023 # Included from sys/resource.h PRIO_MIN = -20 PRIO_MAX = 20 PRIO_PROCESS = 0 PRIO_PGRP = 1 PRIO_USER = 2 RUSAGE_SELF = 0 RUSAGE_CHILDREN = -1 RLIMIT_CPU = 0 RLIMIT_FSIZE = 1 RLIMIT_DATA = 2 RLIMIT_STACK = 3 RLIMIT_CORE = 4 RLIMIT_NOFILE = 5 RLIMIT_VMEM = 6 RLIMIT_RSS = 7 RLIMIT_AS = RLIMIT_VMEM RLIM_NLIMITS = 8 RLIM32_INFINITY = 0x7fffffff RLIM_INFINITY = 0x7fffffff
mit
Danielhiversen/home-assistant
tests/components/camera/test_push.py
3
3648
"""The tests for generic camera component.""" import io from datetime import timedelta from homeassistant import core as ha from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util from homeassistant.components.http.auth import setup_auth async def test_bad_posting(aioclient_mock, hass, aiohttp_client): """Test that posting to wrong api endpoint fails.""" await async_setup_component(hass, 'camera', { 'camera': { 'platform': 'push', 'name': 'config_test', 'token': '12345678' }}) client = await aiohttp_client(hass.http.app) # missing file resp = await client.post('/api/camera_push/camera.config_test') assert resp.status == 400 # wrong entity files = {'image': io.BytesIO(b'fake')} resp = await client.post('/api/camera_push/camera.wrong', data=files) assert resp.status == 404 async def test_cases_with_no_auth(aioclient_mock, hass, aiohttp_client): """Test cases where aiohttp_client is not auth.""" await async_setup_component(hass, 'camera', { 'camera': { 'platform': 'push', 'name': 'config_test', 'token': '12345678' }}) setup_auth(hass.http.app, [], True, api_password=None) client = await aiohttp_client(hass.http.app) # wrong token files = {'image': io.BytesIO(b'fake')} resp = await client.post('/api/camera_push/camera.config_test?token=1234', data=files) assert resp.status == 401 # right token files = {'image': io.BytesIO(b'fake')} resp = await client.post( '/api/camera_push/camera.config_test?token=12345678', data=files) assert resp.status == 200 async def test_no_auth_no_token(aioclient_mock, hass, aiohttp_client): """Test cases where aiohttp_client is not auth.""" await async_setup_component(hass, 'camera', { 'camera': { 'platform': 'push', 'name': 'config_test', }}) setup_auth(hass.http.app, [], True, api_password=None) client = await aiohttp_client(hass.http.app) # no token files = {'image': io.BytesIO(b'fake')} resp = await client.post('/api/camera_push/camera.config_test', data=files) assert resp.status == 401 # fake token files = {'image': io.BytesIO(b'fake')} resp = await client.post( '/api/camera_push/camera.config_test?token=12345678', data=files) assert resp.status == 401 async def test_posting_url(hass, aiohttp_client): """Test that posting to api endpoint works.""" await async_setup_component(hass, 'camera', { 'camera': { 'platform': 'push', 'name': 'config_test', 'token': '12345678' }}) client = await aiohttp_client(hass.http.app) files = {'image': io.BytesIO(b'fake')} # initial state camera_state = hass.states.get('camera.config_test') assert camera_state.state == 'idle' # post image resp = await client.post( '/api/camera_push/camera.config_test?token=12345678', data=files) assert resp.status == 200 # state recording camera_state = hass.states.get('camera.config_test') assert camera_state.state == 'recording' # await timeout shifted_time = dt_util.utcnow() + timedelta(seconds=15) hass.bus.async_fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: shifted_time}) await hass.async_block_till_done() # back to initial state camera_state = hass.states.get('camera.config_test') assert camera_state.state == 'idle'
mit
orgito/ansible
lib/ansible/modules/cloud/google/gcp_container_cluster.py
2
37620
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_container_cluster description: - A Google Container Engine cluster. short_description: Creates a GCP Cluster version_added: 2.6 author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: state: description: - Whether the given object should exist in GCP choices: - present - absent default: present name: description: - The name of this cluster. The name must be unique within this project and zone, and can be up to 40 characters. Must be Lowercase letters, numbers, and hyphens only. Must start with a letter. Must end with a number or a letter. required: false description: description: - An optional description of this cluster. required: false initial_node_count: description: - The number of nodes to create in this cluster. You must ensure that your Compute Engine resource quota is sufficient for this number of instances. You must also have available firewall and routes quota. For requests, this field should only be used in lieu of a "nodePool" object, since this configuration (along with the "nodeConfig") will be used to create a "NodePool" object with an auto-generated name. Do not use this and a nodePool at the same time. required: true node_config: description: - Parameters used in creating the cluster's nodes. - For requests, this field should only be used in lieu of a "nodePool" object, since this configuration (along with the "initialNodeCount") will be used to create a "NodePool" object with an auto-generated name. Do not use this and a nodePool at the same time. For responses, this field will be populated with the node configuration of the first node pool. If unspecified, the defaults are used. required: false suboptions: machine_type: description: - The name of a Google Compute Engine machine type (e.g. - n1-standard-1). If unspecified, the default machine type is n1-standard-1. required: false disk_size_gb: description: - Size of the disk attached to each node, specified in GB. The smallest allowed disk size is 10GB. If unspecified, the default disk size is 100GB. required: false oauth_scopes: description: - The set of Google API scopes to be made available on all of the node VMs under the "default" service account. - 'The following scopes are recommended, but not required, and by default are not included: U(https://www.googleapis.com/auth/compute) is required for mounting persistent storage on your nodes.' - U(https://www.googleapis.com/auth/devstorage.read_only) is required for communicating with gcr.io (the Google Container Registry). - If unspecified, no scopes are added, unless Cloud Logging or Cloud Monitoring are enabled, in which case their required scopes will be added. required: false service_account: description: - The Google Cloud Platform Service Account to be used by the node VMs. If no Service Account is specified, the "default" service account is used. required: false metadata: description: - The metadata key/value pairs assigned to instances in the cluster. - 'Keys must conform to the regexp [a-zA-Z0-9-_]+ and be less than 128 bytes in length. These are reflected as part of a URL in the metadata server. Additionally, to avoid ambiguity, keys must not conflict with any other metadata keys for the project or be one of the four reserved keys: "instance-template", "kube-env", "startup-script", and "user-data" Values are free-form strings, and only have meaning as interpreted by the image running in the instance. The only restriction placed on them is that each value''s size must be less than or equal to 32 KB.' - The total size of all keys and values must be less than 512 KB. - 'An object containing a list of "key": value pairs.' - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.' required: false image_type: description: - The image type to use for this node. Note that for a given image type, the latest version of it will be used. required: false labels: description: - 'The map of Kubernetes labels (key/value pairs) to be applied to each node. These will added in addition to any default label(s) that Kubernetes may apply to the node. In case of conflict in label keys, the applied set may differ depending on the Kubernetes version -- it''s best to assume the behavior is undefined and conflicts should be avoided. For more information, including usage and the valid values, see: U(http://kubernetes.io/v1.1/docs/user-guide/labels.html) An object containing a list of "key": value pairs.' - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.' required: false local_ssd_count: description: - The number of local SSD disks to be attached to the node. - 'The limit for this value is dependant upon the maximum number of disks available on a machine per zone. See: U(https://cloud.google.com/compute/docs/disks/local-ssd#local_ssd_limits) for more information.' required: false tags: description: - The list of instance tags applied to all nodes. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during cluster or node pool creation. Each tag within the list must comply with RFC1035. required: false preemptible: description: - 'Whether the nodes are created as preemptible VM instances. See: U(https://cloud.google.com/compute/docs/instances/preemptible) for more inforamtion about preemptible VM instances.' required: false type: bool master_auth: description: - The authentication information for accessing the master endpoint. required: false suboptions: username: description: - The username to use for HTTP basic authentication to the master endpoint. required: false password: description: - The password to use for HTTP basic authentication to the master endpoint. Because the master endpoint is open to the Internet, you should create a strong password. required: false cluster_ca_certificate: description: - Base64-encoded public certificate that is the root of trust for the cluster. required: false client_certificate: description: - Base64-encoded public certificate used by clients to authenticate to the cluster endpoint. required: false client_key: description: - Base64-encoded private key used by clients to authenticate to the cluster endpoint. required: false logging_service: description: - 'The logging service the cluster should use to write logs. Currently available options: logging.googleapis.com - the Google Cloud Logging service.' - none - no logs will be exported from the cluster. - if left as an empty string,logging.googleapis.com will be used. required: false choices: - logging.googleapis.com - none monitoring_service: description: - The monitoring service the cluster should use to write metrics. - 'Currently available options: monitoring.googleapis.com - the Google Cloud Monitoring service.' - none - no metrics will be exported from the cluster. - if left as an empty string, monitoring.googleapis.com will be used. required: false choices: - monitoring.googleapis.com - none network: description: - The name of the Google Compute Engine network to which the cluster is connected. If left unspecified, the default network will be used. - To ensure it exists and it is operations, configure the network using 'gcompute_network' resource. required: false cluster_ipv4_cidr: description: - The IP address range of the container pods in this cluster, in CIDR notation (e.g. 10.96.0.0/14). Leave blank to have one automatically chosen or specify a /14 block in 10.0.0.0/8. required: false addons_config: description: - Configurations for the various addons available to run in the cluster. required: false suboptions: http_load_balancing: description: - Configuration for the HTTP (L7) load balancing controller addon, which makes it easy to set up HTTP load balancers for services in a cluster. required: false suboptions: disabled: description: - Whether the HTTP Load Balancing controller is enabled in the cluster. When enabled, it runs a small pod in the cluster that manages the load balancers. required: false type: bool horizontal_pod_autoscaling: description: - Configuration for the horizontal pod autoscaling feature, which increases or decreases the number of replica pods a replication controller has based on the resource usage of the existing pods. required: false suboptions: disabled: description: - Whether the Horizontal Pod Autoscaling feature is enabled in the cluster. When enabled, it ensures that a Heapster pod is running in the cluster, which is also used by the Cloud Monitoring service. required: false type: bool subnetwork: description: - The name of the Google Compute Engine subnetwork to which the cluster is connected. required: false location: description: - The list of Google Compute Engine locations in which the cluster's nodes should be located. required: false zone: description: - The zone where the cluster is deployed. required: true extends_documentation_fragment: gcp ''' EXAMPLES = ''' - name: create a cluster gcp_container_cluster: name: my-cluster initial_node_count: 2 master_auth: username: cluster_admin password: my-secret-password node_config: machine_type: n1-standard-4 disk_size_gb: 500 zone: us-central1-a project: "test_project" auth_kind: "serviceaccount" service_account_file: "/tmp/auth.pem" state: present ''' RETURN = ''' name: description: - The name of this cluster. The name must be unique within this project and zone, and can be up to 40 characters. Must be Lowercase letters, numbers, and hyphens only. Must start with a letter. Must end with a number or a letter. returned: success type: str description: description: - An optional description of this cluster. returned: success type: str initialNodeCount: description: - The number of nodes to create in this cluster. You must ensure that your Compute Engine resource quota is sufficient for this number of instances. You must also have available firewall and routes quota. For requests, this field should only be used in lieu of a "nodePool" object, since this configuration (along with the "nodeConfig") will be used to create a "NodePool" object with an auto-generated name. Do not use this and a nodePool at the same time. returned: success type: int nodeConfig: description: - Parameters used in creating the cluster's nodes. - For requests, this field should only be used in lieu of a "nodePool" object, since this configuration (along with the "initialNodeCount") will be used to create a "NodePool" object with an auto-generated name. Do not use this and a nodePool at the same time. For responses, this field will be populated with the node configuration of the first node pool. If unspecified, the defaults are used. returned: success type: complex contains: machineType: description: - The name of a Google Compute Engine machine type (e.g. - n1-standard-1). If unspecified, the default machine type is n1-standard-1. returned: success type: str diskSizeGb: description: - Size of the disk attached to each node, specified in GB. The smallest allowed disk size is 10GB. If unspecified, the default disk size is 100GB. returned: success type: int oauthScopes: description: - The set of Google API scopes to be made available on all of the node VMs under the "default" service account. - 'The following scopes are recommended, but not required, and by default are not included: U(https://www.googleapis.com/auth/compute) is required for mounting persistent storage on your nodes.' - U(https://www.googleapis.com/auth/devstorage.read_only) is required for communicating with gcr.io (the Google Container Registry). - If unspecified, no scopes are added, unless Cloud Logging or Cloud Monitoring are enabled, in which case their required scopes will be added. returned: success type: list serviceAccount: description: - The Google Cloud Platform Service Account to be used by the node VMs. If no Service Account is specified, the "default" service account is used. returned: success type: str metadata: description: - The metadata key/value pairs assigned to instances in the cluster. - 'Keys must conform to the regexp [a-zA-Z0-9-_]+ and be less than 128 bytes in length. These are reflected as part of a URL in the metadata server. Additionally, to avoid ambiguity, keys must not conflict with any other metadata keys for the project or be one of the four reserved keys: "instance-template", "kube-env", "startup-script", and "user-data" Values are free-form strings, and only have meaning as interpreted by the image running in the instance. The only restriction placed on them is that each value''s size must be less than or equal to 32 KB.' - The total size of all keys and values must be less than 512 KB. - 'An object containing a list of "key": value pairs.' - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.' returned: success type: dict imageType: description: - The image type to use for this node. Note that for a given image type, the latest version of it will be used. returned: success type: str labels: description: - 'The map of Kubernetes labels (key/value pairs) to be applied to each node. These will added in addition to any default label(s) that Kubernetes may apply to the node. In case of conflict in label keys, the applied set may differ depending on the Kubernetes version -- it''s best to assume the behavior is undefined and conflicts should be avoided. For more information, including usage and the valid values, see: U(http://kubernetes.io/v1.1/docs/user-guide/labels.html) An object containing a list of "key": value pairs.' - 'Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.' returned: success type: dict localSsdCount: description: - The number of local SSD disks to be attached to the node. - 'The limit for this value is dependant upon the maximum number of disks available on a machine per zone. See: U(https://cloud.google.com/compute/docs/disks/local-ssd#local_ssd_limits) for more information.' returned: success type: int tags: description: - The list of instance tags applied to all nodes. Tags are used to identify valid sources or targets for network firewalls and are specified by the client during cluster or node pool creation. Each tag within the list must comply with RFC1035. returned: success type: list preemptible: description: - 'Whether the nodes are created as preemptible VM instances. See: U(https://cloud.google.com/compute/docs/instances/preemptible) for more inforamtion about preemptible VM instances.' returned: success type: bool masterAuth: description: - The authentication information for accessing the master endpoint. returned: success type: complex contains: username: description: - The username to use for HTTP basic authentication to the master endpoint. returned: success type: str password: description: - The password to use for HTTP basic authentication to the master endpoint. Because the master endpoint is open to the Internet, you should create a strong password. returned: success type: str clusterCaCertificate: description: - Base64-encoded public certificate that is the root of trust for the cluster. returned: success type: str clientCertificate: description: - Base64-encoded public certificate used by clients to authenticate to the cluster endpoint. returned: success type: str clientKey: description: - Base64-encoded private key used by clients to authenticate to the cluster endpoint. returned: success type: str loggingService: description: - 'The logging service the cluster should use to write logs. Currently available options: logging.googleapis.com - the Google Cloud Logging service.' - none - no logs will be exported from the cluster. - if left as an empty string,logging.googleapis.com will be used. returned: success type: str monitoringService: description: - The monitoring service the cluster should use to write metrics. - 'Currently available options: monitoring.googleapis.com - the Google Cloud Monitoring service.' - none - no metrics will be exported from the cluster. - if left as an empty string, monitoring.googleapis.com will be used. returned: success type: str network: description: - The name of the Google Compute Engine network to which the cluster is connected. If left unspecified, the default network will be used. - To ensure it exists and it is operations, configure the network using 'gcompute_network' resource. returned: success type: str clusterIpv4Cidr: description: - The IP address range of the container pods in this cluster, in CIDR notation (e.g. 10.96.0.0/14). Leave blank to have one automatically chosen or specify a /14 block in 10.0.0.0/8. returned: success type: str addonsConfig: description: - Configurations for the various addons available to run in the cluster. returned: success type: complex contains: httpLoadBalancing: description: - Configuration for the HTTP (L7) load balancing controller addon, which makes it easy to set up HTTP load balancers for services in a cluster. returned: success type: complex contains: disabled: description: - Whether the HTTP Load Balancing controller is enabled in the cluster. When enabled, it runs a small pod in the cluster that manages the load balancers. returned: success type: bool horizontalPodAutoscaling: description: - Configuration for the horizontal pod autoscaling feature, which increases or decreases the number of replica pods a replication controller has based on the resource usage of the existing pods. returned: success type: complex contains: disabled: description: - Whether the Horizontal Pod Autoscaling feature is enabled in the cluster. When enabled, it ensures that a Heapster pod is running in the cluster, which is also used by the Cloud Monitoring service. returned: success type: bool subnetwork: description: - The name of the Google Compute Engine subnetwork to which the cluster is connected. returned: success type: str location: description: - The list of Google Compute Engine locations in which the cluster's nodes should be located. returned: success type: list endpoint: description: - The IP address of this cluster's master endpoint. - The endpoint can be accessed from the internet at https://username:password@endpoint/ See the masterAuth property of this resource for username and password information. returned: success type: str initialClusterVersion: description: - The software version of the master endpoint and kubelets used in the cluster when it was first created. The version can be upgraded over time. returned: success type: str currentMasterVersion: description: - The current software version of the master endpoint. returned: success type: str currentNodeVersion: description: - The current version of the node software components. If they are currently at multiple versions because they're in the process of being upgraded, this reflects the minimum version of all nodes. returned: success type: str createTime: description: - The time the cluster was created, in RFC3339 text format. returned: success type: str nodeIpv4CidrSize: description: - The size of the address space on each node for hosting containers. - This is provisioned from within the container_ipv4_cidr range. returned: success type: int servicesIpv4Cidr: description: - The IP address range of the Kubernetes services in this cluster, in CIDR notation (e.g. 1.2.3.4/29). Service addresses are typically put in the last /16 from the container CIDR. returned: success type: str currentNodeCount: description: - The number of nodes currently in the cluster. returned: success type: int expireTime: description: - The time the cluster will be automatically deleted in RFC3339 text format. returned: success type: str zone: description: - The zone where the cluster is deployed. returned: success type: str ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, remove_nones_from_dict, replace_resource_dict import json import time ################################################################################ # Main ################################################################################ def main(): """Main function""" module = GcpModule( argument_spec=dict( state=dict(default='present', choices=['present', 'absent'], type='str'), name=dict(type='str'), description=dict(type='str'), initial_node_count=dict(required=True, type='int'), node_config=dict(type='dict', options=dict( machine_type=dict(type='str'), disk_size_gb=dict(type='int'), oauth_scopes=dict(type='list', elements='str'), service_account=dict(type='str'), metadata=dict(type='dict'), image_type=dict(type='str'), labels=dict(type='dict'), local_ssd_count=dict(type='int'), tags=dict(type='list', elements='str'), preemptible=dict(type='bool') )), master_auth=dict(type='dict', options=dict( username=dict(type='str'), password=dict(type='str'), cluster_ca_certificate=dict(type='str'), client_certificate=dict(type='str'), client_key=dict(type='str') )), logging_service=dict(type='str', choices=['logging.googleapis.com', 'none']), monitoring_service=dict(type='str', choices=['monitoring.googleapis.com', 'none']), network=dict(type='str'), cluster_ipv4_cidr=dict(type='str'), addons_config=dict(type='dict', options=dict( http_load_balancing=dict(type='dict', options=dict( disabled=dict(type='bool') )), horizontal_pod_autoscaling=dict(type='dict', options=dict( disabled=dict(type='bool') )) )), subnetwork=dict(type='str'), location=dict(type='list', elements='str'), zone=dict(required=True, type='str') ) ) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/cloud-platform'] state = module.params['state'] fetch = fetch_resource(module, self_link(module)) changed = False if fetch: if state == 'present': if is_different(module, fetch): update(module, self_link(module)) fetch = fetch_resource(module, self_link(module)) changed = True else: delete(module, self_link(module)) fetch = {} changed = True else: if state == 'present': fetch = create(module, collection(module)) changed = True else: fetch = {} fetch.update({'changed': changed}) module.exit_json(**fetch) def create(module, link): auth = GcpSession(module, 'container') return wait_for_operation(module, auth.post(link, resource_to_request(module))) def update(module, link): auth = GcpSession(module, 'container') return wait_for_operation(module, auth.put(link, resource_to_request(module))) def delete(module, link): auth = GcpSession(module, 'container') return wait_for_operation(module, auth.delete(link)) def resource_to_request(module): request = { u'name': module.params.get('name'), u'description': module.params.get('description'), u'initialNodeCount': module.params.get('initial_node_count'), u'nodeConfig': ClusterNodeconfig(module.params.get('node_config', {}), module).to_request(), u'masterAuth': ClusterMasterauth(module.params.get('master_auth', {}), module).to_request(), u'loggingService': module.params.get('logging_service'), u'monitoringService': module.params.get('monitoring_service'), u'network': module.params.get('network'), u'clusterIpv4Cidr': module.params.get('cluster_ipv4_cidr'), u'addonsConfig': ClusterAddonsconfig(module.params.get('addons_config', {}), module).to_request(), u'subnetwork': module.params.get('subnetwork'), u'location': module.params.get('location') } request = encode_request(request, module) return_vals = {} for k, v in request.items(): if v or v is False: return_vals[k] = v return return_vals def fetch_resource(module, link, allow_not_found=True): auth = GcpSession(module, 'container') return return_if_object(module, auth.get(link), allow_not_found) def self_link(module): return "https://container.googleapis.com/v1/projects/{project}/zones/{zone}/clusters/{name}".format(**module.params) def collection(module): return "https://container.googleapis.com/v1/projects/{project}/zones/{zone}/clusters".format(**module.params) def return_if_object(module, response, allow_not_found=False): # If not found, return nothing. if allow_not_found and response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result def is_different(module, response): request = resource_to_request(module) response = response_to_hash(module, response) # Remove all output-only from response. response_vals = {} for k, v in response.items(): if k in request: response_vals[k] = v request_vals = {} for k, v in request.items(): if k in response: request_vals[k] = v return GcpRequest(request_vals) != GcpRequest(response_vals) # Remove unnecessary properties from the response. # This is for doing comparisons with Ansible's current parameters. def response_to_hash(module, response): return { u'name': response.get(u'name'), u'description': response.get(u'description'), u'initialNodeCount': module.params.get('initial_node_count'), u'nodeConfig': ClusterNodeconfig(module.params.get('node_config', {}), module).to_request(), u'masterAuth': ClusterMasterauth(response.get(u'masterAuth', {}), module).from_response(), u'loggingService': response.get(u'loggingService'), u'monitoringService': response.get(u'monitoringService'), u'network': response.get(u'network'), u'clusterIpv4Cidr': response.get(u'clusterIpv4Cidr'), u'addonsConfig': ClusterAddonsconfig(response.get(u'addonsConfig', {}), module).from_response(), u'subnetwork': response.get(u'subnetwork'), u'location': response.get(u'location'), u'endpoint': response.get(u'endpoint'), u'initialClusterVersion': response.get(u'initialClusterVersion'), u'currentMasterVersion': response.get(u'currentMasterVersion'), u'currentNodeVersion': response.get(u'currentNodeVersion'), u'createTime': response.get(u'createTime'), u'nodeIpv4CidrSize': response.get(u'nodeIpv4CidrSize'), u'servicesIpv4Cidr': response.get(u'servicesIpv4Cidr'), u'currentNodeCount': response.get(u'currentNodeCount'), u'expireTime': response.get(u'expireTime') } def async_op_url(module, extra_data=None): if extra_data is None: extra_data = {} url = "https://container.googleapis.com/v1/projects/{project}/zones/{zone}/operations/{op_id}" combined = extra_data.copy() combined.update(module.params) return url.format(**combined) def wait_for_operation(module, response): op_result = return_if_object(module, response) if op_result is None: return {} status = navigate_hash(op_result, ['status']) wait_done = wait_for_completion(status, op_result, module) return fetch_resource(module, navigate_hash(wait_done, ['targetLink'])) def wait_for_completion(status, op_result, module): op_id = navigate_hash(op_result, ['name']) op_uri = async_op_url(module, {'op_id': op_id}) while status != 'DONE': raise_if_errors(op_result, ['error', 'errors'], 'message') time.sleep(1.0) op_result = fetch_resource(module, op_uri) status = navigate_hash(op_result, ['status']) return op_result def raise_if_errors(response, err_path, module): errors = navigate_hash(response, err_path) if errors is not None: module.fail_json(msg=errors) # Google Container Engine API has its own layout for the create method, # defined like this: # # { # 'cluster': { # ... cluster data # } # } # # Format the request to match the expected input by the API def encode_request(resource_request, module): return { 'cluster': resource_request } class ClusterNodeconfig(object): def __init__(self, request, module): self.module = module if request: self.request = request else: self.request = {} def to_request(self): return remove_nones_from_dict({ u'machineType': self.request.get('machine_type'), u'diskSizeGb': self.request.get('disk_size_gb'), u'oauthScopes': self.request.get('oauth_scopes'), u'serviceAccount': self.request.get('service_account'), u'metadata': self.request.get('metadata'), u'imageType': self.request.get('image_type'), u'labels': self.request.get('labels'), u'localSsdCount': self.request.get('local_ssd_count'), u'tags': self.request.get('tags'), u'preemptible': self.request.get('preemptible') }) def from_response(self): return remove_nones_from_dict({ u'machineType': self.request.get(u'machineType'), u'diskSizeGb': self.request.get(u'diskSizeGb'), u'oauthScopes': self.request.get(u'oauthScopes'), u'serviceAccount': self.request.get(u'serviceAccount'), u'metadata': self.request.get(u'metadata'), u'imageType': self.request.get(u'imageType'), u'labels': self.request.get(u'labels'), u'localSsdCount': self.request.get(u'localSsdCount'), u'tags': self.request.get(u'tags'), u'preemptible': self.request.get(u'preemptible') }) class ClusterMasterauth(object): def __init__(self, request, module): self.module = module if request: self.request = request else: self.request = {} def to_request(self): return remove_nones_from_dict({ u'username': self.request.get('username'), u'password': self.request.get('password'), u'clusterCaCertificate': self.request.get('cluster_ca_certificate'), u'clientCertificate': self.request.get('client_certificate'), u'clientKey': self.request.get('client_key') }) def from_response(self): return remove_nones_from_dict({ u'username': self.request.get(u'username'), u'password': self.request.get(u'password'), u'clusterCaCertificate': self.request.get(u'clusterCaCertificate'), u'clientCertificate': self.request.get(u'clientCertificate'), u'clientKey': self.request.get(u'clientKey') }) class ClusterAddonsconfig(object): def __init__(self, request, module): self.module = module if request: self.request = request else: self.request = {} def to_request(self): return remove_nones_from_dict({ u'httpLoadBalancing': ClusterHttploadbalancing(self.request.get('http_load_balancing', {}), self.module).to_request(), u'horizontalPodAutoscaling': ClusterHorizontalpodautoscaling(self.request.get('horizontal_pod_autoscaling', {}), self.module).to_request() }) def from_response(self): return remove_nones_from_dict({ u'httpLoadBalancing': ClusterHttploadbalancing(self.request.get(u'httpLoadBalancing', {}), self.module).from_response(), u'horizontalPodAutoscaling': ClusterHorizontalpodautoscaling(self.request.get(u'horizontalPodAutoscaling', {}), self.module).from_response() }) class ClusterHttploadbalancing(object): def __init__(self, request, module): self.module = module if request: self.request = request else: self.request = {} def to_request(self): return remove_nones_from_dict({ u'disabled': self.request.get('disabled') }) def from_response(self): return remove_nones_from_dict({ u'disabled': self.request.get(u'disabled') }) class ClusterHorizontalpodautoscaling(object): def __init__(self, request, module): self.module = module if request: self.request = request else: self.request = {} def to_request(self): return remove_nones_from_dict({ u'disabled': self.request.get('disabled') }) def from_response(self): return remove_nones_from_dict({ u'disabled': self.request.get(u'disabled') }) if __name__ == '__main__': main()
gpl-3.0
asgard-lab/neutron
neutron/agent/l3/dvr_edge_ha_router.py
5
5092
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_log import log as logging from neutron.agent.l3.dvr_edge_router import DvrEdgeRouter from neutron.agent.l3 import dvr_snat_ns from neutron.agent.l3.ha_router import HaRouter from neutron.agent.l3.router_info import RouterInfo from neutron.common import constants as l3_constants LOG = logging.getLogger(__name__) class DvrEdgeHaRouter(DvrEdgeRouter, HaRouter): """Router class which represents a centralized SNAT DVR router with HA capabilities. """ def __init__(self, agent, host, *args, **kwargs): super(DvrEdgeHaRouter, self).__init__(agent, host, *args, **kwargs) self.enable_snat = None self.snat_ports = None @property def ha_namespace(self): if self.snat_namespace: return self.snat_namespace.name return None def internal_network_added(self, port): # Call RouterInfo's internal_network_added (Plugs the port, adds IP) RouterInfo.internal_network_added(self, port) for subnet in port['subnets']: self._set_subnet_arp_info(subnet['id']) self._snat_redirect_add_from_port(port) if not self.get_ex_gw_port() or not self._is_this_snat_host(): return sn_port = self.get_snat_port_for_internal_port(port) if not sn_port: return self._plug_ha_router_port( sn_port, self._get_snat_int_device_name, dvr_snat_ns.SNAT_INT_DEV_PREFIX) def external_gateway_added(self, ex_gw_port, interface_name): super(DvrEdgeHaRouter, self).external_gateway_added( ex_gw_port, interface_name) for port in self.get_snat_interfaces(): snat_interface_name = self._get_snat_int_device_name(port['id']) self._disable_ipv6_addressing_on_interface(snat_interface_name) self._add_vips( self.get_snat_port_for_internal_port(port), snat_interface_name) self._add_gateway_vip(ex_gw_port, interface_name) self._disable_ipv6_addressing_on_interface(interface_name) def external_gateway_removed(self, ex_gw_port, interface_name): for port in self.snat_ports: snat_interface = self._get_snat_int_device_name(port['id']) self.driver.unplug(snat_interface, namespace=self.ha_namespace, prefix=l3_constants.SNAT_INT_DEV_PREFIX) self._clear_vips(snat_interface) super(DvrEdgeHaRouter, self)._external_gateway_removed( ex_gw_port, interface_name) self._clear_vips(interface_name) def external_gateway_updated(self, ex_gw_port, interface_name): HaRouter.external_gateway_updated(self, ex_gw_port, interface_name) def initialize(self, process_monitor): self._create_snat_namespace() super(DvrEdgeHaRouter, self).initialize(process_monitor) def process(self, agent): super(DvrEdgeHaRouter, self).process(agent) if self.ha_port: self.enable_keepalived() def delete(self, agent): super(DvrEdgeHaRouter, self).delete(agent) if self.snat_namespace: self.snat_namespace.delete() def get_router_cidrs(self, device): return RouterInfo.get_router_cidrs(self, device) def _external_gateway_added(self, ex_gw_port, interface_name, ns_name, preserve_ips): self._plug_external_gateway(ex_gw_port, interface_name, ns_name) def _is_this_snat_host(self): return (self.agent_conf.agent_mode == l3_constants.L3_AGENT_MODE_DVR_SNAT) def _dvr_internal_network_removed(self, port): super(DvrEdgeHaRouter, self)._dvr_internal_network_removed(port) sn_port = self.get_snat_port_for_internal_port(port, self.snat_ports) if not sn_port: return self._clear_vips(self._get_snat_int_device_name(sn_port['id'])) def _plug_snat_port(self, port): """Used by _create_dvr_gateway in DvrEdgeRouter.""" interface_name = self._get_snat_int_device_name(port['id']) self.driver.plug(port['network_id'], port['id'], interface_name, port['mac_address'], namespace=self.snat_namespace.name, prefix=dvr_snat_ns.SNAT_INT_DEV_PREFIX)
apache-2.0
hadim/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
ExamplesFromChapters/Chapter3/ClusteringWithGaussians.py
90
1034
import numpy as np import pymc as pm data = np.loadtxt("../../Chapter3_MCMC/data/mixture_data.csv", delimiter=",") p = pm.Uniform("p", 0, 1) assignment = pm.Categorical("assignment", [p, 1 - p], size=data.shape[0]) taus = 1.0 / pm.Uniform("stds", 0, 100, size=2) ** 2 # notice the size! centers = pm.Normal("centers", [150, 150], [0.001, 0.001], size=2) """ The below deterministic functions map a assingment, in this case 0 or 1, to a set of parameters, located in the (1,2) arrays `taus` and `centers.` """ @pm.deterministic def center_i(assignment=assignment, centers=centers): return centers[assignment] @pm.deterministic def tau_i(assignment=assignment, taus=taus): return taus[assignment] # and to combine it with the observations: observations = pm.Normal("obs", center_i, tau_i, value=data, observed=True) # below we create a model class model = pm.Model([p, assignment, taus, centers]) map_ = pm.MAP(model) map_.fit() mcmc = pm.MCMC(model) mcmc.sample(100000, 50000)
mit
salguarnieri/intellij-community
plugins/hg4idea/testData/bin/hgext/inotify/server.py
90
14406
# server.py - common entry point for inotify status server # # Copyright 2009 Nicolas Dumazet <nicdumz@gmail.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from mercurial.i18n import _ from mercurial import cmdutil, posix, osutil, util import common import errno import os import socket import stat import struct import sys class AlreadyStartedException(Exception): pass class TimeoutException(Exception): pass def join(a, b): if a: if a[-1] == '/': return a + b return a + '/' + b return b def split(path): c = path.rfind('/') if c == -1: return '', path return path[:c], path[c + 1:] walk_ignored_errors = (errno.ENOENT, errno.ENAMETOOLONG) def walk(dirstate, absroot, root): '''Like os.walk, but only yields regular files.''' # This function is critical to performance during startup. def walkit(root, reporoot): files, dirs = [], [] try: fullpath = join(absroot, root) for name, kind in osutil.listdir(fullpath): if kind == stat.S_IFDIR: if name == '.hg': if not reporoot: return else: dirs.append(name) path = join(root, name) if dirstate._ignore(path): continue for result in walkit(path, False): yield result elif kind in (stat.S_IFREG, stat.S_IFLNK): files.append(name) yield fullpath, dirs, files except OSError, err: if err.errno == errno.ENOTDIR: # fullpath was a directory, but has since been replaced # by a file. yield fullpath, dirs, files elif err.errno not in walk_ignored_errors: raise return walkit(root, root == '') class directory(object): """ Representing a directory * path is the relative path from repo root to this directory * files is a dict listing the files in this directory - keys are file names - values are file status * dirs is a dict listing the subdirectories - key are subdirectories names - values are directory objects """ def __init__(self, relpath=''): self.path = relpath self.files = {} self.dirs = {} def dir(self, relpath): """ Returns the directory contained at the relative path relpath. Creates the intermediate directories if necessary. """ if not relpath: return self l = relpath.split('/') ret = self while l: next = l.pop(0) try: ret = ret.dirs[next] except KeyError: d = directory(join(ret.path, next)) ret.dirs[next] = d ret = d return ret def walk(self, states, visited=None): """ yield (filename, status) pairs for items in the trees that have status in states. filenames are relative to the repo root """ for file, st in self.files.iteritems(): if st in states: yield join(self.path, file), st for dir in self.dirs.itervalues(): if visited is not None: visited.add(dir.path) for e in dir.walk(states): yield e def lookup(self, states, path, visited): """ yield root-relative filenames that match path, and whose status are in states: * if path is a file, yield path * if path is a directory, yield directory files * if path is not tracked, yield nothing """ if path[-1] == '/': path = path[:-1] paths = path.split('/') # we need to check separately for last node last = paths.pop() tree = self try: for dir in paths: tree = tree.dirs[dir] except KeyError: # path is not tracked visited.add(tree.path) return try: # if path is a directory, walk it target = tree.dirs[last] visited.add(target.path) for file, st in target.walk(states, visited): yield file except KeyError: try: if tree.files[last] in states: # path is a file visited.add(tree.path) yield path except KeyError: # path is not tracked pass class repowatcher(object): """ Watches inotify events """ statuskeys = 'almr!?' def __init__(self, ui, dirstate, root): self.ui = ui self.dirstate = dirstate self.wprefix = join(root, '') self.prefixlen = len(self.wprefix) self.tree = directory() self.statcache = {} self.statustrees = dict([(s, directory()) for s in self.statuskeys]) self.ds_info = self.dirstate_info() self.last_event = None def handle_timeout(self): pass def dirstate_info(self): try: st = os.lstat(self.wprefix + '.hg/dirstate') return st.st_mtime, st.st_ino except OSError, err: if err.errno != errno.ENOENT: raise return 0, 0 def filestatus(self, fn, st): try: type_, mode, size, time = self.dirstate._map[fn][:4] except KeyError: type_ = '?' if type_ == 'n': st_mode, st_size, st_mtime = st if size == -1: return 'l' if size and (size != st_size or (mode ^ st_mode) & 0100): return 'm' if time != int(st_mtime): return 'l' return 'n' if type_ == '?' and self.dirstate._dirignore(fn): # we must check not only if the file is ignored, but if any part # of its path match an ignore pattern return 'i' return type_ def updatefile(self, wfn, osstat): ''' update the file entry of an existing file. osstat: (mode, size, time) tuple, as returned by os.lstat(wfn) ''' self._updatestatus(wfn, self.filestatus(wfn, osstat)) def deletefile(self, wfn, oldstatus): ''' update the entry of a file which has been deleted. oldstatus: char in statuskeys, status of the file before deletion ''' if oldstatus == 'r': newstatus = 'r' elif oldstatus in 'almn': newstatus = '!' else: newstatus = None self.statcache.pop(wfn, None) self._updatestatus(wfn, newstatus) def _updatestatus(self, wfn, newstatus): ''' Update the stored status of a file. newstatus: - char in (statuskeys + 'ni'), new status to apply. - or None, to stop tracking wfn ''' root, fn = split(wfn) d = self.tree.dir(root) oldstatus = d.files.get(fn) # oldstatus can be either: # - None : fn is new # - a char in statuskeys: fn is a (tracked) file if self.ui.debugflag and oldstatus != newstatus: self.ui.note(_('status: %r %s -> %s\n') % (wfn, oldstatus, newstatus)) if oldstatus and oldstatus in self.statuskeys \ and oldstatus != newstatus: del self.statustrees[oldstatus].dir(root).files[fn] if newstatus in (None, 'i'): d.files.pop(fn, None) elif oldstatus != newstatus: d.files[fn] = newstatus if newstatus != 'n': self.statustrees[newstatus].dir(root).files[fn] = newstatus def check_deleted(self, key): # Files that had been deleted but were present in the dirstate # may have vanished from the dirstate; we must clean them up. nuke = [] for wfn, ignore in self.statustrees[key].walk(key): if wfn not in self.dirstate: nuke.append(wfn) for wfn in nuke: root, fn = split(wfn) del self.statustrees[key].dir(root).files[fn] del self.tree.dir(root).files[fn] def update_hgignore(self): # An update of the ignore file can potentially change the # states of all unknown and ignored files. # XXX If the user has other ignore files outside the repo, or # changes their list of ignore files at run time, we'll # potentially never see changes to them. We could get the # client to report to us what ignore data they're using. # But it's easier to do nothing than to open that can of # worms. if '_ignore' in self.dirstate.__dict__: delattr(self.dirstate, '_ignore') self.ui.note(_('rescanning due to .hgignore change\n')) self.handle_timeout() self.scan() def getstat(self, wpath): try: return self.statcache[wpath] except KeyError: try: return self.stat(wpath) except OSError, err: if err.errno != errno.ENOENT: raise def stat(self, wpath): try: st = os.lstat(join(self.wprefix, wpath)) ret = st.st_mode, st.st_size, st.st_mtime self.statcache[wpath] = ret return ret except OSError: self.statcache.pop(wpath, None) raise class socketlistener(object): """ Listens for client queries on unix socket inotify.sock """ def __init__(self, ui, root, repowatcher, timeout): self.ui = ui self.repowatcher = repowatcher try: self.sock = posix.unixdomainserver( lambda p: os.path.join(root, '.hg', p), 'inotify') except (OSError, socket.error), err: if err.args[0] == errno.EADDRINUSE: raise AlreadyStartedException(_('cannot start: ' 'socket is already bound')) raise self.fileno = self.sock.fileno def answer_stat_query(self, cs): names = cs.read().split('\0') states = names.pop() self.ui.note(_('answering query for %r\n') % states) visited = set() if not names: def genresult(states, tree): for fn, state in tree.walk(states): yield fn else: def genresult(states, tree): for fn in names: for f in tree.lookup(states, fn, visited): yield f return ['\0'.join(r) for r in [ genresult('l', self.repowatcher.statustrees['l']), genresult('m', self.repowatcher.statustrees['m']), genresult('a', self.repowatcher.statustrees['a']), genresult('r', self.repowatcher.statustrees['r']), genresult('!', self.repowatcher.statustrees['!']), '?' in states and genresult('?', self.repowatcher.statustrees['?']) or [], [], 'c' in states and genresult('n', self.repowatcher.tree) or [], visited ]] def answer_dbug_query(self): return ['\0'.join(self.repowatcher.debug())] def accept_connection(self): sock, addr = self.sock.accept() cs = common.recvcs(sock) version = ord(cs.read(1)) if version != common.version: self.ui.warn(_('received query from incompatible client ' 'version %d\n') % version) try: # try to send back our version to the client # this way, the client too is informed of the mismatch sock.sendall(chr(common.version)) except socket.error: pass return type = cs.read(4) if type == 'STAT': results = self.answer_stat_query(cs) elif type == 'DBUG': results = self.answer_dbug_query() else: self.ui.warn(_('unrecognized query type: %s\n') % type) return try: try: v = chr(common.version) sock.sendall(v + type + struct.pack(common.resphdrfmts[type], *map(len, results))) sock.sendall(''.join(results)) finally: sock.shutdown(socket.SHUT_WR) except socket.error, err: if err.args[0] != errno.EPIPE: raise if sys.platform.startswith('linux'): import linuxserver as _server else: raise ImportError master = _server.master def start(ui, dirstate, root, opts): timeout = opts.get('idle_timeout') if timeout: timeout = float(timeout) * 60000 else: timeout = None class service(object): def init(self): try: self.master = master(ui, dirstate, root, timeout) except AlreadyStartedException, inst: raise util.Abort("inotify-server: %s" % inst) def run(self): try: try: self.master.run() except TimeoutException: pass finally: self.master.shutdown() if 'inserve' not in sys.argv: runargs = util.hgcmd() + ['inserve', '-R', root] else: runargs = util.hgcmd() + sys.argv[1:] pidfile = ui.config('inotify', 'pidfile') if opts['daemon'] and pidfile is not None and 'pid-file' not in runargs: runargs.append("--pid-file=%s" % pidfile) service = service() logfile = ui.config('inotify', 'log') appendpid = ui.configbool('inotify', 'appendpid', False) ui.debug('starting inotify server: %s\n' % ' '.join(runargs)) cmdutil.service(opts, initfn=service.init, runfn=service.run, logfile=logfile, runargs=runargs, appendpid=appendpid)
apache-2.0
40023256/W17test
static/Brython3.1.3-20150514-095342/Lib/inspect.py
637
78935
"""Get useful information from live Python objects. This module encapsulates the interface provided by the internal special attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion. It also provides some help for examining source code and class layout. Here are some of the useful functions provided by this module: ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(), isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(), isroutine() - check object types getmembers() - get members of an object that satisfy a given condition getfile(), getsourcefile(), getsource() - find an object's source code getdoc(), getcomments() - get documentation on an object getmodule() - determine the module that an object came from getclasstree() - arrange classes so as to represent their hierarchy getargspec(), getargvalues(), getcallargs() - get info about function arguments getfullargspec() - same, with support for Python-3000 features formatargspec(), formatargvalues() - format an argument spec getouterframes(), getinnerframes() - get info about frames currentframe() - get the current stack frame stack(), trace() - get info about frames on the stack or in a traceback signature() - get a Signature object for the callable """ # This module is in the public domain. No warranties. __author__ = ('Ka-Ping Yee <ping@lfw.org>', 'Yury Selivanov <yselivanov@sprymix.com>') import imp import importlib.machinery import itertools import linecache import os import re import sys import tokenize import types import warnings import functools import builtins from operator import attrgetter from collections import namedtuple, OrderedDict # Create constants for the compiler flags in Include/code.h # We try to get them from dis to avoid duplication, but fall # back to hardcoding so the dependency is optional try: from dis import COMPILER_FLAG_NAMES as _flag_names except ImportError: CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40 else: mod_dict = globals() for k, v in _flag_names.items(): mod_dict["CO_" + v] = k # See Include/object.h TPFLAGS_IS_ABSTRACT = 1 << 20 # ----------------------------------------------------------- type-checking def ismodule(object): """Return true if the object is a module. Module objects provide these attributes: __cached__ pathname to byte compiled file __doc__ documentation string __file__ filename (missing for built-in modules)""" return isinstance(object, types.ModuleType) def isclass(object): """Return true if the object is a class. Class objects provide these attributes: __doc__ documentation string __module__ name of module in which this class was defined""" return isinstance(object, type) def ismethod(object): """Return true if the object is an instance method. Instance method objects provide these attributes: __doc__ documentation string __name__ name with which this method was defined __func__ function object containing implementation of method __self__ instance to which this method is bound""" return isinstance(object, types.MethodType) def ismethoddescriptor(object): """Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the __func__ attribute (etc) when an object passes ismethod().""" if isclass(object) or ismethod(object) or isfunction(object): # mutual exclusion return False tp = type(object) return hasattr(tp, "__get__") and not hasattr(tp, "__set__") def isdatadescriptor(object): """Return true if the object is a data descriptor. Data descriptors have both a __get__ and a __set__ attribute. Examples are properties (defined in Python) and getsets and members (defined in C). Typically, data descriptors will also have __name__ and __doc__ attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed.""" if isclass(object) or ismethod(object) or isfunction(object): # mutual exclusion return False tp = type(object) return hasattr(tp, "__set__") and hasattr(tp, "__get__") if hasattr(types, 'MemberDescriptorType'): # CPython and equivalent def ismemberdescriptor(object): """Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.""" return isinstance(object, types.MemberDescriptorType) else: # Other implementations def ismemberdescriptor(object): """Return true if the object is a member descriptor. Member descriptors are specialized descriptors defined in extension modules.""" return False if hasattr(types, 'GetSetDescriptorType'): # CPython and equivalent def isgetsetdescriptor(object): """Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.""" return isinstance(object, types.GetSetDescriptorType) else: # Other implementations def isgetsetdescriptor(object): """Return true if the object is a getset descriptor. getset descriptors are specialized descriptors defined in extension modules.""" return False def isfunction(object): """Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined __code__ code object containing compiled function bytecode __defaults__ tuple of any default values for arguments __globals__ global namespace in which this function was defined __annotations__ dict of parameter annotations __kwdefaults__ dict of keyword only parameters with defaults""" return isinstance(object, types.FunctionType) def isgeneratorfunction(object): """Return true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See help(isfunction) for attributes listing.""" return bool((isfunction(object) or ismethod(object)) and object.__code__.co_flags & CO_GENERATOR) def isgenerator(object): """Return true if the object is a generator. Generator objects provide these attributes: __iter__ defined to support iteration over container close raises a new GeneratorExit exception inside the generator to terminate the iteration gi_code code object gi_frame frame object or possibly None once the generator has been exhausted gi_running set to 1 when generator is executing, 0 otherwise next return the next item from the container send resumes the generator and "sends" a value that becomes the result of the current yield-expression throw used to raise an exception inside the generator""" return isinstance(object, types.GeneratorType) def istraceback(object): """Return true if the object is a traceback. Traceback objects provide these attributes: tb_frame frame object at this level tb_lasti index of last attempted instruction in bytecode tb_lineno current line number in Python source code tb_next next inner traceback object (called by this level)""" return isinstance(object, types.TracebackType) def isframe(object): """Return true if the object is a frame object. Frame objects provide these attributes: f_back next outer frame object (this frame's caller) f_builtins built-in namespace seen by this frame f_code code object being executed in this frame f_globals global namespace seen by this frame f_lasti index of last attempted instruction in bytecode f_lineno current line number in Python source code f_locals local namespace seen by this frame f_trace tracing function for this frame, or None""" return isinstance(object, types.FrameType) def iscode(object): """Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including * or ** args) co_code string of raw compiled bytecode co_consts tuple of constants used in the bytecode co_filename name of file in which this code object was created co_firstlineno number of first line in Python source code co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg co_lnotab encoded mapping of line numbers to bytecode indices co_name name with which this code object was defined co_names tuple of names of local variables co_nlocals number of local variables co_stacksize virtual machine stack space required co_varnames tuple of names of arguments and local variables""" return isinstance(object, types.CodeType) def isbuiltin(object): """Return true if the object is a built-in function or method. Built-in functions and methods provide these attributes: __doc__ documentation string __name__ original name of this function or method __self__ instance to which a method is bound, or None""" return isinstance(object, types.BuiltinFunctionType) def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object)) def isabstract(object): """Return true if the object is an abstract base class (ABC).""" return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT) def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" if isclass(object): mro = (object,) + getmro(object) else: mro = () results = [] for key in dir(object): # First try to get the value via __dict__. Some descriptors don't # like calling their __get__ (see bug #1785). for base in mro: if key in base.__dict__: value = base.__dict__[key] break else: try: value = getattr(object, key) except AttributeError: continue if not predicate or predicate(value): results.append((key, value)) results.sort() return results Attribute = namedtuple('Attribute', 'name kind defining_class object') def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained directly from the defining class's __dict__, not via getattr. This is especially important for data attributes: C.data is just a data object, but C.__dict__['data'] may be a data descriptor with additional info, like a __doc__ string. """ mro = getmro(cls) names = dir(cls) result = [] for name in names: # Get the object associated with the name, and where it was defined. # Getting an obj from the __dict__ sometimes reveals more than # using getattr. Static and class methods are dramatic examples. # Furthermore, some objects may raise an Exception when fetched with # getattr(). This is the case with some descriptors (bug #1785). # Thus, we only use getattr() as a last resort. homecls = None for base in (cls,) + mro: if name in base.__dict__: obj = base.__dict__[name] homecls = base break else: obj = getattr(cls, name) homecls = getattr(obj, "__objclass__", homecls) # Classify the object. if isinstance(obj, staticmethod): kind = "static method" elif isinstance(obj, classmethod): kind = "class method" elif isinstance(obj, property): kind = "property" elif ismethoddescriptor(obj): kind = "method" elif isdatadescriptor(obj): kind = "data" else: obj_via_getattr = getattr(cls, name) if (isfunction(obj_via_getattr) or ismethoddescriptor(obj_via_getattr)): kind = "method" else: kind = "data" obj = obj_via_getattr result.append(Attribute(name, kind, homecls, obj)) return result # ----------------------------------------------------------- class helpers def getmro(cls): "Return tuple of base classes (including cls) in method resolution order." return cls.__mro__ # -------------------------------------------------- source code extraction def indentsize(line): """Return the indent size, in spaces, at the start of a line of text.""" expline = line.expandtabs() return len(expline) - len(expline.lstrip()) def getdoc(object): """Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.""" try: doc = object.__doc__ except AttributeError: return None if not isinstance(doc, str): return None return cleandoc(doc) def cleandoc(doc): """Clean up indentation from docstrings. Any whitespace that can be uniformly removed from the second line onwards is removed.""" try: lines = doc.expandtabs().split('\n') except UnicodeError: return None else: # Find minimum indentation of any non-blank lines after first line. margin = sys.maxsize for line in lines[1:]: content = len(line.lstrip()) if content: indent = len(line) - content margin = min(margin, indent) # Remove indentation. if lines: lines[0] = lines[0].lstrip() if margin < sys.maxsize: for i in range(1, len(lines)): lines[i] = lines[i][margin:] # Remove any trailing or leading blank lines. while lines and not lines[-1]: lines.pop() while lines and not lines[0]: lines.pop(0) return '\n'.join(lines) def getfile(object): """Work out which source or compiled file an object was defined in.""" if ismodule(object): if hasattr(object, '__file__'): return object.__file__ raise TypeError('{!r} is a built-in module'.format(object)) if isclass(object): object = sys.modules.get(object.__module__) if hasattr(object, '__file__'): return object.__file__ raise TypeError('{!r} is a built-in class'.format(object)) if ismethod(object): object = object.__func__ if isfunction(object): object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): return object.co_filename raise TypeError('{!r} is not a module, class, method, ' 'function, traceback, frame, or code object'.format(object)) ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type') def getmoduleinfo(path): """Get the module name, suffix, mode, and module type for a given file.""" warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning, 2) filename = os.path.basename(path) suffixes = [(-len(suffix), suffix, mode, mtype) for suffix, mode, mtype in imp.get_suffixes()] suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix, mode, mtype in suffixes: if filename[neglen:] == suffix: return ModuleInfo(filename[:neglen], suffix, mode, mtype) def getmodulename(path): """Return the module name for a given file, or None.""" fname = os.path.basename(path) # Check for paths that look like an actual module file suffixes = [(-len(suffix), suffix) for suffix in importlib.machinery.all_suffixes()] suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix in suffixes: if fname.endswith(suffix): return fname[:neglen] return None def getsourcefile(object): """Return the filename that can be used to locate an object's source. Return None if no way can be identified to get the source. """ filename = getfile(object) all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:] all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:] if any(filename.endswith(s) for s in all_bytecode_suffixes): filename = (os.path.splitext(filename)[0] + importlib.machinery.SOURCE_SUFFIXES[0]) elif any(filename.endswith(s) for s in importlib.machinery.EXTENSION_SUFFIXES): return None if os.path.exists(filename): return filename # only return a non-existent filename if the module has a PEP 302 loader if hasattr(getmodule(object, filename), '__loader__'): return filename # or it is in the linecache if filename in linecache.cache: return filename def getabsfile(object, _filename=None): """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.""" if _filename is None: _filename = getsourcefile(object) or getfile(object) return os.path.normcase(os.path.abspath(_filename)) modulesbyfile = {} _filesbymodname = {} def getmodule(object, _filename=None): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if hasattr(object, '__module__'): return sys.modules.get(object.__module__) # Try the filename to modulename cache if _filename is not None and _filename in modulesbyfile: return sys.modules.get(modulesbyfile[_filename]) # Try the cache again with the absolute file name try: file = getabsfile(object, _filename) except TypeError: return None if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) # Update the filename to module name cache and check yet again # Copy sys.modules in order to cope with changes while iterating for modname, module in list(sys.modules.items()): if ismodule(module) and hasattr(module, '__file__'): f = module.__file__ if f == _filesbymodname.get(modname, None): # Have already mapped this module, so skip it continue _filesbymodname[modname] = f f = getabsfile(module) # Always map to the name the module knows itself by modulesbyfile[f] = modulesbyfile[ os.path.realpath(f)] = module.__name__ if file in modulesbyfile: return sys.modules.get(modulesbyfile[file]) # Check the main module main = sys.modules['__main__'] if not hasattr(object, '__name__'): return None if hasattr(main, object.__name__): mainobject = getattr(main, object.__name__) if mainobject is object: return main # Check builtins builtin = sys.modules['builtins'] if hasattr(builtin, object.__name__): builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" file = getfile(object) sourcefile = getsourcefile(object) if not sourcefile and file[:1] + file[-1:] != '<>': raise IOError('source code not available') file = sourcefile if sourcefile else file module = getmodule(object, file) if module: lines = linecache.getlines(file, module.__dict__) else: lines = linecache.getlines(file) if not lines: raise IOError('could not get source code') if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^(\s*)class\s*' + name + r'\b') # make some effort to find the best matching class definition: # use the one with the least indentation, which is the one # that's most probably not inside a function definition. candidates = [] for i in range(len(lines)): match = pat.match(lines[i]) if match: # if it's at toplevel, it's already the best one if lines[i][0] == 'c': return lines, i # else add whitespace to candidate list candidates.append((match.group(1), i)) if candidates: # this will sort by whitespace, and by line number, # less whitespace first candidates.sort() return lines, candidates[0][1] else: raise IOError('could not find class definition') if ismethod(object): object = object.__func__ if isfunction(object): object = object.__code__ if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError('could not find function definition') lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError('could not find code object') def getcomments(object): """Get lines of comments immediately preceding an object's source code. Returns None when source can't be found. """ try: lines, lnum = findsource(object) except (IOError, TypeError): return None if ismodule(object): # Look for a comment block at the top of the file. start = 0 if lines and lines[0][:2] == '#!': start = 1 while start < len(lines) and lines[start].strip() in ('', '#'): start = start + 1 if start < len(lines) and lines[start][:1] == '#': comments = [] end = start while end < len(lines) and lines[end][:1] == '#': comments.append(lines[end].expandtabs()) end = end + 1 return ''.join(comments) # Look for a preceding block of comments at the same indentation. elif lnum > 0: indent = indentsize(lines[lnum]) end = lnum - 1 if end >= 0 and lines[end].lstrip()[:1] == '#' and \ indentsize(lines[end]) == indent: comments = [lines[end].expandtabs().lstrip()] if end > 0: end = end - 1 comment = lines[end].expandtabs().lstrip() while comment[:1] == '#' and indentsize(lines[end]) == indent: comments[:0] = [comment] end = end - 1 if end < 0: break comment = lines[end].expandtabs().lstrip() while comments and comments[0].strip() == '#': comments[:1] = [] while comments and comments[-1].strip() == '#': comments[-1:] = [] return ''.join(comments) class EndOfBlock(Exception): pass class BlockFinder: """Provide a tokeneater() method to detect the end of a code block.""" def __init__(self): self.indent = 0 self.islambda = False self.started = False self.passline = False self.last = 1 def tokeneater(self, type, token, srowcol, erowcol, line): if not self.started: # look for the first "def", "class" or "lambda" if token in ("def", "class", "lambda"): if token == "lambda": self.islambda = True self.started = True self.passline = True # skip to the end of the line elif type == tokenize.NEWLINE: self.passline = False # stop skipping when a NEWLINE is seen self.last = srowcol[0] if self.islambda: # lambdas always end at the first NEWLINE raise EndOfBlock elif self.passline: pass elif type == tokenize.INDENT: self.indent = self.indent + 1 self.passline = True elif type == tokenize.DEDENT: self.indent = self.indent - 1 # the end of matching indent/dedent pairs end a block # (note that this only works for "def"/"class" blocks, # not e.g. for "if: else:" or "try: finally:" blocks) if self.indent <= 0: raise EndOfBlock elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL): # any other token on the same indentation level end the previous # block as well, except the pseudo-tokens COMMENT and NL. raise EndOfBlock def getblock(lines): """Extract the block of code at the top of the given list of lines.""" blockfinder = BlockFinder() try: tokens = tokenize.generate_tokens(iter(lines).__next__) for _token in tokens: blockfinder.tokeneater(*_token) except (EndOfBlock, IndentationError): pass return lines[:blockfinder.last] def getsourcelines(object): """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = findsource(object) if ismodule(object): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1 def getsource(object): """Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = getsourcelines(object) return ''.join(lines) # --------------------------------------------------- class tree extraction def walktree(classes, children, parent): """Recursive helper function for getclasstree().""" results = [] classes.sort(key=attrgetter('__module__', '__name__')) for c in classes: results.append((c, c.__bases__)) if c in children: results.append(walktree(children[c], children, c)) return results def getclasstree(classes, unique=False): """Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the 'unique' argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.""" children = {} roots = [] for c in classes: if c.__bases__: for parent in c.__bases__: if not parent in children: children[parent] = [] if c not in children[parent]: children[parent].append(c) if unique and parent in classes: break elif c not in roots: roots.append(c) for parent in children: if parent not in classes: roots.append(parent) return walktree(roots, children, None) # ------------------------------------------------ argument list extraction Arguments = namedtuple('Arguments', 'args, varargs, varkw') def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is the list of argument names. Keyword-only arguments are appended. 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" args, varargs, kwonlyargs, varkw = _getfullargs(co) return Arguments(args + kwonlyargs, varargs, varkw) def _getfullargs(co): """Get information about the arguments accepted by a code object. Four things are returned: (args, varargs, kwonlyargs, varkw), where 'args' and 'kwonlyargs' are lists of argument names, and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError('{!r} is not a code object'.format(co)) nargs = co.co_argcount names = co.co_varnames nkwargs = co.co_kwonlyargcount args = list(names[:nargs]) kwonlyargs = list(names[nargs:nargs+nkwargs]) step = 0 nargs += nkwargs varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, kwonlyargs, varkw ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults') def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names. 'args' will include keyword-only argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Use the getfullargspec() API for Python-3000 code, as annotations and keyword arguments are supported. getargspec() will raise ValueError if the func has either annotations or keyword arguments. """ args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ getfullargspec(func) if kwonlyargs or ann: raise ValueError("Function has keyword-only arguments or annotations" ", use getfullargspec() API which can support them") return ArgSpec(args, varargs, varkw, defaults) FullArgSpec = namedtuple('FullArgSpec', 'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations') def getfullargspec(func): """Get the names and default values of a function's arguments. A tuple of seven things is returned: (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations). 'args' is a list of the argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. 'kwonlyargs' is a list of keyword-only argument names. 'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults. 'annotations' is a dictionary mapping argument names to annotations. The first four items in the tuple correspond to getargspec(). """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError('{!r} is not a Python function'.format(func)) args, varargs, kwonlyargs, varkw = _getfullargs(func.__code__) return FullArgSpec(args, varargs, varkw, func.__defaults__, kwonlyargs, func.__kwdefaults__, func.__annotations__) ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals') def getargvalues(frame): """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names. 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) return ArgInfo(args, varargs, varkw, frame.f_locals) def formatannotation(annotation, base_module=None): if isinstance(annotation, type): if annotation.__module__ in ('builtins', base_module): return annotation.__name__ return annotation.__module__+'.'+annotation.__name__ return repr(annotation) def formatannotationrelativeto(object): module = getattr(object, '__module__', None) def _formatannotation(annotation): return formatannotation(annotation, module) return _formatannotation #brython fix me def formatargspec(args, varargs=None, varkw=None, defaults=None, kwonlyargs=(), kwonlydefaults={}, annotations={}, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), formatreturns=lambda text: ' -> ' + text, formatannotation=formatannotation): """Format an argument spec from the values returned by getargspec or getfullargspec. The first seven arguments are (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations). The other five arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The last argument is an optional function to format the sequence of arguments.""" def formatargandannotation(arg): result = formatarg(arg) if arg in annotations: result += ': ' + formatannotation(annotations[arg]) return result specs = [] if defaults: firstdefault = len(args) - len(defaults) for i, arg in enumerate(args): spec = formatargandannotation(arg) if defaults and i >= firstdefault: spec = spec + formatvalue(defaults[i - firstdefault]) specs.append(spec) if varargs is not None: specs.append(formatvarargs(formatargandannotation(varargs))) else: if kwonlyargs: specs.append('*') if kwonlyargs: for kwonlyarg in kwonlyargs: spec = formatargandannotation(kwonlyarg) if kwonlydefaults and kwonlyarg in kwonlydefaults: spec += formatvalue(kwonlydefaults[kwonlyarg]) specs.append(spec) if varkw is not None: specs.append(formatvarkw(formatargandannotation(varkw))) result = '(' + ', '.join(specs) + ')' if 'return' in annotations: result += formatreturns(formatannotation(annotations['return'])) return result #brython fix me #def formatargvalues(args, varargs, varkw, locals, # formatarg=str, # formatvarargs=lambda name: '*' + name, # formatvarkw=lambda name: '**' + name, # formatvalue=lambda value: '=' + repr(value)): # """Format an argument spec from the 4 values returned by getargvalues. # The first four arguments are (args, varargs, varkw, locals). The # next four arguments are the corresponding optional formatting functions # that are called to turn names and values into strings. The ninth # argument is an optional function to format the sequence of arguments.""" # def convert(name, locals=locals, # formatarg=formatarg, formatvalue=formatvalue): # return formatarg(name) + formatvalue(locals[name]) # specs = [] # for i in range(len(args)): # specs.append(convert(args[i])) # if varargs: # specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) # if varkw: # specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) # return '(' + ', '.join(specs) + ')' def _missing_arguments(f_name, argnames, pos, values): names = [repr(name) for name in argnames if name not in values] missing = len(names) if missing == 1: s = names[0] elif missing == 2: s = "{} and {}".format(*names) else: tail = ", {} and {}".format(names[-2:]) del names[-2:] s = ", ".join(names) + tail raise TypeError("%s() missing %i required %s argument%s: %s" % (f_name, missing, "positional" if pos else "keyword-only", "" if missing == 1 else "s", s)) def _too_many(f_name, args, kwonly, varargs, defcount, given, values): atleast = len(args) - defcount kwonly_given = len([arg for arg in kwonly if arg in values]) if varargs: plural = atleast != 1 sig = "at least %d" % (atleast,) elif defcount: plural = True sig = "from %d to %d" % (atleast, len(args)) else: plural = len(args) != 1 sig = str(len(args)) kwonly_sig = "" if kwonly_given: msg = " positional argument%s (and %d keyword-only argument%s)" kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given, "s" if kwonly_given != 1 else "")) raise TypeError("%s() takes %s positional argument%s but %d%s %s given" % (f_name, sig, "s" if plural else "", given, kwonly_sig, "was" if given == 1 and not kwonly_given else "were")) def getcallargs(func, *positional, **named): """Get the mapping of arguments to values. A dict is returned, with keys the function argument names (including the names of the * and ** arguments, if any), and values the respective bound values from 'positional' and 'named'.""" spec = getfullargspec(func) args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec f_name = func.__name__ arg2value = {} if ismethod(func) and func.__self__ is not None: # implicit 'self' (or 'cls' for classmethods) argument positional = (func.__self__,) + positional num_pos = len(positional) num_args = len(args) num_defaults = len(defaults) if defaults else 0 n = min(num_pos, num_args) for i in range(n): arg2value[args[i]] = positional[i] if varargs: arg2value[varargs] = tuple(positional[n:]) possible_kwargs = set(args + kwonlyargs) if varkw: arg2value[varkw] = {} for kw, value in named.items(): if kw not in possible_kwargs: if not varkw: raise TypeError("%s() got an unexpected keyword argument %r" % (f_name, kw)) arg2value[varkw][kw] = value continue if kw in arg2value: raise TypeError("%s() got multiple values for argument %r" % (f_name, kw)) arg2value[kw] = value if num_pos > num_args and not varargs: _too_many(f_name, args, kwonlyargs, varargs, num_defaults, num_pos, arg2value) if num_pos < num_args: req = args[:num_args - num_defaults] for arg in req: if arg not in arg2value: _missing_arguments(f_name, req, True, arg2value) for i, arg in enumerate(args[num_args - num_defaults:]): if arg not in arg2value: arg2value[arg] = defaults[i] missing = 0 for kwarg in kwonlyargs: if kwarg not in arg2value: if kwarg in kwonlydefaults: arg2value[kwarg] = kwonlydefaults[kwarg] else: missing += 1 if missing: _missing_arguments(f_name, kwonlyargs, False, arg2value) return arg2value ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound') def getclosurevars(func): """ Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final set of unbound names that could not be resolved is also provided. """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError("'{!r}' is not a Python function".format(func)) code = func.__code__ # Nonlocal references are named in co_freevars and resolved # by looking them up in __closure__ by positional index if func.__closure__ is None: nonlocal_vars = {} else: nonlocal_vars = { var : cell.cell_contents for var, cell in zip(code.co_freevars, func.__closure__) } # Global and builtin references are named in co_names and resolved # by looking them up in __globals__ or __builtins__ global_ns = func.__globals__ builtin_ns = global_ns.get("__builtins__", builtins.__dict__) if ismodule(builtin_ns): builtin_ns = builtin_ns.__dict__ global_vars = {} builtin_vars = {} unbound_names = set() for name in code.co_names: if name in ("None", "True", "False"): # Because these used to be builtins instead of keywords, they # may still show up as name references. We ignore them. continue try: global_vars[name] = global_ns[name] except KeyError: try: builtin_vars[name] = builtin_ns[name] except KeyError: unbound_names.add(name) return ClosureVars(nonlocal_vars, global_vars, builtin_vars, unbound_names) # -------------------------------------------------- stack frame extraction Traceback = namedtuple('Traceback', 'filename lineno function code_context index') def getframeinfo(frame, context=1): """Get information about a frame or traceback object. A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line.""" if istraceback(frame): lineno = frame.tb_lineno frame = frame.tb_frame else: lineno = frame.f_lineno if not isframe(frame): raise TypeError('{!r} is not a frame or traceback object'.format(frame)) filename = getsourcefile(frame) or getfile(frame) if context > 0: start = lineno - 1 - context//2 try: lines, lnum = findsource(frame) except IOError: lines = index = None else: start = max(start, 1) start = max(0, min(start, len(lines) - context)) lines = lines[start:start+context] index = lineno - 1 - start else: lines = index = None return Traceback(filename, lineno, frame.f_code.co_name, lines, index) def getlineno(frame): """Get the line number from a frame object, allowing for optimization.""" # FrameType.f_lineno is now a descriptor that grovels co_lnotab return frame.f_lineno def getouterframes(frame, context=1): """Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while frame: framelist.append((frame,) + getframeinfo(frame, context)) frame = frame.f_back return framelist def getinnerframes(tb, context=1): """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while tb: framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) tb = tb.tb_next return framelist def currentframe(): """Return the frame of the caller or None if this is not possible.""" return sys._getframe(1) if hasattr(sys, "_getframe") else None def stack(context=1): """Return a list of records for the stack above the caller's frame.""" return getouterframes(sys._getframe(1), context) def trace(context=1): """Return a list of records for the stack below the current exception.""" return getinnerframes(sys.exc_info()[2], context) # ------------------------------------------------ static version of getattr _sentinel = object() def _static_getmro(klass): return type.__dict__['__mro__'].__get__(klass) def _check_instance(obj, attr): instance_dict = {} try: instance_dict = object.__getattribute__(obj, "__dict__") except AttributeError: pass return dict.get(instance_dict, attr, _sentinel) def _check_class(klass, attr): for entry in _static_getmro(klass): if _shadowed_dict(type(entry)) is _sentinel: try: return entry.__dict__[attr] except KeyError: pass return _sentinel def _is_type(obj): try: _static_getmro(obj) except TypeError: return False return True def _shadowed_dict(klass): dict_attr = type.__dict__["__dict__"] for entry in _static_getmro(klass): try: class_dict = dict_attr.__get__(entry)["__dict__"] except KeyError: pass else: if not (type(class_dict) is types.GetSetDescriptorType and class_dict.__name__ == "__dict__" and class_dict.__objclass__ is entry): return class_dict return _sentinel def getattr_static(obj, attr, default=_sentinel): """Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__ or __getattribute__. Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can't (like descriptors that raise AttributeError). It can also return descriptor objects instead of instance members in some cases. See the documentation for details. """ instance_result = _sentinel if not _is_type(obj): klass = type(obj) dict_attr = _shadowed_dict(klass) if (dict_attr is _sentinel or type(dict_attr) is types.MemberDescriptorType): instance_result = _check_instance(obj, attr) else: klass = obj klass_result = _check_class(klass, attr) if instance_result is not _sentinel and klass_result is not _sentinel: if (_check_class(type(klass_result), '__get__') is not _sentinel and _check_class(type(klass_result), '__set__') is not _sentinel): return klass_result if instance_result is not _sentinel: return instance_result if klass_result is not _sentinel: return klass_result if obj is klass: # for types we check the metaclass too for entry in _static_getmro(type(klass)): if _shadowed_dict(type(entry)) is _sentinel: try: return entry.__dict__[attr] except KeyError: pass if default is not _sentinel: return default raise AttributeError(attr) # ------------------------------------------------ generator introspection GEN_CREATED = 'GEN_CREATED' GEN_RUNNING = 'GEN_RUNNING' GEN_SUSPENDED = 'GEN_SUSPENDED' GEN_CLOSED = 'GEN_CLOSED' def getgeneratorstate(generator): """Get current state of a generator-iterator. Possible states are: GEN_CREATED: Waiting to start execution. GEN_RUNNING: Currently being executed by the interpreter. GEN_SUSPENDED: Currently suspended at a yield expression. GEN_CLOSED: Execution has completed. """ if generator.gi_running: return GEN_RUNNING if generator.gi_frame is None: return GEN_CLOSED if generator.gi_frame.f_lasti == -1: return GEN_CREATED return GEN_SUSPENDED def getgeneratorlocals(generator): """ Get the mapping of generator local variables to their current values. A dict is returned, with the keys the local variable names and values the bound values.""" if not isgenerator(generator): raise TypeError("'{!r}' is not a Python generator".format(generator)) frame = getattr(generator, "gi_frame", None) if frame is not None: return generator.gi_frame.f_locals else: return {} ############################################################################### ### Function Signature Object (PEP 362) ############################################################################### _WrapperDescriptor = type(type.__call__) _MethodWrapper = type(all.__call__) _NonUserDefinedCallables = (_WrapperDescriptor, _MethodWrapper, types.BuiltinFunctionType) def _get_user_defined_method(cls, method_name): try: meth = getattr(cls, method_name) except AttributeError: return else: if not isinstance(meth, _NonUserDefinedCallables): # Once '__signature__' will be added to 'C'-level # callables, this check won't be necessary return meth def signature(obj): '''Get a signature object for the passed callable.''' if not callable(obj): raise TypeError('{!r} is not a callable object'.format(obj)) if isinstance(obj, types.MethodType): # In this case we skip the first parameter of the underlying # function (usually `self` or `cls`). sig = signature(obj.__func__) return sig.replace(parameters=tuple(sig.parameters.values())[1:]) try: sig = obj.__signature__ except AttributeError: pass else: if sig is not None: return sig try: # Was this function wrapped by a decorator? wrapped = obj.__wrapped__ except AttributeError: pass else: return signature(wrapped) if isinstance(obj, types.FunctionType): return Signature.from_function(obj) if isinstance(obj, functools.partial): sig = signature(obj.func) new_params = OrderedDict(sig.parameters.items()) partial_args = obj.args or () partial_keywords = obj.keywords or {} try: ba = sig.bind_partial(*partial_args, **partial_keywords) except TypeError as ex: msg = 'partial object {!r} has incorrect arguments'.format(obj) raise ValueError(msg) from ex for arg_name, arg_value in ba.arguments.items(): param = new_params[arg_name] if arg_name in partial_keywords: # We set a new default value, because the following code # is correct: # # >>> def foo(a): print(a) # >>> print(partial(partial(foo, a=10), a=20)()) # 20 # >>> print(partial(partial(foo, a=10), a=20)(a=30)) # 30 # # So, with 'partial' objects, passing a keyword argument is # like setting a new default value for the corresponding # parameter # # We also mark this parameter with '_partial_kwarg' # flag. Later, in '_bind', the 'default' value of this # parameter will be added to 'kwargs', to simulate # the 'functools.partial' real call. new_params[arg_name] = param.replace(default=arg_value, _partial_kwarg=True) elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and not param._partial_kwarg): new_params.pop(arg_name) return sig.replace(parameters=new_params.values()) sig = None if isinstance(obj, type): # obj is a class or a metaclass # First, let's see if it has an overloaded __call__ defined # in its metaclass call = _get_user_defined_method(type(obj), '__call__') if call is not None: sig = signature(call) else: # Now we check if the 'obj' class has a '__new__' method new = _get_user_defined_method(obj, '__new__') if new is not None: sig = signature(new) else: # Finally, we should have at least __init__ implemented init = _get_user_defined_method(obj, '__init__') if init is not None: sig = signature(init) elif not isinstance(obj, _NonUserDefinedCallables): # An object with __call__ # We also check that the 'obj' is not an instance of # _WrapperDescriptor or _MethodWrapper to avoid # infinite recursion (and even potential segfault) call = _get_user_defined_method(type(obj), '__call__') if call is not None: sig = signature(call) if sig is not None: # For classes and objects we skip the first parameter of their # __call__, __new__, or __init__ methods return sig.replace(parameters=tuple(sig.parameters.values())[1:]) if isinstance(obj, types.BuiltinFunctionType): # Raise a nicer error message for builtins msg = 'no signature found for builtin function {!r}'.format(obj) raise ValueError(msg) raise ValueError('callable {!r} is not supported by signature'.format(obj)) class _void: '''A private marker - used in Parameter & Signature''' class _empty: pass class _ParameterKind(int): def __new__(self, *args, name): obj = int.__new__(self, *args) obj._name = name return obj def __str__(self): return self._name def __repr__(self): return '<_ParameterKind: {!r}>'.format(self._name) _POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY') _POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD') _VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL') _KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY') _VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD') class Parameter: '''Represents a parameter in a function signature. Has the following public attributes: * name : str The name of the parameter as a string. * default : object The default value for the parameter if specified. If the parameter has no default value, this attribute is not set. * annotation The annotation for the parameter if specified. If the parameter has no annotation, this attribute is not set. * kind : str Describes how argument values are bound to the parameter. Possible values: `Parameter.POSITIONAL_ONLY`, `Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`, `Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`. ''' __slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg') POSITIONAL_ONLY = _POSITIONAL_ONLY POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD VAR_POSITIONAL = _VAR_POSITIONAL KEYWORD_ONLY = _KEYWORD_ONLY VAR_KEYWORD = _VAR_KEYWORD empty = _empty def __init__(self, name, kind, *, default=_empty, annotation=_empty, _partial_kwarg=False): if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD, _VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD): raise ValueError("invalid value for 'Parameter.kind' attribute") self._kind = kind if default is not _empty: if kind in (_VAR_POSITIONAL, _VAR_KEYWORD): msg = '{} parameters cannot have default values'.format(kind) raise ValueError(msg) self._default = default self._annotation = annotation if name is None: if kind != _POSITIONAL_ONLY: raise ValueError("None is not a valid name for a " "non-positional-only parameter") self._name = name else: name = str(name) if kind != _POSITIONAL_ONLY and not name.isidentifier(): msg = '{!r} is not a valid parameter name'.format(name) raise ValueError(msg) self._name = name self._partial_kwarg = _partial_kwarg @property def name(self): return self._name @property def default(self): return self._default @property def annotation(self): return self._annotation @property def kind(self): return self._kind def replace(self, *, name=_void, kind=_void, annotation=_void, default=_void, _partial_kwarg=_void): '''Creates a customized copy of the Parameter.''' if name is _void: name = self._name if kind is _void: kind = self._kind if annotation is _void: annotation = self._annotation if default is _void: default = self._default if _partial_kwarg is _void: _partial_kwarg = self._partial_kwarg return type(self)(name, kind, default=default, annotation=annotation, _partial_kwarg=_partial_kwarg) def __str__(self): kind = self.kind formatted = self._name if kind == _POSITIONAL_ONLY: if formatted is None: formatted = '' formatted = '<{}>'.format(formatted) # Add annotation and default value if self._annotation is not _empty: formatted = '{}:{}'.format(formatted, formatannotation(self._annotation)) if self._default is not _empty: formatted = '{}={}'.format(formatted, repr(self._default)) if kind == _VAR_POSITIONAL: formatted = '*' + formatted elif kind == _VAR_KEYWORD: formatted = '**' + formatted return formatted def __repr__(self): return '<{} at {:#x} {!r}>'.format(self.__class__.__name__, id(self), self.name) def __eq__(self, other): return (issubclass(other.__class__, Parameter) and self._name == other._name and self._kind == other._kind and self._default == other._default and self._annotation == other._annotation) def __ne__(self, other): return not self.__eq__(other) class BoundArguments: '''Result of `Signature.bind` call. Holds the mapping of arguments to the function's parameters. Has the following public attributes: * arguments : OrderedDict An ordered mutable mapping of parameters' names to arguments' values. Does not contain arguments' default values. * signature : Signature The Signature object that created this instance. * args : tuple Tuple of positional arguments values. * kwargs : dict Dict of keyword arguments values. ''' def __init__(self, signature, arguments): self.arguments = arguments self._signature = signature @property def signature(self): return self._signature @property def args(self): args = [] for param_name, param in self._signature.parameters.items(): if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or param._partial_kwarg): # Keyword arguments mapped by 'functools.partial' # (Parameter._partial_kwarg is True) are mapped # in 'BoundArguments.kwargs', along with VAR_KEYWORD & # KEYWORD_ONLY break try: arg = self.arguments[param_name] except KeyError: # We're done here. Other arguments # will be mapped in 'BoundArguments.kwargs' break else: if param.kind == _VAR_POSITIONAL: # *args args.extend(arg) else: # plain argument args.append(arg) return tuple(args) @property def kwargs(self): kwargs = {} kwargs_started = False for param_name, param in self._signature.parameters.items(): if not kwargs_started: if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or param._partial_kwarg): kwargs_started = True else: if param_name not in self.arguments: kwargs_started = True continue if not kwargs_started: continue try: arg = self.arguments[param_name] except KeyError: pass else: if param.kind == _VAR_KEYWORD: # **kwargs kwargs.update(arg) else: # plain keyword argument kwargs[param_name] = arg return kwargs def __eq__(self, other): return (issubclass(other.__class__, BoundArguments) and self.signature == other.signature and self.arguments == other.arguments) def __ne__(self, other): return not self.__eq__(other) class Signature: '''A Signature object represents the overall signature of a function. It stores a Parameter object for each parameter accepted by the function, as well as information specific to the function itself. A Signature object has the following public attributes and methods: * parameters : OrderedDict An ordered mapping of parameters' names to the corresponding Parameter objects (keyword-only arguments are in the same order as listed in `code.co_varnames`). * return_annotation : object The annotation for the return type of the function if specified. If the function has no annotation for its return type, this attribute is not set. * bind(*args, **kwargs) -> BoundArguments Creates a mapping from positional and keyword arguments to parameters. * bind_partial(*args, **kwargs) -> BoundArguments Creates a partial mapping from positional and keyword arguments to parameters (simulating 'functools.partial' behavior.) ''' __slots__ = ('_return_annotation', '_parameters') _parameter_cls = Parameter _bound_arguments_cls = BoundArguments empty = _empty def __init__(self, parameters=None, *, return_annotation=_empty, __validate_parameters__=True): '''Constructs Signature from the given list of Parameter objects and 'return_annotation'. All arguments are optional. ''' if parameters is None: params = OrderedDict() else: if __validate_parameters__: params = OrderedDict() top_kind = _POSITIONAL_ONLY for idx, param in enumerate(parameters): kind = param.kind if kind < top_kind: msg = 'wrong parameter order: {} before {}' msg = msg.format(top_kind, param.kind) raise ValueError(msg) else: top_kind = kind name = param.name if name is None: name = str(idx) param = param.replace(name=name) if name in params: msg = 'duplicate parameter name: {!r}'.format(name) raise ValueError(msg) params[name] = param else: params = OrderedDict(((param.name, param) for param in parameters)) self._parameters = types.MappingProxyType(params) self._return_annotation = return_annotation @classmethod def from_function(cls, func): '''Constructs Signature for the given python function''' if not isinstance(func, types.FunctionType): raise TypeError('{!r} is not a Python function'.format(func)) Parameter = cls._parameter_cls # Parameter information. func_code = func.__code__ pos_count = func_code.co_argcount arg_names = func_code.co_varnames positional = tuple(arg_names[:pos_count]) keyword_only_count = func_code.co_kwonlyargcount keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)] annotations = func.__annotations__ defaults = func.__defaults__ kwdefaults = func.__kwdefaults__ if defaults: pos_default_count = len(defaults) else: pos_default_count = 0 parameters = [] # Non-keyword-only parameters w/o defaults. non_default_count = pos_count - pos_default_count for name in positional[:non_default_count]: annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD)) # ... w/ defaults. for offset, name in enumerate(positional[non_default_count:]): annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD, default=defaults[offset])) # *args if func_code.co_flags & 0x04: name = arg_names[pos_count + keyword_only_count] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_POSITIONAL)) # Keyword-only parameters. for name in keyword_only: default = _empty if kwdefaults is not None: default = kwdefaults.get(name, _empty) annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_KEYWORD_ONLY, default=default)) # **kwargs if func_code.co_flags & 0x08: index = pos_count + keyword_only_count if func_code.co_flags & 0x04: index += 1 name = arg_names[index] annotation = annotations.get(name, _empty) parameters.append(Parameter(name, annotation=annotation, kind=_VAR_KEYWORD)) return cls(parameters, return_annotation=annotations.get('return', _empty), __validate_parameters__=False) @property def parameters(self): return self._parameters @property def return_annotation(self): return self._return_annotation def replace(self, *, parameters=_void, return_annotation=_void): '''Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. ''' if parameters is _void: parameters = self.parameters.values() if return_annotation is _void: return_annotation = self._return_annotation return type(self)(parameters, return_annotation=return_annotation) def __eq__(self, other): if (not issubclass(type(other), Signature) or self.return_annotation != other.return_annotation or len(self.parameters) != len(other.parameters)): return False other_positions = {param: idx for idx, param in enumerate(other.parameters.keys())} for idx, (param_name, param) in enumerate(self.parameters.items()): if param.kind == _KEYWORD_ONLY: try: other_param = other.parameters[param_name] except KeyError: return False else: if param != other_param: return False else: try: other_idx = other_positions[param_name] except KeyError: return False else: if (idx != other_idx or param != other.parameters[param_name]): return False return True def __ne__(self, other): return not self.__eq__(other) def _bind(self, args, kwargs, *, partial=False): '''Private method. Don't use directly.''' arguments = OrderedDict() parameters = iter(self.parameters.values()) parameters_ex = () arg_vals = iter(args) if partial: # Support for binding arguments to 'functools.partial' objects. # See 'functools.partial' case in 'signature()' implementation # for details. for param_name, param in self.parameters.items(): if (param._partial_kwarg and param_name not in kwargs): # Simulating 'functools.partial' behavior kwargs[param_name] = param.default while True: # Let's iterate through the positional arguments and corresponding # parameters try: arg_val = next(arg_vals) except StopIteration: # No more positional arguments try: param = next(parameters) except StopIteration: # No more parameters. That's it. Just need to check that # we have no `kwargs` after this while loop break else: if param.kind == _VAR_POSITIONAL: # That's OK, just empty *args. Let's start parsing # kwargs break elif param.name in kwargs: if param.kind == _POSITIONAL_ONLY: msg = '{arg!r} parameter is positional only, ' \ 'but was passed as a keyword' msg = msg.format(arg=param.name) raise TypeError(msg) from None parameters_ex = (param,) break elif (param.kind == _VAR_KEYWORD or param.default is not _empty): # That's fine too - we have a default value for this # parameter. So, lets start parsing `kwargs`, starting # with the current parameter parameters_ex = (param,) break else: if partial: parameters_ex = (param,) break else: msg = '{arg!r} parameter lacking default value' msg = msg.format(arg=param.name) raise TypeError(msg) from None else: # We have a positional argument to process try: param = next(parameters) except StopIteration: raise TypeError('too many positional arguments') from None else: if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY): # Looks like we have no parameter for this positional # argument raise TypeError('too many positional arguments') if param.kind == _VAR_POSITIONAL: # We have an '*args'-like argument, let's fill it with # all positional arguments we have left and move on to # the next phase values = [arg_val] values.extend(arg_vals) arguments[param.name] = tuple(values) break if param.name in kwargs: raise TypeError('multiple values for argument ' '{arg!r}'.format(arg=param.name)) arguments[param.name] = arg_val # Now, we iterate through the remaining parameters to process # keyword arguments kwargs_param = None for param in itertools.chain(parameters_ex, parameters): if param.kind == _POSITIONAL_ONLY: # This should never happen in case of a properly built # Signature object (but let's have this check here # to ensure correct behaviour just in case) raise TypeError('{arg!r} parameter is positional only, ' 'but was passed as a keyword'. \ format(arg=param.name)) if param.kind == _VAR_KEYWORD: # Memorize that we have a '**kwargs'-like parameter kwargs_param = param continue param_name = param.name try: arg_val = kwargs.pop(param_name) except KeyError: # We have no value for this parameter. It's fine though, # if it has a default value, or it is an '*args'-like # parameter, left alone by the processing of positional # arguments. if (not partial and param.kind != _VAR_POSITIONAL and param.default is _empty): raise TypeError('{arg!r} parameter lacking default value'. \ format(arg=param_name)) from None else: arguments[param_name] = arg_val if kwargs: if kwargs_param is not None: # Process our '**kwargs'-like parameter arguments[kwargs_param.name] = kwargs else: raise TypeError('too many keyword arguments') return self._bound_arguments_cls(self, arguments) def bind(__bind_self, *args, **kwargs): '''Get a BoundArguments object, that maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return __bind_self._bind(args, kwargs) def bind_partial(__bind_self, *args, **kwargs): '''Get a BoundArguments object, that partially maps the passed `args` and `kwargs` to the function's signature. Raises `TypeError` if the passed arguments can not be bound. ''' return __bind_self._bind(args, kwargs, partial=True) def __str__(self): result = [] render_kw_only_separator = True for idx, param in enumerate(self.parameters.values()): formatted = str(param) kind = param.kind if kind == _VAR_POSITIONAL: # OK, we have an '*args'-like parameter, so we won't need # a '*' to separate keyword-only arguments render_kw_only_separator = False elif kind == _KEYWORD_ONLY and render_kw_only_separator: # We have a keyword-only parameter to render and we haven't # rendered an '*args'-like parameter before, so add a '*' # separator to the parameters list ("foo(arg1, *, arg2)" case) result.append('*') # This condition should be only triggered once, so # reset the flag render_kw_only_separator = False result.append(formatted) rendered = '({})'.format(', '.join(result)) if self.return_annotation is not _empty: anno = formatannotation(self.return_annotation) rendered += ' -> {}'.format(anno) return rendered
agpl-3.0
alpgarcia/panels
src/owlwatch/owlwatch.py
1
18230
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2015-2017 Bitergia # # 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, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Authors: # Alberto Pérez García-Plaza <alpgarcia@bitergia.com> # import argparse import json import logging import sys from argparse import RawTextHelpFormatter from colorama import Fore, Style from elasticsearch import Elasticsearch from schema.model import ESMapping from schema.model import Panel DESC_MSG = \ """ _____________________________ ( Who watches the dashboards? ) ( I do. ) ----------------------------- o -._ _.- o (0),(0) ( ) __.._..__Bitergia""" # Logging formats LOG_FORMAT = "[%(asctime)s - %(levelname)s] - %(message)s" DEBUG_LOG_FORMAT = "[%(asctime)s - %(name)s - %(levelname)s] - %(message)s" FORMAT_OK = Fore.GREEN FORMAT_WARN = Fore.YELLOW FORMAT_ERROR = Fore.RED CMP_MAPPING = 'compare-mapping' CMP_PANEL = 'compare-panel' CMP_CSV = 'compare-csv' VERSION = '0.2' def cmp_mapping_panel(es_host, panel_path): """Compares ES mappings to index patterns from a given panel. Compares only those mappings appearing as index patterns in JSON panel file. Returns a dictionary where each 1st level key is an index pattern name. Each of these keys contains a tuple with: {status, correct, missing, distinct, message} being: status 'OK' if all properties in source schema exist in target schema with same values. 'KO' in other case. correct: list of properties that matches. missing: list of properties missing from target schema. distinct: list of properties in both schemas but having with different values. message: a string with additional information. Keyword arguments: es_host -- Elastic Search host to retrieve mappings panel_path -- JSON panel file path """ return cmp_panel_mapping(panel_path, es_host, True) def cmp_panel_mapping(panel_path, es_host, reverse=False): """Compares index patterns from a given panel to the corresponding mappings from a given ES host. Returns a dictionary where each 1st level key is an index pattern name. Each of these keys contains a tuple with: {status, correct, missing, distinct, message} being: status 'OK' if all properties in source schema exist in target schema with same values. 'KO' in other case. correct: list of properties that matches. missing: list of properties missing from target schema. distinct: list of properties in both schemas but having with different values. message: a string with additional information. Keyword arguments: panel_path -- JSON panel file path es_host -- Elastic Search host to retrieve mappings reverse -- use mapping as source schema. """ client = Elasticsearch(es_host, timeout=30) with open(panel_path) as f: panel_json = json.load(f) panel = Panel.from_json(panel_json) result = {} for index_pattern in panel.get_index_patterns().values(): mapping_json = client.indices.get_mapping(index=index_pattern.schema_name) es_mapping = ESMapping.from_json(index_name=index_pattern.schema_name, mapping_json=mapping_json) if reverse: result[index_pattern.schema_name] = es_mapping.compare_properties(index_pattern) else: result[index_pattern.schema_name] = index_pattern.compare_properties(es_mapping) return result def cmp_csv_mapping(csv_path, es_host): """Compares CSV schema definition to a given ES Mapping. Returns a dictionary where each 1st level key is an index pattern name. Each of these keys contains a tuple with: {status, correct, missing, distinct, message} being: status 'OK' if all properties in source schema exist in target schema with same values. 'KO' in other case. correct: list of properties that matches. missing: list of properties missing from target schema. distinct: list of properties in both schemas but having with different values. message: a string with additional information. Keyword arguments: csv_path -- CSV schema definition file path es_host -- Elastic Search host to retrieve mappings """ return cmp_mapping_csv(es_host, csv_path, True) def cmp_mapping_csv(es_host, csv_path, reverse=False): """Compares an ES Mapping to a given CSV schema definition. Returns a dictionary where each 1st level key is an index pattern name. Each of these keys contains a tuple with: {status, correct, missing, distinct, message} being: status 'OK' if all properties in source schema exist in target schema with same values. 'KO' in other case. correct: list of properties that matches. missing: list of properties missing from target schema. distinct: list of properties in both schemas but having with different values. message: a string with additional information. Keyword arguments: es_host -- Elastic Search host to retrieve mappings csv_path -- CSV schema definition file path reverse -- use CSV as source schema. """ # Use file name as index name if '/' in csv_path: schema_name = csv_path[csv_path.rindex('/') + 1:csv_path.rindex('.csv')] else: schema_name = csv_path[:csv_path.rindex('.csv')] csv_mapping = ESMapping.from_csv(index_name=schema_name, csv_file=csv_path) client = Elasticsearch(es_host, timeout=30) mapping_json = client.indices.get_mapping(index=schema_name) es_mapping = ESMapping.from_json(index_name=schema_name, mapping_json=mapping_json) result = {} if reverse: result[schema_name] = csv_mapping.compare_properties(es_mapping) else: result[schema_name] = es_mapping.compare_properties(csv_mapping) return result def cmp_csv_panel(csv_path_list, panel_path): """Compares a list of CSV schema definitions to the corresponding index patterns from a given panel. Compares only those mappings appearing as index patterns in JSON panel file. Returns a dictionary where each 1st level key is an index pattern name. Each of these keys contains a tuple with: {status, correct, missing, distinct, message} being: status 'OK' if all properties in source schema exist in target schema with same values. 'KO' in other case. correct: list of properties that matches. missing: list of properties missing from target schema. distinct: list of properties in both schemas but having with different values. message: a string with additional information. Keyword arguments: csv_path_list -- CSV schema definition file paths panel_path -- JSON panel file path """ return cmp_panel_csv(panel_path, csv_path_list, True) def cmp_panel_csv(panel_path, csv_path_list, reverse=False): """Compares index patterns from a given panel to the corresponding mappings from a given CSV schema definition. Returns a dictionary where each 1st level key is an index pattern name. Each of these keys contains a tuple with: {status, correct, missing, distinct, message} being: status 'OK' if all properties in source schema exist in target schema with same values. 'KO' in other case. correct: list of properties that matches. missing: list of properties missing from target schema. distinct: list of properties in both schemas but having with different values. message: a string with additional information. Keyword arguments: panel_path -- JSON panel file path csv_path_list -- CSV schema definition file paths reverse -- use CSV as source schema. """ with open(panel_path) as f: panel_json = json.load(f) panel = Panel.from_json(panel_json) mappings = {} for csv_path in csv_path_list: # Use file name as index name if '/' in csv_path: schema_name = csv_path[csv_path.rindex('/') + 1:csv_path.rindex('.csv')] else: schema_name = csv_path[:csv_path.rindex('.csv')] mappings[schema_name] = ESMapping.from_csv(index_name=schema_name, csv_file=csv_path) result = {} for index_pattern in panel.get_index_patterns().values(): es_mapping = mappings[index_pattern.schema_name] if reverse: result[index_pattern.schema_name] = es_mapping.compare_properties(index_pattern) else: result[index_pattern.schema_name] = index_pattern.compare_properties(es_mapping) return result def add_mapping_subparser(subparsers): """Adds a subparser for comparing mappings against panels or CSV index definitions""" help_txt = \ """Compares a mapping against panel JSON file or CSV index definition""" parser_cmp = subparsers.add_parser(CMP_MAPPING, help=help_txt) parser_cmp.add_argument('-e', '--elastic-search', dest='es_host', required=True, help='ES host') group_exc = parser_cmp.add_mutually_exclusive_group(required=True) group_exc.add_argument('-p', '--panel-file', dest='panel_path', required=False, help='Panel JSON file path') group_exc.add_argument('-c', '--csv-file', dest='csv_path', required=False, help='Index CSV file path') def add_panel_subparser(subparsers): """Adds a subparser for comparing panels against ES index mapping or CSV index definitions""" help_txt = \ """Compares a panel JSON file against a ES mapping or a CSV index definition""" parser_cmp = subparsers.add_parser(CMP_PANEL, help=help_txt) parser_cmp.add_argument('-p', '--panel-file', dest='panel_path', required=True, help='Panel JSON file path') group_exc = parser_cmp.add_mutually_exclusive_group(required=True) group_exc.add_argument('-e', '--elastic-search', dest='es_host', required=False, help='ES host') group_exc.add_argument('-c', '--csv-file', dest='csv_path_list', action='append', required=False, help='Index CSV file path. Add this ' + 'argument as many times as CSV files you need to ' + ' check.') def add_csv_subparser(subparsers): """Adds a subparser for comparing CSV schema definitions against ES index mapping or panel JSON files""" help_txt = \ """Compares a CSV index definition file against a ES mapping or a JSON panel""" parser_cmp = subparsers.add_parser(CMP_CSV, help=help_txt) parser_cmp.add_argument('-c', '--csv-file', dest='csv_path_list', action='append', required=True, help='Index CSV file path. Add this ' + 'argument as many times as CSV files you need to ' + ' check.') group_exc = parser_cmp.add_mutually_exclusive_group(required=True) group_exc.add_argument('-e', '--elastic-search', dest='es_host', required=False, help='ES host') group_exc.add_argument('-p', '--panel-file', dest='panel_path', required=False, help='Panel JSON file path') def parse_args(): """Parse arguments from the command line""" parser = argparse.ArgumentParser(description=DESC_MSG, formatter_class=RawTextHelpFormatter) group_exc = parser.add_mutually_exclusive_group(required=False) group_exc.add_argument('-g', '--debug', dest='debug', action='store_true') group_exc.add_argument('-l', '--info', dest='info', action='store_true') parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + VERSION) subparsers = parser.add_subparsers(dest='subparser_name') add_mapping_subparser(subparsers) add_panel_subparser(subparsers) add_csv_subparser(subparsers) return parser.parse_args() def configure_logging(info=False, debug=False): """Configure logging The function configures log messages. By default, log messages are sent to stderr. Set the parameter `debug` to activate the debug mode. :param debug: set the debug mode """ if info: logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger('urrlib3').setLevel(logging.WARNING) logging.getLogger('elasticsearch').setLevel(logging.WARNING) elif debug: logging.basicConfig(level=logging.DEBUG, format=DEBUG_LOG_FORMAT) else: logging.basicConfig(level=logging.WARNING, format=LOG_FORMAT) logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger('urrlib3').setLevel(logging.WARNING) logging.getLogger('elasticsearch').setLevel(logging.WARNING) def main(): """This is the Owlcave, where everything starts""" args = parse_args() configure_logging(args.info, args.debug) logging.info("** The Owl is watching **") results = None first = "mapping" second = "panel" if args.subparser_name == CMP_MAPPING: host = args.es_host panel_path = args.panel_path csv_path = args.csv_path logging.info("Compare Mapping from " + host) if csv_path is None: logging.info("Against Panel from " + panel_path) results = cmp_mapping_panel(es_host=host, panel_path=panel_path) elif panel_path is None: logging.info("Against CSV from " + csv_path) second = "csv" results = cmp_mapping_csv(es_host=host, csv_path=csv_path) elif args.subparser_name == CMP_PANEL: first = "panel" host = args.es_host panel_path = args.panel_path csv_path_list = args.csv_path_list logging.info("Compare Panel from " + panel_path) if host is None: logging.info("Against CSVs from " + str(csv_path_list)) second = "csv" results = cmp_panel_csv(panel_path=panel_path, csv_path_list=csv_path_list) elif csv_path_list is None: logging.info("Against Mappings from " + host) second = "mapping" results = cmp_panel_mapping(panel_path=panel_path, es_host=host) elif args.subparser_name == CMP_CSV: first = "csv" host = args.es_host panel_path = args.panel_path csv_path_list = args.csv_path_list logging.info("Compare CSVs from " + str(csv_path_list)) if host is None: logging.info("Against Panel from " + panel_path) second = "panel" results = cmp_csv_panel(csv_path_list=csv_path_list, panel_path=panel_path) elif panel_path is None: logging.info("Against Mappings from " + host) second = "mapping" results = {} for csv_path in csv_path_list: index_name, result = cmp_csv_mapping(csv_path=csv_path, es_host=host).popitem() results[index_name] = result if results is not None: for index_name, result in results.items(): status = result['status'] correct = result['correct'] missing = result['missing'] distinct = result['distinct'] msg = result['msg'] result_format = FORMAT_OK if status == 'OK': logging.info("Matches: " + str(correct)) logging.info("Result: " + status) else: result_format = FORMAT_ERROR logging.info(msg + "\nResult: " + status) print("-" * (len(index_name) + 4)) print("* " + index_name + " *") print("-" * (len(index_name) + 4)) print(first + " Vs. " + second) print("Comparison result: " + result_format + status + Style.RESET_ALL) print("Matches:", len(correct)) print("Not found in " + second + ": ", len(missing)) print("Type mismatches: ", len(distinct)) if msg != "": print("Details: \n" + msg + '\n') else: logging.info("Didn't find anything to do...") logging.info("This is the end.") if __name__ == '__main__': try: main() except KeyboardInterrupt: s = "\n\nReceived Ctrl-C or other break signal. Exiting.\n" sys.stdout.write(s) sys.exit(0) except RuntimeError as e: s = "Error: %s\n" % str(e) sys.stderr.write(s) sys.exit(1)
gpl-3.0
Endika/account-payment
account_due_list/__openerp__.py
2
1800
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2011 Domsense srl (<http://www.domsense.com>) # Copyright (C) 2011-2013 Agile Business Group sagl # (<http://www.agilebg.com>) # @author Jordi Esteve <jesteve@zikzakmedia.com> # @author Lorenzo Battistini <lorenzo.battistini@agilebg.com> # Ported to OpenERP 7.0 by Alex Comba <alex.comba@agilebg.com> and # Bruno Bottacini <bruno.bottacini@dorella.com> # Ported to Odoo by Andrea Cometa <info@andreacometa.it> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': "Payments Due list", 'version': '8.0.0.2.0', 'category': 'Generic Modules/Payment', 'author': 'Odoo Community Association (OCA), ' 'Agile Business Group, ' 'Serv. Tecnol. Avanzados - Pedro M. Baeza,' 'Zikzakmedia SL', 'website': 'http://www.agilebg.com', 'license': 'AGPL-3', "depends": [ 'account', ], "data": [ 'views/payment_view.xml', ], "installable": True, }
agpl-3.0
kuriositeetti/wamp-tikki
venv/lib/python2.7/site-packages/pip/_vendor/requests/structures.py
1160
2977
# -*- coding: utf-8 -*- """ requests.structures ~~~~~~~~~~~~~~~~~~~ Data structures that power Requests. """ import collections class CaseInsensitiveDict(collections.MutableMapping): """ A case-insensitive ``dict``-like object. Implements all methods and operations of ``collections.MutableMapping`` as well as dict's ``copy``. Also provides ``lower_items``. All keys are expected to be strings. The structure remembers the case of the last key to be set, and ``iter(instance)``, ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` will contain case-sensitive keys. However, querying and contains testing is case insensitive:: cid = CaseInsensitiveDict() cid['Accept'] = 'application/json' cid['aCCEPT'] == 'application/json' # True list(cid) == ['Accept'] # True For example, ``headers['content-encoding']`` will return the value of a ``'Content-Encoding'`` response header, regardless of how the header name was originally stored. If the constructor, ``.update``, or equality comparison operations are given keys that have equal ``.lower()``s, the behavior is undefined. """ def __init__(self, data=None, **kwargs): self._store = dict() if data is None: data = {} self.update(data, **kwargs) def __setitem__(self, key, value): # Use the lowercased key for lookups, but store the actual # key alongside the value. self._store[key.lower()] = (key, value) def __getitem__(self, key): return self._store[key.lower()][1] def __delitem__(self, key): del self._store[key.lower()] def __iter__(self): return (casedkey for casedkey, mappedvalue in self._store.values()) def __len__(self): return len(self._store) def lower_items(self): """Like iteritems(), but with all lowercase keys.""" return ( (lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items() ) def __eq__(self, other): if isinstance(other, collections.Mapping): other = CaseInsensitiveDict(other) else: return NotImplemented # Compare insensitively return dict(self.lower_items()) == dict(other.lower_items()) # Copy is required def copy(self): return CaseInsensitiveDict(self._store.values()) def __repr__(self): return str(dict(self.items())) class LookupDict(dict): """Dictionary lookup object.""" def __init__(self, name=None): self.name = name super(LookupDict, self).__init__() def __repr__(self): return '<lookup \'%s\'>' % (self.name) def __getitem__(self, key): # We allow fall-through here, so values default to None return self.__dict__.get(key, None) def get(self, key, default=None): return self.__dict__.get(key, default)
mit
spoqa/protobuf-v120
python/google/protobuf/internal/descriptor_database_test.py
73
2924
#! /usr/bin/python # # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # 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. """Tests for google.protobuf.descriptor_database.""" __author__ = 'matthewtoia@google.com (Matt Toia)' from google.apputils import basetest from google.protobuf import descriptor_pb2 from google.protobuf.internal import factory_test2_pb2 from google.protobuf import descriptor_database class DescriptorDatabaseTest(basetest.TestCase): def testAdd(self): db = descriptor_database.DescriptorDatabase() file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( factory_test2_pb2.DESCRIPTOR.serialized_pb) db.Add(file_desc_proto) self.assertEquals(file_desc_proto, db.FindFileByName( 'google/protobuf/internal/factory_test2.proto')) self.assertEquals(file_desc_proto, db.FindFileContainingSymbol( 'google.protobuf.python.internal.Factory2Message')) self.assertEquals(file_desc_proto, db.FindFileContainingSymbol( 'google.protobuf.python.internal.Factory2Message.NestedFactory2Message')) self.assertEquals(file_desc_proto, db.FindFileContainingSymbol( 'google.protobuf.python.internal.Factory2Enum')) self.assertEquals(file_desc_proto, db.FindFileContainingSymbol( 'google.protobuf.python.internal.Factory2Message.NestedFactory2Enum')) if __name__ == '__main__': basetest.main()
bsd-3-clause
un33k/robotframework
utest/reporting/test_stringcache.py
26
2601
import time import random import string import unittest import sys from robot.reporting.stringcache import StringCache, StringIndex from robot.utils.asserts import assert_equals, assert_true, assert_false class TestStringCache(unittest.TestCase): def setUp(self): # To make test reproducable log the random seed if test fails self._seed = long(time.time() * 256) random.seed(self._seed) self.cache = StringCache() def _verify_text(self, string, expected): self.cache.add(string) assert_equals(('*', expected), self.cache.dump()) def _compress(self, text): return self.cache._encode(text) def test_short_test_is_not_compressed(self): self._verify_text('short', '*short') def test_long_test_is_compressed(self): long_string = 'long'*1000 self._verify_text(long_string, self._compress(long_string)) def test_coded_string_is_at_most_1_characters_longer_than_raw(self): for i in range(300): id = self.cache.add(self._generate_random_string(i)) assert_true(i+1 >= len(self.cache.dump()[id]), 'len(self._text_cache.dump()[id]) (%s) > i+1 (%s) [test seed = %s]' % (len(self.cache.dump()[id]), i+1, self._seed)) def test_long_random_strings_are_compressed(self): for i in range(30): value = self._generate_random_string(300) id = self.cache.add(value) assert_equals(self._compress(value), self.cache.dump()[id], msg='Did not compress [test seed = %s]' % self._seed) def _generate_random_string(self, length): return ''.join(random.choice(string.digits) for _ in range(length)) def test_indices_reused_instances(self): strings = ['', 'short', 'long'*1000, ''] indices1 = [self.cache.add(s) for s in strings] indices2 = [self.cache.add(s) for s in strings] for i1, i2 in zip(indices1, indices2): assert_true(i1 is i2, 'not same: %s and %s' % (i1, i2)) class TestStringIndex(unittest.TestCase): def test_to_string(self): value = StringIndex(42) assert_equals(str(value), '42') def test_long_values(self): target = sys.maxint + 42 value = StringIndex(target) assert_equals(str(value), str(target)) assert_false(str(value).endswith('L')) def test_truth(self): assert_true(StringIndex(1)) assert_true(StringIndex(-42)) assert_false(StringIndex(0)) if __name__ == '__main__': unittest.main()
apache-2.0
eceglov/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/style/checkers/png_unittest.py
124
5663
# Copyright (C) 2012 Balazs Ankes (bank@inf.u-szeged.hu) University of Szeged # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 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. """Unit test for png.py.""" import unittest2 as unittest from png import PNGChecker from webkitpy.common.system.filesystem_mock import MockFileSystem from webkitpy.common.system.systemhost_mock import MockSystemHost class MockSCMDetector(object): def __init__(self, scm, prop=None): self._scm = scm self._prop = prop def display_name(self): return self._scm def propget(self, pname, path): return self._prop class PNGCheckerTest(unittest.TestCase): """Tests PNGChecker class.""" def test_init(self): """Test __init__() method.""" def mock_handle_style_error(self): pass checker = PNGChecker("test/config", mock_handle_style_error, MockSCMDetector('git'), MockSystemHost()) self.assertEqual(checker._file_path, "test/config") self.assertEqual(checker._handle_style_error, mock_handle_style_error) def test_check(self): errors = [] def mock_handle_style_error(line_number, category, confidence, message): error = (line_number, category, confidence, message) errors.append(error) file_path = '' fs = MockFileSystem() scm = MockSCMDetector('svn') checker = PNGChecker(file_path, mock_handle_style_error, scm, MockSystemHost(filesystem=fs)) checker.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0], (0, 'image/png', 5, 'Set the svn:mime-type property (svn propset svn:mime-type image/png ).')) files = {'/Users/mock/.subversion/config': 'enable-auto-props = yes\n*.png = svn:mime-type=image/png'} fs = MockFileSystem(files) scm = MockSCMDetector('git') errors = [] checker = PNGChecker("config", mock_handle_style_error, scm, MockSystemHost(os_name='linux', filesystem=fs)) checker.check() self.assertEqual(len(errors), 0) files = {'/Users/mock/.subversion/config': '#enable-auto-props = yes'} fs = MockFileSystem(files) scm = MockSCMDetector('git') errors = [] checker = PNGChecker("config", mock_handle_style_error, scm, MockSystemHost(os_name='linux', filesystem=fs)) checker.check() self.assertEqual(len(errors), 1) files = {'/Users/mock/.subversion/config': 'enable-auto-props = yes\n#enable-auto-props = yes\n*.png = svn:mime-type=image/png'} fs = MockFileSystem(files) scm = MockSCMDetector('git') errors = [] checker = PNGChecker("config", mock_handle_style_error, scm, MockSystemHost(os_name='linux', filesystem=fs)) checker.check() self.assertEqual(len(errors), 0) files = {'/Users/mock/.subversion/config': '#enable-auto-props = yes\nenable-auto-props = yes\n*.png = svn:mime-type=image/png'} fs = MockFileSystem(files) scm = MockSCMDetector('git') errors = [] checker = PNGChecker("config", mock_handle_style_error, scm, MockSystemHost(os_name='linux', filesystem=fs)) checker.check() self.assertEqual(len(errors), 0) files = {'/Users/mock/.subversion/config': 'enable-auto-props = no'} fs = MockFileSystem(files) scm = MockSCMDetector('git') errors = [] checker = PNGChecker("config", mock_handle_style_error, scm, MockSystemHost(os_name='linux', filesystem=fs)) checker.check() self.assertEqual(len(errors), 1) file_path = "foo.png" fs.write_binary_file(file_path, "Dummy binary data") scm = MockSCMDetector('git') errors = [] checker = PNGChecker(file_path, mock_handle_style_error, scm, MockSystemHost(os_name='linux', filesystem=fs)) checker.check() self.assertEqual(len(errors), 1) file_path = "foo-expected.png" fs.write_binary_file(file_path, "Dummy binary data") scm = MockSCMDetector('git') errors = [] checker = PNGChecker(file_path, mock_handle_style_error, scm, MockSystemHost(os_name='linux', filesystem=fs)) checker.check() self.assertEqual(len(errors), 2) self.assertEqual(errors[0], (0, 'image/png', 5, 'Image lacks a checksum. Generate pngs using run-webkit-tests to ensure they have a checksum.'))
bsd-3-clause
BassantMorsi/finderApp
lib/python2.7/site-packages/numpy/distutils/command/build_src.py
28
30933
""" Build swig and f2py sources. """ from __future__ import division, absolute_import, print_function import os import re import sys import shlex import copy from distutils.command import build_ext from distutils.dep_util import newer_group, newer from distutils.util import get_platform from distutils.errors import DistutilsError, DistutilsSetupError # this import can't be done here, as it uses numpy stuff only available # after it's installed #import numpy.f2py from numpy.distutils import log from numpy.distutils.misc_util import ( fortran_ext_match, appendpath, is_string, is_sequence, get_cmd ) from numpy.distutils.from_template import process_file as process_f_file from numpy.distutils.conv_template import process_file as process_c_file def subst_vars(target, source, d): """Substitute any occurrence of @foo@ by d['foo'] from source file into target.""" var = re.compile('@([a-zA-Z_]+)@') fs = open(source, 'r') try: ft = open(target, 'w') try: for l in fs: m = var.search(l) if m: ft.write(l.replace('@%s@' % m.group(1), d[m.group(1)])) else: ft.write(l) finally: ft.close() finally: fs.close() class build_src(build_ext.build_ext): description = "build sources from SWIG, F2PY files or a function" user_options = [ ('build-src=', 'd', "directory to \"build\" sources to"), ('f2py-opts=', None, "list of f2py command line options"), ('swig=', None, "path to the SWIG executable"), ('swig-opts=', None, "list of SWIG command line options"), ('swig-cpp', None, "make SWIG create C++ files (default is autodetected from sources)"), ('f2pyflags=', None, "additional flags to f2py (use --f2py-opts= instead)"), # obsolete ('swigflags=', None, "additional flags to swig (use --swig-opts= instead)"), # obsolete ('force', 'f', "forcibly build everything (ignore file timestamps)"), ('inplace', 'i', "ignore build-lib and put compiled extensions into the source " + "directory alongside your pure Python modules"), ] boolean_options = ['force', 'inplace'] help_options = [] def initialize_options(self): self.extensions = None self.package = None self.py_modules = None self.py_modules_dict = None self.build_src = None self.build_lib = None self.build_base = None self.force = None self.inplace = None self.package_dir = None self.f2pyflags = None # obsolete self.f2py_opts = None self.swigflags = None # obsolete self.swig_opts = None self.swig_cpp = None self.swig = None def finalize_options(self): self.set_undefined_options('build', ('build_base', 'build_base'), ('build_lib', 'build_lib'), ('force', 'force')) if self.package is None: self.package = self.distribution.ext_package self.extensions = self.distribution.ext_modules self.libraries = self.distribution.libraries or [] self.py_modules = self.distribution.py_modules or [] self.data_files = self.distribution.data_files or [] if self.build_src is None: plat_specifier = ".%s-%s" % (get_platform(), sys.version[0:3]) self.build_src = os.path.join(self.build_base, 'src'+plat_specifier) # py_modules_dict is used in build_py.find_package_modules self.py_modules_dict = {} if self.f2pyflags: if self.f2py_opts: log.warn('ignoring --f2pyflags as --f2py-opts already used') else: self.f2py_opts = self.f2pyflags self.f2pyflags = None if self.f2py_opts is None: self.f2py_opts = [] else: self.f2py_opts = shlex.split(self.f2py_opts) if self.swigflags: if self.swig_opts: log.warn('ignoring --swigflags as --swig-opts already used') else: self.swig_opts = self.swigflags self.swigflags = None if self.swig_opts is None: self.swig_opts = [] else: self.swig_opts = shlex.split(self.swig_opts) # use options from build_ext command build_ext = self.get_finalized_command('build_ext') if self.inplace is None: self.inplace = build_ext.inplace if self.swig_cpp is None: self.swig_cpp = build_ext.swig_cpp for c in ['swig', 'swig_opt']: o = '--'+c.replace('_', '-') v = getattr(build_ext, c, None) if v: if getattr(self, c): log.warn('both build_src and build_ext define %s option' % (o)) else: log.info('using "%s=%s" option from build_ext command' % (o, v)) setattr(self, c, v) def run(self): log.info("build_src") if not (self.extensions or self.libraries): return self.build_sources() def build_sources(self): if self.inplace: self.get_package_dir = \ self.get_finalized_command('build_py').get_package_dir self.build_py_modules_sources() for libname_info in self.libraries: self.build_library_sources(*libname_info) if self.extensions: self.check_extensions_list(self.extensions) for ext in self.extensions: self.build_extension_sources(ext) self.build_data_files_sources() self.build_npy_pkg_config() def build_data_files_sources(self): if not self.data_files: return log.info('building data_files sources') from numpy.distutils.misc_util import get_data_files new_data_files = [] for data in self.data_files: if isinstance(data, str): new_data_files.append(data) elif isinstance(data, tuple): d, files = data if self.inplace: build_dir = self.get_package_dir('.'.join(d.split(os.sep))) else: build_dir = os.path.join(self.build_src, d) funcs = [f for f in files if hasattr(f, '__call__')] files = [f for f in files if not hasattr(f, '__call__')] for f in funcs: if f.__code__.co_argcount==1: s = f(build_dir) else: s = f() if s is not None: if isinstance(s, list): files.extend(s) elif isinstance(s, str): files.append(s) else: raise TypeError(repr(s)) filenames = get_data_files((d, files)) new_data_files.append((d, filenames)) else: raise TypeError(repr(data)) self.data_files[:] = new_data_files def _build_npy_pkg_config(self, info, gd): import shutil template, install_dir, subst_dict = info template_dir = os.path.dirname(template) for k, v in gd.items(): subst_dict[k] = v if self.inplace == 1: generated_dir = os.path.join(template_dir, install_dir) else: generated_dir = os.path.join(self.build_src, template_dir, install_dir) generated = os.path.basename(os.path.splitext(template)[0]) generated_path = os.path.join(generated_dir, generated) if not os.path.exists(generated_dir): os.makedirs(generated_dir) subst_vars(generated_path, template, subst_dict) # Where to install relatively to install prefix full_install_dir = os.path.join(template_dir, install_dir) return full_install_dir, generated_path def build_npy_pkg_config(self): log.info('build_src: building npy-pkg config files') # XXX: another ugly workaround to circumvent distutils brain damage. We # need the install prefix here, but finalizing the options of the # install command when only building sources cause error. Instead, we # copy the install command instance, and finalize the copy so that it # does not disrupt how distutils want to do things when with the # original install command instance. install_cmd = copy.copy(get_cmd('install')) if not install_cmd.finalized == 1: install_cmd.finalize_options() build_npkg = False gd = {} if self.inplace == 1: top_prefix = '.' build_npkg = True elif hasattr(install_cmd, 'install_libbase'): top_prefix = install_cmd.install_libbase build_npkg = True if build_npkg: for pkg, infos in self.distribution.installed_pkg_config.items(): pkg_path = self.distribution.package_dir[pkg] prefix = os.path.join(os.path.abspath(top_prefix), pkg_path) d = {'prefix': prefix} for info in infos: install_dir, generated = self._build_npy_pkg_config(info, d) self.distribution.data_files.append((install_dir, [generated])) def build_py_modules_sources(self): if not self.py_modules: return log.info('building py_modules sources') new_py_modules = [] for source in self.py_modules: if is_sequence(source) and len(source)==3: package, module_base, source = source if self.inplace: build_dir = self.get_package_dir(package) else: build_dir = os.path.join(self.build_src, os.path.join(*package.split('.'))) if hasattr(source, '__call__'): target = os.path.join(build_dir, module_base + '.py') source = source(target) if source is None: continue modules = [(package, module_base, source)] if package not in self.py_modules_dict: self.py_modules_dict[package] = [] self.py_modules_dict[package] += modules else: new_py_modules.append(source) self.py_modules[:] = new_py_modules def build_library_sources(self, lib_name, build_info): sources = list(build_info.get('sources', [])) if not sources: return log.info('building library "%s" sources' % (lib_name)) sources = self.generate_sources(sources, (lib_name, build_info)) sources = self.template_sources(sources, (lib_name, build_info)) sources, h_files = self.filter_h_files(sources) if h_files: log.info('%s - nothing done with h_files = %s', self.package, h_files) #for f in h_files: # self.distribution.headers.append((lib_name,f)) build_info['sources'] = sources return def build_extension_sources(self, ext): sources = list(ext.sources) log.info('building extension "%s" sources' % (ext.name)) fullname = self.get_ext_fullname(ext.name) modpath = fullname.split('.') package = '.'.join(modpath[0:-1]) if self.inplace: self.ext_target_dir = self.get_package_dir(package) sources = self.generate_sources(sources, ext) sources = self.template_sources(sources, ext) sources = self.swig_sources(sources, ext) sources = self.f2py_sources(sources, ext) sources = self.pyrex_sources(sources, ext) sources, py_files = self.filter_py_files(sources) if package not in self.py_modules_dict: self.py_modules_dict[package] = [] modules = [] for f in py_files: module = os.path.splitext(os.path.basename(f))[0] modules.append((package, module, f)) self.py_modules_dict[package] += modules sources, h_files = self.filter_h_files(sources) if h_files: log.info('%s - nothing done with h_files = %s', package, h_files) #for f in h_files: # self.distribution.headers.append((package,f)) ext.sources = sources def generate_sources(self, sources, extension): new_sources = [] func_sources = [] for source in sources: if is_string(source): new_sources.append(source) else: func_sources.append(source) if not func_sources: return new_sources if self.inplace and not is_sequence(extension): build_dir = self.ext_target_dir else: if is_sequence(extension): name = extension[0] # if 'include_dirs' not in extension[1]: # extension[1]['include_dirs'] = [] # incl_dirs = extension[1]['include_dirs'] else: name = extension.name # incl_dirs = extension.include_dirs #if self.build_src not in incl_dirs: # incl_dirs.append(self.build_src) build_dir = os.path.join(*([self.build_src]\ +name.split('.')[:-1])) self.mkpath(build_dir) for func in func_sources: source = func(extension, build_dir) if not source: continue if is_sequence(source): [log.info(" adding '%s' to sources." % (s,)) for s in source] new_sources.extend(source) else: log.info(" adding '%s' to sources." % (source,)) new_sources.append(source) return new_sources def filter_py_files(self, sources): return self.filter_files(sources, ['.py']) def filter_h_files(self, sources): return self.filter_files(sources, ['.h', '.hpp', '.inc']) def filter_files(self, sources, exts = []): new_sources = [] files = [] for source in sources: (base, ext) = os.path.splitext(source) if ext in exts: files.append(source) else: new_sources.append(source) return new_sources, files def template_sources(self, sources, extension): new_sources = [] if is_sequence(extension): depends = extension[1].get('depends') include_dirs = extension[1].get('include_dirs') else: depends = extension.depends include_dirs = extension.include_dirs for source in sources: (base, ext) = os.path.splitext(source) if ext == '.src': # Template file if self.inplace: target_dir = os.path.dirname(base) else: target_dir = appendpath(self.build_src, os.path.dirname(base)) self.mkpath(target_dir) target_file = os.path.join(target_dir, os.path.basename(base)) if (self.force or newer_group([source] + depends, target_file)): if _f_pyf_ext_match(base): log.info("from_template:> %s" % (target_file)) outstr = process_f_file(source) else: log.info("conv_template:> %s" % (target_file)) outstr = process_c_file(source) fid = open(target_file, 'w') fid.write(outstr) fid.close() if _header_ext_match(target_file): d = os.path.dirname(target_file) if d not in include_dirs: log.info(" adding '%s' to include_dirs." % (d)) include_dirs.append(d) new_sources.append(target_file) else: new_sources.append(source) return new_sources def pyrex_sources(self, sources, extension): """Pyrex not supported; this remains for Cython support (see below)""" new_sources = [] ext_name = extension.name.split('.')[-1] for source in sources: (base, ext) = os.path.splitext(source) if ext == '.pyx': target_file = self.generate_a_pyrex_source(base, ext_name, source, extension) new_sources.append(target_file) else: new_sources.append(source) return new_sources def generate_a_pyrex_source(self, base, ext_name, source, extension): """Pyrex is not supported, but some projects monkeypatch this method. That allows compiling Cython code, see gh-6955. This method will remain here for compatibility reasons. """ return [] def f2py_sources(self, sources, extension): new_sources = [] f2py_sources = [] f_sources = [] f2py_targets = {} target_dirs = [] ext_name = extension.name.split('.')[-1] skip_f2py = 0 for source in sources: (base, ext) = os.path.splitext(source) if ext == '.pyf': # F2PY interface file if self.inplace: target_dir = os.path.dirname(base) else: target_dir = appendpath(self.build_src, os.path.dirname(base)) if os.path.isfile(source): name = get_f2py_modulename(source) if name != ext_name: raise DistutilsSetupError('mismatch of extension names: %s ' 'provides %r but expected %r' % ( source, name, ext_name)) target_file = os.path.join(target_dir, name+'module.c') else: log.debug(' source %s does not exist: skipping f2py\'ing.' \ % (source)) name = ext_name skip_f2py = 1 target_file = os.path.join(target_dir, name+'module.c') if not os.path.isfile(target_file): log.warn(' target %s does not exist:\n '\ 'Assuming %smodule.c was generated with '\ '"build_src --inplace" command.' \ % (target_file, name)) target_dir = os.path.dirname(base) target_file = os.path.join(target_dir, name+'module.c') if not os.path.isfile(target_file): raise DistutilsSetupError("%r missing" % (target_file,)) log.info(' Yes! Using %r as up-to-date target.' \ % (target_file)) target_dirs.append(target_dir) f2py_sources.append(source) f2py_targets[source] = target_file new_sources.append(target_file) elif fortran_ext_match(ext): f_sources.append(source) else: new_sources.append(source) if not (f2py_sources or f_sources): return new_sources for d in target_dirs: self.mkpath(d) f2py_options = extension.f2py_options + self.f2py_opts if self.distribution.libraries: for name, build_info in self.distribution.libraries: if name in extension.libraries: f2py_options.extend(build_info.get('f2py_options', [])) log.info("f2py options: %s" % (f2py_options)) if f2py_sources: if len(f2py_sources) != 1: raise DistutilsSetupError( 'only one .pyf file is allowed per extension module but got'\ ' more: %r' % (f2py_sources,)) source = f2py_sources[0] target_file = f2py_targets[source] target_dir = os.path.dirname(target_file) or '.' depends = [source] + extension.depends if (self.force or newer_group(depends, target_file, 'newer')) \ and not skip_f2py: log.info("f2py: %s" % (source)) import numpy.f2py numpy.f2py.run_main(f2py_options + ['--build-dir', target_dir, source]) else: log.debug(" skipping '%s' f2py interface (up-to-date)" % (source)) else: #XXX TODO: --inplace support for sdist command if is_sequence(extension): name = extension[0] else: name = extension.name target_dir = os.path.join(*([self.build_src]\ +name.split('.')[:-1])) target_file = os.path.join(target_dir, ext_name + 'module.c') new_sources.append(target_file) depends = f_sources + extension.depends if (self.force or newer_group(depends, target_file, 'newer')) \ and not skip_f2py: log.info("f2py:> %s" % (target_file)) self.mkpath(target_dir) import numpy.f2py numpy.f2py.run_main(f2py_options + ['--lower', '--build-dir', target_dir]+\ ['-m', ext_name]+f_sources) else: log.debug(" skipping f2py fortran files for '%s' (up-to-date)"\ % (target_file)) if not os.path.isfile(target_file): raise DistutilsError("f2py target file %r not generated" % (target_file,)) target_c = os.path.join(self.build_src, 'fortranobject.c') target_h = os.path.join(self.build_src, 'fortranobject.h') log.info(" adding '%s' to sources." % (target_c)) new_sources.append(target_c) if self.build_src not in extension.include_dirs: log.info(" adding '%s' to include_dirs." \ % (self.build_src)) extension.include_dirs.append(self.build_src) if not skip_f2py: import numpy.f2py d = os.path.dirname(numpy.f2py.__file__) source_c = os.path.join(d, 'src', 'fortranobject.c') source_h = os.path.join(d, 'src', 'fortranobject.h') if newer(source_c, target_c) or newer(source_h, target_h): self.mkpath(os.path.dirname(target_c)) self.copy_file(source_c, target_c) self.copy_file(source_h, target_h) else: if not os.path.isfile(target_c): raise DistutilsSetupError("f2py target_c file %r not found" % (target_c,)) if not os.path.isfile(target_h): raise DistutilsSetupError("f2py target_h file %r not found" % (target_h,)) for name_ext in ['-f2pywrappers.f', '-f2pywrappers2.f90']: filename = os.path.join(target_dir, ext_name + name_ext) if os.path.isfile(filename): log.info(" adding '%s' to sources." % (filename)) f_sources.append(filename) return new_sources + f_sources def swig_sources(self, sources, extension): # Assuming SWIG 1.3.14 or later. See compatibility note in # http://www.swig.org/Doc1.3/Python.html#Python_nn6 new_sources = [] swig_sources = [] swig_targets = {} target_dirs = [] py_files = [] # swig generated .py files target_ext = '.c' if '-c++' in extension.swig_opts: typ = 'c++' is_cpp = True extension.swig_opts.remove('-c++') elif self.swig_cpp: typ = 'c++' is_cpp = True else: typ = None is_cpp = False skip_swig = 0 ext_name = extension.name.split('.')[-1] for source in sources: (base, ext) = os.path.splitext(source) if ext == '.i': # SWIG interface file # the code below assumes that the sources list # contains not more than one .i SWIG interface file if self.inplace: target_dir = os.path.dirname(base) py_target_dir = self.ext_target_dir else: target_dir = appendpath(self.build_src, os.path.dirname(base)) py_target_dir = target_dir if os.path.isfile(source): name = get_swig_modulename(source) if name != ext_name[1:]: raise DistutilsSetupError( 'mismatch of extension names: %s provides %r' ' but expected %r' % (source, name, ext_name[1:])) if typ is None: typ = get_swig_target(source) is_cpp = typ=='c++' else: typ2 = get_swig_target(source) if typ2 is None: log.warn('source %r does not define swig target, assuming %s swig target' \ % (source, typ)) elif typ!=typ2: log.warn('expected %r but source %r defines %r swig target' \ % (typ, source, typ2)) if typ2=='c++': log.warn('resetting swig target to c++ (some targets may have .c extension)') is_cpp = True else: log.warn('assuming that %r has c++ swig target' % (source)) if is_cpp: target_ext = '.cpp' target_file = os.path.join(target_dir, '%s_wrap%s' \ % (name, target_ext)) else: log.warn(' source %s does not exist: skipping swig\'ing.' \ % (source)) name = ext_name[1:] skip_swig = 1 target_file = _find_swig_target(target_dir, name) if not os.path.isfile(target_file): log.warn(' target %s does not exist:\n '\ 'Assuming %s_wrap.{c,cpp} was generated with '\ '"build_src --inplace" command.' \ % (target_file, name)) target_dir = os.path.dirname(base) target_file = _find_swig_target(target_dir, name) if not os.path.isfile(target_file): raise DistutilsSetupError("%r missing" % (target_file,)) log.warn(' Yes! Using %r as up-to-date target.' \ % (target_file)) target_dirs.append(target_dir) new_sources.append(target_file) py_files.append(os.path.join(py_target_dir, name+'.py')) swig_sources.append(source) swig_targets[source] = new_sources[-1] else: new_sources.append(source) if not swig_sources: return new_sources if skip_swig: return new_sources + py_files for d in target_dirs: self.mkpath(d) swig = self.swig or self.find_swig() swig_cmd = [swig, "-python"] + extension.swig_opts if is_cpp: swig_cmd.append('-c++') for d in extension.include_dirs: swig_cmd.append('-I'+d) for source in swig_sources: target = swig_targets[source] depends = [source] + extension.depends if self.force or newer_group(depends, target, 'newer'): log.info("%s: %s" % (os.path.basename(swig) \ + (is_cpp and '++' or ''), source)) self.spawn(swig_cmd + self.swig_opts \ + ["-o", target, '-outdir', py_target_dir, source]) else: log.debug(" skipping '%s' swig interface (up-to-date)" \ % (source)) return new_sources + py_files _f_pyf_ext_match = re.compile(r'.*[.](f90|f95|f77|for|ftn|f|pyf)\Z', re.I).match _header_ext_match = re.compile(r'.*[.](inc|h|hpp)\Z', re.I).match #### SWIG related auxiliary functions #### _swig_module_name_match = re.compile(r'\s*%module\s*(.*\(\s*package\s*=\s*"(?P<package>[\w_]+)".*\)|)\s*(?P<name>[\w_]+)', re.I).match _has_c_header = re.compile(r'-[*]-\s*c\s*-[*]-', re.I).search _has_cpp_header = re.compile(r'-[*]-\s*c[+][+]\s*-[*]-', re.I).search def get_swig_target(source): f = open(source, 'r') result = None line = f.readline() if _has_cpp_header(line): result = 'c++' if _has_c_header(line): result = 'c' f.close() return result def get_swig_modulename(source): f = open(source, 'r') name = None for line in f: m = _swig_module_name_match(line) if m: name = m.group('name') break f.close() return name def _find_swig_target(target_dir, name): for ext in ['.cpp', '.c']: target = os.path.join(target_dir, '%s_wrap%s' % (name, ext)) if os.path.isfile(target): break return target #### F2PY related auxiliary functions #### _f2py_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]+)', re.I).match _f2py_user_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]*?' r'__user__[\w_]*)', re.I).match def get_f2py_modulename(source): name = None f = open(source) for line in f: m = _f2py_module_name_match(line) if m: if _f2py_user_module_name_match(line): # skip *__user__* names continue name = m.group('name') break f.close() return name ##########################################
mit
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2016_09_01/aio/operations/_virtual_network_gateway_connections_operations.py
1
39335
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class VirtualNetworkGatewayConnectionsOperations: """VirtualNetworkGatewayConnectionsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2016_09_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def _create_or_update_initial( self, resource_group_name: str, virtual_network_gateway_connection_name: str, parameters: "_models.VirtualNetworkGatewayConnection", **kwargs ) -> "_models.VirtualNetworkGatewayConnection": cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkGatewayConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json, text/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'VirtualNetworkGatewayConnection') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('VirtualNetworkGatewayConnection', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('VirtualNetworkGatewayConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, virtual_network_gateway_connection_name: str, parameters: "_models.VirtualNetworkGatewayConnection", **kwargs ) -> AsyncLROPoller["_models.VirtualNetworkGatewayConnection"]: """Creates or updates a virtual network gateway connection in the specified resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_network_gateway_connection_name: The name of the virtual network gateway connection. :type virtual_network_gateway_connection_name: str :param parameters: Parameters supplied to the create or update virtual network gateway connection operation. :type parameters: ~azure.mgmt.network.v2016_09_01.models.VirtualNetworkGatewayConnection :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either VirtualNetworkGatewayConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2016_09_01.models.VirtualNetworkGatewayConnection] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkGatewayConnection"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, virtual_network_gateway_connection_name=virtual_network_gateway_connection_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('VirtualNetworkGatewayConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}'} # type: ignore async def get( self, resource_group_name: str, virtual_network_gateway_connection_name: str, **kwargs ) -> "_models.VirtualNetworkGatewayConnection": """Gets the specified virtual network gateway connection by resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_network_gateway_connection_name: The name of the virtual network gateway connection. :type virtual_network_gateway_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: VirtualNetworkGatewayConnection, or the result of cls(response) :rtype: ~azure.mgmt.network.v2016_09_01.models.VirtualNetworkGatewayConnection :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkGatewayConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" accept = "application/json, text/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('VirtualNetworkGatewayConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, virtual_network_gateway_connection_name: str, **kwargs ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}'} # type: ignore async def begin_delete( self, resource_group_name: str, virtual_network_gateway_connection_name: str, **kwargs ) -> AsyncLROPoller[None]: """Deletes the specified virtual network Gateway connection. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_network_gateway_connection_name: The name of the virtual network gateway connection. :type virtual_network_gateway_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, virtual_network_gateway_connection_name=virtual_network_gateway_connection_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}'} # type: ignore async def _set_shared_key_initial( self, resource_group_name: str, virtual_network_gateway_connection_name: str, parameters: "_models.ConnectionSharedKey", **kwargs ) -> "_models.ConnectionSharedKey": cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSharedKey"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json, text/json" # Construct URL url = self._set_shared_key_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ConnectionSharedKey') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('ConnectionSharedKey', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('ConnectionSharedKey', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _set_shared_key_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey'} # type: ignore async def begin_set_shared_key( self, resource_group_name: str, virtual_network_gateway_connection_name: str, parameters: "_models.ConnectionSharedKey", **kwargs ) -> AsyncLROPoller["_models.ConnectionSharedKey"]: """The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_network_gateway_connection_name: The virtual network gateway connection name. :type virtual_network_gateway_connection_name: str :param parameters: Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider. :type parameters: ~azure.mgmt.network.v2016_09_01.models.ConnectionSharedKey :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ConnectionSharedKey or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2016_09_01.models.ConnectionSharedKey] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSharedKey"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._set_shared_key_initial( resource_group_name=resource_group_name, virtual_network_gateway_connection_name=virtual_network_gateway_connection_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ConnectionSharedKey', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_set_shared_key.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey'} # type: ignore async def get_shared_key( self, resource_group_name: str, virtual_network_gateway_connection_name: str, **kwargs ) -> "_models.ConnectionSharedKey": """The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified virtual network gateway connection shared key through Network resource provider. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_network_gateway_connection_name: The virtual network gateway connection shared key name. :type virtual_network_gateway_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ConnectionSharedKey, or the result of cls(response) :rtype: ~azure.mgmt.network.v2016_09_01.models.ConnectionSharedKey :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionSharedKey"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" accept = "application/json, text/json" # Construct URL url = self.get_shared_key.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ConnectionSharedKey', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get_shared_key.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey'} # type: ignore def list( self, resource_group_name: str, **kwargs ) -> AsyncIterable["_models.VirtualNetworkGatewayConnectionListResult"]: """The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either VirtualNetworkGatewayConnectionListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2016_09_01.models.VirtualNetworkGatewayConnectionListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkGatewayConnectionListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" accept = "application/json, text/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('VirtualNetworkGatewayConnectionListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections'} # type: ignore async def _reset_shared_key_initial( self, resource_group_name: str, virtual_network_gateway_connection_name: str, parameters: "_models.ConnectionResetSharedKey", **kwargs ) -> Optional["_models.ConnectionResetSharedKey"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ConnectionResetSharedKey"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2016-09-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json, text/json" # Construct URL url = self._reset_shared_key_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ConnectionResetSharedKey') body_content_kwargs['content'] = body_content request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ConnectionResetSharedKey', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _reset_shared_key_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset'} # type: ignore async def begin_reset_shared_key( self, resource_group_name: str, virtual_network_gateway_connection_name: str, parameters: "_models.ConnectionResetSharedKey", **kwargs ) -> AsyncLROPoller["_models.ConnectionResetSharedKey"]: """The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_network_gateway_connection_name: The virtual network gateway connection reset shared key Name. :type virtual_network_gateway_connection_name: str :param parameters: Parameters supplied to the begin reset virtual network gateway connection shared key operation through network resource provider. :type parameters: ~azure.mgmt.network.v2016_09_01.models.ConnectionResetSharedKey :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ConnectionResetSharedKey or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2016_09_01.models.ConnectionResetSharedKey] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ConnectionResetSharedKey"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._reset_shared_key_initial( resource_group_name=resource_group_name, virtual_network_gateway_connection_name=virtual_network_gateway_connection_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ConnectionResetSharedKey', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'virtualNetworkGatewayConnectionName': self._serialize.url("virtual_network_gateway_connection_name", virtual_network_gateway_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_reset_shared_key.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset'} # type: ignore
mit
karesansui/karesansui
karesansui/gadget/hostby1.py
1
15575
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # 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. # import web import simplejson as json import karesansui from karesansui.lib.rest import Rest, auth from karesansui.db.access.machine import \ findbyhost1, findby1name, findby1hostname, \ update as m_update, delete as m_delete, logical_delete from karesansui.lib.merge import MergeHost from karesansui.lib.virt.virt import KaresansuiVirtConnection, KaresansuiVirtConnectionAuth from karesansui.lib.utils import \ comma_split, uniq_sort, is_param, json_dumps, \ get_proc_cpuinfo, get_proc_meminfo, get_partition_info, \ available_virt_uris, uri_split, uri_join from karesansui.lib.checker import Checker, \ CHECK_EMPTY, CHECK_LENGTH, CHECK_ONLYSPACE, CHECK_VALID,\ CHECK_MIN, CHECK_MAX from karesansui.lib.const import \ NOTE_TITLE_MIN_LENGTH, NOTE_TITLE_MAX_LENGTH, \ MACHINE_NAME_MIN_LENGTH, MACHINE_NAME_MAX_LENGTH, \ TAG_MIN_LENGTH, TAG_MAX_LENGTH, \ FQDN_MIN_LENGTH, FQDN_MAX_LENGTH, \ PORT_MIN_NUMBER, PORT_MAX_NUMBER, \ MACHINE_ATTRIBUTE, MACHINE_HYPERVISOR, \ USER_MIN_LENGTH, USER_MAX_LENGTH, \ VENDOR_DATA_DIR from karesansui.db.access.tag import \ new as t_new, samecount as t_count, findby1name as t_name def validates_host_edit(obj): checker = Checker() check = True _ = obj._ checker.errors = [] if not is_param(obj.input, 'm_name'): check = False checker.add_error(_('Parameter m_name does not exist.')) else: check = checker.check_string( _('Machine Name'), obj.input.m_name, CHECK_EMPTY | CHECK_LENGTH | CHECK_ONLYSPACE, None, min = MACHINE_NAME_MIN_LENGTH, max = MACHINE_NAME_MAX_LENGTH, ) and check if not is_param(obj.input, 'm_connect_type'): check = False checker.add_error(_('Parameter m_connect_type does not exist.')) else: if obj.input.m_connect_type == "karesansui": if not is_param(obj.input, 'm_hostname'): check = False checker.add_error(_('"%s" is required.') % _('FQDN')) else: m_hostname_parts = obj.input.m_hostname.split(":") if len(m_hostname_parts) > 2: check = False checker.add_error(_('%s contains too many colon(:)s.') % _('FQDN')) else: check = checker.check_domainname( _('FQDN'), m_hostname_parts[0], CHECK_EMPTY | CHECK_LENGTH | CHECK_VALID, min = FQDN_MIN_LENGTH, max = FQDN_MAX_LENGTH, ) and check try: check = checker.check_number( _('Port Number'), m_hostname_parts[1], CHECK_EMPTY | CHECK_VALID | CHECK_MIN | CHECK_MAX, PORT_MIN_NUMBER, PORT_MAX_NUMBER, ) and check except IndexError: # when reach here, 'm_hostname' has only host name pass if obj.input.m_connect_type == "libvirt": if not is_param(obj.input, 'm_uri'): check = False checker.add_error(_('"%s" is required.') % _('URI')) else: pass if is_param(obj.input, 'm_auth_user') and obj.input.m_auth_user != "": check = checker.check_username( _('User Name'), obj.input.m_auth_user, CHECK_LENGTH | CHECK_ONLYSPACE, min = USER_MIN_LENGTH, max = USER_MAX_LENGTH, ) and check if is_param(obj.input, 'note_title'): check = checker.check_string( _('Title'), obj.input.note_title, CHECK_LENGTH | CHECK_ONLYSPACE, None, min = NOTE_TITLE_MIN_LENGTH, max = NOTE_TITLE_MAX_LENGTH, ) and check if is_param(obj.input, 'note_value'): check = checker.check_string( _('Note'), obj.input.note_value, CHECK_ONLYSPACE, None, None, None, ) and check if is_param(obj.input, 'tags'): for tag in comma_split(obj.input.tags): check = checker.check_string( _('Tag'), tag, CHECK_LENGTH | CHECK_ONLYSPACE, None, min = TAG_MIN_LENGTH, max = TAG_MAX_LENGTH, ) and check obj.view.alert = checker.errors return check class HostBy1(Rest): def _post(self, f): ret = Rest._post(self, f) if hasattr(self, "kvc") is True: self.kvc.close() return ret @auth def _GET(self, *param, **params): if self.input.has_key('job_id') is True: self.view.job_id = self.input.job_id else: self.view.job_id = None host_id = self.chk_hostby1(param) if host_id is None: return web.notfound() model = findbyhost1(self.orm, host_id) uris = available_virt_uris() if model.attribute == 0 and model.hypervisor == 1: uri = uris["XEN"] elif model.attribute == 0 and model.hypervisor == 2: uri = uris["KVM"] else: uri = None # other_url other_url = "%s://%s%s/" % (self.view.ctx.protocol, model.hostname, karesansui.config['application.url.prefix']) if self.is_mode_input() is False: if karesansui.config["application.uniqkey"] == model.uniq_key: # My host host_cpuinfo = get_proc_cpuinfo() cpuinfo = {} cpuinfo["number"] = len(host_cpuinfo) cpuinfo["vendor"] = host_cpuinfo[0]["vendor_id"] cpuinfo["model"] = host_cpuinfo[0]["model name"] cpuinfo["frequency"] = host_cpuinfo[0]["cpu MHz"] host_meminfo = get_proc_meminfo() meminfo = {} meminfo["total"] = host_meminfo["MemTotal"][0] meminfo["free"] = host_meminfo["MemFree"][0] meminfo["buffers"] = host_meminfo["Buffers"][0] meminfo["cached"] = host_meminfo["Cached"][0] host_diskinfo = get_partition_info(VENDOR_DATA_DIR) diskinfo = {} diskinfo["total"] = host_diskinfo[1] diskinfo["free"] = host_diskinfo[3] self.kvc = KaresansuiVirtConnection(uri) try: host = MergeHost(self.kvc, model) if self.is_json() is True: json_host = host.get_json(self.me.languages) self.view.data = json_dumps({"model": json_host["model"], "cpuinfo": cpuinfo, "meminfo": meminfo, "diskinfo": diskinfo, }) else: self.view.model = host.info["model"] self.view.virt = host.info["virt"] finally: self.kvc.close() else: # other uri if model.attribute == 2: segs = uri_split(model.hostname) uri = uri_join(segs, without_auth=True) creds = '' if segs["user"] is not None: creds += segs["user"] if segs["passwd"] is not None: creds += ':' + segs["passwd"] try: self.kvc = KaresansuiVirtConnectionAuth(uri,creds) host = MergeHost(self.kvc, model) if self.is_json() is True: json_host = host.get_json(self.me.languages) self.view.data = json_dumps({"model": json_host["model"], "uri" : uri, "num_of_guests" : len(host.guests), }) else: self.view.model = host.info["model"] self.view.virt = host.info["virt"] self.view.uri = uri try: self.view.auth_user = segs["user"] except: self.view.auth_user = "" try: self.view.auth_passwd = segs["passwd"] except: self.view.auth_passwd = "" except: pass finally: #if 'kvc' in dir(locals()["self"]) if 'kvc' in dir(self): self.kvc.close() # other host else: if self.is_json() is True: self.view.data = json_dumps({ "model": model.get_json(self.me.languages), "other_url" : other_url, }) else: self.view.model = model self.view.virt = None self.view.other_url = other_url return True else: # mode=input if model.attribute == 2: segs = uri_split(model.hostname) uri = uri_join(segs, without_auth=True) creds = '' if segs["user"] is not None: creds += segs["user"] if segs["passwd"] is not None: creds += ':' + segs["passwd"] self.view.model = model self.view.uri = uri try: self.view.auth_user = segs["user"] except: self.view.auth_user = "" try: self.view.auth_passwd = segs["passwd"] except: self.view.auth_passwd = "" else: self.kvc = KaresansuiVirtConnection(uri) try: host = MergeHost(self.kvc, model) self.view.model = host.info["model"] finally: self.kvc.close() self.view.application_uniqkey = karesansui.config['application.uniqkey'] return True @auth def _PUT(self, *param, **params): host_id = self.chk_hostby1(param) if host_id is None: return web.notfound() if not validates_host_edit(self): self.logger.debug("Update Host OS is failed, Invalid input value.") return web.badrequest(self.view.alert) host = findbyhost1(self.orm, host_id) cmp_host = findby1name(self.orm, self.input.m_name) if cmp_host is not None and int(host_id) != cmp_host.id: self.logger.debug("Update Host OS is failed, " "Already exists name" "- %s, %s" % (host, cmp_host)) return web.conflict(web.ctx.path) if self.input.m_connect_type == "karesansui": hostname_check = findby1hostname(self.orm, self.input.m_hostname) if hostname_check is not None and int(host_id) != hostname_check.id: return web.conflict(web.ctx.path) if self.input.m_connect_type == "karesansui": host.attribute = MACHINE_ATTRIBUTE['HOST'] if is_param(self.input, "m_hostname"): host.hostname = self.input.m_hostname if self.input.m_connect_type == "libvirt": host.attribute = MACHINE_ATTRIBUTE['URI'] if is_param(self.input, "m_uri"): segs = uri_split(self.input.m_uri) if is_param(self.input, "m_auth_user") and self.input.m_auth_user: segs["user"] = self.input.m_auth_user if is_param(self.input, "m_auth_passwd") and self.input.m_auth_passwd: segs["passwd"] = self.input.m_auth_passwd host.hostname = uri_join(segs) if is_param(self.input, "note_title"): host.notebook.title = self.input.note_title if is_param(self.input, "note_value"): host.notebook.value = self.input.note_value if is_param(self.input, "m_name"): host.name = self.input.m_name # Icon icon_filename = None if is_param(self.input, "icon_filename", empty=True): host.icon = self.input.icon_filename # tag UPDATE if is_param(self.input, "tags"): _tags = [] tag_array = comma_split(self.input.tags) tag_array = uniq_sort(tag_array) for x in tag_array: if t_count(self.orm, x) == 0: _tags.append(t_new(x)) else: _tags.append(t_name(self.orm, x)) host.tags = _tags host.modified_user = self.me m_update(self.orm, host) return web.seeother(web.ctx.path) @auth def _DELETE(self, *param, **params): host_id = self.chk_hostby1(param) if host_id is None: return web.notfound() host = findbyhost1(self.orm, host_id) logical_delete(self.orm, host) return web.seeother(url = "/") urls = ( '/host/(\d+)/?(\.html|\.part|\.json)?$', HostBy1, )
mit
BlaisProteomics/mzStudio
mzStudio/Comet_GUI.py
1
30899
import wx import os from collections import defaultdict from multiplierz.mzSearch import CometSearch from multiplierz.settings import settings from multiplierz.mzGUI_standalone import file_chooser from multiplierz.mass_biochem import unimod cometExe = settings.get_comet() mod_list = sorted(unimod.site_form_mod_names()) class idlookup(object): def __init__(self): pass def __getitem__(self, key): return key no_convert = idlookup() bool_convert = {True:'1',False:'0', '1':True,'0':False} unit_convert = {'amu':'0', '0':'amu', 'mmu':'1', '1':'mmu', 'ppm':'2', '2':'ppm'} mass_type_convert = {'Average':'0', '0':'Average', 'Monoisotopic':'1', '1':'Monoisotopic'} isotope_err_convert = {'None':'0', '0':'None', '-1, 0, 1, +2, +3':'1', '1':'-1, 0, 1, +2, +3', '-8, -4, 0, +4, +8':'2', '2':'-8, -4, 0, +4, +8'} termini_convert = {'1': 'Semi-Enzymatic', '2': 'Fully Enzymatic', '8': 'Req. N-Term Enzymatic', '9': 'Req. C-Term Enzymatic', 'Fully Enzymatic': '2', 'Req. C-Term Enzymatic': '9', 'Req. N-Term Enzymatic': '8', 'Semi-Enzymatic': '1'} NameToParameter = [('Database', 'database_name', no_convert), ('Run Decoy Search', 'decoy_search', bool_convert), ('Precursor Tolerance', 'peptide_mass_tolerance', no_convert), ('Precursor Units', 'peptide_mass_units', unit_convert), ('Precursor Mass Type', 'mass_type_parent', mass_type_convert), ('Fragment Mass Type', 'mass_type_fragment', mass_type_convert), ('Allowed Isotope Error', 'isotope_error', isotope_err_convert), ('Enzyme', 'search_enzyme_number', 'enzyme_special'), ('Termini', 'num_enzyme_termini', termini_convert), ('Missed Cleavages', 'allowed_missed_cleavage', no_convert), ('Fragment Bin Width', 'fragment_bin_tol', no_convert), ('a ions', 'use_A_ions', bool_convert), ('b ions', 'use_B_ions', bool_convert), ('c ions', 'use_C_ions', bool_convert), ('x ions', 'use_X_ions', bool_convert), ('y ions', 'use_Y_ions', bool_convert), ('z ions', 'use_Z_ions', bool_convert), ('H2O/NH3 Loss ions', 'use_NL_ions', bool_convert), ('Decoy String', 'decoy_prefix', no_convert), ('Minimum Peaks Filter', 'minimum_peaks', no_convert), ('Minimum Intensity Filter', 'minimum_intensity', no_convert), ('Remove +/- Precursor MZ', 'remove_precursor_tolerance', no_convert), ('Max Fragment Charge', 'max_fragment_charge', no_convert), ('Max Precursor Charge', 'max_precursor_charge', no_convert)] # Ignoring parameters with convenient default values. AutomaticallySetParameters = [('remove_precursor_peak', '1')] FixModFields = [('G', 'add_G_glycine'), ('A', 'add_A_alanine'), ('S', 'add_S_serine'), ('P', 'add_P_proline'), ('V', 'add_V_valine'), ('T', 'add_T_threonine'), ('C', 'add_C_cysteine'), ('L', 'add_L_leucine'), ('I', 'add_I_isoleucine'), ('N', 'add_N_asparagine'), ('D', 'add_D_aspartic_acid'), ('Q', 'add_Q_glutamine'), ('K', 'add_K_lysine'), ('E', 'add_E_glutamic_acid'), ('M', 'add_M_methionine'), ('O', 'add_O_ornithine'), ('H', 'add_H_histidine'), ('F', 'add_F_phenylalanine'), ('R', 'add_R_arginine'), ('Y', 'add_Y_tyrosine'), ('W', 'add_W_tryptophan'), ('C-term', 'add_Cterm_peptide'), ('N-term', 'add_Nterm_peptide')] class ModWidget(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) #self.title = wx.StaticText(self, -1, "Modifications") self.fixmods = wx.ListCtrl(self, -1, name = "Fixed", style = wx.LC_REPORT) self.varmods = wx.ListCtrl(self, -1, name = "Variable", style = wx.LC_REPORT) self.modSelector = wx.ListCtrl(self, -1, name = "Unimods", style = wx.LC_REPORT, size = (250, -1)) self.addFixed = wx.Button(self, -1, '->', size = (25, -1)) self.addVar = wx.Button(self, -1, '->', size = (25, -1)) self.clearFix = wx.Button(self, -1, 'Clr', size = (25, -1)) self.clearVar = wx.Button(self, -1, 'Clr', size = (25, -1)) self.searchBar = wx.TextCtrl(self, -1, '') self.fixLabel = wx.StaticText(self, -1, "Fixed Modifications") self.varLabel = wx.StaticText(self, -1, "Variable Modifications") self.modSelector.AppendColumn('Mod') self.modSelector.AppendColumn('Site') self.full_mod_data = [] for modname in mod_list: words = modname.split(' ') basename = ' '.join(words[:-1]) site = words[-1].strip('()') self.modSelector.Append([basename, site]) self.full_mod_data.append((basename, site)) sitecolsize = self.modSelector.GetColumnWidth(1) self.modSelector.SetColumnWidth(0, 250 - sitecolsize) self.fixmods.AppendColumn('Site') self.fixmods.AppendColumn('Delta') self.varmods.AppendColumn('Site') self.varmods.AppendColumn('Delta') # Append blank rows to avoid annoying popup error. self.fixmods.Append(['', '']) self.varmods.Append(['', '']) gbs = wx.GridBagSizer(5, 5) gbs.Add(self.searchBar, (0, 0), flag = wx.EXPAND) gbs.Add(self.modSelector, (1, 0), span = (7, 1), flag = wx.EXPAND) gbs.Add(self.addFixed, (1, 1)) gbs.Add(self.addVar, (5, 1)) gbs.Add(self.clearFix, (3, 1), flag = wx.ALIGN_CENTER) gbs.Add(self.clearVar, (7, 1), flag = wx.ALIGN_CENTER) gbs.Add(self.fixLabel, (0, 2), flag = wx.ALIGN_BOTTOM) gbs.Add(self.varLabel, (4, 2), flag = wx.ALIGN_BOTTOM) gbs.Add(self.fixmods, (1, 2), span = (3, 1), flag = wx.EXPAND) gbs.Add(self.varmods, (5, 2), span = (3, 1), flag = wx.EXPAND) gbs.AddGrowableRow(3) gbs.AddGrowableRow(6) self.Bind(wx.EVT_BUTTON, self.assignFix, self.addFixed) self.Bind(wx.EVT_BUTTON, self.assignVar, self.addVar) self.Bind(wx.EVT_BUTTON, self.clearFixed, self.clearFix) self.Bind(wx.EVT_BUTTON, self.clearVariable, self.clearVar) self.Bind(wx.EVT_TEXT, self.filterMods, self.searchBar) self.SetSizerAndFit(gbs) self.oldFilterString = None self.Show() def updateFromModSelections(self, targetCtrl): index = self.modSelector.GetFirstSelected() siteDeltas = [] while index != -1: modname = self.modSelector.GetItem(index, 0).GetText() sitename = self.modSelector.GetItem(index, 1).GetText() delta = unimod.get_mod_delta(modname) if sitename == 'C-term': findsites = ['C-term'] elif sitename == 'N-term': findsites = ['N-term'] else: findsites = sitename.split() siteDeltas.append((findsites, float(delta))) index = self.modSelector.GetNextSelected(index) index = targetCtrl.GetTopItem() ctrlDeltas = defaultdict(float) while index != -1: site = targetCtrl.GetItem(index, 0).GetText() delta = targetCtrl.GetItem(index, 1).GetText() if delta: ctrlDeltas[site] = float(delta) index = targetCtrl.GetNextItem(index) for sites, delta in siteDeltas: for site in sites: ctrlDeltas[site] += delta #targetCtrl.ClearAll() #targetCtrl.AppendColumn('Site') #targetCtrl.AppendColumn('Delta') targetCtrl.DeleteAllItems() for site, delta in sorted(ctrlDeltas.items()): targetCtrl.Append((site, str(delta))) def assignFix(self, event): self.updateFromModSelections(self.fixmods) def assignVar(self, event): self.updateFromModSelections(self.varmods) def clearFixed(self, event): self.fixmods.ClearAll() self.fixmods.AppendColumn('Site') self.fixmods.AppendColumn('Delta') self.fixmods.Append(['', '']) def clearVariable(self, event): self.varmods.ClearAll() self.varmods.AppendColumn('Site') self.varmods.AppendColumn('Delta') self.varmods.Append(['', '']) def filterMods(self, event): filterstring = self.searchBar.GetValue().lower() self.modSelector.ClearAll() self.modSelector.AppendColumn('Mod') self.modSelector.AppendColumn('Site') for name, site in self.full_mod_data: if filterstring in name.lower(): self.modSelector.Append([name, site]) sitecolsize = self.modSelector.GetColumnWidth(1) self.modSelector.SetColumnWidth(0, 250 - sitecolsize) def readmods(self): varmods = [] for i in range(self.varmods.GetItemCount()): site = self.varmods.GetItem(i, 0).GetText() delta = self.varmods.GetItem(i, 1).GetText() varmods.append((site, delta)) fixmods = [] for i in range(self.fixmods.GetItemCount()): site = self.fixmods.GetItem(i, 0).GetText() delta = self.fixmods.GetItem(i, 1).GetText() fixmods.append((site, delta)) return varmods, fixmods def write_varmods(self, modlist): self.varmods.ClearAll() self.varmods.AppendColumn('Site') self.varmods.AppendColumn('Delta') if not modlist: self.varmods.Append(['', '']) for modsite, modmass in modlist: self.varmods.Append((modsite, modmass)) def write_fixmods(self, modlist): self.fixmods.ClearAll() self.fixmods.AppendColumn('Site') self.fixmods.AppendColumn('Delta') if not modlist: self.fixmods.Append(['', '']) for modsite, modmass in modlist: self.fixmods.Append((modsite, modmass)) class CometGUI(wx.Dialog): def textCtrl(self, name, defaultVal = ''): label = wx.StaticText(self.pane, -1, name) ctrl = wx.TextCtrl(self.pane, -1, str(defaultVal), name = name.replace('\n', ''), size = (70, -1)) return label, ctrl def fileCtrl(self, name, bind = True): label = wx.StaticText(self.pane, -1, name) ctrl = wx.TextCtrl(self.pane, -1, '', name = name.replace('\n', '')) button = wx.Button(self.pane, -1, "Browse") if bind: def browse(event): filename = file_chooser('Select %s' % name, mode = 'r') if filename: ctrl.SetValue(filename) self.Bind(wx.EVT_BUTTON, browse, button) return label, ctrl, button def checkCtrl(self, label, choices, size = None): return (wx.StaticText(self.pane, -1, label), wx.CheckListBox(self.pane, -1, choices = choices, name = label.replace('\n', ' '), size = size, style = wx.LB_HSCROLL)) def choiceCtrl(self, label, choices): return (wx.StaticText(self.pane, -1, label), wx.Choice(self.pane, -1, choices = choices, name = label.replace('\n', ' '))) def checkBox(self, label): return wx.CheckBox(self.pane, -1, label, name = label) def __init__(self, parent, ident, datafile, *etc, **etcetc): wx.Dialog.__init__(self, parent, ident, *etc, **etcetc) assert os.path.exists(cometExe), ('Comet not found at %s; please ' 'update multiplierz settings to ' 'indicate the directory of a copy ' 'of Comet.' % cometExe) self.pane = wx.Panel(self, -1) topLabel = wx.StaticText(self.pane, -1, "Comet Search Utility") topLabel.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD)) dataLabel, self.dataCtrl, self.dataBrowse = self.fileCtrl('Data File') # Modification for mzStudio. self.dataCtrl.SetValue(datafile) for ctrl in [dataLabel, self.dataCtrl, self.dataBrowse]: ctrl.Enable(False) ctrl.Show(False) dbaseLabel, self.dbaseCtrl, self.dbaseBrowse = self.fileCtrl('Database') parfileLabel, self.parfileCtrl, self.parfileBrowse = self.fileCtrl('Parameter File', bind = False) #varmodText, self.varmodCtrl = self.checkCtrl('Variable Modifications', mod_list, (300, -1)) #fixmodText, self.fixmodCtrl = self.checkCtrl('Fixed Modifications', mod_list, (300, -1)) precTolLabel, self.precTolCtrl = self.textCtrl('Precursor Tolerance') fragTolLabel, self.fragTolCtrl = self.textCtrl('Fragment Bin Width') precUnitLabel, self.precUnitCtrl = self.choiceCtrl('Precursor Units', ['amu', 'mmu', 'ppm']) precUnitLabel.Show(False) fragUnitLabel = wx.StaticText(self.pane, -1, 'amu') #fragUnitLabel, self.fragUnitCtrl = choiceCtrl('', ['amu', 'mmu', 'ppm']) isoErrLabel, self.isoErrCtrl = self.choiceCtrl('Allowed Isotope Error', ['None', '-1, 0, 1, +2, +3', '-8, -4, 0, +4, +8']) enzymeLabel, self.enzymeCtrl = self.choiceCtrl('Enzyme', []) terminiLabel, self.terminiCtrl = self.choiceCtrl('Termini', ['Fully Enzymatic', # 2 'Semi-Enzymatic', # 1 'Req. N-Term Enzymatic', # 8 'Req. C-Term Enzymatic']) # 9 missedCleLabel, self.missedCleCtrl = self.choiceCtrl('Missed\nCleavages', map(str, range(10))) precTypeLabel, self.precTypeCtrl = self.choiceCtrl('Precursor Mass Type', ['Monoisotopic', 'Average']) fragTypeLabel, self.fragTypeCtrl = self.choiceCtrl('Fragment Mass Type', ['Monoisotopic', 'Average']) topFragChargeLabel, self.topFragChargeCtrl = self.choiceCtrl('Max Fragment Charge', map(str, range(1, 9))) topPrecChargeLabel, self.topPrecChargeCtrl = self.choiceCtrl('Max Precursor Charge', map(str, range(1, 9))) #self.overrideCharge = self.checkBox('Ignore MGF Charge') #self.decoyCtrl = self.checkBox('Run Decoy Search') #decoyStringLabel, self.decoyStringCtrl = self.textCtrl('Decoy String') # mass_offsets control? Neutral loss? minPeakLabel, self.minPeakCtrl = self.textCtrl('Minimum Peaks Filter') minIntLabel, self.minIntCtrl = self.textCtrl('Minimum Intensity Filter') removePrecLabel, self.removePrecCtrl = self.textCtrl('Remove +/- Precursor MZ') # remove_precursor_peak should be a different setting for ETD spectra; add control? reportOptLabel = wx.StaticText(self.pane, -1, 'Output Options') reportOptLabel.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.FONTWEIGHT_BOLD)) maxRankLabel, self.maxRankCtrl = self.textCtrl('Rank Cutoff', defaultVal = 1) maxExpLabel, self.maxExpCtrl = self.textCtrl('Expectation Value Cutoff', defaultVal = 0.01) self.saveButton = wx.Button(self.pane, -1, "Save Parameters") self.goButton = wx.Button(self.pane, -1, 'Run Search') ### Peptide Ion Controls self.ionBox = wx.StaticBox(self.pane, -1, label = 'Ions') ionSizer = wx.StaticBoxSizer(self.ionBox) for ion in ['a','b','c','x','y','z','H2O/NH3 Loss']: ionctrl = wx.CheckBox(self.pane, -1, ion, name = '%s ions' % ion) if ion in ['b', 'y']: ionctrl.SetValue(True) ionSizer.Add(ionctrl, 0, wx.ALL, 5) self.modWidget = ModWidget(self.pane) gbs = wx.GridBagSizer(10, 10) #modSizer = wx.GridBagSizer(10, 10) #modSizer.Add(fixmodText, (0, 0), flag = wx.ALIGN_LEFT) #modSizer.Add(self.fixmodCtrl, (1, 0), span = (1, 2), flag = wx.EXPAND) #modSizer.Add(varmodText, (0, 2), flag = wx.ALIGN_LEFT) #modSizer.Add(self.varmodCtrl, (1, 2), span = (1, 2), flag = wx.EXPAND) #modSizer.Add(ionSizer, (2, 0), span = (1, 4), flag = wx.ALIGN_CENTRE) #modSizer.Add(wx.StaticLine(self.pane, -1, style = wx.LI_VERTICAL), #(0, 4), span = (3, 1), flag = wx.EXPAND) scanSizer = wx.GridBagSizer(5, 5) scanBox = [(precTolLabel, (0, 0), wx.ALIGN_RIGHT), (self.precTolCtrl, (0, 1), wx.EXPAND), (self.precUnitCtrl, (0, 2), wx.ALIGN_LEFT), (fragTolLabel, (1, 0), wx.ALIGN_RIGHT), (self.fragTolCtrl, (1, 1), wx.ALIGN_LEFT), (fragUnitLabel, (1, 2), wx.ALIGN_LEFT), (isoErrLabel, (2, 0), wx.ALIGN_RIGHT), (self.isoErrCtrl, (2, 1), wx.ALIGN_LEFT, (1, 2)), (wx.StaticLine(self.pane, -1, style = wx.LI_HORIZONTAL), (3, 0), wx.EXPAND, (1, 3)), (precTypeLabel, (4, 0), wx.ALIGN_RIGHT), (self.precTypeCtrl, (4, 1), wx.ALIGN_LEFT, (1, 2)), (fragTypeLabel, (5, 0), wx.ALIGN_RIGHT), (self.fragTypeCtrl, (5, 1), wx.ALIGN_LEFT, (1, 2)), (wx.StaticLine(self.pane, -1, style = wx.LI_HORIZONTAL), (6, 0), wx.EXPAND, (1, 3)), (topFragChargeLabel, (7, 0), wx.ALIGN_RIGHT), (self.topFragChargeCtrl, (7, 1), wx.ALIGN_LEFT), (topPrecChargeLabel, (8, 0), wx.ALIGN_RIGHT), (self.topPrecChargeCtrl, (8, 1), wx.ALIGN_LEFT), (wx.StaticLine(self.pane, -1, style = wx.LI_HORIZONTAL), (9, 0), wx.EXPAND, (1, 3)), (minPeakLabel, (10, 0), wx.ALIGN_RIGHT), (self.minPeakCtrl, (10, 1), wx.ALIGN_LEFT), (minIntLabel, (11, 0), wx.ALIGN_RIGHT), (self.minIntCtrl, (11, 1), wx.ALIGN_LEFT), (removePrecLabel, (12, 0), wx.ALIGN_RIGHT), (self.removePrecCtrl, (12, 1), wx.ALIGN_LEFT)] pepSizer = wx.GridBagSizer(5, 5) pepBox = [(wx.StaticLine(self.pane, -1, style = wx.LI_HORIZONTAL), (0, 0), wx.EXPAND, (1, 2)), (enzymeLabel, (1, 0), wx.ALIGN_RIGHT), (self.enzymeCtrl, (1, 1), wx.ALIGN_LEFT), (terminiLabel, (2, 0), wx.ALIGN_RIGHT), (self.terminiCtrl, (2, 1), wx.ALIGN_LEFT), (missedCleLabel, (3, 0), wx.ALIGN_RIGHT), (self.missedCleCtrl, (3, 1), wx.ALIGN_LEFT), (wx.StaticLine(self.pane, -1, style = wx.LI_HORIZONTAL), (4, 0), wx.EXPAND, (1, 2))] #searchSizer = wx.GridBagSizer(5, 5) #searchBox = [(self.decoyCtrl, (0, 0), wx.ALIGN_RIGHT), (decoyStringLabel, (0, 1), wx.ALIGN_RIGHT), #(self.decoyStringCtrl, (0, 2), wx.ALIGN_LEFT)] reportSizer = wx.GridBagSizer(5, 5, ) reportBox = [(reportOptLabel, (0, 0), wx.ALIGN_CENTRE | wx.BOTTOM, (1, 5)), (maxRankLabel, (1, 0), wx.ALIGN_RIGHT), (self.maxRankCtrl, (1, 1), wx.ALIGN_LEFT | wx.RIGHT), (maxExpLabel, (1, 3), wx.ALIGN_RIGHT | wx.LEFT), (self.maxExpCtrl, (1, 4), wx.ALIGN_LEFT)] fileSizer = wx.GridBagSizer(5, 5) fileBox = [(dataLabel, (0, 0), wx.ALIGN_RIGHT), (self.dataCtrl, (0, 1), wx.EXPAND, (1, 2)), (self.dataBrowse, (0, 3), wx.ALIGN_LEFT), (dbaseLabel, (1, 0), wx.ALIGN_RIGHT), (self.dbaseCtrl, (1, 1), wx.EXPAND, (1, 2)), (self.dbaseBrowse, (1, 3), wx.ALIGN_LEFT), (parfileLabel, (2, 0), wx.ALIGN_RIGHT), (self.parfileCtrl, (2, 1), wx.EXPAND, (1, 2)), (self.parfileBrowse, (2, 3), wx.ALIGN_LEFT), (self.saveButton, (3, 0), wx.EXPAND, (1, 2)), (self.goButton, (3, 2), wx.EXPAND, (1, 2))] for sizer, box in [(pepSizer, pepBox), (scanSizer, scanBox), (fileSizer, fileBox), (reportSizer, reportBox)]: for element in box: if len(element) == 3: widget, pos, flag = element span = (1, 1) elif len(element) == 4: widget, pos, flag, span = element sizer.Add(widget, pos = pos, span = span, flag = flag) #modSizer.AddGrowableRow(1) fileSizer.AddGrowableCol(1) fileSizer.AddGrowableCol(2) #topSizer.Add(modSizer) #topSizer.Add() gbs.Add(topLabel, (0, 0), span = (1, 3), flag = wx.ALIGN_CENTRE) #gbs.Add(modSizer, (1, 0), span = (3, 2), flag = wx.EXPAND | wx.RIGHT) gbs.Add(self.modWidget, (1, 0), span = (3, 2), flag = wx.EXPAND | wx.RIGHT) gbs.Add(ionSizer, (3, 2), flag = wx.ALIGN_RIGHT) gbs.Add(scanSizer, (1, 2), flag = wx.EXPAND | wx.LEFT) #gbs.Add(ionSizer, (2, 0), flag = wx.EXPAND) gbs.Add(pepSizer, (2, 2), flag = wx.ALIGN_CENTRE | wx.LEFT) #gbs.Add(searchSizer, (3, 2), flag = wx.EXPAND) gbs.Add(wx.StaticLine(self.pane, -1, style = wx.LI_HORIZONTAL), (4, 0), span = (1, 3), flag = wx.EXPAND) gbs.Add(reportSizer, (5, 0), span = (1, 3), flag = wx.ALIGN_CENTRE) gbs.Add(wx.StaticLine(self.pane, -1, style = wx.LI_HORIZONTAL), (6, 0), span = (1, 3), flag = wx.EXPAND) gbs.Add(fileSizer, (7, 0), span = (1, 3), flag = wx.EXPAND) overBox = wx.BoxSizer() overBox.Add(gbs, 0, wx.ALL, 10) self.pane.SetSizerAndFit(overBox) self.SetClientSize(self.pane.GetSize()) self.Bind(wx.EVT_BUTTON, self.load_parameters, self.parfileBrowse) self.Bind(wx.EVT_BUTTON, self.run_search, self.goButton) self.Bind(wx.EVT_BUTTON, self.save_parameters, self.saveButton) # Load default values (stored in comet_search.py.) self.parToGui(CometSearch()) self.did_run = False self.Show() def guiToPar(self): searchObj = CometSearch() # Does this get reasonable default parameters? for ctrlname, parname, convert in NameToParameter: ctrl = self.FindWindowByName(ctrlname) if not ctrl: continue if parname == 'search_enzyme_number': enzyme = ctrl.GetString(ctrl.GetSelection()) try: num = [k for k, v in searchObj.enzymes.items() if v['name'] == enzyme][0] except IndexError: raise NotImplementedError, "Invalid enzyme string: %s" % enzyme searchObj['search_enzyme_number'] = num continue if isinstance(ctrl, wx.CheckBox): parval = convert[ctrl.GetValue()] elif isinstance(ctrl, wx.Choice): parval = convert[str(ctrl.GetString(ctrl.GetSelection())).strip()] else: parval = convert[ctrl.GetValue().strip()] searchObj[parname] = parval #varmodstrs = self.varmodCtrl.GetCheckedStrings() #fixmodstrs = self.fixmodCtrl.GetCheckedStrings() varmodvalues, fixmodvalues = self.modWidget.readmods() if len(varmodvalues) > 9: wx.MessageBox("Comet only supports up to 9 separate variable modifications.") # Fixed mods don't havet his limitation, being site-based. return searchObj.varmods = [] for site, modmass in varmodvalues: if not modmass: continue modmass = float(modmass.strip()) mod = {'mass' : float(modmass), 'residues' : site, 'binary' : '0', 'max_mods_per_peptide' : '5', 'term_distance' : '-1', 'N/C-term' : '0', 'required' : '0'} searchObj.varmods.append(mod) fixmodMassBySite = defaultdict(float) for site, modmass in fixmodvalues: modmass = float(modmass) fixmodMassBySite[site] += modmass for sitename, parname in FixModFields: searchObj[parname] = fixmodMassBySite[sitename] return searchObj def parToGui(self, searchObj): for ctrlname, parname, convert in NameToParameter: ctrl = self.FindWindowByName(ctrlname) if not ctrl: continue # Not included in mzStudio version. if parname == 'search_enzyme_number': ctrl.Set(sorted([x['name'] for x in searchObj.enzymes.values()])) enzymeNum = str(searchObj[parname]) enzymeName = searchObj.enzymes[enzymeNum]['name'] ctrlNum = ctrl.FindString(enzymeName) assert ctrlNum >= 0, "Enzyme not found." ctrl.Select(ctrlNum) continue if isinstance(ctrl, wx.CheckBox): ctrl.SetValue(convert[str(searchObj[parname])]) elif isinstance(ctrl, wx.Choice): num = ctrl.FindString(convert[str(searchObj[parname])]) ctrl.SetSelection(num) else: ctrl.SetValue(convert[str(searchObj[parname])]) varmodlist = [] for varmod in searchObj.varmods: modmass = str(varmod['mass']) modsites = varmod['residues'] varmodlist.append((modsites, modmass)) #modsites = modsites.replace('n', 'N-Term').replace('c', 'C-Term') #modstr = '%s (%s)' % (modmass, modsites) #self.varmodCtrl.Insert(modstr, 0) #self.varmodCtrl.Check(0) #fixedMassSites = defaultdict(list) fixmodlist = [] for site, fixmodpar in FixModFields: parvalue = searchObj[fixmodpar] if parvalue and float(parvalue): fixmodlist.append((site, parvalue)) #fixedMassSites[parvalue].append(site) self.modWidget.write_varmods(varmodlist) self.modWidget.write_fixmods(fixmodlist) #for mass, sitelist in fixedMassSites.items(): #if float(mass): #modstr = '%s (%s)' % (mass, ''.join(sitelist)) #self.fixmodCtrl.Insert(modstr, 0) #self.fixmodCtrl.Check(0) def load_parameters(self, event): loadfile = file_chooser(title = 'Open parameter file:', mode = 'r') if loadfile: self.parfileCtrl.SetValue(loadfile) if os.path.exists(loadfile): self.parToGui(CometSearch(loadfile)) def save_parameters(self, event): searchObj = self.guiToPar() parfile = self.parfileCtrl.GetValue() if parfile: savefile = file_chooser(title = 'Save parameter file to:', default_path = os.path.dirname(parfile), default_file = os.path.basename(parfile), mode = 'w') else: savefile = file_chooser(title = 'Save parameter file to:', mode = 'w') searchObj.write(savefile) def run_search(self, event): datafile = self.dataCtrl.GetValue() if not datafile: wx.MessageBox('No data file selected.') return rankval = self.maxRankCtrl.GetValue().strip() expval = self.maxExpCtrl.GetValue().strip() try: if rankval: most_rank = int(rankval) else: most_rank = None except ValueError: wx.MessageBox('Invalid value for rank cutoff (must be int): %s' % rankval) return try: if expval: most_exp = float(expval) else: most_exp = None except ValueError: wx.MessageBox('Invalid value for expectation value cutoff (must be decimal number): %s' % expval) return searchObj = self.guiToPar() # Async-ify this? outputfile = searchObj.run_search(datafile, most_rank = most_rank, most_exp = most_exp) #wx.MessageBox('Search complete: output written to %s' % outputfile) self.output = outputfile self.did_run = True self.Close() def run_GUI_from_app(parent, spectrum, pepmass): from multiplierz.mgf import write_mgf from multiplierz.mzReport import reader tempfile = 'comet.temp.mgf' write_mgf([{'spectrum':spectrum, 'pepmass':pepmass, 'title':'test_spectrum'}], tempfile) #searchObj = CometGUI('foo','bar','baz') searchObj = CometGUI(parent, -1, tempfile) searchObj.ShowModal() if searchObj.did_run == True: outputfile = searchObj.output return list(reader(outputfile, sheet_name = 'Data')), list(reader(outputfile, sheet_name = 'Comet_Header')) else: return None, None if __name__ == '__main__': foo = wx.App(0) bar = CometGUI(None, -1, '') foo.MainLoop()
gpl-3.0
lgscofield/odoo
addons/email_template/tests/__init__.py
260
1093
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2012-TODAY OpenERP S.A. <http://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/>. # ############################################################################## from . import test_mail, test_ir_actions # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
safarijv/django-waffle
waffle/models.py
8
6824
try: from django.utils import timezone as datetime except ImportError: from datetime import datetime from django.contrib.auth.models import Group from django.db import models from django.db.models.signals import post_save, post_delete, m2m_changed from waffle.compat import AUTH_USER_MODEL, cache from waffle.utils import get_setting, keyfmt class Flag(models.Model): """A feature flag. Flags are active (or not) on a per-request basis. """ name = models.CharField(max_length=100, unique=True, help_text='The human/computer readable name.') everyone = models.NullBooleanField(blank=True, help_text=( 'Flip this flag on (Yes) or off (No) for everyone, overriding all ' 'other settings. Leave as Unknown to use normally.')) percent = models.DecimalField(max_digits=3, decimal_places=1, null=True, blank=True, help_text=( 'A number between 0.0 and 99.9 to indicate a percentage of users for ' 'whom this flag will be active.')) testing = models.BooleanField(default=False, help_text=( 'Allow this flag to be set for a session for user testing.')) superusers = models.BooleanField(default=True, help_text=( 'Flag always active for superusers?')) staff = models.BooleanField(default=False, help_text=( 'Flag always active for staff?')) authenticated = models.BooleanField(default=False, help_text=( 'Flag always active for authenticate users?')) languages = models.TextField(blank=True, default='', help_text=( 'Activate this flag for users with one of these languages (comma ' 'separated list)')) groups = models.ManyToManyField(Group, blank=True, help_text=( 'Activate this flag for these user groups.')) users = models.ManyToManyField(AUTH_USER_MODEL, blank=True, help_text=( 'Activate this flag for these users.')) rollout = models.BooleanField(default=False, help_text=( 'Activate roll-out mode?')) note = models.TextField(blank=True, help_text=( 'Note where this Flag is used.')) created = models.DateTimeField(default=datetime.now, db_index=True, help_text=('Date when this Flag was created.')) modified = models.DateTimeField(default=datetime.now, help_text=( 'Date when this Flag was last modified.')) def __unicode__(self): return self.name def save(self, *args, **kwargs): self.modified = datetime.now() super(Flag, self).save(*args, **kwargs) class Switch(models.Model): """A feature switch. Switches are active, or inactive, globally. """ name = models.CharField(max_length=100, unique=True, help_text='The human/computer readable name.') active = models.BooleanField(default=False, help_text=( 'Is this flag active?')) note = models.TextField(blank=True, help_text=( 'Note where this Switch is used.')) created = models.DateTimeField(default=datetime.now, db_index=True, help_text=('Date when this Switch was created.')) modified = models.DateTimeField(default=datetime.now, help_text=( 'Date when this Switch was last modified.')) def __unicode__(self): return self.name def save(self, *args, **kwargs): self.modified = datetime.now() super(Switch, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'Switches' class Sample(models.Model): """A sample is true some percentage of the time, but is not connected to users or requests. """ name = models.CharField(max_length=100, unique=True, help_text='The human/computer readable name.') percent = models.DecimalField(max_digits=4, decimal_places=1, help_text=( 'A number between 0.0 and 100.0 to indicate a percentage of the time ' 'this sample will be active.')) note = models.TextField(blank=True, help_text=( 'Note where this Sample is used.')) created = models.DateTimeField(default=datetime.now, db_index=True, help_text=('Date when this Sample was created.')) modified = models.DateTimeField(default=datetime.now, help_text=( 'Date when this Sample was last modified.')) def __unicode__(self): return self.name def save(self, *args, **kwargs): self.modified = datetime.now() super(Sample, self).save(*args, **kwargs) def cache_flag(**kwargs): action = kwargs.get('action', None) # action is included for m2m_changed signal. Only cache on the post_*. if not action or action in ['post_add', 'post_remove', 'post_clear']: f = kwargs.get('instance') cache.add(keyfmt(get_setting('FLAG_CACHE_KEY'), f.name), f) cache.add(keyfmt(get_setting('FLAG_USERS_CACHE_KEY'), f.name), f.users.all()) cache.add(keyfmt(get_setting('FLAG_GROUPS_CACHE_KEY'), f.name), f.groups.all()) def uncache_flag(**kwargs): flag = kwargs.get('instance') data = { keyfmt(get_setting('FLAG_CACHE_KEY'), flag.name): None, keyfmt(get_setting('FLAG_USERS_CACHE_KEY'), flag.name): None, keyfmt(get_setting('FLAG_GROUPS_CACHE_KEY'), flag.name): None, keyfmt(get_setting('ALL_FLAGS_CACHE_KEY')): None } cache.set_many(data, 5) post_save.connect(uncache_flag, sender=Flag, dispatch_uid='save_flag') post_delete.connect(uncache_flag, sender=Flag, dispatch_uid='delete_flag') m2m_changed.connect(uncache_flag, sender=Flag.users.through, dispatch_uid='m2m_flag_users') m2m_changed.connect(uncache_flag, sender=Flag.groups.through, dispatch_uid='m2m_flag_groups') def cache_sample(**kwargs): sample = kwargs.get('instance') cache.add(keyfmt(get_setting('SAMPLE_CACHE_KEY'), sample.name), sample) def uncache_sample(**kwargs): sample = kwargs.get('instance') cache.set(keyfmt(get_setting('SAMPLE_CACHE_KEY'), sample.name), None, 5) cache.set(keyfmt(get_setting('ALL_SAMPLES_CACHE_KEY')), None, 5) post_save.connect(uncache_sample, sender=Sample, dispatch_uid='save_sample') post_delete.connect(uncache_sample, sender=Sample, dispatch_uid='delete_sample') def cache_switch(**kwargs): switch = kwargs.get('instance') cache.add(keyfmt(get_setting('SWITCH_CACHE_KEY'), switch.name), switch) def uncache_switch(**kwargs): switch = kwargs.get('instance') cache.set(keyfmt(get_setting('SWITCH_CACHE_KEY'), switch.name), None, 5) cache.set(keyfmt(get_setting('ALL_SWITCHES_CACHE_KEY')), None, 5) post_delete.connect(uncache_switch, sender=Switch, dispatch_uid='delete_switch') post_save.connect(uncache_switch, sender=Switch, dispatch_uid='save_switch')
bsd-3-clause
pybrain2/pybrain2
pybrain/supervised/evolino/variate.py
32
1438
__author__ = 'Michael Isik' from random import uniform, random, gauss from numpy import tan, pi class UniformVariate: def __init__(self, min_val=0., max_val=1.): """ Initializes the uniform variate with a min and a max value. """ self._min_val = min_val self._max_val = max_val def getSample(self, min_val=None, max_val=None): """ Returns a random value between min_val and max_val. """ if min_val is None: min_val = self._min_val if max_val is None: max_val = self._max_val return uniform(min_val, max_val) class CauchyVariate: def __init__(self, x0=0., alpha=1.): """ :key x0: Median and mode of the Cauchy distribution :key alpha: scale """ self.x0 = x0 self.alpha = alpha def getSample(self, x0=None, alpha=None): if x0 is None: x0 = self.x0 if alpha is None: alpha = self.alpha uniform_variate = random() cauchy_variate = x0 + alpha * tan(pi * (uniform_variate - 0.5)) return cauchy_variate class GaussianVariate: def __init__(self, x0=0., alpha=1.): """ :key x0: Mean :key alpha: standard deviation """ self.x0 = x0 self.alpha = alpha def getSample(self, x0=None, alpha=None): if x0 is None: x0 = self.x0 if alpha is None: alpha = self.alpha return gauss(x0, alpha)
bsd-3-clause
binhqnguyen/ln
nsc/scons-local-1.2.0.d20090223/SCons/Tool/pdflatex.py
19
2896
"""SCons.Tool.pdflatex Tool-specific initialization for pdflatex. 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 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/pdflatex.py 4043 2009/02/23 09:06:45 scons" import SCons.Action import SCons.Util import SCons.Tool.pdf import SCons.Tool.tex PDFLaTeXAction = None def PDFLaTeXAuxFunction(target = None, source= None, env=None): result = SCons.Tool.tex.InternalLaTeXAuxAction( PDFLaTeXAction, target, source, env ) return result PDFLaTeXAuxAction = None def generate(env): """Add Builders and construction variables for pdflatex to an Environment.""" global PDFLaTeXAction if PDFLaTeXAction is None: PDFLaTeXAction = SCons.Action.Action('$PDFLATEXCOM', '$PDFLATEXCOMSTR') global PDFLaTeXAuxAction if PDFLaTeXAuxAction is None: PDFLaTeXAuxAction = SCons.Action.Action(PDFLaTeXAuxFunction, strfunction=SCons.Tool.tex.TeXLaTeXStrFunction) import pdf pdf.generate(env) bld = env['BUILDERS']['PDF'] bld.add_action('.ltx', PDFLaTeXAuxAction) bld.add_action('.latex', PDFLaTeXAuxAction) bld.add_emitter('.ltx', SCons.Tool.tex.tex_pdf_emitter) bld.add_emitter('.latex', SCons.Tool.tex.tex_pdf_emitter) env['PDFLATEX'] = 'pdflatex' env['PDFLATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode') env['PDFLATEXCOM'] = 'cd ${TARGET.dir} && $PDFLATEX $PDFLATEXFLAGS ${SOURCE.file}' env['LATEXRETRIES'] = 3 def exists(env): return env.Detect('pdflatex') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
gpl-2.0
sxjscience/tvm
vta/tests/python/unittest/test_environment.py
5
1176
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import vta def test_env(): env = vta.get_env() mock = env.mock assert mock.alu == "skip_alu" def test_env_scope(): env = vta.get_env() cfg = env.cfg_dict cfg["TARGET"] = "xyz" with vta.Environment(cfg): assert vta.get_env().TARGET == "xyz" assert vta.get_env().TARGET == env.TARGET if __name__ == "__main__": test_env() test_env_scope()
apache-2.0
addition-it-solutions/project-all
addons/mail/tests/test_invite.py
4
1974
# -*- coding: utf-8 -*- from openerp.addons.mail.tests.common import TestMail from openerp.tools import mute_logger class TestInvite(TestMail): @mute_logger('openerp.addons.mail.mail_mail') def test_invite_email(self): mail_invite = self.env['mail.wizard.invite'].with_context({ 'default_res_model': 'mail.group', 'default_res_id': self.group_pigs.id }).sudo(self.user_employee.id).create({ 'partner_ids': [(4, self.user_portal.partner_id.id), (4, self.user_employee_2.partner_id.id)], 'send_mail': True}) mail_invite.add_followers() # Test: Pigs followers should contain Admin, Bert self.assertEqual(self.group_pigs.message_follower_ids, self.user_portal.partner_id | self.user_employee_2.partner_id, 'invite wizard: Pigs followers after invite is incorrect, should be Admin + added follower') # Test: (pretend to) send email and check subject, body self.assertEqual(len(self._mails), 2, 'invite wizard: sent email number incorrect, should be only for Bert') self.assertEqual(self._mails[0].get('subject'), 'Invitation to follow Discussion group: Pigs', 'invite wizard: subject of invitation email is incorrect') self.assertEqual(self._mails[1].get('subject'), 'Invitation to follow Discussion group: Pigs', 'invite wizard: subject of invitation email is incorrect') self.assertIn('%s invited you to follow Discussion group document: Pigs' % self.user_employee.name, self._mails[0].get('body'), 'invite wizard: body of invitation email is incorrect') self.assertIn('%s invited you to follow Discussion group document: Pigs' % self.user_employee.name, self._mails[1].get('body'), 'invite wizard: body of invitation email is incorrect')
agpl-3.0
vaniakov/twisted-intro
twisted-deferred/defer-block.py
10
1216
import sys, time from twisted.internet.defer import Deferred def start_chain(_): print "The start of the callback chain." def blocking_poem(_): def delayed_write(s, delay): time.sleep(delay) sys.stdout.write(s) sys.stdout.flush() delayed_write('\n', 0) delayed_write('I', .6) delayed_write(' block', .4) delayed_write('\n and', 1) delayed_write(' the', .4) delayed_write(' deferred', .6) delayed_write('\n blocks', 1.5) delayed_write(' with', .2) delayed_write(' me', .2) delayed_write('\nas does', 1) delayed_write('\n the reactor', .6) delayed_write('\nkeep that', 1) delayed_write('\n factor', .6) delayed_write('\nin', 1) delayed_write(' mind', .4) delayed_write('\n\n', 2) def end_chain(_): print "The end of the callback chain." from twisted.internet import reactor reactor.stop() d = Deferred() d.addCallback(start_chain) d.addCallback(blocking_poem) d.addCallback(end_chain) def fire(): print 'Firing deferred.' d.callback(True) print 'Firing finished.' from twisted.internet import reactor reactor.callWhenRunning(fire) print 'Starting reactor.' reactor.run() print 'Done.'
mit
rht/zulip
zerver/webhooks/librato/tests.py
1
3657
# -*- coding: utf-8 -*- import urllib from zerver.lib.test_classes import WebhookTestCase class LibratoHookTests(WebhookTestCase): STREAM_NAME = 'librato' URL_TEMPLATE = u"/api/v1/external/librato?api_key={api_key}&stream={stream}" FIXTURE_DIR_NAME = 'librato' IS_ATTACHMENT = False def get_body(self, fixture_name: str) -> str: if self.IS_ATTACHMENT: return self.webhook_fixture_data("librato", fixture_name, file_type='json') return urllib.parse.urlencode({'payload': self.webhook_fixture_data("librato", fixture_name, file_type='json')}) def test_alert_message_with_default_topic(self) -> None: expected_topic = 'Alert alert.name' expected_message = "Alert [alert_name](https://metrics.librato.com/alerts#/6294535) has triggered! [Reaction steps](http://www.google.pl):\n * Metric `librato.cpu.percent.idle`, sum was below 44 by 300s, recorded at 2016-03-31 09:11:42 UTC.\n * Metric `librato.swap.swap.cached`, average was absent by 300s, recorded at 2016-03-31 09:11:42 UTC.\n * Metric `librato.swap.swap.cached`, derivative was above 9 by 300s, recorded at 2016-03-31 09:11:42 UTC." self.send_and_test_stream_message('alert', expected_topic, expected_message, content_type="application/x-www-form-urlencoded") def test_alert_message_with_custom_topic(self) -> None: custom_topic = 'custom_name' self.url = self.build_webhook_url(topic=custom_topic) expected_message = "Alert [alert_name](https://metrics.librato.com/alerts#/6294535) has triggered! [Reaction steps](http://www.google.pl):\n * Metric `librato.cpu.percent.idle`, sum was below 44 by 300s, recorded at 2016-03-31 09:11:42 UTC.\n * Metric `librato.swap.swap.cached`, average was absent by 300s, recorded at 2016-03-31 09:11:42 UTC.\n * Metric `librato.swap.swap.cached`, derivative was above 9 by 300s, recorded at 2016-03-31 09:11:42 UTC." self.send_and_test_stream_message('alert', custom_topic, expected_message, content_type="application/x-www-form-urlencoded") def test_three_conditions_alert_message(self) -> None: expected_message = "Alert [alert_name](https://metrics.librato.com/alerts#/6294535) has triggered! [Reaction steps](http://www.use.water.pl):\n * Metric `collectd.interface.eth0.if_octets.tx`, absolute_value was above 4 by 300s, recorded at 2016-04-11 20:40:14 UTC.\n * Metric `collectd.load.load.longterm`, max was above 99, recorded at 2016-04-11 20:40:14 UTC.\n * Metric `librato.swap.swap.cached`, average was absent by 60s, recorded at 2016-04-11 20:40:14 UTC." expected_topic = 'Alert ToHighTemeprature' self.send_and_test_stream_message('three_conditions_alert', expected_topic, expected_message, content_type="application/x-www-form-urlencoded") def test_alert_clear(self) -> None: expected_topic = 'Alert Alert_name' expected_message = "Alert [alert_name](https://metrics.librato.com/alerts#/6309313) has cleared at 2016-04-12 13:11:44 UTC!" self.send_and_test_stream_message('alert_cleared', expected_topic, expected_message, content_type="application/x-www-form-urlencoded") def test_snapshot(self) -> None: self.IS_ATTACHMENT = True expected_topic = 'Snapshots' expected_message = "**Hamlet** sent a [snapshot](http://snapshots.librato.com/chart/nr5l3n0c-82162.png) of [metric](https://metrics.librato.com/s/spaces/167315/explore/1731491?duration=72039&end_time=1460569409)." self.send_and_test_stream_message('snapshot', expected_topic, expected_message, content_type="application/x-www-form-urlencoded") self.IS_ATTACHMENT = False
apache-2.0
manazhao/tf_recsys
tensorflow/contrib/tensor_forest/hybrid/python/models/decisions_to_data_then_nn_test.py
101
4681
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for the hybrid tensor forest model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import random # pylint: disable=unused-import from tensorflow.contrib.tensor_forest.hybrid.python.models import decisions_to_data_then_nn from tensorflow.contrib.tensor_forest.python import tensor_forest from tensorflow.python.framework import constant_op from tensorflow.python.framework import test_util from tensorflow.python.framework.ops import Operation from tensorflow.python.framework.ops import Tensor from tensorflow.python.ops import variable_scope from tensorflow.python.platform import googletest class DecisionsToDataThenNNTest(test_util.TensorFlowTestCase): def setUp(self): self.params = tensor_forest.ForestHParams( num_classes=2, num_features=31, layer_size=11, num_layers=13, num_trees=17, connection_probability=0.1, hybrid_tree_depth=4, regularization_strength=0.01, learning_rate=0.01, regularization="", weight_init_mean=0.0, weight_init_std=0.1) self.params.regression = False self.params.num_nodes = 2**self.params.hybrid_tree_depth - 1 self.params.num_leaves = 2**(self.params.hybrid_tree_depth - 1) def testHParams(self): self.assertEquals(self.params.num_classes, 2) self.assertEquals(self.params.num_features, 31) self.assertEquals(self.params.layer_size, 11) self.assertEquals(self.params.num_layers, 13) self.assertEquals(self.params.num_trees, 17) self.assertEquals(self.params.hybrid_tree_depth, 4) self.assertEquals(self.params.connection_probability, 0.1) # Building the graphs modifies the params. with variable_scope.variable_scope("DecisionsToDataThenNNTest_testHParams"): # pylint: disable=W0612 graph_builder = decisions_to_data_then_nn.DecisionsToDataThenNN( self.params) # Tree with depth 4 should have 2**0 + 2**1 + 2**2 + 2**3 = 15 nodes. self.assertEquals(self.params.num_nodes, 15) def testConstructionPollution(self): """Ensure that graph building doesn't modify the params in a bad way.""" # pylint: disable=W0612 data = [[random.uniform(-1, 1) for i in range(self.params.num_features)] for _ in range(100)] self.assertTrue(isinstance(self.params, tensor_forest.ForestHParams)) self.assertFalse( isinstance(self.params.num_trees, tensor_forest.ForestHParams)) with variable_scope.variable_scope( "DecisionsToDataThenNNTest_testContructionPollution"): graph_builder = decisions_to_data_then_nn.DecisionsToDataThenNN( self.params) self.assertTrue(isinstance(self.params, tensor_forest.ForestHParams)) self.assertFalse( isinstance(self.params.num_trees, tensor_forest.ForestHParams)) def testInferenceConstruction(self): # pylint: disable=W0612 data = constant_op.constant( [[random.uniform(-1, 1) for i in range(self.params.num_features)] for _ in range(100)]) with variable_scope.variable_scope( "DecisionsToDataThenNNTest_testInferenceContruction"): graph_builder = decisions_to_data_then_nn.DecisionsToDataThenNN( self.params) graph = graph_builder.inference_graph(data, None) self.assertTrue(isinstance(graph, Tensor)) def testTrainingConstruction(self): # pylint: disable=W0612 data = constant_op.constant( [[random.uniform(-1, 1) for i in range(self.params.num_features)] for _ in range(100)]) labels = [1 for _ in range(100)] with variable_scope.variable_scope( "DecisionsToDataThenNNTest_testTrainingContruction"): graph_builder = decisions_to_data_then_nn.DecisionsToDataThenNN( self.params) graph = graph_builder.training_graph(data, labels, None) self.assertTrue(isinstance(graph, Operation)) if __name__ == "__main__": googletest.main()
apache-2.0
birdonwheels5/p2pool-dgbsha
p2pool/util/variable.py
270
2541
import itertools import weakref from twisted.internet import defer, reactor from twisted.python import failure, log class Event(object): def __init__(self): self.observers = {} self.id_generator = itertools.count() self._once = None self.times = 0 def run_and_watch(self, func): func() return self.watch(func) def watch_weakref(self, obj, func): # func must not contain a reference to obj! watch_id = self.watch(lambda *args: func(obj_ref(), *args)) obj_ref = weakref.ref(obj, lambda _: self.unwatch(watch_id)) def watch(self, func): id = self.id_generator.next() self.observers[id] = func return id def unwatch(self, id): self.observers.pop(id) @property def once(self): res = self._once if res is None: res = self._once = Event() return res def happened(self, *event): self.times += 1 once, self._once = self._once, None for id, func in sorted(self.observers.iteritems()): try: func(*event) except: log.err(None, "Error while processing Event callbacks:") if once is not None: once.happened(*event) def get_deferred(self, timeout=None): once = self.once df = defer.Deferred() id1 = once.watch(lambda *event: df.callback(event)) if timeout is not None: def do_timeout(): df.errback(failure.Failure(defer.TimeoutError('in Event.get_deferred'))) once.unwatch(id1) once.unwatch(x) delay = reactor.callLater(timeout, do_timeout) x = once.watch(lambda *event: delay.cancel()) return df class Variable(object): def __init__(self, value): self.value = value self.changed = Event() self.transitioned = Event() def set(self, value): if value == self.value: return oldvalue = self.value self.value = value self.changed.happened(value) self.transitioned.happened(oldvalue, value) @defer.inlineCallbacks def get_when_satisfies(self, func): while True: if func(self.value): defer.returnValue(self.value) yield self.changed.once.get_deferred() def get_not_none(self): return self.get_when_satisfies(lambda val: val is not None)
gpl-3.0
drawks/ansible
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_phase2.py
21
21260
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # # the lib use python logging can get it if the following is set in your # Ansible config. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_vpn_ipsec_phase2 short_description: Configure VPN autokey tunnel in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS by allowing the user to set and modify vpn_ipsec feature and phase2 category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.2 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate ip address. required: true username: description: - FortiOS or FortiGate username. required: true password: description: - FortiOS or FortiGate password. default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol type: bool default: true vpn_ipsec_phase2: description: - Configure VPN autokey tunnel. default: null suboptions: state: description: - Indicates whether to create or remove the object choices: - present - absent add-route: description: - Enable/disable automatic route addition. choices: - phase1 - enable - disable auto-negotiate: description: - Enable/disable IPsec SA auto-negotiation. choices: - enable - disable comments: description: - Comment. dhcp-ipsec: description: - Enable/disable DHCP-IPsec. choices: - enable - disable dhgrp: description: - Phase2 DH group. choices: - 1 - 2 - 5 - 14 - 15 - 16 - 17 - 18 - 19 - 20 - 21 - 27 - 28 - 29 - 30 - 31 dst-addr-type: description: - Remote proxy ID type. choices: - subnet - range - ip - name dst-end-ip: description: - Remote proxy ID IPv4 end. dst-end-ip6: description: - Remote proxy ID IPv6 end. dst-name: description: - Remote proxy ID name. Source firewall.address.name firewall.addrgrp.name. dst-name6: description: - Remote proxy ID name. Source firewall.address6.name firewall.addrgrp6.name. dst-port: description: - Quick mode destination port (1 - 65535 or 0 for all). dst-start-ip: description: - Remote proxy ID IPv4 start. dst-start-ip6: description: - Remote proxy ID IPv6 start. dst-subnet: description: - Remote proxy ID IPv4 subnet. dst-subnet6: description: - Remote proxy ID IPv6 subnet. encapsulation: description: - ESP encapsulation mode. choices: - tunnel-mode - transport-mode keepalive: description: - Enable/disable keep alive. choices: - enable - disable keylife-type: description: - Keylife type. choices: - seconds - kbs - both keylifekbs: description: - Phase2 key life in number of bytes of traffic (5120 - 4294967295). keylifeseconds: description: - Phase2 key life in time in seconds (120 - 172800). l2tp: description: - Enable/disable L2TP over IPsec. choices: - enable - disable name: description: - IPsec tunnel name. required: true pfs: description: - Enable/disable PFS feature. choices: - enable - disable phase1name: description: - Phase 1 determines the options required for phase 2. Source vpn.ipsec.phase1.name. proposal: description: - Phase2 proposal. choices: - null-md5 - null-sha1 - null-sha256 - null-sha384 - null-sha512 - des-null - des-md5 - des-sha1 - des-sha256 - des-sha384 - des-sha512 protocol: description: - Quick mode protocol selector (1 - 255 or 0 for all). replay: description: - Enable/disable replay detection. choices: - enable - disable route-overlap: description: - Action for overlapping routes. choices: - use-old - use-new - allow selector-match: description: - Match type to use when comparing selectors. choices: - exact - subset - auto single-source: description: - Enable/disable single source IP restriction. choices: - enable - disable src-addr-type: description: - Local proxy ID type. choices: - subnet - range - ip - name src-end-ip: description: - Local proxy ID end. src-end-ip6: description: - Local proxy ID IPv6 end. src-name: description: - Local proxy ID name. Source firewall.address.name firewall.addrgrp.name. src-name6: description: - Local proxy ID name. Source firewall.address6.name firewall.addrgrp6.name. src-port: description: - Quick mode source port (1 - 65535 or 0 for all). src-start-ip: description: - Local proxy ID start. src-start-ip6: description: - Local proxy ID IPv6 start. src-subnet: description: - Local proxy ID subnet. src-subnet6: description: - Local proxy ID IPv6 subnet. use-natip: description: - Enable to use the FortiGate public IP as the source selector when outbound NAT is used. choices: - enable - disable ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" tasks: - name: Configure VPN autokey tunnel. fortios_vpn_ipsec_phase2: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" vpn_ipsec_phase2: state: "present" add-route: "phase1" auto-negotiate: "enable" comments: "<your_own_value>" dhcp-ipsec: "enable" dhgrp: "1" dst-addr-type: "subnet" dst-end-ip: "<your_own_value>" dst-end-ip6: "<your_own_value>" dst-name: "<your_own_value> (source firewall.address.name firewall.addrgrp.name)" dst-name6: "<your_own_value> (source firewall.address6.name firewall.addrgrp6.name)" dst-port: "13" dst-start-ip: "<your_own_value>" dst-start-ip6: "<your_own_value>" dst-subnet: "<your_own_value>" dst-subnet6: "<your_own_value>" encapsulation: "tunnel-mode" keepalive: "enable" keylife-type: "seconds" keylifekbs: "21" keylifeseconds: "22" l2tp: "enable" name: "default_name_24" pfs: "enable" phase1name: "<your_own_value> (source vpn.ipsec.phase1.name)" proposal: "null-md5" protocol: "28" replay: "enable" route-overlap: "use-old" selector-match: "exact" single-source: "enable" src-addr-type: "subnet" src-end-ip: "<your_own_value>" src-end-ip6: "<your_own_value>" src-name: "<your_own_value> (source firewall.address.name firewall.addrgrp.name)" src-name6: "<your_own_value> (source firewall.address6.name firewall.addrgrp6.name)" src-port: "38" src-start-ip: "<your_own_value>" src-start-ip6: "<your_own_value>" src-subnet: "<your_own_value>" src-subnet6: "<your_own_value>" use-natip: "enable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule fos = None def login(data): host = data['host'] username = data['username'] password = data['password'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password) def filter_vpn_ipsec_phase2_data(json): option_list = ['add-route', 'auto-negotiate', 'comments', 'dhcp-ipsec', 'dhgrp', 'dst-addr-type', 'dst-end-ip', 'dst-end-ip6', 'dst-name', 'dst-name6', 'dst-port', 'dst-start-ip', 'dst-start-ip6', 'dst-subnet', 'dst-subnet6', 'encapsulation', 'keepalive', 'keylife-type', 'keylifekbs', 'keylifeseconds', 'l2tp', 'name', 'pfs', 'phase1name', 'proposal', 'protocol', 'replay', 'route-overlap', 'selector-match', 'single-source', 'src-addr-type', 'src-end-ip', 'src-end-ip6', 'src-name', 'src-name6', 'src-port', 'src-start-ip', 'src-start-ip6', 'src-subnet', 'src-subnet6', 'use-natip'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def flatten_multilists_attributes(data): multilist_attrs = [] for attr in multilist_attrs: try: path = "data['" + "']['".join(elem for elem in attr) + "']" current_val = eval(path) flattened_val = ' '.join(elem for elem in current_val) exec(path + '= flattened_val') except BaseException: pass return data def vpn_ipsec_phase2(data, fos): vdom = data['vdom'] vpn_ipsec_phase2_data = data['vpn_ipsec_phase2'] flattened_data = flatten_multilists_attributes(vpn_ipsec_phase2_data) filtered_data = filter_vpn_ipsec_phase2_data(flattened_data) if vpn_ipsec_phase2_data['state'] == "present": return fos.set('vpn.ipsec', 'phase2', data=filtered_data, vdom=vdom) elif vpn_ipsec_phase2_data['state'] == "absent": return fos.delete('vpn.ipsec', 'phase2', mkey=filtered_data['name'], vdom=vdom) def fortios_vpn_ipsec(data, fos): login(data) if data['vpn_ipsec_phase2']: resp = vpn_ipsec_phase2(data, fos) fos.logout() return not resp['status'] == "success", resp['status'] == "success", resp def main(): fields = { "host": {"required": True, "type": "str"}, "username": {"required": True, "type": "str"}, "password": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "vpn_ipsec_phase2": { "required": False, "type": "dict", "options": { "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "add-route": {"required": False, "type": "str", "choices": ["phase1", "enable", "disable"]}, "auto-negotiate": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "comments": {"required": False, "type": "str"}, "dhcp-ipsec": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "dhgrp": {"required": False, "type": "str", "choices": ["1", "2", "5", "14", "15", "16", "17", "18", "19", "20", "21", "27", "28", "29", "30", "31"]}, "dst-addr-type": {"required": False, "type": "str", "choices": ["subnet", "range", "ip", "name"]}, "dst-end-ip": {"required": False, "type": "str"}, "dst-end-ip6": {"required": False, "type": "str"}, "dst-name": {"required": False, "type": "str"}, "dst-name6": {"required": False, "type": "str"}, "dst-port": {"required": False, "type": "int"}, "dst-start-ip": {"required": False, "type": "str"}, "dst-start-ip6": {"required": False, "type": "str"}, "dst-subnet": {"required": False, "type": "str"}, "dst-subnet6": {"required": False, "type": "str"}, "encapsulation": {"required": False, "type": "str", "choices": ["tunnel-mode", "transport-mode"]}, "keepalive": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "keylife-type": {"required": False, "type": "str", "choices": ["seconds", "kbs", "both"]}, "keylifekbs": {"required": False, "type": "int"}, "keylifeseconds": {"required": False, "type": "int"}, "l2tp": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "name": {"required": True, "type": "str"}, "pfs": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "phase1name": {"required": False, "type": "str"}, "proposal": {"required": False, "type": "str", "choices": ["null-md5", "null-sha1", "null-sha256", "null-sha384", "null-sha512", "des-null", "des-md5", "des-sha1", "des-sha256", "des-sha384", "des-sha512"]}, "protocol": {"required": False, "type": "int"}, "replay": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "route-overlap": {"required": False, "type": "str", "choices": ["use-old", "use-new", "allow"]}, "selector-match": {"required": False, "type": "str", "choices": ["exact", "subset", "auto"]}, "single-source": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "src-addr-type": {"required": False, "type": "str", "choices": ["subnet", "range", "ip", "name"]}, "src-end-ip": {"required": False, "type": "str"}, "src-end-ip6": {"required": False, "type": "str"}, "src-name": {"required": False, "type": "str"}, "src-name6": {"required": False, "type": "str"}, "src-port": {"required": False, "type": "int"}, "src-start-ip": {"required": False, "type": "str"}, "src-start-ip6": {"required": False, "type": "str"}, "src-subnet": {"required": False, "type": "str"}, "src-subnet6": {"required": False, "type": "str"}, "use-natip": {"required": False, "type": "str", "choices": ["enable", "disable"]} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") global fos fos = FortiOSAPI() is_error, has_changed, result = fortios_vpn_ipsec(module.params, fos) if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
gpl-3.0
dudepare/django
django/test/signals.py
240
5928
import os import threading import time import warnings from django.core.signals import setting_changed from django.db import connections, router from django.db.utils import ConnectionRouter from django.dispatch import Signal, receiver from django.utils import timezone from django.utils.functional import empty template_rendered = Signal(providing_args=["template", "context"]) # Most setting_changed receivers are supposed to be added below, # except for cases where the receiver is related to a contrib app. # Settings that may not work well when using 'override_settings' (#19031) COMPLEX_OVERRIDE_SETTINGS = {'DATABASES'} @receiver(setting_changed) def clear_cache_handlers(**kwargs): if kwargs['setting'] == 'CACHES': from django.core.cache import caches caches._caches = threading.local() @receiver(setting_changed) def update_installed_apps(**kwargs): if kwargs['setting'] == 'INSTALLED_APPS': # Rebuild any AppDirectoriesFinder instance. from django.contrib.staticfiles.finders import get_finder get_finder.cache_clear() # Rebuild management commands cache from django.core.management import get_commands get_commands.cache_clear() # Rebuild get_app_template_dirs cache. from django.template.utils import get_app_template_dirs get_app_template_dirs.cache_clear() # Rebuild translations cache. from django.utils.translation import trans_real trans_real._translations = {} @receiver(setting_changed) def update_connections_time_zone(**kwargs): if kwargs['setting'] == 'TIME_ZONE': # Reset process time zone if hasattr(time, 'tzset'): if kwargs['value']: os.environ['TZ'] = kwargs['value'] else: os.environ.pop('TZ', None) time.tzset() # Reset local time zone cache timezone.get_default_timezone.cache_clear() # Reset the database connections' time zone if kwargs['setting'] in {'TIME_ZONE', 'USE_TZ'}: for conn in connections.all(): try: del conn.timezone except AttributeError: pass try: del conn.timezone_name except AttributeError: pass tz_sql = conn.ops.set_time_zone_sql() if tz_sql: with conn.cursor() as cursor: cursor.execute(tz_sql, [conn.timezone_name]) @receiver(setting_changed) def clear_routers_cache(**kwargs): if kwargs['setting'] == 'DATABASE_ROUTERS': router.routers = ConnectionRouter().routers @receiver(setting_changed) def reset_template_engines(**kwargs): if kwargs['setting'] in { 'TEMPLATES', 'TEMPLATE_DIRS', 'ALLOWED_INCLUDE_ROOTS', 'TEMPLATE_CONTEXT_PROCESSORS', 'TEMPLATE_DEBUG', 'TEMPLATE_LOADERS', 'TEMPLATE_STRING_IF_INVALID', 'DEBUG', 'FILE_CHARSET', 'INSTALLED_APPS', }: from django.template import engines try: del engines.templates except AttributeError: pass engines._templates = None engines._engines = {} from django.template.engine import Engine Engine.get_default.cache_clear() @receiver(setting_changed) def clear_serializers_cache(**kwargs): if kwargs['setting'] == 'SERIALIZATION_MODULES': from django.core import serializers serializers._serializers = {} @receiver(setting_changed) def language_changed(**kwargs): if kwargs['setting'] in {'LANGUAGES', 'LANGUAGE_CODE', 'LOCALE_PATHS'}: from django.utils.translation import trans_real trans_real._default = None trans_real._active = threading.local() if kwargs['setting'] in {'LANGUAGES', 'LOCALE_PATHS'}: from django.utils.translation import trans_real trans_real._translations = {} trans_real.check_for_language.cache_clear() @receiver(setting_changed) def file_storage_changed(**kwargs): file_storage_settings = { 'DEFAULT_FILE_STORAGE', 'FILE_UPLOAD_DIRECTORY_PERMISSIONS', 'FILE_UPLOAD_PERMISSIONS', 'MEDIA_ROOT', 'MEDIA_URL', } if kwargs['setting'] in file_storage_settings: from django.core.files.storage import default_storage default_storage._wrapped = empty @receiver(setting_changed) def complex_setting_changed(**kwargs): if kwargs['enter'] and kwargs['setting'] in COMPLEX_OVERRIDE_SETTINGS: # Considering the current implementation of the signals framework, # stacklevel=5 shows the line containing the override_settings call. warnings.warn("Overriding setting %s can lead to unexpected behavior." % kwargs['setting'], stacklevel=5) @receiver(setting_changed) def root_urlconf_changed(**kwargs): if kwargs['setting'] == 'ROOT_URLCONF': from django.core.urlresolvers import clear_url_caches, set_urlconf clear_url_caches() set_urlconf(None) @receiver(setting_changed) def static_storage_changed(**kwargs): if kwargs['setting'] in { 'STATICFILES_STORAGE', 'STATIC_ROOT', 'STATIC_URL', }: from django.contrib.staticfiles.storage import staticfiles_storage staticfiles_storage._wrapped = empty @receiver(setting_changed) def static_finders_changed(**kwargs): if kwargs['setting'] in { 'STATICFILES_DIRS', 'STATIC_ROOT', }: from django.contrib.staticfiles.finders import get_finder get_finder.cache_clear() @receiver(setting_changed) def auth_password_validators_changed(**kwargs): if kwargs['setting'] == 'AUTH_PASSWORD_VALIDATORS': from django.contrib.auth.password_validation import get_default_password_validators get_default_password_validators.cache_clear()
bsd-3-clause
techdragon/django
tests/view_tests/tests/test_csrf.py
24
5268
from django.template import TemplateDoesNotExist from django.test import ( Client, RequestFactory, SimpleTestCase, override_settings, ) from django.test.utils import ignore_warnings from django.utils.deprecation import RemovedInDjango20Warning from django.utils.translation import override from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure @override_settings(ROOT_URLCONF='view_tests.urls') class CsrfViewTests(SimpleTestCase): def setUp(self): super(CsrfViewTests, self).setUp() self.client = Client(enforce_csrf_checks=True) @override_settings( USE_I18N=True, MIDDLEWARE=[ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ], ) def test_translation(self): """ Test that an invalid request is rejected with a localized error message. """ response = self.client.post('/') self.assertContains(response, "Forbidden", status_code=403) self.assertContains(response, "CSRF verification failed. Request aborted.", status_code=403) with self.settings(LANGUAGE_CODE='nl'), override('en-us'): response = self.client.post('/') self.assertContains(response, "Verboden", status_code=403) self.assertContains(response, "CSRF-verificatie mislukt. Verzoek afgebroken.", status_code=403) @ignore_warnings(category=RemovedInDjango20Warning) @override_settings( USE_I18N=True, MIDDLEWARE=None, MIDDLEWARE_CLASSES=[ 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ], ) def test_translation_middleware_classes(self): """ Test that an invalid request is rejected with a localized error message. """ response = self.client.post('/') self.assertContains(response, "Forbidden", status_code=403) self.assertContains(response, "CSRF verification failed. Request aborted.", status_code=403) with self.settings(LANGUAGE_CODE='nl'), override('en-us'): response = self.client.post('/') self.assertContains(response, "Verboden", status_code=403) self.assertContains(response, "CSRF-verificatie mislukt. Verzoek afgebroken.", status_code=403) @override_settings( SECURE_PROXY_SSL_HEADER=('HTTP_X_FORWARDED_PROTO', 'https') ) def test_no_referer(self): """ Referer header is strictly checked for POST over HTTPS. Trigger the exception by sending an incorrect referer. """ response = self.client.post('/', HTTP_X_FORWARDED_PROTO='https') self.assertContains(response, "You are seeing this message because this HTTPS " "site requires a &#39;Referer header&#39; to be " "sent by your Web browser, but none was sent.", status_code=403) def test_no_cookies(self): """ The CSRF cookie is checked for POST. Failure to send this cookie should provide a nice error message. """ response = self.client.post('/') self.assertContains(response, "You are seeing this message because this site " "requires a CSRF cookie when submitting forms. " "This cookie is required for security reasons, to " "ensure that your browser is not being hijacked " "by third parties.", status_code=403) @override_settings(TEMPLATES=[]) def test_no_django_template_engine(self): """ The CSRF view doesn't depend on the TEMPLATES configuration (#24388). """ response = self.client.post('/') self.assertContains(response, "Forbidden", status_code=403) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { CSRF_FAILURE_TEMPLATE_NAME: 'Test template for CSRF failure' }), ], }, }]) def test_custom_template(self): """ A custom CSRF_FAILURE_TEMPLATE_NAME is used. """ response = self.client.post('/') self.assertContains(response, "Test template for CSRF failure", status_code=403) def test_custom_template_does_not_exist(self): """ An exception is raised if a nonexistent template is supplied. """ factory = RequestFactory() request = factory.post('/') with self.assertRaises(TemplateDoesNotExist): csrf_failure(request, template_name="nonexistent.html")
bsd-3-clause
ntt-sic/keystone
keystone/openstack/common/gettextutils.py
6
12823
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Red Hat, Inc. # Copyright 2013 IBM Corp. # 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. """ gettext for openstack-common modules. Usual usage in an openstack.common module: from keystone.openstack.common.gettextutils import _ """ import copy import gettext import logging import os import re try: import UserString as _userString except ImportError: import collections as _userString from babel import localedata import six _localedir = os.environ.get('keystone'.upper() + '_LOCALEDIR') _t = gettext.translation('keystone', localedir=_localedir, fallback=True) _AVAILABLE_LANGUAGES = {} USE_LAZY = False def enable_lazy(): """Convenience function for configuring _() to use lazy gettext Call this at the start of execution to enable the gettextutils._ function to use lazy gettext functionality. This is useful if your project is importing _ directly instead of using the gettextutils.install() way of importing the _ function. """ global USE_LAZY USE_LAZY = True def _(msg): if USE_LAZY: return Message(msg, 'keystone') else: if six.PY3: return _t.gettext(msg) return _t.ugettext(msg) def install(domain, lazy=False): """Install a _() function using the given translation domain. Given a translation domain, install a _() function using gettext's install() function. The main difference from gettext.install() is that we allow overriding the default localedir (e.g. /usr/share/locale) using a translation-domain-specific environment variable (e.g. NOVA_LOCALEDIR). :param domain: the translation domain :param lazy: indicates whether or not to install the lazy _() function. The lazy _() introduces a way to do deferred translation of messages by installing a _ that builds Message objects, instead of strings, which can then be lazily translated into any available locale. """ if lazy: # NOTE(mrodden): Lazy gettext functionality. # # The following introduces a deferred way to do translations on # messages in OpenStack. We override the standard _() function # and % (format string) operation to build Message objects that can # later be translated when we have more information. # # Also included below is an example LocaleHandler that translates # Messages to an associated locale, effectively allowing many logs, # each with their own locale. def _lazy_gettext(msg): """Create and return a Message object. Lazy gettext function for a given domain, it is a factory method for a project/module to get a lazy gettext function for its own translation domain (i.e. nova, glance, cinder, etc.) Message encapsulates a string so that we can translate it later when needed. """ return Message(msg, domain) from six import moves moves.builtins.__dict__['_'] = _lazy_gettext else: localedir = '%s_LOCALEDIR' % domain.upper() if six.PY3: gettext.install(domain, localedir=os.environ.get(localedir)) else: gettext.install(domain, localedir=os.environ.get(localedir), unicode=True) class Message(_userString.UserString, object): """Class used to encapsulate translatable messages.""" def __init__(self, msg, domain): # _msg is the gettext msgid and should never change self._msg = msg self._left_extra_msg = '' self._right_extra_msg = '' self._locale = None self.params = None self.domain = domain @property def data(self): # NOTE(mrodden): this should always resolve to a unicode string # that best represents the state of the message currently localedir = os.environ.get(self.domain.upper() + '_LOCALEDIR') if self.locale: lang = gettext.translation(self.domain, localedir=localedir, languages=[self.locale], fallback=True) else: # use system locale for translations lang = gettext.translation(self.domain, localedir=localedir, fallback=True) if six.PY3: ugettext = lang.gettext else: ugettext = lang.ugettext full_msg = (self._left_extra_msg + ugettext(self._msg) + self._right_extra_msg) if self.params is not None: full_msg = full_msg % self.params return six.text_type(full_msg) @property def locale(self): return self._locale @locale.setter def locale(self, value): self._locale = value if not self.params: return # This Message object may have been constructed with one or more # Message objects as substitution parameters, given as a single # Message, or a tuple or Map containing some, so when setting the # locale for this Message we need to set it for those Messages too. if isinstance(self.params, Message): self.params.locale = value return if isinstance(self.params, tuple): for param in self.params: if isinstance(param, Message): param.locale = value return if isinstance(self.params, dict): for param in self.params.values(): if isinstance(param, Message): param.locale = value def _save_dictionary_parameter(self, dict_param): full_msg = self.data # look for %(blah) fields in string; # ignore %% and deal with the # case where % is first character on the line keys = re.findall('(?:[^%]|^)?%\((\w*)\)[a-z]', full_msg) # if we don't find any %(blah) blocks but have a %s if not keys and re.findall('(?:[^%]|^)%[a-z]', full_msg): # apparently the full dictionary is the parameter params = copy.deepcopy(dict_param) else: params = {} for key in keys: try: params[key] = copy.deepcopy(dict_param[key]) except TypeError: # cast uncopyable thing to unicode string params[key] = six.text_type(dict_param[key]) return params def _save_parameters(self, other): # we check for None later to see if # we actually have parameters to inject, # so encapsulate if our parameter is actually None if other is None: self.params = (other, ) elif isinstance(other, dict): self.params = self._save_dictionary_parameter(other) else: # fallback to casting to unicode, # this will handle the problematic python code-like # objects that cannot be deep-copied try: self.params = copy.deepcopy(other) except TypeError: self.params = six.text_type(other) return self # overrides to be more string-like def __unicode__(self): return self.data def __str__(self): if six.PY3: return self.__unicode__() return self.data.encode('utf-8') def __getstate__(self): to_copy = ['_msg', '_right_extra_msg', '_left_extra_msg', 'domain', 'params', '_locale'] new_dict = self.__dict__.fromkeys(to_copy) for attr in to_copy: new_dict[attr] = copy.deepcopy(self.__dict__[attr]) return new_dict def __setstate__(self, state): for (k, v) in state.items(): setattr(self, k, v) # operator overloads def __add__(self, other): copied = copy.deepcopy(self) copied._right_extra_msg += other.__str__() return copied def __radd__(self, other): copied = copy.deepcopy(self) copied._left_extra_msg += other.__str__() return copied def __mod__(self, other): # do a format string to catch and raise # any possible KeyErrors from missing parameters self.data % other copied = copy.deepcopy(self) return copied._save_parameters(other) def __mul__(self, other): return self.data * other def __rmul__(self, other): return other * self.data def __getitem__(self, key): return self.data[key] def __getslice__(self, start, end): return self.data.__getslice__(start, end) def __getattribute__(self, name): # NOTE(mrodden): handle lossy operations that we can't deal with yet # These override the UserString implementation, since UserString # uses our __class__ attribute to try and build a new message # after running the inner data string through the operation. # At that point, we have lost the gettext message id and can just # safely resolve to a string instead. ops = ['capitalize', 'center', 'decode', 'encode', 'expandtabs', 'ljust', 'lstrip', 'replace', 'rjust', 'rstrip', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] if name in ops: return getattr(self.data, name) else: return _userString.UserString.__getattribute__(self, name) def get_available_languages(domain): """Lists the available languages for the given translation domain. :param domain: the domain to get languages for """ if domain in _AVAILABLE_LANGUAGES: return copy.copy(_AVAILABLE_LANGUAGES[domain]) localedir = '%s_LOCALEDIR' % domain.upper() find = lambda x: gettext.find(domain, localedir=os.environ.get(localedir), languages=[x]) # NOTE(mrodden): en_US should always be available (and first in case # order matters) since our in-line message strings are en_US language_list = ['en_US'] # NOTE(luisg): Babel <1.0 used a function called list(), which was # renamed to locale_identifiers() in >=1.0, the requirements master list # requires >=0.9.6, uncapped, so defensively work with both. We can remove # this check when the master list updates to >=1.0, and all projects udpate list_identifiers = (getattr(localedata, 'list', None) or getattr(localedata, 'locale_identifiers')) locale_identifiers = list_identifiers() for i in locale_identifiers: if find(i) is not None: language_list.append(i) _AVAILABLE_LANGUAGES[domain] = language_list return copy.copy(language_list) def get_localized_message(message, user_locale): """Gets a localized version of the given message in the given locale.""" if isinstance(message, Message): if user_locale: message.locale = user_locale return six.text_type(message) else: return message class LocaleHandler(logging.Handler): """Handler that can have a locale associated to translate Messages. A quick example of how to utilize the Message class above. LocaleHandler takes a locale and a target logging.Handler object to forward LogRecord objects to after translating the internal Message. """ def __init__(self, locale, target): """Initialize a LocaleHandler :param locale: locale to use for translating messages :param target: logging.Handler object to forward LogRecord objects to after translation """ logging.Handler.__init__(self) self.locale = locale self.target = target def emit(self, record): if isinstance(record.msg, Message): # set the locale and resolve to a string record.msg.locale = self.locale self.target.emit(record)
apache-2.0
patrikpettersson/rest-engine
lib/werkzeug/contrib/kickstart.py
95
11336
# -*- coding: utf-8 -*- """ werkzeug.contrib.kickstart ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module provides some simple shortcuts to make using Werkzeug simpler for small scripts. These improvements include predefined `Request` and `Response` objects as well as a predefined `Application` object which can be customized in child classes, of course. The `Request` and `Reponse` objects handle URL generation as well as sessions via `werkzeug.contrib.sessions` and are purely optional. There is also some integration of template engines. The template loaders are, of course, not neccessary to use the template engines in Werkzeug, but they provide a common interface. Currently supported template engines include Werkzeug's minitmpl and Genshi_. Support for other engines can be added in a trivial way. These loaders provide a template interface similar to the one used by Django_. .. _Genshi: http://genshi.edgewall.org/ .. _Django: http://www.djangoproject.com/ :copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from os import path from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase from werkzeug.templates import Template from werkzeug.exceptions import HTTPException from werkzeug.routing import RequestRedirect __all__ = ['Request', 'Response', 'TemplateNotFound', 'TemplateLoader', 'GenshiTemplateLoader', 'Application'] from warnings import warn warn(DeprecationWarning('werkzeug.contrib.kickstart is deprecated and ' 'will be removed in Werkzeug 1.0')) class Request(RequestBase): """A handy subclass of the base request that adds a URL builder. It when supplied a session store, it is also able to handle sessions. """ def __init__(self, environ, url_map, session_store=None, cookie_name=None): # call the parent for initialization RequestBase.__init__(self, environ) # create an adapter self.url_adapter = url_map.bind_to_environ(environ) # create all stuff for sessions self.session_store = session_store self.cookie_name = cookie_name if session_store is not None and cookie_name is not None: if cookie_name in self.cookies: # get the session out of the storage self.session = session_store.get(self.cookies[cookie_name]) else: # create a new session self.session = session_store.new() def url_for(self, callback, **values): return self.url_adapter.build(callback, values) class Response(ResponseBase): """ A subclass of base response which sets the default mimetype to text/html. It the `Request` that came in is using Werkzeug sessions, this class takes care of saving that session. """ default_mimetype = 'text/html' def __call__(self, environ, start_response): # get the request object request = environ['werkzeug.request'] if request.session_store is not None: # save the session if neccessary request.session_store.save_if_modified(request.session) # set the cookie for the browser if it is not there: if request.cookie_name not in request.cookies: self.set_cookie(request.cookie_name, request.session.sid) # go on with normal response business return ResponseBase.__call__(self, environ, start_response) class Processor(object): """A request and response processor - it is what Django calls a middleware, but Werkzeug also includes straight-foward support for real WSGI middlewares, so another name was chosen. The code of this processor is derived from the example in the Werkzeug trac, called `Request and Response Processor <http://dev.pocoo.org/projects/werkzeug/wiki/RequestResponseProcessor>`_ """ def process_request(self, request): return request def process_response(self, request, response): return response def process_view(self, request, view_func, view_args, view_kwargs): """process_view() is called just before the Application calls the function specified by view_func. If this returns None, the Application processes the next Processor, and if it returns something else (like a Response instance), that will be returned without any further processing. """ return None def process_exception(self, request, exception): return None class Application(object): """A generic WSGI application which can be used to start with Werkzeug in an easy, straightforward way. """ def __init__(self, name, url_map, session=False, processors=None): # save the name and the URL-map, as it'll be needed later on self.name = name self.url_map = url_map # save the list of processors if supplied self.processors = processors or [] # create an instance of the storage if session: self.store = session else: self.store = None def __call__(self, environ, start_response): # create a request - with or without session support if self.store is not None: request = Request(environ, self.url_map, session_store=self.store, cookie_name='%s_sid' % self.name) else: request = Request(environ, self.url_map) # apply the request processors for processor in self.processors: request = processor.process_request(request) try: # find the callback to which the URL is mapped callback, args = request.url_adapter.match(request.path) except (HTTPException, RequestRedirect), e: response = e else: # check all view processors for processor in self.processors: action = processor.process_view(request, callback, (), args) if action is not None: # it is overriding the default behaviour, this is # short-circuiting the processing, so it returns here return action(environ, start_response) try: response = callback(request, **args) except Exception, exception: # the callback raised some exception, need to process that for processor in reversed(self.processors): # filter it through the exception processor action = processor.process_exception(request, exception) if action is not None: # the exception processor returned some action return action(environ, start_response) # still not handled by a exception processor, so re-raise raise # apply the response processors for processor in reversed(self.processors): response = processor.process_response(request, response) # return the completely processed response return response(environ, start_response) def config_session(self, store, expiration='session'): """ Configures the setting for cookies. You can also disable cookies by setting store to None. """ self.store = store # expiration=session is the default anyway # TODO: add settings to define the expiration date, the domain, the # path any maybe the secure parameter. class TemplateNotFound(IOError, LookupError): """ A template was not found by the template loader. """ def __init__(self, name): IOError.__init__(self, name) self.name = name class TemplateLoader(object): """ A simple loader interface for the werkzeug minitmpl template language. """ def __init__(self, search_path, encoding='utf-8'): self.search_path = path.abspath(search_path) self.encoding = encoding def get_template(self, name): """Get a template from a given name.""" filename = path.join(self.search_path, *[p for p in name.split('/') if p and p[0] != '.']) if not path.exists(filename): raise TemplateNotFound(name) return Template.from_file(filename, self.encoding) def render_to_response(self, *args, **kwargs): """Load and render a template into a response object.""" return Response(self.render_to_string(*args, **kwargs)) def render_to_string(self, *args, **kwargs): """Load and render a template into a unicode string.""" try: template_name, args = args[0], args[1:] except IndexError: raise TypeError('name of template required') return self.get_template(template_name).render(*args, **kwargs) class GenshiTemplateLoader(TemplateLoader): """A unified interface for loading Genshi templates. Actually a quite thin wrapper for Genshi's TemplateLoader. It sets some defaults that differ from the Genshi loader, most notably auto_reload is active. All imporant options can be passed through to Genshi. The default output type is 'html', but can be adjusted easily by changing the `output_type` attribute. """ def __init__(self, search_path, encoding='utf-8', **kwargs): TemplateLoader.__init__(self, search_path, encoding) # import Genshi here, because we don't want a general Genshi # dependency, only a local one from genshi.template import TemplateLoader as GenshiLoader from genshi.template.loader import TemplateNotFound self.not_found_exception = TemplateNotFound # set auto_reload to True per default reload_template = kwargs.pop('auto_reload', True) # get rid of default_encoding as this template loaders overwrites it # with the value of encoding kwargs.pop('default_encoding', None) # now, all arguments are clean, pass them on self.loader = GenshiLoader(search_path, default_encoding=encoding, auto_reload=reload_template, **kwargs) # the default output is HTML but can be overridden easily self.output_type = 'html' self.encoding = encoding def get_template(self, template_name): """Get the template which is at the given name""" try: return self.loader.load(template_name, encoding=self.encoding) except self.not_found_exception, e: # catch the exception raised by Genshi, convert it into a werkzeug # exception (for the sake of consistency) raise TemplateNotFound(template_name) def render_to_string(self, template_name, context=None): """Load and render a template into an unicode string""" # create an empty context if no context was specified context = context or {} tmpl = self.get_template(template_name) # render the template into a unicode string (None means unicode) return tmpl. \ generate(**context). \ render(self.output_type, encoding=None)
mit
xiangke/pycopia
core/pycopia/charbuffer.py
1
2001
#!/usr/bin/python2.4 # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # # $Id$ # # Copyright (C) 1999-2006 Keith Dart <keith@kdart.com> # # 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. """ Defines a Buffer object that uses an anonymous mmap. The object looks like a StringIO object as well as supporting string operators. """ import mmap # get an anonymous mmap range. Only works on Linux (possibly other Unix) def get_buffer(size): return mmap.mmap(-1, size, flags=mmap.MAP_PRIVATE|mmap.MAP_ANONYMOUS, prot=mmap.PROT_READ|mmap.PROT_WRITE ) # Also emulate a StringIO object. class Buffer(object): def __init__(self, size=4096): self._bufsize = size self._buf = get_buffer(size) size = property(lambda s: s._bufsize) def close(self): if self._buf is not None: self._buf.close() self._buf = None def getvalue(self): return self._buf[:] # auto-delegate most attributes def __getattr__(self, name): return getattr(self._buf, name) def __getitem__(self, i): return self._buf[i] def __setitem__(self, i, v): self._buf[i] = v def __getslice__(self, i, j): return self._buf[i:j] def __setslice__(self, i, j, seq): self._buf[i:j] = seq def __iadd__(self, seq): self._buf.write(seq) return self def __len__(self): return self._buf.tell() def __str__(self): return self._buf[0:self._buf.tell()]
lgpl-2.1
ChenJunor/hue
desktop/core/ext-py/PyYAML-3.09/examples/yaml-highlight/yaml_hl.py
95
4429
#!/usr/bin/python import yaml, codecs, sys, os.path, optparse class Style: def __init__(self, header=None, footer=None, tokens=None, events=None, replaces=None): self.header = header self.footer = footer self.replaces = replaces self.substitutions = {} for domain, Class in [(tokens, 'Token'), (events, 'Event')]: if not domain: continue for key in domain: name = ''.join([part.capitalize() for part in key.split('-')]) cls = getattr(yaml, '%s%s' % (name, Class)) value = domain[key] if not value: continue start = value.get('start') end = value.get('end') if start: self.substitutions[cls, -1] = start if end: self.substitutions[cls, +1] = end def __setstate__(self, state): self.__init__(**state) yaml.add_path_resolver(u'tag:yaml.org,2002:python/object:__main__.Style', [None], dict) yaml.add_path_resolver(u'tag:yaml.org,2002:pairs', [None, u'replaces'], list) class YAMLHighlight: def __init__(self, options): config = yaml.load(file(options.config, 'rb').read()) self.style = config[options.style] if options.input: self.input = file(options.input, 'rb') else: self.input = sys.stdin if options.output: self.output = file(options.output, 'wb') else: self.output = sys.stdout def highlight(self): input = self.input.read() if input.startswith(codecs.BOM_UTF16_LE): input = unicode(input, 'utf-16-le') elif input.startswith(codecs.BOM_UTF16_BE): input = unicode(input, 'utf-16-be') else: input = unicode(input, 'utf-8') substitutions = self.style.substitutions tokens = yaml.scan(input) events = yaml.parse(input) markers = [] number = 0 for token in tokens: number += 1 if token.start_mark.index != token.end_mark.index: cls = token.__class__ if (cls, -1) in substitutions: markers.append([token.start_mark.index, +2, number, substitutions[cls, -1]]) if (cls, +1) in substitutions: markers.append([token.end_mark.index, -2, number, substitutions[cls, +1]]) number = 0 for event in events: number += 1 cls = event.__class__ if (cls, -1) in substitutions: markers.append([event.start_mark.index, +1, number, substitutions[cls, -1]]) if (cls, +1) in substitutions: markers.append([event.end_mark.index, -1, number, substitutions[cls, +1]]) markers.sort() markers.reverse() chunks = [] position = len(input) for index, weight1, weight2, substitution in markers: if index < position: chunk = input[index:position] for substring, replacement in self.style.replaces: chunk = chunk.replace(substring, replacement) chunks.append(chunk) position = index chunks.append(substitution) chunks.reverse() result = u''.join(chunks) if self.style.header: self.output.write(self.style.header) self.output.write(result.encode('utf-8')) if self.style.footer: self.output.write(self.style.footer) if __name__ == '__main__': parser = optparse.OptionParser() parser.add_option('-s', '--style', dest='style', default='ascii', help="specify the highlighting style", metavar='STYLE') parser.add_option('-c', '--config', dest='config', default=os.path.join(os.path.dirname(sys.argv[0]), 'yaml_hl.cfg'), help="set an alternative configuration file", metavar='CONFIG') parser.add_option('-i', '--input', dest='input', default=None, help="set the input file (default: stdin)", metavar='FILE') parser.add_option('-o', '--output', dest='output', default=None, help="set the output file (default: stdout)", metavar='FILE') (options, args) = parser.parse_args() hl = YAMLHighlight(options) hl.highlight()
apache-2.0
raildo/nova
nova/db/sqlalchemy/migrate_repo/versions/280_add_nullable_false_to_keypairs_name.py
81
1503
# Copyright 2015 Intel Corporation # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from migrate.changeset import UniqueConstraint from sqlalchemy import MetaData, Table def upgrade(migrate_engine): """Function enforces non-null value for keypairs name field.""" meta = MetaData(bind=migrate_engine) key_pairs = Table('key_pairs', meta, autoload=True) # Note: Since we are altering name field, this constraint on name needs to # first be dropped before we can alter name. We then re-create the same # constraint. It was first added in 216_havana.py so no need to remove # constraint on downgrade. UniqueConstraint('user_id', 'name', 'deleted', table=key_pairs, name='uniq_key_pairs0user_id0name0deleted').drop() key_pairs.c.name.alter(nullable=False) UniqueConstraint('user_id', 'name', 'deleted', table=key_pairs, name='uniq_key_pairs0user_id0name0deleted').create()
apache-2.0
ewindisch/nova
nova/volume/__init__.py
29
1462
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import oslo.config.cfg # Importing full names to not pollute the namespace and cause possible # collisions with use of 'from nova.volume import <foo>' elsewhere. import nova.openstack.common.importutils _volume_opts = [ oslo.config.cfg.StrOpt('volume_api_class', default='nova.volume.cinder.API', help='The full class name of the ' 'volume API class to use'), ] oslo.config.cfg.CONF.register_opts(_volume_opts) def API(): importutils = nova.openstack.common.importutils volume_api_class = oslo.config.cfg.CONF.volume_api_class cls = importutils.import_class(volume_api_class) return cls()
apache-2.0
sauloal/linuxscripts
apache/var/www/html/saulo/torrent/html/bin/clients/mainline/BTL/platform.py
3
3777
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software distributed under the License is distributed on an AS IS basis, # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License # for the specific language governing rights and limitations under the # License. import os import sys import time import codecs import urllib if os.name == 'nt': #import BTL.likewin32api as win32api import win32api from win32com.shell import shellcon, shell is_frozen_exe = getattr(sys, 'frozen', '') == 'windows_exe' def get_module_filename(): if is_frozen_exe: return os.path.abspath(win32api.GetModuleFileName(0)) else: return os.path.abspath(sys.argv[0]) try: from __main__ import app_name except: # ok, I'm sick of this. Everyone gets BTL if they don't # specify otherwise. app_name = "BTL" if sys.platform.startswith('win'): bttime = time.clock else: bttime = time.time def urlquote_error(error): s = error.object[error.start:error.end] s = s.encode('utf8') s = urllib.quote(s) s = s.decode('ascii') return (s, error.end) codecs.register_error('urlquote', urlquote_error) def get_filesystem_encoding(errorfunc=None): def dummy_log(e): print e pass if not errorfunc: errorfunc = dummy_log default_encoding = 'utf8' if os.path.supports_unicode_filenames: encoding = None else: try: encoding = sys.getfilesystemencoding() except AttributeError: errorfunc("This version of Python cannot detect filesystem encoding.") if encoding is None: encoding = default_encoding errorfunc("Python failed to detect filesystem encoding. " "Assuming '%s' instead." % default_encoding) else: try: 'a1'.decode(encoding) except: errorfunc("Filesystem encoding '%s' is not supported. Using '%s' instead." % (encoding, default_encoding)) encoding = default_encoding return encoding def encode_for_filesystem(path): assert isinstance(path, unicode), "Path should be unicode not %s" % type(path) bad = False encoding = get_filesystem_encoding() if encoding == None: encoded_path = path else: try: encoded_path = path.encode(encoding) except: bad = True path.replace(u"%", urllib.quote(u"%")) encoded_path = path.encode(encoding, 'urlquote') return (encoded_path, bad) def decode_from_filesystem(path): encoding = get_filesystem_encoding() if encoding == None: assert isinstance(path, unicode), "Path should be unicode not %s" % type(path) decoded_path = path else: assert isinstance(path, str), "Path should be str not %s" % type(path) decoded_path = path.decode(encoding) return decoded_path efs = encode_for_filesystem def efs2(path): # same as encode_for_filesystem, but doesn't bother returning "bad" return encode_for_filesystem(path)[0] # this function is the preferred way to get windows' paths def get_shell_dir(value): dir = None if os.name == 'nt': try: dir = shell.SHGetFolderPath(0, value, 0, 0) except: pass return dir def get_cache_dir(): dir = None if os.name == 'nt': dir = get_shell_dir(shellcon.CSIDL_INTERNET_CACHE) return dir
mit
doganaltunbay/odoo
addons/product/report/__init__.py
452
1080
# -*- 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 product_pricelist # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
lisong521/wireshark
tools/dftestlib/time_relative.py
40
1244
# Copyright (c) 2013 by Gilbert Ramirez <gram@alumni.rice.edu> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from dftestlib import dftest class testTimeRelative(dftest.DFTest): trace_file = "nfs.pcap" def test_relative_time_1(self): dfilter = "frame.time_delta == 0.7" self.assertDFilterCount(dfilter, 1) def test_relative_time_2(self): dfilter = "frame.time_delta > 0.7" self.assertDFilterCount(dfilter, 0) def test_relative_time_3(self): dfilter = "frame.time_delta < 0.7" self.assertDFilterCount(dfilter, 1)
gpl-2.0
mrwangxc/zstack-utility
zstacklib/zstacklib/utils/puppet.py
5
1507
''' @author: Frank ''' import shell import ssh import os.path import log import lock logger = log.get_logger(__name__) class PuppetError(Exception): '''puppet error''' def deploy_puppet_module(module_path, node_express=None, node_file_name=None, puppet_node_path='/etc/puppet/manifests/nodes', puppet_module_path='/etc/puppet/modules/'): if node_express: node_file_path = os.path.join(puppet_node_path, node_file_name) with open(node_file_path, 'w') as fd: fd.write(node_express) shell.call('rm -rf %s' % os.path.join(puppet_module_path, os.path.basename(module_path))) shell.call('cp -r %s %s' % (module_path, puppet_module_path)) def poke_puppet_agent(hostname, username, password, node_name, master_certname='zstack'): with lock.FileLock(hostname): ssh.execute('''ip=`env | grep SSH_CLIENT | cut -d '=' -f 2 | cut -d ' ' -f 1`; [ $ip == ::1 ] && ip=127.0.0.1; sed -i "/%s/d" /etc/hosts; echo "$ip %s" >> /etc/hosts''' % (master_certname, master_certname), hostname, username, password) (retcode, output, err) = ssh.execute('puppet agent --certname %s --no-daemonize --onetime --waitforcert 60 --server %s --verbose --detailed-exitcodes' % (node_name, master_certname), hostname, username, password, exception_if_error=False) if retcode == 4 or retcode == 6 or retcode == 1: raise PuppetError('failed to run puppet agent:\nstdout:%s\nstderr:%s\n' % (output, err)) logger.debug(output)
apache-2.0
michalliu/OpenWrt-Firefly-Libraries
staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python2.7/lib-tk/Tkconstants.py
375
1493
# Symbolic constants for Tk # Booleans NO=FALSE=OFF=0 YES=TRUE=ON=1 # -anchor and -sticky N='n' S='s' W='w' E='e' NW='nw' SW='sw' NE='ne' SE='se' NS='ns' EW='ew' NSEW='nsew' CENTER='center' # -fill NONE='none' X='x' Y='y' BOTH='both' # -side LEFT='left' TOP='top' RIGHT='right' BOTTOM='bottom' # -relief RAISED='raised' SUNKEN='sunken' FLAT='flat' RIDGE='ridge' GROOVE='groove' SOLID = 'solid' # -orient HORIZONTAL='horizontal' VERTICAL='vertical' # -tabs NUMERIC='numeric' # -wrap CHAR='char' WORD='word' # -align BASELINE='baseline' # -bordermode INSIDE='inside' OUTSIDE='outside' # Special tags, marks and insert positions SEL='sel' SEL_FIRST='sel.first' SEL_LAST='sel.last' END='end' INSERT='insert' CURRENT='current' ANCHOR='anchor' ALL='all' # e.g. Canvas.delete(ALL) # Text widget and button states NORMAL='normal' DISABLED='disabled' ACTIVE='active' # Canvas state HIDDEN='hidden' # Menu item types CASCADE='cascade' CHECKBUTTON='checkbutton' COMMAND='command' RADIOBUTTON='radiobutton' SEPARATOR='separator' # Selection modes for list boxes SINGLE='single' BROWSE='browse' MULTIPLE='multiple' EXTENDED='extended' # Activestyle for list boxes # NONE='none' is also valid DOTBOX='dotbox' UNDERLINE='underline' # Various canvas styles PIESLICE='pieslice' CHORD='chord' ARC='arc' FIRST='first' LAST='last' BUTT='butt' PROJECTING='projecting' ROUND='round' BEVEL='bevel' MITER='miter' # Arguments to xview/yview MOVETO='moveto' SCROLL='scroll' UNITS='units' PAGES='pages'
gpl-2.0
jaryn/dt174b
dt174b/dt174b.py
1
9468
# # Python tool for interfacing the CEM DT-174B Weather Datalogger. # Copyright (C) 2013 Jaroslav Henner # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import logging from collections import namedtuple from struct import pack, unpack from contextlib import contextmanager from itertools import islice, chain import usb import usb.core import usb.util BUF_SIZE = 128 VENDOR, PRODUCT = 0x10c4, 0xea61 REQTYPE_HOST_TO_INTERFACE = 0x41 REQTYPE_INTERFACE_TO_HOST = 0xc1 REQTYPE_HOST_TO_DEVICE = 0x40 REQTYPE_DEVICE_TO_HOST = 0xc0 FORMAT = '!' + 'BBBBBHBBB' + 'BBHB' 'hh' 'HH' 'hh' 'BhH' XFORMAT = '!' + 'BBBBBHxxx' + 'BBHB' 'hh' 'HH' 'hh' 'xhH' # Some magic values that were found out by listening the USB. DOWNLOAD_INIT_CMD = '0f0000'.decode('hex') DOWNLOAD_INIT_RES_PRFIX = 0xf DOWNLOAD_CHUNK_OK_RES = 'fe0100'.decode('hex') _Settings = namedtuple('SettingsPacket', ''' year month day hour min sec rec_int alm_int smpl_int auto temp_high temp_low hum_high hum_low pressure_high pressure_low alt samples ''') class SettingsPacket(_Settings): def pack(self): return pack(FORMAT, self.sec, self.min, self.hour, # pylint: disable=E1101 self.day, self.month, self.year, # pylint: disable=E1101 0xff, 0xff, 0xff, self.rec_int if self.rec_int else 0xff, # pylint: disable=E1101 self.alm_int if self.alm_int else 0xff, # pylint: disable=E1101 self.smpl_int, self.auto, # pylint: disable=E1101 self.temp_high * 100, self.temp_low * 100, # pylint: disable=E1101 self.hum_high * 10, self.hum_low * 10, # pylint: disable=E1101 self.pressure_high * 10 - 10132, # pylint: disable=E1101 self.pressure_low * 10 - 10132, # pylint: disable=E1101 0x5a, self.alt, self.samples) # pylint: disable=E1101 @classmethod def unpack(cls, data): packet = unpack(XFORMAT, data) return cls(*packet) def split_every(n, iterable): i = iter(iterable) while True: piece = list(islice(i, n)) if not piece: break yield piece def data_parser(reader): ''' Parses the output of reader, yielding pressure, temp and humidity values. ''' pres = lambda x: (x + 10132) / 10. temp = lambda x: x/10. hum = lambda x: x/10. # One measurement is 6 bytes. measurements = split_every(6, chain.from_iterable(reader)) # The chain returns list, when unpack needs strings. measurements = (''.join(m) for m in measurements) # Unpack the values. measurements = (unpack('!hHh', m) for m in measurements) # Transform them into floats. measurements = ((pres(p), temp(t), hum(h)) for p, t, h in measurements) return measurements class DT174BError(Exception): pass class DT174B(object): def __init__(self): self.LOGGER = logging.getLogger('DT174B') self.start() def start(self): # Find our device. self.dev = usb.core.find(idVendor=VENDOR, idProduct=PRODUCT) if self.dev is None: raise DT174BError('Device %s:%s not found.', VENDOR, PRODUCT) # Try detaching the kernel driver. try: if self.dev.is_kernel_driver_active(0): self.dev.detach_kernel_driver(0) except usb.USBError as e: self.LOGGER.warning("Couldn't detach the kernel driver: %s", e) self.dev.set_configuration() self.cfg = self.dev.get_active_configuration() self.iep, self.oep = self._get_eps() def reset(self): # NOTE: [http://libusb.sourceforge.net/doc/function.usbreset.html] # Causes re-enumeration: After calling usb_reset, the device will # need to re-enumerate and thusly, requires you to find the new device # and open a new handle. The handle used to call usb_reset will no # longer work. self.dev.reset() self.start() def read_log(self): LOGGER = logging.getLogger('DT174B.read_log') with self._temporary_device_state(0x2, 0x4): # Retrieve the settings packet. self._write_oep(DOWNLOAD_INIT_CMD) cmd, total = unpack('>BH', self._read_iep(BUF_SIZE)) assert cmd == DOWNLOAD_INIT_RES_PRFIX, 'cmd was %s' % hex(cmd) settings_pkt = self._read_iep(BUF_SIZE) LOGGER.debug(settings_pkt.encode('hex')) # Parse the settings packet. settings = SettingsPacket.unpack(settings_pkt) LOGGER.info('Settings: %s', settings) i = 0 remaining = total while 0 < remaining: i += 1 wdata = pack('BBB', 0x0f, i, 0) self._write_oep(wdata) assert DOWNLOAD_CHUNK_OK_RES == self._read_iep(BUF_SIZE) LOGGER.info('Bytes remaining: %d, read %s, total %s.', remaining, total - remaining, total) try: for _ in range(4): if remaining <= 0: break buf = self._read_iep(BUF_SIZE, timeout=100) remaining -= len(buf) yield buf except usb.USBError as e: if e.message != 'Operation timed out': raise LOGGER.info('Bytes remaining: %d, read %s, total %s.', remaining, total - remaining, total) @contextmanager def _temporary_device_state(self, pre_state, post_state): ''' The device seems to be listening to commands only after it has been put to some special state. This context manager ensures the device is first set to the state `pre_state` -- the temporary state. Then it yields. After the real work is done, it finally sets the device to `post_state`. ''' try: self.LOGGER.debug('Setting device to state %s.', hex(pre_state)) self._send_control(REQTYPE_HOST_TO_DEVICE, 2, pre_state) yield finally: self.LOGGER.debug('Setting device to state %s.', hex(post_state)) self._send_control(REQTYPE_HOST_TO_DEVICE, 2, post_state) def send_settings(self, packet): # The function of the 0xffff command is unknown. Following code hunk is # probably redundant. We are only simulating the windows driver there. try: self._send_control(REQTYPE_HOST_TO_DEVICE, 0, 0xffff) except usb.USBError: # Pipe Error pass with self._temporary_device_state(0x2, 0x4): assert 3 == self._write_oep('0e4000'.decode('hex')) self._write_oep(packet.pack()) assert '\xff' == self._read_iep(BUF_SIZE) def _get_eps(self): interface_number = self.cfg[(0, 0)].bInterfaceNumber alternate_setting = usb.control.get_interface( self.dev, interface_number) self.intf = intf = usb.util.find_descriptor( self.cfg, bInterfaceNumber = interface_number, bAlternateSetting = alternate_setting ) iep = usb.util.find_descriptor( intf, custom_match = \ lambda e: \ usb.util.endpoint_direction(e.bEndpointAddress) == \ usb.util.ENDPOINT_IN ) oep = usb.util.find_descriptor( intf, custom_match = \ lambda e: \ usb.util.endpoint_direction(e.bEndpointAddress) == \ usb.util.ENDPOINT_OUT ) assert all((iep, oep)) return iep, oep def _send_control(self, *args, **kwargs): ''' params: see ctrl_transfer bmRequestType, bRequest, wValue=0, wIndex=0, data_or_wLength=None, timeout=None ''' LOGGER = logging.getLogger('DT174B.control') try: self.dev.ctrl_transfer(*args, **kwargs) except usb.USBError as e: if e.errno != 32: raise else: LOGGER.error(e) def _write_oep(self, data): LOGGER = logging.getLogger('DT174B.write') LOGGER.debug('> %s', data.encode('hex')) return self.oep.write(data) def _read_iep(self, *args, **kwargs): data = self.iep.read(*args, **kwargs).tostring() LOGGER = logging.getLogger('DT174B.read') LOGGER.debug('< %s', data.encode('hex')) return data def __del__(self): self.close() def close(self): usb.util.release_interface(self.dev, self.intf)
gpl-3.0
supriyantomaftuh/syzygy
third_party/numpy/files/numpy/lib/benchmarks/benchmark.py
45
1366
from timeit import Timer class Benchmark(dict): """Benchmark a feature in different modules.""" def __init__(self,modules,title='',runs=3,reps=1000): self.module_test = dict((m,'') for m in modules) self.runs = runs self.reps = reps self.title = title def __setitem__(self,module,(test_str,setup_str)): """Set the test code for modules.""" if module == 'all': modules = self.module_test.keys() else: modules = [module] for m in modules: setup_str = 'import %s; import %s as np; ' % (m,m) \ + setup_str self.module_test[m] = Timer(test_str, setup_str) def run(self): """Run the benchmark on the different modules.""" module_column_len = max(len(mod) for mod in self.module_test) if self.title: print self.title print 'Doing %d runs, each with %d reps.' % (self.runs,self.reps) print '-'*79 for mod in sorted(self.module_test): modname = mod.ljust(module_column_len) try: print "%s: %s" % (modname, \ self.module_test[mod].repeat(self.runs,self.reps)) except Exception, e: print "%s: Failed to benchmark (%s)." % (modname,e) print '-'*79 print
apache-2.0
sammerry/ansible
lib/ansible/plugins/lookup/redis_kv.py
69
2504
# (c) 2012, Jan-Piet Mens <jpmens(at)gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import re HAVE_REDIS=False try: import redis # https://github.com/andymccurdy/redis-py/ HAVE_REDIS=True except ImportError: pass from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase # ============================================================== # REDISGET: Obtain value from a GET on a Redis key. Terms # expected: 0 = URL, 1 = Key # URL may be empty, in which case redis://localhost:6379 assumed # -------------------------------------------------------------- class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): if not HAVE_REDIS: raise AnsibleError("Can't LOOKUP(redis_kv): module redis is not installed") if not isinstance(terms, list): terms = [ terms ] ret = [] for term in terms: (url,key) = term.split(',') if url == "": url = 'redis://localhost:6379' # urlsplit on Python 2.6.1 is broken. Hmm. Probably also the reason # Redis' from_url() doesn't work here. p = '(?P<scheme>[^:]+)://?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' try: m = re.search(p, url) host = m.group('host') port = int(m.group('port')) except AttributeError: raise AnsibleError("Bad URI in redis lookup") try: conn = redis.Redis(host=host, port=port) res = conn.get(key) if res is None: res = "" ret.append(res) except: ret.append("") # connection failed or key not found return ret
gpl-3.0
sodafree/backend
build/lib.linux-i686-2.7/django/core/cache/backends/dummy.py
209
1229
"Dummy cache backend" from django.core.cache.backends.base import BaseCache class DummyCache(BaseCache): def __init__(self, host, *args, **kwargs): BaseCache.__init__(self, *args, **kwargs) def add(self, key, value, timeout=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) return True def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) return default def set(self, key, value, timeout=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) def delete(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) def get_many(self, keys, version=None): return {} def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) return False def set_many(self, data, timeout=0, version=None): pass def delete_many(self, keys, version=None): pass def clear(self): pass # For backwards compatibility class CacheClass(DummyCache): pass
bsd-3-clause
bgxavier/nova
nova/api/openstack/compute/extensions.py
35
1332
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg from oslo_log import log as logging from nova.api.openstack import extensions as base_extensions ext_opts = [ cfg.MultiStrOpt('osapi_compute_extension', default=[ 'nova.api.openstack.compute.contrib.standard_extensions' ], help='osapi compute extension to load'), ] CONF = cfg.CONF CONF.register_opts(ext_opts) LOG = logging.getLogger(__name__) class ExtensionManager(base_extensions.ExtensionManager): def __init__(self): self.cls_list = CONF.osapi_compute_extension self.extensions = {} self.sorted_ext_list = [] self._load_extensions()
apache-2.0
TalShafir/ansible
lib/ansible/modules/web_infrastructure/ansible_tower/tower_team.py
27
3178
#!/usr/bin/python # coding: utf-8 -*- # (c) 2017, Wayne Witzel III <wayne@riotousliving.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: tower_team author: "Wayne Witzel III (@wwitzel3)" version_added: "2.3" short_description: create, update, or destroy Ansible Tower team. description: - Create, update, or destroy Ansible Tower teams. See U(https://www.ansible.com/tower) for an overview. options: name: description: - Name to use for the team. required: True organization: description: - Organization the team should be made a member of. required: True state: description: - Desired state of the resource. choices: ["present", "absent"] default: "present" extends_documentation_fragment: tower ''' EXAMPLES = ''' - name: Create tower team tower_team: name: Team Name description: Team Description organization: test-org state: present tower_config_file: "~/tower_cli.cfg" ''' from ansible.module_utils.ansible_tower import TowerModule, tower_auth_config, tower_check_mode try: import tower_cli import tower_cli.utils.exceptions as exc from tower_cli.conf import settings except ImportError: pass def main(): argument_spec = dict( name=dict(required=True), description=dict(), organization=dict(required=True), state=dict(choices=['present', 'absent'], default='present'), ) module = TowerModule(argument_spec=argument_spec, supports_check_mode=True) name = module.params.get('name') description = module.params.get('description') organization = module.params.get('organization') state = module.params.get('state') json_output = {'team': name, 'state': state} tower_auth = tower_auth_config(module) with settings.runtime_values(**tower_auth): tower_check_mode(module) team = tower_cli.get_resource('team') try: org_res = tower_cli.get_resource('organization') org = org_res.get(name=organization) if state == 'present': result = team.modify(name=name, organization=org['id'], description=description, create_on_missing=True) json_output['id'] = result['id'] elif state == 'absent': result = team.delete(name=name, organization=org['id']) except (exc.NotFound) as excinfo: module.fail_json(msg='Failed to update team, organization not found: {0}'.format(excinfo), changed=False) except (exc.ConnectionError, exc.BadRequest, exc.NotFound) as excinfo: module.fail_json(msg='Failed to update team: {0}'.format(excinfo), changed=False) json_output['changed'] = result['changed'] module.exit_json(**json_output) if __name__ == '__main__': main()
gpl-3.0
marcusrehm/serenata-de-amor
jarbas/chamber_of_deputies/management/commands/receipts_text.py
2
2681
import csv import lzma import os from concurrent.futures import ThreadPoolExecutor from bulk_update.helper import bulk_update from jarbas.core.management.commands import LoadCommand from jarbas.chamber_of_deputies.models import Reimbursement class Command(LoadCommand): help = 'Load Serenata de Amor receipts text dataset' count = 0 def add_arguments(self, parser): super().add_arguments(parser, add_drop_all=False) parser.add_argument( '--batch-size', '-b', dest='batch_size', type=int, default=4096, help='Batch size for bulk update (default: 4096)' ) def handle(self, *args, **options): self.queue = [] self.path = options['dataset'] self.batch_size = options['batch_size'] if not os.path.exists(self.path): raise FileNotFoundError(os.path.abspath(self.path)) self.main() print('{:,} reimbursements updated.'.format(self.count)) def receipts(self): """Returns a Generator with batches of receipts text.""" print('Loading receipts text dataset…', end='\r') with lzma.open(self.path, mode='rt') as file_handler: batch = [] for row in csv.DictReader(file_handler): batch.append(self.serialize(row)) if len(batch) >= self.batch_size: yield batch batch = [] yield batch def serialize(self, row): """ Reads the dict generated by DictReader and returns another dict with the `document_id` and with data about the receipts text. """ document_id = self.to_number(row.get('document_id'), cast=int) receipt_text = row.get('text') return dict( document_id=document_id, receipt_text=receipt_text, ) def main(self): for batch in self.receipts(): with ThreadPoolExecutor(max_workers=32) as executor: executor.map(self.schedule_update, batch) self.update() def schedule_update(self, content): document_id = content.get('document_id') try: reimbursement = Reimbursement.objects.get(document_id=document_id) except Reimbursement.DoesNotExist: pass else: reimbursement.receipt_text = content.get('receipt_text') self.queue.append(reimbursement) def update(self): fields = ['receipt_text', ] bulk_update(self.queue, update_fields=fields) self.count += len(self.queue) print('{:,} reimbursements updated.'.format(self.count), end='\r') self.queue = []
mit
mshuler/cassandra
pylib/cqlshlib/test/basecase.py
21
3011
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import logging from os.path import dirname, join, normpath cqlshlog = logging.getLogger('test_cqlsh') try: # a backport of python2.7 unittest features, so we can test against older # pythons as necessary. python2.7 users who don't care about testing older # versions need not install. import unittest2 as unittest except ImportError: import unittest rundir = dirname(__file__) cqlshdir = normpath(join(rundir, '..', '..', '..', 'bin')) path_to_cqlsh = normpath(join(cqlshdir, 'cqlsh.py')) sys.path.append(cqlshdir) import cqlsh cql = cqlsh.cassandra.cluster.Cluster policy = cqlsh.cassandra.policies.RoundRobinPolicy() quote_name = cqlsh.cassandra.metadata.maybe_escape_name TEST_HOST = os.environ.get('CQL_TEST_HOST', '127.0.0.1') TEST_PORT = int(os.environ.get('CQL_TEST_PORT', 9042)) class BaseTestCase(unittest.TestCase): def assertNicelyFormattedTableHeader(self, line, msg=None): return self.assertRegex(line, r'^ +\w+( +\| \w+)*\s*$', msg=msg) def assertNicelyFormattedTableRule(self, line, msg=None): return self.assertRegex(line, r'^-+(\+-+)*\s*$', msg=msg) def assertNicelyFormattedTableData(self, line, msg=None): return self.assertRegex(line, r'^ .* \| ', msg=msg) def assertRegex(self, text, regex, msg=None): """Call assertRegexpMatches() if in Python 2""" if hasattr(unittest.TestCase, 'assertRegex'): return super().assertRegex(text, regex, msg) else: return self.assertRegexpMatches(text, regex, msg) def assertNotRegex(self, text, regex, msg=None): """Call assertNotRegexpMatches() if in Python 2""" if hasattr(unittest.TestCase, 'assertNotRegex'): return super().assertNotRegex(text, regex, msg) else: return self.assertNotRegexpMatches(text, regex, msg) def dedent(s): lines = [ln.rstrip() for ln in s.splitlines()] if lines[0] == '': lines = lines[1:] spaces = [len(line) - len(line.lstrip()) for line in lines if line] minspace = min(spaces if len(spaces) > 0 else (0,)) return '\n'.join(line[minspace:] for line in lines) def at_a_time(i, num): return zip(*([iter(i)] * num))
apache-2.0
boooka/GeoPowerOff
venv/lib/python2.7/site-packages/django/utils/deconstruct.py
70
2066
from __future__ import absolute_import # Avoid importing `importlib` from this package. from importlib import import_module def deconstructible(*args, **kwargs): """ Class decorator that allow the decorated class to be serialized by the migrations subsystem. Accepts an optional kwarg `path` to specify the import path. """ path = kwargs.pop('path', None) def decorator(klass): def __new__(cls, *args, **kwargs): # We capture the arguments to make returning them trivial obj = super(klass, cls).__new__(cls) obj._constructor_args = (args, kwargs) return obj def deconstruct(obj): """ Returns a 3-tuple of class import path, positional arguments, and keyword arguments. """ # Python 2/fallback version if path: module_name, _, name = path.rpartition('.') else: module_name = obj.__module__ name = obj.__class__.__name__ # Make sure it's actually there and not an inner class module = import_module(module_name) if not hasattr(module, name): raise ValueError( "Could not find object %s in %s.\n" "Please note that you cannot serialize things like inner " "classes. Please move the object into the main module " "body to use migrations.\n" "For more information, see " "https://docs.djangoproject.com/en/dev/topics/migrations/#serializing-values" % (name, module_name)) return ( path or '%s.%s' % (obj.__class__.__module__, name), obj._constructor_args[0], obj._constructor_args[1], ) klass.__new__ = staticmethod(__new__) klass.deconstruct = deconstruct return klass if not args: return decorator return decorator(*args, **kwargs)
apache-2.0
EvanK/ansible
lib/ansible/modules/network/ovs/openvswitch_port.py
102
8041
#!/usr/bin/python # coding: utf-8 -*- # (c) 2013, David Stygstra <david.stygstra@gmail.com> # Portions copyright @ 2015 VMware, Inc. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = ''' --- module: openvswitch_port version_added: 1.4 author: "David Stygstra (@stygstra)" short_description: Manage Open vSwitch ports requirements: [ ovs-vsctl ] description: - Manage Open vSwitch ports options: bridge: required: true description: - Name of bridge to manage port: required: true description: - Name of port to manage on the bridge tag: version_added: 2.2 description: - VLAN tag for this port. Must be a value between 0 and 4095. state: default: "present" choices: [ present, absent ] description: - Whether the port should exist timeout: default: 5 description: - How long to wait for ovs-vswitchd to respond external_ids: version_added: 2.0 default: {} description: - Dictionary of external_ids applied to a port. set: version_added: 2.0 description: - Set a single property on a port. ''' EXAMPLES = ''' # Creates port eth2 on bridge br-ex - openvswitch_port: bridge: br-ex port: eth2 state: present # Creates port eth6 - openvswitch_port: bridge: bridge-loop port: eth6 state: present set: Interface eth6 # Creates port vlan10 with tag 10 on bridge br-ex - openvswitch_port: bridge: br-ex port: vlan10 tag: 10 state: present set: Interface vlan10 # Assign interface id server1-vifeth6 and mac address 00:00:5E:00:53:23 # to port vifeth6 and setup port to be managed by a controller. - openvswitch_port: bridge: br-int port: vifeth6 state: present args: external_ids: iface-id: '{{ inventory_hostname }}-vifeth6' attached-mac: '00:00:5E:00:53:23' vm-id: '{{ inventory_hostname }}' iface-status: active ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six import iteritems def _external_ids_to_dict(text): text = text.strip() if text == '{}': return None else: d = {} for kv in text[1:-1].split(','): kv = kv.strip() k, v = kv.split('=') d[k] = v return d def _tag_to_str(text): text = text.strip() if text == '[]': return None else: return text def map_obj_to_commands(want, have, module): commands = list() if module.params['state'] == 'absent': if have: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s del-port" " %(bridge)s %(port)s") command = templatized_command % module.params commands.append(command) else: if have: if want['tag'] != have['tag']: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s" " set port %(port)s tag=%(tag)s") command = templatized_command % module.params commands.append(command) if want['external_ids'] != have['external_ids']: for k, v in iteritems(want['external_ids']): if (not have['external_ids'] or k not in have['external_ids'] or want['external_ids'][k] != have['external_ids'][k]): if v is None: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s" " remove port %(port)s" " external_ids " + k) command = templatized_command % module.params commands.append(command) else: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s" " set port %(port)s" " external_ids:") command = templatized_command % module.params command += k + "=" + v commands.append(command) else: templatized_command = ("%(ovs-vsctl)s -t %(timeout)s add-port" " %(bridge)s %(port)s") command = templatized_command % module.params if want['tag']: templatized_command = " tag=%(tag)s" command += templatized_command % module.params if want['set']: templatized_command = " -- set %(set)s" command += templatized_command % module.params commands.append(command) if want['external_ids']: for k, v in iteritems(want['external_ids']): templatized_command = ("%(ovs-vsctl)s -t %(timeout)s" " set port %(port)s external_ids:") command = templatized_command % module.params command += k + "=" + v commands.append(command) return commands def map_config_to_obj(module): templatized_command = "%(ovs-vsctl)s -t %(timeout)s list-ports %(bridge)s" command = templatized_command % module.params rc, out, err = module.run_command(command, check_rc=True) if rc != 0: module.fail_json(msg=err) obj = {} if module.params['port'] in out.splitlines(): obj['bridge'] = module.params['bridge'] obj['port'] = module.params['port'] templatized_command = ("%(ovs-vsctl)s -t %(timeout)s get" " Port %(port)s tag") command = templatized_command % module.params rc, out, err = module.run_command(command, check_rc=True) obj['tag'] = _tag_to_str(out) templatized_command = ("%(ovs-vsctl)s -t %(timeout)s get" " Port %(port)s external_ids") command = templatized_command % module.params rc, out, err = module.run_command(command, check_rc=True) obj['external_ids'] = _external_ids_to_dict(out) return obj def map_params_to_obj(module): obj = { 'bridge': module.params['bridge'], 'port': module.params['port'], 'tag': module.params['tag'], 'external_ids': module.params['external_ids'], 'set': module.params['set'] } return obj def main(): """ Entry point. """ argument_spec = { 'bridge': {'required': True}, 'port': {'required': True}, 'state': {'default': 'present', 'choices': ['present', 'absent']}, 'timeout': {'default': 5, 'type': 'int'}, 'external_ids': {'default': None, 'type': 'dict'}, 'tag': {'default': None}, 'set': {'required': False, 'default': None} } module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) result = {'changed': False} # We add ovs-vsctl to module_params to later build up templatized commands module.params["ovs-vsctl"] = module.get_bin_path("ovs-vsctl", True) want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands(want, have, module) result['commands'] = commands if commands: if not module.check_mode: for c in commands: module.run_command(c, check_rc=True) result['changed'] = True module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
henrytao-me/openerp.positionq
openerp/addons/project_timesheet/__init__.py
441
1084
# -*- 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 project_timesheet import report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
rawodb/bitcoin
test/functional/rpc_bind.py
9
6033
#!/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. """Test running bitcoind with the -rpcbind and -rpcallowip options.""" import sys from test_framework.test_framework import BitcoinTestFramework, SkipTest from test_framework.util import * from test_framework.netutil import * class RPCBindTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.bind_to_localhost_only = False self.num_nodes = 1 def setup_network(self): self.add_nodes(self.num_nodes, None) def add_options(self, parser): parser.add_option("--ipv4", action='store_true', dest="run_ipv4", help="Run ipv4 tests only", default=False) parser.add_option("--ipv6", action='store_true', dest="run_ipv6", help="Run ipv6 tests only", default=False) parser.add_option("--nonloopback", action='store_true', dest="run_nonloopback", help="Run non-loopback tests only", default=False) def run_bind_test(self, allow_ips, connect_to, addresses, expected): ''' Start a node with requested rpcallowip and rpcbind parameters, then try to connect, and check if the set of bound addresses matches the expected set. ''' self.log.info("Bind test for %s" % str(addresses)) expected = [(addr_to_hex(addr), port) for (addr, port) in expected] base_args = ['-disablewallet', '-nolisten'] if allow_ips: base_args += ['-rpcallowip=' + x for x in allow_ips] binds = ['-rpcbind='+addr for addr in addresses] self.nodes[0].rpchost = connect_to self.start_node(0, base_args + binds) pid = self.nodes[0].process.pid assert_equal(set(get_bind_addrs(pid)), set(expected)) self.stop_nodes() def run_allowip_test(self, allow_ips, rpchost, rpcport): ''' Start a node with rpcallow IP, and request getnetworkinfo at a non-localhost IP. ''' self.log.info("Allow IP test for %s:%d" % (rpchost, rpcport)) base_args = ['-disablewallet', '-nolisten'] + ['-rpcallowip='+x for x in allow_ips] self.nodes[0].rpchost = None self.start_nodes([base_args]) # connect to node through non-loopback interface node = get_rpc_proxy(rpc_url(self.nodes[0].datadir, 0, "%s:%d" % (rpchost, rpcport)), 0, coveragedir=self.options.coveragedir) node.getnetworkinfo() self.stop_nodes() def run_test(self): # due to OS-specific network stats queries, this test works only on Linux if sum([self.options.run_ipv4, self.options.run_ipv6, self.options.run_nonloopback]) > 1: raise AssertionError("Only one of --ipv4, --ipv6 and --nonloopback can be set") self.log.info("Check for linux") if not sys.platform.startswith('linux'): raise SkipTest("This test can only be run on linux.") self.log.info("Check for ipv6") have_ipv6 = test_ipv6_local() if not have_ipv6 and not self.options.run_ipv4: raise SkipTest("This test requires ipv6 support.") self.log.info("Check for non-loopback interface") self.non_loopback_ip = None for name,ip in all_interfaces(): if ip != '127.0.0.1': self.non_loopback_ip = ip break if self.non_loopback_ip is None and self.options.run_nonloopback: raise SkipTest("This test requires a non-loopback ip address.") self.defaultport = rpc_port(0) if not self.options.run_nonloopback: self._run_loopback_tests() if not self.options.run_ipv4 and not self.options.run_ipv6: self._run_nonloopback_tests() def _run_loopback_tests(self): if self.options.run_ipv4: # check only IPv4 localhost (explicit) self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1'], [('127.0.0.1', self.defaultport)]) # check only IPv4 localhost (explicit) with alternative port self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171'], [('127.0.0.1', 32171)]) # check only IPv4 localhost (explicit) with multiple alternative ports on same host self.run_bind_test(['127.0.0.1'], '127.0.0.1:32171', ['127.0.0.1:32171', '127.0.0.1:32172'], [('127.0.0.1', 32171), ('127.0.0.1', 32172)]) else: # check default without rpcallowip (IPv4 and IPv6 localhost) self.run_bind_test(None, '127.0.0.1', [], [('127.0.0.1', self.defaultport), ('::1', self.defaultport)]) # check default with rpcallowip (IPv6 any) self.run_bind_test(['127.0.0.1'], '127.0.0.1', [], [('::0', self.defaultport)]) # check only IPv6 localhost (explicit) self.run_bind_test(['[::1]'], '[::1]', ['[::1]'], [('::1', self.defaultport)]) # check both IPv4 and IPv6 localhost (explicit) self.run_bind_test(['127.0.0.1'], '127.0.0.1', ['127.0.0.1', '[::1]'], [('127.0.0.1', self.defaultport), ('::1', self.defaultport)]) def _run_nonloopback_tests(self): self.log.info("Using interface %s for testing" % self.non_loopback_ip) # check only non-loopback interface self.run_bind_test([self.non_loopback_ip], self.non_loopback_ip, [self.non_loopback_ip], [(self.non_loopback_ip, self.defaultport)]) # Check that with invalid rpcallowip, we are denied self.run_allowip_test([self.non_loopback_ip], self.non_loopback_ip, self.defaultport) assert_raises_rpc_error(-342, "non-JSON HTTP response with '403 Forbidden' from server", self.run_allowip_test, ['1.1.1.1'], self.non_loopback_ip, self.defaultport) if __name__ == '__main__': RPCBindTest().main()
mit
zy02636/emacs-config
python-libs/ropemacs/__init__.py
7
19234
"""ropemacs, an emacs mode for using rope refactoring library""" import sys import ropemode.decorators import ropemode.environment import ropemode.interface from Pymacs import lisp from rope.base import utils class LispUtils(ropemode.environment.Environment): def ask(self, prompt, default=None, starting=None): if default is not None: prompt = prompt + ('[%s] ' % default) result = lisp.read_from_minibuffer(prompt, starting, None, None, None, default, None) if result == '' and default is not None: return default return result def ask_values(self, prompt, values, default=None, starting=None, exact=True): if self._emacs_version() < 22: values = [[value, value] for value in values] if exact and default is not None: prompt = prompt + ('[%s] ' % default) reader = lisp['ropemacs-completing-read-function'].value() result = reader(prompt, values, None, exact, starting) if result == '' and exact: return default return result def ask_completion(self, prompt, values, starting=None): return self.ask_values(prompt, values, starting=starting, exact=None) def ask_directory(self, prompt, default=None, starting=None): location = starting or default if location is not None: prompt = prompt + ('[%s] ' % location) if lisp.fboundp(lisp['read-directory-name']): # returns default when starting is entered result = lisp.read_directory_name(prompt, location, location) else: result = lisp.read_file_name(prompt, location, location) if result == '' and location is not None: return location return result def message(self, msg): message(msg) def yes_or_no(self, prompt): return lisp.yes_or_no_p(prompt) def y_or_n(self, prompt): return lisp.y_or_n_p(prompt) def get(self, name, default=None): lispname = 'ropemacs-' + name.replace('_', '-') if lisp.boundp(lisp[lispname]): return lisp[lispname].value() return default def get_offset(self): return lisp.point() - 1 def get_text(self): end = lisp.buffer_size() + 1 old_min = lisp.point_min() old_max = lisp.point_max() narrowed = (old_min != 1 or old_max != end) if narrowed: lisp.narrow_to_region(1, lisp.buffer_size() + 1) try: return lisp.buffer_string() finally: if narrowed: lisp.narrow_to_region(old_min, old_max) def get_region(self): offset1 = self.get_offset() lisp.exchange_point_and_mark() offset2 = self.get_offset() lisp.exchange_point_and_mark() return min(offset1, offset2), max(offset1, offset2) def filename(self): return lisp.buffer_file_name() def is_modified(self): return lisp.buffer_modified_p() def goto_line(self, lineno): lisp.goto_line(lineno) def insert_line(self, line, lineno): current = lisp.point() lisp.goto_line(lineno) lisp.insert(line + '\n') lisp.goto_char(current + len(line) + 1) def insert(self, text): lisp.insert(text) def delete(self, start, end): lisp.delete_region(start, end) def filenames(self): result = [] for buffer in lisp.buffer_list(): filename = lisp.buffer_file_name(buffer) if filename: result.append(filename) return result def save_files(self, filenames): ask = self.get('confirm_saving') initial = lisp.current_buffer() for filename in filenames: buffer = lisp.find_buffer_visiting(filename) if buffer: if lisp.buffer_modified_p(buffer): if not ask or lisp.y_or_n_p('Save %s buffer?' % filename): lisp.set_buffer(buffer) lisp.save_buffer() lisp.set_buffer(initial) def reload_files(self, filenames, moves={}): if self.filename() in moves: initial = None else: initial = lisp.current_buffer() for filename in filenames: buffer = lisp.find_buffer_visiting(filename) if buffer: if filename in moves: lisp.kill_buffer(buffer) lisp.find_file(moves[filename]) else: lisp.set_buffer(buffer) lisp.revert_buffer(False, True) if initial is not None: lisp.set_buffer(initial) def find_file(self, filename, readonly=False, other=False): if other: lisp.find_file_other_window(filename) elif readonly: lisp.find_file_read_only(filename) else: lisp.find_file(filename) def _make_buffer(self, name, contents, empty_goto=True, switch=False, window='other', modes=[], fit_lines=None): """Make an emacs buffer `window` can be one of `None`, 'current' or 'other'. """ new_buffer = lisp.get_buffer_create(name) lisp.set_buffer(new_buffer) lisp.toggle_read_only(-1) lisp.erase_buffer() if contents or empty_goto: lisp.insert(contents) for mode in modes: lisp[mode + '-mode']() lisp.buffer_disable_undo(new_buffer) lisp.toggle_read_only(1) if switch: if window == 'current': lisp.switch_to_buffer(new_buffer) else: lisp.switch_to_buffer_other_window(new_buffer) lisp.goto_char(lisp.point_min()) elif window == 'other': new_window = lisp.display_buffer(new_buffer) lisp.set_window_point(new_window, lisp.point_min()) if fit_lines and lisp.fboundp(lisp['fit-window-to-buffer']): lisp.fit_window_to_buffer(new_window, fit_lines) lisp.bury_buffer(new_buffer) return new_buffer def _hide_buffer(self, name, delete=True): buffer = lisp.get_buffer(name) if buffer is not None: window = lisp.get_buffer_window(buffer) if window is not None: lisp.bury_buffer(buffer) if delete: lisp.delete_window(window) else: if lisp.buffer_name(lisp.current_buffer()) == name: lisp.switch_to_buffer(None) def _emacs_version(self): return int(lisp['emacs-version'].value().split('.')[0]) def create_progress(self, name): if lisp.fboundp(lisp['make-progress-reporter']): progress = _LispProgress(name) else: progress = _OldProgress(name) return progress def current_word(self): return lisp.current_word() def push_mark(self): lisp.push_mark() def prefix_value(self, prefix): return lisp.prefix_numeric_value(prefix) def show_occurrences(self, locations): text = ['List of occurrences:', ''] for location in locations: line = '%s : %s %s %s' % (location.filename, location.lineno, location.note, location.offset) text.append(line) text = '\n'.join(text) + '\n' buffer = self._make_buffer('*rope-occurrences*', text, switch=False) lisp.set_buffer(buffer) lisp.toggle_read_only(1) lisp.set(lisp["next-error-function"], lisp.rope_occurrences_next) lisp.local_set_key('\r', lisp.rope_occurrences_goto) lisp.local_set_key('q', lisp.delete_window) def show_doc(self, docs, altview=False): use_minibuffer = not altview if self.get('separate_doc_buffer'): use_minibuffer = not use_minibuffer if not use_minibuffer: fit_lines = self.get('max_doc_buffer_height') buffer = self._make_buffer('*rope-pydoc*', docs, empty_goto=False, fit_lines=fit_lines) lisp.local_set_key('q', lisp.bury_buffer) elif docs: docs = '\n'.join(docs.split('\n')[:7]) self.message(docs) def preview_changes(self, diffs): self._make_buffer('*rope-preview*', diffs, switch=True, modes=['diff'], window='current') try: return self.yes_or_no('Do the changes? ') finally: self._hide_buffer('*rope-preview*', delete=False) def local_command(self, name, callback, key=None, prefix=False): globals()[name] = callback self._set_interaction(callback, prefix) if self.local_prefix and key: key = self._key_sequence(self.local_prefix + ' ' + key) self._bind_local(_lisp_name(name), key) def _bind_local(self, name, key): lisp('(define-key ropemacs-local-keymap "%s" \'%s)' % (self._key_sequence(key), name)) def global_command(self, name, callback, key=None, prefix=False): globals()[name] = callback self._set_interaction(callback, prefix) if self.global_prefix and key: key = self._key_sequence(self.global_prefix + ' ' + key) lisp.global_set_key(key, lisp[_lisp_name(name)]) def _key_sequence(self, sequence): result = [] for key in sequence.split(): if key.startswith('C-'): number = ord(key[-1].upper()) - ord('A') + 1 result.append(chr(number)) elif key.startswith('M-'): number = ord(key[-1].upper()) + 0x80 result.append(chr(number)) else: result.append(key) return ''.join(result) def _set_interaction(self, callback, prefix): if hasattr(callback, 'im_func'): callback = callback.im_func if prefix: callback.interaction = 'P' else: callback.interaction = '' def add_hook(self, name, callback, hook): mapping = {'before_save': 'before-save-hook', 'after_save': 'after-save-hook', 'exit': 'kill-emacs-hook'} globals()[name] = callback lisp.add_hook(lisp[mapping[hook]], lisp[_lisp_name(name)]) def project_opened(self): ''' This method is called when a new project is opened, it runs the hooks associated with rope-open-project-hook. ''' lisp.run_hooks(lisp["rope-open-project-hook"]) @property @utils.saveit def global_prefix(self): return self.get('global_prefix') @property @utils.saveit def local_prefix(self): return self.get('local_prefix') def _lisp_name(name): return 'rope-' + name.replace('_', '-') class _LispProgress(object): def __init__(self, name): self.progress = lisp.make_progress_reporter('%s ... ' % name, 0, 100) def update(self, percent): lisp.progress_reporter_update(self.progress, percent) def done(self): lisp.progress_reporter_done(self.progress) class _OldProgress(object): def __init__(self, name): self.name = name self.update(0) def update(self, percent): if percent != 0: message('%s ... %s%%%%' % (self.name, percent)) else: message('%s ... ' % self.name) def done(self): message('%s ... done' % self.name) def message(message): lisp.message(message.replace('%', '%%')) def occurrences_goto(): if lisp.line_number_at_pos() < 3: lisp.forward_line(3 - lisp.line_number_at_pos()) lisp.end_of_line() end = lisp.point() lisp.beginning_of_line() line = lisp.buffer_substring_no_properties(lisp.point(), end) tokens = line.split() if tokens: filename = tokens[0] offset = int(tokens[-1]) resource = _interface._get_resource(filename) LispUtils().find_file(resource.real_path, other=True) lisp.goto_char(offset + 1) occurrences_goto.interaction = '' def occurrences_next(arg, reset): lisp.switch_to_buffer_other_window('*rope-occurrences*', True) if reset: lisp.goto_char(lisp.point_min()) lisp.forward_line(arg) if lisp.eobp(): lisp.message("Cycling rope occurences") lisp.goto_char(lisp.point_min()) occurrences_goto() occurrences_next.interaction = '' DEFVARS = """\ (defgroup ropemacs nil "ropemacs, an emacs plugin for rope." :link '(url-link "http://rope.sourceforge.net/ropemacs.html") :prefix "rope-") (defcustom ropemacs-confirm-saving t "Shows whether to confirm saving modified buffers before refactorings. If non-nil, you have to confirm saving all modified python files before refactorings; otherwise they are saved automatically.") (defcustom ropemacs-codeassist-maxfixes 1 "The number of errors to fix before code-assist. How many errors to fix, at most, when proposing code completions.") (defcustom ropemacs-separate-doc-buffer t "Should `rope-show-doc' use a separate buffer or the minibuffer.") (defcustom ropemacs-max-doc-buffer-height 22 "The maximum buffer height for `rope-show-doc'.") (defcustom ropemacs-enable-autoimport 'nil "Specifies whether autoimport should be enabled.") (defcustom ropemacs-autoimport-modules nil "The name of modules whose global names should be cached. The `rope-generate-autoimport-cache' reads this list and fills its cache.") (defcustom ropemacs-autoimport-underlineds 'nil "If set, autoimport will cache names starting with underlines, too.") (defcustom ropemacs-completing-read-function (if (and (boundp 'ido-mode) ido-mode) 'ido-completing-read 'completing-read) "Function to call when prompting user to choose between a list of options. This should take the same arguments as `completing-read'. Possible values are `completing-read' and `ido-completing-read'. Note that you must set `ido-mode' if using`ido-completing-read'." :type 'function) (make-obsolete-variable 'rope-confirm-saving 'ropemacs-confirm-saving) (make-obsolete-variable 'rope-code-assist-max-fixes 'ropemacs-codeassist-maxfixes) (defcustom ropemacs-local-prefix "C-c r" "The prefix for ropemacs refactorings. Use nil to prevent binding keys.") (defcustom ropemacs-global-prefix "C-x p" "The prefix for ropemacs project commands. Use nil to prevent binding keys.") (defcustom ropemacs-enable-shortcuts 't "Shows whether to bind ropemacs shortcuts keys. If non-nil it binds: ================ ============================ Key Command ================ ============================ M-/ rope-code-assist C-c g rope-goto-definition C-c d rope-show-doc C-c f rope-find-occurrences M-? rope-lucky-assist ================ ============================ ") (defvar ropemacs-local-keymap (make-sparse-keymap)) (easy-menu-define ropemacs-mode-menu ropemacs-local-keymap "`ropemacs' menu" '("Rope" ["Code assist" rope-code-assist t] ["Lucky assist" rope-lucky-assist t] ["Goto definition" rope-goto-definition t] ["Jump to global" rope-jump-to-global t] ["Show documentation" rope-show-doc t] ["Find Occurrences" rope-find-occurrences t] ["Analyze module" rope-analyze-module t] ("Refactor" ["Inline" rope-inline t] ["Extract Variable" rope-extract-variable t] ["Extract Method" rope-extract-method t] ["Organize Imports" rope-organize-imports t] ["Rename" rope-rename t] ["Move" rope-move t] ["Restructure" rope-restructure t] ["Use Function" rope-use-function t] ["Introduce Factory" rope-introduce-factory t] ("Generate" ["Class" rope-generate-class t] ["Function" rope-generate-function t] ["Module" rope-generate-module t] ["Package" rope-generate-package t] ["Variable" rope-generate-variable t] ) ("Module" ["Module to Package" rope-module-to-package t] ["Rename Module" rope-rename-current-module t] ["Move Module" rope-move-current-module t] ) "--" ["Undo" rope-undo t] ["Redo" rope-redo t] ) ("Project" ["Open project" rope-open-project t] ["Close project" rope-close-project t] ["Find file" rope-find-file t] ["Open project config" rope-project-config t] ) ("Create" ["Module" rope-create-module t] ["Package" rope-create-package t] ["File" rope-create-file t] ["Directory" rope-create-directory t] ) )) (defcustom ropemacs-guess-project 'nil "Try to guess the project when needed. If non-nil, ropemacs tries to guess and open the project that contains a file on which the rope command is performed when no project is already opened.") (provide 'ropemacs) """ MINOR_MODE = """\ (define-minor-mode ropemacs-mode "ropemacs, rope in emacs!" nil " Rope" ropemacs-local-keymap :global nil) ) """ shortcuts = [('M-/', 'rope-code-assist'), ('M-?', 'rope-lucky-assist'), ('C-c g', 'rope-goto-definition'), ('C-c d', 'rope-show-doc'), ('C-c f', 'rope-find-occurrences')] _interface = None def _load_ropemacs(): global _interface ropemode.decorators.logger.message = message lisp(DEFVARS) _interface = ropemode.interface.RopeMode(env=LispUtils()) _interface.init() lisp(MINOR_MODE) if LispUtils().get('enable_shortcuts'): for key, command in shortcuts: LispUtils()._bind_local(command, key) lisp.add_hook(lisp['python-mode-hook'], lisp['ropemacs-mode']) def _started_from_pymacs(): import inspect frame = sys._getframe() while frame: # checking frame.f_code.co_name == 'pymacs_load_helper' might # be very fragile. if inspect.getfile(frame).rstrip('c').endswith('pymacs.py'): return True frame = frame.f_back if _started_from_pymacs(): _load_ropemacs()
gpl-3.0
Xeralux/tensorflow
tensorflow/contrib/py2tf/impl/conversion.py
1
12693
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """High level conversion support.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.contrib.py2tf import utils from tensorflow.contrib.py2tf.converters import asserts from tensorflow.contrib.py2tf.converters import break_statements from tensorflow.contrib.py2tf.converters import builtin_functions from tensorflow.contrib.py2tf.converters import call_trees from tensorflow.contrib.py2tf.converters import continue_statements from tensorflow.contrib.py2tf.converters import control_flow from tensorflow.contrib.py2tf.converters import decorators from tensorflow.contrib.py2tf.converters import for_loops from tensorflow.contrib.py2tf.converters import ifexp from tensorflow.contrib.py2tf.converters import lists from tensorflow.contrib.py2tf.converters import logical_expressions from tensorflow.contrib.py2tf.converters import name_scopes from tensorflow.contrib.py2tf.converters import side_effect_guards from tensorflow.contrib.py2tf.converters import single_return from tensorflow.contrib.py2tf.impl import config from tensorflow.contrib.py2tf.impl import naming from tensorflow.contrib.py2tf.pyct import context from tensorflow.contrib.py2tf.pyct import inspect_utils from tensorflow.contrib.py2tf.pyct import parser from tensorflow.contrib.py2tf.pyct import qual_names from tensorflow.contrib.py2tf.pyct.static_analysis import activity from tensorflow.contrib.py2tf.pyct.static_analysis import live_values from tensorflow.contrib.py2tf.pyct.static_analysis import type_info from tensorflow.contrib.py2tf.utils import type_hints from tensorflow.python.util import tf_inspect # TODO(mdan): Might we not need any renaming at all? class ConversionMap(object): """ConversionMap keeps track of converting function hierarchies. This object is mutable, and is updated as functions are converted. Attributes: recursive: Whether to recusrively convert any functions that the decorator function may call. nocompile_decorators: tuple of decorator functions that toggle compilation off. dependency_cache: dict[object]: ast; maps original entities to their converted AST additional_imports: set(object); additional entities which for any reason cannot be attached after loading and need to be explicitly imported in the generated code name_map: dict[string]: string; maps original entities to the name of their converted counterparts api_module: A reference to the api module. The reference needs to be passed to avoid circular dependencies. """ # TODO(mdan): Rename to ConversionContext, and pull in additional flags. def __init__(self, recursive, nocompile_decorators, partial_types, api_module): self.recursive = recursive self.nocompile_decorators = nocompile_decorators self.partial_types = partial_types if partial_types else () self.dependency_cache = {} self.additional_imports = set() self.name_map = {} self.api_module = api_module def new_namer(self, namespace): return naming.Namer(namespace, self.recursive, self.name_map, self.partial_types) def update_name_map(self, namer): for o, name in namer.renamed_calls.items(): if o in self.name_map: if self.name_map[o] != name: raise ValueError( 'Calls to %s were converted using multiple names (%s). This is ' 'possible when an entity with one of these names already ' 'existed. To fix, avoid using any of these names.') else: self.name_map[o] = name def add_to_cache(self, original_entity, converted_ast): self.dependency_cache[original_entity] = converted_ast def is_whitelisted_for_graph(o): """Check whether an entity is whitelisted for use in graph mode. Examples of whitelisted entities include all members of the tensorflow package. Args: o: A Python entity. Returns: Boolean """ m = tf_inspect.getmodule(o) for prefix, in config.DEFAULT_UNCOMPILED_MODULES: if m.__name__.startswith(prefix): return True return False def entity_to_graph(o, conversion_map, arg_values, arg_types): """Compile a Python entity into equivalent TensorFlow. The function will also recursively compile all the entities that `o` references, updating `dependency_cache`. This function is reentrant, and relies on dependency_cache to avoid generating duplicate code. Args: o: A Python entity. conversion_map: A ConversionMap object. arg_values: A dict containing value hints for symbols like function parameters. arg_types: A dict containing type hints for symbols like function parameters. Returns: A tuple (ast, new_name): * ast: An AST representing an entity with interface equivalent to `o`, but which when executed it creates TF a graph. * new_name: The symbol name under which the new entity can be found. Raises: ValueError: if the entity type is not supported. """ if tf_inspect.isclass(o): node, new_name = class_to_graph(o, conversion_map) elif tf_inspect.isfunction(o): node, new_name = function_to_graph(o, conversion_map, arg_values, arg_types) elif tf_inspect.ismethod(o): node, new_name = function_to_graph(o, conversion_map, arg_values, arg_types) else: raise ValueError( 'Entity "%s" has unsupported type "%s". Only functions and classes are ' 'supported for now.' % (o, type(o))) conversion_map.add_to_cache(o, node) if conversion_map.recursive: while True: candidate = None for obj in conversion_map.name_map.keys(): if obj not in conversion_map.dependency_cache: candidate = obj break if candidate is None: break if (hasattr(candidate, 'im_class') and getattr(candidate, 'im_class') not in conversion_map.partial_types): # Class members are converted with their objects, unless they're # only converted partially. continue entity_to_graph(candidate, conversion_map, {}, {}) return node, new_name def class_to_graph(c, conversion_map): """Specialization of `entity_to_graph` for classes.""" converted_members = {} method_filter = lambda m: tf_inspect.isfunction(m) or tf_inspect.ismethod(m) members = tf_inspect.getmembers(c, predicate=method_filter) if not members: raise ValueError('Cannot convert %s: it has no member methods.' % c) class_namespace = None for _, m in members: node, _ = function_to_graph( m, conversion_map=conversion_map, arg_values={}, arg_types={'self': (c.__name__, c)}, owner_type=c) # TODO(mdan): Do not assume all members have the same view of globals. if class_namespace is None: class_namespace = inspect_utils.getnamespace(m) converted_members[m] = node namer = conversion_map.new_namer(class_namespace) class_name = namer.compiled_class_name(c.__name__, c) node = gast.ClassDef( class_name, bases=[], keywords=[], body=list(converted_members.values()), decorator_list=[]) return node, class_name def _add_self_references(namespace, api_module): """Self refs are only required for analysis and are not used directly.""" # Manually add the utils namespace which may be used from generated code. if 'py2tf_util' not in namespace: namespace['py2tf_utils'] = utils elif namespace['py2tf_utils'] != utils: raise ValueError( 'The module name "py2tf_utils" is reserved and may not be used.') # We also make reference to the api module for dynamic conversion, but # to avoid circular references we don't import it here. if 'py2tf_api' not in namespace: namespace['py2tf_api'] = api_module elif namespace['py2tf_api'] != api_module: raise ValueError( 'The module name "py2tf_api" is reserved and may not be used.') def function_to_graph(f, conversion_map, arg_values, arg_types, owner_type=None): """Specialization of `entity_to_graph` for callable functions.""" node, source = parser.parse_entity(f) node = node.body[0] namespace = inspect_utils.getnamespace(f) _add_self_references(namespace, conversion_map.api_module) namer = conversion_map.new_namer(namespace) ctx = context.EntityContext( namer=namer, source_code=source, source_file='<fragment>', namespace=namespace, arg_values=arg_values, arg_types=arg_types, owner_type=owner_type, recursive=conversion_map.recursive, type_annotation_func=type_hints.set_element_type) node, deps = node_to_graph(node, ctx, conversion_map.nocompile_decorators) # TODO(mdan): This somewhat duplicates the call rename logic in call_treest.py new_name, did_rename = namer.compiled_function_name(f.__name__, f, owner_type) if not did_rename: new_name = f.__name__ if node.name != f.__name__: raise NotImplementedError('Strange corner case. Send us offending code!') node.name = new_name conversion_map.update_name_map(namer) # TODO(mdan): Use this at compilation. conversion_map.additional_imports.update(deps) return node, new_name def _static_analysis_pass(node, ctx): node = qual_names.resolve(node) node = activity.resolve(node, ctx, None) node = live_values.resolve(node, ctx, config.PYTHON_LITERALS) node = type_info.resolve(node, ctx) return node def node_to_graph(node, ctx, nocompile_decorators): """Convert Python code to equivalent TF graph mode code. Args: node: A Python AST node representing the code to convert. ctx: An EntityContext object. nocompile_decorators: A tuple containing decorators to be stripped from functions during conversion. Returns: A tuple (node, deps): * node: A Python ast node, representing the converted code. * deps: A set of strings, the fully qualified names of entity dependencies that this node has. """ # TODO(mdan): Verify arguments for correctness. # TODO(mdan): Factor out common elements. # These include: # * code move between blocks # * visiting blocks in transformers # Certain steps, especially canonicalization, insert new symbols into the # tree, which must be accounted. Although less efficient, it is most robust # to re-run the analysis. node = _static_analysis_pass(node, ctx) # TODO(mdan): Clean this up. # Some intermediate analyses are not required, and some comments got orphaned. # Past this point, line numbers are no longer accurate so we ignore the # source. # TODO(mdan): Is it feasible to reconstruct intermediate source code? ctx.source_code = None node = ifexp.transform(node, ctx) node, deps = decorators.transform(node, nocompile_decorators) node = break_statements.transform(node, ctx) node = asserts.transform(node, ctx) # Note: sequencing continue canonicalization before for loop one avoids # dealing with the extra loop increment operation that the for # canonicalization creates. node = continue_statements.transform(node, ctx) ctx.namespace['len'] = len node = _static_analysis_pass(node, ctx) node = single_return.transform(node, ctx) node = _static_analysis_pass(node, ctx) node = lists.transform(node, ctx) node = for_loops.transform(node, ctx) # for_loops may insert new global references. node = builtin_functions.transform(node, ctx) node = _static_analysis_pass(node, ctx) node = call_trees.transform(node, ctx, config.DEFAULT_UNCOMPILED_MODULES, nocompile_decorators) node = control_flow.transform(node, ctx) # control_flow may create new symbols and change scopes. node = _static_analysis_pass(node, ctx) node = logical_expressions.transform(node, ctx) node = side_effect_guards.transform(node, ctx) node = name_scopes.transform(node, ctx) return node, deps
apache-2.0
rosudrag/eve-wspace
evewspace/account/tests.py
138
1244
# Eve W-Space # Copyright (C) 2013 Andrew Austin and other contributors # # 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. An additional term under section # 7 of the GPL is included in the LICENSE file. # # 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/>. """ This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
gpl-3.0
mahendra-r/edx-platform
common/lib/chem/chem/chemtools.py
250
10721
"""This module originally includes functions for grading Vsepr problems. Also, may be this module is the place for other chemistry-related grade functions. TODO: discuss it. """ import json import unittest import itertools def vsepr_parse_user_answer(user_input): """ user_input is json generated by vsepr.js from dictionary. There are must be only two keys in original user_input dictionary: "geometry" and "atoms". Format: u'{"geometry": "AX3E0","atoms":{"c0": "B","p0": "F","p1": "B","p2": "F"}}' Order of elements inside "atoms" subdict does not matters. Return dict from parsed json. "Atoms" subdict stores positions of atoms in molecule. General types of positions: c0 - central atom p0..pN - peripheral atoms a0..aN - axial atoms e0..eN - equatorial atoms Each position is dictionary key, i.e. user_input["atoms"]["c0"] is central atom, user_input["atoms"]["a0"] is one of axial atoms. Special position only for AX6 (Octahedral) geometry: e10, e12 - atom pairs opposite the central atom, e20, e22 - atom pairs opposite the central atom, e1 and e2 pairs lying crosswise in equatorial plane. In user_input["atoms"] may be only 3 set of keys: (c0,p0..pN), (c0, a0..aN, e0..eN), (c0, a0, a1, e10,e11,e20,e21) - if geometry is AX6. """ return json.loads(user_input) def vsepr_build_correct_answer(geometry, atoms): """ geometry is string. atoms is dict of atoms with proper positions. Example: correct_answer = vsepr_build_correct_answer(geometry="AX4E0", atoms={"c0": "N", "p0": "H", "p1": "(ep)", "p2": "H", "p3": "H"}) returns a dictionary composed from input values: {'geometry': geometry, 'atoms': atoms} """ return {'geometry': geometry, 'atoms': atoms} def vsepr_grade(user_input, correct_answer, convert_to_peripheral=False): """ This function does comparison between user_input and correct_answer. Comparison is successful if all steps are successful: 1) geometries are equal 2) central atoms (index in dictionary 'c0') are equal 3): In next steps there is comparing of corresponding subsets of atom positions: equatorial (e0..eN), axial (a0..aN) or peripheral (p0..pN) If convert_to_peripheral is True, then axial and equatorial positions are converted to peripheral. This means that user_input from: "atoms":{"c0": "Br","a0": "test","a1": "(ep)","e10": "H","e11": "(ep)","e20": "H","e21": "(ep)"}}' after parsing to json is converted to: {"c0": "Br", "p0": "(ep)", "p1": "test", "p2": "H", "p3": "H", "p4": "(ep)", "p6": "(ep)"} i.e. aX and eX -> pX So if converted, p subsets are compared, if not a and e subsets are compared If all subsets are equal, grade succeeds. There is also one special case for AX6 geometry. In this case user_input["atoms"] contains special 3 symbol keys: e10, e12, e20, and e21. Correct answer for this geometry can be of 3 types: 1) c0 and peripheral 2) c0 and axial and equatorial 3) c0 and axial and equatorial-subset-1 (e1X) and equatorial-subset-2 (e2X) If correct answer is type 1 or 2, then user_input is converted from type 3 to type 2 (or to type 1 if convert_to_peripheral is True) If correct_answer is type 3, then we done special case comparison. We have 3 sets of atoms positions both in user_input and correct_answer: axial, eq-1 and eq-2. Answer will be correct if these sets are equals for one of permutations. For example, if : user_axial = correct_eq-1 user_eq-1 = correct-axial user_eq-2 = correct-eq-2 """ if user_input['geometry'] != correct_answer['geometry']: return False if user_input['atoms']['c0'] != correct_answer['atoms']['c0']: return False if convert_to_peripheral: # convert user_input from (a,e,e1,e2) to (p) # correct_answer must be set in (p) using this flag c0 = user_input['atoms'].pop('c0') user_input['atoms'] = {'p' + str(i): v for i, v in enumerate(user_input['atoms'].values())} user_input['atoms']['c0'] = c0 # special case for AX6 if 'e10' in correct_answer['atoms']: # need check e1x, e2x symmetry for AX6.. a_user = {} a_correct = {} for ea_position in ['a', 'e1', 'e2']: # collecting positions: a_user[ea_position] = [v for k, v in user_input['atoms'].items() if k.startswith(ea_position)] a_correct[ea_position] = [v for k, v in correct_answer['atoms'].items() if k.startswith(ea_position)] correct = [sorted(a_correct['a'])] + [sorted(a_correct['e1'])] + [sorted(a_correct['e2'])] for permutation in itertools.permutations(['a', 'e1', 'e2']): if correct == [sorted(a_user[permutation[0]])] + [sorted(a_user[permutation[1]])] + [sorted(a_user[permutation[2]])]: return True return False else: # no need to check e1x,e2x symmetry - convert them to ex if 'e10' in user_input['atoms']: # e1x exists, it is AX6.. case e_index = 0 for k, v in user_input['atoms'].items(): if len(k) == 3: # e1x del user_input['atoms'][k] user_input['atoms']['e' + str(e_index)] = v e_index += 1 # common case for ea_position in ['p', 'a', 'e']: # collecting atoms: a_user = [v for k, v in user_input['atoms'].items() if k.startswith(ea_position)] a_correct = [v for k, v in correct_answer['atoms'].items() if k.startswith(ea_position)] # print a_user, a_correct if len(a_user) != len(a_correct): return False if sorted(a_user) != sorted(a_correct): return False return True class Test_Grade(unittest.TestCase): ''' test grade function ''' def test_incorrect_geometry(self): correct_answer = vsepr_build_correct_answer(geometry="AX4E0", atoms={"c0": "N", "p0": "H", "p1": "(ep)", "p2": "H", "p3": "H"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX3E0","atoms":{"c0": "B","p0": "F","p1": "B","p2": "F"}}') self.assertFalse(vsepr_grade(user_answer, correct_answer)) def test_correct_answer_p(self): correct_answer = vsepr_build_correct_answer(geometry="AX4E0", atoms={"c0": "N", "p0": "H", "p1": "(ep)", "p2": "H", "p3": "H"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX4E0","atoms":{"c0": "N","p0": "H","p1": "(ep)","p2": "H", "p3": "H"}}') self.assertTrue(vsepr_grade(user_answer, correct_answer)) def test_correct_answer_ae(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "test", "a1": "(ep)", "e0": "H", "e1": "H", "e2": "(ep)", "e3": "(ep)"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "test","a1": "(ep)","e10": "H","e11": "H","e20": "(ep)","e21": "(ep)"}}') self.assertTrue(vsepr_grade(user_answer, correct_answer)) def test_correct_answer_ae_convert_to_p_but_input_not_in_p(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "test", "e0": "H", "e1": "H", "e2": "(ep)", "e3": "(ep)"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "test","a1": "(ep)","e10": "H","e11": "(ep)","e20": "H","e21": "(ep)"}}') self.assertFalse(vsepr_grade(user_answer, correct_answer, convert_to_peripheral=True)) def test_correct_answer_ae_convert_to_p(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "p0": "(ep)", "p1": "test", "p2": "H", "p3": "H", "p4": "(ep)", "p6": "(ep)"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "test","a1": "(ep)","e10": "H","e11": "(ep)","e20": "H","e21": "(ep)"}}') self.assertTrue(vsepr_grade(user_answer, correct_answer, convert_to_peripheral=True)) def test_correct_answer_e1e2_in_a(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "(ep)", "e10": "H", "e11": "H", "e20": "H", "e21": "H"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "(ep)","a1": "(ep)","e10": "H","e11": "H","e20": "H","e21": "H"}}') self.assertTrue(vsepr_grade(user_answer, correct_answer)) def test_correct_answer_e1e2_in_e1(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "(ep)", "e10": "H", "e11": "H", "e20": "H", "e21": "H"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "H","a1": "H","e10": "(ep)","e11": "(ep)","e20": "H","e21": "H"}}') self.assertTrue(vsepr_grade(user_answer, correct_answer)) def test_correct_answer_e1e2_in_e2(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "(ep)", "e10": "H", "e11": "H", "e20": "H", "e21": "H"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "H","a1": "H","e10": "H","e11": "H","e20": "(ep)","e21": "(ep)"}}') self.assertTrue(vsepr_grade(user_answer, correct_answer)) def test_incorrect_answer_e1e2(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "(ep)", "e10": "H", "e11": "H", "e20": "H", "e21": "H"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "Br","a0": "H","a1": "H","e10": "(ep)","e11": "H","e20": "H","e21": "(ep)"}}') self.assertFalse(vsepr_grade(user_answer, correct_answer)) def test_incorrect_c0(self): correct_answer = vsepr_build_correct_answer(geometry="AX6E0", atoms={"c0": "Br", "a0": "(ep)", "a1": "test", "e0": "H", "e1": "H", "e2": "H", "e3": "(ep)"}) user_answer = vsepr_parse_user_answer(u'{"geometry": "AX6E0","atoms":{"c0": "H","a0": "test","a1": "(ep)","e0": "H","e1": "H","e2": "(ep)","e3": "H"}}') self.assertFalse(vsepr_grade(user_answer, correct_answer)) def suite(): testcases = [Test_Grade] suites = [] for testcase in testcases: suites.append(unittest.TestLoader().loadTestsFromTestCase(testcase)) return unittest.TestSuite(suites) if __name__ == "__main__": unittest.TextTestRunner(verbosity=2).run(suite())
agpl-3.0
mixturemodel-flow/tensorflow
tensorflow/contrib/cluster_resolver/python/training/cluster_resolver_test.py
57
8759
# 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. # ============================================================================== """Tests for Cluster Resolvers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.cluster_resolver.python.training.cluster_resolver import SimpleClusterResolver from tensorflow.contrib.cluster_resolver.python.training.cluster_resolver import UnionClusterResolver from tensorflow.python.platform import test from tensorflow.python.training import server_lib class UnionClusterResolverTest(test.TestCase): # TODO(frankchn): Transform to parameterized test after it is included in the # TF open source codebase. def _verifyClusterSpecEquality(self, cluster_spec, expected_proto): self.assertProtoEquals(expected_proto, cluster_spec.as_cluster_def()) self.assertProtoEquals( expected_proto, server_lib.ClusterSpec(cluster_spec).as_cluster_def()) self.assertProtoEquals( expected_proto, server_lib.ClusterSpec(cluster_spec.as_cluster_def()).as_cluster_def()) self.assertProtoEquals( expected_proto, server_lib.ClusterSpec(cluster_spec.as_dict()).as_cluster_def()) def testSingleClusterResolver(self): base_cluster_spec = server_lib.ClusterSpec({ "ps": ["ps0:2222", "ps1:2222"], "worker": ["worker0:2222", "worker1:2222", "worker2:2222"] }) simple_resolver = SimpleClusterResolver(base_cluster_spec) union_resolver = UnionClusterResolver(simple_resolver) expected_proto = """ job { name: 'ps' tasks { key: 0 value: 'ps0:2222' } tasks { key: 1 value: 'ps1:2222' } } job { name: 'worker' tasks { key: 0 value: 'worker0:2222' } tasks { key: 1 value: 'worker1:2222' } tasks { key: 2 value: 'worker2:2222' } } """ actual_cluster_spec = union_resolver.cluster_spec() self._verifyClusterSpecEquality(actual_cluster_spec, expected_proto) def testTwoNonOverlappingJobMergedClusterResolver(self): cluster_spec_1 = server_lib.ClusterSpec({ "ps": [ "ps0:2222", "ps1:2222" ] }) cluster_spec_2 = server_lib.ClusterSpec({ "worker": [ "worker0:2222", "worker1:2222", "worker2:2222" ] }) cluster_resolver_1 = SimpleClusterResolver(cluster_spec_1) cluster_resolver_2 = SimpleClusterResolver(cluster_spec_2) union_cluster = UnionClusterResolver(cluster_resolver_1, cluster_resolver_2) cluster_spec = union_cluster.cluster_spec() expected_proto = """ job { name: 'ps' tasks { key: 0 value: 'ps0:2222' } tasks { key: 1 value: 'ps1:2222' } } job { name: 'worker' tasks { key: 0 value: 'worker0:2222' } tasks { key: 1 value: 'worker1:2222' } tasks { key: 2 value: 'worker2:2222' } } """ self._verifyClusterSpecEquality(cluster_spec, expected_proto) def testOverlappingJobMergedClusterResolver(self): cluster_spec_1 = server_lib.ClusterSpec({ "worker": [ "worker4:2222", "worker5:2222" ] }) cluster_spec_2 = server_lib.ClusterSpec({ "worker": [ "worker0:2222", "worker1:2222", "worker2:2222" ] }) cluster_resolver_1 = SimpleClusterResolver(cluster_spec_1) cluster_resolver_2 = SimpleClusterResolver(cluster_spec_2) union_cluster = UnionClusterResolver(cluster_resolver_1, cluster_resolver_2) cluster_spec = union_cluster.cluster_spec() expected_proto = """ job { name: 'worker' tasks { key: 0 value: 'worker4:2222' } tasks { key: 1 value: 'worker5:2222' } tasks { key: 2 value: 'worker0:2222' } tasks { key: 3 value: 'worker1:2222' } tasks { key: 4 value: 'worker2:2222' } } """ self._verifyClusterSpecEquality(cluster_spec, expected_proto) def testOverlappingSparseJobMergedClusterResolverThrowError(self): cluster_spec_1 = server_lib.ClusterSpec({ "worker": { 7: "worker4:2222", 9: "worker5:2222" } }) cluster_spec_2 = server_lib.ClusterSpec({ "worker": { 3: "worker0:2222", 6: "worker1:2222", 7: "worker2:2222" } }) cluster_resolver_1 = SimpleClusterResolver(cluster_spec_1) cluster_resolver_2 = SimpleClusterResolver(cluster_spec_2) union_cluster = UnionClusterResolver(cluster_resolver_1, cluster_resolver_2) self.assertRaises(KeyError, union_cluster.cluster_spec) def testOverlappingDictAndListThrowError(self): cluster_spec_1 = server_lib.ClusterSpec({ "worker": [ "worker4:2222", "worker5:2222" ] }) cluster_spec_2 = server_lib.ClusterSpec({ "worker": { 1: "worker0:2222", 2: "worker1:2222", 3: "worker2:2222" } }) cluster_resolver_1 = SimpleClusterResolver(cluster_spec_1) cluster_resolver_2 = SimpleClusterResolver(cluster_spec_2) union_cluster = UnionClusterResolver(cluster_resolver_1, cluster_resolver_2) self.assertRaises(KeyError, union_cluster.cluster_spec) def testOverlappingJobNonOverlappingKey(self): cluster_spec_1 = server_lib.ClusterSpec({ "worker": { 5: "worker4:2222", 9: "worker5:2222" } }) cluster_spec_2 = server_lib.ClusterSpec({ "worker": { 3: "worker0:2222", 6: "worker1:2222", 7: "worker2:2222" } }) cluster_resolver_1 = SimpleClusterResolver(cluster_spec_1) cluster_resolver_2 = SimpleClusterResolver(cluster_spec_2) union_cluster = UnionClusterResolver(cluster_resolver_1, cluster_resolver_2) cluster_spec = union_cluster.cluster_spec() expected_proto = """ job { name: 'worker' tasks { key: 3 value: 'worker0:2222' } tasks { key: 5 value: 'worker4:2222' } tasks { key: 6 value: 'worker1:2222' } tasks { key: 7 value: 'worker2:2222' } tasks { key: 9 value: 'worker5:2222' }} """ self._verifyClusterSpecEquality(cluster_spec, expected_proto) def testMixedModeNonOverlappingKey(self): cluster_spec_1 = server_lib.ClusterSpec({ "worker": [ "worker4:2222", "worker5:2222" ] }) cluster_spec_2 = server_lib.ClusterSpec({ "worker": { 3: "worker0:2222", 6: "worker1:2222", 7: "worker2:2222" } }) cluster_resolver_1 = SimpleClusterResolver(cluster_spec_1) cluster_resolver_2 = SimpleClusterResolver(cluster_spec_2) union_cluster = UnionClusterResolver(cluster_resolver_1, cluster_resolver_2) cluster_spec = union_cluster.cluster_spec() expected_proto = """ job { name: 'worker' tasks { key: 0 value: 'worker4:2222' } tasks { key: 1 value: 'worker5:2222' } tasks { key: 3 value: 'worker0:2222' } tasks { key: 6 value: 'worker1:2222' } tasks { key: 7 value: 'worker2:2222' }} """ self._verifyClusterSpecEquality(cluster_spec, expected_proto) def testRetainSparseJobWithNoMerging(self): base_cluster_spec = server_lib.ClusterSpec({ "worker": { 1: "worker0:2222", 3: "worker1:2222", 5: "worker2:2222" } }) base_cluster_resolver = SimpleClusterResolver(base_cluster_spec) union_cluster = UnionClusterResolver(base_cluster_resolver) cluster_spec = union_cluster.cluster_spec() expected_proto = """ job { name: 'worker' tasks { key: 1 value: 'worker0:2222' } tasks { key: 3 value: 'worker1:2222' } tasks { key: 5 value: 'worker2:2222' } } """ self._verifyClusterSpecEquality(cluster_spec, expected_proto) if __name__ == "__main__": test.main()
apache-2.0
ryano144/intellij-community
python/lib/Lib/site-packages/django/core/management/commands/inspectdb.py
110
7529
import keyword from optparse import make_option from django.core.management.base import NoArgsCommand, CommandError from django.db import connections, DEFAULT_DB_ALIAS class Command(NoArgsCommand): help = "Introspects the database tables in the given database and outputs a Django model module." option_list = NoArgsCommand.option_list + ( make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to ' 'introspect. Defaults to using the "default" database.'), ) requires_model_validation = False db_module = 'django.db' def handle_noargs(self, **options): try: for line in self.handle_inspection(options): print line except NotImplementedError: raise CommandError("Database inspection isn't supported for the currently selected database backend.") def handle_inspection(self, options): connection = connections[options.get('database', DEFAULT_DB_ALIAS)] table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '') cursor = connection.cursor() yield "# This is an auto-generated Django model module." yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" yield "# Feel free to rename the models, but don't rename db_table values or field names." yield "#" yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'" yield "# into your database." yield '' yield 'from %s import models' % self.db_module yield '' for table_name in connection.introspection.get_table_list(cursor): yield 'class %s(models.Model):' % table2model(table_name) try: relations = connection.introspection.get_relations(cursor, table_name) except NotImplementedError: relations = {} try: indexes = connection.introspection.get_indexes(cursor, table_name) except NotImplementedError: indexes = {} for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)): column_name = row[0] att_name = column_name.lower() comment_notes = [] # Holds Field notes, to be displayed in a Python comment. extra_params = {} # Holds Field parameters such as 'db_column'. # If the column name can't be used verbatim as a Python # attribute, set the "db_column" for this Field. if ' ' in att_name or '-' in att_name or keyword.iskeyword(att_name) or column_name != att_name: extra_params['db_column'] = column_name # Modify the field name to make it Python-compatible. if ' ' in att_name: att_name = att_name.replace(' ', '_') comment_notes.append('Field renamed to remove spaces.') if '-' in att_name: att_name = att_name.replace('-', '_') comment_notes.append('Field renamed to remove dashes.') if keyword.iskeyword(att_name): att_name += '_field' comment_notes.append('Field renamed because it was a Python reserved word.') if column_name != att_name: comment_notes.append('Field name made lowercase.') if i in relations: rel_to = relations[i][1] == table_name and "'self'" or table2model(relations[i][1]) field_type = 'ForeignKey(%s' % rel_to if att_name.endswith('_id'): att_name = att_name[:-3] else: extra_params['db_column'] = column_name else: # Calling `get_field_type` to get the field type string and any # additional paramters and notes. field_type, field_params, field_notes = self.get_field_type(connection, table_name, row) extra_params.update(field_params) comment_notes.extend(field_notes) # Add primary_key and unique, if necessary. if column_name in indexes: if indexes[column_name]['primary_key']: extra_params['primary_key'] = True elif indexes[column_name]['unique']: extra_params['unique'] = True field_type += '(' # Don't output 'id = meta.AutoField(primary_key=True)', because # that's assumed if it doesn't exist. if att_name == 'id' and field_type == 'AutoField(' and extra_params == {'primary_key': True}: continue # Add 'null' and 'blank', if the 'null_ok' flag was present in the # table description. if row[6]: # If it's NULL... extra_params['blank'] = True if not field_type in ('TextField(', 'CharField('): extra_params['null'] = True field_desc = '%s = models.%s' % (att_name, field_type) if extra_params: if not field_desc.endswith('('): field_desc += ', ' field_desc += ', '.join(['%s=%r' % (k, v) for k, v in extra_params.items()]) field_desc += ')' if comment_notes: field_desc += ' # ' + ' '.join(comment_notes) yield ' %s' % field_desc for meta_line in self.get_meta(table_name): yield meta_line def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_params = {} field_notes = [] try: field_type = connection.introspection.get_field_type(row[1], row) except KeyError: field_type = 'TextField' field_notes.append('This field type is a guess.') # This is a hook for DATA_TYPES_REVERSE to return a tuple of # (field_type, field_params_dict). if type(field_type) is tuple: field_type, new_params = field_type field_params.update(new_params) # Add max_length for all CharFields. if field_type == 'CharField' and row[3]: field_params['max_length'] = row[3] if field_type == 'DecimalField': field_params['max_digits'] = row[4] field_params['decimal_places'] = row[5] return field_type, field_params, field_notes def get_meta(self, table_name): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ return [' class Meta:', ' db_table = %r' % table_name, '']
apache-2.0
rhatdan/selinux
libsemanage/src/pywrap-test.py
3
39446
#!/usr/bin/python import sys import getopt import semanage usage = "\ Choose one of the following tests:\n\ -m for modules\n\ -u for users\n\ -U for add user (warning this will write!)\n\ -s for seusers\n\ -S for add seuser (warning this will write!)\n\ -p for ports\n\ -P for add port (warning this will write!)\n\ -f for file contexts \n\ -F for add file context (warning this will write!)\n\ -i for network interfaces \n\ -I for add network interface (warning this will write!)\n\ -b for booleans \n\ -B for add boolean (warning this will write!)\n\ -c for aCtive booleans\n\ -C for set aCtive boolean (warning this will write!)\n\n\ -n for network nodes\n\ -N for add node (warning this will write!)\n\n\ Other options:\n\ -h for this help\n\ -v for verbose output\ " class Usage(Exception): def __init__(self, msg): Exception.__init__(self) self.msg = msg class Status(Exception): def __init__(self, msg): Exception.__init__(self) self.msg = msg class Error(Exception): def __init__(self, msg): Exception.__init__(self) self.msg = msg class Tests: def __init__(self): self.all = False self.users = False self.writeuser = False self.seusers = False self.writeseuser = False self.ports = False self.writeport = False self.fcontexts = False self.writefcontext = False self.interfaces = False self.writeinterface = False self.booleans = False self.writeboolean = False self.abooleans = False self.writeaboolean = False self.nodes = False self.writenode = False self.modules = False self.verbose = False def selected(self): return (self.all or self.users or self.modules or self.seusers or self.ports or self.fcontexts or self.interfaces or self.booleans or self.abooleans or self.writeuser or self.writeseuser or self.writeport or self.writefcontext or self.writeinterface or self.writeboolean or self.writeaboolean or self.nodes or self.writenode) def run(self, handle): if (self.users or self.all): self.test_users(handle) print "" if (self.seusers or self.all): self.test_seusers(handle) print "" if (self.ports or self.all): self.test_ports(handle) print "" if (self.modules or self.all): self.test_modules(handle) print "" if (self.fcontexts or self.all): self.test_fcontexts(handle) print "" if (self.interfaces or self.all): self.test_interfaces(handle) print "" if (self.booleans or self.all): self.test_booleans(handle) print "" if (self.abooleans or self.all): self.test_abooleans(handle) print "" if (self.nodes or self.all): self.test_nodes(handle) print "" if (self.writeuser or self.all): self.test_writeuser(handle) print "" if (self.writeseuser or self.all): self.test_writeseuser(handle) print "" if (self.writeport or self.all): self.test_writeport(handle) print "" if (self.writefcontext or self.all): self.test_writefcontext(handle) print "" if (self.writeinterface or self.all): self.test_writeinterface(handle) print "" if (self.writeboolean or self.all): self.test_writeboolean(handle) print "" if (self.writeaboolean or self.all): self.test_writeaboolean(handle) print "" if (self.writenode or self.all): self.test_writenode(handle) print "" def test_modules(self,sh): print "Testing modules..." (trans_cnt, mlist, mlist_size) = semanage.semanage_module_list(sh) print "Transaction number: ", trans_cnt print "Module list size: ", mlist_size if self.verbose: print "List reference: ", mlist if (mlist_size == 0): print "No modules installed!" print "This is not necessarily a test failure." return for idx in range(mlist_size): module = semanage.semanage_module_list_nth(mlist, idx) if self.verbose: print "Module reference: ", module print "Module name: ", semanage.semanage_module_get_name(module) def test_seusers(self,sh): print "Testing seusers..." (status, slist) = semanage.semanage_seuser_list(sh) if status < 0: raise Error("Could not list seusers") print "Query status (commit number): ", status if ( len(slist) == 0): print "No seusers found!" print "This is not necessarily a test failure." return for seuser in slist: if self.verbose: print "seseuser reference: ", seuser print "seuser name: ", semanage.semanage_seuser_get_name(seuser) print " seuser mls range: ", semanage.semanage_seuser_get_mlsrange(seuser) print " seuser sename: ", semanage.semanage_seuser_get_sename(seuser) semanage.semanage_seuser_free(seuser) def test_users(self,sh): print "Testing users..." (status, ulist) = semanage.semanage_user_list(sh) if status < 0: raise Error("Could not list users") print "Query status (commit number): ", status if ( len(ulist) == 0): print "No users found!" print "This is not necessarily a test failure." return for user in ulist: if self.verbose: print "User reference: ", user print "User name: ", semanage.semanage_user_get_name(user) print " User labeling prefix: ", semanage.semanage_user_get_prefix(user) print " User mls level: ", semanage.semanage_user_get_mlslevel(user) print " User mls range: ", semanage.semanage_user_get_mlsrange(user) print " User number of roles: ", semanage.semanage_user_get_num_roles(user) print " User roles: " (status, rlist) = semanage.semanage_user_get_roles(sh, user) if status < 0: raise Error("Could not get user roles") for role in rlist: print " ", role semanage.semanage_user_free(user) def test_ports(self,sh): print "Testing ports..." (status, plist) = semanage.semanage_port_list(sh) if status < 0: raise Error("Could not list ports") print "Query status (commit number): ", status if ( len(plist) == 0): print "No ports found!" print "This is not necessarily a test failure." return for port in plist: if self.verbose: print "Port reference: ", port low = semanage.semanage_port_get_low(port) high = semanage.semanage_port_get_high(port) con = semanage.semanage_port_get_con(port) proto = semanage.semanage_port_get_proto(port) proto_str = semanage.semanage_port_get_proto_str(proto) if low == high: range_str = str(low) else: range_str = str(low) + "-" + str(high) (rc, con_str) = semanage.semanage_context_to_string(sh,con) if rc < 0: con_str = "" print "Port: ", range_str, " ", proto_str, " Context: ", con_str semanage.semanage_port_free(port) def test_fcontexts(self,sh): print "Testing file contexts..." (status, flist) = semanage.semanage_fcontext_list(sh) if status < 0: raise Error("Could not list file contexts") print "Query status (commit number): ", status if (len(flist) == 0): print "No file contexts found!" print "This is not necessarily a test failure." return for fcon in flist: if self.verbose: print "File Context reference: ", fcon expr = semanage.semanage_fcontext_get_expr(fcon) type = semanage.semanage_fcontext_get_type(fcon) type_str = semanage.semanage_fcontext_get_type_str(type) con = semanage.semanage_fcontext_get_con(fcon) if not con: con_str = "<<none>>" else: (rc, con_str) = semanage.semanage_context_to_string(sh,con) if rc < 0: con_str = "" print "File Expr: ", expr, " [", type_str, "] Context: ", con_str semanage.semanage_fcontext_free(fcon) def test_interfaces(self,sh): print "Testing network interfaces..." (status, ilist) = semanage.semanage_iface_list(sh) if status < 0: raise Error("Could not list interfaces") print "Query status (commit number): ", status if (len(ilist) == 0): print "No network interfaces found!" print "This is not necessarily a test failure." return for iface in ilist: if self.verbose: print "Interface reference: ", iface name = semanage.semanage_iface_get_name(iface) msg_con = semanage.semanage_iface_get_msgcon(iface) if_con = semanage.semanage_iface_get_ifcon(iface) (rc, msg_con_str) = semanage.semanage_context_to_string(sh,msg_con) if rc < 0: msg_con_str = "" (rc, if_con_str) = semanage.semanage_context_to_string(sh, if_con) if rc < 0: if_con_str = "" print "Interface: ", name, " Context: ", if_con_str, " Message Context: ", msg_con_str semanage.semanage_iface_free(iface) def test_booleans(self,sh): print "Testing booleans..." (status, blist) = semanage.semanage_bool_list(sh) if status < 0: raise Error("Could not list booleans") print "Query status (commit number): ", status if (len(blist) == 0): print "No booleans found!" print "This is not necessarily a test failure." return for pbool in blist: if self.verbose: print "Boolean reference: ", pbool name = semanage.semanage_bool_get_name(pbool) value = semanage.semanage_bool_get_value(pbool) print "Boolean: ", name, " Value: ", value semanage.semanage_bool_free(pbool) def test_abooleans(self,sh): print "Testing active booleans..." (status, ablist) = semanage.semanage_bool_list_active(sh) if status < 0: raise Error("Could not list active booleans") print "Query status (commit number): ", status if (len(ablist) == 0): print "No active booleans found!" print "This is not necessarily a test failure." return for abool in ablist: if self.verbose: print "Active boolean reference: ", abool name = semanage.semanage_bool_get_name(abool) value = semanage.semanage_bool_get_value(abool) print "Active Boolean: ", name, " Value: ", value semanage.semanage_bool_free(abool) def test_nodes(self,sh): print "Testing network nodes..." (status, nlist) = semanage.semanage_node_list(sh) if status < 0: raise Error("Could not list network nodes") print "Query status (commit number): ", status if (len(nlist) == 0): print "No network nodes found!" print "This is not necessarily a test failure." return for node in nlist: if self.verbose: print "Network node reference: ", node (status, addr) = semanage.semanage_node_get_addr(sh, node) if status < 0: addr = "" (status, mask) = semanage.semanage_node_get_mask(sh, node) if status < 0: mask = "" proto = semanage.semanage_node_get_proto(node) proto_str = semanage.semanage_node_get_proto_str(proto) con = semanage.semanage_node_get_con(node) (status, con_str) = semanage.semanage_context_to_string(sh, con) if status < 0: con_str = "" print "Network Node: ", addr, "/", mask, " (", proto_str, ")", "Context: ", con_str semanage.semanage_node_free(node) def test_writeuser(self,sh): print "Testing user write..." (status, user) = semanage.semanage_user_create(sh) if status < 0: raise Error("Could not create user object") if self.verbose: print "User object created" status = semanage.semanage_user_set_name(sh,user, "testPyUser") if status < 0: raise Error("Could not set user name") if self.verbose: print "User name set: ", semanage.semanage_user_get_name(user) status = semanage.semanage_user_add_role(sh, user, "user_r") if status < 0: raise Error("Could not add role") status = semanage.semanage_user_set_prefix(sh,user, "user") if status < 0: raise Error("Could not set labeling prefix") if self.verbose: print "User prefix set: ", semanage.semanage_user_get_prefix(user) status = semanage.semanage_user_set_mlsrange(sh, user, "s0") if status < 0: raise Error("Could not set MLS range") if self.verbose: print "User mlsrange: ", semanage.semanage_user_get_mlsrange(user) status = semanage.semanage_user_set_mlslevel(sh, user, "s0") if status < 0: raise Error("Could not set MLS level") if self.verbose: print "User mlslevel: ", semanage.semanage_user_get_mlslevel(user) (status,key) = semanage.semanage_user_key_extract(sh,user) if status < 0: raise Error("Could not extract user key") if self.verbose: print "User key extracted: ", key (status,exists) = semanage.semanage_user_exists_local(sh,key) if status < 0: raise Error("Could not check if user exists") if self.verbose: print "Exists status (commit number): ", status if exists: (status, old_user) = semanage.semanage_user_query_local(sh, key) if status < 0: raise Error("Could not query old user") if self.verbose: print "Query status (commit number): ", status print "Starting transaction.." status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") status = semanage.semanage_user_modify_local(sh,key,user) if status < 0: raise Error("Could not modify user") status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit test transaction") print "Commit status (transaction number): ", status status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") if not exists: print "Removing user..." status = semanage.semanage_user_del_local(sh, key) if status < 0: raise Error("Could not delete test user") if self.verbose: print "User delete: ", status else: print "Resetting user..." status = semanage.semanage_user_modify_local(sh, key, old_user) if status < 0: raise Error("Could not reset test user") if self.verbose: print "User modify: ", status status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit reset transaction") print "Commit status (transaction number): ", status semanage.semanage_user_key_free(key) semanage.semanage_user_free(user) if exists: semanage.semanage_user_free(old_user) def test_writeseuser(self,sh): print "Testing seuser write..." (status, seuser) = semanage.semanage_seuser_create(sh) if status < 0: raise Error("Could not create SEUser object") if self.verbose: print "SEUser object created." status = semanage.semanage_seuser_set_name(sh,seuser, "testPySEUser") if status < 0: raise Error("Could not set name") if self.verbose: print "SEUser name set: ", semanage.semanage_seuser_get_name(seuser) status = semanage.semanage_seuser_set_sename(sh, seuser, "root") if status < 0: raise Error("Could not set sename") if self.verbose: print "SEUser seuser: ", semanage.semanage_seuser_get_sename(seuser) status = semanage.semanage_seuser_set_mlsrange(sh, seuser, "s0:c0.c255") if status < 0: raise Error("Could not set MLS range") if self.verbose: print "SEUser mlsrange: ", semanage.semanage_seuser_get_mlsrange(seuser) (status,key) = semanage.semanage_seuser_key_extract(sh,seuser) if status < 0: raise Error("Could not extract SEUser key") if self.verbose: print "SEUser key extracted: ", key (status,exists) = semanage.semanage_seuser_exists_local(sh,key) if status < 0: raise Error("Could not check if SEUser exists") if self.verbose: print "Exists status (commit number): ", status if exists: (status, old_seuser) = semanage.semanage_seuser_query_local(sh, key) if status < 0: raise Error("Could not query old SEUser") if self.verbose: print "Query status (commit number): ", status print "Starting transaction..." status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") status = semanage.semanage_seuser_modify_local(sh,key,seuser) if status < 0: raise Error("Could not modify SEUser") status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit test transaction") print "Commit status (transaction number): ", status status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") if not exists: print "Removing seuser..." status = semanage.semanage_seuser_del_local(sh, key) if status < 0: raise Error("Could not delete test SEUser") if self.verbose: print "Seuser delete: ", status else: print "Resetting seuser..." status = semanage.semanage_seuser_modify_local(sh, key, old_seuser) if status < 0: raise Error("Could not reset test SEUser") if self.verbose: print "Seuser modify: ", status status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit reset transaction") print "Commit status (transaction number): ", status semanage.semanage_seuser_key_free(key) semanage.semanage_seuser_free(seuser) if exists: semanage.semanage_seuser_free(old_seuser) def test_writeport(self,sh): print "Testing port write..." (status, port) = semanage.semanage_port_create(sh) if status < 0: raise Error("Could not create SEPort object") if self.verbose: print "SEPort object created." semanage.semanage_port_set_range(port,150,200) low = semanage.semanage_port_get_low(port) high = semanage.semanage_port_get_high(port) if self.verbose: print "SEPort range set: ", low, "-", high semanage.semanage_port_set_proto(port, semanage.SEMANAGE_PROTO_TCP); if self.verbose: print "SEPort protocol set: ", \ semanage.semanage_port_get_proto_str(semanage.SEMANAGE_PROTO_TCP) (status, con) = semanage.semanage_context_create(sh) if status < 0: raise Error("Could not create SEContext object") if self.verbose: print "SEContext object created (for port)." status = semanage.semanage_context_set_user(sh, con, "system_u") if status < 0: raise Error("Could not set context user") if self.verbose: print "SEContext user: ", semanage.semanage_context_get_user(con) status = semanage.semanage_context_set_role(sh, con, "object_r") if status < 0: raise Error("Could not set context role") if self.verbose: print "SEContext role: ", semanage.semanage_context_get_role(con) status = semanage.semanage_context_set_type(sh, con, "http_port_t") if status < 0: raise Error("Could not set context type") if self.verbose: print "SEContext type: ", semanage.semanage_context_get_type(con) status = semanage.semanage_context_set_mls(sh, con, "s0:c0.c255") if status < 0: raise Error("Could not set context MLS fields") if self.verbose: print "SEContext mls: ", semanage.semanage_context_get_mls(con) status = semanage.semanage_port_set_con(sh, port, con) if status < 0: raise Error("Could not set SEPort context") if self.verbose: print "SEPort context set: ", con (status,key) = semanage.semanage_port_key_extract(sh,port) if status < 0: raise Error("Could not extract SEPort key") if self.verbose: print "SEPort key extracted: ", key (status,exists) = semanage.semanage_port_exists_local(sh,key) if status < 0: raise Error("Could not check if SEPort exists") if self.verbose: print "Exists status (commit number): ", status if exists: (status, old_port) = semanage.semanage_port_query_local(sh, key) if status < 0: raise Error("Could not query old SEPort") if self.verbose: print "Query status (commit number): ", status print "Starting transaction..." status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") status = semanage.semanage_port_modify_local(sh,key,port) if status < 0: raise Error("Could not modify SEPort") status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit test transaction") print "Commit status (transaction number): ", status status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") if not exists: print "Removing port range..." status = semanage.semanage_port_del_local(sh, key) if status < 0: raise Error("Could not delete test SEPort") if self.verbose: print "Port range delete: ", status else: print "Resetting port range..." status = semanage.semanage_port_modify_local(sh, key, old_port) if status < 0: raise Error("Could not reset test SEPort") if self.verbose: print "Port range modify: ", status status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit reset transaction") print "Commit status (transaction number): ", status semanage.semanage_context_free(con) semanage.semanage_port_key_free(key) semanage.semanage_port_free(port) if exists: semanage.semanage_port_free(old_port) def test_writefcontext(self,sh): print "Testing file context write..." (status, fcon) = semanage.semanage_fcontext_create(sh) if status < 0: raise Error("Could not create SEFcontext object") if self.verbose: print "SEFcontext object created." status = semanage.semanage_fcontext_set_expr(sh, fcon, "/test/fcontext(/.*)?") if status < 0: raise Error("Could not set expression") if self.verbose: print "SEFContext expr set: ", semanage.semanage_fcontext_get_expr(fcon) semanage.semanage_fcontext_set_type(fcon, semanage.SEMANAGE_FCONTEXT_REG) if self.verbose: ftype = semanage.semanage_fcontext_get_type(fcon) print "SEFContext type set: ", semanage.semanage_fcontext_get_type_str(ftype) (status, con) = semanage.semanage_context_create(sh) if status < 0: raise Error("Could not create SEContext object") if self.verbose: print "SEContext object created (for file context)." status = semanage.semanage_context_set_user(sh, con, "system_u") if status < 0: raise Error("Could not set context user") if self.verbose: print "SEContext user: ", semanage.semanage_context_get_user(con) status = semanage.semanage_context_set_role(sh, con, "object_r") if status < 0: raise Error("Could not set context role") if self.verbose: print "SEContext role: ", semanage.semanage_context_get_role(con) status = semanage.semanage_context_set_type(sh, con, "default_t") if status < 0: raise Error("Could not set context type") if self.verbose: print "SEContext type: ", semanage.semanage_context_get_type(con) status = semanage.semanage_context_set_mls(sh, con, "s0:c0.c255") if status < 0: raise Error("Could not set context MLS fields") if self.verbose: print "SEContext mls: ", semanage.semanage_context_get_mls(con) status = semanage.semanage_fcontext_set_con(sh, fcon, con) if status < 0: raise Error("Could not set SEFcontext context") if self.verbose: print "SEFcontext context set: ", con (status,key) = semanage.semanage_fcontext_key_extract(sh,fcon) if status < 0: raise Error("Could not extract SEFcontext key") if self.verbose: print "SEFcontext key extracted: ", key (status,exists) = semanage.semanage_fcontext_exists_local(sh,key) if status < 0: raise Error("Could not check if SEFcontext exists") if self.verbose: print "Exists status (commit number): ", status if exists: (status, old_fcontext) = semanage.semanage_fcontext_query_local(sh, key) if status < 0: raise Error("Could not query old SEFcontext") if self.verbose: print "Query status (commit number): ", status print "Starting transaction..." status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") status = semanage.semanage_fcontext_modify_local(sh,key,fcon) if status < 0: raise Error("Could not modify SEFcontext") status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit test transaction") print "Commit status (transaction number): ", status status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") if not exists: print "Removing file context..." status = semanage.semanage_fcontext_del_local(sh, key) if status < 0: raise Error("Could not delete test SEFcontext") if self.verbose: print "File context delete: ", status else: print "Resetting file context..." status = semanage.semanage_fcontext_modify_local(sh, key, old_fcontext) if status < 0: raise Error("Could not reset test FContext") if self.verbose: print "File context modify: ", status status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit reset transaction") print "Commit status (transaction number): ", status semanage.semanage_context_free(con) semanage.semanage_fcontext_key_free(key) semanage.semanage_fcontext_free(fcon) if exists: semanage.semanage_fcontext_free(old_fcontext) def test_writeinterface(self,sh): print "Testing network interface write..." (status, iface) = semanage.semanage_iface_create(sh) if status < 0: raise Error("Could not create SEIface object") if self.verbose: print "SEIface object created." status = semanage.semanage_iface_set_name(sh, iface, "test_iface") if status < 0: raise Error("Could not set SEIface name") if self.verbose: print "SEIface name set: ", semanage.semanage_iface_get_name(iface) (status, con) = semanage.semanage_context_create(sh) if status < 0: raise Error("Could not create SEContext object") if self.verbose: print "SEContext object created (for network interface)" status = semanage.semanage_context_set_user(sh, con, "system_u") if status < 0: raise Error("Could not set interface context user") if self.verbose: print "SEContext user: ", semanage.semanage_context_get_user(con) status = semanage.semanage_context_set_role(sh, con, "object_r") if status < 0: raise Error("Could not set interface context role") if self.verbose: print "SEContext role: ", semanage.semanage_context_get_role(con) status = semanage.semanage_context_set_type(sh, con, "default_t") if status < 0: raise Error("Could not set interface context type") if self.verbose: print "SEContext type: ", semanage.semanage_context_get_type(con) status = semanage.semanage_context_set_mls(sh, con, "s0:c0.c255") if status < 0: raise Error("Could not set interface context MLS fields") if self.verbose: print "SEContext mls: ", semanage.semanage_context_get_mls(con) status = semanage.semanage_iface_set_ifcon(sh, iface, con) if status < 0: raise Error("Could not set SEIface interface context") if self.verbose: print "SEIface interface context set: ", con status = semanage.semanage_iface_set_msgcon(sh, iface, con) if status < 0: raise Error("Could not set SEIface message context") if self.verbose: print "SEIface message context set: ", con (status,key) = semanage.semanage_iface_key_extract(sh,iface) if status < 0: raise Error("Could not extract SEIface key") if self.verbose: print "SEIface key extracted: ", key (status,exists) = semanage.semanage_iface_exists_local(sh,key) if status < 0: raise Error("Could not check if SEIface exists") if self.verbose: print "Exists status (commit number): ", status if exists: (status, old_iface) = semanage.semanage_iface_query_local(sh, key) if status < 0: raise Error("Could not query old SEIface") if self.verbose: print "Query status (commit number): ", status print "Starting transaction..." status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not begin semanage transaction") status = semanage.semanage_iface_modify_local(sh,key,iface) if status < 0: raise Error("Could not modify SEIface") status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit test transaction") print "Commit status (transaction number): ", status status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not begin semanage transaction") if not exists: print "Removing interface..." status = semanage.semanage_iface_del_local(sh, key) if status < 0: raise Error("Could not delete test SEIface") if self.verbose: print "Interface delete: ", status else: print "Resetting interface..." status = semanage.semanage_iface_modify_local(sh, key, old_iface) if status < 0: raise Error("Could not reset test SEIface") if self.verbose: print "Interface modify: ", status status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit reset transaction") print "Commit status (transaction number): ", status semanage.semanage_context_free(con) semanage.semanage_iface_key_free(key) semanage.semanage_iface_free(iface) if exists: semanage.semanage_iface_free(old_iface) def test_writeboolean(self,sh): print "Testing boolean write..." (status, pbool) = semanage.semanage_bool_create(sh) if status < 0: raise Error("Could not create SEBool object") if self.verbose: print "SEBool object created." status = semanage.semanage_bool_set_name(sh, pbool, "allow_execmem") if status < 0: raise Error("Could not set name") if self.verbose: print "SEBool name set: ", semanage.semanage_bool_get_name(pbool) semanage.semanage_bool_set_value(pbool, 0) if self.verbose: print "SEbool value set: ", semanage.semanage_bool_get_value(pbool) (status,key) = semanage.semanage_bool_key_extract(sh, pbool) if status < 0: raise Error("Could not extract SEBool key") if self.verbose: print "SEBool key extracted: ", key (status,exists) = semanage.semanage_bool_exists_local(sh,key) if status < 0: raise Error("Could not check if SEBool exists") if self.verbose: print "Exists status (commit number): ", status if exists: (status, old_bool) = semanage.semanage_bool_query_local(sh, key) if status < 0: raise Error("Could not query old SEBool") if self.verbose: print "Query status (commit number): ", status print "Starting transaction..." status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") status = semanage.semanage_bool_modify_local(sh, key, pbool) if status < 0: raise Error("Could not modify SEBool") status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit test transaction") print "Commit status (transaction number): ", status status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") if not exists: print "Removing boolean..." status = semanage.semanage_bool_del_local(sh, key) if status < 0: raise Error("Could not delete test SEBool") if self.verbose: print "Boolean delete: ", status else: print "Resetting boolean..." status = semanage.semanage_bool_modify_local(sh, key, old_bool) if status < 0: raise Error("Could not reset test SEBool") if self.verbose: print "Boolean modify: ", status status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit reset transaction") print "Commit status (transaction number): ", status semanage.semanage_bool_key_free(key) semanage.semanage_bool_free(pbool) if exists: semanage.semanage_bool_free(old_bool) def test_writeaboolean(self,sh): print "Testing active boolean write..." (status, key) = semanage.semanage_bool_key_create(sh, "allow_execmem") if status < 0: raise Error("Could not create SEBool key") if self.verbose: print "SEBool key created: ", key (status, old_bool) = semanage.semanage_bool_query_active(sh, key) if status < 0: raise Error("Could not query old SEBool") if self.verbose: print "Query status (commit number): ", status (status, abool) = semanage.semanage_bool_create(sh) if status < 0: raise Error("Could not create SEBool object") if self.verbose: print "SEBool object created." status = semanage.semanage_bool_set_name(sh, abool, "allow_execmem") if status < 0: raise Error("Could not set name") if self.verbose: print "SEBool name set: ", semanage.semanage_bool_get_name(abool) semanage.semanage_bool_set_value(abool, 0) if self.verbose: print "SEbool value set: ", semanage.semanage_bool_get_value(abool) print "Starting transaction..." status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") status = semanage.semanage_bool_set_active(sh,key,abool) if status < 0: raise Error("Could not modify SEBool") status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit test transaction") print "Commit status (transaction number): ", status print "Resetting old active boolean..." status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") status = semanage.semanage_bool_set_active(sh, key,old_bool) if status < 0: raise Error("Could not reset test SEBool") if self.verbose: print "SEBool active reset: ", status status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit reset transaction") print "Commit status (transaction number): ", status semanage.semanage_bool_key_free(key) semanage.semanage_bool_free(abool) semanage.semanage_bool_free(old_bool) def test_writenode(self,sh): print "Testing network node write..." (status, node) = semanage.semanage_node_create(sh) if status < 0: raise Error("Could not create SENode object") if self.verbose: print "SENode object created." status = semanage.semanage_node_set_addr(sh, node, semanage.SEMANAGE_PROTO_IP6, "ffee:dddd::bbbb") if status < 0: raise Error("Could not set SENode address") status = semanage.semanage_node_set_mask(sh, node, semanage.SEMANAGE_PROTO_IP6, "::ffff:ffff:abcd:0000") if status < 0: raise Error("Could not set SENode netmask") semanage.semanage_node_set_proto(node, semanage.SEMANAGE_PROTO_IP6); if self.verbose: print "SENode protocol set: ", \ semanage.semanage_node_get_proto_str(semanage.SEMANAGE_PROTO_IP6) (status, con) = semanage.semanage_context_create(sh) if status < 0: raise Error("Could not create SEContext object") if self.verbose: print "SEContext object created (for node)." status = semanage.semanage_context_set_user(sh, con, "system_u") if status < 0: raise Error("Could not set context user") if self.verbose: print "SEContext user: ", semanage.semanage_context_get_user(con) status = semanage.semanage_context_set_role(sh, con, "object_r") if status < 0: raise Error("Could not set context role") if self.verbose: print "SEContext role: ", semanage.semanage_context_get_role(con) status = semanage.semanage_context_set_type(sh, con, "lo_node_t") if status < 0: raise Error("Could not set context type") if self.verbose: print "SEContext type: ", semanage.semanage_context_get_type(con) status = semanage.semanage_context_set_mls(sh, con, "s0:c0.c255") if status < 0: raise Error("Could not set context MLS fields") if self.verbose: print "SEContext mls: ", semanage.semanage_context_get_mls(con) status = semanage.semanage_node_set_con(sh, node, con) if status < 0: raise Error("Could not set SENode context") if self.verbose: print "SENode context set: ", con (status,key) = semanage.semanage_node_key_extract(sh, node) if status < 0: raise Error("Could not extract SENode key") if self.verbose: print "SENode key extracted: ", key (status,exists) = semanage.semanage_node_exists_local(sh,key) if status < 0: raise Error("Could not check if SENode exists") if self.verbose: print "Exists status (commit number): ", status if exists: (status, old_node) = semanage.semanage_node_query_local(sh, key) if status < 0: raise Error("Could not query old SENode") if self.verbose: print "Query status (commit number): ", status print "Starting transaction..." status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") status = semanage.semanage_node_modify_local(sh,key, node) if status < 0: raise Error("Could not modify SENode") status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit test transaction") print "Commit status (transaction number): ", status status = semanage.semanage_begin_transaction(sh) if status < 0: raise Error("Could not start semanage transaction") if not exists: print "Removing network node..." status = semanage.semanage_node_del_local(sh, key) if status < 0: raise Error("Could not delete test SENode") if self.verbose: print "Network node delete: ", status else: print "Resetting network node..." status = semanage.semanage_node_modify_local(sh, key, old_node) if status < 0: raise Error("Could not reset test SENode") if self.verbose: print "Network node modify: ", status status = semanage.semanage_commit(sh) if status < 0: raise Error("Could not commit reset transaction") print "Commit status (transaction number): ", status semanage.semanage_context_free(con) semanage.semanage_node_key_free(key) semanage.semanage_node_free(node) if exists: semanage.semanage_node_free(old_node) def main(argv=None): if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[1:], "hvmuspfibcUSPFIBCanN", ["help", "verbose", "modules", "users", "seusers", "ports", "file contexts", "network interfaces", "booleans", "active booleans", "network nodes", "writeuser", "writeseuser", "writeport", "writefcontext", "writeinterface", "writeboolean", "writeaboolean", "writenode", "all"]) tests = Tests() for o, a in opts: if o == "-v": tests.verbose = True print "Verbose output selected." if o == "-a": tests.all = True if o == "-u": tests.users = True if o == "-U": tests.writeuser = True if o == "-s": tests.seusers = True if o == "-S": tests.writeseuser = True if o == "-p": tests.ports = True if o == "-P": tests.writeport = True if o == "-f": tests.fcontexts = True if o == "-F": tests.writefcontext = True if o == "-i": tests.interfaces = True if o == "-I": tests.writeinterface = True if o == "-b": tests.booleans = True if o == "-B": tests.writeboolean = True if o == "-c": tests.abooleans = True if o == "-C": tests.writeaboolean = True if o == "-n": tests.nodes = True if o == "-N": tests.writenode = True if o == "-m": tests.modules = True if o == "-h": raise Usage(usage) if not tests.selected(): raise Usage("Please select a valid test.") except getopt.error, msg: raise Usage(msg) sh=semanage.semanage_handle_create() if (semanage.semanage_is_managed(sh) != 1): raise Status("Unmanaged!") status = semanage.semanage_connect(sh) if status < 0: raise Error("Could not establish semanage connection") tests.run(sh) status = semanage.semanage_disconnect(sh) if status < 0: raise Error("Could not disconnect") semanage.semanage_handle_destroy(sh) except Usage, err: print >>sys.stderr, err.msg except Status, err: print >>sys.stderr, err.msg except Error, err: print >>sys.stderr, err.msg return 2 if __name__ == "__main__": sys.exit(main())
gpl-2.0
priyesh16/thesis
src/nix-vector-routing/bindings/modulegen__gcc_LP64.py
24
370694
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.nix_vector_routing', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## hash.h (module 'core'): ns3::Hasher [class] module.add_class('Hasher', import_from_module='ns.core') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] module.add_class('Inet6SocketAddress', import_from_module='ns.network') ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress [class] module.add_class('Ipv4InterfaceAddress', import_from_module='ns.internet') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e [enumeration] module.add_enum('InterfaceAddressScope_e', ['HOST', 'LINK', 'GLOBAL'], outer_class=root_module['ns3::Ipv4InterfaceAddress'], import_from_module='ns.internet') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper [class] module.add_class('Ipv4RoutingHelper', allow_subclassing=True, import_from_module='ns.internet') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## 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') ## node-list.h (module 'network'): ns3::NodeList [class] module.add_class('NodeList', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData_e [enumeration] module.add_enum('TagData_e', ['MAX_SIZE'], outer_class=root_module['ns3::PacketTagList::TagData'], import_from_module='ns.network') ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## nstime.h (module 'core'): ns3::TimeWithUnit [class] module.add_class('TimeWithUnit', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t::impl_type [enumeration] module.add_enum('impl_type', ['int128_impl', 'cairo_impl', 'ld_impl'], outer_class=root_module['ns3::int64x64_t'], import_from_module='ns.core') ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header [class] module.add_class('Ipv4Header', import_from_module='ns.internet', parent=root_module['ns3::Header']) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType [enumeration] module.add_enum('DscpType', ['DscpDefault', 'DSCP_CS1', 'DSCP_AF11', 'DSCP_AF12', 'DSCP_AF13', 'DSCP_CS2', 'DSCP_AF21', 'DSCP_AF22', 'DSCP_AF23', 'DSCP_CS3', 'DSCP_AF31', 'DSCP_AF32', 'DSCP_AF33', 'DSCP_CS4', 'DSCP_AF41', 'DSCP_AF42', 'DSCP_AF43', 'DSCP_CS5', 'DSCP_EF', 'DSCP_CS6', 'DSCP_CS7'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType [enumeration] module.add_enum('EcnType', ['ECN_NotECT', 'ECN_ECT1', 'ECN_ECT0', 'ECN_CE'], outer_class=root_module['ns3::Ipv4Header'], import_from_module='ns.internet') ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper [class] module.add_class('Ipv4NixVectorHelper', parent=root_module['ns3::Ipv4RoutingHelper']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Hash::Implementation', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Hash::Implementation>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::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::SocketIpTosTag [class] module.add_class('SocketIpTosTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpTtlTag [class] module.add_class('SocketIpTtlTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag [class] module.add_class('SocketIpv6HopLimitTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag [class] module.add_class('SocketIpv6TclassTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag [class] module.add_class('SocketSetDontFragmentTag', import_from_module='ns.network', parent=root_module['ns3::Tag']) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['Y', 'D', 'H', 'MIN', 'S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## channel.h (module 'network'): ns3::Channel [class] module.add_class('Channel', import_from_module='ns.network', parent=root_module['ns3::Object']) ## 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> >']) ## 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-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-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## 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::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']) ## bridge-channel.h (module 'bridge'): ns3::BridgeChannel [class] module.add_class('BridgeChannel', import_from_module='ns.bridge', parent=root_module['ns3::Channel']) ## bridge-net-device.h (module 'bridge'): ns3::BridgeNetDevice [class] module.add_class('BridgeNetDevice', import_from_module='ns.bridge', parent=root_module['ns3::NetDevice']) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting [class] module.add_class('Ipv4ListRouting', import_from_module='ns.internet', parent=root_module['ns3::Ipv4RoutingProtocol']) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorRouting [class] module.add_class('Ipv4NixVectorRouting', parent=root_module['ns3::Ipv4RoutingProtocol']) module.add_container('std::map< unsigned int, unsigned int >', ('unsigned int', 'unsigned int'), container_type=u'map') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >', u'ns3::NixMap_t') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >*', u'ns3::NixMap_t*') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::NixVector >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::NixVector > > > >&', u'ns3::NixMap_t&') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >', u'ns3::Ipv4RouteMap_t') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >*', u'ns3::Ipv4RouteMap_t*') typehandlers.add_type_alias(u'std::map< ns3::Ipv4Address, ns3::Ptr< ns3::Ipv4Route >, std::less< ns3::Ipv4Address >, std::allocator< std::pair< ns3::Ipv4Address const, ns3::Ptr< ns3::Ipv4Route > > > >&', u'ns3::Ipv4RouteMap_t&') ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) ## Register a nested module for the namespace Hash nested_module = module.add_cpp_namespace('Hash') register_types_ns3_Hash(nested_module) def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_types_ns3_Hash(module): root_module = module.get_root() ## hash-function.h (module 'core'): ns3::Hash::Implementation [class] module.add_class('Implementation', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash32Function_ptr') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash32Function_ptr*') typehandlers.add_type_alias(u'uint32_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash32Function_ptr&') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *', u'ns3::Hash::Hash64Function_ptr') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) **', u'ns3::Hash::Hash64Function_ptr*') typehandlers.add_type_alias(u'uint64_t ( * ) ( char const *, size_t ) *&', u'ns3::Hash::Hash64Function_ptr&') ## Register a nested module for the namespace Function nested_module = module.add_cpp_namespace('Function') register_types_ns3_Hash_Function(nested_module) def register_types_ns3_Hash_Function(module): root_module = module.get_root() ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a [class] module.add_class('Fnv1a', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32 [class] module.add_class('Hash32', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64 [class] module.add_class('Hash64', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3 [class] module.add_class('Murmur3', import_from_module='ns.core', parent=root_module['ns3::Hash::Implementation']) def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Hasher_methods(root_module, root_module['ns3::Hasher']) register_Ns3Inet6SocketAddress_methods(root_module, root_module['ns3::Inet6SocketAddress']) register_Ns3InetSocketAddress_methods(root_module, root_module['ns3::InetSocketAddress']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4InterfaceAddress_methods(root_module, root_module['ns3::Ipv4InterfaceAddress']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv4RoutingHelper_methods(root_module, root_module['ns3::Ipv4RoutingHelper']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NetDeviceContainer_methods(root_module, root_module['ns3::NetDeviceContainer']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3NodeList_methods(root_module, root_module['ns3::NodeList']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TimeWithUnit_methods(root_module, root_module['ns3::TimeWithUnit']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Ipv4Header_methods(root_module, root_module['ns3::Ipv4Header']) register_Ns3Ipv4NixVectorHelper_methods(root_module, root_module['ns3::Ipv4NixVectorHelper']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >']) register_Ns3SimpleRefCount__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_Ns3SocketIpTosTag_methods(root_module, root_module['ns3::SocketIpTosTag']) register_Ns3SocketIpTtlTag_methods(root_module, root_module['ns3::SocketIpTtlTag']) register_Ns3SocketIpv6HopLimitTag_methods(root_module, root_module['ns3::SocketIpv6HopLimitTag']) register_Ns3SocketIpv6TclassTag_methods(root_module, root_module['ns3::SocketIpv6TclassTag']) register_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_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) 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_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_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_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_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3BridgeChannel_methods(root_module, root_module['ns3::BridgeChannel']) register_Ns3BridgeNetDevice_methods(root_module, root_module['ns3::BridgeNetDevice']) register_Ns3Ipv4ListRouting_methods(root_module, root_module['ns3::Ipv4ListRouting']) register_Ns3Ipv4NixVectorRouting_methods(root_module, root_module['ns3::Ipv4NixVectorRouting']) register_Ns3HashImplementation_methods(root_module, root_module['ns3::Hash::Implementation']) register_Ns3HashFunctionFnv1a_methods(root_module, root_module['ns3::Hash::Function::Fnv1a']) register_Ns3HashFunctionHash32_methods(root_module, root_module['ns3::Hash::Function::Hash32']) register_Ns3HashFunctionHash64_methods(root_module, root_module['ns3::Hash::Function::Hash64']) register_Ns3HashFunctionMurmur3_methods(root_module, root_module['ns3::Hash::Function::Murmur3']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::PeekU8() [member function] cls.add_method('PeekU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(ns3::Buffer::Iterator start, uint32_t size) [member function] cls.add_method('Read', 'void', [param('ns3::Buffer::Iterator', 'start'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Hasher_methods(root_module, cls): ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Hasher const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hasher const &', 'arg0')]) ## hash.h (module 'core'): ns3::Hasher::Hasher() [constructor] cls.add_constructor([]) ## hash.h (module 'core'): ns3::Hasher::Hasher(ns3::Ptr<ns3::Hash::Implementation> hp) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Hash::Implementation >', 'hp')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint32_t ns3::Hasher::GetHash32(std::string const s) [member function] cls.add_method('GetHash32', 'uint32_t', [param('std::string const', 's')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')]) ## hash.h (module 'core'): uint64_t ns3::Hasher::GetHash64(std::string const s) [member function] cls.add_method('GetHash64', 'uint64_t', [param('std::string const', 's')]) ## hash.h (module 'core'): ns3::Hasher & ns3::Hasher::clear() [member function] cls.add_method('clear', 'ns3::Hasher &', []) return def register_Ns3Inet6SocketAddress_methods(root_module, cls): ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Inet6SocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::Inet6SocketAddress const &', 'arg0')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(ns3::Ipv6Address ipv6) [constructor] cls.add_constructor([param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv6'), param('uint16_t', 'port')]) ## inet6-socket-address.h (module 'network'): ns3::Inet6SocketAddress::Inet6SocketAddress(char const * ipv6) [constructor] cls.add_constructor([param('char const *', 'ipv6')]) ## inet6-socket-address.h (module 'network'): static ns3::Inet6SocketAddress ns3::Inet6SocketAddress::ConvertFrom(ns3::Address const & addr) [member function] cls.add_method('ConvertFrom', 'ns3::Inet6SocketAddress', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): ns3::Ipv6Address ns3::Inet6SocketAddress::GetIpv6() const [member function] cls.add_method('GetIpv6', 'ns3::Ipv6Address', [], is_const=True) ## inet6-socket-address.h (module 'network'): uint16_t ns3::Inet6SocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet6-socket-address.h (module 'network'): static bool ns3::Inet6SocketAddress::IsMatchingType(ns3::Address const & addr) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'addr')], is_static=True) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetIpv6(ns3::Ipv6Address ipv6) [member function] cls.add_method('SetIpv6', 'void', [param('ns3::Ipv6Address', 'ipv6')]) ## inet6-socket-address.h (module 'network'): void ns3::Inet6SocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) return def register_Ns3InetSocketAddress_methods(root_module, cls): ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::InetSocketAddress const & arg0) [copy constructor] cls.add_constructor([param('ns3::InetSocketAddress const &', 'arg0')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4, uint16_t port) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(ns3::Ipv4Address ipv4) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'ipv4')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(uint16_t port) [constructor] cls.add_constructor([param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4, uint16_t port) [constructor] cls.add_constructor([param('char const *', 'ipv4'), param('uint16_t', 'port')]) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress::InetSocketAddress(char const * ipv4) [constructor] cls.add_constructor([param('char const *', 'ipv4')]) ## inet-socket-address.h (module 'network'): static ns3::InetSocketAddress ns3::InetSocketAddress::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::InetSocketAddress', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): ns3::Ipv4Address ns3::InetSocketAddress::GetIpv4() const [member function] cls.add_method('GetIpv4', 'ns3::Ipv4Address', [], is_const=True) ## inet-socket-address.h (module 'network'): uint16_t ns3::InetSocketAddress::GetPort() const [member function] cls.add_method('GetPort', 'uint16_t', [], is_const=True) ## inet-socket-address.h (module 'network'): static bool ns3::InetSocketAddress::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetIpv4(ns3::Ipv4Address address) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ipv4Address', 'address')]) ## inet-socket-address.h (module 'network'): void ns3::InetSocketAddress::SetPort(uint16_t port) [member function] cls.add_method('SetPort', 'void', [param('uint16_t', 'port')]) 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_Ns3Ipv4InterfaceAddress_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress() [constructor] cls.add_constructor([]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4Address local, ns3::Ipv4Mask mask) [constructor] cls.add_constructor([param('ns3::Ipv4Address', 'local'), param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::Ipv4InterfaceAddress(ns3::Ipv4InterfaceAddress const & o) [copy constructor] cls.add_constructor([param('ns3::Ipv4InterfaceAddress const &', 'o')]) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4InterfaceAddress::GetLocal() const [member function] cls.add_method('GetLocal', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4Mask ns3::Ipv4InterfaceAddress::GetMask() const [member function] cls.add_method('GetMask', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e ns3::Ipv4InterfaceAddress::GetScope() const [member function] cls.add_method('GetScope', 'ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): bool ns3::Ipv4InterfaceAddress::IsSecondary() const [member function] cls.add_method('IsSecondary', 'bool', [], is_const=True) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetBroadcast(ns3::Ipv4Address broadcast) [member function] cls.add_method('SetBroadcast', 'void', [param('ns3::Ipv4Address', 'broadcast')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetLocal(ns3::Ipv4Address local) [member function] cls.add_method('SetLocal', 'void', [param('ns3::Ipv4Address', 'local')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetMask(ns3::Ipv4Mask mask) [member function] cls.add_method('SetMask', 'void', [param('ns3::Ipv4Mask', 'mask')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetPrimary() [member function] cls.add_method('SetPrimary', 'void', []) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetScope(ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SetScope', 'void', [param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')]) ## ipv4-interface-address.h (module 'internet'): void ns3::Ipv4InterfaceAddress::SetSecondary() [member function] cls.add_method('SetSecondary', 'void', []) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv4RoutingHelper_methods(root_module, cls): ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper() [constructor] cls.add_constructor([]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper::Ipv4RoutingHelper(ns3::Ipv4RoutingHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4RoutingHelper const &', 'arg0')]) ## ipv4-routing-helper.h (module 'internet'): ns3::Ipv4RoutingHelper * ns3::Ipv4RoutingHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::Ipv4RoutingHelper *', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4RoutingHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableAllAt(ns3::Time printTime, ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTableAllAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) ## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableAllEvery(ns3::Time printInterval, ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTableAllEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) ## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableAt(ns3::Time printTime, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTableAt', 'void', [param('ns3::Time', 'printTime'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) ## ipv4-routing-helper.h (module 'internet'): void ns3::Ipv4RoutingHelper::PrintRoutingTableEvery(ns3::Time printInterval, ns3::Ptr<ns3::Node> node, ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTableEvery', 'void', [param('ns3::Time', 'printInterval'), param('ns3::Ptr< ns3::Node >', 'node'), param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsDocumentation() const [member function] cls.add_method('IsDocumentation', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() const [member function] cls.add_method('IsIpv4MappedAddress', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac16Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac64Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac16Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac16Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac64Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac64Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_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_Ns3NodeList_methods(root_module, cls): ## node-list.h (module 'network'): ns3::NodeList::NodeList() [constructor] cls.add_constructor([]) ## node-list.h (module 'network'): ns3::NodeList::NodeList(ns3::NodeList const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeList const &', 'arg0')]) ## node-list.h (module 'network'): static uint32_t ns3::NodeList::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'uint32_t', [param('ns3::Ptr< ns3::Node >', 'node')], is_static=True) ## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::Begin() [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_static=True) ## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::End() [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_static=True) ## node-list.h (module 'network'): static uint32_t ns3::NodeList::GetNNodes() [member function] cls.add_method('GetNNodes', 'uint32_t', [], is_static=True) ## node-list.h (module 'network'): static ns3::Ptr<ns3::Node> ns3::NodeList::GetNode(uint32_t n) [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'n')], is_static=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Replace(ns3::Tag & tag) [member function] cls.add_method('Replace', 'bool', [param('ns3::Tag &', 'tag')]) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_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_Ns3TimeWithUnit_methods(root_module, cls): cls.add_output_stream_operator() ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::TimeWithUnit const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeWithUnit const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeWithUnit::TimeWithUnit(ns3::Time const time, ns3::Time::Unit const unit) [constructor] cls.add_constructor([param('ns3::Time const', 'time'), param('ns3::Time::Unit const', 'unit')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetHash() const [member function] cls.add_method('GetHash', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByHash(uint32_t hash) [member function] cls.add_method('LookupByHash', 'ns3::TypeId', [param('uint32_t', 'hash')], is_static=True) ## type-id.h (module 'core'): static bool ns3::TypeId::LookupByHashFailSafe(uint32_t hash, ns3::TypeId * tid) [member function] cls.add_method('LookupByHashFailSafe', 'bool', [param('uint32_t', 'hash'), param('ns3::TypeId *', 'tid')], is_static=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', u'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long double v) [constructor] cls.add_constructor([param('long double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::implementation [variable] cls.add_static_attribute('implementation', 'ns3::int64x64_t::impl_type const', is_const=True) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Ipv4Header_methods(root_module, cls): ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header(ns3::Ipv4Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Header const &', 'arg0')]) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::Ipv4Header() [constructor] cls.add_constructor([]) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::DscpTypeToString(ns3::Ipv4Header::DscpType dscp) const [member function] cls.add_method('DscpTypeToString', 'std::string', [param('ns3::Ipv4Header::DscpType', 'dscp')], is_const=True) ## ipv4-header.h (module 'internet'): std::string ns3::Ipv4Header::EcnTypeToString(ns3::Ipv4Header::EcnType ecn) const [member function] cls.add_method('EcnTypeToString', 'std::string', [param('ns3::Ipv4Header::EcnType', 'ecn')], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::EnableChecksum() [member function] cls.add_method('EnableChecksum', 'void', []) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetDestination() const [member function] cls.add_method('GetDestination', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::DscpType ns3::Ipv4Header::GetDscp() const [member function] cls.add_method('GetDscp', 'ns3::Ipv4Header::DscpType', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Header::EcnType ns3::Ipv4Header::GetEcn() const [member function] cls.add_method('GetEcn', 'ns3::Ipv4Header::EcnType', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetFragmentOffset() const [member function] cls.add_method('GetFragmentOffset', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetIdentification() const [member function] cls.add_method('GetIdentification', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): ns3::TypeId ns3::Ipv4Header::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): uint16_t ns3::Ipv4Header::GetPayloadSize() const [member function] cls.add_method('GetPayloadSize', 'uint16_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetProtocol() const [member function] cls.add_method('GetProtocol', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint32_t ns3::Ipv4Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4Header::GetSource() const [member function] cls.add_method('GetSource', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): uint8_t ns3::Ipv4Header::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## ipv4-header.h (module 'internet'): static ns3::TypeId ns3::Ipv4Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsChecksumOk() const [member function] cls.add_method('IsChecksumOk', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsDontFragment() const [member function] cls.add_method('IsDontFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): bool ns3::Ipv4Header::IsLastFragment() const [member function] cls.add_method('IsLastFragment', 'bool', [], is_const=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_const=True, is_virtual=True) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDestination(ns3::Ipv4Address destination) [member function] cls.add_method('SetDestination', 'void', [param('ns3::Ipv4Address', 'destination')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDontFragment() [member function] cls.add_method('SetDontFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetDscp(ns3::Ipv4Header::DscpType dscp) [member function] cls.add_method('SetDscp', 'void', [param('ns3::Ipv4Header::DscpType', 'dscp')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetEcn(ns3::Ipv4Header::EcnType ecn) [member function] cls.add_method('SetEcn', 'void', [param('ns3::Ipv4Header::EcnType', 'ecn')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetFragmentOffset(uint16_t offsetBytes) [member function] cls.add_method('SetFragmentOffset', 'void', [param('uint16_t', 'offsetBytes')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetIdentification(uint16_t identification) [member function] cls.add_method('SetIdentification', 'void', [param('uint16_t', 'identification')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetLastFragment() [member function] cls.add_method('SetLastFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMayFragment() [member function] cls.add_method('SetMayFragment', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetMoreFragments() [member function] cls.add_method('SetMoreFragments', 'void', []) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetPayloadSize(uint16_t size) [member function] cls.add_method('SetPayloadSize', 'void', [param('uint16_t', 'size')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetProtocol(uint8_t num) [member function] cls.add_method('SetProtocol', 'void', [param('uint8_t', 'num')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetSource(ns3::Ipv4Address source) [member function] cls.add_method('SetSource', 'void', [param('ns3::Ipv4Address', 'source')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) ## ipv4-header.h (module 'internet'): void ns3::Ipv4Header::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3Ipv4NixVectorHelper_methods(root_module, cls): ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper::Ipv4NixVectorHelper() [constructor] cls.add_constructor([]) ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper::Ipv4NixVectorHelper(ns3::Ipv4NixVectorHelper const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4NixVectorHelper const &', 'arg0')]) ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorHelper * ns3::Ipv4NixVectorHelper::Copy() const [member function] cls.add_method('Copy', 'ns3::Ipv4NixVectorHelper *', [], is_const=True, is_virtual=True) ## ipv4-nix-vector-helper.h (module 'nix-vector-routing'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4NixVectorHelper::Create(ns3::Ptr<ns3::Node> node) const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('ns3::Ptr< ns3::Node >', 'node')], is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Initialize() [member function] cls.add_method('Initialize', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3HashImplementation_Ns3Empty_Ns3DefaultDeleter__lt__ns3HashImplementation__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter< ns3::Hash::Implementation > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Hash::Implementation, ns3::empty, ns3::DefaultDeleter<ns3::Hash::Implementation> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__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'): uint8_t ns3::Socket::GetIpTos() const [member function] cls.add_method('GetIpTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpTtl() const [member function] cls.add_method('GetIpTtl', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6HopLimit() const [member function] cls.add_method('GetIpv6HopLimit', 'uint8_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::Socket::GetIpv6Tclass() const [member function] cls.add_method('GetIpv6Tclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Node> ns3::Socket::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## socket.h (module 'network'): 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::IsIpRecvTos() const [member function] cls.add_method('IsIpRecvTos', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpRecvTtl() const [member function] cls.add_method('IsIpRecvTtl', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvHopLimit() const [member function] cls.add_method('IsIpv6RecvHopLimit', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsIpv6RecvTclass() const [member function] cls.add_method('IsIpv6RecvTclass', 'bool', [], is_const=True) ## socket.h (module 'network'): bool ns3::Socket::IsRecvPktInfo() const [member function] cls.add_method('IsRecvPktInfo', 'bool', [], is_const=True) ## socket.h (module 'network'): int ns3::Socket::Listen() [member function] cls.add_method('Listen', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv(uint32_t maxSize, uint32_t flags) [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::Recv() [member function] cls.add_method('Recv', 'ns3::Ptr< ns3::Packet >', []) ## socket.h (module 'network'): int ns3::Socket::Recv(uint8_t * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Recv', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(uint32_t maxSize, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'maxSize'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Socket::RecvFrom(ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'ns3::Ptr< ns3::Packet >', [param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::RecvFrom(uint8_t * buf, uint32_t size, uint32_t flags, ns3::Address & fromAddress) [member function] cls.add_method('RecvFrom', 'int', [param('uint8_t *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address &', 'fromAddress')]) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::Send(ns3::Ptr<ns3::Packet> p) [member function] cls.add_method('Send', 'int', [param('ns3::Ptr< ns3::Packet >', 'p')]) ## socket.h (module 'network'): int ns3::Socket::Send(uint8_t const * buf, uint32_t size, uint32_t flags) [member function] cls.add_method('Send', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags')]) ## socket.h (module 'network'): int ns3::Socket::SendTo(ns3::Ptr<ns3::Packet> p, uint32_t flags, ns3::Address const & toAddress) [member function] cls.add_method('SendTo', 'int', [param('ns3::Ptr< ns3::Packet >', 'p'), param('uint32_t', 'flags'), param('ns3::Address const &', 'toAddress')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::SendTo(uint8_t const * buf, uint32_t size, uint32_t flags, ns3::Address const & address) [member function] cls.add_method('SendTo', 'int', [param('uint8_t const *', 'buf'), param('uint32_t', 'size'), param('uint32_t', 'flags'), param('ns3::Address const &', 'address')]) ## socket.h (module 'network'): void ns3::Socket::SetAcceptCallback(ns3::Callback<bool, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionRequest, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> newConnectionCreated) [member function] cls.add_method('SetAcceptCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionRequest'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'newConnectionCreated')]) ## socket.h (module 'network'): bool ns3::Socket::SetAllowBroadcast(bool allowBroadcast) [member function] cls.add_method('SetAllowBroadcast', 'bool', [param('bool', 'allowBroadcast')], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetCloseCallbacks(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> normalClose, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> errorClose) [member function] cls.add_method('SetCloseCallbacks', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'normalClose'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'errorClose')]) ## socket.h (module 'network'): void ns3::Socket::SetConnectCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionSucceeded, ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> connectionFailed) [member function] cls.add_method('SetConnectCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionSucceeded'), param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'connectionFailed')]) ## socket.h (module 'network'): void ns3::Socket::SetDataSentCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> dataSent) [member function] cls.add_method('SetDataSentCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'dataSent')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTos(bool ipv4RecvTos) [member function] cls.add_method('SetIpRecvTos', 'void', [param('bool', 'ipv4RecvTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpRecvTtl(bool ipv4RecvTtl) [member function] cls.add_method('SetIpRecvTtl', 'void', [param('bool', 'ipv4RecvTtl')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTos(uint8_t ipTos) [member function] cls.add_method('SetIpTos', 'void', [param('uint8_t', 'ipTos')]) ## socket.h (module 'network'): void ns3::Socket::SetIpTtl(uint8_t ipTtl) [member function] cls.add_method('SetIpTtl', 'void', [param('uint8_t', 'ipTtl')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6HopLimit(uint8_t ipHopLimit) [member function] cls.add_method('SetIpv6HopLimit', 'void', [param('uint8_t', 'ipHopLimit')], is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvHopLimit(bool ipv6RecvHopLimit) [member function] cls.add_method('SetIpv6RecvHopLimit', 'void', [param('bool', 'ipv6RecvHopLimit')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6RecvTclass(bool ipv6RecvTclass) [member function] cls.add_method('SetIpv6RecvTclass', 'void', [param('bool', 'ipv6RecvTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetIpv6Tclass(int ipTclass) [member function] cls.add_method('SetIpv6Tclass', 'void', [param('int', 'ipTclass')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> arg0) [member function] cls.add_method('SetRecvCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'arg0')]) ## socket.h (module 'network'): void ns3::Socket::SetRecvPktInfo(bool flag) [member function] cls.add_method('SetRecvPktInfo', 'void', [param('bool', 'flag')]) ## socket.h (module 'network'): void ns3::Socket::SetSendCallback(ns3::Callback<void, ns3::Ptr<ns3::Socket>, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> sendCb) [member function] cls.add_method('SetSendCallback', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::Socket >, unsigned int, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'sendCb')]) ## socket.h (module 'network'): int ns3::Socket::ShutdownRecv() [member function] cls.add_method('ShutdownRecv', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): int ns3::Socket::ShutdownSend() [member function] cls.add_method('ShutdownSend', 'int', [], is_pure_virtual=True, is_virtual=True) ## socket.h (module 'network'): void ns3::Socket::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTos() const [member function] cls.add_method('IsManualIpTos', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpTtl() const [member function] cls.add_method('IsManualIpTtl', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6HopLimit() const [member function] cls.add_method('IsManualIpv6HopLimit', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::IsManualIpv6Tclass() const [member function] cls.add_method('IsManualIpv6Tclass', 'bool', [], is_const=True, visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionFailed() [member function] cls.add_method('NotifyConnectionFailed', 'void', [], visibility='protected') ## socket.h (module 'network'): bool ns3::Socket::NotifyConnectionRequest(ns3::Address const & from) [member function] cls.add_method('NotifyConnectionRequest', 'bool', [param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyConnectionSucceeded() [member function] cls.add_method('NotifyConnectionSucceeded', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataRecv() [member function] cls.add_method('NotifyDataRecv', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyDataSent(uint32_t size) [member function] cls.add_method('NotifyDataSent', 'void', [param('uint32_t', 'size')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyErrorClose() [member function] cls.add_method('NotifyErrorClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNewConnectionCreated(ns3::Ptr<ns3::Socket> socket, ns3::Address const & from) [member function] cls.add_method('NotifyNewConnectionCreated', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket'), param('ns3::Address const &', 'from')], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifyNormalClose() [member function] cls.add_method('NotifyNormalClose', 'void', [], visibility='protected') ## socket.h (module 'network'): void ns3::Socket::NotifySend(uint32_t spaceAvailable) [member function] cls.add_method('NotifySend', 'void', [param('uint32_t', 'spaceAvailable')], visibility='protected') return def register_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_Ns3SocketIpTosTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag(ns3::SocketIpTosTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTosTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTosTag::SocketIpTosTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTosTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTosTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTosTag::GetTos() const [member function] cls.add_method('GetTos', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTosTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTosTag::SetTos(uint8_t tos) [member function] cls.add_method('SetTos', 'void', [param('uint8_t', 'tos')]) return def register_Ns3SocketIpTtlTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag(ns3::SocketIpTtlTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpTtlTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpTtlTag::SocketIpTtlTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpTtlTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpTtlTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpTtlTag::GetTtl() const [member function] cls.add_method('GetTtl', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpTtlTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpTtlTag::SetTtl(uint8_t ttl) [member function] cls.add_method('SetTtl', 'void', [param('uint8_t', 'ttl')]) return def register_Ns3SocketIpv6HopLimitTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag(ns3::SocketIpv6HopLimitTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6HopLimitTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6HopLimitTag::SocketIpv6HopLimitTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6HopLimitTag::GetHopLimit() const [member function] cls.add_method('GetHopLimit', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6HopLimitTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6HopLimitTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6HopLimitTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6HopLimitTag::SetHopLimit(uint8_t hopLimit) [member function] cls.add_method('SetHopLimit', 'void', [param('uint8_t', 'hopLimit')]) return def register_Ns3SocketIpv6TclassTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag(ns3::SocketIpv6TclassTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketIpv6TclassTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketIpv6TclassTag::SocketIpv6TclassTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): ns3::TypeId ns3::SocketIpv6TclassTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketIpv6TclassTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint8_t ns3::SocketIpv6TclassTag::GetTclass() const [member function] cls.add_method('GetTclass', 'uint8_t', [], is_const=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketIpv6TclassTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketIpv6TclassTag::SetTclass(uint8_t tclass) [member function] cls.add_method('SetTclass', 'void', [param('uint8_t', 'tclass')]) return def register_Ns3SocketSetDontFragmentTag_methods(root_module, cls): ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag(ns3::SocketSetDontFragmentTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::SocketSetDontFragmentTag const &', 'arg0')]) ## socket.h (module 'network'): ns3::SocketSetDontFragmentTag::SocketSetDontFragmentTag() [constructor] cls.add_constructor([]) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Disable() [member function] cls.add_method('Disable', 'void', []) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Enable() [member function] cls.add_method('Enable', 'void', []) ## socket.h (module 'network'): ns3::TypeId ns3::SocketSetDontFragmentTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): uint32_t ns3::SocketSetDontFragmentTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## socket.h (module 'network'): static ns3::TypeId ns3::SocketSetDontFragmentTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## socket.h (module 'network'): bool ns3::SocketSetDontFragmentTag::IsEnabled() const [member function] cls.add_method('IsEnabled', 'bool', [], is_const=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## socket.h (module 'network'): void ns3::SocketSetDontFragmentTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', u'right')) cls.add_binary_numeric_operator('/', root_module['ns3::Time'], root_module['ns3::Time'], param('int64_t const &', u'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', u'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', u'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & v) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::TimeWithUnit ns3::Time::As(ns3::Time::Unit const unit) const [member function] cls.add_method('As', 'ns3::TimeWithUnit', [param('ns3::Time::Unit const', 'unit')], is_const=True) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value, ns3::Time::Unit unit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit unit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit unit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'unit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDays() const [member function] cls.add_method('GetDays', 'double', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetHours() const [member function] cls.add_method('GetHours', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetMinutes() const [member function] cls.add_method('GetMinutes', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): double ns3::Time::GetYears() const [member function] cls.add_method('GetYears', 'double', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Max() [member function] cls.add_method('Max', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::Min() [member function] cls.add_method('Min', 'ns3::Time', [], is_static=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): static bool ns3::Time::StaticInit() [member function] cls.add_method('StaticInit', 'bool', [], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit unit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit unit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'unit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit unit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'unit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): 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_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_Ns3Ipv4_methods(root_module, cls): ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4(ns3::Ipv4 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4 const &', 'arg0')]) ## ipv4.h (module 'internet'): ns3::Ipv4::Ipv4() [constructor] cls.add_constructor([]) ## ipv4.h (module 'internet'): bool ns3::Ipv4::AddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('AddAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::AddInterface(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddInterface', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::Socket> ns3::Ipv4::CreateRawSocket() [member function] cls.add_method('CreateRawSocket', 'ns3::Ptr< ns3::Socket >', [], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::DeleteRawSocket(ns3::Ptr<ns3::Socket> socket) [member function] cls.add_method('DeleteRawSocket', 'void', [param('ns3::Ptr< ns3::Socket >', 'socket')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4InterfaceAddress ns3::Ipv4::GetAddress(uint32_t interface, uint32_t addressIndex) const [member function] cls.add_method('GetAddress', 'ns3::Ipv4InterfaceAddress', [param('uint32_t', 'interface'), param('uint32_t', 'addressIndex')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForAddress(ns3::Ipv4Address address) const [member function] cls.add_method('GetInterfaceForAddress', 'int32_t', [param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForDevice(ns3::Ptr<const ns3::NetDevice> device) const [member function] cls.add_method('GetInterfaceForDevice', 'int32_t', [param('ns3::Ptr< ns3::NetDevice const >', 'device')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): int32_t ns3::Ipv4::GetInterfaceForPrefix(ns3::Ipv4Address address, ns3::Ipv4Mask mask) const [member function] cls.add_method('GetInterfaceForPrefix', 'int32_t', [param('ns3::Ipv4Address', 'address'), param('ns3::Ipv4Mask', 'mask')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMetric(uint32_t interface) const [member function] cls.add_method('GetMetric', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint16_t ns3::Ipv4::GetMtu(uint32_t interface) const [member function] cls.add_method('GetMtu', 'uint16_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNAddresses(uint32_t interface) const [member function] cls.add_method('GetNAddresses', 'uint32_t', [param('uint32_t', 'interface')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): uint32_t ns3::Ipv4::GetNInterfaces() const [member function] cls.add_method('GetNInterfaces', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::NetDevice> ns3::Ipv4::GetNetDevice(uint32_t interface) [member function] cls.add_method('GetNetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::IpL4Protocol> ns3::Ipv4::GetProtocol(int protocolNumber) const [member function] cls.add_method('GetProtocol', 'ns3::Ptr< ns3::IpL4Protocol >', [param('int', 'protocolNumber')], is_pure_virtual=True, is_const=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ptr<ns3::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'): bool ns3::Ipv4::RemoveAddress(uint32_t interface, ns3::Ipv4Address address) [member function] cls.add_method('RemoveAddress', 'bool', [param('uint32_t', 'interface'), param('ns3::Ipv4Address', 'address')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::Ipv4Address ns3::Ipv4::SelectSourceAddress(ns3::Ptr<const ns3::NetDevice> device, ns3::Ipv4Address dst, ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e scope) [member function] cls.add_method('SelectSourceAddress', 'ns3::Ipv4Address', [param('ns3::Ptr< ns3::NetDevice const >', 'device'), param('ns3::Ipv4Address', 'dst'), param('ns3::Ipv4InterfaceAddress::InterfaceAddressScope_e', 'scope')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::Send(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Address source, ns3::Ipv4Address destination, uint8_t protocol, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('Send', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Address', 'source'), param('ns3::Ipv4Address', 'destination'), param('uint8_t', 'protocol'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SendWithHeader(ns3::Ptr<ns3::Packet> packet, ns3::Ipv4Header ipHeader, ns3::Ptr<ns3::Ipv4Route> route) [member function] cls.add_method('SendWithHeader', 'void', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Ipv4Header', 'ipHeader'), param('ns3::Ptr< ns3::Ipv4Route >', 'route')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetDown(uint32_t interface) [member function] cls.add_method('SetDown', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetForwarding(uint32_t interface, bool val) [member function] cls.add_method('SetForwarding', 'void', [param('uint32_t', 'interface'), param('bool', 'val')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetMetric(uint32_t interface, uint16_t metric) [member function] cls.add_method('SetMetric', 'void', [param('uint32_t', 'interface'), param('uint16_t', 'metric')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol) [member function] cls.add_method('SetRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): void ns3::Ipv4::SetUp(uint32_t interface) [member function] cls.add_method('SetUp', 'void', [param('uint32_t', 'interface')], is_pure_virtual=True, is_virtual=True) ## ipv4.h (module 'internet'): ns3::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_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_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, 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 >, unsigned short, 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<ns3::Packet const>, unsigned short, ns3::Address const&, 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 >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_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'): bool ns3::Packet::ReplacePacketTag(ns3::Tag & tag) [member function] cls.add_method('ReplacePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> nixVector) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'nixVector')]) return def register_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_Ns3BridgeChannel_methods(root_module, cls): ## bridge-channel.h (module 'bridge'): static ns3::TypeId ns3::BridgeChannel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bridge-channel.h (module 'bridge'): ns3::BridgeChannel::BridgeChannel() [constructor] cls.add_constructor([]) ## bridge-channel.h (module 'bridge'): void ns3::BridgeChannel::AddChannel(ns3::Ptr<ns3::Channel> bridgedChannel) [member function] cls.add_method('AddChannel', 'void', [param('ns3::Ptr< ns3::Channel >', 'bridgedChannel')]) ## bridge-channel.h (module 'bridge'): uint32_t ns3::BridgeChannel::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True, is_virtual=True) ## bridge-channel.h (module 'bridge'): ns3::Ptr<ns3::NetDevice> ns3::BridgeChannel::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) return def register_Ns3BridgeNetDevice_methods(root_module, cls): ## bridge-net-device.h (module 'bridge'): ns3::BridgeNetDevice::BridgeNetDevice() [constructor] cls.add_constructor([]) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::AddBridgePort(ns3::Ptr<ns3::NetDevice> bridgePort) [member function] cls.add_method('AddBridgePort', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'bridgePort')]) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::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_virtual=True) ## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::NetDevice> ns3::BridgeNetDevice::GetBridgePort(uint32_t n) const [member function] cls.add_method('GetBridgePort', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'n')], is_const=True) ## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::Channel> ns3::BridgeNetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): uint32_t ns3::BridgeNetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): uint16_t ns3::BridgeNetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): ns3::Address ns3::BridgeNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): uint32_t ns3::BridgeNetDevice::GetNBridgePorts() const [member function] cls.add_method('GetNBridgePorts', 'uint32_t', [], is_const=True) ## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::Node> ns3::BridgeNetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): static ns3::TypeId ns3::BridgeNetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::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_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::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_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetPromiscReceiveCallback(ns3::Callback<bool, 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> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, 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 >', 'cb')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::SetReceiveCallback(ns3::Callback<bool, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, 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 >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_virtual=True) ## bridge-net-device.h (module 'bridge'): bool ns3::BridgeNetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_const=True, is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::ForwardBroadcast(ns3::Ptr<ns3::NetDevice> incomingPort, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address src, ns3::Mac48Address dst) [member function] cls.add_method('ForwardBroadcast', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'incomingPort'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'src'), param('ns3::Mac48Address', 'dst')], visibility='protected') ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::ForwardUnicast(ns3::Ptr<ns3::NetDevice> incomingPort, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Mac48Address src, ns3::Mac48Address dst) [member function] cls.add_method('ForwardUnicast', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'incomingPort'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Mac48Address', 'src'), param('ns3::Mac48Address', 'dst')], visibility='protected') ## bridge-net-device.h (module 'bridge'): ns3::Ptr<ns3::NetDevice> ns3::BridgeNetDevice::GetLearnedState(ns3::Mac48Address source) [member function] cls.add_method('GetLearnedState', 'ns3::Ptr< ns3::NetDevice >', [param('ns3::Mac48Address', 'source')], visibility='protected') ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::Learn(ns3::Mac48Address source, ns3::Ptr<ns3::NetDevice> port) [member function] cls.add_method('Learn', 'void', [param('ns3::Mac48Address', 'source'), param('ns3::Ptr< ns3::NetDevice >', 'port')], visibility='protected') ## bridge-net-device.h (module 'bridge'): void ns3::BridgeNetDevice::ReceiveFromDevice(ns3::Ptr<ns3::NetDevice> device, ns3::Ptr<const ns3::Packet> packet, uint16_t protocol, ns3::Address const & source, ns3::Address const & destination, ns3::NetDevice::PacketType packetType) [member function] cls.add_method('ReceiveFromDevice', 'void', [param('ns3::Ptr< ns3::NetDevice >', 'device'), param('ns3::Ptr< ns3::Packet const >', 'packet'), param('uint16_t', 'protocol'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'destination'), param('ns3::NetDevice::PacketType', 'packetType')], visibility='protected') return def register_Ns3Ipv4ListRouting_methods(root_module, cls): ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting(ns3::Ipv4ListRouting const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4ListRouting const &', 'arg0')]) ## ipv4-list-routing.h (module 'internet'): ns3::Ipv4ListRouting::Ipv4ListRouting() [constructor] cls.add_constructor([]) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::AddRoutingProtocol(ns3::Ptr<ns3::Ipv4RoutingProtocol> routingProtocol, int16_t priority) [member function] cls.add_method('AddRoutingProtocol', 'void', [param('ns3::Ptr< ns3::Ipv4RoutingProtocol >', 'routingProtocol'), param('int16_t', 'priority')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): uint32_t ns3::Ipv4ListRouting::GetNRoutingProtocols() const [member function] cls.add_method('GetNRoutingProtocols', 'uint32_t', [], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4RoutingProtocol> ns3::Ipv4ListRouting::GetRoutingProtocol(uint32_t index, int16_t & priority) const [member function] cls.add_method('GetRoutingProtocol', 'ns3::Ptr< ns3::Ipv4RoutingProtocol >', [param('uint32_t', 'index'), param('int16_t &', 'priority', direction=2)], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): static ns3::TypeId ns3::Ipv4ListRouting::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True, is_virtual=True) ## ipv4-list-routing.h (module 'internet'): bool ns3::Ipv4ListRouting::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_virtual=True) ## ipv4-list-routing.h (module 'internet'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4ListRouting::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_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## ipv4-list-routing.h (module 'internet'): void ns3::Ipv4ListRouting::DoInitialize() [member function] cls.add_method('DoInitialize', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3Ipv4NixVectorRouting_methods(root_module, cls): ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorRouting::Ipv4NixVectorRouting(ns3::Ipv4NixVectorRouting const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4NixVectorRouting const &', 'arg0')]) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ipv4NixVectorRouting::Ipv4NixVectorRouting() [constructor] cls.add_constructor([]) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::FlushGlobalNixRoutingCache() [member function] cls.add_method('FlushGlobalNixRoutingCache', 'void', []) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): static ns3::TypeId ns3::Ipv4NixVectorRouting::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyAddAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyAddAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyInterfaceDown(uint32_t interface) [member function] cls.add_method('NotifyInterfaceDown', 'void', [param('uint32_t', 'interface')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyInterfaceUp(uint32_t interface) [member function] cls.add_method('NotifyInterfaceUp', 'void', [param('uint32_t', 'interface')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::NotifyRemoveAddress(uint32_t interface, ns3::Ipv4InterfaceAddress address) [member function] cls.add_method('NotifyRemoveAddress', 'void', [param('uint32_t', 'interface'), param('ns3::Ipv4InterfaceAddress', 'address')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::PrintRoutingTable(ns3::Ptr<ns3::OutputStreamWrapper> stream) const [member function] cls.add_method('PrintRoutingTable', 'void', [param('ns3::Ptr< ns3::OutputStreamWrapper >', 'stream')], is_const=True, visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): bool ns3::Ipv4NixVectorRouting::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')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): ns3::Ptr<ns3::Ipv4Route> ns3::Ipv4NixVectorRouting::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')], visibility='private', is_virtual=True) ## ipv4-nix-vector-routing.h (module 'nix-vector-routing'): void ns3::Ipv4NixVectorRouting::SetIpv4(ns3::Ptr<ns3::Ipv4> ipv4) [member function] cls.add_method('SetIpv4', 'void', [param('ns3::Ptr< ns3::Ipv4 >', 'ipv4')], visibility='private', is_virtual=True) return def register_Ns3HashImplementation_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation(ns3::Hash::Implementation const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Implementation const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Implementation::Implementation() [constructor] cls.add_constructor([]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Implementation::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_pure_virtual=True, is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Implementation::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Implementation::clear() [member function] cls.add_method('clear', 'void', [], is_pure_virtual=True, is_virtual=True) return def register_Ns3HashFunctionFnv1a_methods(root_module, cls): ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a(ns3::Hash::Function::Fnv1a const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Fnv1a const &', 'arg0')]) ## hash-fnv.h (module 'core'): ns3::Hash::Function::Fnv1a::Fnv1a() [constructor] cls.add_constructor([]) ## hash-fnv.h (module 'core'): uint32_t ns3::Hash::Function::Fnv1a::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): uint64_t ns3::Hash::Function::Fnv1a::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-fnv.h (module 'core'): void ns3::Hash::Function::Fnv1a::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash32_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Function::Hash32 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash32 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash32::Hash32(ns3::Hash::Hash32Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash32Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash32::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash32::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionHash64_methods(root_module, cls): ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Function::Hash64 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Hash64 const &', 'arg0')]) ## hash-function.h (module 'core'): ns3::Hash::Function::Hash64::Hash64(ns3::Hash::Hash64Function_ptr hp) [constructor] cls.add_constructor([param('ns3::Hash::Hash64Function_ptr', 'hp')]) ## hash-function.h (module 'core'): uint32_t ns3::Hash::Function::Hash64::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): uint64_t ns3::Hash::Function::Hash64::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-function.h (module 'core'): void ns3::Hash::Function::Hash64::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_Ns3HashFunctionMurmur3_methods(root_module, cls): ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3(ns3::Hash::Function::Murmur3 const & arg0) [copy constructor] cls.add_constructor([param('ns3::Hash::Function::Murmur3 const &', 'arg0')]) ## hash-murmur3.h (module 'core'): ns3::Hash::Function::Murmur3::Murmur3() [constructor] cls.add_constructor([]) ## hash-murmur3.h (module 'core'): uint32_t ns3::Hash::Function::Murmur3::GetHash32(char const * buffer, size_t const size) [member function] cls.add_method('GetHash32', 'uint32_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): uint64_t ns3::Hash::Function::Murmur3::GetHash64(char const * buffer, size_t const size) [member function] cls.add_method('GetHash64', 'uint64_t', [param('char const *', 'buffer'), param('size_t const', 'size')], is_virtual=True) ## hash-murmur3.h (module 'core'): void ns3::Hash::Function::Murmur3::clear() [member function] cls.add_method('clear', 'void', [], is_virtual=True) return def register_functions(root_module): module = root_module register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) register_functions_ns3_Hash(module.get_submodule('Hash'), root_module) return def register_functions_ns3_FatalImpl(module, root_module): return def register_functions_ns3_Hash(module, root_module): register_functions_ns3_Hash_Function(module.get_submodule('Function'), root_module) return def register_functions_ns3_Hash_Function(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
gpl-2.0
wxgeo/geophar
wxgeometrie/sympy/polys/tests/test_injections.py
126
1795
"""Tests for functions that inject symbols into the global namespace. """ from sympy.polys.rings import vring from sympy.polys.fields import vfield from sympy.polys.domains import QQ from sympy.utilities.pytest import raises # make r1 with call-depth = 1 def _make_r1(): return vring("r1", QQ) # make r2 with call-depth = 2 def __make_r2(): return vring("r2", QQ) def _make_r2(): return __make_r2() def test_vring(): R = vring("r", QQ) assert r == R.gens[0] R = vring("rb rbb rcc rzz _rx", QQ) assert rb == R.gens[0] assert rbb == R.gens[1] assert rcc == R.gens[2] assert rzz == R.gens[3] assert _rx == R.gens[4] R = vring(['rd', 're', 'rfg'], QQ) assert rd == R.gens[0] assert re == R.gens[1] assert rfg == R.gens[2] # see if vring() really injects into global namespace raises(NameError, lambda: r1) R = _make_r1() assert r1 == R.gens[0] raises(NameError, lambda: r2) R = _make_r2() assert r2 == R.gens[0] # make f1 with call-depth = 1 def _make_f1(): return vfield("f1", QQ) # make f2 with call-depth = 2 def __make_f2(): return vfield("f2", QQ) def _make_f2(): return __make_f2() def test_vfield(): F = vfield("f", QQ) assert f == F.gens[0] F = vfield("fb fbb fcc fzz _fx", QQ) assert fb == F.gens[0] assert fbb == F.gens[1] assert fcc == F.gens[2] assert fzz == F.gens[3] assert _fx == F.gens[4] F = vfield(['fd', 'fe', 'ffg'], QQ) assert fd == F.gens[0] assert fe == F.gens[1] assert ffg == F.gens[2] # see if vfield() really injects into global namespace raises(NameError, lambda: f1) F = _make_f1() assert f1 == F.gens[0] raises(NameError, lambda: f2) F = _make_f2() assert f2 == F.gens[0]
gpl-2.0
ConectividadInnovadoraSAdeCV/WeOn
src/weon_daemon_interface.py
1
4440
#!/usr/bin/python import logging import time import datetime import urllib2 import os import sys import subprocess from daemon import runner import multiprocessing import weon_threads import weon_user_management import weon_utils import weon_test class weon_daemonize(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = '/var/log/weon_daemon/system.log' self.stderr_path = '/var/log/weon_daemon/system.log' self.pidfile_path = '/var/run/weon_daemon/daemon_interface.pid' self.pidfile_timeout = 5 self.check_services = 0 self.report = 0 self.threads = dict() self.user_management = "" def _weon_user(self,logger): if not self.user_management: logger.info("Start service for user connections") self.user_management = multiprocessing.Process(target=weon_user_management.start_service, args=(logger,)) self.user_management.start() def _thread_logs(self,logger): if not self.threads: logger.info( "Create threads for status, gps and active" ) self.threads["active_log"] = weon_threads.active_thread(0,"active_log", self.weon_connection, logger) self.threads["status_log"] = weon_threads.status_thread(1, "status_log", self.weon_connection, logger) self.threads["gps_log"] = weon_threads.gps_thread(2, "gps_log", self.weon_connection, logger) [ self.threads[thread_log].start() for thread_log in self.threads.keys() ] def _check_thread_logs(self,logger): if not self.threads["active_log"].isAlive(): self.threads["active_log"] = "" self.threads["active_log"] = weon_threads.active_thread(0,"active_log", self.weon_connection, logger) self.threads["active_log"].start() if not self.threads["status_log"].isAlive(): self.threads["status_log"] = "" self.threads["status_log"] = weon_threads.status_thread(1, "status_log", self.weon_connection, logger) self.threads["status_log"].start() if not self.threads["gps_log"].isAlive(): self.threads["gps_log"] = "" self.threads["gps_log"] = weon_threads.gps_thread(2, "gps_log", self.weon_connection, logger) self.threads["gps_log"].start() def _check_weon_user_process( self, logger ): if not self.user_management.is_alive(): self.user_management = "" def run(self): self.weon_connection = weon_utils.read_conf_file() while True: try: if urllib2.urlopen('http://www.google.com',timeout=9): if not self.check_services: self.check_services = weon_utils.check_services(logger) weon_test.gps_testing( logger ) if not self.report: self.report = weon_utils.reporter(self.weon_connection, logger) self._weon_user(logger) self._thread_logs(logger) self._check_thread_logs(logger) self._check_weon_user_process( logger ) time.sleep(1) else: logger.info("Unable to connect: %s " % datetime.datetime.now()) time.sleep(60) except urllib2.URLError: logger.info("Lost connection") if self.threads: weon_threads.exit() time.sleep(60) [ logger.info("%s - %s" %(self.threads[thread_log].isAlive(),self.threads[thread_log].getName())) for thread_log in self.threads.keys() ] [ thread.join() for thread in self.threads if self.threads[thread].isAlive == True ] self.threads = dict() weon_threads.start() self.check_services = 0 time.sleep(5) continue logger = logging.getLogger("WeOn Log") logger.setLevel(logging.INFO) ftpd = weon_daemonize() formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler = logging.FileHandler("/var/log/weon_daemon/weon_daemon.log") handler.setFormatter(formatter) logger.addHandler(handler) daemon_runner = runner.DaemonRunner(ftpd) daemon_runner.daemon_context.files_preserve=[handler.stream] daemon_runner.do_action()
apache-2.0
iankronquist/hamper
hamper/tests/test_command.py
3
1166
from unittest import TestCase from hamper.interfaces import Command class CommandSubclass(Command): regex = "^!test(.*)$" def command(self, unused, d, matches): self.matches = matches class TestCommand(TestCase): """ The Command class provides some basic structure for regex-powered commands. """ def test_only_directed(self): c = CommandSubclass(None) d = {"directed": False} self.assertFalse(c.message(None, d)) def test_no_match(self): c = CommandSubclass(None) c.onlyDirected = False d = {"directed": False, "message": "!example"} self.assertFalse(c.message(None, d)) def test_simple_match(self): c = CommandSubclass(None) c.onlyDirected = False d = {"directed": False, "message": "!test"} self.assertTrue(c.message(None, d)) self.assertEqual(c.matches, ("",)) def test_match_groups(self): c = CommandSubclass(None) c.onlyDirected = False d = {"directed": False, "message": "!testing"} self.assertTrue(c.message(None, d)) self.assertEqual(c.matches, ("ing",))
mit
AnhellO/DAS_Sistemas
Ago-Dic-2017/Enrique Castillo/Ordinario/test/Lib/site-packages/django/contrib/gis/ptr.py
59
1276
from ctypes import c_void_p class CPointerBase: """ Base class for objects that have a pointer access property that controls access to the underlying C pointer. """ _ptr = None # Initially the pointer is NULL. ptr_type = c_void_p destructor = None null_ptr_exception_class = AttributeError @property def ptr(self): # Raise an exception if the pointer isn't valid so that NULL pointers # aren't passed to routines -- that's very bad. if self._ptr: return self._ptr raise self.null_ptr_exception_class('NULL %s pointer encountered.' % self.__class__.__name__) @ptr.setter def ptr(self, ptr): # Only allow the pointer to be set with pointers of the compatible # type or None (NULL). if not (ptr is None or isinstance(ptr, self.ptr_type)): raise TypeError('Incompatible pointer type: %s.' % type(ptr)) self._ptr = ptr def __del__(self): """ Free the memory used by the C++ object. """ if self.destructor and self._ptr: try: self.destructor(self.ptr) except (AttributeError, TypeError): pass # Some part might already have been garbage collected
mit
anntzer/scikit-learn
sklearn/datasets/_species_distributions.py
11
8726
""" ============================= Species distribution dataset ============================= This dataset represents the geographic distribution of species. The dataset is provided by Phillips et. al. (2006). The two species are: - `"Bradypus variegatus" <http://www.iucnredlist.org/details/3038/0>`_ , the Brown-throated Sloth. - `"Microryzomys minutus" <http://www.iucnredlist.org/details/13408/0>`_ , also known as the Forest Small Rice Rat, a rodent that lives in Peru, Colombia, Ecuador, Peru, and Venezuela. References ---------- `"Maximum entropy modeling of species geographic distributions" <http://rob.schapire.net/papers/ecolmod.pdf>`_ S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006. Notes ----- For an example of using this dataset, see :ref:`examples/applications/plot_species_distribution_modeling.py <sphx_glr_auto_examples_applications_plot_species_distribution_modeling.py>`. """ # Authors: Peter Prettenhofer <peter.prettenhofer@gmail.com> # Jake Vanderplas <vanderplas@astro.washington.edu> # # License: BSD 3 clause from io import BytesIO from os import makedirs, remove from os.path import exists import logging import numpy as np import joblib from . import get_data_home from ._base import _fetch_remote from ._base import RemoteFileMetadata from ..utils import Bunch from ..utils.validation import _deprecate_positional_args from ._base import _pkl_filepath # The original data can be found at: # https://biodiversityinformatics.amnh.org/open_source/maxent/samples.zip SAMPLES = RemoteFileMetadata( filename='samples.zip', url='https://ndownloader.figshare.com/files/5976075', checksum=('abb07ad284ac50d9e6d20f1c4211e0fd' '3c098f7f85955e89d321ee8efe37ac28')) # The original data can be found at: # https://biodiversityinformatics.amnh.org/open_source/maxent/coverages.zip COVERAGES = RemoteFileMetadata( filename='coverages.zip', url='https://ndownloader.figshare.com/files/5976078', checksum=('4d862674d72e79d6cee77e63b98651ec' '7926043ba7d39dcb31329cf3f6073807')) DATA_ARCHIVE_NAME = "species_coverage.pkz" logger = logging.getLogger(__name__) def _load_coverage(F, header_length=6, dtype=np.int16): """Load a coverage file from an open file object. This will return a numpy array of the given dtype """ header = [F.readline() for _ in range(header_length)] make_tuple = lambda t: (t.split()[0], float(t.split()[1])) header = dict([make_tuple(line) for line in header]) M = np.loadtxt(F, dtype=dtype) nodata = int(header[b'NODATA_value']) if nodata != -9999: M[nodata] = -9999 return M def _load_csv(F): """Load csv file. Parameters ---------- F : file object CSV file open in byte mode. Returns ------- rec : np.ndarray record array representing the data """ names = F.readline().decode('ascii').strip().split(',') rec = np.loadtxt(F, skiprows=0, delimiter=',', dtype='a22,f4,f4') rec.dtype.names = names return rec def construct_grids(batch): """Construct the map grid from the batch object Parameters ---------- batch : Batch object The object returned by :func:`fetch_species_distributions` Returns ------- (xgrid, ygrid) : 1-D arrays The grid corresponding to the values in batch.coverages """ # x,y coordinates for corner cells xmin = batch.x_left_lower_corner + batch.grid_size xmax = xmin + (batch.Nx * batch.grid_size) ymin = batch.y_left_lower_corner + batch.grid_size ymax = ymin + (batch.Ny * batch.grid_size) # x coordinates of the grid cells xgrid = np.arange(xmin, xmax, batch.grid_size) # y coordinates of the grid cells ygrid = np.arange(ymin, ymax, batch.grid_size) return (xgrid, ygrid) @_deprecate_positional_args def fetch_species_distributions(*, data_home=None, download_if_missing=True): """Loader for species distribution dataset from Phillips et. al. (2006) Read more in the :ref:`User Guide <datasets>`. Parameters ---------- data_home : str, default=None Specify another download and cache folder for the datasets. By default all scikit-learn data is stored in '~/scikit_learn_data' subfolders. download_if_missing : bool, default=True If False, raise a IOError if the data is not locally available instead of trying to download the data from the source site. Returns ------- data : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. coverages : array, shape = [14, 1592, 1212] These represent the 14 features measured at each point of the map grid. The latitude/longitude values for the grid are discussed below. Missing data is represented by the value -9999. train : record array, shape = (1624,) The training points for the data. Each point has three fields: - train['species'] is the species name - train['dd long'] is the longitude, in degrees - train['dd lat'] is the latitude, in degrees test : record array, shape = (620,) The test points for the data. Same format as the training data. Nx, Ny : integers The number of longitudes (x) and latitudes (y) in the grid x_left_lower_corner, y_left_lower_corner : floats The (x,y) position of the lower-left corner, in degrees grid_size : float The spacing between points of the grid, in degrees References ---------- * `"Maximum entropy modeling of species geographic distributions" <http://rob.schapire.net/papers/ecolmod.pdf>`_ S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006. Notes ----- This dataset represents the geographic distribution of species. The dataset is provided by Phillips et. al. (2006). The two species are: - `"Bradypus variegatus" <http://www.iucnredlist.org/details/3038/0>`_ , the Brown-throated Sloth. - `"Microryzomys minutus" <http://www.iucnredlist.org/details/13408/0>`_ , also known as the Forest Small Rice Rat, a rodent that lives in Peru, Colombia, Ecuador, Peru, and Venezuela. - For an example of using this dataset with scikit-learn, see :ref:`examples/applications/plot_species_distribution_modeling.py <sphx_glr_auto_examples_applications_plot_species_distribution_modeling.py>`. """ data_home = get_data_home(data_home) if not exists(data_home): makedirs(data_home) # Define parameters for the data files. These should not be changed # unless the data model changes. They will be saved in the npz file # with the downloaded data. extra_params = dict(x_left_lower_corner=-94.8, Nx=1212, y_left_lower_corner=-56.05, Ny=1592, grid_size=0.05) dtype = np.int16 archive_path = _pkl_filepath(data_home, DATA_ARCHIVE_NAME) if not exists(archive_path): if not download_if_missing: raise IOError("Data not found and `download_if_missing` is False") logger.info('Downloading species data from %s to %s' % ( SAMPLES.url, data_home)) samples_path = _fetch_remote(SAMPLES, dirname=data_home) with np.load(samples_path) as X: # samples.zip is a valid npz for f in X.files: fhandle = BytesIO(X[f]) if 'train' in f: train = _load_csv(fhandle) if 'test' in f: test = _load_csv(fhandle) remove(samples_path) logger.info('Downloading coverage data from %s to %s' % ( COVERAGES.url, data_home)) coverages_path = _fetch_remote(COVERAGES, dirname=data_home) with np.load(coverages_path) as X: # coverages.zip is a valid npz coverages = [] for f in X.files: fhandle = BytesIO(X[f]) logger.debug(' - converting {}'.format(f)) coverages.append(_load_coverage(fhandle)) coverages = np.asarray(coverages, dtype=dtype) remove(coverages_path) bunch = Bunch(coverages=coverages, test=test, train=train, **extra_params) joblib.dump(bunch, archive_path, compress=9) else: bunch = joblib.load(archive_path) return bunch
bsd-3-clause
40223125/w16btest1
static/Brython3.1.3-20150514-095342/Lib/unittest/test/test_loader.py
738
49593
import sys import types import unittest class Test_TestLoader(unittest.TestCase): ### Tests for TestLoader.loadTestsFromTestCase ################################################################ # "Return a suite of all tests cases contained in the TestCase-derived # class testCaseClass" def test_loadTestsFromTestCase(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) loader = unittest.TestLoader() self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) # "Return a suite of all tests cases contained in the TestCase-derived # class testCaseClass" # # Make sure it does the right thing even if no tests were found def test_loadTestsFromTestCase__no_matches(self): class Foo(unittest.TestCase): def foo_bar(self): pass empty_suite = unittest.TestSuite() loader = unittest.TestLoader() self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite) # "Return a suite of all tests cases contained in the TestCase-derived # class testCaseClass" # # What happens if loadTestsFromTestCase() is given an object # that isn't a subclass of TestCase? Specifically, what happens # if testCaseClass is a subclass of TestSuite? # # This is checked for specifically in the code, so we better add a # test for it. def test_loadTestsFromTestCase__TestSuite_subclass(self): class NotATestCase(unittest.TestSuite): pass loader = unittest.TestLoader() try: loader.loadTestsFromTestCase(NotATestCase) except TypeError: pass else: self.fail('Should raise TypeError') # "Return a suite of all tests cases contained in the TestCase-derived # class testCaseClass" # # Make sure loadTestsFromTestCase() picks up the default test method # name (as specified by TestCase), even though the method name does # not match the default TestLoader.testMethodPrefix string def test_loadTestsFromTestCase__default_method_name(self): class Foo(unittest.TestCase): def runTest(self): pass loader = unittest.TestLoader() # This has to be false for the test to succeed self.assertFalse('runTest'.startswith(loader.testMethodPrefix)) suite = loader.loadTestsFromTestCase(Foo) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [Foo('runTest')]) ################################################################ ### /Tests for TestLoader.loadTestsFromTestCase ### Tests for TestLoader.loadTestsFromModule ################################################################ # "This method searches `module` for classes derived from TestCase" def test_loadTestsFromModule__TestCase_subclass(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, loader.suiteClass) expected = [loader.suiteClass([MyTestCase('test')])] self.assertEqual(list(suite), expected) # "This method searches `module` for classes derived from TestCase" # # What happens if no tests are found (no TestCase instances)? def test_loadTestsFromModule__no_TestCase_instances(self): m = types.ModuleType('m') loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # "This method searches `module` for classes derived from TestCase" # # What happens if no tests are found (TestCases instances, but no tests)? def test_loadTestsFromModule__no_TestCase_tests(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [loader.suiteClass()]) # "This method searches `module` for classes derived from TestCase"s # # What happens if loadTestsFromModule() is given something other # than a module? # # XXX Currently, it succeeds anyway. This flexibility # should either be documented or loadTestsFromModule() should # raise a TypeError # # XXX Certain people are using this behaviour. We'll add a test for it def test_loadTestsFromModule__not_a_module(self): class MyTestCase(unittest.TestCase): def test(self): pass class NotAModule(object): test_2 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromModule(NotAModule) reference = [unittest.TestSuite([MyTestCase('test')])] self.assertEqual(list(suite), reference) # Check that loadTestsFromModule honors (or not) a module # with a load_tests function. def test_loadTestsFromModule__load_tests(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase load_tests_args = [] def load_tests(loader, tests, pattern): self.assertIsInstance(tests, unittest.TestSuite) load_tests_args.extend((loader, tests, pattern)) return tests m.load_tests = load_tests loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, unittest.TestSuite) self.assertEqual(load_tests_args, [loader, suite, None]) load_tests_args = [] suite = loader.loadTestsFromModule(m, use_load_tests=False) self.assertEqual(load_tests_args, []) def test_loadTestsFromModule__faulty_load_tests(self): m = types.ModuleType('m') def load_tests(loader, tests, pattern): raise TypeError('some failure') m.load_tests = load_tests loader = unittest.TestLoader() suite = loader.loadTestsFromModule(m) self.assertIsInstance(suite, unittest.TestSuite) self.assertEqual(suite.countTestCases(), 1) test = list(suite)[0] self.assertRaisesRegex(TypeError, "some failure", test.m) ################################################################ ### /Tests for TestLoader.loadTestsFromModule() ### Tests for TestLoader.loadTestsFromName() ################################################################ # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Is ValueError raised in response to an empty name? def test_loadTestsFromName__empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('') except ValueError as e: self.assertEqual(str(e), "Empty module name") else: self.fail("TestLoader.loadTestsFromName failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the name contains invalid characters? def test_loadTestsFromName__malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise ValueError or ImportError? try: loader.loadTestsFromName('abc () //') except ValueError: pass except ImportError: pass else: self.fail("TestLoader.loadTestsFromName failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve ... to a # module" # # What happens when a module by that name can't be found? def test_loadTestsFromName__unknown_module_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('sdasfasfasdf') except ImportError as e: self.assertEqual(str(e), "No module named 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise ImportError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the module is found, but the attribute can't? def test_loadTestsFromName__unknown_attr_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('unittest.sdasfasfasdf') except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when we provide the module, but the attribute can't be # found? def test_loadTestsFromName__relative_unknown_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('sdasfasfasdf', unittest) except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # Does loadTestsFromName raise ValueError when passed an empty # name relative to a provided module? # # XXX Should probably raise a ValueError instead of an AttributeError def test_loadTestsFromName__relative_empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromName('', unittest) except AttributeError as e: pass else: self.fail("Failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when an impossible name is given, relative to the provided # `module`? def test_loadTestsFromName__relative_malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise AttributeError or ValueError? try: loader.loadTestsFromName('abc () //', unittest) except ValueError: pass except AttributeError: pass else: self.fail("TestLoader.loadTestsFromName failed to raise ValueError") # "The method optionally resolves name relative to the given module" # # Does loadTestsFromName raise TypeError when the `module` argument # isn't a module object? # # XXX Accepts the not-a-module object, ignorning the object's type # This should raise an exception or the method name should be changed # # XXX Some people are relying on this, so keep it for now def test_loadTestsFromName__relative_not_a_module(self): class MyTestCase(unittest.TestCase): def test(self): pass class NotAModule(object): test_2 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('test_2', NotAModule) reference = [MyTestCase('test')] self.assertEqual(list(suite), reference) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Does it raise an exception if the name resolves to an invalid # object? def test_loadTestsFromName__relative_bad_object(self): m = types.ModuleType('m') m.testcase_1 = object() loader = unittest.TestLoader() try: loader.loadTestsFromName('testcase_1', m) except TypeError: pass else: self.fail("Should have raised TypeError") # "The specifier name is a ``dotted name'' that may # resolve either to ... a test case class" def test_loadTestsFromName__relative_TestCase_subclass(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('testcase_1', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." def test_loadTestsFromName__relative_TestSuite(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testsuite = unittest.TestSuite([MyTestCase('test')]) loader = unittest.TestLoader() suite = loader.loadTestsFromName('testsuite', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a test method within a test case class" def test_loadTestsFromName__relative_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('testcase_1.test', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Does loadTestsFromName() raise the proper exception when trying to # resolve "a test method within a test case class" that doesn't exist # for the given name (relative to a provided module)? def test_loadTestsFromName__relative_invalid_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() try: loader.loadTestsFromName('testcase_1.testfoo', m) except AttributeError as e: self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") else: self.fail("Failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a ... TestSuite instance" def test_loadTestsFromName__callable__TestSuite(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) testcase_2 = unittest.FunctionTestCase(lambda: None) def return_TestSuite(): return unittest.TestSuite([testcase_1, testcase_2]) m.return_TestSuite = return_TestSuite loader = unittest.TestLoader() suite = loader.loadTestsFromName('return_TestSuite', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [testcase_1, testcase_2]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase ... instance" def test_loadTestsFromName__callable__TestCase_instance(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) def return_TestCase(): return testcase_1 m.return_TestCase = return_TestCase loader = unittest.TestLoader() suite = loader.loadTestsFromName('return_TestCase', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [testcase_1]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase ... instance" #***************************************************************** #Override the suiteClass attribute to ensure that the suiteClass #attribute is used def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self): class SubTestSuite(unittest.TestSuite): pass m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) def return_TestCase(): return testcase_1 m.return_TestCase = return_TestCase loader = unittest.TestLoader() loader.suiteClass = SubTestSuite suite = loader.loadTestsFromName('return_TestCase', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [testcase_1]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a test method within a test case class" #***************************************************************** #Override the suiteClass attribute to ensure that the suiteClass #attribute is used def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self): class SubTestSuite(unittest.TestSuite): pass m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() loader.suiteClass=SubTestSuite suite = loader.loadTestsFromName('testcase_1.test', m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [MyTestCase('test')]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase or TestSuite instance" # # What happens if the callable returns something else? def test_loadTestsFromName__callable__wrong_type(self): m = types.ModuleType('m') def return_wrong(): return 6 m.return_wrong = return_wrong loader = unittest.TestLoader() try: suite = loader.loadTestsFromName('return_wrong', m) except TypeError: pass else: self.fail("TestLoader.loadTestsFromName failed to raise TypeError") # "The specifier can refer to modules and packages which have not been # imported; they will be imported as a side-effect" def test_loadTestsFromName__module_not_loaded(self): # We're going to try to load this module as a side-effect, so it # better not be loaded before we try. # module_name = 'unittest.test.dummy' sys.modules.pop(module_name, None) loader = unittest.TestLoader() try: suite = loader.loadTestsFromName(module_name) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # module should now be loaded, thanks to loadTestsFromName() self.assertIn(module_name, sys.modules) finally: if module_name in sys.modules: del sys.modules[module_name] ################################################################ ### Tests for TestLoader.loadTestsFromName() ### Tests for TestLoader.loadTestsFromNames() ################################################################ # "Similar to loadTestsFromName(), but takes a sequence of names rather # than a single name." # # What happens if that sequence of names is empty? def test_loadTestsFromNames__empty_name_list(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames([]) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # "Similar to loadTestsFromName(), but takes a sequence of names rather # than a single name." # ... # "The method optionally resolves name relative to the given module" # # What happens if that sequence of names is empty? # # XXX Should this raise a ValueError or just return an empty TestSuite? def test_loadTestsFromNames__relative_empty_name_list(self): loader = unittest.TestLoader() suite = loader.loadTestsFromNames([], unittest) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Is ValueError raised in response to an empty name? def test_loadTestsFromNames__empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['']) except ValueError as e: self.assertEqual(str(e), "Empty module name") else: self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when presented with an impossible module name? def test_loadTestsFromNames__malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise ValueError or ImportError? try: loader.loadTestsFromNames(['abc () //']) except ValueError: pass except ImportError: pass else: self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when no module can be found for the given name? def test_loadTestsFromNames__unknown_module_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['sdasfasfasdf']) except ImportError as e: self.assertEqual(str(e), "No module named 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromNames failed to raise ImportError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # What happens when the module can be found, but not the attribute? def test_loadTestsFromNames__unknown_attr_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest']) except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when given an unknown attribute on a specified `module` # argument? def test_loadTestsFromNames__unknown_name_relative_1(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['sdasfasfasdf'], unittest) except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # Do unknown attributes (relative to a provided module) still raise an # exception even in the presence of valid attribute names? def test_loadTestsFromNames__unknown_name_relative_2(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest) except AttributeError as e: self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'") else: self.fail("TestLoader.loadTestsFromName failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when faced with the empty string? # # XXX This currently raises AttributeError, though ValueError is probably # more appropriate def test_loadTestsFromNames__relative_empty_name(self): loader = unittest.TestLoader() try: loader.loadTestsFromNames([''], unittest) except AttributeError: pass else: self.fail("Failed to raise ValueError") # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # ... # "The method optionally resolves name relative to the given module" # # What happens when presented with an impossible attribute name? def test_loadTestsFromNames__relative_malformed_name(self): loader = unittest.TestLoader() # XXX Should this raise AttributeError or ValueError? try: loader.loadTestsFromNames(['abc () //'], unittest) except AttributeError: pass except ValueError: pass else: self.fail("TestLoader.loadTestsFromNames failed to raise ValueError") # "The method optionally resolves name relative to the given module" # # Does loadTestsFromNames() make sure the provided `module` is in fact # a module? # # XXX This validation is currently not done. This flexibility should # either be documented or a TypeError should be raised. def test_loadTestsFromNames__relative_not_a_module(self): class MyTestCase(unittest.TestCase): def test(self): pass class NotAModule(object): test_2 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['test_2'], NotAModule) reference = [unittest.TestSuite([MyTestCase('test')])] self.assertEqual(list(suite), reference) # "The specifier name is a ``dotted name'' that may resolve either to # a module, a test case class, a TestSuite instance, a test method # within a test case class, or a callable object which returns a # TestCase or TestSuite instance." # # Does it raise an exception if the name resolves to an invalid # object? def test_loadTestsFromNames__relative_bad_object(self): m = types.ModuleType('m') m.testcase_1 = object() loader = unittest.TestLoader() try: loader.loadTestsFromNames(['testcase_1'], m) except TypeError: pass else: self.fail("Should have raised TypeError") # "The specifier name is a ``dotted name'' that may resolve ... to # ... a test case class" def test_loadTestsFromNames__relative_TestCase_subclass(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testcase_1'], m) self.assertIsInstance(suite, loader.suiteClass) expected = loader.suiteClass([MyTestCase('test')]) self.assertEqual(list(suite), [expected]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a TestSuite instance" def test_loadTestsFromNames__relative_TestSuite(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testsuite = unittest.TestSuite([MyTestCase('test')]) loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testsuite'], m) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [m.testsuite]) # "The specifier name is a ``dotted name'' that may resolve ... to ... a # test method within a test case class" def test_loadTestsFromNames__relative_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['testcase_1.test'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([MyTestCase('test')]) self.assertEqual(list(suite), [ref_suite]) # "The specifier name is a ``dotted name'' that may resolve ... to ... a # test method within a test case class" # # Does the method gracefully handle names that initially look like they # resolve to "a test method within a test case class" but don't? def test_loadTestsFromNames__relative_invalid_testmethod(self): m = types.ModuleType('m') class MyTestCase(unittest.TestCase): def test(self): pass m.testcase_1 = MyTestCase loader = unittest.TestLoader() try: loader.loadTestsFromNames(['testcase_1.testfoo'], m) except AttributeError as e: self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") else: self.fail("Failed to raise AttributeError") # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a ... TestSuite instance" def test_loadTestsFromNames__callable__TestSuite(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) testcase_2 = unittest.FunctionTestCase(lambda: None) def return_TestSuite(): return unittest.TestSuite([testcase_1, testcase_2]) m.return_TestSuite = return_TestSuite loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['return_TestSuite'], m) self.assertIsInstance(suite, loader.suiteClass) expected = unittest.TestSuite([testcase_1, testcase_2]) self.assertEqual(list(suite), [expected]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase ... instance" def test_loadTestsFromNames__callable__TestCase_instance(self): m = types.ModuleType('m') testcase_1 = unittest.FunctionTestCase(lambda: None) def return_TestCase(): return testcase_1 m.return_TestCase = return_TestCase loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['return_TestCase'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([testcase_1]) self.assertEqual(list(suite), [ref_suite]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase or TestSuite instance" # # Are staticmethods handled correctly? def test_loadTestsFromNames__callable__call_staticmethod(self): m = types.ModuleType('m') class Test1(unittest.TestCase): def test(self): pass testcase_1 = Test1('test') class Foo(unittest.TestCase): @staticmethod def foo(): return testcase_1 m.Foo = Foo loader = unittest.TestLoader() suite = loader.loadTestsFromNames(['Foo.foo'], m) self.assertIsInstance(suite, loader.suiteClass) ref_suite = unittest.TestSuite([testcase_1]) self.assertEqual(list(suite), [ref_suite]) # "The specifier name is a ``dotted name'' that may resolve ... to # ... a callable object which returns a TestCase or TestSuite instance" # # What happens when the callable returns something else? def test_loadTestsFromNames__callable__wrong_type(self): m = types.ModuleType('m') def return_wrong(): return 6 m.return_wrong = return_wrong loader = unittest.TestLoader() try: suite = loader.loadTestsFromNames(['return_wrong'], m) except TypeError: pass else: self.fail("TestLoader.loadTestsFromNames failed to raise TypeError") # "The specifier can refer to modules and packages which have not been # imported; they will be imported as a side-effect" def test_loadTestsFromNames__module_not_loaded(self): # We're going to try to load this module as a side-effect, so it # better not be loaded before we try. # module_name = 'unittest.test.dummy' sys.modules.pop(module_name, None) loader = unittest.TestLoader() try: suite = loader.loadTestsFromNames([module_name]) self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), [unittest.TestSuite()]) # module should now be loaded, thanks to loadTestsFromName() self.assertIn(module_name, sys.modules) finally: if module_name in sys.modules: del sys.modules[module_name] ################################################################ ### /Tests for TestLoader.loadTestsFromNames() ### Tests for TestLoader.getTestCaseNames() ################################################################ # "Return a sorted sequence of method names found within testCaseClass" # # Test.foobar is defined to make sure getTestCaseNames() respects # loader.testMethodPrefix def test_getTestCaseNames(self): class Test(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foobar(self): pass loader = unittest.TestLoader() self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2']) # "Return a sorted sequence of method names found within testCaseClass" # # Does getTestCaseNames() behave appropriately if no tests are found? def test_getTestCaseNames__no_tests(self): class Test(unittest.TestCase): def foobar(self): pass loader = unittest.TestLoader() self.assertEqual(loader.getTestCaseNames(Test), []) # "Return a sorted sequence of method names found within testCaseClass" # # Are not-TestCases handled gracefully? # # XXX This should raise a TypeError, not return a list # # XXX It's too late in the 2.5 release cycle to fix this, but it should # probably be revisited for 2.6 def test_getTestCaseNames__not_a_TestCase(self): class BadCase(int): def test_foo(self): pass loader = unittest.TestLoader() names = loader.getTestCaseNames(BadCase) self.assertEqual(names, ['test_foo']) # "Return a sorted sequence of method names found within testCaseClass" # # Make sure inherited names are handled. # # TestP.foobar is defined to make sure getTestCaseNames() respects # loader.testMethodPrefix def test_getTestCaseNames__inheritance(self): class TestP(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foobar(self): pass class TestC(TestP): def test_1(self): pass def test_3(self): pass loader = unittest.TestLoader() names = ['test_1', 'test_2', 'test_3'] self.assertEqual(loader.getTestCaseNames(TestC), names) ################################################################ ### /Tests for TestLoader.getTestCaseNames() ### Tests for TestLoader.testMethodPrefix ################################################################ # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromTestCase(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass tests_1 = unittest.TestSuite([Foo('foo_bar')]) tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2) # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromModule(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests_1 = [unittest.TestSuite([Foo('foo_bar')])] tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])] loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2) # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromName(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests_1 = unittest.TestSuite([Foo('foo_bar')]) tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2) # "String giving the prefix of method names which will be interpreted as # test methods" # # Implicit in the documentation is that testMethodPrefix is respected by # all loadTestsFrom* methods. def test_testMethodPrefix__loadTestsFromNames(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])]) tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')]) tests_2 = unittest.TestSuite([tests_2]) loader = unittest.TestLoader() loader.testMethodPrefix = 'foo' self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1) loader.testMethodPrefix = 'test' self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2) # "The default value is 'test'" def test_testMethodPrefix__default_value(self): loader = unittest.TestLoader() self.assertEqual(loader.testMethodPrefix, 'test') ################################################################ ### /Tests for TestLoader.testMethodPrefix ### Tests for TestLoader.sortTestMethodsUsing ################################################################ # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromTestCase(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromModule(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass m.Foo = Foo loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] self.assertEqual(list(loader.loadTestsFromModule(m)), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromName(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass m.Foo = Foo loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = loader.suiteClass([Foo('test_2'), Foo('test_1')]) self.assertEqual(loader.loadTestsFromName('Foo', m), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames() and all the loadTestsFromX() methods" def test_sortTestMethodsUsing__loadTestsFromNames(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass m.Foo = Foo loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])] self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests) # "Function to be used to compare method names when sorting them in # getTestCaseNames()" # # Does it actually affect getTestCaseNames()? def test_sortTestMethodsUsing__getTestCaseNames(self): def reversed_cmp(x, y): return -((x > y) - (x < y)) class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass loader = unittest.TestLoader() loader.sortTestMethodsUsing = reversed_cmp test_names = ['test_2', 'test_1'] self.assertEqual(loader.getTestCaseNames(Foo), test_names) # "The default value is the built-in cmp() function" # Since cmp is now defunct, we simply verify that the results # occur in the same order as they would with the default sort. def test_sortTestMethodsUsing__default_value(self): loader = unittest.TestLoader() class Foo(unittest.TestCase): def test_2(self): pass def test_3(self): pass def test_1(self): pass test_names = ['test_2', 'test_3', 'test_1'] self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names)) # "it can be set to None to disable the sort." # # XXX How is this different from reassigning cmp? Are the tests returned # in a random order or something? This behaviour should die def test_sortTestMethodsUsing__None(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass loader = unittest.TestLoader() loader.sortTestMethodsUsing = None test_names = ['test_2', 'test_1'] self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names)) ################################################################ ### /Tests for TestLoader.sortTestMethodsUsing ### Tests for TestLoader.suiteClass ################################################################ # "Callable object that constructs a test suite from a list of tests." def test_suiteClass__loadTestsFromTestCase(self): class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass tests = [Foo('test_1'), Foo('test_2')] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromTestCase(Foo), tests) # It is implicit in the documentation for TestLoader.suiteClass that # all TestLoader.loadTestsFrom* methods respect it. Let's make sure def test_suiteClass__loadTestsFromModule(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests = [[Foo('test_1'), Foo('test_2')]] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromModule(m), tests) # It is implicit in the documentation for TestLoader.suiteClass that # all TestLoader.loadTestsFrom* methods respect it. Let's make sure def test_suiteClass__loadTestsFromName(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests = [Foo('test_1'), Foo('test_2')] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromName('Foo', m), tests) # It is implicit in the documentation for TestLoader.suiteClass that # all TestLoader.loadTestsFrom* methods respect it. Let's make sure def test_suiteClass__loadTestsFromNames(self): m = types.ModuleType('m') class Foo(unittest.TestCase): def test_1(self): pass def test_2(self): pass def foo_bar(self): pass m.Foo = Foo tests = [[Foo('test_1'), Foo('test_2')]] loader = unittest.TestLoader() loader.suiteClass = list self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests) # "The default value is the TestSuite class" def test_suiteClass__default_value(self): loader = unittest.TestLoader() self.assertTrue(loader.suiteClass is unittest.TestSuite)
agpl-3.0
puzan/ansible
lib/ansible/constants.py
3
29560
# (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 import os import tempfile from string import ascii_letters, digits from ansible.compat.six import string_types from ansible.compat.six.moves import configparser from ansible.errors import AnsibleOptionsError from ansible.module_utils._text import to_text from ansible.parsing.quoting import unquote from ansible.utils.path import makedirs_safe BOOL_TRUE = frozenset([ "true", "t", "y", "1", "yes", "on" ]) def mk_boolean(value): ret = value if not isinstance(value, bool): if value is None: ret = False ret = (str(value).lower() in BOOL_TRUE) return ret def shell_expand(path, expand_relative_paths=False): ''' shell_expand is needed as os.path.expanduser does not work when path is None, which is the default for ANSIBLE_PRIVATE_KEY_FILE ''' if path: path = os.path.expanduser(os.path.expandvars(path)) if expand_relative_paths and not path.startswith('/'): # paths are always 'relative' to the config? if 'CONFIG_FILE' in globals(): CFGDIR = os.path.dirname(CONFIG_FILE) path = os.path.join(CFGDIR, path) path = os.path.abspath(path) return path def get_config(p, section, key, env_var, default, value_type=None, expand_relative_paths=False): ''' return a configuration variable with casting :arg p: A ConfigParser object to look for the configuration in :arg section: A section of the ini config that should be examined for this section. :arg key: The config key to get this config from :arg env_var: An Environment variable to check for the config var. If this is set to None then no environment variable will be used. :arg default: A default value to assign to the config var if nothing else sets it. :kwarg value_type: The type of the value. This can be any of the following strings: :boolean: sets the value to a True or False value :integer: Sets the value to an integer or raises a ValueType error :float: Sets the value to a float or raises a ValueType error :list: Treats the value as a comma separated list. Split the value and return it as a python list. :none: Sets the value to None :path: Expands any environment variables and tilde's in the value. :tmp_path: Create a unique temporary directory inside of the directory specified by value and return its path. :pathlist: Treat the value as a typical PATH string. (On POSIX, this means colon separated strings.) Split the value and then expand each part for environment variables and tildes. :kwarg expand_relative_paths: for pathlist and path types, if this is set to True then also change any relative paths into absolute paths. The default is False. ''' value = _get_config(p, section, key, env_var, default) if value_type == 'boolean': value = mk_boolean(value) elif value: if value_type == 'integer': value = int(value) elif value_type == 'float': value = float(value) elif value_type == 'list': if isinstance(value, string_types): value = [x.strip() for x in value.split(',')] elif value_type == 'none': if value == "None": value = None elif value_type == 'path': value = shell_expand(value, expand_relative_paths=expand_relative_paths) elif value_type == 'tmppath': value = shell_expand(value) if not os.path.exists(value): makedirs_safe(value, 0o700) prefix = 'ansible-local-%s' % os.getpid() value = tempfile.mkdtemp(prefix=prefix, dir=value) elif value_type == 'pathlist': if isinstance(value, string_types): value = [shell_expand(x, expand_relative_paths=expand_relative_paths) \ for x in value.split(os.pathsep)] elif isinstance(value, string_types): value = unquote(value) return to_text(value, errors='surrogate_or_strict', nonstring='passthru') def _get_config(p, section, key, env_var, default): ''' helper function for get_config ''' value = default if p is not None: try: value = p.get(section, key, raw=True) except: pass if env_var is not None: env_value = os.environ.get(env_var, None) if env_value is not None: value = env_value return to_text(value, errors='surrogate_or_strict', nonstring='passthru') def load_config_file(): ''' Load Config File order(first found is used): ENV, CWD, HOME, /etc/ansible ''' p = configparser.ConfigParser() path0 = os.getenv("ANSIBLE_CONFIG", None) if path0 is not None: path0 = os.path.expanduser(path0) if os.path.isdir(path0): path0 += "/ansible.cfg" try: path1 = os.getcwd() + "/ansible.cfg" except OSError: path1 = None path2 = os.path.expanduser("~/.ansible.cfg") path3 = "/etc/ansible/ansible.cfg" for path in [path0, path1, path2, path3]: if path is not None and os.path.exists(path): try: p.read(path) except configparser.Error as e: raise AnsibleOptionsError("Error reading config file: \n{0}".format(e)) return p, path return None, '' p, CONFIG_FILE = load_config_file() # check all of these extensions when looking for yaml files for things like # group variables -- really anything we can load YAML_FILENAME_EXTENSIONS = [ "", ".yml", ".yaml", ".json" ] # the default whitelist for cow stencils DEFAULT_COW_WHITELIST = ['bud-frogs', 'bunny', 'cheese', 'daemon', 'default', 'dragon', 'elephant-in-snake', 'elephant', 'eyes', 'hellokitty', 'kitty', 'luke-koala', 'meow', 'milk', 'moofasa', 'moose', 'ren', 'sheep', 'small', 'stegosaurus', 'stimpy', 'supermilker', 'three-eyes', 'turkey', 'turtle', 'tux', 'udder', 'vader-koala', 'vader', 'www',] # sections in config file DEFAULTS='defaults' # FIXME: add deprecation warning when these get set #### DEPRECATED VARS #### # use more sanely named 'inventory' DEPRECATED_HOST_LIST = get_config(p, DEFAULTS, 'hostfile', 'ANSIBLE_HOSTS', '/etc/ansible/hosts', value_type='path') # this is not used since 0.5 but people might still have in config DEFAULT_PATTERN = get_config(p, DEFAULTS, 'pattern', None, None) # If --tags or --skip-tags is given multiple times on the CLI and this is # True, merge the lists of tags together. If False, let the last argument # overwrite any previous ones. Behaviour is overwrite through 2.2. 2.3 # overwrites but prints deprecation. 2.4 the default is to merge. MERGE_MULTIPLE_CLI_TAGS = get_config(p, DEFAULTS, 'merge_multiple_cli_tags', 'ANSIBLE_MERGE_MULTIPLE_CLI_TAGS', False, value_type='boolean') #### GENERALLY CONFIGURABLE THINGS #### DEFAULT_DEBUG = get_config(p, DEFAULTS, 'debug', 'ANSIBLE_DEBUG', False, value_type='boolean') DEFAULT_VERBOSITY = get_config(p, DEFAULTS, 'verbosity', 'ANSIBLE_VERBOSITY', 0, value_type='integer') DEFAULT_HOST_LIST = get_config(p, DEFAULTS,'inventory', 'ANSIBLE_INVENTORY', DEPRECATED_HOST_LIST, value_type='path') DEFAULT_ROLES_PATH = get_config(p, DEFAULTS, 'roles_path', 'ANSIBLE_ROLES_PATH', '/etc/ansible/roles', value_type='pathlist', expand_relative_paths=True) DEFAULT_REMOTE_TMP = get_config(p, DEFAULTS, 'remote_tmp', 'ANSIBLE_REMOTE_TEMP', '~/.ansible/tmp') DEFAULT_LOCAL_TMP = get_config(p, DEFAULTS, 'local_tmp', 'ANSIBLE_LOCAL_TEMP', '~/.ansible/tmp', value_type='tmppath') DEFAULT_MODULE_NAME = get_config(p, DEFAULTS, 'module_name', None, 'command') DEFAULT_FACT_PATH = get_config(p, DEFAULTS, 'fact_path', 'ANSIBLE_FACT_PATH', None, value_type='path') DEFAULT_FORKS = get_config(p, DEFAULTS, 'forks', 'ANSIBLE_FORKS', 5, value_type='integer') DEFAULT_MODULE_ARGS = get_config(p, DEFAULTS, 'module_args', 'ANSIBLE_MODULE_ARGS', '') DEFAULT_MODULE_LANG = get_config(p, DEFAULTS, 'module_lang', 'ANSIBLE_MODULE_LANG', os.getenv('LANG', 'en_US.UTF-8')) DEFAULT_MODULE_SET_LOCALE = get_config(p, DEFAULTS, 'module_set_locale','ANSIBLE_MODULE_SET_LOCALE',False, value_type='boolean') DEFAULT_MODULE_COMPRESSION= get_config(p, DEFAULTS, 'module_compression', None, 'ZIP_DEFLATED') DEFAULT_TIMEOUT = get_config(p, DEFAULTS, 'timeout', 'ANSIBLE_TIMEOUT', 10, value_type='integer') DEFAULT_POLL_INTERVAL = get_config(p, DEFAULTS, 'poll_interval', 'ANSIBLE_POLL_INTERVAL', 15, value_type='integer') DEFAULT_REMOTE_USER = get_config(p, DEFAULTS, 'remote_user', 'ANSIBLE_REMOTE_USER', None) DEFAULT_ASK_PASS = get_config(p, DEFAULTS, 'ask_pass', 'ANSIBLE_ASK_PASS', False, value_type='boolean') DEFAULT_PRIVATE_KEY_FILE = get_config(p, DEFAULTS, 'private_key_file', 'ANSIBLE_PRIVATE_KEY_FILE', None, value_type='path') DEFAULT_REMOTE_PORT = get_config(p, DEFAULTS, 'remote_port', 'ANSIBLE_REMOTE_PORT', None, value_type='integer') DEFAULT_ASK_VAULT_PASS = get_config(p, DEFAULTS, 'ask_vault_pass', 'ANSIBLE_ASK_VAULT_PASS', False, value_type='boolean') DEFAULT_VAULT_PASSWORD_FILE = get_config(p, DEFAULTS, 'vault_password_file', 'ANSIBLE_VAULT_PASSWORD_FILE', None, value_type='path') DEFAULT_TRANSPORT = get_config(p, DEFAULTS, 'transport', 'ANSIBLE_TRANSPORT', 'smart') DEFAULT_SCP_IF_SSH = get_config(p, 'ssh_connection', 'scp_if_ssh', 'ANSIBLE_SCP_IF_SSH', 'smart') DEFAULT_SFTP_BATCH_MODE = get_config(p, 'ssh_connection', 'sftp_batch_mode', 'ANSIBLE_SFTP_BATCH_MODE', True, value_type='boolean') DEFAULT_SSH_TRANSFER_METHOD = get_config(p, 'ssh_connection', 'transfer_method', 'ANSIBLE_SSH_TRANSFER_METHOD', None) DEFAULT_MANAGED_STR = get_config(p, DEFAULTS, 'ansible_managed', None, 'Ansible managed') DEFAULT_SYSLOG_FACILITY = get_config(p, DEFAULTS, 'syslog_facility', 'ANSIBLE_SYSLOG_FACILITY', 'LOG_USER') DEFAULT_KEEP_REMOTE_FILES = get_config(p, DEFAULTS, 'keep_remote_files', 'ANSIBLE_KEEP_REMOTE_FILES', False, value_type='boolean') DEFAULT_HASH_BEHAVIOUR = get_config(p, DEFAULTS, 'hash_behaviour', 'ANSIBLE_HASH_BEHAVIOUR', 'replace') DEFAULT_PRIVATE_ROLE_VARS = get_config(p, DEFAULTS, 'private_role_vars', 'ANSIBLE_PRIVATE_ROLE_VARS', False, value_type='boolean') DEFAULT_JINJA2_EXTENSIONS = get_config(p, DEFAULTS, 'jinja2_extensions', 'ANSIBLE_JINJA2_EXTENSIONS', None) DEFAULT_EXECUTABLE = get_config(p, DEFAULTS, 'executable', 'ANSIBLE_EXECUTABLE', '/bin/sh') DEFAULT_GATHERING = get_config(p, DEFAULTS, 'gathering', 'ANSIBLE_GATHERING', 'implicit').lower() DEFAULT_GATHER_SUBSET = get_config(p, DEFAULTS, 'gather_subset', 'ANSIBLE_GATHER_SUBSET', 'all').lower() DEFAULT_GATHER_TIMEOUT = get_config(p, DEFAULTS, 'gather_timeout', 'ANSIBLE_GATHER_TIMEOUT', 10, value_type='integer') DEFAULT_LOG_PATH = get_config(p, DEFAULTS, 'log_path', 'ANSIBLE_LOG_PATH', '', value_type='path') DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_FORCE_HANDLERS', False, value_type='boolean') DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], value_type='list') DEFAULT_VAR_COMPRESSION_LEVEL = get_config(p, DEFAULTS, 'var_compression_level', 'ANSIBLE_VAR_COMPRESSION_LEVEL', 0, value_type='integer') DEFAULT_INTERNAL_POLL_INTERVAL = get_config(p, DEFAULTS, 'internal_poll_interval', None, 0.001, value_type='float') ERROR_ON_MISSING_HANDLER = get_config(p, DEFAULTS, 'error_on_missing_handler', 'ANSIBLE_ERROR_ON_MISSING_HANDLER', True, value_type='boolean') SHOW_CUSTOM_STATS = get_config(p, DEFAULTS, 'show_custom_stats', 'ANSIBLE_SHOW_CUSTOM_STATS', False, value_type='boolean') # static includes DEFAULT_TASK_INCLUDES_STATIC = get_config(p, DEFAULTS, 'task_includes_static', 'ANSIBLE_TASK_INCLUDES_STATIC', False, value_type='boolean') DEFAULT_HANDLER_INCLUDES_STATIC = get_config(p, DEFAULTS, 'handler_includes_static', 'ANSIBLE_HANDLER_INCLUDES_STATIC', False, value_type='boolean') # disclosure DEFAULT_NO_LOG = get_config(p, DEFAULTS, 'no_log', 'ANSIBLE_NO_LOG', False, value_type='boolean') DEFAULT_NO_TARGET_SYSLOG = get_config(p, DEFAULTS, 'no_target_syslog', 'ANSIBLE_NO_TARGET_SYSLOG', False, value_type='boolean') ALLOW_WORLD_READABLE_TMPFILES = get_config(p, DEFAULTS, 'allow_world_readable_tmpfiles', None, False, value_type='boolean') # selinux DEFAULT_SELINUX_SPECIAL_FS = get_config(p, 'selinux', 'special_context_filesystems', None, 'fuse, nfs, vboxsf, ramfs, 9p', value_type='list') DEFAULT_LIBVIRT_LXC_NOSECLABEL = get_config(p, 'selinux', 'libvirt_lxc_noseclabel', 'LIBVIRT_LXC_NOSECLABEL', False, value_type='boolean') ### PRIVILEGE ESCALATION ### # Backwards Compat DEFAULT_SU = get_config(p, DEFAULTS, 'su', 'ANSIBLE_SU', False, value_type='boolean') DEFAULT_SU_USER = get_config(p, DEFAULTS, 'su_user', 'ANSIBLE_SU_USER', 'root') DEFAULT_SU_EXE = get_config(p, DEFAULTS, 'su_exe', 'ANSIBLE_SU_EXE', None) DEFAULT_SU_FLAGS = get_config(p, DEFAULTS, 'su_flags', 'ANSIBLE_SU_FLAGS', None) DEFAULT_ASK_SU_PASS = get_config(p, DEFAULTS, 'ask_su_pass', 'ANSIBLE_ASK_SU_PASS', False, value_type='boolean') DEFAULT_SUDO = get_config(p, DEFAULTS, 'sudo', 'ANSIBLE_SUDO', False, value_type='boolean') DEFAULT_SUDO_USER = get_config(p, DEFAULTS, 'sudo_user', 'ANSIBLE_SUDO_USER', 'root') DEFAULT_SUDO_EXE = get_config(p, DEFAULTS, 'sudo_exe', 'ANSIBLE_SUDO_EXE', None) DEFAULT_SUDO_FLAGS = get_config(p, DEFAULTS, 'sudo_flags', 'ANSIBLE_SUDO_FLAGS', '-H -S -n') DEFAULT_ASK_SUDO_PASS = get_config(p, DEFAULTS, 'ask_sudo_pass', 'ANSIBLE_ASK_SUDO_PASS', False, value_type='boolean') # Become BECOME_ERROR_STRINGS = {'sudo': 'Sorry, try again.', 'su': 'Authentication failure', 'pbrun': '', 'pfexec': '', 'doas': 'Permission denied', 'dzdo': '', 'ksu': 'Password incorrect'} #FIXME: deal with i18n BECOME_MISSING_STRINGS = {'sudo': 'sorry, a password is required to run sudo', 'su': '', 'pbrun': '', 'pfexec': '', 'doas': 'Authorization required', 'dzdo': '', 'ksu': 'No password given'} #FIXME: deal with i18n BECOME_METHODS = ['sudo','su','pbrun','pfexec','doas','dzdo','ksu','runas'] BECOME_ALLOW_SAME_USER = get_config(p, 'privilege_escalation', 'become_allow_same_user', 'ANSIBLE_BECOME_ALLOW_SAME_USER', False, value_type='boolean') DEFAULT_BECOME_METHOD = get_config(p, 'privilege_escalation', 'become_method', 'ANSIBLE_BECOME_METHOD','sudo' if DEFAULT_SUDO else 'su' if DEFAULT_SU else 'sudo' ).lower() DEFAULT_BECOME = get_config(p, 'privilege_escalation', 'become', 'ANSIBLE_BECOME',False, value_type='boolean') DEFAULT_BECOME_USER = get_config(p, 'privilege_escalation', 'become_user', 'ANSIBLE_BECOME_USER', 'root') DEFAULT_BECOME_EXE = get_config(p, 'privilege_escalation', 'become_exe', 'ANSIBLE_BECOME_EXE', None) DEFAULT_BECOME_FLAGS = get_config(p, 'privilege_escalation', 'become_flags', 'ANSIBLE_BECOME_FLAGS', None) DEFAULT_BECOME_ASK_PASS = get_config(p, 'privilege_escalation', 'become_ask_pass', 'ANSIBLE_BECOME_ASK_PASS', False, value_type='boolean') # PLUGINS # Modules that can optimize with_items loops into a single call. Currently # these modules must (1) take a "name" or "pkg" parameter that is a list. If # the module takes both, bad things could happen. # In the future we should probably generalize this even further # (mapping of param: squash field) DEFAULT_SQUASH_ACTIONS = get_config(p, DEFAULTS, 'squash_actions', 'ANSIBLE_SQUASH_ACTIONS', "apk, apt, dnf, homebrew, openbsd_pkg, pacman, pkgng, yum, zypper", value_type='list') # paths DEFAULT_ACTION_PLUGIN_PATH = get_config(p, DEFAULTS, 'action_plugins', 'ANSIBLE_ACTION_PLUGINS', '~/.ansible/plugins/action:/usr/share/ansible/plugins/action', value_type='pathlist') DEFAULT_CACHE_PLUGIN_PATH = get_config(p, DEFAULTS, 'cache_plugins', 'ANSIBLE_CACHE_PLUGINS', '~/.ansible/plugins/cache:/usr/share/ansible/plugins/cache', value_type='pathlist') DEFAULT_CALLBACK_PLUGIN_PATH = get_config(p, DEFAULTS, 'callback_plugins', 'ANSIBLE_CALLBACK_PLUGINS', '~/.ansible/plugins/callback:/usr/share/ansible/plugins/callback', value_type='pathlist') DEFAULT_CONNECTION_PLUGIN_PATH = get_config(p, DEFAULTS, 'connection_plugins', 'ANSIBLE_CONNECTION_PLUGINS', '~/.ansible/plugins/connection:/usr/share/ansible/plugins/connection', value_type='pathlist') DEFAULT_LOOKUP_PLUGIN_PATH = get_config(p, DEFAULTS, 'lookup_plugins', 'ANSIBLE_LOOKUP_PLUGINS', '~/.ansible/plugins/lookup:/usr/share/ansible/plugins/lookup', value_type='pathlist') DEFAULT_MODULE_PATH = get_config(p, DEFAULTS, 'library', 'ANSIBLE_LIBRARY', None, value_type='pathlist') DEFAULT_MODULE_UTILS_PATH = get_config(p, DEFAULTS, 'module_utils', 'ANSIBLE_MODULE_UTILS', None, value_type='pathlist') DEFAULT_INVENTORY_PLUGIN_PATH = get_config(p, DEFAULTS, 'inventory_plugins', 'ANSIBLE_INVENTORY_PLUGINS', '~/.ansible/plugins/inventory:/usr/share/ansible/plugins/inventory', value_type='pathlist') DEFAULT_VARS_PLUGIN_PATH = get_config(p, DEFAULTS, 'vars_plugins', 'ANSIBLE_VARS_PLUGINS', '~/.ansible/plugins/vars:/usr/share/ansible/plugins/vars', value_type='pathlist') DEFAULT_FILTER_PLUGIN_PATH = get_config(p, DEFAULTS, 'filter_plugins', 'ANSIBLE_FILTER_PLUGINS', '~/.ansible/plugins/filter:/usr/share/ansible/plugins/filter', value_type='pathlist') DEFAULT_TEST_PLUGIN_PATH = get_config(p, DEFAULTS, 'test_plugins', 'ANSIBLE_TEST_PLUGINS', '~/.ansible/plugins/test:/usr/share/ansible/plugins/test', value_type='pathlist') DEFAULT_STRATEGY_PLUGIN_PATH = get_config(p, DEFAULTS, 'strategy_plugins', 'ANSIBLE_STRATEGY_PLUGINS', '~/.ansible/plugins/strategy:/usr/share/ansible/plugins/strategy', value_type='pathlist') NETWORK_GROUP_MODULES = get_config(p, DEFAULTS, 'network_group_modules','NETWORK_GROUP_MODULES', ['eos', 'nxos', 'ios', 'iosxr', 'junos', 'vyos'], value_type='list') DEFAULT_STRATEGY = get_config(p, DEFAULTS, 'strategy', 'ANSIBLE_STRATEGY', 'linear') DEFAULT_STDOUT_CALLBACK = get_config(p, DEFAULTS, 'stdout_callback', 'ANSIBLE_STDOUT_CALLBACK', 'default') # cache CACHE_PLUGIN = get_config(p, DEFAULTS, 'fact_caching', 'ANSIBLE_CACHE_PLUGIN', 'memory') CACHE_PLUGIN_CONNECTION = get_config(p, DEFAULTS, 'fact_caching_connection', 'ANSIBLE_CACHE_PLUGIN_CONNECTION', None) CACHE_PLUGIN_PREFIX = get_config(p, DEFAULTS, 'fact_caching_prefix', 'ANSIBLE_CACHE_PLUGIN_PREFIX', 'ansible_facts') CACHE_PLUGIN_TIMEOUT = get_config(p, DEFAULTS, 'fact_caching_timeout', 'ANSIBLE_CACHE_PLUGIN_TIMEOUT', 24 * 60 * 60, value_type='integer') # Display ANSIBLE_FORCE_COLOR = get_config(p, DEFAULTS, 'force_color', 'ANSIBLE_FORCE_COLOR', None, value_type='boolean') ANSIBLE_NOCOLOR = get_config(p, DEFAULTS, 'nocolor', 'ANSIBLE_NOCOLOR', None, value_type='boolean') ANSIBLE_NOCOWS = get_config(p, DEFAULTS, 'nocows', 'ANSIBLE_NOCOWS', None, value_type='boolean') ANSIBLE_COW_SELECTION = get_config(p, DEFAULTS, 'cow_selection', 'ANSIBLE_COW_SELECTION', 'default') ANSIBLE_COW_WHITELIST = get_config(p, DEFAULTS, 'cow_whitelist', 'ANSIBLE_COW_WHITELIST', DEFAULT_COW_WHITELIST, value_type='list') DISPLAY_SKIPPED_HOSTS = get_config(p, DEFAULTS, 'display_skipped_hosts', 'DISPLAY_SKIPPED_HOSTS', True, value_type='boolean') DEFAULT_UNDEFINED_VAR_BEHAVIOR = get_config(p, DEFAULTS, 'error_on_undefined_vars', 'ANSIBLE_ERROR_ON_UNDEFINED_VARS', True, value_type='boolean') HOST_KEY_CHECKING = get_config(p, DEFAULTS, 'host_key_checking', 'ANSIBLE_HOST_KEY_CHECKING', True, value_type='boolean') SYSTEM_WARNINGS = get_config(p, DEFAULTS, 'system_warnings', 'ANSIBLE_SYSTEM_WARNINGS', True, value_type='boolean') DEPRECATION_WARNINGS = get_config(p, DEFAULTS, 'deprecation_warnings', 'ANSIBLE_DEPRECATION_WARNINGS', True, value_type='boolean') DEFAULT_CALLABLE_WHITELIST = get_config(p, DEFAULTS, 'callable_whitelist', 'ANSIBLE_CALLABLE_WHITELIST', [], value_type='list') COMMAND_WARNINGS = get_config(p, DEFAULTS, 'command_warnings', 'ANSIBLE_COMMAND_WARNINGS', True, value_type='boolean') DEFAULT_LOAD_CALLBACK_PLUGINS = get_config(p, DEFAULTS, 'bin_ansible_callbacks', 'ANSIBLE_LOAD_CALLBACK_PLUGINS', False, value_type='boolean') DEFAULT_CALLBACK_WHITELIST = get_config(p, DEFAULTS, 'callback_whitelist', 'ANSIBLE_CALLBACK_WHITELIST', [], value_type='list') RETRY_FILES_ENABLED = get_config(p, DEFAULTS, 'retry_files_enabled', 'ANSIBLE_RETRY_FILES_ENABLED', True, value_type='boolean') RETRY_FILES_SAVE_PATH = get_config(p, DEFAULTS, 'retry_files_save_path', 'ANSIBLE_RETRY_FILES_SAVE_PATH', None, value_type='path') DEFAULT_NULL_REPRESENTATION = get_config(p, DEFAULTS, 'null_representation', 'ANSIBLE_NULL_REPRESENTATION', None, value_type='none') DISPLAY_ARGS_TO_STDOUT = get_config(p, DEFAULTS, 'display_args_to_stdout', 'ANSIBLE_DISPLAY_ARGS_TO_STDOUT', False, value_type='boolean') MAX_FILE_SIZE_FOR_DIFF = get_config(p, DEFAULTS, 'max_diff_size', 'ANSIBLE_MAX_DIFF_SIZE', 1024*1024, value_type='integer') # CONNECTION RELATED USE_PERSISTENT_CONNECTIONS = get_config(p, DEFAULTS, 'use_persistent_connections', 'ANSIBLE_USE_PERSISTENT_CONNECTIONS', False, value_type='boolean') ANSIBLE_SSH_ARGS = get_config(p, 'ssh_connection', 'ssh_args', 'ANSIBLE_SSH_ARGS', '-C -o ControlMaster=auto -o ControlPersist=60s') ### WARNING: Someone might be tempted to switch this from percent-formatting # to .format() in the future. be sure to read this: # http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/ and understand # that it may be a security risk to do so. ANSIBLE_SSH_CONTROL_PATH = get_config(p, 'ssh_connection', 'control_path', 'ANSIBLE_SSH_CONTROL_PATH', None) ANSIBLE_SSH_CONTROL_PATH_DIR = get_config(p, 'ssh_connection', 'control_path_dir', 'ANSIBLE_SSH_CONTROL_PATH_DIR', u'~/.ansible/cp') ANSIBLE_SSH_PIPELINING = get_config(p, 'ssh_connection', 'pipelining', 'ANSIBLE_SSH_PIPELINING', False, value_type='boolean') ANSIBLE_SSH_RETRIES = get_config(p, 'ssh_connection', 'retries', 'ANSIBLE_SSH_RETRIES', 0, value_type='integer') ANSIBLE_SSH_EXECUTABLE = get_config(p, 'ssh_connection', 'ssh_executable', 'ANSIBLE_SSH_EXECUTABLE', 'ssh') PARAMIKO_RECORD_HOST_KEYS = get_config(p, 'paramiko_connection', 'record_host_keys', 'ANSIBLE_PARAMIKO_RECORD_HOST_KEYS', True, value_type='boolean') PARAMIKO_HOST_KEY_AUTO_ADD = get_config(p, 'paramiko_connection', 'host_key_auto_add', 'ANSIBLE_PARAMIKO_HOST_KEY_AUTO_ADD', False, value_type='boolean') PARAMIKO_PROXY_COMMAND = get_config(p, 'paramiko_connection', 'proxy_command', 'ANSIBLE_PARAMIKO_PROXY_COMMAND', None) PARAMIKO_LOOK_FOR_KEYS = get_config(p, 'paramiko_connection', 'look_for_keys', 'ANSIBLE_PARAMIKO_LOOK_FOR_KEYS', True, value_type='boolean') PERSISTENT_CONNECT_TIMEOUT = get_config(p, 'persistent_connection', 'connect_timeout', 'ANSIBLE_PERSISTENT_CONNECT_TIMEOUT', 30, value_type='integer') PERSISTENT_CONNECT_RETRIES = get_config(p, 'persistent_connection', 'connect_retries', 'ANSIBLE_PERSISTENT_CONNECT_RETRIES', 10, value_type='integer') PERSISTENT_CONNECT_INTERVAL = get_config(p, 'persistent_connection', 'connect_interval', 'ANSIBLE_PERSISTENT_CONNECT_INTERVAL', 1, value_type='integer') # obsolete -- will be formally removed ACCELERATE_PORT = get_config(p, 'accelerate', 'accelerate_port', 'ACCELERATE_PORT', 5099, value_type='integer') ACCELERATE_TIMEOUT = get_config(p, 'accelerate', 'accelerate_timeout', 'ACCELERATE_TIMEOUT', 30, value_type='integer') ACCELERATE_CONNECT_TIMEOUT = get_config(p, 'accelerate', 'accelerate_connect_timeout', 'ACCELERATE_CONNECT_TIMEOUT', 1.0, value_type='float') ACCELERATE_DAEMON_TIMEOUT = get_config(p, 'accelerate', 'accelerate_daemon_timeout', 'ACCELERATE_DAEMON_TIMEOUT', 30, value_type='integer') ACCELERATE_KEYS_DIR = get_config(p, 'accelerate', 'accelerate_keys_dir', 'ACCELERATE_KEYS_DIR', '~/.fireball.keys') ACCELERATE_KEYS_DIR_PERMS = get_config(p, 'accelerate', 'accelerate_keys_dir_perms', 'ACCELERATE_KEYS_DIR_PERMS', '700') ACCELERATE_KEYS_FILE_PERMS = get_config(p, 'accelerate', 'accelerate_keys_file_perms', 'ACCELERATE_KEYS_FILE_PERMS', '600') ACCELERATE_MULTI_KEY = get_config(p, 'accelerate', 'accelerate_multi_key', 'ACCELERATE_MULTI_KEY', False, value_type='boolean') PARAMIKO_PTY = get_config(p, 'paramiko_connection', 'pty', 'ANSIBLE_PARAMIKO_PTY', True, value_type='boolean') # galaxy related GALAXY_SERVER = get_config(p, 'galaxy', 'server', 'ANSIBLE_GALAXY_SERVER', 'https://galaxy.ansible.com') GALAXY_IGNORE_CERTS = get_config(p, 'galaxy', 'ignore_certs', 'ANSIBLE_GALAXY_IGNORE', False, value_type='boolean') # this can be configured to blacklist SCMS but cannot add new ones unless the code is also updated GALAXY_SCMS = get_config(p, 'galaxy', 'scms', 'ANSIBLE_GALAXY_SCMS', 'git, hg', value_type='list') GALAXY_ROLE_SKELETON = get_config(p, 'galaxy', 'role_skeleton', 'ANSIBLE_GALAXY_ROLE_SKELETON', None, value_type='path') GALAXY_ROLE_SKELETON_IGNORE = get_config(p, 'galaxy', 'role_skeleton_ignore', 'ANSIBLE_GALAXY_ROLE_SKELETON_IGNORE', ['^.git$', '^.*/.git_keep$'], value_type='list') STRING_TYPE_FILTERS = get_config(p, 'jinja2', 'dont_type_filters', 'ANSIBLE_STRING_TYPE_FILTERS', ['string', 'to_json', 'to_nice_json', 'to_yaml', 'ppretty', 'json'], value_type='list' ) # colors COLOR_HIGHLIGHT = get_config(p, 'colors', 'highlight', 'ANSIBLE_COLOR_HIGHLIGHT', 'white') COLOR_VERBOSE = get_config(p, 'colors', 'verbose', 'ANSIBLE_COLOR_VERBOSE', 'blue') COLOR_WARN = get_config(p, 'colors', 'warn', 'ANSIBLE_COLOR_WARN', 'bright purple') COLOR_ERROR = get_config(p, 'colors', 'error', 'ANSIBLE_COLOR_ERROR', 'red') COLOR_DEBUG = get_config(p, 'colors', 'debug', 'ANSIBLE_COLOR_DEBUG', 'dark gray') COLOR_DEPRECATE = get_config(p, 'colors', 'deprecate', 'ANSIBLE_COLOR_DEPRECATE', 'purple') COLOR_SKIP = get_config(p, 'colors', 'skip', 'ANSIBLE_COLOR_SKIP', 'cyan') COLOR_UNREACHABLE = get_config(p, 'colors', 'unreachable', 'ANSIBLE_COLOR_UNREACHABLE', 'bright red') COLOR_OK = get_config(p, 'colors', 'ok', 'ANSIBLE_COLOR_OK', 'green') COLOR_CHANGED = get_config(p, 'colors', 'changed', 'ANSIBLE_COLOR_CHANGED', 'yellow') COLOR_DIFF_ADD = get_config(p, 'colors', 'diff_add', 'ANSIBLE_COLOR_DIFF_ADD', 'green') COLOR_DIFF_REMOVE = get_config(p, 'colors', 'diff_remove', 'ANSIBLE_COLOR_DIFF_REMOVE', 'red') COLOR_DIFF_LINES = get_config(p, 'colors', 'diff_lines', 'ANSIBLE_COLOR_DIFF_LINES', 'cyan') # diff DIFF_CONTEXT = get_config(p, 'diff', 'context', 'ANSIBLE_DIFF_CONTEXT', 3, value_type='integer') DIFF_ALWAYS = get_config(p, 'diff', 'always', 'ANSIBLE_DIFF_ALWAYS', False, value_type='bool') # non-configurable things MODULE_REQUIRE_ARGS = ['command', 'win_command', 'shell', 'win_shell', 'raw', 'script'] MODULE_NO_JSON = ['command', 'win_command', 'shell', 'win_shell', 'raw'] DEFAULT_BECOME_PASS = None DEFAULT_PASSWORD_CHARS = to_text(ascii_letters + digits + ".,:-_", errors='strict') # characters included in auto-generated passwords DEFAULT_SUDO_PASS = None DEFAULT_REMOTE_PASS = None DEFAULT_SUBSET = None DEFAULT_SU_PASS = None VAULT_VERSION_MIN = 1.0 VAULT_VERSION_MAX = 1.0 TREE_DIR = None LOCALHOST = frozenset(['127.0.0.1', 'localhost', '::1']) # module search BLACKLIST_EXTS = ('.pyc', '.swp', '.bak', '~', '.rpm', '.md', '.txt') IGNORE_FILES = ["COPYING", "CONTRIBUTING", "LICENSE", "README", "VERSION", "GUIDELINES"] INTERNAL_RESULT_KEYS = ['add_host', 'add_group'] RESTRICTED_RESULT_KEYS = ['ansible_rsync_path', 'ansible_playbook_python']
gpl-3.0
sanketn26/Slic
client/async/loadtest/EchoClient.py
1
1275
__author__ = 'slic' from autobahn.twisted.websocket import WebSocketClientProtocol, \ WebSocketClientFactory class WebSocketEchoProtocol(WebSocketClientProtocol): def onConnect(self, response): print("Server connected: {0}".format(response.peer)) def onOpen(self): print("WebSocket connection open.") def hello(): self.sendMessage(u"Hello, world!".encode('utf8')) self.factory.reactor.callLater(1, hello) # start sending messages every second .. hello() def onMessage(self, payload, isBinary): if isBinary: print("Binary message received: {0} bytes".format(len(payload))) else: print("Text message received: {0}".format(payload.decode('utf8'))) def onClose(self, wasClean, code, reason): print("WebSocket connection closed: {0}".format(reason)) if __name__ == '__main__': import sys from twisted.python import log from twisted.internet import reactor log.startLogging(sys.stdout) for i in range(10000): factory = WebSocketClientFactory("ws://localhost:8080/echo", debug=False) factory.protocol = WebSocketEchoProtocol reactor.connectTCP("127.0.0.1", 8080, factory) reactor.run()
apache-2.0
ptchankue/youtube-dl
youtube_dl/extractor/abc7news.py
132
2364
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import parse_iso8601 class Abc7NewsIE(InfoExtractor): _VALID_URL = r'https?://abc7news\.com(?:/[^/]+/(?P<display_id>[^/]+))?/(?P<id>\d+)' _TESTS = [ { 'url': 'http://abc7news.com/entertainment/east-bay-museum-celebrates-vintage-synthesizers/472581/', 'info_dict': { 'id': '472581', 'display_id': 'east-bay-museum-celebrates-vintage-synthesizers', 'ext': 'mp4', 'title': 'East Bay museum celebrates history of synthesized music', 'description': 'md5:a4f10fb2f2a02565c1749d4adbab4b10', 'thumbnail': 're:^https?://.*\.jpg$', 'timestamp': 1421123075, 'upload_date': '20150113', 'uploader': 'Jonathan Bloom', }, 'params': { # m3u8 download 'skip_download': True, }, }, { 'url': 'http://abc7news.com/472581', 'only_matching': True, }, ] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('display_id') or video_id webpage = self._download_webpage(url, display_id) m3u8 = self._html_search_meta( 'contentURL', webpage, 'm3u8 url', fatal=True) formats = self._extract_m3u8_formats(m3u8, display_id, 'mp4') self._sort_formats(formats) title = self._og_search_title(webpage).strip() description = self._og_search_description(webpage).strip() thumbnail = self._og_search_thumbnail(webpage) timestamp = parse_iso8601(self._search_regex( r'<div class="meta">\s*<time class="timeago" datetime="([^"]+)">', webpage, 'upload date', fatal=False)) uploader = self._search_regex( r'rel="author">([^<]+)</a>', webpage, 'uploader', default=None) return { 'id': video_id, 'display_id': display_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'timestamp': timestamp, 'uploader': uploader, 'formats': formats, }
unlicense
asbjorn/segpy
segpy-ext/segpy_numpy/segpy_numpy/extract.py
5
21692
"""Tools for interoperability between Segpy and Numpy arrays.""" from collections import namedtuple import numpy as np from segpy.header import Header, SubFormatMeta from segpy.packer import make_header_packer from segpy.util import ensure_superset from segpy_numpy.dtypes import make_dtype def extract_trace_header_field_3d(reader_3d, fields, inline_numbers=None, xline_numbers=None, null=None): """Extract a single trace header field from all trace headers as an array. Args: reader_3d: A SegYReader3D fields: A an iterable series where each item is either the name of a field as a string or an object such as a NamedField with a 'name' attribute which in turn is the name of a field as a string, such as a NamedField. inline_numbers: The inline numbers for which traces are to be extracted. This argument can be specified in three ways: None (the default) - All traces within the each crossline will be be extracted. sequence - When a sequence, such as a range or a list is provided only those traces at inline numbers corresponding to the items in the sequence will be extracted. The traces will always be extracted in increasing numeric order and duplicate entries will be ignored. For example inline_numbers=range(100, 200, 2) will extract alternate traces from inline number 100 to inline number 198 inclusive. slice - When a slice object is provided the slice will be applied to the sequence of all inline numbers. For example inline_numbers=slice(100, -100) will omit the first one hundred and the last one hundred traces, irrespective of their numbers. xline_numbers: The crossline numbers at which traces are to be extracted. This argument can be specified in three ways: None (the default) - All traces at within each inline will be be extracted. sequence - When a sequence, such as a range or a list is provided only those traces at crossline numbers corresponding to the items in the sequence will be extracted. The traces will always be extracted in increasing numeric order and duplicate entries will be ignored. For example xline_numbers=range(100, 200, 2) will extract alternate traces from crossline number 100 to crossline number 198 inclusive. slice - When a slice object is provided the slice will be applied to the sequence of all crossline numbers. For example xline_numbers=slice(100, -100) will omit the first one hundred and the last one hundred traces, irrespective of their numbers. null: An optional null value for missing traces. The null value must be convertible to all field value types. Returns: A namedtuple object with attributes which are two-dimensional Numpy arrays. If a null value was specified the arrays will be ndarrays, otherwise they will be masked arrays. The attributes of the named tuple are in the same order as the fields specified in the `fields` argument. Raises: AttributeError: If the the named fields do not exist in the trace header definition. """ field_names = [_extract_field_name(field) for field in fields] inline_numbers = ensure_superset(reader_3d.inline_numbers(), inline_numbers) xline_numbers = ensure_superset(reader_3d.xline_numbers(), xline_numbers) shape = (len(inline_numbers), len(xline_numbers)) class SubFormat(metaclass=SubFormatMeta, parent_format=reader_3d.trace_header_format_class, parent_field_names=field_names): pass sub_header_packer = make_header_packer(SubFormat, reader_3d.endian) TraceHeaderArrays = namedtuple('TraceHeaderArrays', field_names) arrays = (_make_array(shape, make_dtype(getattr(SubFormat, field_name).value_type.SEG_Y_TYPE), null) for field_name in field_names) trace_header_arrays = TraceHeaderArrays(*arrays) for inline_index, inline_number in enumerate(inline_numbers): for xline_index, xline_number in enumerate(xline_numbers): inline_xline_number = (inline_number, xline_number) if reader_3d.has_trace_index(inline_xline_number): trace_index = reader_3d.trace_index((inline_number, xline_number)) trace_header = reader_3d.trace_header(trace_index, sub_header_packer) for field_name, a in zip(field_names, trace_header_arrays): field_value = getattr(trace_header, field_name) a[inline_index, xline_index] = field_value return trace_header_arrays def extract_trace(reader, trace_index, sample_numbers): """Extract an single trace as a one-dimensional array. Args: reader: A SegYReader3D object. trace_index: The index of the trace to be extracted. sample_numbers: The sample numbers within each trace at which samples are to be extracted. This argument can be specified in three ways: None (the default) - All samples within the trace will be be extracted. sequence - When a sequence, such as a range or a list is provided only those samples at sample numbers corresponding to the items in the sequence will be extracted. The samples will always be extracted in increasing numeric order and duplicate entries will be ignored. For example sample_numbers=range(100, 200, 2) will extract alternate samples from sample number 100 to sample number 198 inclusive. slice - When a slice object is provided the slice will be applied to the sequence of all sample numbers. For example sample_numbers=slice(100, -100) will omit the first one hundred and the last one hundred samples, irrespective of their numbers. Returns: A one-dimensional array. """ if not reader.has_trace_index(trace_index): raise ValueError("Inline number {} not present in {}".format(trace_index, reader)) sample_numbers = ensure_superset(range(0, reader.max_num_trace_samples()), sample_numbers) trace_sample_start = sample_numbers[0] trace_sample_stop = min(sample_numbers[-1] + 1, reader.num_trace_samples(trace_index)) trace_samples = reader.trace_samples(trace_index, trace_sample_start, trace_sample_stop) arr = np.fromiter((trace_samples[sample_number - trace_sample_start] for sample_number in sample_numbers), make_dtype(reader.data_sample_format)) return arr def extract_inline_3d(reader_3d, inline_number, xline_numbers=None, sample_numbers=None, null=None): """Extract an inline as a two-dimensional array. Args: reader_3d: A SegYReader3D object. inline_number: The number of the inline to be extracted. xline_numbers: The crossline numbers within the inline at which traces are to be extracted. This argument can be specified in three ways: None (the default) - All traces within the inline will be be extracted. sequence - When a sequence, such as a range or a list is provided only those traces at crossline numbers corresponding to the items in the sequence will be extracted. The traces will always be extracted in increasing numeric order and duplicate entries will be ignored. For example xline_numbers=range(100, 200, 2) will extract alternate traces from crossline number 100 to crossline number 198 inclusive. slice - When a slice object is provided the slice will be applied to the sequence of all crossline numbers. For example xline_numbers=slice(100, -100) will omit the first one hundred and the last one hundred traces, irrespective of their numbers. sample_numbers: The sample numbers within each trace at which samples are to be extracted. This argument can be specified in three ways: None (the default) - All samples within the trace will be be extracted. sequence - When a sequence, such as a range or a list is provided only those samples at sample numbers corresponding to the items in the sequence will be extracted. The samples will always be extracted in increasing numeric order and duplicate entries will be ignored. For example sample_numbers=range(100, 200, 2) will extract alternate samples from sample number 100 to sample number 198 inclusive. slice - When a slice object is provided the slice will be applied to the sequence of all sample numbers. For example sample_numbers=slice(100, -100) will omit the first one hundred and the last one hundred samples, irrespective of their numbers. null: A null value. When None is specified as the null value a masked array will be returned. Returns: A two-dimensional array. If null is None a masked array will be returned, otherwise a regular array will be returned. The first (slowest changing) index will correspond to the traces (index zero will correspond to the first crossline number). The second (fastest changing) index will correspond to the samples (index zero will correspond to the first sample number). """ if inline_number not in reader_3d.inline_numbers(): raise ValueError("Inline number {} not present in {}".format(inline_number, reader_3d)) xline_numbers = ensure_superset(reader_3d.xline_numbers(), xline_numbers) sample_numbers = ensure_superset(range(0, reader_3d.max_num_trace_samples()), sample_numbers) shape = (len(xline_numbers), len(sample_numbers)) dtype = make_dtype(reader_3d.data_sample_format) array = _make_array(shape, dtype, null) if isinstance(sample_numbers, range): _populate_inline_array_over_sample_range(reader_3d, inline_number, xline_numbers, sample_numbers, array) else: _populate_inline_array_numbered_samples(reader_3d, inline_number, xline_numbers, sample_numbers, array) return array def _populate_inline_array_numbered_samples(reader_3d, inline_number, xline_numbers, sample_numbers, array): for xline_index, xline_number in enumerate(xline_numbers): inline_xline_number = (inline_number, xline_number) if reader_3d.has_trace_index(inline_xline_number): trace_index = reader_3d.trace_index(inline_xline_number) num_trace_samples = reader_3d.num_trace_samples(trace_index) trace_sample_start = sample_numbers[0] trace_sample_stop = min(sample_numbers[-1] + 1, num_trace_samples) trace_samples = reader_3d.trace_samples(trace_index, trace_sample_start, trace_sample_stop) for sample_index, sample_number in enumerate(sample_numbers): array[xline_index, sample_index] = trace_samples[sample_number - trace_sample_start] def _populate_inline_array_over_sample_range(reader_3d, inline_number, xline_numbers, sample_numbers, array): for xline_index, xline_number in enumerate(xline_numbers): inline_xline_number = (inline_number, xline_number) if reader_3d.has_trace_index(inline_xline_number): trace_index = reader_3d.trace_index(inline_xline_number) num_trace_samples = reader_3d.num_trace_samples(trace_index) trace_sample_stop = min(sample_numbers.stop, num_trace_samples) trace_samples = reader_3d.trace_samples(trace_index, sample_numbers.start, trace_sample_stop) source_slice = slice(sample_numbers.start, trace_sample_stop, sample_numbers.step) array[xline_index, :] = trace_samples[source_slice] def extract_xline_3d(reader_3d, xline_number, inline_numbers=None, sample_numbers=None, null=None): """Extract an inline as a two-dimensional array. Args: reader_3d: A SegYReader3D object. xline_number: The number of the xline to be extracted. inline_numbers: The inline numbers within the crossline at which traces are to be extracted. This argument can be specified in three ways: None (the default) - All traces within the crossline will be be extracted. sequence - When a sequence, such as a range or a list is provided only those traces at inline numbers corresponding to the items in the sequence will be extracted. The traces will always be extracted in increasing numeric order and duplicate entries will be ignored. For example inline_numbers=range(100, 200, 2) will extract alternate traces from inline number 100 to inline number 198 inclusive. slice - When a slice object is provided the slice will be applied to the sequence of all inline numbers. For example inline_numbers=slice(100, -100) will omit the first one hundred and the last one hundred traces, irrespective of their numbers. sample_numbers: The sample numbers within each trace at which samples are to be extracted. This argument can be specified in three ways: None (the default) - All samples within the trace will be be extracted. sequence - When a sequence, such as a range or a list is provided only those samples at sample numbers corresponding to the items in the sequence will be extracted. The samples will always be extracted in increasing numeric order and duplicate entries will be ignored. For example sample_numbers=range(100, 200, 2) will extract alternate samples from sample number 100 to sample number 198 inclusive. slice - When a slice object is provided the slice will be applied to the sequence of all sample numbers. For example sample_numbers=slice(100, -100) will omit the first one hundred and the last one hundred samples, irrespective of their numbers. null: A null value. When None is specified as the null value a masked array will be returned. Returns: A two-dimensional array. If null is None a masked array will be returned, otherwise a regular array will be returned. The first (slowest changing) index will correspond to the traces (index zero will correspond to the first inline number). The second (fastest changing) index will correspond to the samples (index zero will correspond to the first sample number). """ if xline_number not in reader_3d.xline_numbers(): raise ValueError("Crossline number {} not present in {}".format(xline_number, reader_3d)) inline_numbers = ensure_superset(reader_3d.inline_numbers(), inline_numbers) sample_numbers = ensure_superset(range(0, reader_3d.max_num_trace_samples()), sample_numbers) shape = (len(inline_numbers), len(sample_numbers)) dtype = make_dtype(reader_3d.data_sample_format) array = _make_array(shape, dtype, null) if isinstance(sample_numbers, range): _populate_xline_array_over_sample_range(reader_3d, xline_number, inline_numbers, sample_numbers, array) else: _populate_xline_array_numbered_samples(reader_3d, xline_number, inline_numbers, sample_numbers, array) return array def _populate_xline_array_numbered_samples(reader_3d, xline_number, inline_numbers, sample_numbers, array): for inline_index, inline_number in enumerate(inline_numbers): inline_xline_number = (inline_number, xline_number) if reader_3d.has_trace_index(inline_xline_number): trace_index = reader_3d.trace_index(inline_xline_number) num_trace_samples = reader_3d.num_trace_samples(trace_index) trace_sample_start = sample_numbers[0] trace_sample_stop = min(sample_numbers[-1] + 1, num_trace_samples) trace_samples = reader_3d.trace_samples(trace_index, trace_sample_start, trace_sample_stop) for sample_index, sample_number in enumerate(sample_numbers): array[inline_index, sample_index] = trace_samples[sample_number - trace_sample_start] def _populate_xline_array_over_sample_range(reader_3d, xline_number, inline_numbers, sample_numbers, array): for inline_index, inline_number in enumerate(inline_numbers): inline_xline_number = (inline_number, xline_number) if reader_3d.has_trace_index(inline_xline_number): trace_index = reader_3d.trace_index(inline_xline_number) num_trace_samples = reader_3d.num_trace_samples(trace_index) trace_sample_stop = min(sample_numbers.stop, num_trace_samples) trace_samples = reader_3d.trace_samples(trace_index, sample_numbers.start, trace_sample_stop) source_slice = slice(sample_numbers.start, trace_sample_stop, sample_numbers.step) array[inline_index, :] = trace_samples[source_slice] def extract_timeslice_3d(reader_3d, sample_number, inline_numbers=None, xline_numbers=None, null=None): """Extract a single timeslice header field from all trace headers as an array. Args: reader_3d: A SegYReader3D sample_number: The zero-based sample index. inline_numbers: The inline numbers for which traces are to be extracted. This argument can be specified in three ways: None (the default) - All traces within the each crossline will be be extracted. sequence - When a sequence, such as a range or a list is provided only those traces at inline numbers corresponding to the items in the sequence will be extracted. The traces will always be extracted in increasing numeric order and duplicate entries will be ignored. For example inline_numbers=range(100, 200, 2) will extract alternate traces from inline number 100 to inline number 198 inclusive. slice - When a slice object is provided the slice will be applied to the sequence of all inline numbers. For example inline_numbers=slice(100, -100) will omit the first one hundred and the last one hundred traces, irrespective of their numbers. xline_numbers: The crossline numbers at which traces are to be extracted. This argument can be specified in three ways: None (the default) - All traces at within each inline will be be extracted. sequence - When a sequence, such as a range or a list is provided only those traces at crossline numbers corresponding to the items in the sequence will be extracted. The traces will always be extracted in increasing numeric order and duplicate entries will be ignored. For example xline_numbers=range(100, 200, 2) will extract alternate traces from crossline number 100 to crossline number 198 inclusive. slice - When a slice object is provided the slice will be applied to the sequence of all crossline numbers. For example xline_numbers=slice(100, -100) will omit the first one hundred and the last one hundred traces, irrespective of their numbers. null: An optional null value for missing traces. The null value must be convertible to all field value types. Returns: An namedtuple object with attributes which are two-dimensional Numpy arrays. If a null value was specified the arrays will be ndarrays, otherwise they will be masked arrays. The attributes of the named tuple are in the same order as the fields specified in the `fields` argument. Raises: AttributeError: If the the named fields do not exist in the trace header definition. """ inline_numbers = ensure_superset(reader_3d.inline_numbers(), inline_numbers) xline_numbers = ensure_superset(reader_3d.xline_numbers(), xline_numbers) shape = (len(inline_numbers), len(xline_numbers)) dtype = make_dtype(reader_3d.data_sample_format) array = _make_array(shape, dtype, null) sample_number_stop = sample_number + 1 for inline_index, inline_number in enumerate(inline_numbers): for xline_index, xline_number in enumerate(xline_numbers): inline_xline_number = (inline_number, xline_number) if reader_3d.has_trace_index(inline_xline_number): trace_index = reader_3d.trace_index((inline_number, xline_number)) trace_samples = reader_3d.trace_samples(trace_index, sample_number, sample_number_stop) array[inline_index, xline_index] = trace_samples[0] return array def _make_array(shape, dtype, null=None): """Make an array""" if null is None: return np.ma.masked_all(shape, dtype) array = np.empty(shape, dtype) array.fill(null) return array def _extract_field_name(field): """Args: field: If field in an object with a name attribute the name is returned. If field is a string it is returned unmodified. Raises: TypeError: """ if isinstance(field, str): return field try: return field.name except AttributeError: raise TypeError("{!r} neither is a string nor has a 'name' attribute".format(field))
agpl-3.0
Natim/sentry
src/sentry/utils/runner.py
5
13876
#!/usr/bin/env python """ sentry.utils.runner ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function from logan.runner import run_app, configure_app import base64 import os import sys import pkg_resources import warnings from functools import partial USE_GEVENT = os.environ.get('USE_GEVENT') == '1' SKIP_BACKEND_VALIDATION = os.environ.get('SKIP_BACKEND_VALIDATION') == '1' KEY_LENGTH = 40 CONFIG_TEMPLATE = """ # This file is just Python, with a touch of Django which means # you can inherit and tweak settings to your hearts content. from sentry.conf.server import * import os.path CONF_ROOT = os.path.dirname(__file__) DATABASES = { 'default': { # You can swap out the engine for MySQL easily by changing this value # to ``django.db.backends.mysql`` or to PostgreSQL with # ``sentry.db.postgres`` # If you change this, you'll also need to install the appropriate python # package: psycopg2 (Postgres) or mysql-python 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(CONF_ROOT, 'sentry.db'), 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # You should not change this setting after your database has been created # unless you have altered all schemas first SENTRY_USE_BIG_INTS = True # If you're expecting any kind of real traffic on Sentry, we highly recommend # configuring the CACHES and Redis settings ########### # General # ########### # The administrative email for this installation. # Note: This will be reported back to getsentry.com as the point of contact. See # the beacon documentation for more information. This **must** be a string. # SENTRY_ADMIN_EMAIL = 'your.name@example.com' SENTRY_ADMIN_EMAIL = '' # Instruct Sentry that this install intends to be run by a single organization # and thus various UI optimizations should be enabled. SENTRY_SINGLE_ORGANIZATION = True ######### # Redis # ######### # Generic Redis configuration used as defaults for various things including: # Buffers, Quotas, TSDB SENTRY_REDIS_OPTIONS = { 'hosts': { 0: { 'host': '127.0.0.1', 'port': 6379, } } } ######### # Cache # ######### # Sentry currently utilizes two separate mechanisms. While CACHES is not a # requirement, it will optimize several high throughput patterns. # If you wish to use memcached, install the dependencies and adjust the config # as shown: # # pip install python-memcached # # CACHES = { # 'default': { # 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', # 'LOCATION': ['127.0.0.1:11211'], # } # } # A primary cache is required for things such as processing events SENTRY_CACHE = 'sentry.cache.redis.RedisCache' ######### # Queue # ######### # See https://docs.getsentry.com/on-premise/server/queue/ for more # information on configuring your queue broker and workers. Sentry relies # on a Python framework called Celery to manage queues. CELERY_ALWAYS_EAGER = False BROKER_URL = 'redis://localhost:6379' ############### # Rate Limits # ############### # Rate limits apply to notification handlers and are enforced per-project # automatically. SENTRY_RATELIMITER = 'sentry.ratelimits.redis.RedisRateLimiter' ################## # Update Buffers # ################## # Buffers (combined with queueing) act as an intermediate layer between the # database and the storage API. They will greatly improve efficiency on large # numbers of the same events being sent to the API in a short amount of time. # (read: if you send any kind of real data to Sentry, you should enable buffers) SENTRY_BUFFER = 'sentry.buffer.redis.RedisBuffer' ########## # Quotas # ########## # Quotas allow you to rate limit individual projects or the Sentry install as # a whole. SENTRY_QUOTAS = 'sentry.quotas.redis.RedisQuota' ######## # TSDB # ######## # The TSDB is used for building charts as well as making things like per-rate # alerts possible. SENTRY_TSDB = 'sentry.tsdb.redis.RedisTSDB' ################ # File storage # ################ # Any Django storage backend is compatible with Sentry. For more solutions see # the django-storages package: https://django-storages.readthedocs.org/en/latest/ SENTRY_FILESTORE = 'django.core.files.storage.FileSystemStorage' SENTRY_FILESTORE_OPTIONS = { 'location': '/tmp/sentry-files', } ############## # Web Server # ############## # You MUST configure the absolute URI root for Sentry: SENTRY_URL_PREFIX = 'http://sentry.example.com' # No trailing slash! # If you're using a reverse proxy, you should enable the X-Forwarded-Proto # header and uncomment the following settings # SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # SESSION_COOKIE_SECURE = True # If you're not hosting at the root of your web server, and not using uWSGI, # you need to uncomment and set it to the path where Sentry is hosted. # FORCE_SCRIPT_NAME = '/sentry' SENTRY_WEB_HOST = '0.0.0.0' SENTRY_WEB_PORT = 9000 SENTRY_WEB_OPTIONS = { # 'workers': 3, # the number of gunicorn workers # 'secure_scheme_headers': {'X-FORWARDED-PROTO': 'https'}, } ############### # Mail Server # ############### # For more information check Django's documentation: # https://docs.djangoproject.com/en/1.3/topics/email/?from=olddocs#e-mail-backends EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_HOST_PASSWORD = '' EMAIL_HOST_USER = '' EMAIL_PORT = 25 EMAIL_USE_TLS = False # The email address to send on behalf of SERVER_EMAIL = 'root@localhost' # If you're using mailgun for inbound mail, set your API key and configure a # route to forward to /api/hooks/mailgun/inbound/ MAILGUN_API_KEY = '' ######## # etc. # ######## # If this file ever becomes compromised, it's important to regenerate your SECRET_KEY # Changing this value will result in all current sessions being invalidated SECRET_KEY = %(default_key)r """ def generate_settings(): """ This command is run when ``default_path`` doesn't exist, or ``init`` is run and returns a string representing the default data to put into their settings file. """ output = CONFIG_TEMPLATE % dict( default_key=base64.b64encode(os.urandom(KEY_LENGTH)), ) return output def install_plugin_apps(settings): # entry_points={ # 'sentry.apps': [ # 'phabricator = sentry_phabricator' # ], # }, installed_apps = list(settings.INSTALLED_APPS) for ep in pkg_resources.iter_entry_points('sentry.apps'): installed_apps.append(ep.module_name) settings.INSTALLED_APPS = tuple(installed_apps) def register_plugins(settings): from sentry.plugins import register # entry_points={ # 'sentry.plugins': [ # 'phabricator = sentry_phabricator.plugins:PhabricatorPlugin' # ], # }, for ep in pkg_resources.iter_entry_points('sentry.plugins'): try: plugin = ep.load() except Exception: import sys import traceback sys.stderr.write("Failed to load plugin %r:\n%s\n" % (ep.name, traceback.format_exc())) else: register(plugin) def initialize_receivers(): # force signal registration import sentry.receivers # NOQA def initialize_gevent(): from gevent import monkey monkey.patch_all() try: import psycopg2 # NOQA except ImportError: pass else: from sentry.utils.gevent import make_psycopg_green make_psycopg_green() def initialize_app(config, skip_backend_validation=False): settings = config['settings'] fix_south(settings) apply_legacy_settings(settings) install_plugin_apps(settings) # Commonly setups don't correctly configure themselves for production envs # so lets try to provide a bit more guidance if settings.CELERY_ALWAYS_EAGER and not settings.DEBUG: warnings.warn('Sentry is configured to run asynchronous tasks in-process. ' 'This is not recommended within production environments. ' 'See https://docs.getsentry.com/on-premise/server/queue/ for more information.') if settings.SENTRY_SINGLE_ORGANIZATION: settings.SENTRY_FEATURES['organizations:create'] = False settings.SUDO_COOKIE_SECURE = getattr(settings, 'SESSION_COOKIE_SECURE', False) settings.SUDO_COOKIE_DOMAIN = getattr(settings, 'SESSION_COOKIE_DOMAIN', None) settings.CACHES['default']['VERSION'] = settings.CACHE_VERSION if USE_GEVENT: from django.db import connections connections['default'].allow_thread_sharing = True register_plugins(settings) initialize_receivers() if not (skip_backend_validation or SKIP_BACKEND_VALIDATION): validate_backends() from django.utils import timezone from sentry.app import env env.data['config'] = config.get('config_path') env.data['start_date'] = timezone.now() def validate_backends(): from sentry import app app.buffer.validate() app.nodestore.validate() app.quotas.validate() app.search.validate() app.ratelimiter.validate() app.tsdb.validate() def fix_south(settings): # South needs an adapter defined conditionally if settings.DATABASES['default']['ENGINE'] != 'sentry.db.postgres': return settings.SOUTH_DATABASE_ADAPTERS = { 'default': 'south.db.postgresql_psycopg2' } def show_big_error(message): sys.stderr.write('\n') sys.stderr.write('\033[91m!! %s !!\033[0m\n' % ('!' * min(len(message), 80),)) sys.stderr.write('\033[91m!! %s !!\033[0m\n' % message) sys.stderr.write('\033[91m!! %s !!\033[0m\n' % ('!' * min(len(message), 80),)) sys.stderr.write('\n') def apply_legacy_settings(settings): # SENTRY_USE_QUEUE used to determine if Celery was eager or not if hasattr(settings, 'SENTRY_USE_QUEUE'): warnings.warn('SENTRY_USE_QUEUE is deprecated. Please use CELERY_ALWAYS_EAGER instead. ' 'See https://docs.getsentry.com/on-premise/server/queue/ for more information.', DeprecationWarning) settings.CELERY_ALWAYS_EAGER = (not settings.SENTRY_USE_QUEUE) if not settings.SENTRY_ADMIN_EMAIL: show_big_error('SENTRY_ADMIN_EMAIL is not configured') elif not isinstance(settings.SENTRY_ADMIN_EMAIL, basestring): show_big_error('SENTRY_ADMIN_EMAIL must be a string') if settings.SENTRY_URL_PREFIX in ('', 'http://sentry.example.com') and not settings.DEBUG: # Maybe also point to a piece of documentation for more information? # This directly coincides with users getting the awkward # `ALLOWED_HOSTS` exception. show_big_error('SENTRY_URL_PREFIX is not configured') # Set `ALLOWED_HOSTS` to the catch-all so it works settings.ALLOWED_HOSTS = ['*'] if settings.TIME_ZONE != 'UTC': # non-UTC timezones are not supported show_big_error('TIME_ZONE should be set to UTC') # Set ALLOWED_HOSTS if it's not already available if not settings.ALLOWED_HOSTS: from urlparse import urlparse urlbits = urlparse(settings.SENTRY_URL_PREFIX) if urlbits.hostname: settings.ALLOWED_HOSTS = (urlbits.hostname,) if hasattr(settings, 'SENTRY_ALLOW_REGISTRATION'): warnings.warn('SENTRY_ALLOW_REGISTRATION is deprecated. Use SENTRY_FEATURES instead.', DeprecationWarning) settings.SENTRY_FEATURES['auth:register'] = settings.SENTRY_ALLOW_REGISTRATION def skip_migration_if_applied(settings, app_name, table_name, name='0001_initial'): from south.migration import Migrations from sentry.utils.db import table_exists import types if app_name not in settings.INSTALLED_APPS: return migration = Migrations(app_name)[name] def skip_if_table_exists(original): def wrapped(self): # TODO: look into why we're having to return some ridiculous # lambda if table_exists(table_name): return lambda x=None: None return original() wrapped.__name__ = original.__name__ return wrapped migration.forwards = types.MethodType( skip_if_table_exists(migration.forwards), migration) def on_configure(config): """ Executes after settings are full installed and configured. At this point we can force import on various things such as models as all of settings should be correctly configured. """ settings = config['settings'] skip_migration_if_applied( settings, 'kombu.contrib.django', 'djkombu_queue') skip_migration_if_applied( settings, 'social_auth', 'social_auth_association') def configure(config_path=None, skip_backend_validation=False): configure_app( project='sentry', config_path=config_path, default_config_path='~/.sentry/sentry.conf.py', default_settings='sentry.conf.server', settings_initializer=generate_settings, settings_envvar='SENTRY_CONF', initializer=partial( initialize_app, skip_backend_validation=skip_backend_validation), on_configure=on_configure, ) def main(): if USE_GEVENT: sys.stderr.write("Configuring Sentry with gevent bindings\n") initialize_gevent() run_app( project='sentry', default_config_path='~/.sentry/sentry.conf.py', default_settings='sentry.conf.server', settings_initializer=generate_settings, settings_envvar='SENTRY_CONF', initializer=initialize_app, ) if __name__ == '__main__': main()
bsd-3-clause
trueblue2704/AskMeAnything
lib/python2.7/site-packages/flask/testsuite/templating.py
562
11237
# -*- coding: utf-8 -*- """ flask.testsuite.templating ~~~~~~~~~~~~~~~~~~~~~~~~~~ Template functionality :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import flask import unittest from flask.testsuite import FlaskTestCase class TemplatingTestCase(FlaskTestCase): def test_context_processing(self): app = flask.Flask(__name__) @app.context_processor def context_processor(): return {'injected_value': 42} @app.route('/') def index(): return flask.render_template('context_template.html', value=23) rv = app.test_client().get('/') self.assert_equal(rv.data, b'<p>23|42') def test_original_win(self): app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template_string('{{ config }}', config=42) rv = app.test_client().get('/') self.assert_equal(rv.data, b'42') def test_request_less_rendering(self): app = flask.Flask(__name__) app.config['WORLD_NAME'] = 'Special World' @app.context_processor def context_processor(): return dict(foo=42) with app.app_context(): rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} ' '{{ foo }}') self.assert_equal(rv, 'Hello Special World 42') def test_standard_context(self): app = flask.Flask(__name__) app.secret_key = 'development key' @app.route('/') def index(): flask.g.foo = 23 flask.session['test'] = 'aha' return flask.render_template_string(''' {{ request.args.foo }} {{ g.foo }} {{ config.DEBUG }} {{ session.test }} ''') rv = app.test_client().get('/?foo=42') self.assert_equal(rv.data.split(), [b'42', b'23', b'False', b'aha']) def test_escaping(self): text = '<p>Hello World!' app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('escaping_template.html', text=text, html=flask.Markup(text)) lines = app.test_client().get('/').data.splitlines() self.assert_equal(lines, [ b'&lt;p&gt;Hello World!', b'<p>Hello World!', b'<p>Hello World!', b'<p>Hello World!', b'&lt;p&gt;Hello World!', b'<p>Hello World!' ]) def test_no_escaping(self): app = flask.Flask(__name__) with app.test_request_context(): self.assert_equal(flask.render_template_string('{{ foo }}', foo='<test>'), '<test>') self.assert_equal(flask.render_template('mail.txt', foo='<test>'), '<test> Mail') def test_macros(self): app = flask.Flask(__name__) with app.test_request_context(): macro = flask.get_template_attribute('_macro.html', 'hello') self.assert_equal(macro('World'), 'Hello World!') def test_template_filter(self): app = flask.Flask(__name__) @app.template_filter() def my_reverse(s): return s[::-1] self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') def test_add_template_filter(self): app = flask.Flask(__name__) def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse) self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') def test_template_filter_with_name(self): app = flask.Flask(__name__) @app.template_filter('strrev') def my_reverse(s): return s[::-1] self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') def test_add_template_filter_with_name(self): app = flask.Flask(__name__) def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse, 'strrev') self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') def test_template_filter_with_template(self): app = flask.Flask(__name__) @app.template_filter() def super_reverse(s): return s[::-1] @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_template(self): app = flask.Flask(__name__) def super_reverse(s): return s[::-1] app.add_template_filter(super_reverse) @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_template_filter_with_name_and_template(self): app = flask.Flask(__name__) @app.template_filter('super_reverse') def my_reverse(s): return s[::-1] @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_name_and_template(self): app = flask.Flask(__name__) def my_reverse(s): return s[::-1] app.add_template_filter(my_reverse, 'super_reverse') @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_template_test(self): app = flask.Flask(__name__) @app.template_test() def boolean(value): return isinstance(value, bool) self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_add_template_test(self): app = flask.Flask(__name__) def boolean(value): return isinstance(value, bool) app.add_template_test(boolean) self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_template_test_with_name(self): app = flask.Flask(__name__) @app.template_test('boolean') def is_boolean(value): return isinstance(value, bool) self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_add_template_test_with_name(self): app = flask.Flask(__name__) def is_boolean(value): return isinstance(value, bool) app.add_template_test(is_boolean, 'boolean') self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_template_test_with_template(self): app = flask.Flask(__name__) @app.template_test() def boolean(value): return isinstance(value, bool) @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_add_template_test_with_template(self): app = flask.Flask(__name__) def boolean(value): return isinstance(value, bool) app.add_template_test(boolean) @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_template_test_with_name_and_template(self): app = flask.Flask(__name__) @app.template_test('boolean') def is_boolean(value): return isinstance(value, bool) @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_add_template_test_with_name_and_template(self): app = flask.Flask(__name__) def is_boolean(value): return isinstance(value, bool) app.add_template_test(is_boolean, 'boolean') @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_add_template_global(self): app = flask.Flask(__name__) @app.template_global() def get_stuff(): return 42 self.assert_in('get_stuff', app.jinja_env.globals.keys()) self.assert_equal(app.jinja_env.globals['get_stuff'], get_stuff) self.assert_true(app.jinja_env.globals['get_stuff'](), 42) with app.app_context(): rv = flask.render_template_string('{{ get_stuff() }}') self.assert_equal(rv, '42') def test_custom_template_loader(self): class MyFlask(flask.Flask): def create_global_jinja_loader(self): from jinja2 import DictLoader return DictLoader({'index.html': 'Hello Custom World!'}) app = MyFlask(__name__) @app.route('/') def index(): return flask.render_template('index.html') c = app.test_client() rv = c.get('/') self.assert_equal(rv.data, b'Hello Custom World!') def test_iterable_loader(self): app = flask.Flask(__name__) @app.context_processor def context_processor(): return {'whiskey': 'Jameson'} @app.route('/') def index(): return flask.render_template( ['no_template.xml', # should skip this one 'simple_template.html', # should render this 'context_template.html'], value=23) rv = app.test_client().get('/') self.assert_equal(rv.data, b'<h1>Jameson</h1>') def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TemplatingTestCase)) return suite
mit
devanshdalal/scikit-learn
examples/svm/plot_svm_margin.py
88
2540
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= SVM Margins Example ========================================================= The plots below illustrate the effect the parameter `C` has on the separation line. A large value of `C` basically tells our model that we do not have that much faith in our data's distribution, and will only consider points close to line of separation. A small value of `C` includes more/all the observations, allowing the margins to be calculated using all the data in the area. """ print(__doc__) # Code source: Gaël Varoquaux # Modified for documentation by Jaques Grobler # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn import svm # we create 40 separable points np.random.seed(0) X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]] Y = [0] * 20 + [1] * 20 # figure number fignum = 1 # fit the model for name, penalty in (('unreg', 1), ('reg', 0.05)): clf = svm.SVC(kernel='linear', C=penalty) clf.fit(X, Y) # get the separating hyperplane w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(-5, 5) yy = a * xx - (clf.intercept_[0]) / w[1] # plot the parallels to the separating hyperplane that pass through the # support vectors (margin away from hyperplane in direction # perpendicular to hyperplane). This is sqrt(1+a^2) away vertically in # 2-d. margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2)) yy_down = yy - np.sqrt(1 + a ** 2) * margin yy_up = yy + np.sqrt(1 + a ** 2) * margin # plot the line, the points, and the nearest vectors to the plane plt.figure(fignum, figsize=(4, 3)) plt.clf() plt.plot(xx, yy, 'k-') plt.plot(xx, yy_down, 'k--') plt.plot(xx, yy_up, 'k--') plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80, facecolors='none', zorder=10, edgecolors='k') plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired, edgecolors='k') plt.axis('tight') x_min = -4.8 x_max = 4.2 y_min = -6 y_max = 6 XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j] Z = clf.predict(np.c_[XX.ravel(), YY.ravel()]) # Put the result into a color plot Z = Z.reshape(XX.shape) plt.figure(fignum, figsize=(4, 3)) plt.pcolormesh(XX, YY, Z, cmap=plt.cm.Paired) plt.xlim(x_min, x_max) plt.ylim(y_min, y_max) plt.xticks(()) plt.yticks(()) fignum = fignum + 1 plt.show()
bsd-3-clause
rogerscristo/BotFWD
env/lib/python3.6/site-packages/pytests/test_inlinequeryresultcachedphoto.py
1
4943
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2017 # Leandro Toledo de Souza <devs@python-telegram-bot.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 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 json import pytest from telegram import (InputTextMessageContent, InlineQueryResultCachedPhoto, InlineKeyboardButton, InlineQueryResultCachedVoice, InlineKeyboardMarkup) @pytest.fixture(scope='class') def inline_query_result_cached_photo(): return InlineQueryResultCachedPhoto(TestInlineQueryResultCachedPhoto.id, TestInlineQueryResultCachedPhoto.photo_file_id, title=TestInlineQueryResultCachedPhoto.title, description=TestInlineQueryResultCachedPhoto.description, caption=TestInlineQueryResultCachedPhoto.caption, input_message_content=TestInlineQueryResultCachedPhoto.input_message_content, reply_markup=TestInlineQueryResultCachedPhoto.reply_markup) class TestInlineQueryResultCachedPhoto: id = 'id' type = 'photo' photo_file_id = 'photo file id' title = 'title' description = 'description' caption = 'caption' input_message_content = InputTextMessageContent('input_message_content') reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]]) def test_expected_values(self, inline_query_result_cached_photo): assert inline_query_result_cached_photo.type == self.type assert inline_query_result_cached_photo.id == self.id assert inline_query_result_cached_photo.photo_file_id == self.photo_file_id assert inline_query_result_cached_photo.title == self.title assert inline_query_result_cached_photo.description == self.description assert inline_query_result_cached_photo.caption == self.caption assert inline_query_result_cached_photo.input_message_content.to_dict() == \ self.input_message_content.to_dict() assert inline_query_result_cached_photo.reply_markup.to_dict() == \ self.reply_markup.to_dict() def test_to_json(self, inline_query_result_cached_photo): json.loads(inline_query_result_cached_photo.to_json()) def test_to_dict(self, inline_query_result_cached_photo): inline_query_result_cached_photo_dict = inline_query_result_cached_photo.to_dict() assert isinstance(inline_query_result_cached_photo_dict, dict) assert inline_query_result_cached_photo_dict['type'] == \ inline_query_result_cached_photo.type assert inline_query_result_cached_photo_dict['id'] == inline_query_result_cached_photo.id assert inline_query_result_cached_photo_dict['photo_file_id'] == \ inline_query_result_cached_photo.photo_file_id assert inline_query_result_cached_photo_dict['title'] == \ inline_query_result_cached_photo.title assert inline_query_result_cached_photo_dict['description'] == \ inline_query_result_cached_photo.description assert inline_query_result_cached_photo_dict['caption'] == \ inline_query_result_cached_photo.caption assert inline_query_result_cached_photo_dict['input_message_content'] == \ inline_query_result_cached_photo.input_message_content.to_dict() assert inline_query_result_cached_photo_dict['reply_markup'] == \ inline_query_result_cached_photo.reply_markup.to_dict() def test_equality(self): a = InlineQueryResultCachedPhoto(self.id, self.photo_file_id) b = InlineQueryResultCachedPhoto(self.id, self.photo_file_id) c = InlineQueryResultCachedPhoto(self.id, "") d = InlineQueryResultCachedPhoto("", self.photo_file_id) e = InlineQueryResultCachedVoice(self.id, "", "") assert a == b assert hash(a) == hash(b) assert a is not b assert a == c assert hash(a) == hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
mit
Fantu/Cinnamon
files/usr/share/cinnamon/cinnamon-settings/bin/CinnamonGtkSettings.py
3
19824
#!/usr/bin/python3 import os.path import signal try: import tinycss2 except: pass import gi gi.require_version("Gtk", "3.0") from gi.repository import GLib, Gtk, Gio, GObject from xapp.SettingsWidgets import SettingsWidget, Range, Switch SETTINGS_GROUP_NAME = "Settings" ini_instance = None def get_ini_editor(): global ini_instance if ini_instance is None: ini_instance = GtkSettingsEditor() return ini_instance class GtkSettingsEditor: def __init__(self): self._path = os.path.join(GLib.get_user_config_dir(), "gtk-3.0", "settings.ini") self.default_settings = Gtk.Settings.get_default() def _get_keyfile(self): keyfile = None try: keyfile = GLib.KeyFile() keyfile.load_from_file(self._path, 0) except: pass finally: return keyfile def get_boolean(self, key): keyfile = self._get_keyfile() try: result = keyfile.get_boolean(SETTINGS_GROUP_NAME, key) except: result = self.default_settings.get_property(key) return result def set_boolean(self, key, value): keyfile = self._get_keyfile() keyfile.set_boolean(SETTINGS_GROUP_NAME, key, value) try: data = keyfile.to_data() GLib.file_set_contents(self._path, bytes(data[0], encoding="utf8")) except: raise class GtkSettingsSwitch(Switch): def __init__(self, markup, setting_name=None): self.setting_name = setting_name super(GtkSettingsSwitch, self).__init__(markup) self.settings = get_ini_editor() self.content_widget.set_active(self.settings.get_boolean(self.setting_name)) self.content_widget.connect("notify::active", self.on_switch_active_changed) def on_switch_active_changed(self, switch, pspec, data=None): self.settings.set_boolean(self.setting_name, self.content_widget.get_active()) css_instance = None def get_css_editor(selector=None): global css_instance if css_instance is None: css_instance = GtkCssEditor(selector) return css_instance class CSSSettingsException(Exception): pass class GtkCssEditor: def __init__(self, selector): self._path = os.path.join(GLib.get_user_config_dir(), "gtk-3.0", "gtk.css") self.selector = selector self.rule_separator = "/***** %s - cinnamon-settings-generated - do not edit *****/" % self.selector rules = [] file = Gio.File.new_for_path(self._path) try: success, content_bytes, tag = file.load_contents(None) self._contents = content_bytes.decode() stylesheet = tinycss2.parse_stylesheet(self._contents) for rs in stylesheet: if isinstance(rs, tinycss2.ast.ParseError): continue rules.append(rs) self.stylesheet = rules except GLib.Error as e: if e.code == Gio.IOErrorEnum.NOT_FOUND: self._contents = "" self.stylesheet = rules else: raise PermissionError("Could not load ~/.config/gtk-3.0/gtk.css file, check permissions") def sanitize_contents(self): in_lines = self._contents.split("\n") out_lines = [] sof = True selector_found = False for line in in_lines: if self.rule_separator in line: break if line == "" and sof: continue if line.strip().startswith(self.selector): selector_found = True continue if not selector_found: out_lines.append(line) sof = False continue if "}" in line: selector_found = False continue if line == "" and len(out_lines) > 0: out_lines.pop() self._contents = "\n".join(out_lines) def _serialize_selector(self, rule): at_css = "" if isinstance(rule, tinycss2.ast.AtRule): at_css += "@" + rule.at_keyword at_css += self._serialize_prelude(rule.prelude) return at_css def _serialize_prelude(self, prelude): at_css = "" for cv in prelude: if isinstance(cv, tinycss2.ast.WhitespaceToken): at_css += " " elif isinstance(cv, tinycss2.ast.HashToken): at_css += "#" + cv.value elif isinstance(cv, tinycss2.ast.FunctionBlock): next else: at_css += cv.value return at_css.strip() def get_ruleset(self, selector_css): """ Gets the current ruleset for selector_css, If it isn't currently defined, returns an empty one. """ idx = 0 for rs in self.stylesheet: if isinstance(rs, (tinycss2.ast.AtRule, tinycss2.ast.QualifiedRule)): if self._serialize_selector(rs) == selector_css: return rs, idx idx += 1 new_ruleset = tinycss2.parse_one_rule(selector_css + " {}", False) self.stylesheet.append(new_ruleset) return new_ruleset, len(self.stylesheet) - 1 def get_declaration(self, selector, decl_name): rs, _ = self.get_ruleset(selector) declarations = tinycss2.parse_declaration_list(rs.content, True, True) for declaration in declarations: if decl_name == declaration.name: decl_value = None for component_value in declaration.value: if isinstance(component_value, tinycss2.ast.DimensionToken): decl_value = component_value.value return decl_value return None def set_declaration(self, selector, decl_name, value_as_str): # Remove an existing declaration.. for some reason if they # get modified, they become invalid (or I'm doing something wrong) self.remove_declaration(selector, decl_name) rs, idx = self.get_ruleset(selector) # rs.content[0].value: the value of the WhitespaceToken is the actual indent prefix = "\n\t" if rs.content: prefix = rs.content[0].value component_values = tinycss2.parse_component_value_list(prefix + decl_name + ": " + value_as_str + ";") for component_value in component_values: self.stylesheet[idx].content.append(component_value) @staticmethod def _remove_declaration_from_content(declaration, content): idx = 0 ident_idx = 0 found_ident = False done = False new_content = [] for component_value in content: idx += 1 if len(content) != idx and isinstance(content[idx], tinycss2.ast.IdentToken) and \ content[idx].value == declaration.name and \ isinstance(component_value, tinycss2.ast.WhitespaceToken): continue if isinstance(component_value, tinycss2.ast.IdentToken) and \ component_value.value == declaration.name: found_ident = True continue if found_ident: if isinstance(component_value, tinycss2.ast.LiteralToken): if ident_idx == 0 or done: done = False continue if len(declaration.value) - 1 == ident_idx and \ component_value == declaration.value[ident_idx]: done = True continue if component_value == declaration.value[ident_idx] and \ content[idx] == declaration.value[ident_idx + 1]: ident_idx += 1 continue new_content.append(component_value) return new_content def remove_declaration(self, selector, decl_name): rs, idx = self.get_ruleset(selector) if not rs: return declarations = tinycss2.parse_declaration_list(rs.content, True, True) for declaration in declarations: if decl_name == declaration.name: new_content = self._remove_declaration_from_content(declaration, rs.content) if not new_content: self.stylesheet.remove(rs) break self.stylesheet[idx].content = new_content break def save_stylesheet(self): self.sanitize_contents() out = "" lines = self._contents.split("\n") for line in lines: if self.rule_separator in line: break out += line + "\n" if self.stylesheet: if line != "": out += "\n" out += self.rule_separator + "\n" for rs in self.stylesheet: out += rs.serialize() self._contents = out try: with open(self._path, "w+") as f: f.write(out) except PermissionError as e: print(e) class CssOverrideSwitch(Switch): def __init__(self, markup, setting_name=None): self.setting_name = setting_name super(CssOverrideSwitch, self).__init__(markup) self.content_widget.set_active(False) class CssRange(Range): def __init__(self, markup, selector, decl_names, mini, maxi, units="", tooltip="", switch_widget=None): # we override get_range() on the SettingsWidget, these properties need to exist before super() self.mini = mini self.maxi = maxi super(CssRange, self).__init__(markup, units=units, mini=mini, maxi=maxi, step=1, tooltip=tooltip) self.units = units self.timer = 0 self.switch_widget = switch_widget.content_widget self.selector = selector self.decl_names = decl_names def sync_initial_switch_state(self): editor = get_css_editor(self.selector) all_existing = True for decl_name in self.decl_names: if editor.get_declaration(self.selector, decl_name): continue all_existing = False break starting_value = 10 if all_existing: starting_value = editor.get_declaration(self.selector, self.decl_names[0]) self.content_widget.set_value(starting_value) self.switch_widget.set_active(all_existing) self.switch_widget.connect("notify::active", self.on_switch_active_changed) self.revealer.set_reveal_child(all_existing) def on_switch_active_changed(self, switch, pspec, data=None): active = switch.get_active() if active: # I'm not sure how we could get the current theme's scrollbar min-width, without # parsing it with tinycss also - a bit overkill? 10 is pretty common... self.revealer.set_reveal_child(True) self.content_widget.set_value(10) # set_value doesn't work if the switch was off at startup, the value won't be changing, # so apply_later won't be called from SettingsWidgets.Range self.apply_later() else: for name in self.decl_names: get_css_editor().remove_declaration(self.selector, name) self.revealer.set_reveal_child(False) get_css_editor().save_stylesheet() def apply_later(self, *args): def apply(self): editor = get_css_editor() for name in self.decl_names: value_as_str = "%d%s" % (int(self.content_widget.get_value()), self.units) editor.set_declaration(self.selector, name, value_as_str) editor.save_stylesheet() self.timer = 0 if self.timer > 0: GLib.source_remove(self.timer) self.timer = GLib.timeout_add(300, apply, self) def get_range(self): return [self.mini, self.maxi] class PreviewWidget(SettingsWidget): def __init__(self): super(PreviewWidget, self).__init__() self.content_widget = Gtk.Socket() self.content_widget.set_valign(Gtk.Align.CENTER) # This matches the plug toplevel container, it keeps the PreviewWidget from # resizing briefly when reloading the plug. self.content_widget.set_size_request(-1, 100) self.content_widget.connect("hierarchy-changed", self.on_widget_hierarchy_changed) self.content_widget.connect("plug-removed", self.on_plug_removed) self.file_monitor_delay = 0 self.interface_settings = Gio.Settings(schema_id="org.cinnamon.desktop.interface") self.update_overlay_state() self.pack_start(self.content_widget, True, True, 0) self.proc = None def update_overlay_state(self): if self.interface_settings.get_boolean("gtk-overlay-scrollbars"): GLib.setenv("GTK_OVERLAY_SCROLLING", "1", True) else: GLib.setenv("GTK_OVERLAY_SCROLLING", "0", True) def socket_is_anchored(self, socket): toplevel = socket.get_toplevel() is_toplevel = isinstance(toplevel, Gtk.Window) return is_toplevel def on_widget_hierarchy_changed(self, widget, previous_toplevel, data=None): if not self.socket_is_anchored(self.content_widget): self.kill_plug() return self.interface_settings.connect("changed::gtk-overlay-scrollbars", self.on_overlay_scrollbars_changed) self.interface_settings.get_boolean("gtk-overlay-scrollbars") path = os.path.join(GLib.get_user_config_dir(), "gtk-3.0") file = Gio.File.new_for_path(path) try: self.config_monitor = file.monitor_directory(Gio.FileMonitorFlags.NONE, None) self.config_monitor.connect("changed", self.on_config_dir_changed) except GLib.Error as e: print(e.message) self.reload() def on_plug_removed(self, socket, data=None): return True def on_overlay_scrollbars_changed(self, settings, key, data=None): self.update_overlay_state() self.reload() def on_config_dir_changed(self, monitor, file, other, event_type, data=None): if event_type != Gio.FileMonitorEvent.CHANGES_DONE_HINT: return if self.file_monitor_delay > 0: GObject.source_remove(self.file_monitor_delay) self.file_monitor_delay = GObject.timeout_add(100, self.on_file_monitor_delay_finished) def on_file_monitor_delay_finished(self, data=None): self.file_monitor_delay = 0 self.reload() return False def kill_plug(self): if self.proc: self.proc.send_signal(signal.SIGTERM) self.proc = None def reload(self): self.kill_plug() self.proc = Gio.Subprocess.new(['python3', '/usr/share/cinnamon/cinnamon-settings/bin/scrollbar-test-widget.py', str(self.content_widget.get_id())], Gio.SubprocessFlags.NONE) class Gtk2ScrollbarSizeEditor: def __init__(self, ui_scale): self._path = os.path.join(GLib.get_home_dir(), ".gtkrc-2.0") self._file = Gio.File.new_for_path(self._path) self._settings = Gio.Settings(schema_id="org.cinnamon.theme") self.ui_scale = ui_scale self.timeout_id = 0 self.number_end = 0 self.style_prop_start = 0 self._contents = "" try: success, content_bytes, tag = self._file.load_contents(None) self._contents = content_bytes.decode() except GLib.Error as e: if e.code == Gio.IOErrorEnum.NOT_FOUND: pass else: print("Could not load ~/.gtkrc-2.0 file: %s" % e.message) self.parse_contents() def set_size(self, size): if self.timeout_id > 0: GLib.source_remove(self.timeout_id) multiplier = self._settings.get_double("gtk-version-scrollbar-multiplier") comped_value = int(size * multiplier * self.ui_scale) self.timeout_id = GLib.timeout_add(300, self.on_set_size_timeout, comped_value) def on_set_size_timeout(self, size): c = self._contents if size > 0: style_prop = "GtkScrollbar::slider-width = %d" % size final_contents = c[:self.style_prop_start] + style_prop + c[self.style_prop_start:] else: final_contents = self._contents # print("saving changed: ", final_contents) try: self._file.replace_contents(final_contents.encode("utf-8"), None, False, 0, None) except GLib.Error as e: print("Could not save .gtkrc-2.0 file: %s" % e.message) self.timeout_id = 0 return False def make_default_contents(self): self._contents = """ ############################################### # Created by cinnamon-settings - please do not edit or reformat. # style "cs-scrollbar-style" { } class "GtkScrollbar" style "cs-scrollbar-style" ############################################### """ self.style_prop_start = 145 def check_preexisting_cs_modification(self): marker = "cs-scrollbar-style" c = self._contents if marker in c: i = c.index(marker) + len(marker) while i < len(c): if c[i] == "{": i += 1 open_bracket = i while i < len(c): if c[i] == "}": close_bracket = i self._contents = c[:open_bracket] + "\n\n" + c[close_bracket:] self.style_prop_start = open_bracket + 1 return True i += 1 i += 1 return False def parse_contents(self): if self.check_preexisting_cs_modification(): return style_prop = "GtkScrollbar::slider-width" if not self._contents: self.make_default_contents() return c = self._contents length = len(c) i = 0 found = False while i < length: if c[i:].startswith(style_prop): self.style_prop_start = i found = True break i += 1 if not found: self.make_default_contents() return i += len(style_prop) found = False while i < length: if c[i] == "=": found = True break i += 1 if not found: self.make_default_contents() return i += 1 found = False while i < length: if c[i].isalpha(): break if c[i].isspace(): i += 1 continue if c[i].isdigit(): found = True break if not found: self.make_default_contents() return i += 1 while i < length: if c[i].isdigit(): i += 1 continue else: self.number_end = i break self._contents = c[:self.style_prop_start] + c[self.number_end:]
gpl-2.0
ygol/dotfiles
bin/.venv-ansible-venv/lib/python2.6/site-packages/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py
1093
8936
# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy. # Passes Python2.7's test suite and incorporates all the latest updates. # Copyright 2009 Raymond Hettinger, released under the MIT License. # http://code.activestate.com/recipes/576693/ try: from thread import get_ident as _get_ident except ImportError: from dummy_thread import get_ident as _get_ident try: from _abcoll import KeysView, ValuesView, ItemsView except ImportError: pass class OrderedDict(dict): 'Dictionary that remembers insertion order' # An inherited dict maps keys to values. # The inherited dict provides __getitem__, __len__, __contains__, and get. # The remaining methods are order-aware. # Big-O running times for all methods are the same as for regular dictionaries. # The internal self.__map dictionary maps keys to links in a doubly linked list. # The circular doubly linked list starts and ends with a sentinel element. # The sentinel element never gets deleted (this simplifies the algorithm). # Each link is stored as a list of length three: [PREV, NEXT, KEY]. def __init__(self, *args, **kwds): '''Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. ''' if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__root except AttributeError: self.__root = root = [] # sentinel node root[:] = [root, root, None] self.__map = {} self.__update(*args, **kwds) def __setitem__(self, key, value, dict_setitem=dict.__setitem__): 'od.__setitem__(i, y) <==> od[i]=y' # Setting a new item creates a new link which goes at the end of the linked # list, and the inherited dictionary is updated with the new key/value pair. if key not in self: root = self.__root last = root[0] last[1] = root[0] = self.__map[key] = [last, root, key] dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__): 'od.__delitem__(y) <==> del od[y]' # Deleting an existing item uses self.__map to find the link which is # then removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) link_prev, link_next, key = self.__map.pop(key) link_prev[1] = link_next link_next[0] = link_prev def __iter__(self): 'od.__iter__() <==> iter(od)' root = self.__root curr = root[1] while curr is not root: yield curr[2] curr = curr[1] def __reversed__(self): 'od.__reversed__() <==> reversed(od)' root = self.__root curr = root[0] while curr is not root: yield curr[2] curr = curr[0] def clear(self): 'od.clear() -> None. Remove all items from od.' try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self) def popitem(self, last=True): '''od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false. ''' if not self: raise KeyError('dictionary is empty') root = self.__root if last: link = root[0] link_prev = link[0] link_prev[1] = root root[0] = link_prev else: link = root[1] link_next = link[1] root[1] = link_next link_next[0] = root key = link[2] del self.__map[key] value = dict.pop(self, key) return key, value # -- the following methods do not depend on the internal structure -- def keys(self): 'od.keys() -> list of keys in od' return list(self) def values(self): 'od.values() -> list of values in od' return [self[key] for key in self] def items(self): 'od.items() -> list of (key, value) pairs in od' return [(key, self[key]) for key in self] def iterkeys(self): 'od.iterkeys() -> an iterator over the keys in od' return iter(self) def itervalues(self): 'od.itervalues -> an iterator over the values in od' for k in self: yield self[k] def iteritems(self): 'od.iteritems -> an iterator over the (key, value) items in od' for k in self: yield (k, self[k]) def update(*args, **kwds): '''od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, v in F.items(): od[k] = v ''' if len(args) > 2: raise TypeError('update() takes at most 2 positional ' 'arguments (%d given)' % (len(args),)) elif not args: raise TypeError('update() takes at least 1 argument (0 given)') self = args[0] # Make progressively weaker assumptions about "other" other = () if len(args) == 2: other = args[1] if isinstance(other, dict): for key in other: self[key] = other[key] elif hasattr(other, 'keys'): for key in other.keys(): self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwds.items(): self[key] = value __update = update # let subclasses override update without breaking __init__ __marker = object() def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] return result if default is self.__marker: raise KeyError(key) return default def setdefault(self, key, default=None): 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od' if key in self: return self[key] self[key] = default return default def __repr__(self, _repr_running={}): 'od.__repr__() <==> repr(od)' call_key = id(self), _get_ident() if call_key in _repr_running: return '...' _repr_running[call_key] = 1 try: if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) finally: del _repr_running[call_key] def __reduce__(self): 'Return state information for pickling' items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,) def copy(self): 'od.copy() -> a shallow copy of od' return self.__class__(self) @classmethod def fromkeys(cls, iterable, value=None): '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None). ''' d = cls() for key in iterable: d[key] = value return d def __eq__(self, other): '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ''' if isinstance(other, OrderedDict): return len(self)==len(other) and self.items() == other.items() return dict.__eq__(self, other) def __ne__(self, other): return not self == other # -- the following methods are only used in Python 2.7 -- def viewkeys(self): "od.viewkeys() -> a set-like object providing a view on od's keys" return KeysView(self) def viewvalues(self): "od.viewvalues() -> an object providing a view on od's values" return ValuesView(self) def viewitems(self): "od.viewitems() -> a set-like object providing a view on od's items" return ItemsView(self)
mit
JamesMGreene/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/style/optparser.py
175
19377
# Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. """Supports the parsing of command-line options for check-webkit-style.""" import logging from optparse import OptionParser import os.path import sys from filter import validate_filter_rules # This module should not import anything from checker.py. _log = logging.getLogger(__name__) _USAGE = """usage: %prog [--help] [options] [path1] [path2] ... Overview: Check coding style according to WebKit style guidelines: http://webkit.org/coding/coding-style.html Path arguments can be files and directories. If neither a git commit nor paths are passed, then all changes in your source control working directory are checked. Style errors: This script assigns to every style error a confidence score from 1-5 and a category name. A confidence score of 5 means the error is certainly a problem, and 1 means it could be fine. Category names appear in error messages in brackets, for example [whitespace/indent]. See the options section below for an option that displays all available categories and which are reported by default. Filters: Use filters to configure what errors to report. Filters are specified using a comma-separated list of boolean filter rules. The script reports errors in a category if the category passes the filter, as described below. All categories start out passing. Boolean filter rules are then evaluated from left to right, with later rules taking precedence. For example, the rule "+foo" passes any category that starts with "foo", and "-foo" fails any such category. The filter input "-whitespace,+whitespace/braces" fails the category "whitespace/tab" and passes "whitespace/braces". Examples: --filter=-whitespace,+whitespace/braces --filter=-whitespace,-runtime/printf,+runtime/printf_format --filter=-,+build/include_what_you_use Paths: Certain style-checking behavior depends on the paths relative to the WebKit source root of the files being checked. For example, certain types of errors may be handled differently for files in WebKit/gtk/webkit/ (e.g. by suppressing "readability/naming" errors for files in this directory). Consequently, if the path relative to the source root cannot be determined for a file being checked, then style checking may not work correctly for that file. This can occur, for example, if no WebKit checkout can be found, or if the source root can be detected, but one of the files being checked lies outside the source tree. If a WebKit checkout can be detected and all files being checked are in the source tree, then all paths will automatically be converted to paths relative to the source root prior to checking. This is also useful for display purposes. Currently, this command can detect the source root only if the command is run from within a WebKit checkout (i.e. if the current working directory is below the root of a checkout). In particular, it is not recommended to run this script from a directory outside a checkout. Running this script from a top-level WebKit source directory and checking only files in the source tree will ensure that all style checking behaves correctly -- whether or not a checkout can be detected. This is because all file paths will already be relative to the source root and so will not need to be converted.""" _EPILOG = ("This script can miss errors and does not substitute for " "code review.") # This class should not have knowledge of the flag key names. class DefaultCommandOptionValues(object): """Stores the default check-webkit-style command-line options. Attributes: output_format: A string that is the default output format. min_confidence: An integer that is the default minimum confidence level. """ def __init__(self, min_confidence, output_format): self.min_confidence = min_confidence self.output_format = output_format # This class should not have knowledge of the flag key names. class CommandOptionValues(object): """Stores the option values passed by the user via the command line. Attributes: is_verbose: A boolean value of whether verbose logging is enabled. filter_rules: The list of filter rules provided by the user. These rules are appended to the base rules and path-specific rules and so take precedence over the base filter rules, etc. git_commit: A string representing the git commit to check. The default is None. min_confidence: An integer between 1 and 5 inclusive that is the minimum confidence level of style errors to report. The default is 1, which reports all errors. output_format: A string that is the output format. The supported output formats are "emacs" which emacs can parse and "vs7" which Microsoft Visual Studio 7 can parse. """ def __init__(self, filter_rules=None, git_commit=None, diff_files=None, is_verbose=False, min_confidence=1, output_format="emacs"): if filter_rules is None: filter_rules = [] if (min_confidence < 1) or (min_confidence > 5): raise ValueError('Invalid "min_confidence" parameter: value ' "must be an integer between 1 and 5 inclusive. " 'Value given: "%s".' % min_confidence) if output_format not in ("emacs", "vs7"): raise ValueError('Invalid "output_format" parameter: ' 'value must be "emacs" or "vs7". ' 'Value given: "%s".' % output_format) self.filter_rules = filter_rules self.git_commit = git_commit self.diff_files = diff_files self.is_verbose = is_verbose self.min_confidence = min_confidence self.output_format = output_format # Useful for unit testing. def __eq__(self, other): """Return whether this instance is equal to another.""" if self.filter_rules != other.filter_rules: return False if self.git_commit != other.git_commit: return False if self.diff_files != other.diff_files: return False if self.is_verbose != other.is_verbose: return False if self.min_confidence != other.min_confidence: return False if self.output_format != other.output_format: return False return True # Useful for unit testing. def __ne__(self, other): # Python does not automatically deduce this from __eq__(). return not self.__eq__(other) class ArgumentPrinter(object): """Supports the printing of check-webkit-style command arguments.""" def _flag_pair_to_string(self, flag_key, flag_value): return '--%(key)s=%(val)s' % {'key': flag_key, 'val': flag_value } def to_flag_string(self, options): """Return a flag string of the given CommandOptionValues instance. This method orders the flag values alphabetically by the flag key. Args: options: A CommandOptionValues instance. """ flags = {} flags['min-confidence'] = options.min_confidence flags['output'] = options.output_format # Only include the filter flag if user-provided rules are present. filter_rules = options.filter_rules if filter_rules: flags['filter'] = ",".join(filter_rules) if options.git_commit: flags['git-commit'] = options.git_commit if options.diff_files: flags['diff_files'] = options.diff_files flag_string = '' # Alphabetizing lets us unit test this method. for key in sorted(flags.keys()): flag_string += self._flag_pair_to_string(key, flags[key]) + ' ' return flag_string.strip() class ArgumentParser(object): # FIXME: Move the documentation of the attributes to the __init__ # docstring after making the attributes internal. """Supports the parsing of check-webkit-style command arguments. Attributes: create_usage: A function that accepts a DefaultCommandOptionValues instance and returns a string of usage instructions. Defaults to the function that generates the usage string for check-webkit-style. default_options: A DefaultCommandOptionValues instance that provides the default values for options not explicitly provided by the user. stderr_write: A function that takes a string as a parameter and serves as stderr.write. Defaults to sys.stderr.write. This parameter should be specified only for unit tests. """ def __init__(self, all_categories, default_options, base_filter_rules=None, mock_stderr=None, usage=None): """Create an ArgumentParser instance. Args: all_categories: The set of all available style categories. default_options: See the corresponding attribute in the class docstring. Keyword Args: base_filter_rules: The list of filter rules at the beginning of the list of rules used to check style. This list has the least precedence when checking style and precedes any user-provided rules. The class uses this parameter only for display purposes to the user. Defaults to the empty list. create_usage: See the documentation of the corresponding attribute in the class docstring. stderr_write: See the documentation of the corresponding attribute in the class docstring. """ if base_filter_rules is None: base_filter_rules = [] stderr = sys.stderr if mock_stderr is None else mock_stderr if usage is None: usage = _USAGE self._all_categories = all_categories self._base_filter_rules = base_filter_rules # FIXME: Rename these to reflect that they are internal. self.default_options = default_options self.stderr_write = stderr.write self._parser = self._create_option_parser(stderr=stderr, usage=usage, default_min_confidence=self.default_options.min_confidence, default_output_format=self.default_options.output_format) def _create_option_parser(self, stderr, usage, default_min_confidence, default_output_format): # Since the epilog string is short, it is not necessary to replace # the epilog string with a mock epilog string when testing. # For this reason, we use _EPILOG directly rather than passing it # as an argument like we do for the usage string. parser = OptionParser(usage=usage, epilog=_EPILOG) filter_help = ('set a filter to control what categories of style ' 'errors to report. Specify a filter using a comma-' 'delimited list of boolean filter rules, for example ' '"--filter -whitespace,+whitespace/braces". To display ' 'all categories and which are enabled by default, pass ' """no value (e.g. '-f ""' or '--filter=').""") parser.add_option("-f", "--filter-rules", metavar="RULES", dest="filter_value", help=filter_help) git_commit_help = ("check all changes in the given commit. " "Use 'commit_id..' to check all changes after commmit_id") parser.add_option("-g", "--git-diff", "--git-commit", metavar="COMMIT", dest="git_commit", help=git_commit_help,) diff_files_help = "diff the files passed on the command line rather than checking the style of every line" parser.add_option("--diff-files", action="store_true", dest="diff_files", default=False, help=diff_files_help) min_confidence_help = ("set the minimum confidence of style errors " "to report. Can be an integer 1-5, with 1 " "displaying all errors. Defaults to %default.") parser.add_option("-m", "--min-confidence", metavar="INT", type="int", dest="min_confidence", default=default_min_confidence, help=min_confidence_help) output_format_help = ('set the output format, which can be "emacs" ' 'or "vs7" (for Visual Studio). ' 'Defaults to "%default".') parser.add_option("-o", "--output-format", metavar="FORMAT", choices=["emacs", "vs7"], dest="output_format", default=default_output_format, help=output_format_help) verbose_help = "enable verbose logging." parser.add_option("-v", "--verbose", dest="is_verbose", default=False, action="store_true", help=verbose_help) # Override OptionParser's error() method so that option help will # also display when an error occurs. Normally, just the usage # string displays and not option help. parser.error = self._parse_error # Override OptionParser's print_help() method so that help output # does not render to the screen while running unit tests. print_help = parser.print_help parser.print_help = lambda file=stderr: print_help(file=file) return parser def _parse_error(self, error_message): """Print the help string and an error message, and exit.""" # The method format_help() includes both the usage string and # the flag options. help = self._parser.format_help() # Separate help from the error message with a single blank line. self.stderr_write(help + "\n") if error_message: _log.error(error_message) # Since we are using this method to replace/override the Python # module optparse's OptionParser.error() method, we match its # behavior and exit with status code 2. # # As additional background, Python documentation says-- # # "Unix programs generally use 2 for command line syntax errors # and 1 for all other kind of errors." # # (from http://docs.python.org/library/sys.html#sys.exit ) sys.exit(2) def _exit_with_categories(self): """Exit and print the style categories and default filter rules.""" self.stderr_write('\nAll categories:\n') for category in sorted(self._all_categories): self.stderr_write(' ' + category + '\n') self.stderr_write('\nDefault filter rules**:\n') for filter_rule in sorted(self._base_filter_rules): self.stderr_write(' ' + filter_rule + '\n') self.stderr_write('\n**The command always evaluates the above rules, ' 'and before any --filter flag.\n\n') sys.exit(0) def _parse_filter_flag(self, flag_value): """Parse the --filter flag, and return a list of filter rules. Args: flag_value: A string of comma-separated filter rules, for example "-whitespace,+whitespace/indent". """ filters = [] for uncleaned_filter in flag_value.split(','): filter = uncleaned_filter.strip() if not filter: continue filters.append(filter) return filters def parse(self, args): """Parse the command line arguments to check-webkit-style. Args: args: A list of command-line arguments as returned by sys.argv[1:]. Returns: A tuple of (paths, options) paths: The list of paths to check. options: A CommandOptionValues instance. """ (options, paths) = self._parser.parse_args(args=args) filter_value = options.filter_value git_commit = options.git_commit diff_files = options.diff_files is_verbose = options.is_verbose min_confidence = options.min_confidence output_format = options.output_format if filter_value is not None and not filter_value: # Then the user explicitly passed no filter, for # example "-f ''" or "--filter=". self._exit_with_categories() # Validate user-provided values. min_confidence = int(min_confidence) if (min_confidence < 1) or (min_confidence > 5): self._parse_error('option --min-confidence: invalid integer: ' '%s: value must be between 1 and 5' % min_confidence) if filter_value: filter_rules = self._parse_filter_flag(filter_value) else: filter_rules = [] try: validate_filter_rules(filter_rules, self._all_categories) except ValueError, err: self._parse_error(err) options = CommandOptionValues(filter_rules=filter_rules, git_commit=git_commit, diff_files=diff_files, is_verbose=is_verbose, min_confidence=min_confidence, output_format=output_format) return (paths, options)
bsd-3-clause
grilo/ansible-1
lib/ansible/modules/cloud/amazon/cloudformation.py
4
23240
#!/usr/bin/python # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type # upcoming features: # - Ted's multifile YAML concatenation # - changesets (and blocking/waiting for them) # - finish AWSRetry conversion # - move create/update code out of main # - unit tests ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'certified'} DOCUMENTATION = ''' --- module: cloudformation short_description: Create or delete an AWS CloudFormation stack description: - Launches or updates an AWS CloudFormation stack and waits for it complete. notes: - As of version 2.3, migrated to boto3 to enable new features. To match existing behavior, YAML parsing is done in the module, not given to AWS as YAML. This will change (in fact, it may change before 2.3 is out). version_added: "1.1" options: stack_name: description: - name of the cloudformation stack required: true disable_rollback: description: - If a stacks fails to form, rollback will remove the stack required: false default: "false" choices: [ "true", "false" ] template_parameters: description: - a list of hashes of all the template variables for the stack required: false default: {} state: description: - If state is "present", stack will be created. If state is "present" and if stack exists and template has changed, it will be updated. If state is "absent", stack will be removed. required: true template: description: - The local path of the cloudformation template. - This must be the full path to the file, relative to the working directory. If using roles this may look like "roles/cloudformation/files/cloudformation-example.json". - If 'state' is 'present' and the stack does not exist yet, either 'template' or 'template_url' must be specified (but not both). If 'state' is present, the stack does exist, and neither 'template' nor 'template_url' are specified, the previous template will be reused. required: false default: null notification_arns: description: - The Simple Notification Service (SNS) topic ARNs to publish stack related events. required: false default: null version_added: "2.0" stack_policy: description: - the path of the cloudformation stack policy. A policy cannot be removed once placed, but it can be modified. (for instance, [allow all updates](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html#d0e9051) required: false default: null version_added: "1.9" tags: description: - Dictionary of tags to associate with stack and its resources during stack creation. Can be updated later, updating tags removes previous entries. required: false default: null version_added: "1.4" template_url: description: - Location of file containing the template body. The URL must point to a template (max size 307,200 bytes) located in an S3 bucket in the same region as the stack. - If 'state' is 'present' and the stack does not exist yet, either 'template' or 'template_url' must be specified (but not both). If 'state' is present, the stack does exist, and neither 'template' nor 'template_url' are specified, the previous template will be reused. required: false version_added: "2.0" create_changeset: description: - "If stack already exists create a changeset instead of directly applying changes. See the AWS Change Sets docs U(http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html). WARNING: if the stack does not exist, it will be created without changeset. If the state is absent, the stack will be deleted immediately with no changeset." required: false default: false version_added: "2.4" changeset_name: description: - Name given to the changeset when creating a changeset, only used when create_changeset is true. By default a name prefixed with Ansible-STACKNAME is generated based on input parameters. See the AWS Change Sets docs U(http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html) required: false default: null version_added: "2.4" template_format: description: - (deprecated) For local templates, allows specification of json or yaml format. Templates are now passed raw to CloudFormation regardless of format. This parameter is ignored since Ansible 2.3. default: json choices: [ json, yaml ] required: false version_added: "2.0" role_arn: description: - The role that AWS CloudFormation assumes to create the stack. See the AWS CloudFormation Service Role docs U(http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-servicerole.html) required: false default: null version_added: "2.3" author: "James S. Martin (@jsmartin)" extends_documentation_fragment: - aws - ec2 requirements: [ botocore>=1.4.57 ] ''' EXAMPLES = ''' # Basic task example - name: launch ansible cloudformation example cloudformation: stack_name: "ansible-cloudformation" state: "present" region: "us-east-1" disable_rollback: true template: "files/cloudformation-example.json" template_parameters: KeyName: "jmartin" DiskType: "ephemeral" InstanceType: "m1.small" ClusterSize: 3 tags: Stack: "ansible-cloudformation" # Basic role example - name: launch ansible cloudformation example cloudformation: stack_name: "ansible-cloudformation" state: "present" region: "us-east-1" disable_rollback: true template: "roles/cloudformation/files/cloudformation-example.json" template_parameters: KeyName: "jmartin" DiskType: "ephemeral" InstanceType: "m1.small" ClusterSize: 3 tags: Stack: "ansible-cloudformation" # Removal example - name: tear down old deployment cloudformation: stack_name: "ansible-cloudformation-old" state: "absent" # Use a template from a URL - name: launch ansible cloudformation example cloudformation: stack_name: "ansible-cloudformation" state: present region: us-east-1 disable_rollback: true template_url: https://s3.amazonaws.com/my-bucket/cloudformation.template args: template_parameters: KeyName: jmartin DiskType: ephemeral InstanceType: m1.small ClusterSize: 3 tags: Stack: ansible-cloudformation # Use a template from a URL, and assume a role to execute - name: launch ansible cloudformation example with role assumption cloudformation: stack_name: "ansible-cloudformation" state: present region: us-east-1 disable_rollback: true template_url: https://s3.amazonaws.com/my-bucket/cloudformation.template role_arn: 'arn:aws:iam::123456789012:role/cloudformation-iam-role' args: template_parameters: KeyName: jmartin DiskType: ephemeral InstanceType: m1.small ClusterSize: 3 tags: Stack: ansible-cloudformation ''' RETURN = ''' events: type: list description: Most recent events in Cloudformation's event log. This may be from a previous run in some cases. returned: always sample: ["StackEvent AWS::CloudFormation::Stack stackname UPDATE_COMPLETE", "StackEvent AWS::CloudFormation::Stack stackname UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"] log: description: Debugging logs. Useful when modifying or finding an error. returned: always type: list sample: ["updating stack"] stack_resources: description: AWS stack resources and their status. List of dictionaries, one dict per resource. returned: state == present type: list sample: [ { "last_updated_time": "2016-10-11T19:40:14.979000+00:00", "logical_resource_id": "CFTestSg", "physical_resource_id": "cloudformation2-CFTestSg-16UQ4CYQ57O9F", "resource_type": "AWS::EC2::SecurityGroup", "status": "UPDATE_COMPLETE", "status_reason": null } ] stack_outputs: type: dict description: A key:value dictionary of all the stack outputs currently defined. If there are no stack outputs, it is an empty dictionary. returned: state == present sample: {"MySg": "AnsibleModuleTestYAML-CFTestSg-C8UVS567B6NS"} ''' # NOQA import json import time import traceback from hashlib import sha1 try: import boto3 import botocore HAS_BOTO3 = True except ImportError: HAS_BOTO3 = False import ansible.module_utils.ec2 # import a class, otherwise we'll use a fully qualified path from ansible.module_utils.ec2 import AWSRetry from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes def boto_exception(err): '''generic error message handler''' if hasattr(err, 'error_message'): error = err.error_message elif hasattr(err, 'message'): error = err.message + ' ' + str(err) + ' - ' + str(type(err)) else: error = '%s: %s' % (Exception, err) return error def get_stack_events(cfn, stack_name): '''This event data was never correct, it worked as a side effect. So the v2.3 format is different.''' ret = {'events':[], 'log':[]} try: events = cfn.describe_stack_events(StackName=stack_name) except (botocore.exceptions.ValidationError, botocore.exceptions.ClientError) as err: error_msg = boto_exception(err) if 'does not exist' in error_msg: # missing stack, don't bail. ret['log'].append('Stack does not exist.') return ret ret['log'].append('Unknown error: ' + str(error_msg)) return ret for e in events.get('StackEvents', []): eventline = 'StackEvent {ResourceType} {LogicalResourceId} {ResourceStatus}'.format(**e) ret['events'].append(eventline) if e['ResourceStatus'].endswith('FAILED'): failline = '{ResourceType} {LogicalResourceId} {ResourceStatus}: {ResourceStatusReason}'.format(**e) ret['log'].append(failline) return ret def create_stack(module, stack_params, cfn): if 'TemplateBody' not in stack_params and 'TemplateURL' not in stack_params: module.fail_json(msg="Either 'template' or 'template_url' is required when the stack does not exist.") # 'disablerollback' only applies on creation, not update. stack_params['DisableRollback'] = module.params['disable_rollback'] try: cfn.create_stack(**stack_params) result = stack_operation(cfn, stack_params['StackName'], 'CREATE') except Exception as err: error_msg = boto_exception(err) module.fail_json(msg="Failed to create stack {0}: {1}.".format(stack_params.get('StackName'), error_msg), exception=traceback.format_exc()) if not result: module.fail_json(msg="empty result") return result def list_changesets(cfn, stack_name): res = cfn.list_change_sets(StackName=stack_name) changesets = [] for cs in res['Summaries']: changesets.append(cs['ChangeSetName']) return changesets def create_changeset(module, stack_params, cfn): if 'TemplateBody' not in stack_params and 'TemplateURL' not in stack_params: module.fail_json(msg="Either 'template' or 'template_url' is required.") try: if not 'ChangeSetName' in stack_params: # Determine ChangeSetName using hash of parameters. json_params = json.dumps(stack_params, sort_keys=True) changeset_name = 'Ansible-' + stack_params['StackName'] + '-' + sha1(to_bytes(json_params, errors='surrogate_or_strict')).hexdigest() stack_params['ChangeSetName'] = changeset_name else: changeset_name = stack_params['ChangeSetName'] # Determine if this changeset already exists pending_changesets = list_changesets(cfn, stack_params['StackName']) if changeset_name in pending_changesets: warning = 'WARNING: '+str(len(pending_changesets))+' pending changeset(s) exist(s) for this stack!' result = dict(changed=False, output='ChangeSet ' + changeset_name + ' already exists.', warnings=[warning]) else: cs = cfn.create_change_set(**stack_params) result = stack_operation(cfn, stack_params['StackName'], 'UPDATE') result['warnings'] = [('Created changeset named ' + changeset_name + ' for stack ' + stack_params['StackName']), ('You can execute it using: aws cloudformation execute-change-set --change-set-name ' + cs['Id']), ('NOTE that dependencies on this stack might fail due to pending changes!')] except Exception as err: error_msg = boto_exception(err) if 'No updates are to be performed.' in error_msg: result = dict(changed=False, output='Stack is already up-to-date.') else: module.fail_json(msg="Failed to create change set: {0}".format(error_msg), exception=traceback.format_exc()) if not result: module.fail_json(msg="empty result") return result def update_stack(module, stack_params, cfn): if 'TemplateBody' not in stack_params and 'TemplateURL' not in stack_params: stack_params['UsePreviousTemplate'] = True # if the state is present and the stack already exists, we try to update it. # AWS will tell us if the stack template and parameters are the same and # don't need to be updated. try: cfn.update_stack(**stack_params) result = stack_operation(cfn, stack_params['StackName'], 'UPDATE') except Exception as err: error_msg = boto_exception(err) if 'No updates are to be performed.' in error_msg: result = dict(changed=False, output='Stack is already up-to-date.') else: module.fail_json(msg="Failed to update stack {0}: {1}".format(stack_params.get('StackName'), error_msg), exception=traceback.format_exc()) if not result: module.fail_json(msg="empty result") return result def stack_operation(cfn, stack_name, operation): '''gets the status of a stack while it is created/updated/deleted''' existed = [] while True: try: stack = get_stack_facts(cfn, stack_name) existed.append('yes') except: # If the stack previously existed, and now can't be found then it's # been deleted successfully. if 'yes' in existed or operation == 'DELETE': # stacks may delete fast, look in a few ways. ret = get_stack_events(cfn, stack_name) ret.update({'changed': True, 'output': 'Stack Deleted'}) return ret else: return {'changed': True, 'failed': True, 'output': 'Stack Not Found', 'exception': traceback.format_exc()} ret = get_stack_events(cfn, stack_name) if not stack: if 'yes' in existed or operation == 'DELETE': # stacks may delete fast, look in a few ways. ret = get_stack_events(cfn, stack_name) ret.update({'changed': True, 'output': 'Stack Deleted'}) return ret else: ret.update({'changed': False, 'failed': True, 'output' : 'Stack not found.'}) return ret # it covers ROLLBACK_COMPLETE and UPDATE_ROLLBACK_COMPLETE # Possible states: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-describing-stacks.html#w1ab2c15c17c21c13 elif stack['StackStatus'].endswith('ROLLBACK_COMPLETE'): ret.update({'changed': True, 'failed': True, 'output': 'Problem with %s. Rollback complete' % operation}) return ret # note the ordering of ROLLBACK_COMPLETE and COMPLETE, because otherwise COMPLETE will match both cases. elif stack['StackStatus'].endswith('_COMPLETE'): ret.update({'changed': True, 'output' : 'Stack %s complete' % operation }) return ret elif stack['StackStatus'].endswith('_ROLLBACK_FAILED'): ret.update({'changed': True, 'failed': True, 'output': 'Stack %s rollback failed' % operation}) return ret # note the ordering of ROLLBACK_FAILED and FAILED, because otherwise FAILED will match both cases. elif stack['StackStatus'].endswith('_FAILED'): ret.update({'changed': True, 'failed': True, 'output': 'Stack %s failed' % operation}) return ret else: # this can loop forever :/ time.sleep(5) return {'failed': True, 'output':'Failed for unknown reasons.'} @AWSRetry.backoff(tries=3, delay=5) def describe_stacks(cfn, stack_name): return cfn.describe_stacks(StackName=stack_name) def get_stack_facts(cfn, stack_name): try: stack_response = describe_stacks(cfn, stack_name) stack_info = stack_response['Stacks'][0] #except AmazonCloudFormationException as e: except (botocore.exceptions.ValidationError,botocore.exceptions.ClientError) as err: error_msg = boto_exception(err) if 'does not exist' in error_msg: # missing stack, don't bail. return None # other error, bail. raise err if stack_response and stack_response.get('Stacks', None): stacks = stack_response['Stacks'] if len(stacks): stack_info = stacks[0] return stack_info def main(): argument_spec = ansible.module_utils.ec2.ec2_argument_spec() argument_spec.update(dict( stack_name=dict(required=True), template_parameters=dict(required=False, type='dict', default={}), state=dict(default='present', choices=['present', 'absent']), template=dict(default=None, required=False, type='path'), notification_arns=dict(default=None, required=False), stack_policy=dict(default=None, required=False), disable_rollback=dict(default=False, type='bool'), template_url=dict(default=None, required=False), template_format=dict(default=None, choices=['json', 'yaml'], required=False), create_changeset=dict(default=False, type='bool'), changeset_name=dict(default=None, required=False), role_arn=dict(default=None, required=False), tags=dict(default=None, type='dict') ) ) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=[['template_url', 'template']], ) if not HAS_BOTO3: module.fail_json(msg='boto3 and botocore are required for this module') # collect the parameters that are passed to boto3. Keeps us from having so many scalars floating around. stack_params = { 'Capabilities': ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM'], } state = module.params['state'] stack_params['StackName'] = module.params['stack_name'] if module.params['template'] is not None: stack_params['TemplateBody'] = open(module.params['template'], 'r').read() elif module.params['template_url'] is not None: stack_params['TemplateURL'] = module.params['template_url'] if module.params.get('notification_arns'): stack_params['NotificationARNs'] = module.params['notification_arns'].split(',') else: stack_params['NotificationARNs'] = [] if module.params['stack_policy'] is not None: stack_params['StackPolicyBody'] = open(module.params['stack_policy'], 'r').read() if module.params['changeset_name'] is not None: stack_params['ChangeSetName'] = module.params['changeset_name'] template_parameters = module.params['template_parameters'] stack_params['Parameters'] = [{'ParameterKey':k, 'ParameterValue':str(v)} for k, v in template_parameters.items()] if isinstance(module.params.get('tags'), dict): stack_params['Tags'] = ansible.module_utils.ec2.ansible_dict_to_boto3_tag_list(module.params['tags']) if module.params.get('role_arn'): stack_params['RoleARN'] = module.params['role_arn'] result = {} try: region, ec2_url, aws_connect_kwargs = ansible.module_utils.ec2.get_aws_connection_info(module, boto3=True) cfn = ansible.module_utils.ec2.boto3_conn(module, conn_type='client', resource='cloudformation', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoCredentialsError as e: module.fail_json(msg=boto_exception(e)) stack_info = get_stack_facts(cfn, stack_params['StackName']) if state == 'present': if not stack_info: result = create_stack(module, stack_params, cfn) elif module.params.get('create_changeset'): result = create_changeset(module, stack_params, cfn) else: result = update_stack(module, stack_params, cfn) # format the stack output stack = get_stack_facts(cfn, stack_params['StackName']) if result.get('stack_outputs') is None: # always define stack_outputs, but it may be empty result['stack_outputs'] = {} for output in stack.get('Outputs', []): result['stack_outputs'][output['OutputKey']] = output['OutputValue'] stack_resources = [] reslist = cfn.list_stack_resources(StackName=stack_params['StackName']) for res in reslist.get('StackResourceSummaries', []): stack_resources.append({ "logical_resource_id": res['LogicalResourceId'], "physical_resource_id": res.get('PhysicalResourceId', ''), "resource_type": res['ResourceType'], "last_updated_time": res['LastUpdatedTimestamp'], "status": res['ResourceStatus'], "status_reason": res.get('ResourceStatusReason') # can be blank, apparently }) result['stack_resources'] = stack_resources elif state == 'absent': # absent state is different because of the way delete_stack works. # problem is it it doesn't give an error if stack isn't found # so must describe the stack first try: stack = get_stack_facts(cfn, stack_params['StackName']) if not stack: result = {'changed': False, 'output': 'Stack not found.'} else: cfn.delete_stack(StackName=stack_params['StackName']) result = stack_operation(cfn, stack_params['StackName'], 'DELETE') except Exception as err: module.fail_json(msg=boto_exception(err), exception=traceback.format_exc()) if module.params['template_format'] is not None: result['warnings'] = [('Argument `template_format` is deprecated ' 'since Ansible 2.3, JSON and YAML templates are now passed ' 'directly to the CloudFormation API.')] module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0