text:
using System;
using System.Windows;
using System.Windows.Media;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
#if WINDOWS_BASE
    using MS.Internal.WindowsBase;
#elif PRESENTATION_CORE
    using MS.Internal.PresentationCore;
#elif PRESENTATIONFRAMEWORK
    using MS.Internal.PresentationFramework;
#elif DRT
    using MS.Internal.Drt;
#else
#error Attempt to use FriendAccessAllowedAttribute from an unknown assembly.
using MS.Internal.YourAssemblyName;
#endif

namespace MS.Internal
{
    // MatrixTypes
    [System.Flags]
    internal enum MatrixTypes
    {
        TRANSFORM_IS_IDENTITY = 0,
        TRANSFORM_IS_TRANSLATION = 1,
        TRANSFORM_IS_SCALING     = 2,
        TRANSFORM_IS_UNKNOWN     = 4
    }

    [FriendAccessAllowed]
    internal static class MatrixUtil
    {
        /// <summary>
        /// TransformRect - Internal helper for perf
        /// </summary>
        /// <param name="rect"> The Rect to transform. </param>
        /// <param name="matrix"> The Matrix with which to transform the Rect. </param>
        internal static void TransformRect(ref Rect rect, ref Matrix matrix)
        {
            if (rect.IsEmpty)
            {
                return;
            }

            MatrixTypes matrixType = matrix._type;

            // If the matrix is identity, don't worry.
            if (matrixType == MatrixTypes.TRANSFORM_IS_IDENTITY)
            {
                return;
            }

            // Scaling
            if (0 != (matrixType & MatrixTypes.TRANSFORM_IS_SCALING))
            {
                rect._x *= matrix._m11;
                rect._y *= matrix._m22;
                rect._width *= matrix._m11;
                rect._height *= matrix._m22;

                // Ensure the width is always positive.  For example, if there was a reflection about the
                // y axis followed by a translation into the visual area, the width could be negative.
                if (rect._width < 0.0)
                {
                    rect._x += rect._width;
                    rect._width = -rect._width;
                }

                // Ensure the height is always positive.  For example, if there was a reflection about the
                // x axis followed by a translation into the visual area, the height could be negative.
                if (rect._height < 0.0)
                {
                    rect._y += rect._height;
                    rect._height = -rect._height;
                }
            }

            // Translation
            if (0 != (matrixType & MatrixTypes.TRANSFORM_IS_TRANSLATION))
            {
                // X
                rect._x += matrix._offsetX;

                // Y
                rect._y += matrix._offsetY;
            }

            if (matrixType == MatrixTypes.TRANSFORM_IS_UNKNOWN)
            {
                // Al Bunny implementation.
                Point point0 = matrix.Transform(rect.TopLeft);
                Point point1 = matrix.Transform(rect.TopRight);
                Point point2 = matrix.Transform(rect.BottomRight);
                Point point3 = matrix.Transform(rect.BottomLeft);

                // Width and height is always positive here.
                rect._x = Math.Min(Math.Min(point0.X, point1.X), Math.Min(point2.X, point3.X));
                rect._y = Math.Min(Math.Min(point0.Y, point1.Y), Math.Min(point2.Y, point3.Y));

                rect._width = Math.Max(Math.Max(point0.X, point1.X), Math.Max(point2.X, point3.X)) - rect._x;
                rect._height = Math.Max(Math.Max(point0.Y, point1.Y), Math.Max(point2.Y, point3.Y)) - rect._y;
            }
        }

        /// <summary>
        /// Multiplies two transformations, where the behavior is matrix1 *= matrix2.
        /// This code exists so that we can efficient combine matrices without copying
        /// the data around, since each matrix is 52 bytes.
        /// To reduce duplication and to ensure consistent behavior, this is the
        /// method which is used to implement Matrix * Matrix as well.
        /// </summary>
        internal static void MultiplyMatrix(ref Matrix matrix1, ref Matrix matrix2)
        {
            MatrixTypes type1 = matrix1._type;
            MatrixTypes type2 = matrix2._type;

            // Check for idents

            // If the second is ident, we can just return
            if (type2 == MatrixTypes.TRANSFORM_IS_IDENTITY)
            {
                return;
            }

            // If the first is ident, we can just copy the memory across.
            if (type1 == MatrixTypes.TRANSFORM_IS_IDENTITY)
            {
                matrix1 = matrix2;
                return;
            }

            // Optimize for translate case, where the second is a translate
            if (type2 == MatrixTypes.TRANSFORM_IS_TRANSLATION)
            {
                // 2 additions
                matrix1._offsetX += matrix2._offsetX;
                matrix1._offsetY += matrix2._offsetY;

                // If matrix 1 wasn't unknown we added a translation
                if (type1 != MatrixTypes.TRANSFORM_IS_UNKNOWN)
                {
                    matrix1._type |= MatrixTypes.TRANSFORM_IS_TRANSLATION;
                }

                return;
            }

            // Check for the first value being a translate
            if (type1 == MatrixTypes.TRANSFORM_IS_TRANSLATION)
            {
                // Save off the old offsets
                double offsetX = matrix1._offsetX;
                double offsetY = matrix1._offsetY;

                // Copy the matrix
                matrix1 = matrix2;

                matrix1._offsetX = offsetX * matrix2._m11 + offsetY * matrix2._m21 + matrix2._offsetX;
                matrix1._offsetY = offsetX * matrix2._m12 + offsetY * matrix2._m22 + matrix2._offsetY;

                if (type2 == MatrixTypes.TRANSFORM_IS_UNKNOWN)
                {
                    matrix1._type = MatrixTypes.TRANSFORM_IS_UNKNOWN;
                }
                else
                {
                    matrix1._type = MatrixTypes.TRANSFORM_IS_SCALING | MatrixTypes.TRANSFORM_IS_TRANSLATION;
                }
                return;
            }

            // The following code combines the type of the transformations so that the high nibble
            // is "this"'s type, and the low nibble is mat's type.  This allows for a switch rather
            // than nested switches.

            // trans1._type |  trans2._type
            //  7  6  5  4   |  3  2  1  0
            int combinedType = ((int)type1 << 4) | (int)type2;

            switch (combinedType)
            {
                case 34:  // S * S
                    // 2 multiplications
                    matrix1._m11 *= matrix2._m11;
                    matrix1._m22 *= matrix2._m22;
                    return;

                case 35:  // S * S|T
                    matrix1._m11 *= matrix2._m11;
                    matrix1._m22 *= matrix2._m22;
                    matrix1._offsetX = matrix2._offsetX;
                    matrix1._offsetY = matrix2._offsetY;

                    // Transform set to Translate and Scale
                    matrix1._type = MatrixTypes.TRANSFORM_IS_TRANSLATION | MatrixTypes.TRANSFORM_IS_SCALING;
                    return;

                case 50: // S|T * S
                    matrix1._m11 *= matrix2._m11;
                    matrix1._m22 *= matrix2._m22;
                    matrix1._offsetX *= matrix2._m11;
                    matrix1._offsetY *= matrix2._m22;
                    return;

                case 51: // S|T * S|T
                    matrix1._m11 *= matrix2._m11;
                    matrix1._m22 *= matrix2._m22;
                    matrix1._offsetX = matrix2._m11 * matrix1._offsetX + matrix2._offsetX;
                    matrix1._offsetY = matrix2._m22 * matrix1._offsetY + matrix2._offsetY;
                    return;
                case 36: // S * U
                case 52: // S|T * U
                case 66: // U * S
                case 67: // U * S|T
                case 68: // U * U
                    matrix1 = new Matrix(
                        matrix1._m11 * matrix2._m11 + matrix1._m12 * matrix2._m21,
                        matrix1._m11 * matrix2._m12 + matrix1._m12 * matrix2._m22,

                        matrix1._m21 * matrix2._m11 + matrix1._m22 * matrix2._m21,
                        matrix1._m21 * matrix2._m12 + matrix1._m22 * matrix2._m22,

                        matrix1._offsetX * matrix2._m11 + matrix1._offsetY * matrix2._m21 + matrix2._offsetX,
                        matrix1._offsetX * matrix2._m12 + matrix1._offsetY * matrix2._m22 + matrix2._offsetY);
                    return;
#if DEBUG
            default:
                Debug.Fail("Matrix multiply hit an invalid case: " + combinedType);
                break;
#endif
            }
        }

        /// <summary>
        /// Applies an offset to the specified matrix in place.
        /// </summary>
        internal static void PrependOffset(
            ref Matrix matrix,
            double offsetX,
            double offsetY)
        {
            if (matrix._type == MatrixTypes.TRANSFORM_IS_IDENTITY)
            {
                matrix = new Matrix(1, 0, 0, 1, offsetX, offsetY);
                matrix._type = MatrixTypes.TRANSFORM_IS_TRANSLATION;
            }
            else
            {
                //
                //  / 1   0   0 \       / m11   m12   0 \
                //  | 0   1   0 |   *   | m21   m22   0 |
                //  \ tx  ty  1 /       \  ox    oy   1 /
                //
                //       /   m11                  m12                     0 \
                //  =    |   m21                  m22                     0 |
                //       \   m11*tx+m21*ty+ox     m12*tx + m22*ty + oy    1 /
                //

                matrix._offsetX += matrix._m11 * offsetX + matrix._m21 * offsetY;
                matrix._offsetY += matrix._m12 * offsetX + matrix._m22 * offsetY;

                // It just gained a translate if was a scale transform. Identity transform is handled above.
                Debug.Assert(matrix._type != MatrixTypes.TRANSFORM_IS_IDENTITY);
                if (matrix._type != MatrixTypes.TRANSFORM_IS_UNKNOWN)
                {
                    matrix._type |= MatrixTypes.TRANSFORM_IS_TRANSLATION;
                }
            }
        }
    }
}


text:
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
import json

from django.contrib.gis.geos import Point
from fruitlocations.models import FruitLocations
from fruitlocations.forms import AddFruit

# @login_required

def find_fruit(request):
    return render_to_response("fruitlocations/find_fruit.html")

# Take all data from FruitLocations model table and turn it into a json object to send to map via JS/AJAX (see find_fruit.js)
def ajax_get_fruit(request):
    if request.is_ajax() and request.method == "GET":
        fruits = FruitLocations.objects.all()
        fruit_markers = {}
        for object in fruits:
            fruit_markers[object.id] = {"fruit_variety": object.fruit_variety, "geom": object.geom}
        print(fruit_markers)
        return HttpResponse(json.dumps(fruit_markers), content_type="application/json")
    else:
        return 'Http404'

# Create add fruit form that takes spatial data from a marker on a map garnered through JS/AJAX (see add_fruit.js) and save to DB

def add_fruit(request):

    if request.method == 'POST':
        form = AddFruit(request.POST)
        if form.is_valid():
            new_point = FruitLocations()
            cd = form.cleaned_data
            coordinates = cd['coordinates'].split(',')
            new_point.geom = Point(float(coordinates[0]), float(coordinates[1]))
            new_point.fruit_variety = cd['fruit_variety']

            new_point.save()

            return render_to_response('fruitlocations/AddFruit_success.html')

        else:
            return render_to_response('fruitlocations/AddFruit_fail.html')

    else:
        form = AddFruit()

    token = {}
    token.update(csrf(request))
    token['form'] = AddFruit()

    return render_to_response('fruitlocations/add_fruit.html', token)

