from django import forms
from django.forms.forms import BoundField
from django.utils.html import escape
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe

class SectionedForm(object):
    """
    ToDo
    """
    sections = {}
    section_template = "
%s
"

    def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
        "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
        top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
        output, hidden_fields = [], []

        for section, fields in self.sections:
            if section:
                output.append(normal_row % {'errors': '', 'label': ' ', 'field': self.section_template%section, 'help_text': ''})

            for name, field in [i for i in self.fields.items() if i[0] in fields]:
                bf = BoundField(self, field, name)
                bf_errors = self.error_class([escape(error) for error in bf.errors]) # Escape and cache in local variable.
                if bf.is_hidden:
                    if bf_errors:
                        top_errors.extend([u'(Hidden field %s) %s' % (name, force_unicode(e)) for e in bf_errors])
                    hidden_fields.append(unicode(bf))
                else:
                    if errors_on_separate_row and bf_errors:
                        output.append(error_row % force_unicode(bf_errors))
                    if bf.label:
                        label = escape(force_unicode(bf.label))
                        # Only add the suffix if the label does not end in
                        # punctuation.
                        if self.label_suffix:
                            if label[-1] not in ':?.!':
                                label += self.label_suffix
                        label = bf.label_tag(label) or ''
                    else:
                        label = ''
                    if field.help_text:
                        help_text = help_text_html % force_unicode(field.help_text)
                    else:
                        help_text = u''
                    output.append(normal_row % {'errors': force_unicode(bf_errors), 'label': force_unicode(label), 'field': unicode(bf), 'help_text': help_text})

        if top_errors:
            output.insert(0, error_row % force_unicode(top_errors))
        if hidden_fields: # Insert any hidden fields in the last row.
            str_hidden = u''.join(hidden_fields)
            if output:
                last_row = output[-1]
                # Chop off the trailing row_ender (e.g. '
') and
                # insert the hidden fields.
                output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
            else:
                # If there aren't any rows in the output, just append the
                # hidden fields.
                output.append(str_hidden)
        return mark_safe(u'\n'.join(output))


/*
 * This file is part of EIBA.
 *
 * Copyright (C) 2017 Zhejiang University
 * For more information see <https://github.com/ZJUCVG/EIBA>
 *
 * 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.
 *
 */

#include "PlatformIndependence/sse.h"

#ifndef _FRAME_H_

#include "stdafx.h"

#include "Camera.h"
#include "Feature.h"
#include "M-Estimator.h"
#include "Matrix2x3.h"
#include "Matrix2x4.h"
#include "Matrix8x8.h"

#define FRM_IP_LEVELS 4
#define FRM_IP_LEVELS_MINUS_ONE 3
#define FRM_IP_LEVELS_PLUS_ONE 5
//#define FRM_IT_LEVEL			4

#define FRM_IT_CHECK_INVALID_DEFAULT 0
#define FRM_IT_CHKCK_INVALID_FIRST 1
#define FRM_IT_CHKCK_INVALID_ALL 2

//#define FRM_ALN_DECOUPLE_RIGID

#define FRM_ALN_FLAG_DEFAULT 0
#define FRM_ALN_FLAG_ROTATION 1
#define FRM_ALN_FLAG_POSITION 2
#define FRM_ALN_FLAG_DEPTH 4
#define FRM_ALN_FLAG_INITIALIZED 8

#ifdef CFG_TUNE_PARAMETERS
extern int FRM_IT_LEVEL;
extern float FRM_IT_BLUR_SIGMA;
extern float FRM_ALN_WEIGHT_INTENSITY;
extern float FRM_ALN_WEIGHT_PRIOR_ROTATION;
extern int FRM_ALN_MAX_ITERATIONS;
extern float FRM_ALN_VARIANCE_INTENSITY;
extern float FRM_ALN_VARIANCE_MATCH;
extern float FRM_ALN_VARIANCE_PRIOR_INTENSITY_OFFSET;
extern float FRM_ALN_VARIANCE_PRIOR_DEPTH;
#ifdef CFG_DEPTH_MAP
extern float FRM_ALN_VARIANCE_PRIOR_DEPTH_MAP;
#endif
extern float FRM_ALN_VARIANCE_PRIOR_ROTATION;
extern float FRM_ALN_VARIANCE_PRIOR_POSITION_X;
extern float FRM_ALN_VARIANCE_PRIOR_POSITION_Y;
extern float FRM_ALN_VARIANCE_PRIOR_POSITION_Z;
extern float FRM_ALN_MAX_ERROR_INTENSITY;
extern float FRM_ALN_MAX_ERROR_MATCH;
extern float FRM_ALN_MIN_OVERLAP_RATIO;
extern float FRM_ALN_MIN_OVERLAP_RATIO_ROBUST;
extern float FRM_ALN_CONVERGE_MOVEMENT;
extern float FRM_ALN_CONVERGE_DEPTH;
extern float FRM_ALN_EPSILON_ROTATION;
extern float FRM_ALN_EPSILON_POSITION;
#include "Configurator.h"
extern void LOAD_PARAMETERS_FRAME_ALIGNMENT(const Configurator &cfgor);
#else
#define FRM_IT_LEVEL 4
#define FRM_IT_BLUR_SIGMA 1.5f
#define FRM_ALN_WEIGHT_INTENSITY 1.0e-3f
//#define FRM_ALN_WEIGHT_INTENSITY				1.0f
#define FRM_ALN_WEIGHT_PRIOR_ROTATION 1.0e-3f
//#define FRM_ALN_WEIGHT_PRIOR_ROTATION			1.0f
#define FRM_ALN_MAX_ITERATIONS 20
#define FRM_ALN_VARIANCE_INTENSITY 100.0f // 10^2
#define FRM_ALN_VARIANCE_MATCH 1.0f       // 1^2
#define FRM_ALN_VARIANCE_PRIOR_INTENSITY_OFFSET 9.0f // 3^2
//#define FRM_ALN_VARIANCE_PRIOR_DEPTH			1.0f
//// 1^2
#define FRM_ALN_VARIANCE_PRIOR_DEPTH 100.0f // 10^2
#ifdef CFG_DEPTH_MAP
//#define FRM_ALN_VARIANCE_PRIOR_DEPTH_MAP		0.01f
//// 0.1^2
#define FRM_ALN_VARIANCE_PRIOR_DEPTH_MAP 1.0f // 1^2
#endif
#define FRM_ALN_VARIANCE_PRIOR_ROTATION 3.046174198662e-4f // (1.0*pi/180)^2
#define FRM_ALN_VARIANCE_PRIOR_POSITION_X 9.0f             // 3^2+
#define FRM_ALN_VARIANCE_PRIOR_POSITION_Y 9.0f
#define FRM_ALN_VARIANCE_PRIOR_POSITION_Z 9.0f
#define FRM_ALN_MAX_ERROR_INTENSITY 20.0f
#define FRM_ALN_MAX_ERROR_MATCH 1.0f
#define FRM_ALN_MIN_OVERLAP_RATIO 0.3f
#define FRM_ALN_MIN_OVERLAP_RATIO_ROBUST 0.3f
#define FRM_ALN_CONVERGE_MOVEMENT 0.01f
//#define FRM_ALN_CONVERGE_MOVEMENT				0.1f
#define FRM_ALN_CONVERGE_DEPTH 0.01f
//#define FRM_ALN_CONVERGE_DEPTH				0.1f
#define FRM_ALN_EPSILON_ROTATION 1.745329252e-4f // 0.01*pi/180
#define FRM_ALN_EPSILON_POSITION 0.001f
#endif

namespace FRM
{
template <class TYPE>
inline void VectorSaveB(const std::vector<TYPE> &V, FILE *fp)
{
    const int N = int(V.size());
    UT::SaveB(N, fp);
    for (int i = 0; i < N; ++i) V[i].SaveB(fp);
}
template <class TYPE> inline void VectorLoadB(std::vector<TYPE> &V, FILE *fp)
{
    const int N = UT::LoadB<int>(fp);
    V.resize(N);
    for (int i = 0; i < N; ++i) V[i].LoadB(fp);
}

template <class TYPE> inline void ListSaveB(const std::list<TYPE> &L, FILE *fp)
{
    const int N = int(L.size());
    UT::SaveB(N, fp);
    for (typename std::list<TYPE>::const_iterator it = L.begin(); it != L.end();
         ++it)
        it->SaveB(fp);
}
template <class TYPE> inline void ListLoadB(std::list<TYPE> &L, FILE *fp)
{
    const int N = UT::LoadB<int>(fp);
    L.resize(N);
    for (typename std::list<TYPE>::iterator it = L.begin(); it != L.end(); ++it)
        it->LoadB(fp);
}

// store frame tag
class Tag
{
  public:
    inline bool operator==(const Tag &T) const
    {
        return m_iFrm == T.m_iFrm && m_t == T.m_t;
    }
    inline bool operator!=(const Tag &T) const
    {
        return m_iFrm != T.m_iFrm || m_t != T.m_t;
    }
    inline bool operator<(const Tag &T) const
    {
        return m_iFrm < T.m_iFrm && m_t < T.m_t;
    }
    inline bool operator>(const Tag &T) const
    {
        return m_iFrm > T.m_iFrm && m_t > T.m_t;
    }
    inline void SaveB(FILE *fp) const
    {
        UT::SaveB(m_iFrm, fp);
        UT::SaveB(m_t, fp);
#ifdef CFG_VIEW
        UT::StringSaveB(m_fileName, fp);
#ifdef CFG_DEPTH_MAP
        UT::StringSaveB(m_fileNameDep, fp);
#endif
#endif
    }
    inline void LoadB(FILE *fp)
    {
        UT::LoadB(m_iFrm, fp);
        UT::LoadB(m_t, fp);
        UT::StringLoadB(m_fileName, fp);
        UT::StringLoadB(m_fileNameDep, fp);
    }

  public:
    int m_iFrm;
    float m_t;
    std::string m_fileName;
    std::string m_fileNameDep;
};

class Measurement
{
  public:
    inline Measurement() {}
    inline Measurement(const int iKF, const int izIP[FRM_IP_LEVELS_PLUS_ONE])
    {
        m_iKF = iKF;
        memcpy(m_izIP, izIP, sizeof(m_izIP));
    }
    inline bool operator==(const Measurement &Z) const
    {
        return m_iKF == Z.m_iKF &&
               UT::VectorEqual(m_izIP, Z.m_izIP, FRM_IP_LEVELS_PLUS_ONE);
    }
    inline bool operator<(const int iKF) const { return m_iKF < iKF; }
    inline int SearchFeatureMeasurementLevel(const int iz) const
    {
        if (iz < m_izIP[0] || iz >= m_izIP[FRM_IP_LEVELS]) return -1;
        for (int iLvl = 0; iLvl < FRM_IP_LEVELS; ++iLvl) {
            if (iz < m_izIP[iLvl + 1]) return iLvl;
        }
        return -1;
    }
    inline void AssertConsistency() const
    {
        UT_ASSERT(m_iKF >= 0);
        for (int iLvl = 0; iLvl < FRM_IP_LEVELS; ++iLvl)
            UT_ASSERT(m_izIP[iLvl] <= m_izIP[iLvl + 1]);
    }

