<commit_before># -*- coding: utf-8 -*-
#
# LISA documentation build configuration file, created by
# sphinx-quickstart on Tue Dec 13 14:20:00 2016.
#
# 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 logging
import os
import re
import subprocess
import sys
import unittest

from docutils import nodes
from sphinx.util.docfields import TypedField
from sphinx import addnodes

# This shouldn't be needed, as using a virtualenv + setup.py should set up the
# sys.path correctly. However that seems to be half broken on ReadTheDocs, so
# manually set it here
sys.path.insert(0, os.path.abspath('../'))

# Import our packages after modifying sys.path
import lisa
from lisa.doc.helpers import (
    autodoc_process_test_method, autodoc_process_analysis_events
)

# This ugly hack is required because by default TestCase.__module__ is
# equal to 'case', so sphinx replaces all of our TestCase uses to
# unittest.case.TestCase, which doesn't exist in the doc.
for name, obj in vars(unittest).items():
    try:
        m = obj.__module__
        obj.__module__ = 'unittest' if m == 'unittest.case' else m
    except Exception: pass

# This is a hack to prevent :ivar: docs from attempting to create a reference
# Credit goes to https://stackoverflow.com/a/41184353/5096023
def patched_make_field(self, types, domain, items, env=None):
    # type: (List, unicode, Tuple) -> nodes.field
    def handle_item(fieldarg, content):
        par = nodes.paragraph()
        par += addnodes.literal_strong('', fieldarg)  # Patch: this line added
        #par.extend(self.make_xrefs(self.rolename, domain, fieldarg,
        #                           addnodes.literal_strong))
        if fieldarg in types:
            par += nodes.Text(' (')
            # NOTE: using .pop() here to prevent a single type node to be
            # inserted twice into the doctree, which leads to
            # inconsistencies later when references are resolved
            fieldtype = types.pop(fieldarg)
            if len(fieldtype) == 1 and isinstance(fieldtype[0], nodes.Text):
                typename = u''.join(n.astext() for n in fieldtype)
                par.extend(self.make_xrefs(self.typerolename, domain, typename,
                                           addnodes.literal_emphasis))
            else:
                par += fieldtype
            par += nodes.Text(')')
        par += nodes.Text(' -- ')
        par += content
        return par

    fieldname = nodes.field_name('', self.label)
    if len(items) == 1 and self.can_collapse:
        fieldarg, content = items[0]
        bodynode = handle_item(fieldarg, content)
    else:
        bodynode = self.list_type()
        for fieldarg, content in items:
            bodynode += nodes.list_item('', handle_item(fieldarg, content))
    fieldbody = nodes.field_body('', bodynode)
    return nodes.field('', fieldname, fieldbody)

TypedField.make_field = patched_make_field

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.imgmath',
    'sphinx.ext.viewcode',
    'sphinx.ext.inheritance_diagram',
    'sphinxcontrib.plantuml',
]

# 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'LISA'
copyright = u'2017, ARM-Software'

# 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.
#
try:
    git_description = subprocess.check_output(
        ['git', 'describe', '--tags', '--match=v??.??'])
    version = re.match('v([0-9][0-9]\.[0-9][0-9]).*', git_description).group(1)
except Exception as e:
    logging.info("Couldn't set project version from git: {}".format(e))
    version = lisa.__version__

version = str(version)
release = version

# 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 = 'sphinx_rtd_theme'

# 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 for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any 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 = 'LISAdoc'