redpajama_set_name: RedPajamaGithub


text:
Credits
=======

Project Lead
----------------

* Joshua Greenhalgh <joshuadouglasgreenhalgh@gmail.com>

Project Contributors
------------

None.


text:
#include <aws/sesv2/model/SuppressedDestination.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SESV2
{
namespace Model
{

SuppressedDestination::SuppressedDestination() :
    m_emailAddressHasBeenSet(false),
    m_reason(SuppressionListReason::NOT_SET),
    m_reasonHasBeenSet(false),
    m_lastUpdateTimeHasBeenSet(false),
    m_attributesHasBeenSet(false)
{
}

SuppressedDestination::SuppressedDestination(JsonView jsonValue) :
    m_emailAddressHasBeenSet(false),
    m_reason(SuppressionListReason::NOT_SET),
    m_reasonHasBeenSet(false),
    m_lastUpdateTimeHasBeenSet(false),
    m_attributesHasBeenSet(false)
{
  *this = jsonValue;
}

SuppressedDestination& SuppressedDestination::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("EmailAddress"))
  {
    m_emailAddress = jsonValue.GetString("EmailAddress");

    m_emailAddressHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Reason"))
  {
    m_reason = SuppressionListReasonMapper::GetSuppressionListReasonForName(jsonValue.GetString("Reason"));

    m_reasonHasBeenSet = true;
  }

  if(jsonValue.ValueExists("LastUpdateTime"))
  {
    m_lastUpdateTime = jsonValue.GetDouble("LastUpdateTime");

    m_lastUpdateTimeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Attributes"))
  {
    m_attributes = jsonValue.GetObject("Attributes");

    m_attributesHasBeenSet = true;
  }

  return *this;
}

JsonValue SuppressedDestination::Jsonize() const
{
  JsonValue payload;

  if(m_emailAddressHasBeenSet)
  {
   payload.WithString("EmailAddress", m_emailAddress);

  }

  if(m_reasonHasBeenSet)
  {
   payload.WithString("Reason", SuppressionListReasonMapper::GetNameForSuppressionListReason(m_reason));
  }

  if(m_lastUpdateTimeHasBeenSet)
  {
   payload.WithDouble("LastUpdateTime", m_lastUpdateTime.SecondsWithMSPrecision());
  }

  if(m_attributesHasBeenSet)
  {
   payload.WithObject("Attributes", m_attributes.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace SESV2
} // namespace Aws


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using NDbfReader.Tests.Infrastructure;
using Xunit;

namespace NDbfReader.Tests
{
    public sealed class ReaderTests
    {
        private const string EXPECTED_NO_ROWS_EXCEPTION_MESSAGE = "No row is loaded. Call Read method first and check whether it returns true.";
        private const string ZERO_SIZE_COLUMN_NAME = "KRAJID";

        static ReaderTests()
        {
            // support Windows-1250 encoding in donet core
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        }

        [Theory]
        [InlineData(typeof(string))]
        [InlineData(typeof(IColumn))]
        public void GetBytes_InvalidOffset_ThrowsArgumentOutException(Type columnParameterType)
        {
            using (var table = Samples.OpenBasicTable())
            {
                Reader reader = table.OpenReader();
                reader.Read();
                var column = table.Columns.First();

                var exception = Assert.Throws<ArgumentOutOfRangeException>(
                    () => ExecuteGetBytesMethod(reader, columnParameterType, column, buffer: new byte[column.Size], offset: column.Size + 1));
                exception.ParamName.ShouldBeEquivalentTo("offset");
            }
        }

        [Theory]
        [InlineData(typeof(string))]
        [InlineData(typeof(IColumn))]
        public void GetBytes_NullBuffer_ThrowsArgumentNullException(Type columnParameterType)
        {
            using (var table = Samples.OpenBasicTable())
            {
                Reader reader = table.OpenReader();
                reader.Read();
                var column = table.Columns.First();

                var exception = Assert.Throws<ArgumentNullException>(() => ExecuteGetBytesMethod(reader, columnParameterType, column, buffer: null));
                exception.ParamName.ShouldBeEquivalentTo("buffer");
            }
        }

        [Theory]
        [InlineDataWithExecMode(typeof(string), 0)]
        [InlineDataWithExecMode(typeof(string), 5)]
        [InlineDataWithExecMode(typeof(IColumn), 0)]
        [InlineDataWithExecMode(typeof(IColumn), 5)]
        public async Task GetBytes_ReturnsData(bool useAsync, Type columnParameterType, int offset)
        {
            using (var table = await OpenBasicTable(useAsync))
            {
                var reader = table.OpenReader();
                reader.Read();
                var dateColumn = table.Columns[1];
                var buffer = new byte[dateColumn.Size + offset];

                ExecuteGetBytesMethod(reader, columnParameterType, dateColumn, buffer, offset);

                buffer.Skip(offset).ShouldAllBeEquivalentTo(new byte[] { 50, 48, 49, 52, 48, 50, 50, 48 }, opt => opt.WithStrictOrdering());
            }
        }

        [Theory]
        [InlineData(typeof(string))]
        [InlineData(typeof(IColumn))]
        public void GetBytes_SmallBuffer_ThrowsArgumentException(Type columnParameterType)
        {
            using (var table = Samples.OpenBasicTable())
            {
                Reader reader = table.OpenReader();
                reader.Read();
                var column = table.Columns.First();

                var exception = Assert.Throws<ArgumentException>(() => ExecuteGetBytesMethod(reader, columnParameterType, column, buffer: new byte[column.Size], offset: 1));
                exception.ParamName.ShouldBeEquivalentTo("buffer");
                exception.Message.Should().StartWith($"The buffer is too small. Increase the capacity to at least {column.Size + 1} bytes.");
            }
        }

        [Theory]
        [InlineDataWithExecMode]
        public async Task GetDecimal_ValueWithWhitespace_ReturnsValue(bool useAsync)
        {
            using (var table = await this.Exec(() => Table.Open(EmbeddedSamples.GetStream(EmbeddedSamples.WHITE_SPACES)), useAsync))
            {
                var reader = table.OpenReader();
                await reader.Exec(r => r.Read(), useAsync);

                decimal? actualValue = reader.GetDecimal("OBJ_SEQ");
                actualValue.ShouldBeEquivalentTo(11085340);
            }
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetDecimal_ZeroSizeColumnInstance_ReturnsNull(bool useAsync)
        {
            return GetMethod_ZeroSizeColumn_ReturnsNull(reader => reader.GetDecimal(GetZeroSizeColumn(reader.Table)), useAsync);
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetDecimal_ZeroSizeColumnName_ReturnsNull(bool useAsync)
        {
            return GetMethod_ZeroSizeColumn_ReturnsNull(reader => reader.GetDecimal(ZERO_SIZE_COLUMN_NAME), useAsync);
        }

        [Theory]
        [InlineDataWithExecMode(nameof(Reader.GetString), "TEXT")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "TEXT")]
        [InlineDataWithExecMode(nameof(Reader.GetDecimal), "NUMERIC")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "NUMERIC")]
        [InlineDataWithExecMode(nameof(Reader.GetBoolean), "LOGICAL")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "LOGICAL")]
        [InlineDataWithExecMode(nameof(Reader.GetDate), "DATE")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "DATE")]
        [InlineDataWithExecMode(nameof(Reader.GetInt32), "LONG")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "LONG")]
        public async Task GetMethod_ColumnInstance_ReturnsValue(bool useAsync, string methodName, string columnName)
        {
            // Arrange
            var actualValues = new List<object>();
            var expectedValues = Samples.BasicTableContent[columnName];

            using (var table = await OpenBasicTable(useAsync))
            {
                var reader = table.OpenReader();
                var column = table.Columns.Single(c => c.Name == columnName);

                // Act
                while (await reader.Exec(r => r.Read(), useAsync))
                {
                    actualValues.Add(ExecuteGetMethod(reader, methodName, typeof(IColumn), column));
                }
            }

            //Assert
            actualValues.ShouldAllBeEquivalentTo(expectedValues, opt => opt.WithStrictOrdering());
        }

        [Theory]
        [ReaderGetMethods]
        public void GetMethod_ColumnInstanceFromDifferentTable_ThrowsArgumentOutOfRangeExeptionException(string methodName)
        {
            // Arrange
            Type columnType = typeof(Reader)
                .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
                .SingleOrDefault(m => m.Name == methodName && m.GetParameters().First().ParameterType == typeof(IColumn))
                .ReturnType;

            if (columnType == typeof(void))
            {
                // GetBytes method
                columnType = typeof(object);
            }

            using (var differentTable = Samples.OpenBasicTable())
            using (var table = Samples.OpenBasicTable())
            {
                IColumn differentColumn = null;
                if (columnType == typeof(object))
                {
                    differentColumn = differentTable.Columns.First();
                }
                else
                {
                    differentColumn = differentTable.Columns.Single(c => c.Type == columnType);
                }

                var reader = table.OpenReader();
                reader.Read();

                // Act & Assert
                var exception = Assert.Throws<ArgumentOutOfRangeException>(
                    () => ExecuteGetMethod(reader, methodName, parameterType: typeof(IColumn), columnNameOrInstance: differentColumn));

                exception.ParamName.Should().BeEquivalentTo("column");
                exception.Message.Should().StartWithEquivalent("The column instance not found.");
            }
        }

        [Theory]
        [InlineDataWithExecMode(nameof(Reader.GetString), "TEXT")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "TEXT")]
        [InlineDataWithExecMode(nameof(Reader.GetDecimal), "NUMERIC")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "NUMERIC")]
        [InlineDataWithExecMode(nameof(Reader.GetBoolean), "LOGICAL")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "LOGICAL")]
        [InlineDataWithExecMode(nameof(Reader.GetDate), "DATE")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "DATE")]
        [InlineDataWithExecMode(nameof(Reader.GetInt32), "LONG")]
        [InlineDataWithExecMode(nameof(Reader.GetValue), "LONG")]
        public async Task GetMethod_ColumnName_ReturnsValue(bool useAsync, string methodName, string columnName)
        {
            // Arrange
            var actualValues = new List<object>();
            var expectedValues = Samples.BasicTableContent[columnName];

            using (var table = await OpenBasicTable(useAsync))
            {
                var reader = table.OpenReader();

                // Act
                while (await reader.Exec(r => r.Read(), useAsync))
                {
                    actualValues.Add(ExecuteGetMethod(reader, methodName, typeof(string), columnName));
                }
            }

            //Assert
            actualValues.ShouldAllBeEquivalentTo(expectedValues, opt => opt.WithStrictOrdering());
        }

        [Theory]
        [ReaderGetMethods]
        public void GetMethod_DisposedTable_ThrowsObjectDisposedException(string methodName, Type parameterType)
        {
            PublicInterfaceInteraction_DisposedTable_ThrowsObjectDisposedException(
                reader => ExecuteGetMethod(reader, methodName, parameterType, GetValidArgument(reader, methodName, parameterType)));
        }

        [Theory]
        [ReaderGetMethods(exclude: new[] { "GetValue", nameof(Reader.GetBytes) })]
        public void GetMethod_MismatchedColumnInstance_ThrowsArgumentOutOfRangeExeptionException(string methodName)
        {
            // Arrange
            using (var table = Samples.OpenBasicTable())
            {
                var reader = table.OpenReader();
                reader.Read();

                // Act & Assert
                var exception = Assert.Throws<ArgumentOutOfRangeException>(
                    () => ExecuteGetMethod(reader, methodName, parameterType: typeof(IColumn), columnNameOrInstance: GetMismatchedColumnInstance(reader, methodName)));

                exception.ParamName.Should().BeEquivalentTo("column");
                exception.Message.Should().StartWithEquivalent("The column's type does not match the method's return type.");
            }
        }

        [Theory]
        [ReaderGetMethods(exclude: new[] { "GetValue", nameof(Reader.GetBytes) })]
        public void GetMethod_MismatchedColumnName_ThrowsArgumentOutOfRangeExeptionException(string methodName)
        {
            // Arrange
            using (var table = Samples.OpenBasicTable())
            {
                var reader = table.OpenReader();
                reader.Read();

                // Act & Assert
                var exception = Assert.Throws<ArgumentOutOfRangeException>(
                    () => ExecuteGetMethod(reader, methodName, parameterType: typeof(string), columnNameOrInstance: GetMismatchedColumnName(reader, methodName)));

                exception.ParamName.Should().BeEquivalentTo("columnName");
                exception.Message.Should().StartWithEquivalent("The column's type does not match the method's return type.");
            }
        }

        [Theory]
        [ReaderGetMethods]
        public void GetMethod_NonExistingColumnName_ThrowsArgumentOutOfRangeException(string getMethodName)
        {
            GetMethod_InvalidColumnName_ThrowsArgumentOutOfRangeException("FOO", getMethodName);
        }

        [Theory]
        [ReaderGetMethods]
        public void GetMethod_NullColumnInstance_ThrowsArgumentNullExeptionException(string methodName)
        {
            GetMethod_NullParameter_ThrowsArgumentNullExeptionException(methodName, typeof(IColumn), "column");
        }

        [Theory]
        [ReaderGetMethods]
        public void GetMethod_NullColumnName_ThrowsArgumentNullExeptionException(string methodName)
        {
            GetMethod_NullParameter_ThrowsArgumentNullExeptionException(methodName, typeof(string), "columnName");
        }

        [Theory]
        [InlineDataWithExecMode]
        public async Task GetMethod_PreviousColumnInstanceOnSeekableStream_ReturnsCorrectValue(bool useAsync)
        {
            // Arrange
            using (var table = await OpenBasicTable(useAsync))
            {
                var reader = table.OpenReader();

                await reader.Exec(r => r.Read(), useAsync);

                var dateColumn = table.Columns[1];
                var textColumn = table.Columns[0];

                // Act
                reader.GetDateTime(dateColumn);
                var actualText = reader.GetString(textColumn);

                // Assert
                var expectedText = Samples.BasicTableContent["TEXT"].First();
                Assert.Equal(expectedText, actualText);
            }
        }

        [Theory]
        [InlineDataWithExecMode]
        public async Task GetMethod_PreviousColumnNameOnSeekableStream_ReturnsCorrectValue(bool useAsync)
        {
            // Arrange
            using (var table = await OpenBasicTable(useAsync))
            {
                var reader = table.OpenReader();

                await reader.Exec(r => r.Read(), useAsync);

                // Act
                reader.GetDateTime("DATE");
                var actualText = reader.GetString("TEXT");

                // Assert
                var expectedText = Samples.BasicTableContent["TEXT"].First();
                Assert.Equal(expectedText, actualText);
            }
        }

        [Theory]
        [ReaderGetMethods]
        public void GetMethod_ReadMethodNeverCalled_ThrowsInvalidOperationException(string methodName, Type parameterType)
        {
            // Arrange
            using (var table = Samples.OpenBasicTable())
            {
                var reader = table.OpenReader();

                // Act & Assert
                var exception = Assert.Throws<InvalidOperationException>(() => ExecuteGetMethod(reader, methodName, parameterType, GetValidArgument(reader, methodName, parameterType)));
                Assert.Equal(EXPECTED_NO_ROWS_EXCEPTION_MESSAGE, exception.Message);
            }
        }

        [Theory]
        [ReaderGetMethods]
        public async Task GetMethod_ReadMethodReturnedFalse_ThrowsInvalidOperationException(bool useAsync, string methodName, Type parameterType)
        {
            // Arrange
            using (var table = await OpenBasicTable(useAsync))
            {
                var reader = table.OpenReader();

                while (await reader.Exec(r => r.Read(), useAsync)) { }

                // Act & Assert
                var exception = Assert.Throws<InvalidOperationException>(() => ExecuteGetMethod(reader, methodName, parameterType, GetValidArgument(reader, methodName, parameterType)));

                Assert.Equal(EXPECTED_NO_ROWS_EXCEPTION_MESSAGE, exception.Message);
            }
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetMethod_RepeatedColumnInstanceOnSeeeakbleStream_ReturnsTheSameValue(bool useAsync)
        {
            return GetMethod_RepeatedColumnOnSeekableStream_ReturnsTheSameValue(useAsync, reader => reader.GetDateTime(reader.Table.Columns[1]));
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetMethod_RepeatedColumnNameOnSeeeakbleStream_ReturnsTheSameValue(bool useAsync)
        {
            return GetMethod_RepeatedColumnOnSeekableStream_ReturnsTheSameValue(useAsync, reader => reader.GetDateTime("DATE"));
        }

        [Theory]
        [InlineDataWithExecMode]
        public async Task GetString_ReaderOfTableWithCzechTextsOpenedWithCzechEncoding_ReturnsCorrectlyEncodedString(bool useAsync)
        {
            // Arrange
            Stream stream = EmbeddedSamples.GetStream(EmbeddedSamples.CZECH_ENCODING);
            using (var table = await this.Exec(() => Table.Open(stream), useAsync))
            {
                var reader = table.OpenReader(Encoding.GetEncoding(1250));

                var expectedItems = new List<string> { "Mateřská škola Deštná", "Tělocvična Deštná", "Městský úřad Deštná" };
                var actualItems = new List<string>();

                // Act
                while (await reader.Exec(r => r.Read(), useAsync))
                {
                    actualItems.Add(reader.GetString("DS"));
                }

                // Assert
                actualItems.ShouldAllBeEquivalentTo(expectedItems, opt => opt.WithStrictOrdering());
            }
        }

        [Theory]
        [InlineDataWithExecMode(true)]
        [InlineDataWithExecMode(false)]
        public Task GetDate_FoxProDateTimeColumnName_ReturnsCorrectDateTime(bool useAsync, bool withNullValue)
        {
            (string columnName, DateTime? expectedValue) = Samples.FoxProDateTime.FirstRow(withNullValue);

            return GetMethod_FoxProDateTimeColumn_ReturnsCorrectDateTime(
                useAsync,
                reader => reader.GetDateTime(columnName), expectedValue);
        }

        [Theory]
        [InlineDataWithExecMode(true)]
        [InlineDataWithExecMode(false)]
        public Task GetDate_FoxProDateTimeColumnInstance_ReturnsCorrectDateTime(bool useAsync, bool withNullValue)
        {
            (string columnName, DateTime? expectedValue) = Samples.FoxProDateTime.FirstRow(withNullValue);

            return GetMethod_FoxProDateTimeColumn_ReturnsCorrectDateTime(
                useAsync,
                reader => reader.GetDateTime(reader.Table.Columns[columnName]), expectedValue);
        }

        [Theory]
        [InlineDataWithExecMode(true)]
        [InlineDataWithExecMode(false)]
        public Task GetValue_FoxProDateTimeColumnName_ReturnsCorrectDateTime(bool useAsync, bool withNullValue)
        {
            (string columnName, DateTime? expectedValue) = Samples.FoxProDateTime.FirstRow(withNullValue);

            return GetMethod_FoxProDateTimeColumn_ReturnsCorrectDateTime(
                useAsync,
                reader => (DateTime?)reader.GetValue(columnName), expectedValue);
        }

        [Theory]
        [InlineDataWithExecMode(true)]
        [InlineDataWithExecMode(false)]
        public Task GetValue_FoxProDateTimeColumnInstance_ReturnsCorrectDateTime(bool useAsync, bool withNullValue)
        {
            (string columnName, DateTime? expectedValue) = Samples.FoxProDateTime.FirstRow(withNullValue);

            return GetMethod_FoxProDateTimeColumn_ReturnsCorrectDateTime(
                useAsync,
                reader => (DateTime?)reader.GetValue(reader.Table.Columns[columnName]), expectedValue);
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetDecimal_CurrencyColumnName_ReturnsCorrectDecimal(bool useAsync)
        {
            return GetMethod_CurrencyColumn_ReturnsCorrectDecimal(
                useAsync,
                reader => reader.GetDecimal(Samples.CurrencyDataType.UnitPriceColumn.Name));
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetDecimal_CurrencyColumnInstance_ReturnsCorrectDecimal(bool useAsync)
        {
            return GetMethod_CurrencyColumn_ReturnsCorrectDecimal(
                useAsync,
                reader => reader.GetDecimal(reader.Table.Columns[Samples.CurrencyDataType.UnitPriceColumn.Name]));
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetValue_CurrencyColumnName_ReturnsCorrectDecimal(bool useAsync)
        {
            return GetMethod_CurrencyColumn_ReturnsCorrectDecimal(
                useAsync,
                reader => (decimal?)reader.GetValue(Samples.CurrencyDataType.UnitPriceColumn.Name));
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetValue_CurrencyColumnInstance_ReturnsCorrectDecimal(bool useAsync)
        {
            return GetMethod_CurrencyColumn_ReturnsCorrectDecimal(
                useAsync,
                reader => (decimal?)reader.GetValue(reader.Table.Columns[Samples.CurrencyDataType.UnitPriceColumn.Name]));
        }

        [Theory]
        [InlineDataWithExecMode]
        public async Task GetValue_UnsupportedColumn_ReturnsBytes(bool useAsync)
        {
            using (var table = await this.Exec(() => Table.Open(EmbeddedSamples.GetStream(EmbeddedSamples.UNSUPPORTED_TYPES)), useAsync))
            {
                Reader reader = table.OpenReader();
                for (int i = 0; i < 15; i++)
                {
                    await reader.Exec(r => r.Read(), useAsync);
                }

                var actualBytes = reader.GetValue("APPNOTES") as byte[];
                var expectedBytes = new byte[] { 4, 1, 0, 0 };
                actualBytes.ShouldAllBeEquivalentTo(expectedBytes, opt => opt.WithStrictOrdering());
            }
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetValue_ZeroSizeColumnInstance_ReturnsNull(bool useAsync)
        {
            return GetMethod_ZeroSizeColumn_ReturnsNull(reader => reader.GetValue(GetZeroSizeColumn(reader.Table)), useAsync);
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task GetValue_ZeroSizeColumnName_ReturnsNull(bool useAsync)
        {
            return GetMethod_ZeroSizeColumn_ReturnsNull(reader => reader.GetValue(ZERO_SIZE_COLUMN_NAME), useAsync);
        }

        [Theory]
        [InlineDataWithExecMode]
        public async Task Read_RepeatedCall_SkipsRows(bool useAsync)
        {
            object[] expectedSecondRowContent = Samples.BasicTableContent.Select(pair => pair.Value[1]).ToArray();

            using (Table table = await OpenBasicTable(useAsync))
            {
                Reader reader = table.OpenReader();
                await reader.Exec(r => r.Read(), useAsync);
                await reader.Exec(r => r.Read(), useAsync);

                object[] secondRowContent = table.Columns.Select(reader.GetValue).ToArray();

                secondRowContent.ShouldAllBeEquivalentTo(expectedSecondRowContent, opt => opt.WithStrictOrdering());
            }
        }

        [Theory]
        [InlineDataWithExecMode]
        public async Task Read_TableBasedOnNonSeekableStream_ReadsAllRowsAsUsual(bool useAsync)
        {
            // Arrange
            var stream = EmbeddedSamples.GetStream(EmbeddedSamples.BASIC).ToNonSeekable();

            // Act
            int rowsCount = 0;
            using (var table = await this.Exec(() => Table.Open(stream), useAsync))
            {
                var reader = table.OpenReader();

                while (await reader.Exec(r => r.Read(), useAsync))
                {
                    rowsCount += 1;
                }
            }

            // Assert
            Assert.Equal(3, rowsCount);
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task Read_TableOnNonSeekableStreamWithDeletedRows_SkipsDeletedRows(bool useAsync)
        {
            return Read_TableWithDeletedRows_SkipsDeletedRows(useAsync, StreamExtensions.ToNonSeekable);
        }

        [Theory]
        [InlineDataWithExecMode]
        public Task Read_TableOnSeekableStreamWithDeletedRows_SkipsDeletedRows(bool useAsync)
        {
            return Read_TableWithDeletedRows_SkipsDeletedRows(useAsync, stream => stream);
        }

        [Fact]
        public void Table_DisposedTable_ThrowsObjectDisposedException()
        {
            PublicInterfaceInteraction_DisposedTable_ThrowsObjectDisposedException(reader => reader.Table);
        }

        [Fact]
        public void Table_OpenedReader_ReturnsReferenceToTheParentTable()
        {
            // Arrange
            using (var table = Samples.OpenBasicTable())
            {
                var reader = table.OpenReader();

                // Act
                var actualTable = reader.Table;

                // Assert
                Assert.Same(table, actualTable);
            }
        }

        [Fact]
        public void TextEncoding_ReaderOpenedWithEncoding_ReturnsTheSameEncoding()
        {
            // Arrange
            var utf8Encoding = Encoding.UTF8;

            using (var table = Samples.OpenBasicTable())
            {
                // Act
                var reader = table.OpenReader(utf8Encoding);

                // Assert
                Assert.Same(utf8Encoding, reader.Encoding);
            }
        }

        [Fact]
        public void TextEncoding_ReaderOpenedWithUnspecifiedEncoding_ReturnsUtf8Encoding()
        {
            // Arrange
            using (var table = Samples.OpenBasicTable())
            {
                // Act
                var reader = table.OpenReader();

                // Assert
                Assert.Same(Encoding.UTF8, reader.Encoding);
            }
        }

        private static void ExecuteGetBytesMethod(Reader reader, Type columnParameterType, IColumn column, byte[] buffer, int offset = 0)
        {
            MethodInfo method = typeof(Reader).GetMethod(nameof(Reader.GetBytes), new[] { columnParameterType, typeof(byte[]), typeof(int) });
            object columnParameter = (columnParameterType == typeof(string) ? (object)column.Name : column);

            try
            {
                method.Invoke(reader, new[] { columnParameter, buffer, offset });
            }
            catch (TargetInvocationException e)
            {
                throw e.InnerException;
            }
        }

        private static object ExecuteGetMethod(Reader reader, string methodName, Type parameterType, object columnNameOrInstance = null)
        {
            var methodInfo = typeof(Reader)
                .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                .SingleOrDefault(m => m.Name == methodName && m.GetParameters().First().ParameterType == parameterType);

            if (methodInfo == null)
            {
                throw new ArgumentOutOfRangeException(nameof(methodName), "Method " + methodName + " not found.");
            }

            var parameters = new List<object>() { columnNameOrInstance };
            ParameterInfo[] declaredParameters = methodInfo.GetParameters();
            if (declaredParameters.Length > 1)
            {
                // GetBytes method
                if (columnNameOrInstance == null)
                {
                    // buffer parameter
                    parameters.Add(new byte[1]);
                }
                else
                {
                    var column = columnNameOrInstance as IColumn;
                    if (column == null)
                    {
                        // it's column name, lets find the instance
                        column = reader.Table.Columns.SingleOrDefault(c => c.Name == (string)columnNameOrInstance);
                    }
                    // buffer parameter
                    parameters.Add(new byte[column?.Size ?? 1]);
                }

                // offset parameter
                parameters.Add(0);
            }

            try
            {
                return methodInfo.Invoke(reader, parameters.ToArray());
            }
            catch (TargetInvocationException e)
            {
                throw e.InnerException;
            }
        }

        private static IColumn GetMismatchedColumnInstance(Reader reader, string methodName)
        {
            var methodInfo = reader.GetType().GetMethod(methodName, new[] { typeof(IColumn) });
            var returnType = Nullable.GetUnderlyingType(methodInfo.ReturnType) ?? methodInfo.ReturnType;

            return reader.Table.Columns.First(column => column.Type != returnType);
        }

        private static string GetMismatchedColumnName(Reader reader, string methodName)
        {
            var methodInfo = reader.GetType().GetMethod(methodName, new[] { typeof(string) });
            var returnType = Nullable.GetUnderlyingType(methodInfo.ReturnType) ?? methodInfo.ReturnType;

            return reader.Table.Columns.First(column => column.Type != returnType).Name;
        }

        private static object GetValidArgument(Reader reader, string methodName, Type argType)
        {
            Type columnType = typeof(Reader)
                .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
                .Single(m => m.Name == methodName && m.GetParameters().First().ParameterType == argType)
                .ReturnType;

            if (columnType == typeof(void))
            {
                // GetBytes method
                columnType = typeof(object);
            }

            IColumn column = null;
            if (columnType == typeof(object))
            {
                column = reader.Table.Columns.First();
            }
            else
            {
                column = reader.Table.Columns.Single(c => c.Type == columnType);
            }

            if (argType == typeof(string))
            {
                return column.Name;
            }
            if (argType == typeof(IColumn))
            {
                return column;
            }

            throw new ArgumentOutOfRangeException(nameof(argType));
        }

        private static IColumn GetZeroSizeColumn(Table table)
        {
            return table.Columns.Single(c => c.Name == ZERO_SIZE_COLUMN_NAME);
        }

        private void GetMethod_InvalidColumnName_ThrowsArgumentOutOfRangeException(string invalidColumnName, string getMethodName)
        {
            // Arrange
            using (var table = Samples.OpenBasicTable())
            {
                var reader = table.OpenReader();
                reader.Read();

                // Act & Assert
                var exception = Assert.Throws<ArgumentOutOfRangeException>(
                    () => ExecuteGetMethod(reader, getMethodName, parameterType: typeof(string), columnNameOrInstance: invalidColumnName));
                exception.ParamName.Should().BeEquivalentTo("columnName");
                exception.Message.Should().StartWithEquivalent($"Column {invalidColumnName} not found.");
            }
        }

        private void GetMethod_NullParameter_ThrowsArgumentNullExeptionException(string methodName, Type paramaterType, string parameterName)
        {
            // Arrange
            using (var table = Samples.OpenBasicTable())
            {
                var reader = table.OpenReader();
                reader.Read();

                // Act & Assert
                var exception = Assert.Throws<ArgumentNullException>(
                    () => ExecuteGetMethod(reader, methodName, parameterType: paramaterType, columnNameOrInstance: null));

                Assert.Equal(parameterName, exception.ParamName);
            }
        }

        private async Task GetMethod_RepeatedColumnOnSeekableStream_ReturnsTheSameValue(bool useAsync, Func<Reader, object> getCall)
        {
            // Arrange
            using (var table = await OpenBasicTable(useAsync))
            {
                var reader = table.OpenReader();

                await reader.Exec(r => r.Read(), useAsync);

                // Act
                var firstValue = getCall(reader);
                var secondValue = getCall(reader);

                // Assert
                Assert.Equal(firstValue, secondValue);
            }
        }

        private async Task GetMethod_ZeroSizeColumn_ReturnsNull(Func<Reader, object> getter, bool useAsync)
        {
            // Arrange
            Stream stream = EmbeddedSamples.GetStream(EmbeddedSamples.ZERO_SIZE_COLUMN);
            using (var table = await this.Exec(() => Table.Open(stream), useAsync))
            {
                var reader = table.OpenReader();
                await reader.Exec((r) => r.Read(), useAsync);

                var expectedValues = new[] { null, "ABCD" };

                // Act
                var actualValues = new[] { getter(reader), reader.GetString("CSU_KRAJ") };

                // Assert
                actualValues.ShouldAllBeEquivalentTo(expectedValues, opt => opt.WithStrictOrdering());
            }
        }

        private async Task GetMethod_FoxProDateTimeColumn_ReturnsCorrectDateTime(bool useAsync, Func<Reader, DateTime?> getMethod, DateTime? expectedValue)
        {
            // Arrange
            Stream stream = EmbeddedSamples.GetStream(EmbeddedSamples.FOXPRO_DATETIME);
            using (var table = await this.Exec(() => Table.Open(stream), useAsync))
            {
                var reader = table.OpenReader();

                DateTime? actualValue = null;

                if (await reader.Exec(r => r.Read(), useAsync))
                {
                    // Act
                    actualValue = getMethod(reader);
                }

                // Assert
                actualValue.TrimMilliseconds().ShouldBeEquivalentTo(expectedValue);
            }
        }

        private async Task GetMethod_CurrencyColumn_ReturnsCorrectDecimal(bool useAsync, Func<Reader, decimal?> getMethod)
        {
            // Arrange
            Stream stream = EmbeddedSamples.GetStream(EmbeddedSamples.CURRENCY_DATA_TYPE);
            using (var table = await this.Exec(() => Table.Open(stream), useAsync))
            {
                var reader = table.OpenReader();

                var actualValues = new List<decimal?>();
                while (await reader.Exec(r => r.Read(), useAsync) && actualValues.Count < Samples.CurrencyDataType.UnitPriceColumn.FirstSixRows.Count)
                {
                    // Act
                    actualValues.Add(getMethod(reader));
                }

                // Assert
                actualValues.ShouldAllBeEquivalentTo(Samples.CurrencyDataType.UnitPriceColumn.FirstSixRows, opt => opt.WithStrictOrdering());
            }
        }

        private Task<Table> OpenBasicTable(bool useAsync)
        {
            return this.Exec(() => Samples.OpenBasicTable(), useAsync);
        }

        private void PublicInterfaceInteraction_DisposedTable_ThrowsObjectDisposedException(Func<Reader, object> action)
        {
            // Arrange
            var table = Samples.OpenBasicTable();
            var reader = table.OpenReader();
            table.Dispose();

            // Act & Assert
            var exception = Assert.Throws<ObjectDisposedException>(() => action(reader));
            Assert.Equal(typeof(Table).FullName, exception.ObjectName);
        }

        private async Task Read_TableWithDeletedRows_SkipsDeletedRows(bool useAsync, Func<Stream, Stream> streamModifier)
        {
            // Arrange
            var stream = streamModifier(EmbeddedSamples.GetStream(EmbeddedSamples.DELETED_ROWS));
            using (var table = await this.Exec(() => Table.Open(stream), useAsync))
            {
                var reader = table.OpenReader();
                var expectedItems = new List<string> { "text3" };
                var actualItems = new List<string>();

                // Act
                while (await reader.Exec(r => r.Read(), useAsync))
                {
                    actualItems.Add(reader.GetString("NAME"));
                }

                // Assert
                actualItems.ShouldAllBeEquivalentTo(expectedItems, opt => opt.WithStrictOrdering());
            }
        }
    }
}


text:
title: Custom Fencing
authors: emesika
wiki_title: Custom Fencing
wiki_revision_count: 11
wiki_last_updated: 2015-03-18
---

# Custom Fencing

Here are detailed instructions how to add a custom agent:

## Pre oVirt 3.5 releases

a) Add your new agent to VdsFenceType option_value in vdc_options table for the relevant cluster version
b) Add agent options mappings to VdsFenceOptionMapping option_value in vdc_options table for the relevant cluster version
c) If the agent maps actually to another agent , add that to FenceAgentMapping option_value in vdc_options
 Example :

        Adding zzz agent support for version 3.3 that maps internally to ipmi and have just port setting (from: port, slot, secure) that maps to the fencing script ipport
        a) VdsFenceType for 3.3 becomes "apc,apc_snmp,bladecenter,cisco_ucs,drac5,eps,ilo,ilo2,ilo3,ilo4,ipmilan,rsa,rsb,wti,zzz"
         b) VdsFenceOptionMapping for 3.3 becomes "apc:secure=secure,port=ipport,slot=port;apc_snmp:port=port;bladecenter:secure=secure,port=ipport,slot=port;cisco_ucs:secure=ssl,slot=port; drac5:secure=secure,slot=port;eps:slot=port;ilo:secure=ssl,port=ipport;ipmilan:;ilo2:secure=ssl,port=ipport;ilo3:;ilo4:;rsa:secure=secure,port=ipport;rsb:;wti:secure=secure,port=ipport,slot=port;zzz:port=ipport"
         c) FenceAgentMapping becomes "ilo2=ilo,ilo3=ipmilan,ilo4=ipmilan,zzz=ipmilan"

NOTES

1) Please backup your database
2) You should restart the engine for this to take place
3) Custom definitions will be overridden in your next upgrade , for the long run please fill RFE so it will be part of the supported agents