  public:
    // m_iKF : keyframe index
    // m_izIP : measurement start index for every image level
    int m_iKF, m_izIP[FRM_IP_LEVELS_PLUS_ONE];
};

class Frame
{
  public:
    inline Frame() {}
    inline Frame(const Frame &F) { *this = F; }
    inline void operator=(const Frame &F)
    {
        m_T = F.m_T;
        m_Zs = F.m_Zs;
        m_zs = F.m_zs;
        m_iKFsMatch = F.m_iKFsMatch;
    }
    inline bool operator==(const Frame &F) const
    {
        return m_T == F.m_T && UT::VectorEqual(m_Zs, F.m_Zs) &&
               UT::VectorEqual(m_zs, F.m_zs) &&
               UT::VectorEqual(m_iKFsMatch, F.m_iKFsMatch);
    }
    inline void Initialize(const Tag &T)
    {
        m_T = T;
        ClearMeasurements();
    }
    inline void Initialize(const Frame &F)
    {
        m_T = F.m_T;
        m_Zs = F.m_Zs;
        m_zs = F.m_zs;
        m_iKFsMatch = F.m_iKFsMatch;
    }
    inline void ClearMeasurements()
    {
        m_Zs.resize(0);
        m_zs.resize(0);
        m_iKFsMatch.resize(0);
    }
    inline int SearchFrameMeasurement(const int iKF) const
    {
        const std::vector<Measurement>::const_iterator iZ =
            std::lower_bound(m_Zs.begin(), m_Zs.end(), iKF);
        if (iZ == m_Zs.end() || iZ->m_iKF != iKF)
            return -1;
        else
            return int(iZ - m_Zs.begin());
    }
    inline int SearchFeatureMeasurement(const int iKF, const int ix) const
    {
        const int iZ = SearchFrameMeasurement(iKF);
        if (iZ == -1) return -1;
        const Measurement &Z = m_Zs[iZ];
        for (int iLvl = 0; iLvl < FRM_IP_LEVELS; ++iLvl) {
            const std::vector<FTR::Measurement>::const_iterator
                iz1 = m_zs.begin() + Z.m_izIP[iLvl],
                iz2 = m_zs.begin() + Z.m_izIP[iLvl + 1];
            const std::vector<FTR::Measurement>::const_iterator iz =
                std::lower_bound(iz1, iz2, ix);
            if (iz != iz2 && iz->m_ix == ix) return int(iz - m_zs.begin());
        }
        return -1;
    }
#if 0
	inline bool SearchFeatureMeasurement(const int iKF, const int ix, int &iz, int &iLvl) const
	{
		iz = iLvl = -1;
		const int iZ = SearchFrameMeasurement(iKF);
		if(iZ == -1)
			return false;
		const Measurement &Z = m_Zs[iZ];
		for(int _iLvl = 0; _iLvl < FRM_IP_LEVELS; ++_iLvl)
		{
			const std::vector<FTR::Measurement>::const_iterator iz1 = m_zs.begin() + Z.m_izIP[_iLvl], iz2 = m_zs.begin() + Z.m_izIP[_iLvl + 1];
			const std::vector<FTR::Measurement>::const_iterator _iz = std::lower_bound(iz1, iz2, ix);
			if(_iz != iz2 && _iz->m_ix == ix)
			{
				iz = int(_iz - m_zs.begin());
				iLvl = _iLvl;
				return true;
			}
		}
		return false;
	}
#endif
    inline int SearchFeatureMeasurementLevel(const int iz) const
    {
#ifdef CFG_DEBUG
        UT_ASSERT(iz < int(m_zs.size()));
#endif
        const int NZ = int(m_Zs.size());
        for (int iZ = 0; iZ < NZ; ++iZ) {
            const Measurement &Z = m_Zs[iZ];
            if (Z.m_izIP[FRM_IP_LEVELS] <= iz) continue;
            for (int iLvl = 0; iLvl < FRM_IP_LEVELS; ++iLvl) {
                if (Z.m_izIP[iLvl + 1] > iz) return iLvl;
            }
        }
        return -1;
    }
    inline void SearchFeatureMeasurementMatches(
        const Frame &F, std::vector<FTR::Measurement::Match> &izms) const
    {
        izms.resize(0);
        const int NZ1 = int(m_Zs.size());
        for (int iZ1 = 0; iZ1 < NZ1; ++iZ1) {
            const Measurement &Z1 = m_Zs[iZ1];
            const int iZ2 = F.SearchFrameMeasurement(Z1.m_iKF);
            if (iZ2 == -1) continue;
            const Measurement &Z2 = F.m_Zs[iZ2];
            const std::vector<FTR::Measurement>::const_iterator
                iz21 = F.m_zs.begin() + Z2.m_izIP[0],
                iz22 = F.m_zs.begin() + Z2.m_izIP[FRM_IP_LEVELS];
            const int iz11 = Z1.m_izIP[0], iz12 = Z1.m_izIP[FRM_IP_LEVELS];
            for (int iz1 = iz11; iz1 < iz12; ++iz1) {
                const int ix = m_zs[iz1].m_ix;
                const std::vector<FTR::Measurement>::const_iterator iz2 =
                    std::lower_bound(iz21, iz22, ix);
                if (iz2 != iz22 && iz2->m_ix == ix)
                    izms.push_back(FTR::Measurement::Match(
                        iz1, int(iz2 - F.m_zs.begin())));
            }
        }
    }
    inline int CountFeatureMeasurements(const int iLvl) const
    {
        int SN = 0;
        const int NZ = int(m_Zs.size());
        for (int iZ = 0; iZ < NZ; ++iZ) {
            const Measurement &Z = m_Zs[iZ];
            SN += Z.m_izIP[iLvl + 1] - Z.m_izIP[iLvl];
        }
        return SN;
    }
    inline void PyramidToFirstLevel()
    {
        const int NZ = int(m_Zs.size());
        for (int iZ = 0; iZ < NZ; ++iZ) {
            Measurement &Z = m_Zs[iZ];
            const int iz1 = Z.m_izIP[0], iz2 = Z.m_izIP[FRM_IP_LEVELS];
            for (int iLvl = 1; iLvl < FRM_IP_LEVELS; ++iLvl)
                Z.m_izIP[iLvl] = iz2;
            std::sort(m_zs.begin() + iz1, m_zs.begin() + iz2);
        }
    }
    inline void SaveB(FILE *fp) const
    {
        m_T.SaveB(fp);
        UT::VectorSaveB(m_Zs, fp);
        UT::VectorSaveB(m_zs, fp);
        UT::VectorSaveB(m_iKFsMatch, fp);
    }
    inline void LoadB(FILE *fp)
    {
        m_T.LoadB(fp);
        UT::VectorLoadB(m_Zs, fp);
        UT::VectorLoadB(m_zs, fp);
        UT::VectorLoadB(m_iKFsMatch, fp);
    }
    inline void AssertConsistency() const
    {
        const int NZ = int(m_Zs.size());
        if (NZ == 0) return;
        for (int iZ = 0; iZ < NZ; ++iZ) m_Zs[iZ].AssertConsistency();
        UT_ASSERT(m_Zs.front().m_izIP[0] == 0);
        for (int iZ = 1; iZ < NZ; ++iZ) {
            const Measurement &Z1 = m_Zs[iZ - 1], &Z2 = m_Zs[iZ];
            UT_ASSERT(Z1.m_iKF < Z2.m_iKF);
            UT_ASSERT(Z1.m_izIP[FRM_IP_LEVELS] == Z2.m_izIP[0]);
        }
        UT_ASSERT(m_Zs.back().m_izIP[FRM_IP_LEVELS] == int(m_zs.size()));
        const int nKFsMatch = int(m_iKFsMatch.size());
        for (int i = 1; i < nKFsMatch; ++i)
            UT_ASSERT(m_iKFsMatch[i - 1] < m_iKFsMatch[i]);
        std::vector<int>::const_iterator ik = m_iKFsMatch.begin();
        for (int iZ = 0; iZ < NZ; ++iZ) {
            const Measurement &Z = m_Zs[iZ];
            for (int iLvl = 0; iLvl < FRM_IP_LEVELS; ++iLvl) {
                const int iz1 = Z.m_izIP[iLvl], iz2 = Z.m_izIP[iLvl + 1];
                for (int iz = iz1 + 1; iz < iz2; ++iz)
                    UT_ASSERT(m_zs[iz - 1].m_ix < m_zs[iz].m_ix);
            }
            ik = std::lower_bound(ik, m_iKFsMatch.end(), Z.m_iKF);
            UT_ASSERT(ik != m_iKFsMatch.end() && *ik == Z.m_iKF);
        }
    }

  public:
    // frame tag info
    Tag m_T;
    // measurements start index (store each matched frames by pyramid level)
    std::vector<Measurement> m_Zs;
    // feature measurements
    std::vector<FTR::Measurement> m_zs;
    // matched keyframe's index
    std::vector<int> m_iKFsMatch;
};

namespace ALN
{
class Jacobian
{
  public:
    inline bool Empty() const { return m_jxrs.Empty(); }
    inline void Resize(const int N)
    {
        m_jxrs.Resize(N);
        m_jxhs.Resize(N);
    }

  public:
    AlignedVector<LA::AlignedMatrix2x3f> m_jxrs;
    AlignedVector<LA::AlignedMatrix2x4f> m_jxhs;
};

class Factor
{
  public:
    class Data3
    {
        struct CanNotMakeAnonymous {
            LA::AlignedVector3f m_j;
            LA::SymmetricMatrix3x3f m_a;
        };

      public:
        CanNotMakeAnonymous fe;
        _pi__m128 m_data[3];
    };
    class Data6
    {
        struct CanNotMakeAnonymous {
            LA::AlignedVector6f m_j;
            LA::SymmetricMatrix3x3f m_arr, m_app;
            LA::Matrix3x3f m_arp;
        };

      public:
        CanNotMakeAnonymous fe;
        _pi__m128 m_data[8];
    };
    class Data8
    {
      public:
        LA::AlignedVector8f m_j;
        LA::SymmetricMatrix8x8f m_a;
    };

  public:
    inline void Resize(const int N)
    {
        m_ars.Resize(N);
        m_ahs.Resize(N);
#ifdef FRM_ALN_DECOUPLE_RIGID
        m_aps.Resize(N);
#else
        m_arps.Resize(N);
#endif
    }

  public:
    AlignedVector<Data3> m_ars;
    AlignedVector<Data8> m_ahs;
#ifdef FRM_ALN_DECOUPLE_RIGID
    AlignedVector<Data3> m_aps;
#else
    AlignedVector<Data6> m_arps;
#endif
};

class MatchList
{
  public:
    inline MatchList(AlignedVector<Point2D> &x1s, AlignedVector<Point2D> &x2s)
        : m_x1s(x1s), m_x2s(x2s)
    {
    }
    inline int Size() const { return m_x1s.Size(); }
  public:
    AlignedVector<Point2D> m_x1s, m_x2s;
};
}
}