# -- 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 = [
  ('index', 'LISA.tex', u'LISA Documentation',
   u'ARM-Software', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'lisa', u'LISA Documentation',
     [u'ARM-Software'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'LISA', u'LISA Documentation',
   u'ARM-Software', 'LISA', '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

intersphinx_mapping = {
    'python' : ('https://docs.python.org/3', None),
    'pandas' : ('https://pandas.pydata.org/pandas-docs/stable/', None),
    'matplotlib' : ('https://matplotlib.org', None),
    'numpy': ('http://docs.scipy.org/doc/numpy', None),
    # XXX: Doesn't seem to work, might be due to how devlib doc is generated
    'wa' : ('https://devlib.readthedocs.io/en/latest/', None),
    'trappy' : ('https://pythonhosted.org/TRAPpy', None),
    'bart' :   ('https://pythonhosted.org/bart-py/', None),
    'wa' : ('https://workload-automation.readthedocs.io/en/latest/', None),
}

#
# Fix autodoc
#

# Include __init__ docstrings (obviously)
autoclass_content = 'both'

autodoc_member_order = 'bysource'

autodoc_default_options = {
    'show-inheritance' : '', # Show parent class
    'undoc-members' : '',    # Show members even if they don't have docstrings
}
autodoc_inherit_docstrings = True

def setup(app):
    app.connect('autodoc-process-docstring', autodoc_process_test_method)
    app.connect('autodoc-process-docstring', autodoc_process_analysis_events)

# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab:
<commit_msg>doc: update intersphinx inventory numpy URL<commit_after># -*- coding: utf-8 -*-
#
# LISA documentation build configuration file, created by
# sphinx-quickstart on Tue Dec 13 14:20:00 2016.
#
# 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 logging
import os
import re
import subprocess
import sys
import unittest

from docutils import nodes
from sphinx.util.docfields import TypedField
from sphinx import addnodes

# This shouldn't be needed, as using a virtualenv + setup.py should set up the
# sys.path correctly. However that seems to be half broken on ReadTheDocs, so
# manually set it here
sys.path.insert(0, os.path.abspath('../'))

# Import our packages after modifying sys.path
import lisa
from lisa.doc.helpers import (
    autodoc_process_test_method, autodoc_process_analysis_events
)

# This ugly hack is required because by default TestCase.__module__ is
# equal to 'case', so sphinx replaces all of our TestCase uses to
# unittest.case.TestCase, which doesn't exist in the doc.
for name, obj in vars(unittest).items():
    try:
        m = obj.__module__
        obj.__module__ = 'unittest' if m == 'unittest.case' else m
    except Exception: pass

# This is a hack to prevent :ivar: docs from attempting to create a reference
# Credit goes to https://stackoverflow.com/a/41184353/5096023
def patched_make_field(self, types, domain, items, env=None):
    # type: (List, unicode, Tuple) -> nodes.field
    def handle_item(fieldarg, content):
        par = nodes.paragraph()
        par += addnodes.literal_strong('', fieldarg)  # Patch: this line added
        #par.extend(self.make_xrefs(self.rolename, domain, fieldarg,
        #                           addnodes.literal_strong))
        if fieldarg in types:
            par += nodes.Text(' (')
            # NOTE: using .pop() here to prevent a single type node to be
            # inserted twice into the doctree, which leads to
            # inconsistencies later when references are resolved
            fieldtype = types.pop(fieldarg)
            if len(fieldtype) == 1 and isinstance(fieldtype[0], nodes.Text):
                typename = u''.join(n.astext() for n in fieldtype)
                par.extend(self.make_xrefs(self.typerolename, domain, typename,
                                           addnodes.literal_emphasis))
            else:
                par += fieldtype
            par += nodes.Text(')')
        par += nodes.Text(' -- ')
        par += content
        return par

    fieldname = nodes.field_name('', self.label)
    if len(items) == 1 and self.can_collapse:
        fieldarg, content = items[0]
        bodynode = handle_item(fieldarg, content)
    else:
        bodynode = self.list_type()
        for fieldarg, content in items:
            bodynode += nodes.list_item('', handle_item(fieldarg, content))
    fieldbody = nodes.field_body('', bodynode)
    return nodes.field('', fieldname, fieldbody)

TypedField.make_field = patched_make_field

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.imgmath',
    'sphinx.ext.viewcode',
    'sphinx.ext.inheritance_diagram',
    'sphinxcontrib.plantuml',
]

# 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'LISA'
copyright = u'2017, ARM-Software'

# 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.
#
try:
    git_description = subprocess.check_output(
        ['git', 'describe', '--tags', '--match=v??.??'])
    version = re.match('v([0-9][0-9]\.[0-9][0-9]).*', git_description).group(1)
except Exception as e:
    logging.info("Couldn't set project version from git: {}".format(e))
    version = lisa.__version__

version = str(version)
release = version

# 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 = 'sphinx_rtd_theme'

# 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 for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any 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 = 'LISAdoc'

# -- 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 = [
  ('index', 'LISA.tex', u'LISA Documentation',
   u'ARM-Software', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'lisa', u'LISA Documentation',
     [u'ARM-Software'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'LISA', u'LISA Documentation',
   u'ARM-Software', 'LISA', '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

intersphinx_mapping = {
    'python' : ('https://docs.python.org/3', None),
    'pandas' : ('https://pandas.pydata.org/pandas-docs/stable/', None),
    'matplotlib' : ('https://matplotlib.org', None),
    'numpy': ('https://docs.scipy.org/doc/numpy', None),
    # XXX: Doesn't seem to work, might be due to how devlib doc is generated
    'wa' : ('https://devlib.readthedocs.io/en/latest/', None),
    'trappy' : ('https://pythonhosted.org/TRAPpy', None),
    'bart' :   ('https://pythonhosted.org/bart-py/', None),
    'wa' : ('https://workload-automation.readthedocs.io/en/latest/', None),
}

#
# Fix autodoc
#

# Include __init__ docstrings (obviously)
autoclass_content = 'both'

autodoc_member_order = 'bysource'

autodoc_default_options = {
    'show-inheritance' : '', # Show parent class
    'undoc-members' : '',    # Show members even if they don't have docstrings
}
autodoc_inherit_docstrings = True

def setup(app):
    app.connect('autodoc-process-docstring', autodoc_process_test_method)
    app.connect('autodoc-process-docstring', autodoc_process_analysis_events)

# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab:
<|endoftext|>


<commit_before>#coding=utf-8
from flask import Flask, request, url_for
from flask.ext.restful import fields, reqparse, marshal_with
from instance_manager import NavitiaManager, RegionNotFound
from protobuf_to_dict import protobuf_to_dict
from fields import stop_point, stop_area, route, line, physical_mode,\
                   commercial_mode, company, network, pagination, place,\
                   PbField, stop_date_time, enum_type, NonNullList, NonNullNested,\
                   display_informations_vj,additional_informations_vj,error

from interfaces.parsers import option_value
from ResourceUri import ResourceUri, add_notes
import datetime
from functools import wraps
from make_links import add_id_links, clean_links
from errors import ManageError
from interfaces.argument import ArgumentDoc
from interfaces.parsers import depth_argument
from operator import itemgetter
from datetime import datetime, timedelta
import sys
from copy import copy
from datetime import datetime

class SectionLinks(fields.Raw):
    def __init__(self, **kwargs):
        super(SectionLinks, self).__init__(**kwargs)

    def output(self, key, obj):
        links = None
        try:
            if obj.HasField("uris"):
                links = obj.uris.ListFields()
        except ValueError:
            return None
        response = []
        if links:
            for type_, value in links:
                response.append({"type": type_.name, "id": value})
        return response

class GeoJson(fields.Raw):
    def __init__(self, **kwargs):
        super(GeoJson, self).__init__(**kwargs)

    def output(self, key, obj):
        coords = []
        length = 0
        enum = obj.DESCRIPTOR.fields_by_name['type'].enum_type.values_by_name
        if obj.type == enum['STREET_NETWORK'].number:
            try:
                if obj.HasField("street_network"):
                    coords = obj.street_network.coordinates
                    length = obj.street_network.length
                else:
                    return None
            except ValueError:
                return None
        elif obj.type == enum['PUBLIC_TRANSPORT'].number:
            coords = [sdt.stop_point.coord for sdt in obj.stop_date_times]
        elif obj.type == enum['TRANSFER'].number:
            coords.append(obj.origin.stop_point.coord)
            coords.append(obj.destination.stop_point.coord)
        else:
            return None

        response = {
                "type" : "LineString",
                "coordinates" : [],
                "properties" : [{
                    "length" : length
                    }]
        }
        for coord in coords:
            response["coordinates"].append([coord.lon, coord.lat])
        return response

class section_type(enum_type):
    def output(self, key, obj):
        try:
            if obj.HasField("pt_display_informations"):
                infos = obj.pt_display_informations
                if infos.HasField("vehicle_journey_type"):
                    infos_desc = infos.DESCRIPTOR
                    odt_enum = infos_desc.fields_by_name['vehicle_journey_type'].enum_type
                    if infos.vehicle_journey_type != odt_enum.values_by_name['regular'].number:
                        return "on_demand_transport"
        except ValueError:
            pass
        return super(section_type, self).output(key, obj)

class section_place(PbField):
    def output(self, key, obj):
        enum_t = obj.DESCRIPTOR.fields_by_name['type'].enum_type.values_by_name
        if obj.type == enum_t['WAITING'].number:
            return None
        else:
            return super(PbField, self).output(key, obj)

section = {
    "type": section_type(attribute="type"),
    "mode" : enum_type(attribute="street_network.mode"),
    "duration": fields.Integer(),
    "from" : section_place(place, attribute="origin"),
    "to": section_place(place, attribute="destination"),
    "links" : SectionLinks(attribute="uris"),
    "display_informations" : display_informations_vj(),
    "additional_informations" : additional_informations_vj(),
    "geojson" : GeoJson(),
    "path" : NonNullList(NonNullNested({"length":fields.Integer(),
                                        "name":fields.String()}),
                         attribute="street_network.path_items"),
    "transfer_type" : enum_type(),
    "stop_date_times" : NonNullList(NonNullNested(stop_date_time)),
    "departure_date_time" : fields.String(attribute="begin_date_time"),
    "arrival_date_time" : fields.String(attribute="end_date_time")
}

journey = {
    'duration' : fields.Integer(),
    'nb_transfers' : fields.Integer(),
    'departure_date_time' : fields.String(),
    'arrival_date_time' : fields.String(),
    'requested_date_time' : fields.String(),
    'sections' : NonNullList(NonNullNested(section)),
    'from' : PbField(place, attribute='origin'),
    'to' : PbField(place, attribute='destination'),
    'type' : fields.String()
}

journeys = {
    "journeys" : NonNullList(NonNullNested(journey)),
    "error": PbField(error,attribute='error')
}

def dt_represents(value):
    if value == "arrival":
        return False
    elif value == "departure":
        return True
    else:
        raise ValueError("Unable to parse datetime_represents")

class add_journey_href(object):
    def __call__(self, f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            objects = f(*args, **kwargs)
            if objects[1] != 200:
                return objects
            if not "journeys" in objects[0].keys():
                return objects
            if "region" in kwargs.keys():
                del kwargs["region"]
            if "uri" in kwargs.keys():
                kwargs["from"] = kwargs["uri"].split("/")[-1]
                del kwargs["uri"]
            if "lon" in kwargs.keys() and "lat" in kwargs.keys():
                if not "from" in kwargs.keys():
                    kwargs["from"] = kwargs["lon"] + ';' + kwargs["lat"]
                del kwargs["lon"]
                del kwargs["lat"]
            kwargs["_external"] = True
            for journey in objects[0]['journeys']:
                if not "sections" in journey.keys():
                    kwargs["datetime"] = journey["requested_date_time"]
                    kwargs["to"] = journey["to"]["id"]
                    journey['links'] = [
                            {
                                "type" : "journeys",
                                "href" : url_for("v1.journeys", **kwargs),
                                "templated" : False
                                }
                    ]
            return objects
        return wrapper

class add_journey_pagination(object):
    def __call__(self, f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            objects = f(*args, **kwargs)
            if objects[1] != 200:
                return objects
            datetime_before, datetime_after = self.extremes(objects[0])
            if not datetime_before is None and not datetime_after is None:
                if not "links" in objects[0]:
                    objects[0]["links"] = []

                args = request.args.copy()
                args["datetime"] = datetime_before.strftime("%Y%m%dT%H%M%S")
                args["datetime_represents"] = "arrival"
                objects[0]["links"].append({
                    "href" : url_for("v1.journeys", _external=True, **args),
                    "templated" : False,
                    "type" : "prev"
                    })
                args["datetime"] = datetime_after.strftime("%Y%m%dT%H%M%S")
                args["datetime_represents"] = "departure"
                objects[0]["links"].append({
                    "href" : url_for("v1.journeys", _external=True, **args),
                    "templated" : False,
                    "type" : "next"
                    })
            return objects
        return wrapper

    def extremes(self, resp):
        datetime_before = None
        datetime_after = None
        try:
            list_journeys = [journey for journey in resp['journeys']\
                                if 'arrival_date_time' in journey.keys() and\
                                    journey['arrival_date_time'] != '']
            asap_journey = min(list_journeys, key=itemgetter('arrival_date_time'))
        except:
            return (None, None)
        if asap_journey['arrival_date_time'] and ['asap_journey.departure_date_time']:
            minute = timedelta(minutes = 1)
            datetime_after = datetime.strptime(asap_journey['departure_date_time'], "%Y%m%dT%H%M%S") + minute
            datetime_before = datetime.strptime(asap_journey['arrival_date_time'], "%Y%m%dT%H%M%S") - minute

        return (datetime_before, datetime_after)

class Journeys(ResourceUri):
    def __init__(self):
        ResourceUri.__init__(self)
        modes = ["walking", "car", "bike", "br"]
        types = ["all", "rapid"]
        self.parsers = {}
        self.parsers["get"] = reqparse.RequestParser(argument_class=ArgumentDoc)
        parser_get = self.parsers["get"]
        parser_get.add_argument("from", type=str, dest="origin")
        parser_get.add_argument("to", type=str, dest="destination")
        parser_get.add_argument("datetime", type=str)
        parser_get.add_argument("datetime_represents", dest="clockwise",
                           type=dt_represents, default=True)
        parser_get.add_argument("max_nb_transfers", type=int, default=10,
                           dest="max_transfers")
        parser_get.add_argument("first_section_mode",
                           type=option_value(modes),
                           default="walking",
                           dest="origin_mode")
        parser_get.add_argument("last_section_mode",
                           type=option_value(modes),
                           default="walking",
                           dest="destination_mode")
        parser_get.add_argument("walking_speed", type=float, default=1.68)
        parser_get.add_argument("walking_distance", type=int, default=1000)
        parser_get.add_argument("bike_speed", type=float, default=8.8)
        parser_get.add_argument("bike_distance", type=int, default=5000)
        parser_get.add_argument("br_speed", type=float, default=8.8,)
        parser_get.add_argument("br_distance", type=int, default=5000)
        parser_get.add_argument("car_speed", type=float, default=16.8)
        parser_get.add_argument("car_distance", type=int, default=15000)
        parser_get.add_argument("forbidden_uris[]", type=str, action="append")
        parser_get.add_argument("count", type=int)
        parser_get.add_argument("type", type=option_value(types), default="all")
#a supprimer
        parser_get.add_argument("max_duration", type=int, default=36000)
        self.method_decorators.append(add_notes(self))

    @clean_links()
    @add_id_links()
    @add_journey_pagination()
    @add_journey_href()
    @marshal_with(journeys)
    @ManageError()
    def get(self, region=None, lon=None, lat=None, uri=None):
        args = self.parsers["get"].parse_args()
        #TODO : Changer le protobuff pour que ce soit propre
        args["destination_mode"] = "vls" if args["destination_mode"] == "br" else args["destination_mode"]
        args["origin_mode"] = "vls" if args["origin_mode"] == "br" else args["origin_mode"]
        if not region is None or (not lon is None and not lat is None):
            self.region = NavitiaManager().get_region(region, lon, lat)
            if uri:
                objects = uri.split("/")
                if objects and len(objects) % 2 == 0:
                    args["origin"] = objects[-1]
                else:
                    return {"error" : "Unable to compute journeys from this \
                                       object"}, 503
        else:
            if "origin" in args.keys():
                self.region = NavitiaManager().key_of_id(args["origin"])
                args["origin"] = self.transform_id(args["origin"])
            elif "destination" in args.keys():
                self.region = NavitiaManager().key_of_id(args["destination"])
            if "destination" in args.keys():
                args["destination"] = self.transform_id(args["destination"])
            else:
                raise RegionNotFound("")
        if not args["datetime"]:
            args["datetime"] = datetime.now().strftime("%Y%m%dT1337")
        api = None
        if "destination" in args.keys() and args["destination"]:
            api = "journeys"
        else:
            api = "isochrone"
        response = NavitiaManager().dispatch(args, self.region, api)
        return response

    def transform_id(self, id):
        splitted_coord = id.split(";")
        splitted_address = id.split(":")
        if len(splitted_coord) == 2:
            return "coord:"+id.replace(";", ":")
        if len(splitted_address) >=3 and splitted_address[0] == 'address':
            del splitted_address[1]
            return ':'.join(splitted_address)
        return id
<commit_msg>Jormungandr : Transformation des id dans journeys<commit_after>#coding=utf-8
from flask import Flask, request, url_for
from flask.ext.restful import fields, reqparse, marshal_with
from instance_manager import NavitiaManager, RegionNotFound
from protobuf_to_dict import protobuf_to_dict
from fields import stop_point, stop_area, route, line, physical_mode,\
                   commercial_mode, company, network, pagination, place,\
                   PbField, stop_date_time, enum_type, NonNullList, NonNullNested,\
                   display_informations_vj,additional_informations_vj,error

from interfaces.parsers import option_value
from ResourceUri import ResourceUri, add_notes
import datetime
from functools import wraps
from make_links import add_id_links, clean_links
from errors import ManageError
from interfaces.argument import ArgumentDoc
from interfaces.parsers import depth_argument
from operator import itemgetter
from datetime import datetime, timedelta
import sys
from copy import copy
from datetime import datetime

class SectionLinks(fields.Raw):
    def __init__(self, **kwargs):
        super(SectionLinks, self).__init__(**kwargs)

    def output(self, key, obj):
        links = None
        try:
            if obj.HasField("uris"):
                links = obj.uris.ListFields()
        except ValueError:
            return None
        response = []
        if links:
            for type_, value in links:
                response.append({"type": type_.name, "id": value})
        return response

class GeoJson(fields.Raw):
    def __init__(self, **kwargs):
        super(GeoJson, self).__init__(**kwargs)

    def output(self, key, obj):
        coords = []
        length = 0
        enum = obj.DESCRIPTOR.fields_by_name['type'].enum_type.values_by_name
        if obj.type == enum['STREET_NETWORK'].number:
            try:
                if obj.HasField("street_network"):
                    coords = obj.street_network.coordinates
                    length = obj.street_network.length
                else:
                    return None
            except ValueError:
                return None
        elif obj.type == enum['PUBLIC_TRANSPORT'].number:
            coords = [sdt.stop_point.coord for sdt in obj.stop_date_times]
        elif obj.type == enum['TRANSFER'].number:
            coords.append(obj.origin.stop_point.coord)
            coords.append(obj.destination.stop_point.coord)
        else:
            return None

        response = {
                "type" : "LineString",
                "coordinates" : [],
                "properties" : [{
                    "length" : length
                    }]
        }
        for coord in coords:
            response["coordinates"].append([coord.lon, coord.lat])
        return response

class section_type(enum_type):
    def output(self, key, obj):
        try:
            if obj.HasField("pt_display_informations"):
                infos = obj.pt_display_informations
                if infos.HasField("vehicle_journey_type"):
                    infos_desc = infos.DESCRIPTOR
                    odt_enum = infos_desc.fields_by_name['vehicle_journey_type'].enum_type
                    if infos.vehicle_journey_type != odt_enum.values_by_name['regular'].number:
                        return "on_demand_transport"
        except ValueError:
            pass
        return super(section_type, self).output(key, obj)

class section_place(PbField):
    def output(self, key, obj):
        enum_t = obj.DESCRIPTOR.fields_by_name['type'].enum_type.values_by_name
        if obj.type == enum_t['WAITING'].number:
            return None
        else:
            return super(PbField, self).output(key, obj)

section = {
    "type": section_type(attribute="type"),
    "mode" : enum_type(attribute="street_network.mode"),
    "duration": fields.Integer(),
    "from" : section_place(place, attribute="origin"),
    "to": section_place(place, attribute="destination"),
    "links" : SectionLinks(attribute="uris"),
    "display_informations" : display_informations_vj(),
    "additional_informations" : additional_informations_vj(),
    "geojson" : GeoJson(),
    "path" : NonNullList(NonNullNested({"length":fields.Integer(),
                                        "name":fields.String()}),
                         attribute="street_network.path_items"),
    "transfer_type" : enum_type(),
    "stop_date_times" : NonNullList(NonNullNested(stop_date_time)),
    "departure_date_time" : fields.String(attribute="begin_date_time"),
    "arrival_date_time" : fields.String(attribute="end_date_time")
}

journey = {
    'duration' : fields.Integer(),
    'nb_transfers' : fields.Integer(),
    'departure_date_time' : fields.String(),
    'arrival_date_time' : fields.String(),
    'requested_date_time' : fields.String(),
    'sections' : NonNullList(NonNullNested(section)),
    'from' : PbField(place, attribute='origin'),
    'to' : PbField(place, attribute='destination'),
    'type' : fields.String()
}

journeys = {
    "journeys" : NonNullList(NonNullNested(journey)),
    "error": PbField(error,attribute='error')
}

def dt_represents(value):
    if value == "arrival":
        return False
    elif value == "departure":
        return True
    else:
        raise ValueError("Unable to parse datetime_represents")

class add_journey_href(object):
    def __call__(self, f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            objects = f(*args, **kwargs)
            if objects[1] != 200:
                return objects
            if not "journeys" in objects[0].keys():
                return objects
            if "region" in kwargs.keys():
                del kwargs["region"]
            if "uri" in kwargs.keys():
                kwargs["from"] = kwargs["uri"].split("/")[-1]
                del kwargs["uri"]
            if "lon" in kwargs.keys() and "lat" in kwargs.keys():
                if not "from" in kwargs.keys():
                    kwargs["from"] = kwargs["lon"] + ';' + kwargs["lat"]
                del kwargs["lon"]
                del kwargs["lat"]
            kwargs["_external"] = True
            for journey in objects[0]['journeys']:
                if not "sections" in journey.keys():
                    kwargs["datetime"] = journey["requested_date_time"]
                    kwargs["to"] = journey["to"]["id"]
                    journey['links'] = [
                            {
                                "type" : "journeys",
                                "href" : url_for("v1.journeys", **kwargs),
                                "templated" : False
                                }
                    ]
            return objects
        return wrapper

class add_journey_pagination(object):
    def __call__(self, f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            objects = f(*args, **kwargs)
            if objects[1] != 200:
                return objects
            datetime_before, datetime_after = self.extremes(objects[0])
            if not datetime_before is None and not datetime_after is None:
                if not "links" in objects[0]:
                    objects[0]["links"] = []

                args = request.args.copy()
                args["datetime"] = datetime_before.strftime("%Y%m%dT%H%M%S")
                args["datetime_represents"] = "arrival"
                objects[0]["links"].append({
                    "href" : url_for("v1.journeys", _external=True, **args),
                    "templated" : False,
                    "type" : "prev"
                    })
                args["datetime"] = datetime_after.strftime("%Y%m%dT%H%M%S")
                args["datetime_represents"] = "departure"
                objects[0]["links"].append({
                    "href" : url_for("v1.journeys", _external=True, **args),
                    "templated" : False,
                    "type" : "next"
                    })
            return objects
        return wrapper

    def extremes(self, resp):
        datetime_before = None
        datetime_after = None
        try:
            list_journeys = [journey for journey in resp['journeys']\
                                if 'arrival_date_time' in journey.keys() and\
                                    journey['arrival_date_time'] != '']
            asap_journey = min(list_journeys, key=itemgetter('arrival_date_time'))
        except:
            return (None, None)
        if asap_journey['arrival_date_time'] and ['asap_journey.departure_date_time']:
            minute = timedelta(minutes = 1)
            datetime_after = datetime.strptime(asap_journey['departure_date_time'], "%Y%m%dT%H%M%S") + minute
            datetime_before = datetime.strptime(asap_journey['arrival_date_time'], "%Y%m%dT%H%M%S") - minute

        return (datetime_before, datetime_after)

class Journeys(ResourceUri):
    def __init__(self):
        ResourceUri.__init__(self)
        modes = ["walking", "car", "bike", "br"]
        types = ["all", "rapid"]
        self.parsers = {}
        self.parsers["get"] = reqparse.RequestParser(argument_class=ArgumentDoc)
        parser_get = self.parsers["get"]
        parser_get.add_argument("from", type=str, dest="origin")
        parser_get.add_argument("to", type=str, dest="destination")
        parser_get.add_argument("datetime", type=str)
        parser_get.add_argument("datetime_represents", dest="clockwise",
                           type=dt_represents, default=True)
        parser_get.add_argument("max_nb_transfers", type=int, default=10,
                           dest="max_transfers")
        parser_get.add_argument("first_section_mode",
                           type=option_value(modes),
                           default="walking",
                           dest="origin_mode")
        parser_get.add_argument("last_section_mode",
                           type=option_value(modes),
                           default="walking",
                           dest="destination_mode")
        parser_get.add_argument("walking_speed", type=float, default=1.68)
        parser_get.add_argument("walking_distance", type=int, default=1000)
        parser_get.add_argument("bike_speed", type=float, default=8.8)
        parser_get.add_argument("bike_distance", type=int, default=5000)
        parser_get.add_argument("br_speed", type=float, default=8.8,)
        parser_get.add_argument("br_distance", type=int, default=5000)
        parser_get.add_argument("car_speed", type=float, default=16.8)
        parser_get.add_argument("car_distance", type=int, default=15000)
        parser_get.add_argument("forbidden_uris[]", type=str, action="append")
        parser_get.add_argument("count", type=int)
        parser_get.add_argument("type", type=option_value(types), default="all")
#a supprimer
        parser_get.add_argument("max_duration", type=int, default=36000)
        self.method_decorators.append(add_notes(self))

    @clean_links()
    @add_id_links()
    @add_journey_pagination()
    @add_journey_href()
    @marshal_with(journeys)
    @ManageError()
    def get(self, region=None, lon=None, lat=None, uri=None):
        args = self.parsers["get"].parse_args()
        #TODO : Changer le protobuff pour que ce soit propre
        args["destination_mode"] = "vls" if args["destination_mode"] == "br" else args["destination_mode"]
        args["origin_mode"] = "vls" if args["origin_mode"] == "br" else args["origin_mode"]
        if not region is None or (not lon is None and not lat is None):
            self.region = NavitiaManager().get_region(region, lon, lat)
            if uri:
                objects = uri.split("/")
                if objects and len(objects) % 2 == 0:
                    args["origin"] =  self.transform_id(objects[-1])
                else:
                    return {"error" : "Unable to compute journeys from this \
                                       object"}, 503
        else:
            if "origin" in args.keys():
                self.region = NavitiaManager().key_of_id(args["origin"])
                args["origin"] = self.transform_id(args["origin"])
            elif "destination" in args.keys():
                self.region = NavitiaManager().key_of_id(args["destination"])
            if "destination" in args.keys():
                args["destination"] = self.transform_id(args["destination"])
            else:
                raise RegionNotFound("")
        if not args["datetime"]:
            args["datetime"] = datetime.now().strftime("%Y%m%dT1337")
        api = None
        if "destination" in args.keys() and args["destination"]:
            api = "journeys"
        else:
            api = "isochrone"
        response = NavitiaManager().dispatch(args, self.region, api)
        return response

    def transform_id(self, id):
        splitted_coord = id.split(";")
        splitted_address = id.split(":")
        if len(splitted_coord) == 2:
            return "coord:"+id.replace(";", ":")
        if len(splitted_address) >=3 and splitted_address[0] == 'address':
            del splitted_address[1]
            return ':'.join(splitted_address)
        return id
<|endoftext|>


<commit_before># This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# (c) 2016 Red Hat Inc.
#
# 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.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

# Networking tools for network modules only

import re
import ast
import operator
import socket

from itertools import chain
from socket import inet_aton

from ansible.module_utils._text import to_text
from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils.basic import AnsibleFallbackNotFound

# Backwards compatibility for 3rd party modules
from ansible.module_utils.common.network import (
    to_bits, is_netmask, is_masklen, to_netmask, to_masklen, to_subnet, to_ipv6_network, VALID_MASKS
)

try:
    from jinja2 import Environment, StrictUndefined
    from jinja2.exceptions import UndefinedError
    HAS_JINJA2 = True
except ImportError:
    HAS_JINJA2 = False

OPERATORS = frozenset(['ge', 'gt', 'eq', 'neq', 'lt', 'le'])
ALIASES = frozenset([('min', 'ge'), ('max', 'le'), ('exactly', 'eq'), ('neq', 'ne')])

def to_list(val):
    if isinstance(val, (list, tuple, set)):
        return list(val)
    elif val is not None:
        return [val]
    else:
        return list()

def to_lines(stdout):
    for item in stdout:
        if isinstance(item, string_types):
            item = to_text(item).split('\n')
        yield item

def transform_commands(module):
    transform = ComplexList(dict(
        command=dict(key=True),
        output=dict(),
        prompt=dict(type='list'),
        answer=dict(type='list'),
        sendonly=dict(type='bool', default=False),
        check_all=dict(type='bool', default=False),
    ), module)

    return transform(module.params['commands'])

def sort_list(val):
    if isinstance(val, list):
        return sorted(val)
    return val

class Entity(object):
    """Transforms a dict to with an argument spec

    This class will take a dict and apply an Ansible argument spec to the
    values.  The resulting dict will contain all of the keys in the param
    with appropriate values set.

    Example::

        argument_spec = dict(
            command=dict(key=True),
            display=dict(default='text', choices=['text', 'json']),
            validate=dict(type='bool')
        )
        transform = Entity(module, argument_spec)
        value = dict(command='foo')
        result = transform(value)
        print result
        {'command': 'foo', 'display': 'text', 'validate': None}

    Supported argument spec:
        * key - specifies how to map a single value to a dict
        * read_from - read and apply the argument_spec from the module
        * required - a value is required
        * type - type of value (uses AnsibleModule type checker)
        * fallback - implements fallback function
        * choices - set of valid options
        * default - default value
    """

    def __init__(self, module, attrs=None, args=None, keys=None, from_argspec=False):
        args = [] if args is None else args

        self._attributes = attrs or {}
        self._module = module

        for arg in args:
            self._attributes[arg] = dict()
            if from_argspec:
                self._attributes[arg]['read_from'] = arg
            if keys and arg in keys:
                self._attributes[arg]['key'] = True

        self.attr_names = frozenset(self._attributes.keys())

        _has_key = False

        for name, attr in iteritems(self._attributes):
            if attr.get('read_from'):
                if attr['read_from'] not in self._module.argument_spec:
                    module.fail_json(msg='argument %s does not exist' % attr['read_from'])
                spec = self._module.argument_spec.get(attr['read_from'])
                for key, value in iteritems(spec):
                    if key not in attr:
                        attr[key] = value

            if attr.get('key'):
                if _has_key:
                    module.fail_json(msg='only one key value can be specified')
                _has_key = True
                attr['required'] = True

    def serialize(self):
        return self._attributes

    def to_dict(self, value):
        obj = {}
        for name, attr in iteritems(self._attributes):
            if attr.get('key'):
                obj[name] = value
            else:
                obj[name] = attr.get('default')
        return obj

    def __call__(self, value, strict=True):
        if not isinstance(value, dict):
            value = self.to_dict(value)

        if strict:
            unknown = set(value).difference(self.attr_names)
            if unknown:
                self._module.fail_json(msg='invalid keys: %s' % ','.join(unknown))

        for name, attr in iteritems(self._attributes):
            if value.get(name) is None:
                value[name] = attr.get('default')

            if attr.get('fallback') and not value.get(name):
                fallback = attr.get('fallback', (None,))
                fallback_strategy = fallback[0]
                fallback_args = []
                fallback_kwargs = {}
                if fallback_strategy is not None:
                    for item in fallback[1:]:
                        if isinstance(item, dict):
                            fallback_kwargs = item
                        else:
                            fallback_args = item
                    try:
                        value[name] = fallback_strategy(*fallback_args, **fallback_kwargs)
                    except AnsibleFallbackNotFound:
                        continue

            if attr.get('required') and value.get(name) is None:
                self._module.fail_json(msg='missing required attribute %s' % name)

            if 'choices' in attr:
                if value[name] not in attr['choices']:
                    self._module.fail_json(msg='%s must be one of %s, got %s' % (name, ', '.join(attr['choices']), value[name]))

            if value[name] is not None:
                value_type = attr.get('type', 'str')
                type_checker = self._module._CHECK_ARGUMENT_TYPES_DISPATCHER[value_type]
                type_checker(value[name])
            elif value.get(name):
                value[name] = self._module.params[name]

        return value

class EntityCollection(Entity):
    """Extends ```Entity``` to handle a list of dicts """

    def __call__(self, iterable, strict=True):
        if iterable is None:
            iterable = [super(EntityCollection, self).__call__(self._module.params, strict)]

        if not isinstance(iterable, (list, tuple)):
            self._module.fail_json(msg='value must be an iterable')

        return [(super(EntityCollection, self).__call__(i, strict)) for i in iterable]

# these two are for backwards compatibility and can be removed once all of the
# modules that use them are updated
class ComplexDict(Entity):
    def __init__(self, attrs, module, *args, **kwargs):
        super(ComplexDict, self).__init__(module, attrs, *args, **kwargs)

class ComplexList(EntityCollection):
    def __init__(self, attrs, module, *args, **kwargs):
        super(ComplexList, self).__init__(module, attrs, *args, **kwargs)

def dict_diff(base, comparable):
    """ Generate a dict object of differences

    This function will compare two dict objects and return the difference
    between them as a dict object.  For scalar values, the key will reflect
    the updated value.  If the key does not exist in `comparable`, then then no
    key will be returned.  For lists, the value in comparable will wholly replace
    the value in base for the key.  For dicts, the returned value will only
    return keys that are different.

    :param base: dict object to base the diff on
    :param comparable: dict object to compare against base

    :returns: new dict object with differences
    """
    if not isinstance(base, dict):
        raise AssertionError("`base` must be of type <dict>")
    if not isinstance(comparable, dict):
        raise AssertionError("`comparable` must be of type <dict>")

    updates = dict()

    for key, value in iteritems(base):
        if isinstance(value, dict):
            item = comparable.get(key)
            if item is not None:
                updates[key] = dict_diff(value, comparable[key])
        else:
            comparable_value = comparable.get(key)
            if comparable_value is not None:
                if sort_list(base[key]) != sort_list(comparable_value):
                    updates[key] = comparable_value

    for key in set(comparable.keys()).difference(base.keys()):
        updates[key] = comparable.get(key)

    return updates

def dict_merge(base, other):
    """ Return a new dict object that combines base and other

    This will create a new dict object that is a combination of the key/value
    pairs from base and other.  When both keys exist, the value will be
    selected from other.  If the value is a list object, the two lists will
    be combined and duplicate entries removed.

    :param base: dict object to serve as base
    :param other: dict object to combine with base

    :returns: new combined dict object
    """
    if not isinstance(base, dict):
        raise AssertionError("`base` must be of type <dict>")
    if not isinstance(other, dict):
        raise AssertionError("`other` must be of type <dict>")

    combined = dict()

    for key, value in iteritems(base):
        if isinstance(value, dict):
            if key in other:
                item = other.get(key)
                if item is not None:
                    combined[key] = dict_merge(value, other[key])
                else:
                    combined[key] = item
            else:
                combined[key] = value
        elif isinstance(value, list):
            if key in other:
                item = other.get(key)
                if item is not None:
                    try:
                        combined[key] = list(set(chain(value, item)))
                    except TypeError:
                        value.extend([i for i in item if i not in value])
                        combined[key] = value
                else:
                    combined[key] = item
            else:
                combined[key] = value
        else:
            if key in other:
                other_value = other.get(key)
                if other_value is not None:
                    if sort_list(base[key]) != sort_list(other_value):
                        combined[key] = other_value
                    else:
                        combined[key] = value
                else:
                    combined[key] = other_value
            else:
                combined[key] = value

    for key in set(other.keys()).difference(base.keys()):
        combined[key] = other.get(key)

    return combined

def conditional(expr, val, cast=None):
    match = re.match(r'^(.+)\((.+)\)$', str(expr), re.I)
    if match:
        op, arg = match.groups()
    else:
        op = 'eq'
        if ' ' in str(expr):
            raise AssertionError('invalid expression: cannot contain spaces')
        arg = expr

    if cast is None and val is not None:
        arg = type(val)(arg)
    elif callable(cast):
        arg = cast(arg)
        val = cast(val)

    op = next((oper for alias, oper in ALIASES if op == alias), op)

    if not hasattr(operator, op) and op not in OPERATORS:
        raise ValueError('unknown operator: %s' % op)

    func = getattr(operator, op)
    return func(val, arg)

def ternary(value, true_val, false_val):
    '''  value ? true_val : false_val '''
    if value:
        return true_val
    else:
        return false_val

def remove_default_spec(spec):
    for item in spec:
        if 'default' in spec[item]:
            del spec[item]['default']

def validate_ip_address(address):
    try:
        socket.inet_aton(address)
    except socket.error:
        return False
    return address.count('.') == 3

def validate_ip_v6_address(address):
    try:
        socket.inet_pton(socket.AF_INET6, address)
    except socket.error:
        return False
    return True

def validate_prefix(prefix):
    if prefix and not 0 <= int(prefix) <= 32:
        return False
    return True

def load_provider(spec, args):
    provider = args.get('provider', {})
    for key, value in iteritems(spec):
        if key not in provider:
            if key in args:
                provider[key] = args[key]
            elif 'fallback' in value:
                provider[key] = _fallback(value['fallback'])
            elif 'default' in value:
                provider[key] = value['default']
            else:
                provider[key] = None
    args['provider'] = provider
    return provider

def _fallback(fallback):
    strategy = fallback[0]
    args = []
    kwargs = {}

    for item in fallback[1:]:
        if isinstance(item, dict):
            kwargs = item
        else:
            args = item
    try:
        return strategy(*args, **kwargs)
    except AnsibleFallbackNotFound:
        pass

class Template:

    def __init__(self):
        if not HAS_JINJA2:
            raise ImportError("jinja2 is required but does not appear to be installed.  "
                              "It can be installed using `pip install jinja2`")

        self.env = Environment(undefined=StrictUndefined)
        self.env.filters.update({'ternary': ternary})

    def __call__(self, value, variables=None, fail_on_undefined=True):
        variables = variables or {}

        if not self.contains_vars(value):
            return value

        try:
            value = self.env.from_string(value).render(variables)
        except UndefinedError:
            if not fail_on_undefined:
                return None
            raise

        if value:
            try:
                return ast.literal_eval(value)
            except:
                return str(value)
        else:
            return None

    def contains_vars(self, data):
        if isinstance(data, string_types):
            for marker in (self.env.block_start_string, self.env.variable_start_string, self.env.comment_start_string):
                if marker in data:
                    return True
        return False
<commit_msg>fixes an issue with dict_merge in network utils (#41107)<commit_after># This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# (c) 2016 Red Hat Inc.
#
# 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.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

# Networking tools for network modules only

import re
import ast
import operator
import socket

from itertools import chain
from socket import inet_aton

from ansible.module_utils._text import to_text
from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils.basic import AnsibleFallbackNotFound

# Backwards compatibility for 3rd party modules
from ansible.module_utils.common.network import (
    to_bits, is_netmask, is_masklen, to_netmask, to_masklen, to_subnet, to_ipv6_network, VALID_MASKS
)

try:
    from jinja2 import Environment, StrictUndefined
    from jinja2.exceptions import UndefinedError
    HAS_JINJA2 = True
except ImportError:
    HAS_JINJA2 = False

OPERATORS = frozenset(['ge', 'gt', 'eq', 'neq', 'lt', 'le'])
ALIASES = frozenset([('min', 'ge'), ('max', 'le'), ('exactly', 'eq'), ('neq', 'ne')])

def to_list(val):
    if isinstance(val, (list, tuple, set)):
        return list(val)
    elif val is not None:
        return [val]
    else:
        return list()

def to_lines(stdout):
    for item in stdout:
        if isinstance(item, string_types):
            item = to_text(item).split('\n')
        yield item

def transform_commands(module):
    transform = ComplexList(dict(
        command=dict(key=True),
        output=dict(),
        prompt=dict(type='list'),
        answer=dict(type='list'),
        sendonly=dict(type='bool', default=False),
        check_all=dict(type='bool', default=False),
    ), module)

    return transform(module.params['commands'])

def sort_list(val):
    if isinstance(val, list):
        return sorted(val)
    return val

class Entity(object):
    """Transforms a dict to with an argument spec

    This class will take a dict and apply an Ansible argument spec to the
    values.  The resulting dict will contain all of the keys in the param
    with appropriate values set.

    Example::

        argument_spec = dict(
            command=dict(key=True),
            display=dict(default='text', choices=['text', 'json']),
            validate=dict(type='bool')
        )
        transform = Entity(module, argument_spec)
        value = dict(command='foo')
        result = transform(value)
        print result
        {'command': 'foo', 'display': 'text', 'validate': None}

    Supported argument spec:
        * key - specifies how to map a single value to a dict
        * read_from - read and apply the argument_spec from the module
        * required - a value is required
        * type - type of value (uses AnsibleModule type checker)
        * fallback - implements fallback function
        * choices - set of valid options
        * default - default value
    """

    def __init__(self, module, attrs=None, args=None, keys=None, from_argspec=False):
        args = [] if args is None else args

        self._attributes = attrs or {}
        self._module = module

        for arg in args:
            self._attributes[arg] = dict()
            if from_argspec:
                self._attributes[arg]['read_from'] = arg
            if keys and arg in keys:
                self._attributes[arg]['key'] = True

        self.attr_names = frozenset(self._attributes.keys())

        _has_key = False

        for name, attr in iteritems(self._attributes):
            if attr.get('read_from'):
                if attr['read_from'] not in self._module.argument_spec:
                    module.fail_json(msg='argument %s does not exist' % attr['read_from'])
                spec = self._module.argument_spec.get(attr['read_from'])
                for key, value in iteritems(spec):
                    if key not in attr:
                        attr[key] = value

            if attr.get('key'):
                if _has_key:
                    module.fail_json(msg='only one key value can be specified')
                _has_key = True
                attr['required'] = True

    def serialize(self):
        return self._attributes

    def to_dict(self, value):
        obj = {}
        for name, attr in iteritems(self._attributes):
            if attr.get('key'):
                obj[name] = value
            else:
                obj[name] = attr.get('default')
        return obj

    def __call__(self, value, strict=True):
        if not isinstance(value, dict):
            value = self.to_dict(value)

        if strict:
            unknown = set(value).difference(self.attr_names)
            if unknown:
                self._module.fail_json(msg='invalid keys: %s' % ','.join(unknown))

        for name, attr in iteritems(self._attributes):
            if value.get(name) is None:
                value[name] = attr.get('default')

            if attr.get('fallback') and not value.get(name):
                fallback = attr.get('fallback', (None,))
                fallback_strategy = fallback[0]
                fallback_args = []
                fallback_kwargs = {}
                if fallback_strategy is not None:
                    for item in fallback[1:]:
                        if isinstance(item, dict):
                            fallback_kwargs = item
                        else:
                            fallback_args = item
                    try:
                        value[name] = fallback_strategy(*fallback_args, **fallback_kwargs)
                    except AnsibleFallbackNotFound:
                        continue

            if attr.get('required') and value.get(name) is None:
                self._module.fail_json(msg='missing required attribute %s' % name)

            if 'choices' in attr:
                if value[name] not in attr['choices']:
                    self._module.fail_json(msg='%s must be one of %s, got %s' % (name, ', '.join(attr['choices']), value[name]))

            if value[name] is not None:
                value_type = attr.get('type', 'str')
                type_checker = self._module._CHECK_ARGUMENT_TYPES_DISPATCHER[value_type]
                type_checker(value[name])
            elif value.get(name):
                value[name] = self._module.params[name]

        return value

class EntityCollection(Entity):
    """Extends ```Entity``` to handle a list of dicts """

    def __call__(self, iterable, strict=True):
        if iterable is None:
            iterable = [super(EntityCollection, self).__call__(self._module.params, strict)]

        if not isinstance(iterable, (list, tuple)):
            self._module.fail_json(msg='value must be an iterable')

        return [(super(EntityCollection, self).__call__(i, strict)) for i in iterable]

# these two are for backwards compatibility and can be removed once all of the
# modules that use them are updated
class ComplexDict(Entity):
    def __init__(self, attrs, module, *args, **kwargs):
        super(ComplexDict, self).__init__(module, attrs, *args, **kwargs)

class ComplexList(EntityCollection):
    def __init__(self, attrs, module, *args, **kwargs):
        super(ComplexList, self).__init__(module, attrs, *args, **kwargs)

def dict_diff(base, comparable):
    """ Generate a dict object of differences

    This function will compare two dict objects and return the difference
    between them as a dict object.  For scalar values, the key will reflect
    the updated value.  If the key does not exist in `comparable`, then then no
    key will be returned.  For lists, the value in comparable will wholly replace
    the value in base for the key.  For dicts, the returned value will only
    return keys that are different.

    :param base: dict object to base the diff on
    :param comparable: dict object to compare against base

    :returns: new dict object with differences
    """
    if not isinstance(base, dict):
        raise AssertionError("`base` must be of type <dict>")
    if not isinstance(comparable, dict):
        raise AssertionError("`comparable` must be of type <dict>")

    updates = dict()

    for key, value in iteritems(base):
        if isinstance(value, dict):
            item = comparable.get(key)
            if item is not None:
                updates[key] = dict_diff(value, comparable[key])
        else:
            comparable_value = comparable.get(key)
            if comparable_value is not None:
                if sort_list(base[key]) != sort_list(comparable_value):
                    updates[key] = comparable_value

    for key in set(comparable.keys()).difference(base.keys()):
        updates[key] = comparable.get(key)

    return updates

def dict_merge(base, other):
    """ Return a new dict object that combines base and other

    This will create a new dict object that is a combination of the key/value
    pairs from base and other.  When both keys exist, the value will be
    selected from other.  If the value is a list object, the two lists will
    be combined and duplicate entries removed.

    :param base: dict object to serve as base
    :param other: dict object to combine with base

    :returns: new combined dict object
    """
    if not isinstance(base, dict):
        raise AssertionError("`base` must be of type <dict>")
    if not isinstance(other, dict):
        raise AssertionError("`other` must be of type <dict>")

    combined = dict()

    for key, value in iteritems(base):
        if isinstance(value, dict):
            if key in other:
                item = other.get(key)
                if item is not None:
                    if isinstance(other[key], dict):
                        combined[key] = dict_merge(value, other[key])
                    else:
                        combined[key] = other[key]
                else:
                    combined[key] = item
            else:
                combined[key] = value
        elif isinstance(value, list):
            if key in other:
                item = other.get(key)
                if item is not None:
                    try:
                        combined[key] = list(set(chain(value, item)))
                    except TypeError:
                        value.extend([i for i in item if i not in value])
                        combined[key] = value
                else:
                    combined[key] = item
            else:
                combined[key] = value
        else:
            if key in other:
                other_value = other.get(key)
                if other_value is not None:
                    if sort_list(base[key]) != sort_list(other_value):
                        combined[key] = other_value
                    else:
                        combined[key] = value
                else:
                    combined[key] = other_value
            else:
                combined[key] = value

    for key in set(other.keys()).difference(base.keys()):
        combined[key] = other.get(key)

    return combined

def conditional(expr, val, cast=None):
    match = re.match(r'^(.+)\((.+)\)$', str(expr), re.I)
    if match:
        op, arg = match.groups()
    else:
        op = 'eq'
        if ' ' in str(expr):
            raise AssertionError('invalid expression: cannot contain spaces')
        arg = expr

    if cast is None and val is not None:
        arg = type(val)(arg)
    elif callable(cast):
        arg = cast(arg)
        val = cast(val)

    op = next((oper for alias, oper in ALIASES if op == alias), op)

    if not hasattr(operator, op) and op not in OPERATORS:
        raise ValueError('unknown operator: %s' % op)

    func = getattr(operator, op)
    return func(val, arg)

def ternary(value, true_val, false_val):
    '''  value ? true_val : false_val '''
    if value:
        return true_val
    else:
        return false_val

def remove_default_spec(spec):
    for item in spec:
        if 'default' in spec[item]:
            del spec[item]['default']

def validate_ip_address(address):
    try:
        socket.inet_aton(address)
    except socket.error:
        return False
    return address.count('.') == 3

def validate_ip_v6_address(address):
    try:
        socket.inet_pton(socket.AF_INET6, address)
    except socket.error:
        return False
    return True

def validate_prefix(prefix):
    if prefix and not 0 <= int(prefix) <= 32:
        return False
    return True

def load_provider(spec, args):
    provider = args.get('provider', {})
    for key, value in iteritems(spec):
        if key not in provider:
            if key in args:
                provider[key] = args[key]
            elif 'fallback' in value:
                provider[key] = _fallback(value['fallback'])
            elif 'default' in value:
                provider[key] = value['default']
            else:
                provider[key] = None
    args['provider'] = provider
    return provider

def _fallback(fallback):
    strategy = fallback[0]
    args = []
    kwargs = {}

    for item in fallback[1:]:
        if isinstance(item, dict):
            kwargs = item
        else:
            args = item
    try:
        return strategy(*args, **kwargs)
    except AnsibleFallbackNotFound:
        pass

class Template:

    def __init__(self):
        if not HAS_JINJA2:
            raise ImportError("jinja2 is required but does not appear to be installed.  "
                              "It can be installed using `pip install jinja2`")

        self.env = Environment(undefined=StrictUndefined)
        self.env.filters.update({'ternary': ternary})

    def __call__(self, value, variables=None, fail_on_undefined=True):
        variables = variables or {}

        if not self.contains_vars(value):
            return value

        try:
            value = self.env.from_string(value).render(variables)
        except UndefinedError:
            if not fail_on_undefined:
                return None
            raise

        if value:
            try:
                return ast.literal_eval(value)
            except:
                return str(value)
        else:
            return None

    def contains_vars(self, data):
        if isinstance(data, string_types):
            for marker in (self.env.block_start_string, self.env.variable_start_string, self.env.comment_start_string):
                if marker in data:
                    return True
        return False
<|endoftext|>