## oVirt 3.5

In oVirt 3.5 we had added custom fence configuration keys :

      CustomFenceAgentMapping - Maps a fencing agent to other agent implicitly.
         Format : ((\\w)+[=](\\w)+[,]{0,1})+.
         Example: agent1=agent2,agent3=agent4
      CustomFenceAgentDefaultParams - Default parameters per agent.
         Format ([\\w]+([=][\\w]+){0,1}[,]{0,1})+.
         Example: agent1=key1=val1,flag;key2=val2
      CustomVdsFenceOptionMapping - secure/port/slot mapping support per agent.
         Format ([\\w]+[:]([\\w]*[=][\\w]*[,]{0,1}[;]{0,1}){0,3}[;]{0,1})+.
         Example: agent1:secure=secure;agent2:port=ipport,slot=slot
      CustomVdsFenceType - Fence agents types.
         Format ((\\w)+[,]{0,1})+.
         Example: agent1,agent2
      CustomFencePowerWaitParam - Maps a fencing agent to the param for delay on/off actions.
         Format : ((\\w)+[=](\\w)+[,]{0,1})+.
         Example: agent1=power_wait,agent2=delay

Those keys are accessible from the engine-config util

Example 1 : Adding zzz agent support for version 3.5 that maps internally to ipmi and have just port setting (from: port, slot, secure) that maps to the fencing script ipport

        engine-config -s CustomVdsFenceType="zzz"
        engine-config -s CustomFenceAgentMapping="zzz=ipmilan"
        engine-config -s CustomVdsFenceOptionMapping="zzz:port=ipport"
        engine-config -s CustomFencePowerWaitParam="zzz=power_wait"