#endif


// Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen

#if os(OSX)
  import AppKit.NSColor
  internal typealias Color = NSColor
#elseif os(iOS) || os(tvOS) || os(watchOS)
  import UIKit.UIColor
  internal typealias Color = UIColor
#endif

// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length

// swiftlint:disable operator_usage_whitespace
internal extension Color {
  convenience init(rgbaValue: UInt32) {
    let red   = CGFloat((rgbaValue >> 24) & 0xff) / 255.0
    let green = CGFloat((rgbaValue >> 16) & 0xff) / 255.0
    let blue  = CGFloat((rgbaValue >>  8) & 0xff) / 255.0
    let alpha = CGFloat((rgbaValue      ) & 0xff) / 255.0

    self.init(red: red, green: green, blue: blue, alpha: alpha)
  }
}
// swiftlint:enable operator_usage_whitespace

// swiftlint:disable identifier_name line_length type_body_length
internal struct ColorName {
  internal let rgbaValue: UInt32
  internal var color: Color { return Color(named: self) }

  ///
  /// Alpha: 100%
 (0xc0392bff)
  internal static let errorMessageBackground = ColorName(rgbaValue: 0xc0392bff)
  ///
  /// Alpha: 100%
 (0xffffccff)
  internal static let favoriteBackground = ColorName(rgbaValue: 0xffffccff)
  ///
  /// Alpha: 100%
 (0xc05d5dff)
  internal static let navigationBackground = ColorName(rgbaValue: 0xc05d5dff)
  ///
  /// Alpha: 100%
 (0x27ae60ff)
  internal static let onlineMessageBackground = ColorName(rgbaValue: 0x27ae60ff)
}
// swiftlint:enable identifier_name line_length type_body_length

internal extension Color {
  convenience init(named color: ColorName) {
    self.init(rgbaValue: color.rgbaValue)
  }
}


Timezone
========

Validates that a value is a valid timezone identifier (e.g. ``Europe/Paris``).

==========  ======================================================================
Applies to  :ref:`property or method <validation-property-target>`
Options     - `countryCode`_
            - `groups`_
            - `intlCompatible`_
            - `message`_
            - `payload`_
            - `zone`_
Class       :class:`Symfony\\Component\\Validator\\Constraints\\Timezone`
Validator   :class:`Symfony\\Component\\Validator\\Constraints\\TimezoneValidator`
==========  ======================================================================

Basic Usage
-----------

Suppose you have a ``UserSettings`` class, with a ``timezone`` field that is a
string which contains any of the `PHP timezone identifiers`_ (e.g. ``America/New_York``):

.. configuration-block::

    .. code-block:: php-annotations

        // src/Entity/UserSettings.php
        namespace App\Entity;

        use Symfony\Component\Validator\Constraints as Assert;

        class UserSettings
        {
            /**
             * @Assert\Timezone
             */
            protected $timezone;
        }

    .. code-block:: yaml

        # config/validator/validation.yaml
        App\Entity\UserSettings:
            properties:
                timezone:
                    - Timezone: ~

    .. code-block:: xml

        <!-- config/validator/validation.xml -->
        <?xml version="1.0" encoding="UTF-8" ?>
        <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

            <class name="App\Entity\UserSettings">
                <property name="timezone">
                    <constraint name="Timezone"/>
                </property>
            </class>
        </constraint-mapping>

    .. code-block:: php

        // src/Entity/UserSettings.php
        namespace App\Entity;

        use Symfony\Component\Validator\Constraints as Assert;
        use Symfony\Component\Validator\Mapping\ClassMetadata;

        class UserSettings
        {
            public static function loadValidatorMetadata(ClassMetadata $metadata)
            {
                $metadata->addPropertyConstraint('timezone', new Assert\Timezone());
            }
        }

.. include:: /reference/constraints/_empty-values-are-valid.rst.inc

Options
-------

countryCode
~~~~~~~~~~~

**type**: ``string`` **default**: ``null``

If the ``zone`` option is set to ``\DateTimeZone::PER_COUNTRY``, this option
restricts the valid timezone identifiers to the ones that belong to the given
country.

The value of this option must be a valid `ISO 3166-1 alpha-2`_ country code
(e.g. ``CN`` for China).

.. include:: /reference/constraints/_groups-option.rst.inc

intlCompatible
~~~~~~~~~~~~~~

**type**: ``boolean`` **default**: ``false``

This constraint considers valid both the `PHP timezone identifiers`_ and the
:ref:`ICU timezones <component-intl-timezones>` provided by Symfony's
:doc:`Intl component </components/intl>`

However, the timezones provided by the Intl component can be different from the
timezones provided by PHP's Intl extension (because they use different ICU
versions). If this option is set to ``true``, this constraint only considers
valid the values compatible with the PHP ``\IntlTimeZone::createTimeZone()`` method.

message
~~~~~~~

**type**: ``string`` **default**: ``This value is not a valid timezone.``

This message is shown if the underlying data is not a valid timezone identifier.

You can use the following parameters in this message:

===============  ==============================================================
Parameter        Description
===============  ==============================================================
``{{ value }}``  The current (invalid) value
``{{ label }}``  Corresponding form field label
===============  ==============================================================

.. versionadded:: 5.2

    The ``{{ label }}`` parameter was introduced in Symfony 5.2.

.. include:: /reference/constraints/_payload-option.rst.inc

zone
~~~~

**type**: ``string`` **default**: ``\DateTimeZone::ALL``

Set this option to any of the following constants to restrict the valid timezone
identifiers to the ones that belong to that geographical zone:

* ``\DateTimeZone::AFRICA``
* ``\DateTimeZone::AMERICA``
* ``\DateTimeZone::ANTARCTICA``
* ``\DateTimeZone::ARCTIC``
* ``\DateTimeZone::ASIA``
* ``\DateTimeZone::ATLANTIC``
* ``\DateTimeZone::AUSTRALIA``
* ``\DateTimeZone::EUROPE``
* ``\DateTimeZone::INDIAN``
* ``\DateTimeZone::PACIFIC``

In addition, there are some special zone values:

* ``\DateTimeZone::ALL`` accepts any timezone excluding deprecated timezones;
* ``\DateTimeZone::ALL_WITH_BC`` accepts any timezone including deprecated
  timezones;
* ``\DateTimeZone::PER_COUNTRY`` restricts the valid timezones to a certain
  country (which is defined using the ``countryCode`` option).

.. _`PHP timezone identifiers`: https://www.php.net/manual/en/timezones.php
.. _`ISO 3166-1 alpha-2`: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2


/// <reference types="react-scripts" />


let assert = require('assert').deepStrictEqual

function Product(name, price) {
  this.name = name
  this.price = price
}

function Food(name, price) {
  Product.call(this, name, price)
  this.category = 'food'
}

assert(new Food('cheese', 5).name, 'cheese')
// expected output: "cheese"


// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build arm,freebsd

package unix

import (
	"syscall"
	"unsafe"
)

func setTimespec(sec, nsec int64) Timespec {
	return Timespec{Sec: sec, Nsec: int32(nsec)}
}

func setTimeval(sec, usec int64) Timeval {
	return Timeval{Sec: sec, Usec: int32(usec)}
}

func SetKevent(k *Kevent_t, fd, mode, flags int) {
	k.Ident = uint32(fd)
	k.Filter = int16(mode)
	k.Flags = uint16(flags)
}

func (iov *Iovec) SetLen(length int) {
	iov.Len = uint32(length)
}

func (msghdr *Msghdr) SetControllen(length int) {
	msghdr.Controllen = uint32(length)
}

func (cmsg *Cmsghdr) SetLen(length int) {
	cmsg.Len = uint32(length)
}

func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
	var writtenOut uint64 = 0
	_, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr((*offset)>>32), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0)

	written = int(writtenOut)

	if e1 != 0 {
		err = e1
	}
	return
}

func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)


// 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.
//
// The following only applies to changes made to this file as part of YugaByte development.
//
// Portions Copyright (c) YugaByte, 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.
//
#ifndef YB_CONSENSUS_CONSENSUS_H_
#define YB_CONSENSUS_CONSENSUS_H_

#include <iosfwd>
#include <ostream>
#include <memory>
#include <string>
#include <vector>

#include <boost/optional/optional_fwd.hpp>

#include "yb/common/hybrid_time.h"

#include "yb/consensus/consensus_fwd.h"
#include "yb/consensus/consensus_types.h"
#include "yb/consensus/consensus.pb.h"
#include "yb/consensus/opid_util.h"

#include "yb/gutil/callback.h"
#include "yb/gutil/gscoped_ptr.h"
#include "yb/gutil/ref_counted.h"
#include "yb/gutil/stringprintf.h"
#include "yb/gutil/strings/substitute.h"

#include "yb/util/enums.h"
#include "yb/util/monotime.h"
#include "yb/util/opid.h"
#include "yb/util/status.h"
#include "yb/util/status_callback.h"
#include "yb/util/strongly_typed_bool.h"

namespace yb {

namespace log {
class Log;
}

namespace master {
class SysCatalogTable;
}

namespace server {
class Clock;
}

namespace tablet {
class TabletPeer;
}

namespace tserver {
class TabletServerErrorPB;
}

namespace consensus {

typedef int64_t ConsensusTerm;

typedef std::function<void(
    const Status& status, int64_t leader_term, OpIds* applied_op_ids)>
        ConsensusReplicatedCallback;

// After completing bootstrap, some of the results need to be plumbed through
// into the consensus implementation.
struct ConsensusBootstrapInfo {
  ConsensusBootstrapInfo();

  // The id of the last operation in the log
  OpIdPB last_id;

  // The id of the last committed operation in the log.
  OpIdPB last_committed_id;

  // The id of the split operation designated for this tablet added to Raft log.
  // See comments for ReplicateState::split_op_id_.
  OpIdPB split_op_id;

  // REPLICATE messages which were in the log with no accompanying
  // COMMIT. These need to be passed along to consensus init in order
  // to potentially commit them.
  //
  // These are owned by the ConsensusBootstrapInfo instance.
  ReplicateMsgs orphaned_replicates;

 private:
  DISALLOW_COPY_AND_ASSIGN(ConsensusBootstrapInfo);
};

struct LeaderState;

// Mode is orthogonal to pre-elections, so any combination could be used.
YB_DEFINE_ENUM(ElectionMode,
    // A normal leader election. Peers will not vote for this node
    // if they believe that a leader is alive.
    (NORMAL_ELECTION)
    // In this mode, peers will vote for this candidate even if they
    // think a leader is alive. This can be used for a faster hand-off
    // between a leader and one of its replicas.
    (ELECT_EVEN_IF_LEADER_IS_ALIVE));

// Arguments for StartElection.
struct LeaderElectionData {
  ElectionMode mode;

  // pending_commit - we should start election only after we have specified entry committed.
  const bool pending_commit = false;