Example 2: Adding a new custom fencing device 'yyy' that have just port setting (from: port, slot, secure) that maps to the fencing script ipport First you have to insure that you have a script named fence_yyy in /usr/sbin directory of all servers that might be selected as proxy host for fencing operations

        engine-config -s CustomVdsFenceType="yyy"
        engine-config -s CustomVdsFenceOptionMapping="yyy:port=ipport"
        engine-config -s CustomFencePowerWaitParam="yyy=power_wait"

Example 3: Adding support for Intel Modular agent

       engine-config -s CustomVdsFenceType="intelmodular"
       engine-config -s CustomFencePowerWaitParam="intelmodular=power_wait"
       engine-config -s CustomVdsFenceOptionMapping="intelmodular:port=port"

NOTE : if you have a power management card that needs no other parameters to be set, you still have to set it mapping as empty example

       engine-config -s CustomVdsFenceOptionMapping="zzz:"

In this case those changes remains valid after oVirt upgrades as well, so please use that method from oVirt 3.5 and on.


text:
package com.google.gerrit.server.config;

import com.google.gerrit.common.data.ApprovalType;
import com.google.gerrit.common.data.ApprovalTypes;
import com.google.gerrit.reviewdb.ApprovalCategory;
import com.google.gerrit.reviewdb.ApprovalCategoryValue;
import com.google.gerrit.reviewdb.ReviewDb;
import com.google.gwtorm.client.OrmException;
import com.google.gwtorm.client.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.ProvisionException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class ApprovalTypesProvider implements Provider<ApprovalTypes> {
  private final SchemaFactory<ReviewDb> schema;

  @Inject
  ApprovalTypesProvider(final SchemaFactory<ReviewDb> sf) {
    schema = sf;
  }

  @Override
  public ApprovalTypes get() {
    List<ApprovalType> approvalTypes = new ArrayList<ApprovalType>(2);
    List<ApprovalType> actionTypes = new ArrayList<ApprovalType>(2);

    try {
      final ReviewDb db = schema.open();
      try {
        for (final ApprovalCategory c : db.approvalCategories().all()) {
          final List<ApprovalCategoryValue> values =
              db.approvalCategoryValues().byCategory(c.getId()).toList();
          final ApprovalType type = new ApprovalType(c, values);
          if (type.getCategory().isAction()) {
            actionTypes.add(type);
          } else {
            approvalTypes.add(type);
          }
        }
      } finally {
        db.close();
      }
    } catch (OrmException e) {
      throw new ProvisionException("Cannot query approval categories", e);
    }

    approvalTypes = Collections.unmodifiableList(approvalTypes);
    actionTypes = Collections.unmodifiableList(actionTypes);
    return new ApprovalTypes(approvalTypes, actionTypes);
  }
}


text: Contains kibana3 dockerfile


text:
class CommentsController < ApplicationController
  before_filter :login_required

  def index
    @user = User.find(params[:user_id])
    @entry = Entry.find(params[:entry_id])
    unless @user and @entry == nil
      redirect_to user_entry_path(:user_id => @user, :id => @entry)
    end
  end

  def new
    @comment = Comment.new
    @entry = params[:entry_id]

    respond_to do |format|
      format.html # new.html.erb
      format.js # new.rjs
    end
  end

  def create
    @entry = Entry.find(params[:entry_id])
    @comment = Comment.new(:user_id => @logged_in_user.id, :body => params[:comment][:body])

    if @entry.disable_comment
      respond_to do |format|
        format.html { redirect_to user_entry_path(:user_id => @entry.user, :id => @entry)
          flash[:error] = "這篇文章的設定不允許回覆留言" }
        format.js {render :nothing => true}
      end
    else
      respond_to do |format|

        if @entry.comments << @comment
          format.html { redirect_to user_entry_path(:user_id => @entry.user, :id => @entry)
            flash[:notice] = "你的回覆已成功送出" }
          format.js # create.rjs
        else
          format.html { render :controller => 'comments', :action => 'new' }
          format.js {render :nothing => true}
        end
      end
    end
  end

  def destroy
    @entry = Entry.find_by_user_id_and_id(@logged_in_user.id, params[:entry_id], :include => :user)
    @comment = Comment.find(params[:id])

    respond_to do |format|
      if @comment.entry.user == logged_in_user
        @comment.destroy
        format.html { redirect_to user_entry_path(:user_id => @entry.user.id, :id => @entry.id) }
        format.js # destroy.rjs
      else
        format.html { redirect_to user_entry_path(:user_id => @entry.user.id, :id => @entry.id) }
        format.js {render :nothing => true}
      end
    end
  end
end