  // must_be_committed_opid - only matters if pending_commit is true.
  //    If this is specified, we would wait until this entry is committed. If not specified
  //    (i.e. if this has the default OpId value) it is taken from the last call to StartElection
  //    with pending_commit = true.
  OpIdPB must_be_committed_opid = OpIdPB::default_instance();

  // originator_uuid - if election is initiated by an old leader as part of a stepdown procedure,
  //    this would contain the uuid of the old leader.
  std::string originator_uuid = std::string();

  TEST_SuppressVoteRequest suppress_vote_request = TEST_SuppressVoteRequest::kFalse;

  std::string ToString() const;
};

// The external interface for a consensus peer.
//
// Note: Even though Consensus points to Log, it needs to be destroyed
// after it. See Log class header comment for the reason why. On the other
// hand Consensus must be quiesced before closing the log, otherwise it
// will try to write to a destroyed/closed log.
//
// The order of these operations on shutdown must therefore be:
// 1 - quiesce Consensus
// 2 - close/destroy Log
// 3 - destroy Consensus
class Consensus {
 public:
  class ConsensusFaultHooks;

  Consensus() {}
  virtual ~Consensus() {}

  // Starts running the consensus algorithm.
  virtual CHECKED_STATUS Start(const ConsensusBootstrapInfo& info) = 0;

  // Returns true if consensus is running.
  virtual bool IsRunning() const = 0;

  // Emulates a leader election by simply making this peer leader.
  virtual CHECKED_STATUS EmulateElection() = 0;

  virtual CHECKED_STATUS StartElection(const LeaderElectionData& data) = 0;

  // We tried to step down, so you protege become leader.
  // But it failed to win election, so we should reset our withhold time and try to reelect ourself.
  // election_lost_by_uuid - uuid of protege that lost election.
  virtual CHECKED_STATUS ElectionLostByProtege(const std::string& election_lost_by_uuid) = 0;

  // Implement a LeaderStepDown() request.
  virtual CHECKED_STATUS StepDown(const LeaderStepDownRequestPB* req,
                                  LeaderStepDownResponsePB* resp) {
    return STATUS(NotSupported, "Not implemented.");
  }

  // Wait until the node has LEADER role.
  // Returns Status::TimedOut if the role is not LEADER within 'timeout'.
  virtual CHECKED_STATUS WaitUntilLeaderForTests(const MonoDelta& timeout) = 0;

  // Creates a new ConsensusRound, the entity that owns all the data
  // structures required for a consensus round, such as the ReplicateMsg.
  // ConsensusRound will also point to and increase the reference count for the provided callbacks.
  ConsensusRoundPtr NewRound(
      ReplicateMsgPtr replicate_msg,
      const ConsensusReplicatedCallback& replicated_cb);

  // Called by a Leader to replicate an entry to the state machine.
  //
  // From the leader instance perspective execution proceeds as follows:
  //
  //           Leader                               RaftConfig
  //             +                                     +
  //     1) Req->| Replicate()                         |
  //             |                                     |
  //     2)      +-------------replicate-------------->|
  //             |<---------------ACK------------------+
  //             |                                     |
  //     3)      +--+                                  |
  //           <----+ round.NotifyReplicationFinished()|
  //             |                                     |
  //     3a)     |  +------ update commitIndex ------->|
  //             |                                     |
  //
  // 1) Caller calls Replicate(), method returns immediately to the caller and
  //    runs asynchronously.
  //
  // 2) Leader replicates the entry to the peers using the consensus
  //    algorithm, proceeds as soon as a majority of voters acknowledges the
  //    entry.
  //
  // 3) Leader defers to the caller by calling ConsensusRound::NotifyReplicationFinished,
  //    which calls the ConsensusReplicatedCallback.
  //
  // 3a) The leader asynchronously notifies other peers of the new
  //     commit index, which tells them to apply the operation.
  //
  // This method can only be called on the leader, i.e. role() == LEADER

  virtual CHECKED_STATUS TEST_Replicate(const ConsensusRoundPtr& round) = 0;

  // A batch version of Replicate, which is what we try to use as much as possible for performance.
  virtual CHECKED_STATUS ReplicateBatch(ConsensusRounds* rounds) = 0;

  // Messages sent from LEADER to FOLLOWERS and LEARNERS to update their
  // state machines. This is equivalent to "AppendEntries()" in Raft
  // terminology.
  //
  // ConsensusRequestPB contains a sequence of 0 or more operations to apply
  // on the replica. If there are 0 operations the request is considered
  // 'status-only' i.e. the leader is communicating with the follower only
  // in order to pass back and forth information on watermarks (eg committed
  // operation ID, replicated op id, etc).
  //
  // If the sequence contains 1 or more operations they will be replicated
  // in the same order as the leader, and submitted for asynchronous Prepare
  // in the same order.
  //
  // The leader also provides information on the index of the latest
  // operation considered committed by consensus. The replica uses this
  // information to update the state of any pending (previously replicated/prepared)
  // transactions.
  //
  // Returns Status::OK if the response has been filled (regardless of accepting
  // or rejecting the specific request). Returns non-OK Status if a specific
  // error response could not be formed, which will result in the service
  // returning an UNKNOWN_ERROR RPC error code to the caller and including the
  // stringified Status message.
  virtual CHECKED_STATUS Update(
      ConsensusRequestPB* request,
      ConsensusResponsePB* response,
      CoarseTimePoint deadline) = 0;

  // Messages sent from CANDIDATEs to voting peers to request their vote
  // in leader election.
  virtual CHECKED_STATUS RequestVote(const VoteRequestPB* request,
                                     VoteResponsePB* response) = 0;

  // Implement a ChangeConfig() request.
  virtual CHECKED_STATUS ChangeConfig(const ChangeConfigRequestPB& req,
                                      const StdStatusCallback& client_cb,
                                      boost::optional<tserver::TabletServerErrorPB::Code>* error) {
    return STATUS(NotSupported, "Not implemented.");
  }

  // Returns the current Raft role of this instance.
  virtual RaftPeerPB::Role role() const = 0;

  // Returns the leader status (see LeaderStatus type description for details).
  // If leader is ready, then also returns term, otherwise OpId::kUnknownTerm is returned.
  //
  // allow_stale could be used to avoid refreshing cache, when we are OK to read slightly outdated
  // value.
  virtual LeaderState GetLeaderState(bool allow_stale = false) const = 0;

  LeaderStatus GetLeaderStatus(bool allow_stale = false) const;
  int64_t LeaderTerm() const;

  // Returns the uuid of this peer.
  virtual std::string peer_uuid() const = 0;

  // Returns the id of the tablet whose updates this consensus instance helps coordinate.
  virtual std::string tablet_id() const = 0;

  // Returns a copy of the committed state of the Consensus system. Also allows returning the
  // leader lease status captured under the same lock.
  virtual ConsensusStatePB ConsensusState(
      ConsensusConfigType type,
      LeaderLeaseStatus* leader_lease_status = nullptr) const = 0;

  // Returns a copy of the committed state of the Consensus system, assuming caller holds the needed
  // locks.
  virtual ConsensusStatePB ConsensusStateUnlocked(
      ConsensusConfigType type,
      LeaderLeaseStatus* leader_lease_status = nullptr) const = 0;

  // Returns a copy of the current committed Raft configuration.
  virtual RaftConfigPB CommittedConfig() const = 0;

  virtual void DumpStatusHtml(std::ostream& out) const = 0;

  void SetFaultHooks(const std::shared_ptr<ConsensusFaultHooks>& hooks);

  const std::shared_ptr<ConsensusFaultHooks>& GetFaultHooks() const;

  // Stops running the consensus algorithm.
  virtual void Shutdown() = 0;

  // Returns the last OpId (either received or committed, depending on the 'type' argument) that the
  // Consensus implementation knows about.  Primarily used for testing purposes.
  Result<yb::OpId> GetLastOpId(OpIdType type);

  virtual yb::OpId GetLastReceivedOpId() = 0;

  virtual yb::OpId GetLastCommittedOpId() = 0;

  virtual yb::OpId GetLastAppliedOpId() = 0;

  // Return the ID of the split operation requesting to split this Raft group if it has been added
  // to Raft log and uninitialized OpId otherwise.
  virtual yb::OpId GetSplitOpId() = 0;

  // Assuming we are the leader, wait until we have a valid leader lease (i.e. the old leader's
  // lease has expired, and we have replicated a new lease that has not expired yet).
  virtual CHECKED_STATUS WaitForLeaderLeaseImprecise(CoarseTimePoint deadline) = 0;

  // Check that this Consensus is a leader and has lease, returns Status::OK in this case.
  // Otherwise error status is returned.
  virtual CHECKED_STATUS CheckIsActiveLeaderAndHasLease() const = 0;

  // Returns majority replicated ht lease, so we know that after leader change
  // operations would not be added with hybrid time below this lease.
  //
  // `min_allowed` - result should be greater or equal to `min_allowed`, otherwise
  // it tries to wait until ht lease reaches this value or `deadline` happens.
  //
  // Returns 0 if timeout happened.
  virtual MicrosTime MajorityReplicatedHtLeaseExpiration(
      MicrosTime min_allowed, CoarseTimePoint deadline) const = 0;

  // Read majority replicated messages for CDC producer.
  virtual Result<ReadOpsResult> ReadReplicatedMessagesForCDC(const yb::OpId& from,
                                                             int64_t* repl_index) = 0;

  virtual void UpdateCDCConsumerOpId(const yb::OpId& op_id) = 0;

 protected:
  friend class RefCountedThreadSafe<Consensus>;
  friend class tablet::TabletPeer;
  friend class master::SysCatalogTable;

  // Fault hooks for tests. In production code this will always be null.
  std::shared_ptr<ConsensusFaultHooks> fault_hooks_;

  enum HookPoint {
    PRE_START,
    POST_START,
    PRE_CONFIG_CHANGE,
    POST_CONFIG_CHANGE,
    PRE_REPLICATE,
    POST_REPLICATE,
    PRE_COMMIT,
    POST_COMMIT,
    PRE_UPDATE,
    POST_UPDATE,
    PRE_SHUTDOWN,
    POST_SHUTDOWN
  };

  CHECKED_STATUS ExecuteHook(HookPoint point);

  enum State {
    kNotInitialized,
    kInitializing,
    kConfiguring,
    kRunning,
  };

 private:
  DISALLOW_COPY_AND_ASSIGN(Consensus);
};

YB_DEFINE_ENUM(StateChangeReason,
    (INVALID_REASON)
    (TABLET_PEER_STARTED)
    (CONSENSUS_STARTED)
    (NEW_LEADER_ELECTED)
    (FOLLOWER_NO_OP_COMPLETE)
    (LEADER_CONFIG_CHANGE_COMPLETE)
    (FOLLOWER_CONFIG_CHANGE_COMPLETE));

// Context provided for callback on master/tablet-server peer state change for post processing
// e.g., update in-memory contents.
struct StateChangeContext {

  const StateChangeReason reason;

  explicit StateChangeContext(StateChangeReason in_reason)
      : reason(in_reason) {
  }

  StateChangeContext(StateChangeReason in_reason, bool is_locked)
      : reason(in_reason),
        is_config_locked_(is_locked) {
  }