text:
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   partial class FileInfo
   {
      #region .NET

      /// Replaces the contents of a specified file with the file described by the current <see cref="FileInfo"/> object, deleting the original file, and creating a backup of the replaced file.
      /// <returns>A <see cref="FileInfo"/> object that encapsulates information about the file described by the <paramref name="destinationFileName"/> parameter.</returns>
      /// <remarks>
      ///   The Replace method replaces the contents of a specified file with the contents of the file described by the current
      ///   <see cref="FileInfo"/> object. It also creates a backup of the file that was replaced. Finally, it returns a new
      ///    <see cref="FileInfo"/> object that describes the overwritten file.
      /// </remarks>
      /// <remarks>Pass null to the <paramref name="destinationBackupFileName"/> parameter if you do not want to create a backup of the file being replaced.</remarks>
      /// <param name="destinationFileName">The name of a file to replace with the current file.</param>
      /// <param name="destinationBackupFileName">The name of a file with which to create a backup of the file described by the <paramref name="destinationFileName"/> parameter.</param>
      [SecurityCritical]
      public FileInfo Replace(string destinationFileName, string destinationBackupFileName)
      {
         return Replace(destinationFileName, destinationBackupFileName, false, PathFormat.RelativePath);
      }

      /// Replaces the contents of a specified file with the file described by the current <see cref="FileInfo"/> object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors.
      /// <returns>A <see cref="FileInfo"/> object that encapsulates information about the file described by the <paramref name="destinationFileName"/> parameter.</returns>
      /// <remarks>
      ///   The Replace method replaces the contents of a specified file with the contents of the file described by the current
      ///   <see cref="FileInfo"/> object. It also creates a backup of the file that was replaced. Finally, it returns a new
      ///   <see cref="FileInfo"/> object that describes the overwritten file.
      /// </remarks>
      /// <remarks>Pass null to the <paramref name="destinationBackupFileName"/> parameter if you do not want to create a backup of the file being replaced.</remarks>
      /// <param name="destinationFileName">The name of a file to replace with the current file.</param>
      /// <param name="destinationBackupFileName">The name of a file with which to create a backup of the file described by the <paramref name="destinationFileName"/> parameter.</param>
      /// <param name="ignoreMetadataErrors"><c>true</c> to ignore merge errors (such as attributes and ACLs) from the replaced file to the replacement file; otherwise, <c>false</c>.</param>
      [SecurityCritical]
      public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors)
      {
         return Replace(destinationFileName, destinationBackupFileName, ignoreMetadataErrors, PathFormat.RelativePath);
      }

      #endregion // .NET

      /// [AlphaFS] Replaces the contents of a specified file with the file described by the current <see cref="FileInfo"/> object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors.
      /// <returns>A <see cref="FileInfo"/> object that encapsulates information about the file described by the <paramref name="destinationFileName"/> parameter.</returns>
      /// <remarks>
      ///   The Replace method replaces the contents of a specified file with the contents of the file described by the current
      ///   <see cref="FileInfo"/> object. It also creates a backup of the file that was replaced. Finally, it returns a new
      ///   <see cref="FileInfo"/> object that describes the overwritten file.
      /// </remarks>
      /// <remarks>Pass null to the <paramref name="destinationBackupFileName"/> parameter if you do not want to create a backup of the file being replaced.</remarks>
      /// <param name="destinationFileName">The name of a file to replace with the current file.</param>
      /// <param name="destinationBackupFileName">The name of a file with which to create a backup of the file described by the <paramref name="destinationFileName"/> parameter.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public FileInfo Replace(string destinationFileName, string destinationBackupFileName, PathFormat pathFormat)
      {
         return Replace(destinationFileName, destinationBackupFileName, false, pathFormat);
      }

      /// [AlphaFS] Replaces the contents of a specified file with the file described by the current <see cref="FileInfo"/> object, deleting the original file, and creating a backup of the replaced file. Also specifies whether to ignore merge errors.
      /// <returns>A <see cref="FileInfo"/> object that encapsulates information about the file described by the <paramref name="destinationFileName"/> parameter.</returns>
      /// <remarks>
      ///   The Replace method replaces the contents of a specified file with the contents of the file described by the current
      ///   <see cref="FileInfo"/> object. It also creates a backup of the file that was replaced. Finally, it returns a new
      ///   <see cref="FileInfo"/> object that describes the overwritten file.
      /// </remarks>
      /// <remarks>Pass null to the <paramref name="destinationBackupFileName"/> parameter if you do not want to create a backup of the file being replaced.</remarks>
      /// <param name="destinationFileName">The name of a file to replace with the current file.</param>
      /// <param name="destinationBackupFileName">The name of a file with which to create a backup of the file described by the <paramref name="destinationFileName"/> parameter.</param>
      /// <param name="ignoreMetadataErrors"><c>true</c> to ignore merge errors (such as attributes and ACLs) from the replaced file to the replacement file; otherwise, <c>false</c>.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors, PathFormat pathFormat)
      {
         const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck;

         var destinationFileNameLp = Path.GetExtendedLengthPathCore(Transaction, destinationFileName, pathFormat, options);

         var destinationBackupFileNameLp = destinationBackupFileName != null
            ? Path.GetExtendedLengthPathCore(Transaction, destinationBackupFileName, pathFormat, options)
            : null;

         File.ReplaceCore(LongFullName, destinationFileNameLp, destinationBackupFileNameLp, ignoreMetadataErrors, PathFormat.LongFullPath);

         return new FileInfo(Transaction, destinationFileNameLp, PathFormat.LongFullPath);
      }
   }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager;