  StateChangeContext(StateChangeReason in_reason, string uuid)
      : reason(in_reason),
        new_leader_uuid(uuid) {
  }

  StateChangeContext(StateChangeReason in_reason,
                     ChangeConfigRecordPB change_rec,
                     string remove = "")
      : reason(in_reason),
        change_record(change_rec),
        remove_uuid(remove) {
  }

  bool is_config_locked() const {
    return is_config_locked_;
  }

  ~StateChangeContext() {}

  std::string ToString() const {
    switch (reason) {
      case StateChangeReason::TABLET_PEER_STARTED:
        return "Started TabletPeer";
      case StateChangeReason::CONSENSUS_STARTED:
        return "RaftConsensus started";
      case StateChangeReason::NEW_LEADER_ELECTED:
        return strings::Substitute("New leader $0 elected", new_leader_uuid);
      case StateChangeReason::FOLLOWER_NO_OP_COMPLETE:
        return "Replicate of NO_OP complete on follower";
      case StateChangeReason::LEADER_CONFIG_CHANGE_COMPLETE:
        return strings::Substitute("Replicated change config $0 round complete on leader",
          change_record.ShortDebugString());
      case StateChangeReason::FOLLOWER_CONFIG_CHANGE_COMPLETE:
        return strings::Substitute("Config change $0 complete on follower",
          change_record.ShortDebugString());
      case StateChangeReason::INVALID_REASON: FALLTHROUGH_INTENDED;
      default:
        return "INVALID REASON";
    }
  }

  // Auxiliary info for some of the reasons above.
  // Value is filled when the change reason is NEW_LEADER_ELECTED.
  const string new_leader_uuid;

  // Value is filled when the change reason is LEADER/FOLLOWER_CONFIG_CHANGE_COMPLETE.
  const ChangeConfigRecordPB change_record;

  // Value is filled when the change reason is LEADER_CONFIG_CHANGE_COMPLETE
  // and it is a REMOVE_SERVER, then that server's uuid is saved here by the master leader.
  const string remove_uuid;

  // If this is true, the call-stack above has taken the lock for the raft consensus state. Needed
  // in SysCatalogStateChanged for master to not re-get the lock. Not used for tserver callback.
  // Note that the state changes using the UpdateConsensus() mechanism always hold the lock, so
  // defaulting to true as they are majority. For ones that do not hold the lock, setting
  // it to false in their constructor suffices currently, so marking it const.
  const bool is_config_locked_ = true;
};

// Context for a consensus round on the LEADER side, typically created as an
// out-parameter of Consensus::Append.
// This class is ref-counted because we want to ensure it stays alive for the
// duration of the Operation when it is associated with a Operation, while
// we also want to ensure it has a proper lifecycle when a ConsensusRound is
// pushed that is not associated with a Tablet transaction.
class ConsensusRound : public RefCountedThreadSafe<ConsensusRound> {
 public:
  static constexpr int64_t kUnboundTerm = -1;

  // Ctor used for leader transactions. Leader transactions can and must specify the
  // callbacks prior to initiating the consensus round.
  ConsensusRound(Consensus* consensus,
                 ReplicateMsgPtr replicate_msg,
                 ConsensusReplicatedCallback replicated_cb);

  // Ctor used for follower/learner transactions. These transactions do not use the
  // replicate callback and the commit callback is set later, after the transaction
  // is actually started.
  ConsensusRound(Consensus* consensus, ReplicateMsgPtr replicate_msg);

  std::string ToString() const {
    return replicate_msg_->ShortDebugString();
  }

  const ReplicateMsgPtr& replicate_msg() {
    return replicate_msg_;
  }

  // Returns the id of the (replicate) operation this context
  // refers to. This is only set _after_ Consensus::Replicate(context).
  OpIdPB id() const {
    return replicate_msg_->id();
  }

  // Register a callback that is called by Consensus to notify that the round
  // is considered either replicated, if 'status' is OK(), or that it has
  // permanently failed to replicate if 'status' is anything else. If 'status'
  // is OK() then the operation can be applied to the state machine, otherwise
  // the operation should be aborted.
  void SetConsensusReplicatedCallback(ConsensusReplicatedCallback replicated_cb) {
    replicated_cb_ = std::move(replicated_cb);
  }

  void SetAppendCallback(ConsensusAppendCallback* append_cb) {
    append_cb_ = append_cb;
  }

  ConsensusAppendCallback* append_callback() {
    return append_cb_;
  }

  // If a continuation was set, notifies it that the round has been replicated.
  void NotifyReplicationFinished(
      const Status& status, int64_t leader_term, OpIds* applied_op_ids);

  // Binds this round such that it may not be eventually executed in any term
  // other than 'term'.
  // See CheckBoundTerm().
  void BindToTerm(int64_t term) {
    DCHECK_EQ(bound_term_, kUnboundTerm);
    bound_term_ = term;
  }

  // Check for a rare race in which an operation is submitted to the LEADER in some term,
  // then before the operation is prepared, the replica loses its leadership, receives
  // more operations as a FOLLOWER, and then regains its leadership. We detect this case
  // by setting the ConsensusRound's "bound term" when it is first submitted to the
  // PREPARE queue, and validate that the term is still the same when we have finished
  // preparing it. See KUDU-597 for details.
  //
  // If this round has not been bound to any term, this is a no-op.
  CHECKED_STATUS CheckBoundTerm(int64_t current_term) const;

  int64_t bound_term() { return bound_term_; }

 private:
  friend class RaftConsensusQuorumTest;
  friend class RefCountedThreadSafe<ConsensusRound>;

  ~ConsensusRound() {}

  Consensus* consensus_;
  // This round's replicate message.
  ReplicateMsgPtr replicate_msg_;

  // The continuation that will be called once the transaction is
  // deemed committed/aborted by consensus.
  ConsensusReplicatedCallback replicated_cb_;

  // The leader term that this round was submitted in. CheckBoundTerm()
  // ensures that, when it is eventually replicated, the term has not
  // changed in the meantime.
  //
  // Set to -1 if no term has been bound.
  int64_t bound_term_ = kUnboundTerm;

  ConsensusAppendCallback* append_cb_ = nullptr;
};

class Consensus::ConsensusFaultHooks {
 public:
  virtual CHECKED_STATUS PreStart() { return Status::OK(); }
  virtual CHECKED_STATUS PostStart() { return Status::OK(); }
  virtual CHECKED_STATUS PreConfigChange() { return Status::OK(); }
  virtual CHECKED_STATUS PostConfigChange() { return Status::OK(); }
  virtual CHECKED_STATUS PreReplicate() { return Status::OK(); }
  virtual CHECKED_STATUS PostReplicate() { return Status::OK(); }
  virtual CHECKED_STATUS PreUpdate() { return Status::OK(); }
  virtual CHECKED_STATUS PostUpdate() { return Status::OK(); }
  virtual CHECKED_STATUS PreShutdown() { return Status::OK(); }
  virtual CHECKED_STATUS PostShutdown() { return Status::OK(); }
  virtual ~ConsensusFaultHooks() {}
};

class SafeOpIdWaiter {
 public:
  virtual yb::OpId WaitForSafeOpIdToApply(const yb::OpId& op_id) = 0;

 protected:
  ~SafeOpIdWaiter() {}
};

struct LeaderState {
  LeaderStatus status;
  int64_t term;
  MonoDelta remaining_old_leader_lease;

  LeaderState& MakeNotReadyLeader(LeaderStatus status);

  bool ok() const {
    return status == LeaderStatus::LEADER_AND_READY;
  }

  CHECKED_STATUS CreateStatus() const;
};

inline CHECKED_STATUS MoveStatus(LeaderState&& state) {
  return state.CreateStatus();
}

} // namespace consensus
} // namespace yb

#endif // YB_CONSENSUS_CONSENSUS_H_


// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2014 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_CWISE_UNARY_OP_H
#define EIGEN_CWISE_UNARY_OP_H

namespace Eigen {

namespace internal {
template<typename UnaryOp, typename XprType>
struct traits<CwiseUnaryOp<UnaryOp, XprType> >
 : traits<XprType>
{
  typedef typename result_of<
                     UnaryOp(const typename XprType::Scalar&)
                   >::type Scalar;
  typedef typename XprType::Nested XprTypeNested;
  typedef typename remove_reference<XprTypeNested>::type _XprTypeNested;
  enum {
    Flags = _XprTypeNested::Flags & RowMajorBit
  };
};
}

template<typename UnaryOp, typename XprType, typename StorageKind>
class CwiseUnaryOpImpl;

/** \class CwiseUnaryOp
  * \ingroup Core_Module
  *
  * \brief Generic expression where a coefficient-wise unary operator is applied to an expression
  *
  * \tparam UnaryOp template functor implementing the operator
  * \tparam XprType the type of the expression to which we are applying the unary operator
  *
  * This class represents an expression where a unary operator is applied to an expression.
  * It is the return type of all operations taking exactly 1 input expression, regardless of the
  * presence of other inputs such as scalars. For example, the operator* in the expression 3*matrix
  * is considered unary, because only the right-hand side is an expression, and its
  * return type is a specialization of CwiseUnaryOp.
  *
  * Most of the time, this is the only way that it is used, so you typically don't have to name
  * CwiseUnaryOp types explicitly.
  *
  * \sa MatrixBase::unaryExpr(const CustomUnaryOp &) const, class CwiseBinaryOp, class CwiseNullaryOp
  */
template<typename UnaryOp, typename XprType>
class CwiseUnaryOp : public CwiseUnaryOpImpl<UnaryOp, XprType, typename internal::traits<XprType>::StorageKind>, internal::no_assignment_operator
{
  public:

    typedef typename CwiseUnaryOpImpl<UnaryOp, XprType,typename internal::traits<XprType>::StorageKind>::Base Base;
    EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseUnaryOp)
    typedef typename internal::ref_selector<XprType>::type XprTypeNested;
    typedef typename internal::remove_all<XprType>::type NestedExpression;

    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
    explicit CwiseUnaryOp(const XprType& xpr, const UnaryOp& func = UnaryOp())
      : m_xpr(xpr), m_functor(func) {}

    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
    Index rows() const { return m_xpr.rows(); }
    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
    Index cols() const { return m_xpr.cols(); }

    /** \returns the functor representing the unary operation */
    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
    const UnaryOp& functor() const { return m_functor; }

    /** \returns the nested expression */
    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
    const typename internal::remove_all<XprTypeNested>::type&
    nestedExpression() const { return m_xpr; }

    /** \returns the nested expression */
    EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
    typename internal::remove_all<XprTypeNested>::type&
    nestedExpression() { return m_xpr; }

  protected:
    XprTypeNested m_xpr;
    const UnaryOp m_functor;
};

// Generic API dispatcher
template<typename UnaryOp, typename XprType, typename StorageKind>
class CwiseUnaryOpImpl
  : public internal::generic_xpr_base<CwiseUnaryOp<UnaryOp, XprType> >::type
{
public:
  typedef typename internal::generic_xpr_base<CwiseUnaryOp<UnaryOp, XprType> >::type Base;
};

} // end namespace Eigen

#endif // EIGEN_CWISE_UNARY_OP_H


/*
 * Copyright 2016 Facebook, 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.
 */

#pragma once

#include <limits.h>
#include <pthread.h>

#include <atomic>
#include <functional>
#include <mutex>
#include <string>
#include <vector>

#include <glog/logging.h>

#include <folly/Exception.h>
#include <folly/Foreach.h>
#include <folly/Function.h>
#include <folly/Malloc.h>
#include <folly/MicroSpinLock.h>
#include <folly/Portability.h>
#include <folly/ScopeGuard.h>

#include <folly/detail/StaticSingletonManager.h>

// In general, emutls cleanup is not guaranteed to play nice with the way
// StaticMeta mixes direct pthread calls and the use of __thread. This has
// caused problems on multiple platforms so don't use __thread there.
//
// XXX: Ideally we would instead determine if emutls is in use at runtime as it
// is possible to configure glibc on Linux to use emutls regardless.
#if !FOLLY_MOBILE && !defined(__APPLE__) && !defined(_MSC_VER)
#define FOLLY_TLD_USE_FOLLY_TLS 1
#else
#undef FOLLY_TLD_USE_FOLLY_TLS
#endif

namespace folly {
namespace threadlocal_detail {

/**
 * POD wrapper around an element (a void*) and an associated deleter.
 * This must be POD, as we memset() it to 0 and memcpy() it around.
 */
struct ElementWrapper {
  using DeleterFunType = void(void*, TLPDestructionMode);

  bool dispose(TLPDestructionMode mode) {
    if (ptr == nullptr) {
      return false;
    }

    DCHECK(deleter1 != nullptr);
    ownsDeleter ? (*deleter2)(ptr, mode) : (*deleter1)(ptr, mode);
    cleanup();
    return true;
  }

  void* release() {
    auto retPtr = ptr;

    if (ptr != nullptr) {
      cleanup();
    }

    return retPtr;
  }

  template <class Ptr>
  void set(Ptr p) {
    auto guard = makeGuard([&] { delete p; });
    DCHECK(ptr == nullptr);
    DCHECK(deleter1 == nullptr);

    if (p) {
      ptr = p;
      deleter1 = [](void* pt, TLPDestructionMode) {
        delete static_cast<Ptr>(pt);
      };
      ownsDeleter = false;
      guard.dismiss();
    }
  }

  template <class Ptr, class Deleter>
  void set(Ptr p, const Deleter& d) {
    auto guard = makeGuard([&] {
      if (p) {
        d(p, TLPDestructionMode::THIS_THREAD);
      }
    });
    DCHECK(ptr == nullptr);
    DCHECK(deleter2 == nullptr);
    if (p) {
      ptr = p;
      auto d2 = d; // gcc-4.8 doesn't decay types correctly in lambda captures
      deleter2 = new std::function<DeleterFunType>(
          [d2](void* pt, TLPDestructionMode mode) {
            d2(static_cast<Ptr>(pt), mode);
          });
      ownsDeleter = true;
      guard.dismiss();
    }
  }

  void cleanup() {
    if (ownsDeleter) {
      delete deleter2;
    }
    ptr = nullptr;
    deleter1 = nullptr;
    ownsDeleter = false;
  }

  void* ptr;
  union {
    DeleterFunType* deleter1;
    std::function<DeleterFunType>* deleter2;
  };
  bool ownsDeleter;
};

struct StaticMetaBase;

/**
 * Per-thread entry.  Each thread using a StaticMeta object has one.
 * This is written from the owning thread only (under the lock), read
 * from the owning thread (no lock necessary), and read from other threads
 * (under the lock).
 */
struct ThreadEntry {
  ElementWrapper* elements{nullptr};
  size_t elementsCapacity{0};
  ThreadEntry* next{nullptr};
  ThreadEntry* prev{nullptr};
  StaticMetaBase* meta{nullptr};
};

constexpr uint32_t kEntryIDInvalid = std::numeric_limits<uint32_t>::max();

struct PthreadKeyUnregisterTester;

/**
 * We want to disable onThreadExit call at the end of shutdown, we don't care
 * about leaking memory at that point.
 *
 * Otherwise if ThreadLocal is used in a shared library, onThreadExit may be
 * called after dlclose().
 *
 * This class has one single static instance; however since it's so widely used,
 * directly or indirectly, by so many classes, we need to take care to avoid
 * problems stemming from the Static Initialization/Destruction Order Fiascos.
 * Therefore this class needs to be constexpr-constructible, so as to avoid
 * the need for this to participate in init/destruction order.
 */
class PthreadKeyUnregister {
 public:
  static constexpr size_t kMaxKeys = 1UL << 16;

  ~PthreadKeyUnregister() {
    // If static constructor priorities are not supported then
    // ~PthreadKeyUnregister logic is not safe.
#if !defined(__APPLE__) && !defined(_MSC_VER)
    MSLGuard lg(lock_);
    while (size_) {
      pthread_key_delete(keys_[--size_]);
    }
#endif
  }

  static void registerKey(pthread_key_t key) {
    instance_.registerKeyImpl(key);
  }

 private:
  /**
   * Only one global instance should exist, hence this is private.
   * See also the important note at the top of this class about `constexpr`
   * usage.
   */
  constexpr PthreadKeyUnregister() : lock_(), size_(0), keys_() { }
  friend struct folly::threadlocal_detail::PthreadKeyUnregisterTester;

  void registerKeyImpl(pthread_key_t key) {
    MSLGuard lg(lock_);
    if (size_ == kMaxKeys) {
      throw std::logic_error("pthread_key limit has already been reached");
    }
    keys_[size_++] = key;
  }

  MicroSpinLock lock_;
  size_t size_;
  pthread_key_t keys_[kMaxKeys];

  static PthreadKeyUnregister instance_;
};

struct StaticMetaBase {
  // Represents an ID of a thread local object. Initially set to the maximum
  // uint. This representation allows us to avoid a branch in accessing TLS data
  // (because if you test capacity > id if id = maxint then the test will always
  // fail). It allows us to keep a constexpr constructor and avoid SIOF.
  class EntryID {
   public:
    std::atomic<uint32_t> value;

    constexpr EntryID() : value(kEntryIDInvalid) {
    }

    EntryID(EntryID&& other) noexcept : value(other.value.load()) {
      other.value = kEntryIDInvalid;
    }

    EntryID& operator=(EntryID&& other) {
      assert(this != &other);
      value = other.value.load();
      other.value = kEntryIDInvalid;
      return *this;
    }

    EntryID(const EntryID& other) = delete;
    EntryID& operator=(const EntryID& other) = delete;

    uint32_t getOrInvalid() {
      // It's OK for this to be relaxed, even though we're effectively doing
      // double checked locking in using this value. We only care about the
      // uniqueness of IDs, getOrAllocate does not modify any other memory
      // this thread will use.
      return value.load(std::memory_order_relaxed);
    }

    uint32_t getOrAllocate(StaticMetaBase& meta) {
      uint32_t id = getOrInvalid();
      if (id != kEntryIDInvalid) {
        return id;
      }
      // The lock inside allocate ensures that a single value is allocated
      return meta.allocate(this);
    }
  };

  explicit StaticMetaBase(ThreadEntry* (*threadEntry)());

  ~StaticMetaBase() {
    LOG(FATAL) << "StaticMeta lives forever!";
  }

  void push_back(ThreadEntry* t) {
    t->next = &head_;
    t->prev = head_.prev;
    head_.prev->next = t;
    head_.prev = t;
  }

  void erase(ThreadEntry* t) {
    t->next->prev = t->prev;
    t->prev->next = t->next;
    t->next = t->prev = t;
  }

  static void onThreadExit(void* ptr);

  uint32_t allocate(EntryID* ent);

  void destroy(EntryID* ent);

  /**
   * Reserve enough space in the ThreadEntry::elements for the item
   * @id to fit in.
   */
  void reserve(EntryID* id);

  ElementWrapper& get(EntryID* ent);

  static void initAtFork();
  static void registerAtFork(
      folly::Function<void()> prepare,
      folly::Function<void()> parent,
      folly::Function<void()> child);

  uint32_t nextId_;
  std::vector<uint32_t> freeIds_;
  std::mutex lock_;
  pthread_key_t pthreadKey_;
  ThreadEntry head_;
  ThreadEntry* (*threadEntry_)();
};

// Held in a singleton to track our global instances.
// We have one of these per "Tag", by default one for the whole system
// (Tag=void).
//
// Creating and destroying ThreadLocalPtr objects, as well as thread exit
// for threads that use ThreadLocalPtr objects collide on a lock inside
// StaticMeta; you can specify multiple Tag types to break that lock.
template <class Tag>
struct StaticMeta : StaticMetaBase {
  StaticMeta() : StaticMetaBase(&StaticMeta::getThreadEntrySlow) {
    registerAtFork(
        /*prepare*/ &StaticMeta::preFork,
        /*parent*/ &StaticMeta::onForkParent,
        /*child*/ &StaticMeta::onForkChild);
  }

  static StaticMeta<Tag>& instance() {
    // Leak it on exit, there's only one per process and we don't have to
    // worry about synchronization with exiting threads.
    static auto instance = detail::createGlobal<StaticMeta<Tag>, void>();
    return *instance;
  }

  ElementWrapper& get(EntryID* ent) {
    ThreadEntry* threadEntry = getThreadEntry();
    uint32_t id = ent->getOrInvalid();
    // if id is invalid, it is equal to uint32_t's max value.
    // x <= max value is always true
    if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
      reserve(ent);
      id = ent->getOrInvalid();
      assert(threadEntry->elementsCapacity > id);
    }
    return threadEntry->elements[id];
  }

  static ThreadEntry* getThreadEntrySlow() {
    auto& meta = instance();
    auto key = meta.pthreadKey_;
    ThreadEntry* threadEntry =
      static_cast<ThreadEntry*>(pthread_getspecific(key));
    if (!threadEntry) {
#ifdef FOLLY_TLD_USE_FOLLY_TLS
      static FOLLY_TLS ThreadEntry threadEntrySingleton;
      threadEntry = &threadEntrySingleton;
#else
      threadEntry = new ThreadEntry();
#endif
      threadEntry->meta = &meta;
      int ret = pthread_setspecific(key, threadEntry);
      checkPosixError(ret, "pthread_setspecific failed");
    }
    return threadEntry;
  }

  inline static ThreadEntry* getThreadEntry() {
#ifdef FOLLY_TLD_USE_FOLLY_TLS
    static FOLLY_TLS ThreadEntry* threadEntryCache{nullptr};
    if (UNLIKELY(threadEntryCache == nullptr)) {
      threadEntryCache = instance().threadEntry_();
    }
    return threadEntryCache;
#else
    return instance().threadEntry_();
#endif
  }

  static void preFork(void) {
    instance().lock_.lock();  // Make sure it's created
  }

  static void onForkParent(void) { instance().lock_.unlock(); }