namespace Azure.ResourceManager.Network.Models
{
    public partial class Probe : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            writer.WritePropertyName("id");
            writer.WriteStringValue(Id);
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(Protocol))
            {
                writer.WritePropertyName("protocol");
                writer.WriteStringValue(Protocol.Value.ToString());
            }
            if (Optional.IsDefined(Port))
            {
                writer.WritePropertyName("port");
                writer.WriteNumberValue(Port.Value);
            }
            if (Optional.IsDefined(IntervalInSeconds))
            {
                writer.WritePropertyName("intervalInSeconds");
                writer.WriteNumberValue(IntervalInSeconds.Value);
            }
            if (Optional.IsDefined(NumberOfProbes))
            {
                writer.WritePropertyName("numberOfProbes");
                writer.WriteNumberValue(NumberOfProbes.Value);
            }
            if (Optional.IsDefined(RequestPath))
            {
                writer.WritePropertyName("requestPath");
                writer.WriteStringValue(RequestPath);
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static Probe DeserializeProbe(JsonElement element)
        {
            Optional<string> name = default;
            Optional<string> etag = default;
            Optional<string> type = default;
            ResourceIdentifier id = default;
            Optional<IReadOnlyList<SubResource>> loadBalancingRules = default;
            Optional<ProbeProtocol> protocol = default;
            Optional<int> port = default;
            Optional<int> intervalInSeconds = default;
            Optional<int> numberOfProbes = default;
            Optional<string> requestPath = default;
            Optional<ProvisioningState> provisioningState = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("etag"))
                {
                    etag = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("loadBalancingRules"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<SubResource> array = new List<SubResource>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(SubResource.DeserializeSubResource(item));
                            }
                            loadBalancingRules = array;
                            continue;
                        }
                        if (property0.NameEquals("protocol"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            protocol = new ProbeProtocol(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("port"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            port = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("intervalInSeconds"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            intervalInSeconds = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("numberOfProbes"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            numberOfProbes = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("requestPath"))
                        {
                            requestPath = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new ProvisioningState(property0.Value.GetString());
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new Probe(id, name.Value, etag.Value, type.Value, Optional.ToList(loadBalancingRules), Optional.ToNullable(protocol), Optional.ToNullable(port), Optional.ToNullable(intervalInSeconds), Optional.ToNullable(numberOfProbes), requestPath.Value, Optional.ToNullable(provisioningState));
        }
    }
}


text:
/**
 *  \file   cpsw.h
 *
 *  \brief  CPSW APIs and macros.
 *
 *   This file contains the driver API prototypes and macro definitions.
 */

/*
* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/
*/
/*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*    Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
*
*    Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the
*    distribution.
*
*    Neither the name of Texas Instruments Incorporated nor the names of
*    its contributors may be used to endorse or promote products derived
*    from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/

#ifndef __CPSW_H__
#define __CPSW_H__

#include "hw_cpsw_ale.h"
#include "hw_cpsw_cpdma.h"
#include "hw_cpsw_port.h"
#include "hw_cpsw_sl.h"
#include "hw_cpsw_ss.h"
#include "hw_cpsw_wr.h"

#ifdef __cplusplus
extern "C" {
#endif

/*****************************************************************************/
/*
** Macros which can be used as 'mode' to pass to the API CPSWSlTransferModeSet
*/
#define CPSW_SLIVER_NON_GIG_FULL_DUPLEX        CPSW_SL_MACCONTROL_FULLDUPLEX
#define CPSW_SLIVER_NON_GIG_HALF_DUPLEX        (0x00u)
#define CPSW_SLIVER_GIG_FULL_DUPLEX            CPSW_SL_MACCONTROL_GIG

/*
** Macros which can be used as 'statFlag' to the API CPSWSlMACStatusGet
*/
#define CPSW_SLIVER_STATE                      CPSW_SL_MACSTATUS_IDLE
#define CPSW_SLIVER_EXT_GIG_INPUT_BIT          CPSW_SL_MACSTATUS_EXT_GIG
#define CPSW_SLIVER_EXT_FULL_DUPLEX_BIT        CPSW_SL_MACSTATUS_EXT_FULLDUPLEX
#define CPSW_SLIVER_RX_FLOWCTRL                CPSW_SL_MACSTATUS_RX_FLOW_ACT
#define CPSW_SLIVER_TX_FLOWCTRL                CPSW_SL_MACSTATUS_TX_FLOW_ACT

/*
** Macros returned by API CPSWSlMACStatusGet
*/
#define CPSW_SLIVER_STATE_IDLE                 CPSW_SL_MACSTATUS_IDLE
#define CPSW_SLIVER_EXT_GIG_INPUT_HIGH         CPSW_SL_MACSTATUS_EXT_GIG
#define CPSW_SLIVER_EXT_FULL_DUPLEX_HIGH       CPSW_SL_MACSTATUS_EXT_FULLDUPLEX
#define CPSW_SLIVER_RX_FLOWCTRL_ACTIVE         CPSW_SL_MACSTATUS_RX_FLOW_ACT
#define CPSW_SLIVER_TX_FLOWCTRL_ACTIVE         CPSW_SL_MACSTATUS_TX_FLOW_ACT

/*
** Macros which can be passed asi 'intFlag' to the API CPSWWrCoreIntEnable
** , CPSWWrCoreIntDisable and CPSWWrCoreIntStatusGet
*/
#define CPSW_CORE_INT_RX_THRESH                (0x00u)
#define CPSW_CORE_INT_RX_PULSE                 (0x04u)
#define CPSW_CORE_INT_TX_PULSE                 (0x08u)
#define CPSW_CORE_INT_MISC                     (0x0Cu)

/*
** Macros which can be passed as 'statFlag' to the API CPSWWrRGMIIStatusGet
*/
#define CPSW_RGMII2_DUPLEX                     CPSW_WR_RGMII_CTL_RGMII2_FULLDUPLEX
#define CPSW_RGMII2_SPEED                      CPSW_WR_RGMII_CTL_RGMII2_SPEED
#define CPSW_RGMII2_LINK_STAT                  CPSW_WR_RGMII_CTL_RGMII2_LINK
#define CPSW_RGMII1_DUPLEX                     CPSW_WR_RGMII_CTL_RGMII1_FULLDUPLEX
#define CPSW_RGMII1_SPEED                      CPSW_WR_RGMII_CTL_RGMII1_SPEED
#define CPSW_RGMII1_LINK_STAT                  CPSW_WR_RGMII_CTL_RGMII1_LINK

/* The values, one of which will be returned by CPSWWrRGMIIStatusGet */
#define CPSW_RGMII2_DUPLEX_FULL                CPSW_WR_RGMII_CTL_RGMII2_FULLDUPLEX
#define CPSW_RGMII2_DUPLEX_HALF                (0x00u)
#define CPSW_RGMII2_SPEED_10M                  (0x00u << CPSW_WR_RGMII_CTL_RGMII2_SPEED_SHIFT)
#define CPSW_RGMII2_SPEED_100M                 (0x01u << CPSW_WR_RGMII_CTL_RGMII2_SPEED_SHIFT)
#define CPSW_RGMII2_SPEED_1000M                (0x02u << CPSW_WR_RGMII_CTL_RGMII2_SPEED_SHIFT)
#define CPSW_RGMII2_LINK_UP                    CPSW_WR_RGMII_CTL_RGMII2_LINK
#define CPSW_RGMII2_LINK_DOWN                  (0x00u)
#define CPSW_RGMII1_DUPLEX_FULL                CPSW_WR_RGMII_CTL_RGMII1_FULLDUPLEX
#define CPSW_RGMII1_DUPLEX_HALF                (0x00u)
#define CPSW_RGMII1_SPEED_10M                  (0x00u << CPSW_WR_RGMII_CTL_RGMII1_SPEED_SHIFT)
#define CPSW_RGMII1_SPEED_100M                 (0x01u << CPSW_WR_RGMII_CTL_RGMII1_SPEED_SHIFT)
#define CPSW_RGMII1_SPEED_1000M                (0x02u << CPSW_WR_RGMII_CTL_RGMII1_SPEED_SHIFT)
#define CPSW_RGMII1_LINK_UP                    CPSW_WR_RGMII_CTL_RGMII1_LINK
#define CPSW_RGMII1_LINK_DOWN                  (0x00u)

/*
** Macros which can be passed as 'pacFlag' to the API CPSWWrIntPacingEnable
** CPSWWrIntPacingDisable
*/
#define CPSW_INT_PACING_C0_RX_PULSE            (0x01 << CPSW_WR_INT_CONTROL_INT_PACE_EN_SHIFT)
#define CPSW_INT_PACING_C0_TX_PULSE            (0x02 << CPSW_WR_INT_CONTROL_INT_PACE_EN_SHIFT)
#define CPSW_INT_PACING_C1_RX_PULSE            (0x04 << CPSW_WR_INT_CONTROL_INT_PACE_EN_SHIFT)
#define CPSW_INT_PACING_C1_TX_PULSE            (0x08 << CPSW_WR_INT_CONTROL_INT_PACE_EN_SHIFT)
#define CPSW_INT_PACING_C2_RX_PULSE            (0x10 << CPSW_WR_INT_CONTROL_INT_PACE_EN_SHIFT)
#define CPSW_INT_PACING_C2_TX_PULSE            (0x20 << CPSW_WR_INT_CONTROL_INT_PACE_EN_SHIFT)

/*
** Macros which can be passed as 'portState' to CPSWALEPortStateSet
*/
#define CPSW_ALE_PORT_STATE_FWD                (0x03u)
#define CPSW_ALE_PORT_STATE_LEARN              (0x02u)
#define CPSW_ALE_PORT_STATE_BLOCKED            (0x01u)
#define CPSW_ALE_PORT_STATE_DISABLED           (0x00u)

/*
** Macros which can be passed as 'eoiFlag' to CPSWCPDMAEndOfIntVectorWrite
*/
#define CPSW_EOI_TX_PULSE                      (0x02u)
#define CPSW_EOI_RX_PULSE                      (0x01u)
#define CPSW_EOI_RX_THRESH_PULSE               (0x00u)
#define CPSW_EOI_MISC_PULSE                    (0x03u)

/*
** Macro which can be passed as 'statFlag' to CPSWCPDMAStatusGet
** The same value can be used to compare against the idle status
*/
#define CPDMA_STAT_IDLE                        (CPSW_CPDMA_DMASTATUS_IDLE)

/*
** Macro which can be passed as 'statFlag' to CPSWCPDMAStatusGet
*/
#define CPDMA_STAT_TX_HOST_ERR_CODE            (CPSW_CPDMA_DMASTATUS_TX_HOST_ERR_CODE)

/* The return values for the above 'statFlag' */
#define CPDMA_STAT_TX_NO_ERR                   (0x00u << CPSW_CPDMA_DMASTATUS_TX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_TX_SOP_ERR                  (0x01u << CPSW_CPDMA_DMASTATUS_TX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_TX_OWN_ERR                  (0x02u << CPSW_CPDMA_DMASTATUS_TX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_TX_ZERO_DESC                (0x03u << CPSW_CPDMA_DMASTATUS_TX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_TX_ZERO_BUF_PTR             (0x04u << CPSW_CPDMA_DMASTATUS_TX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_TX_ZERO_BUF_LEN             (0x05u << CPSW_CPDMA_DMASTATUS_TX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_TX_PKT_LEN_ERR              (0x06u << CPSW_CPDMA_DMASTATUS_TX_HOST_ERR_CODE_SHIFT)

/*
** Macro which can be passed as 'statFlag' to CPSWCPDMAStatusGet
*/
#define CPDMA_STAT_RX_HOST_ERR_CODE            (CPSW_CPDMA_DMASTATUS_RX_HOST_ERR_CODE)

/* The return values for the above 'statFlag' */
#define CPDMA_STAT_RX_NO_ERR                   (0x00u << CPSW_CPDMA_DMASTATUS_RX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_RX_OWN_NOT_SET              (0x02u << CPSW_CPDMA_DMASTATUS_RX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_RX_ZERO_BUF_PTR             (0x04u << CPSW_CPDMA_DMASTATUS_RX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_RX_ZERO_BUF_LEN             (0x05u << CPSW_CPDMA_DMASTATUS_RX_HOST_ERR_CODE_SHIFT)
#define CPDMA_STAT_RX_SOP_BUF_LEN_ERR          (0x06u << CPSW_CPDMA_DMASTATUS_RX_HOST_ERR_CODE_SHIFT)

/*
** Macros which can be passed as 'statFlag' to CPSWCPDMAStatusGet
*/
#define CPDMA_STAT_TX_HOST_ERR_CHAN            (CPSW_CPDMA_DMASTATUS_TX_ERR_CH | 0x10u)
#define CPDMA_STAT_RX_HOST_ERR_CHAN            (CPSW_CPDMA_DMASTATUS_RX_ERR_CH | 0x08u)

/*
** Macro which can be passed as 'cfg' to the API CPSWCPDMAConfig
** The values for individual fields are also listed below.
*/
#define CPDMA_CFG(tx_rlim, rx_cef, cmd_idle, rx_offlen_blk, rx_own, tx_ptype) \
             (tx_rlim | rx_cef | cmd_idle | rx_offlen_blk | rx_own | tx_ptype)
/* Values for 'tx_rlim' */
#define CPDMA_CFG_TX_RATE_LIM_CH_7             (0x80u << CPSW_CPDMA_DMACONTROL_TX_RLIM_SHIFT)
#define CPDMA_CFG_TX_RATE_LIM_CH_7_TO_6        (0xC0u << CPSW_CPDMA_DMACONTROL_TX_RLIM_SHIFT)
#define CPDMA_CFG_TX_RATE_LIM_CH_7_TO_5        (0xE0u << CPSW_CPDMA_DMACONTROL_TX_RLIM_SHIFT)
#define CPDMA_CFG_TX_RATE_LIM_CH_7_TO_4        (0xF0u << CPSW_CPDMA_DMACONTROL_TX_RLIM_SHIFT)
#define CPDMA_CFG_TX_RATE_LIM_CH_7_TO_3        (0xF8u << CPSW_CPDMA_DMACONTROL_TX_RLIM_SHIFT)
#define CPDMA_CFG_TX_RATE_LIM_CH_7_TO_2        (0xFCu << CPSW_CPDMA_DMACONTROL_TX_RLIM_SHIFT)
#define CPDMA_CFG_TX_RATE_LIM_CH_7_TO_1        (0xFEu << CPSW_CPDMA_DMACONTROL_TX_RLIM_SHIFT)
#define CPDMA_CFG_TX_RATE_LIM_CH_7_TO_0        (0xFFu << CPSW_CPDMA_DMACONTROL_TX_RLIM_SHIFT)

/* Values for 'rx_cef' */
#define CPDMA_CFG_COPY_ERR_FRAMES              (CPSW_CPDMA_DMACONTROL_RX_CEF)
#define CPDMA_CFG_NO_COPY_ERR_FRAMES           (0x00u)

/* Values for 'cmd_idle' */
#define CPDMA_CFG_IDLE_COMMAND                 (CPSW_CPDMA_DMACONTROL_CMD_IDLE)
#define CPDMA_CFG_IDLE_COMMAND_NONE            (0x00u)

/* Values for 'rx_offlen_blk' */
#define CPDMA_CFG_BLOCK_RX_OFF_LEN_WRITE       (CPSW_CPDMA_DMACONTROL_RX_OFFLEN_BLOCK)
#define CPDMA_CFG_NOT_BLOCK_RX_OFF_LEN_WRITE   (0x00u)

/* Values for 'rx_own' */
#define CPDMA_CFG_RX_OWN_1                     (CPSW_CPDMA_DMACONTROL_RX_OWNERSHIP)
#define CPDMA_CFG_RX_OWN_0                     (0x00u)

/* Values for 'tx_ptype' */
#define CPDMA_CFG_TX_PRI_ROUND_ROBIN           (CPSW_CPDMA_DMACONTROL_TX_PTYPE)
#define CPDMA_CFG_TX_PRI_FIXED                 (0x00u)

/*
** Macros which can be passed as 'intType' to CPSWCPDMARxIntStatRawGet
** and CPSWCPDMARxIntStatMaskedGet
*/
#define CPDMA_RX_INT_THRESH_PEND               (0x08u)
#define CPDMA_RX_INT_PULSE_PEND                (0x00u)

#define CPSW_MAX_NUM_ALE_ENTRY                 (1024)
#define CPSW_SIZE_CPPI_RAM                     (8192)

/*
** Structure to save CPSW context
*/
typedef struct cpswContext {
    unsigned int aleBase;
    unsigned int ssBase;
    unsigned int port1Base;
    unsigned int port2Base;
    unsigned int cpdmaBase;
    unsigned int cppiRamBase;
    unsigned int wrBase;
    unsigned int sl1Base;
    unsigned int sl2Base;
    unsigned int aleCtrl;
    unsigned int alePortCtl[3];
    unsigned int aleEntry[CPSW_MAX_NUM_ALE_ENTRY * 3];
    unsigned int ssStatPortEn;
    unsigned int port1SaHi;
    unsigned int port1SaLo;
    unsigned int port2SaHi;
    unsigned int port2SaLo;
    unsigned int cpdmaRxFB;
    unsigned int cpdmaTxCtl;
    unsigned int cpdmaRxCtl;
    unsigned int cpdmaRxHdp;
    unsigned int txIntMaskSet;
    unsigned int rxIntMaskSet;
    unsigned int wrCoreIntTxPulse;
    unsigned int wrCoreIntRxPulse;
    unsigned int sl1MacCtl;
    unsigned int sl2MacCtl;
    unsigned int cppiRam[CPSW_SIZE_CPPI_RAM];
} CPSWCONTEXT;

/*****************************************************************************/
/*
** Prototypes for the APIs
*/
extern void CPSWSSReset(unsigned int baseAddr);
extern void CPSWSlControlExtEnable(unsigned int baseAddr);
extern void CPSWSlRxShortFramesCopyEnable(unsigned int baseAddr);
extern void CPSWSlRxShortFramesCopyDisable(unsigned int baseAddr);
extern void CPSWSlTxShortGapLimitEnable(unsigned int baseAddr);
extern void CPSWSlTxShortGapLimitDisable(unsigned int baseAddr);
extern void CPSWSlGigModeForceEnable(unsigned int baseAddr);
extern void CPSWSlGigModeForceDisable(unsigned int baseAddr);
extern void CPSWSlTransferModeSet(unsigned int baseAddr, unsigned int mode);
extern unsigned int CPSWSlMACStatusGet(unsigned int baseAddr, unsigned int statFlag);
extern void CPSWSlReset(unsigned int baseAddr);
extern void CPSWSlRxMaxLenSet(unsigned int baseAddr, unsigned int rxMaxLen);
extern void CPSWSlRxPauseTmrSet(unsigned int baseAddr, unsigned int rxPauseTmr);
extern unsigned int CPSWSlRxPauseTmrGet(unsigned int baseAddr);
extern void CPSWSlTxPauseTmrSet(unsigned int baseAddr, unsigned int txPauseTmr);
extern unsigned int CPSWSlTxPauseTmrGet(unsigned int baseAddr);
extern void CPSWSlTxIntrPktGapSet(unsigned int baseAddr, unsigned int intrPktGap);
extern void CPSWSlGMIIEnable(unsigned int baseAddr);
extern void CPSWSlRGMIIEnable(unsigned int baseAddr);
extern void CPSWWrReset(unsigned int baseAddr);
extern void CPSWWrControlRegReset(unsigned int baseAddr);
extern void CPSWWrCoreIntEnable(unsigned int baseAddr, unsigned int core,
                         unsigned int channel, unsigned int intFlag);
extern void CPSWWrCoreIntDisable(unsigned int baseAddr, unsigned int core,
                          unsigned int channel, unsigned int intFlag);
extern unsigned int CPSWWrCoreIntStatusGet(unsigned int baseAddr, unsigned int core,
                                    unsigned int channel, unsigned int intFlag);
extern unsigned int CPSWWrRGMIIStatusGet(unsigned int baseAddr, unsigned int statFlag);
extern void CPSWWrIntPacingEnable(unsigned int baseAddr, unsigned int pacFlag);
extern void CPSWWrIntTxPerMsSet(unsigned int baseAddr, unsigned int core,
                         unsigned int txIntPerMs);
extern void CPSWWrIntRxPerMsSet(unsigned int baseAddr, unsigned int core,
                         unsigned int rxIntPerMs);
extern void CPSWWrIntPacingDisable(unsigned int baseAddr, unsigned int pacFlag);
extern void CPSWALEInit(unsigned int baseAddr);
extern void CPSWALEPortStateSet(unsigned int baseAddr, unsigned int portNum,
                         unsigned int portState);
extern void CPSWALETableEntrySet(unsigned int baseAddr, unsigned int aleTblIdx,
                          unsigned int *aleEntryPtr);
extern void CPSWALETableEntryGet(unsigned int baseAddr, unsigned int aleTblIdx,
                          unsigned int *aleEntryPtr);
extern void CPSWALELearnModeEnable(unsigned int baseAddr, unsigned int  portNum);
extern void CPSWALELearnModeDisable(unsigned int baseAddr, unsigned int  portNum);
extern void CPSWALEBCastPktRateLimitSet(unsigned int baseAddr, unsigned int  portNum,
                                 unsigned int rateLtVal);
extern void CPSWALEMCastPktRateLimitSet(unsigned int baseAddr, unsigned int  portNum,
                                 unsigned int rateLtVal);
extern void CPSWALESrcPortNumUpdateEnable(unsigned int baseAddr, unsigned int portNum);
extern void CPSWALESrcPortNumUpdateDisable(unsigned int baseAddr, unsigned int portNum);
extern unsigned int CPSWALEPrescaleGet(unsigned int baseAddr);
extern void CPSWALEPrescaleSet(unsigned int baseAddr, unsigned int psVal);
extern void CPSWALEAddrTblAgeOut(unsigned int baseAddr);
extern void CPSWALEP0UcastFloodEnable(unsigned int baseAddr);
extern void CPSWALEP0UcastFloodDisable(unsigned int baseAddr);
extern void CPSWALEBypassEnable(unsigned int baseAddr);
extern void CPSWALEBypassDisable(unsigned int baseAddr);
extern void CPSWRxFlowControlEnable(unsigned int baseAddr, unsigned int portNum);
extern void CPSWRxFlowControlDisable(unsigned int baseAddr, unsigned int portNum);
extern void CPSWSoftwareIdleEnable(unsigned int baseAddr);
extern void CPSWSoftwareIdleDisable(unsigned int baseAddr, unsigned int portNum);
extern void CPSWStatisticsEnable(unsigned int baseAddr);
extern void CPSWVLANAwareDisable(unsigned int baseAddr);
extern void CPSWPortSrcAddrSet(unsigned int baseAddr, unsigned char *ethAddr);
extern void CPSWPortTxHdrPriMapSet(unsigned int baseAddr, unsigned int txPriMap);
extern void CPSWPortTxMaxBlksSet(unsigned int baseAddr, unsigned int maxBlks);
extern void CPSWPortRxMaxBlksSet(unsigned int baseAddr, unsigned int maxBlks);
extern void CPSWPortTxFIFOInputRateEnable(unsigned int baseAddr);
extern void CPSWPortTxFIFOInputRateDisable(unsigned int baseAddr);
extern void CPSWPortTxFIFONormalPrioModeSet(unsigned int baseAddr);
extern void CPSWPortTxFIFODualMACModeSet(unsigned int baseAddr, unsigned int blksRem);
extern void CPSWPortRateLimitModeSet(unsigned int baseAddr);
extern void CPSWPortTxFIFOWordsSet(unsigned int baseAddr, unsigned int txPriWds);
extern void CPSWPortRxDscpPriMapSet(unsigned int baseAddr, unsigned int priReg,
                             unsigned int priMap);
extern unsigned int CPSWStatisticsGet(unsigned int baseAddr, unsigned int statReg);
extern void CPSWCPDMARxFlowThreshSet(unsigned int baseAddr, unsigned int channel,
                              unsigned int threshVal);
extern void CPSWCPDMATxChanTearDown(unsigned int baseAddr, unsigned int channel);
extern void CPSWCPDMARxChanTearDown(unsigned int baseAddr, unsigned int channel);
extern void CPSWCPDMAReset(unsigned int baseAddr);
extern void CPSWCPDMACmdIdleEnable(unsigned int baseAddr);
extern void CPSWCPDMACmdIdleDisable(unsigned int baseAddr);
extern void CPSWCPDMATxIntEnable(unsigned int baseAddr, unsigned int channel);
extern void CPSWCPDMARxIntEnable(unsigned int baseAddr, unsigned int channel);
extern void CPSWCPDMATxIntDisable(unsigned int baseAddr, unsigned int channel);
extern void CPSWCPDMARxIntDisable(unsigned int baseAddr, unsigned int channel);
extern void CPSWCPDMATxEnable(unsigned int baseAddr);
extern void CPSWCPDMARxEnable(unsigned int baseAddr);
extern void CPSWCPDMATxHdrDescPtrWrite(unsigned int baseAddr, unsigned int descHdr,
                                unsigned int channel);
extern void CPSWCPDMARxHdrDescPtrWrite(unsigned int baseAddr, unsigned int descHdr,
                                unsigned int channel);
extern void CPSWCPDMAEndOfIntVectorWrite(unsigned int baseAddr, unsigned int eoiFlag);
extern void CPSWCPDMATxCPWrite(unsigned int baseAddr, unsigned int channel,
                        unsigned int comPtr);
extern void CPSWCPDMARxCPWrite(unsigned int baseAddr, unsigned int channel,
                        unsigned int comPtr);
extern void CPSWCPDMANumFreeBufSet(unsigned int baseAddr, unsigned int channel,
                            unsigned int nBuf);
extern unsigned int CPSWCPDMAStatusGet(unsigned int baseAddr, unsigned int statFlag);
extern void CPSWCPDMAConfig(unsigned int baseAddr, unsigned int cfg);
extern void CPSWCPDMARxBufOffsetSet(unsigned int baseAddr, unsigned int bufOff);
extern unsigned int CPSWCPDMATxIntStatRawGet(unsigned int baseAddr,
                                      unsigned int chanMask);
extern unsigned int CPSWCPDMATxIntStatMaskedGet(unsigned int baseAddr,
                                         unsigned int chanMask);
extern unsigned int CPSWCPDMARxIntStatRawGet(unsigned int baseAddr,
                                      unsigned int chanMask,
                                      unsigned int intType);
extern unsigned int CPSWCPDMARxIntStatMaskedGet(unsigned int baseAddr,
                                         unsigned int channel,
                                         unsigned int intFlag);
extern void CPSWContextSave(CPSWCONTEXT *contextPtr);
extern void CPSWContextRestore(CPSWCONTEXT *contextPtr);

#ifdef __cplusplus
}
#endif

#endif /* __CPSW_H__ */


text:
var express = require('express');
var expressValidator = require('../../index');
var bodyParser = require('body-parser');
var Promise = require('bluebird');

var port = process.env.PORT || 8888;
var app = express();

module.exports = function(validation) {

  app.set('port', port);
  app.use(bodyParser.json());
  app.use(expressValidator({
    customValidators: {
      isArray: function(value) {
        return Array.isArray(value);
      },
      isAsyncTest: function(testparam) {
        return new Promise(function(resolve, reject) {
          setTimeout(function() {
            if (testparam === '42') { return resolve(); }
            reject();
          }, 200);
        });
      }
    },
    customSanitizers: {
      toTestSanitize: function() {
        return "!!!!";
      }
    }
  }));

  app.get(/\/test(\d+)/, validation);
  app.get('/:testparam?', validation);
  app.post('/:testparam?', validation);

  return app;
};


text:
class dht11
{
public:
    int read(int pin);
	int humidity;
	int temperature;
};
#endif
//
// END OF FILE
//


text:
package com.github.blahord.bettercollections.compatibility;

import org.testng.annotations.Test;

import static com.github.blahord.bettercollections.util.Lists.asList;
import static org.assertj.core.api.Java6Assertions.assertThat;

@Test(groups = "unit-tests")
public class JavaIterableTest {

    public void testIterator() throws Exception {
        final java.lang.Iterable<Integer> javaCollection = new JavaIterable<>(asList(1, 2, 3, 4, 5, 6));
        final java.util.Iterator<Integer> javaIterator = javaCollection.iterator();
        assertThat(javaIterator.getClass()).isEqualTo(JavaIterator.class);

        assertThat(javaIterator.next()).isEqualTo(1);
        assertThat(javaIterator.next()).isEqualTo(2);
        assertThat(javaIterator.next()).isEqualTo(3);
        assertThat(javaIterator.next()).isEqualTo(4);
        assertThat(javaIterator.next()).isEqualTo(5);
        assertThat(javaIterator.next()).isEqualTo(6);
        assertThat(javaIterator.hasNext()).isFalse();
    }
}