  static void onForkChild(void) {
    // only the current thread survives
    instance().head_.next = instance().head_.prev = &instance().head_;
    ThreadEntry* threadEntry = getThreadEntry();
    // If this thread was in the list before the fork, add it back.
    if (threadEntry->elementsCapacity != 0) {
      instance().push_back(threadEntry);
    }
    instance().lock_.unlock();
  }
};

}  // namespace threadlocal_detail
}  // namespace folly


= Name =

'''ngx_headers_more''' - Set and clear input and output headers...more than "add"!

''This module is not distributed with the Nginx source.'' See [[#Installation|the installation instructions]].

= Version =

This document describes headers-more-nginx-module [http://github.com/agentzh/headers-more-nginx-module/tags v0.24] released on 14 December 2013.

= Synopsis =

<geshi lang="nginx">
    # set the Server output header
    more_set_headers 'Server: my-server';

    # set and clear output headers
    location /bar {
        more_set_headers 'X-MyHeader: blah' 'X-MyHeader2: foo';
        more_set_headers -t 'text/plain text/css' 'Content-Type: text/foo';
        more_set_headers -s '400 404 500 503' -s 413 'Foo: Bar';
        more_clear_headers 'Content-Type';

        # your proxy_pass/memcached_pass/or any other config goes here...
    }

    # set output headers
    location /type {
        more_set_headers 'Content-Type: text/plain';
        # ...
    }

    # set input headers
    location /foo {
        set $my_host 'my dog';
        more_set_input_headers 'Host: $my_host';
        more_set_input_headers -t 'text/plain' 'X-Foo: bah';

        # now $host and $http_host have their new values...
        # ...
    }

    # replace input header X-Foo *only* if it already exists
    more_set_input_headers -r 'X-Foo: howdy';
</geshi>

= Description =

This module allows you to add, set, or clear any output
or input header that you specify.

This is an enhanced version of the standard
[[HttpHeadersModule|headers]] module because it provides more utilities like
resetting or clearing "builtin headers" like Content-Type,
Content-Length, and Server.

It also allows you to specify an optional HTTP status code
criteria using the -s option and an optional content
type criteria using the -t option while modifying the
output headers with the [[#more_set_headers|more_set_headers]] and
[[#more_clear_headers|more_clear_headers]] directives. For example,

<geshi lang="nginx">
    more_set_headers -s 404 -t 'text/html' 'X-Foo: Bar';
</geshi>

Input headers can be modified as well. For example

<geshi lang="nginx">
    location /foo {
        more_set_input_headers 'Host: foo' 'User-Agent: faked';
        # now $host, $http_host, $user_agent, and
        #   $http_user_agent all have their new values.
    }
</geshi>

The option -t is also available in the
[[#more_set_input_headers|more_set_input_headers]] and
[[#more_clear_input_headers|more_clear_input_headers]] directives (for request header filtering) while the -s option
is not allowed.

Unlike the standard [[HttpHeadersModule|headers]] module, this module's directives will by
default apply to all the status codes, including 4xx and 5xx.

= Directives =

== more_set_headers ==
'''syntax:''' ''more_set_headers [-t <content-type list>]... [-s <status-code list>]... <new-header>...''

'''default:''' ''no''

'''context:''' ''http, server, location, location if''

'''phase:''' ''output-header-filter''

Adds or replaces the specified output headers when the response status code matches the codes specified by the -s option ''AND'' the response content type matches the types specified by the -t option.

If either -s or -t is not specified or has an empty list value, then no match is required. Therefore, the following directive set the Server output header to the custom value for ''any'' status code and ''any'' content type:

<geshi lang="nginx">
  more_set_headers    "Server: my_server";
</geshi>

A single directive can set/add multiple output headers. For example

<geshi lang="nginx">
  more_set_headers 'Foo: bar' 'Baz: bah';
</geshi>

Multiple occurrences of the options are allowed in a single directive. Their values will be merged together. For instance

<geshi lang="nginx">
  more_set_headers -s 404 -s '500 503' 'Foo: bar';
</geshi>

is equivalent to

<geshi lang="nginx">
  more_set_headers -s '404 500 503' 'Foo: bar';
</geshi>

The new header should be the one of the forms:

# Name: Value
# Name:
# Name

The last two effectively clear the value of the header Name.

Nginx variables are allowed in header values. For example:

<geshi lang="nginx">
   set $my_var "dog";
   more_set_headers "Server: $my_var";
</geshi>

But variables won't work in header keys due to performance considerations.

Multiple set/clear header directives are allowed in a single location, and they're executed sequentially.

Directives inherited from an upper level scope (say, http block or server blocks) are executed before the directives in the location block.

Note that although more_set_headers is allowed in ''location'' if blocks, it is ''not'' allowed in the ''server'' if blocks, as in

<geshi lang="nginx">
      ?  # This is NOT allowed!
      ?  server {
      ?      if ($args ~ 'download') {
      ?          more_set_headers 'Foo: Bar';
      ?      }
      ?      ...
      ?  }
</geshi>

Behind the scene, use of this directive and its friend [[#more_clear_headers|more_clear_headers]] will (lazily) register an ouput header filter that modifies r->headers_out the way you specify.

== more_clear_headers ==
'''syntax:''' ''more_clear_headers [-t <content-type list>]... [-s <status-code list>]... <new-header>...''

'''default:''' ''no''

'''context:''' ''http, server, location, location if''

'''phase:''' ''output-header-filter''

Clears the specified output headers.

In fact,

<geshi lang="nginx">
   more_clear_headers -s 404 -t 'text/plain' Foo Baz;
</geshi>

is exactly equivalent to

<geshi lang="nginx">
   more_set_headers -s 404 -t 'text/plain' "Foo: " "Baz: ";
</geshi>

or

<geshi lang="nginx">
   more_set_headers -s 404 -t 'text/plain' Foo Baz
</geshi>

See [[#more_set_headers|more_set_headers]] for more details.

Wildcard * can also be used to specify a header name pattern. For example, the following directive effectively clears ''any'' output headers starting by "X-Hidden-":

<geshi lang="nginx">
    more_clear_headers 'X-Hidden-*';
</geshi>

The * wildcard support was first introduced in [[#v0.09|v0.09]].

== more_set_input_headers ==
'''syntax:''' ''more_set_input_headers [-r] [-t <content-type list>]... <new-header>...''

'''default:''' ''no''

'''context:''' ''http, server, location, location if''

'''phase:''' ''rewrite tail''

Very much like [[#more_set_headers|more_set_headers]] except that it operates on input headers (or request headers) and it only supports the -t option.

Note that using the -t option in this directive means filtering by the Content-Type ''request'' header, rather than the response header.

Behind the scene, use of this directive and its friend [[#more_clear_input_headers|more_clear_input_headers]] will (lazily) register a rewrite phase handler that modifies r->headers_in the way you specify. Note that it always run at the ''end'' of the rewrite so that it runs ''after'' the standard [[HttpRewriteModule|rewrite module]] and works in subrequests as well.

If the -r option is specified, then the headers will be replaced to the new values ''only if'' they already exist.

== more_clear_input_headers ==
'''syntax:''' ''more_clear_input_headers [-t <content-type list>]... <new-header>...''

'''default:''' ''no''

'''context:''' ''http, server, location, location if''

'''phase:''' ''rewrite tail''

Clears the specified input headers.

In fact,

<geshi lang="nginx">
   more_clear_input_headers -s 404 -t 'text/plain' Foo Baz;
</geshi>

is exactly equivalent to

<geshi lang="nginx">
   more_set_input_headers -s 404 -t 'text/plain' "Foo: " "Baz: ";
</geshi>

or

<geshi lang="nginx">
   more_set_input_headers -s 404 -t 'text/plain' Foo Baz
</geshi>

See [[#more_set_input_headers|more_set_input_headers]] for more details.

= Limitations =

* Unlike the standard [[HttpHeadersModule|headers]] module, this module does not automatically take care of the constraint among the Expires, Cache-Control, and Last-Modified headers. You have to get them right yourself or use the [[HttpHeadersModule|headers]] module together with this module.

= Installation =

Grab the nginx source code from [http://nginx.org/ nginx.org], for example,
the version 1.4.4 (see [[#Compatibility|nginx compatibility]]), and then build the source with this module:

<geshi lang="bash">
    wget 'http://nginx.org/download/nginx-1.4.4.tar.gz'
    tar -xzvf nginx-1.4.4.tar.gz
    cd nginx-1.4.4/

    # Here we assume you would install you nginx under /opt/nginx/.
    ./configure --prefix=/opt/nginx \
        --add-module=/path/to/headers-more-nginx-module

    make
    make install
</geshi>

Download the latest version of the release tarball of this module from [http://github.com/agentzh/headers-more-nginx-module/tags headers-more-nginx-module file list].

Also, this module is included and enabled by default in the [http://openresty.org ngx_openresty bundle].

= Compatibility =

The following versions of Nginx should work with this module:

* '''1.4.x'''                       (last tested: 1.4.4)
* '''1.3.x'''                       (last tested: 1.3.7)
* '''1.2.x'''                       (last tested: 1.2.9)
* '''1.1.x'''                       (last tested: 1.1.5)
* '''1.0.x'''                       (last tested: 1.0.11)
* '''0.9.x'''                       (last tested: 0.9.4)
* '''0.8.x'''                       (last tested: 0.8.54)
* '''0.7.x >= 0.7.44'''             (last tested: 0.7.68)

Earlier versions of Nginx like 0.6.x and 0.5.x will ''not'' work.

If you find that any particular version of Nginx above 0.7.44 does not work with this module, please consider [[#Report Bugs|reporting a bug]].

= Community =

== English Mailing List ==

The [https://groups.google.com/group/openresty-en openresty-en] mailing list is for English speakers.

== Chinese Mailing List ==

The [https://groups.google.com/group/openresty openresty] mailing list is for Chinese speakers.

= Bugs and Patches =

Please submit bug reports, wishlists, or patches by

# creating a ticket on the [http://github.com/chaoslawful/lua-nginx-module/issues GitHub Issue Tracker],
# or posting to the [[#Community|OpenResty community]].

= Source Repository =

Available on github at [http://github.com/agentzh/headers-more-nginx-module agentzh/headers-more-nginx-module].

= Changes =

The changes of every release of this module can be obtained from the ngx_openresty bundle's change logs:

http://openresty.org/#Changes

= Test Suite =

This module comes with a Perl-driven test suite. The [http://github.com/agentzh/headers-more-nginx-module/tree/master/t/ test cases] are
[http://github.com/agentzh/headers-more-nginx-module/blob/master/t/sanity.t declarative] too. Thanks to the [http://search.cpan.org/perldoc?Test::Nginx Test::Nginx] module in the Perl world.

To run it on your side:

<geshi lang="bash">
    $ PATH=/path/to/your/nginx-with-headers-more-module:$PATH prove -r t
</geshi>

To run the test suite with valgrind's memcheck, use the following commands:

<geshi lang="bash">
    $ export PATH=/path/to/your/nginx-with-headers-more-module:$PATH
    $ TEST_NGINX_USE_VALGRIND=1 prove -r t
</geshi>

You need to terminate any Nginx processes before running the test suite if you have changed the Nginx server binary.

Because a single nginx server (by default, localhost:1984) is used across all the test scripts (.t files), it's meaningless to run the test suite in parallel by specifying -jN when invoking the prove utility.

Some parts of the test suite requires modules [[HttpProxyModule|proxy]], [[HttpRewriteModule|rewrite]], and [[HttpEchoModule|echo]] to be enabled as well when building Nginx.

= TODO =

* Support variables in new headers' keys.

= Getting involved =

You'll be very welcomed to submit patches to the [[#Author|author]] or just ask for a commit bit to the [[#Source Repository|source repository]] on GitHub.

= Authors =

* Yichun "agentzh" Zhang (章亦春) ''<agentzh@gmail.com>'', CloudFlare Inc.
* Bernd Dorn ( http://www.lovelysystems.com/ )

This wiki page is also maintained by the author himself, and everybody is encouraged to improve this page as well.

= Copyright & License =

The code base is borrowed directly from the standard [[HttpHeadersModule|headers]] module in Nginx 0.8.24. This part of code is copyrighted by Igor Sysoev.

Copyright (c) 2009-2013, Yichun "agentzh" Zhang (章亦春) <agentzh@gmail.com>, CloudFlare Inc.

Copyright (c) 2010-2013, Bernd Dorn.

This module is licensed under the terms of the BSD license.

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.

= See Also =

* The original thread on the Nginx mailing list that inspires this module's development: [http://forum.nginx.org/read.php?2,11206,11738 "A question about add_header replication"].
* The orginal announcement thread on the Nginx mailing list: [http://forum.nginx.org/read.php?2,23460 "The "headers_more" module: Set and clear output headers...more than 'add'!"].
* The original [http://agentzh.blogspot.com/2009/11/headers-more-module-scripting-input-and.html blog post] about this module's initial development.
* The [[HttpEchoModule|echo module]] for Nginx module's automated testing.
* The standard [[HttpHeadersModule|headers]] module.


# EMC controller parameters for a simulated machine.

# General note: Comments can either be preceded with a # or ; - either is
# acceptable, although # is in keeping with most linux config files.

# General section -------------------------------------------------------------
[EMC]

# Version of this INI file
VERSION =               $Revision$

# Name of machine, for use with display, etc.
MACHINE =               LinuxCNC-HAL-SIM-AXIS

# Debug level, 0 means no messages. See src/emc/nml_int/emcglb.h for others
# DEBUG =               0x7FFFFFFF
DEBUG = 0

# Sections for display options ------------------------------------------------
[DISPLAY]
PYVCP = vcp.xml
# Name of display program, e.g., axis
DISPLAY =             axis

# Cycle time, in seconds, that display will sleep between polls
CYCLE_TIME =            0.100

# Path to help file
HELP_FILE =             doc/help.txt

# Initial display setting for position, RELATIVE or MACHINE
POSITION_OFFSET =       RELATIVE

# Initial display setting for position, COMMANDED or ACTUAL
POSITION_FEEDBACK =     ACTUAL

# Highest value that will be allowed for feed override, 1.0 = 100%
MAX_FEED_OVERRIDE =     1.2
MAX_SPINDLE_OVERRIDE =  1.0
# Prefix to be used
PROGRAM_PREFIX = ../../../nc_files/

# Introductory graphic
INTRO_GRAPHIC = linuxcnc.gif
INTRO_TIME = 5

EDITOR = gedit

INCREMENTS = 1 mm, .01 in, .1mm, 1 mil, .1 mil, 1/8000 in
[FILTER]
PROGRAM_EXTENSION = .png,.gif,.jpg Grayscale Depth Image
PROGRAM_EXTENSION = .py Python Script

png = image-to-gcode
gif = image-to-gcode
jpg = image-to-gcode
py = python

# Task controller section -----------------------------------------------------
[TASK]

# Name of task controller program, e.g., milltask
TASK =                  milltask

# Cycle time, in seconds, that task controller will sleep between polls
CYCLE_TIME =            0.001

# Part program interpreter section --------------------------------------------
[RS274NGC]

# File containing interpreter variables
PARAMETER_FILE = sim_mm.var

# Motion control section ------------------------------------------------------
[EMCMOT]

EMCMOT =              motmod

# Timeout for comm to emcmot, in seconds
COMM_TIMEOUT =          1.0

# BASE_PERIOD is unused in this configuration but specified in core_sim.hal
BASE_PERIOD  =               0
# Servo task period, in nano-seconds
SERVO_PERIOD =               1000000

# Hardware Abstraction Layer section --------------------------------------------------
[HAL]

# The run script first uses halcmd to execute any HALFILE
# files, and then to execute any individual HALCMD commands.
#

# list of hal config files to run through halcmd
# files are executed in the order in which they appear
HALFILE = core_sim.hal
HALFILE = sim_spindle_encoder.hal
HALFILE = axis_manualtoolchange.hal
HALFILE = simulated_home.hal
HALFILE = test_status.tcl

# list of halcmd commands to execute
# commands are executed in the order in which they appear
#HALCMD =                    save neta

# Single file that is executed after the GUI has started.  Only supported by
# AXIS at this time (only AXIS creates a HAL component of its own)
POSTGUI_HALFILE = postgui.hal

HALUI = halui

# Trajectory planner section --------------------------------------------------
[TRAJ]

AXES =                  3
COORDINATES =           X Y Z
HOME =                  0 0 0
LINEAR_UNITS =          mm
ANGULAR_UNITS =         degree
DEFAULT_LINEAR_VELOCITY = 30.48
MAX_LINEAR_VELOCITY = 53.34
DEFAULT_LINEAR_ACCELERATION = 508
MAX_LINEAR_ACCELERATION = 508
POSITION_FILE = position_mm.txt
ARC_BLEND_ENABLE =      1
ARC_BLEND_FALLBACK_ENABLE = 0
ARC_BLEND_OPTIMIZATION_DEPTH = 100
ARC_BLEND_GAP_CYCLES = 2
ARC_BLEND_RAMP_FREQ = 20

# Axes sections ---------------------------------------------------------------

# First axis
[AXIS_0]

TYPE =                          LINEAR
HOME =                          0.000
MAX_VELOCITY =                  30.48
MAX_ACCELERATION =              508
BACKLASH = 0.000
INPUT_SCALE =                   157.48
OUTPUT_SCALE = 1.000
MIN_LIMIT =                     -254
MAX_LIMIT =                     254
FERROR = 1.27
MIN_FERROR = .254
HOME_OFFSET =                    0.0
HOME_SEARCH_VEL =                127
HOME_LATCH_VEL =                 25.4
HOME_USE_INDEX =                 NO
HOME_IGNORE_LIMITS =             NO
HOME_SEQUENCE = 1
HOME_IS_SHARED = 1

# Second axis
[AXIS_1]

TYPE =                          LINEAR
HOME =                          0.000
MAX_VELOCITY =                  30.48
MAX_ACCELERATION =              508
BACKLASH = 0.000
INPUT_SCALE =                   157.48
OUTPUT_SCALE = 1.000
MIN_LIMIT =                     -254
MAX_LIMIT =                     254
FERROR = 1.27
MIN_FERROR = .254
HOME_OFFSET =                    0.0
HOME_SEARCH_VEL =                127
HOME_LATCH_VEL =                 25.4
HOME_USE_INDEX =                 NO
HOME_IGNORE_LIMITS =             NO
HOME_SEQUENCE = 1

# Third axis
[AXIS_2]

TYPE =                          LINEAR
HOME =                          0.0
MAX_VELOCITY =                  30.48
MAX_ACCELERATION =              508
BACKLASH = 0.000
INPUT_SCALE =                   157.48
OUTPUT_SCALE = 1.000
MIN_LIMIT =                     -50.8
MAX_LIMIT =                     101.6
FERROR = 1.27
MIN_FERROR = .254
HOME_OFFSET =                    25.4
HOME_SEARCH_VEL =                127
HOME_LATCH_VEL =                 25.4
HOME_USE_INDEX =                 NO
HOME_IGNORE_LIMITS =             NO
HOME_SEQUENCE = 0
HOME_IS_SHARED = 1

# section for main IO controller parameters -----------------------------------
[EMCIO]

# Name of IO controller program, e.g., io
EMCIO = 		io

# cycle time, in seconds
CYCLE_TIME =    0.100

# tool table file
TOOL_TABLE = sim_mm.tbl
TOOL_CHANGE_POSITION = 0 0 50.8


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:baselineAligned="true"
	android:background="@drawable/background"
	android:gravity="center_horizontal"
	android:orientation="vertical">
	<LinearLayout
		android:layout_weight="1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:gravity="center">
		<LinearLayout
			android:background="@drawable/image_background"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:gravity="center"
			android:id="@+id/image_container"
			android:padding="5dp">
			<ImageView
				android:layout_width="wrap_content"
				android:layout_height="wrap_content"
				android:background="@drawable/image_default"
				android:scaleType="centerInside"
				android:id="@+id/image" />
		</LinearLayout>
	</LinearLayout>
	<LinearLayout
		android:layout_weight="0"
		android:padding="10dp"
		android:gravity="center_horizontal"
		android:orientation="horizontal"
		android:layout_width="match_parent"
		android:layout_height="wrap_content">
		<Button
			android:text="@string/choose_photo"
			android:padding="10.0dip"
			android:id="@+id/button1"
			android:layout_weight="1"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"></Button>
		<Button
			android:layout_weight="1"
			android:text="@string/launch_editor"
			android:padding="10.0dip"
			android:id="@+id/button2"
			android:enabled="false"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"></Button>
	</LinearLayout>
</LinearLayout>


parrot


/*
 * Copyright 2015-2020 Alexandr Evstigneev
 *
 * 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.
 */

package com.perl5.lang.perl.idea.structureView.filters;

import com.intellij.ide.util.treeView.smartTree.ActionPresentation;
import com.intellij.ide.util.treeView.smartTree.ActionPresentationData;
import com.perl5.PerlIcons;
import com.perl5.lang.perl.idea.structureView.elements.PerlStructureViewElement;
import com.perl5.lang.perl.idea.structureView.elements.PerlVariableDeclarationStructureViewElement;
import org.jetbrains.annotations.NotNull;

public class PerlVariableFilter extends PerlFilter {
  public static final PerlVariableFilter INSTANCE = new PerlVariableFilter();
  private static final String ID = "SHOW_VARIABLES";

  @Override
  protected boolean isMyElement(@NotNull PerlStructureViewElement treeElement) {
    return treeElement instanceof PerlVariableDeclarationStructureViewElement;
  }

  @Override
  public @NotNull ActionPresentation getPresentation() {
    return new ActionPresentationData("Show variables", null, PerlIcons.SCALAR_GUTTER_ICON);
  }

  @Override
  public @NotNull String getName() {
    return ID;
  }
}


[connectivity]
sp =  kernel_getrf_nopivot_0_1.A:DDR[0]
#slr = kernel_getrf_nopivot_0_1:SLR0