text:
package com.juaby.labs.rpc.test;

/**
 * Created by Juaby on 2015/8/28.
 */
public interface InterfaceObject extends InterfaceObject2 {

    public <V> V vmethod();
    public <V> void vmethod(V v);
    public void vmethod3();
    public <V, R> R vmethod2(V v);

}


text:
set :rails_env, :production

# Настраиваем ssh до сервера
server "<--input production host-->", :app, :web, :db, :primary => true

# Авторизационные данные
set :user, "<%= capprojectname %>"
set :group, "<%= capprojectname %>"
set :password, '<--password-->'
set :keep_releases, 5
set :repository, 'prod'

redpajama_set_name: RedPajamaGithub


text:
Homework: Console IO
====================

### Problem List

1. [Sum of 3 numbers](./01. SumOf3Numbers)
1. [Company info](./02.CompanyInfo)
1. [Circle](./03.Circle)
1. [Formatting Numbers](./04.FormattingNumbers)
1. [Number Comparer](./05.NumbersComparer)
1. [Quadratic Equation](./06.QuadraticEquation)
1. [Sum of 5 numbers](./07.Sumof5 Numbers)
1. [Numbers from 1 to N](./08.NumbersFrom 1toN)
1. [Sum of N Numbers](./09.SumOfNNumbers)
1. [Fibonacci Numbers](./10.FibonacciNumbers)
1. [Interval](./11.Interval)


text:
package tests;

import java.util.concurrent.TimeUnit;

public class Benchmarker {

	private final TimeUnit unit;
	private long start = -1, end = -1;
	private long accumulator = 0;
	private boolean seconds = false;

	public Benchmarker(TimeUnit unit){
		this.unit = unit == TimeUnit.SECONDS ? TimeUnit.MILLISECONDS : unit;

		if(unit == TimeUnit.SECONDS)
			seconds = true;
	}

	public void zero(){
		start = System.nanoTime();
	}

	public void reset(){
		zero();
		accumulator = 0;
	}

	public long benchmark(){
		return benchmark(true);
	}

	public long benchmark(boolean print){
		if(start == -1){
			zero();
			System.out.println("BENCHMARK WARNING: Benchmarker not Zeroed using zero() before benchmarking.");
			System.out.println("BENCHMARK WARNING: This is likely an error!");
		}
		end = System.nanoTime();

		long diff = unit.convert(end - start, TimeUnit.NANOSECONDS);

		if(print)
			if(seconds)
				System.out.printf("Time Difference: %.03f %s", (float)diff/1000.0f, Benchmarker.getEndingFor(TimeUnit.SECONDS));
			else
				System.out.println("Time Difference: " + diff + " " + Benchmarker.getEndingFor(unit));

		accumulator += diff;
		start = end;

		return diff;
	}

	public float getAccumulatedDifference(){
		return seconds ? (float)accumulator/1000.0f : accumulator;
	}

	public String getUnitSuffix(){
		return Benchmarker.getEndingFor(seconds ? TimeUnit.SECONDS : unit);
	}

	private static String getEndingFor(TimeUnit unit){
		switch(unit){
		case DAYS:
			return "d";
		case HOURS:
			return "h";
		case MINUTES:
			return "m";
		case SECONDS:
			return "s";
		case MILLISECONDS:
			return "millis";
		case MICROSECONDS:
			return "micros";
		case NANOSECONDS:
			return "nanos";
		default:
			return "";
		}
	}
}


text:
from nose.tools import eq_
from xml.etree import ElementTree
from utils import with_app, pretty_print_xml
from sphinxcontrib.traceables.infrastructure import (Traceable,
                                                     TraceablesStorage)
from sphinxcontrib.traceables.matrix import TraceableMatrix

# =============================================================================
# Tests

@with_app(buildername="xml", srcdir="traceable_matrix", warningiserror=True)
def test_traceable_matrix(app, status, warning):
    app.build()
    storage = TraceablesStorage(app.env)
#    tree = ElementTree.parse(app.outdir / "index.xml")
#    pretty_print_xml(tree.getroot())

    # Construct a traceable matrix.
    forward = "children"
    backward = storage.get_relationship_opposite(forward)
    matrix = TraceableMatrix(forward, backward)
    for traceable in storage.traceables_set:
        relatives = traceable.relationships.get(forward, ())
        for relative in relatives:
            matrix.add_traceable_pair(traceable, relative)

    # Verify correct primaries and secondaries.
    eq_([t.tag for t in matrix.primaries], [u"CEPHEUS", u"SAGITTA"])
    eq_([t.tag for t in matrix.secondaries], [u"AQUILA", u"AURIGA", u"LYRA"])

    # Verify correct splitting of traceable matrix.
    submatrices = matrix.split(2)
    eq_(len(submatrices), 2)
    verify_submatrices(matrix, submatrices)

    submatrices = matrix.split(2, 1)
    eq_(len(submatrices), 4)
    verify_submatrices(matrix, submatrices)

    submatrices = matrix.split(1)
    eq_(len(submatrices), 3)
    verify_submatrices(matrix, submatrices)

    submatrices = matrix.split(None, 1)
    eq_(len(submatrices), 2)
    verify_submatrices(matrix, submatrices)

def verify_submatrices(matrix, submatrices):
    for submatrix in submatrices:
        for primary in submatrix.primaries:
            boolean_row = submatrix.get_boolean_row(primary)
            for (is_related, secondary) in zip(boolean_row,
                                               submatrix.secondaries):
                eq_(is_related, secondary in matrix.get_relatives(primary))

def test_traceable_matrix_calculate_ranges():
    matrix = TraceableMatrix("forward", "backward")
    eq_(matrix.calculate_ranges(5, None), [(0, 5)])
    eq_(matrix.calculate_ranges(5, 0), [(0, 5)])
    eq_(matrix.calculate_ranges(5, 1), [(0, 1), (1, 2), (2, 3), (3, 4),
                                        (4, 5)])
    eq_(matrix.calculate_ranges(5, 2), [(0, 2), (2, 4), (4, 5)])
    eq_(matrix.calculate_ranges(5, 3), [(0, 3), (3, 5)])
    eq_(matrix.calculate_ranges(5, 4), [(0, 4), (4, 5)])
    eq_(matrix.calculate_ranges(5, 5), [(0, 5)])
    eq_(matrix.calculate_ranges(5, 6), [(0, 5)])


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace DataAccessLayer
{
    ///
    /// Serialization class for a 'variant' property value
    ///
    [DataContract]
    public class PropertyValue
    {
        /// Static map of PropertyType's to StringToValue Conversion methods.
        private static readonly Dictionary<PropertyType, Func<string, dynamic>> ToValueMap = new Dictionary<PropertyType, Func<string, dynamic>>
            {
                { PropertyType.String, s => StringConversions.StringToNativeString(s) },
                { PropertyType.Int32, s => StringConversions.StringToNativeInt32(s) },
                { PropertyType.Int64, s => StringConversions.StringToNativeInt64(s) },
                { PropertyType.Double, s => StringConversions.StringToNativeDouble(s) },
                { PropertyType.Date, s => StringConversions.StringToNativeDateTime(s) },
                { PropertyType.Bool, s => StringConversions.StringToNativeBool(s) },
                { PropertyType.Guid, s => StringConversions.StringToNativeGuid(s) },
                { PropertyType.Binary, s => StringConversions.StringToNativeByteArray(s) }
            };

        /// Static map of PropertyType's to ValueToString Conversion methods.
        private static readonly Dictionary<PropertyType, Func<dynamic, string>> ToStringMap = new Dictionary<PropertyType, Func<dynamic, string>>
            {
                { PropertyType.String, v => StringConversions.NativeStringToString((string)v) },
                { PropertyType.Int32, v => StringConversions.NativeInt32ToString((int)v) },
                { PropertyType.Int64, v => StringConversions.NativeInt64ToString((long)v) },
                { PropertyType.Double, v => StringConversions.NativeDoubleToString((double)v) },
                { PropertyType.Date, v => StringConversions.NativeDateTimeToString((DateTime)v) },
                { PropertyType.Bool, v => StringConversions.NativeBoolToString((bool)v) },
                { PropertyType.Guid, v => StringConversions.NativeGuidToString((Guid)v) },
                { PropertyType.Binary, v => StringConversions.NativeByteArrayToString((byte[])v) }
            };

        /// Static map of built-in types to PropertyType values.
        private static readonly Dictionary<Type, PropertyType> AllowedTypesMap = new Dictionary<Type, PropertyType>
                {
                    { typeof(string), PropertyType.String },
                    { typeof(int), PropertyType.Int32 },
                    { typeof(long), PropertyType.Int64 },
                    { typeof(double), PropertyType.Double },
                    { typeof(decimal), PropertyType.Double },
                    { typeof(bool), PropertyType.Bool },
                    { typeof(DateTime), PropertyType.Date },
                    { typeof(Guid), PropertyType.Guid },
                    { typeof(EntityId), PropertyType.Guid },
                    { typeof(byte[]), PropertyType.Binary }
                };

        /// Initializes a new instance of the <see cref="PropertyValue"/> class.
        /// <param name="type">The type as PropertyType.</param>
        /// <param name="serializedValue">The string serialized value.</param>
        public PropertyValue(PropertyType type, string serializedValue)
            : this(StringFromPropertyType(type), serializedValue)
        {
        }

        /// Initializes a new instance of the <see cref="PropertyValue"/> class.
        /// <param name="serializedType">The string serialized type.</param>
        /// <param name="serializedValue">The string serialized value.</param>
        public PropertyValue(string serializedType, string serializedValue)
        {
            this.Initialize(serializedType, serializedValue);
        }

        /// Initializes a new instance of the <see cref="PropertyValue"/> class.
        /// <param name="type">The type.</param>
        /// <param name="value">The value.</param>
        public PropertyValue(PropertyType type, dynamic value)
        {
            this.Initialize(type, value);
        }

        ///
        /// Initializes a new instance of the <see cref="PropertyValue"/> class from an existing PropertyValue.
        ///
        /// <param name="value">An existing PropertyValue.</param>
        public PropertyValue(PropertyValue value)
        {
            this.Initialize(value.DynamicType, value.DynamicValue);
        }

        ///
        /// Gets or sets SerializationType of the property as a string. This is used when (de)serializing
        /// the property for persistence or as a DataContract.
        ///
        [DataMember(Order = 0)]
        public string SerializationType
        {
            get
            {
                // Derived from underlying PropertyType
                return StringFromPropertyType(this.DynamicType);
            }

            protected set
            {
                // Initialize the underlying PropertyType
                this.DynamicType = PropertyTypeFromString(value);
            }
        }

        ///
        /// Gets or sets value of the property as a string. This is used when (de)serializing
        /// the property for persistence or as a DataContract.
        ///
        [DataMember(Order = 1)]
        public string SerializationValue
        {
            get
            {
                // Derived from underlying PropertyType and dynamic value
                return ValueToString(this.DynamicType, this.DynamicValue);
            }

            protected set
            {
                // Intialize the underlying dynamic value
                this.DynamicValue = StringToValue(this.DynamicType, value);
            }
        }

        ///
        /// Gets the type of the property as a PropertyType object.
        ///
        public PropertyType DynamicType { get; private set; }

        ///
        /// Gets or sets dynamic value of the property.
        ///
        public dynamic DynamicValue { get; set; }

        ////
        // Begin Operator overloads
        ////

        /// Check PropertyValue for null and extract value.
        /// <typeparam name="T">The requested return type.</typeparam>
        /// <param name="propertyValue">The property value to check.</param>
        /// <returns>A default value or the extracted value.</returns>
        public static T CheckAndGetValueAs<T>(PropertyValue propertyValue)
        {
            if (propertyValue != null && propertyValue.DynamicValue != null)
            {
                return propertyValue.GetValueAs<T>();
            }

            // String is the only type for which we will accomodate a null PropertyValue.
            if (typeof(T) == typeof(string))
            {
                return default(T);
            }

            throw new ArgumentException(
                "Null value not supported for requested type {0}.".FormatInvariant(typeof(T).FullName));
        }

        ///
        /// Factory method to build a PropertyValue of the appropriate type
        /// from a generically specified value.
        ///
        /// <param name="value">The value of the property.</param>
        /// <typeparam name="T">The generically specified type of the property.</typeparam>
        /// <returns>A PropertyValue if success, otherwise null.</returns>
        public static PropertyValue BuildPropertyValue<T>(T value)
        {
            if (!AllowedTypesMap.ContainsKey(typeof(T)))
            {
                throw new InvalidOperationException("Type cannot be mapped to PropertyValue: {0}"
                    .FormatInvariant(typeof(T).FullName));
            }

            return new PropertyValue(AllowedTypesMap[typeof(T)], value);
        }

        /// Copy construct from native string type.
        /// <param name="value">The value as native string type.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(string value)
        {
            return new PropertyValue(PropertyType.String, value);
        }

        /// Cast value to native string type.
        /// <param name="property">The property.</param>
        /// <returns>The property value as native string.</returns>
        /// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
        public static implicit operator string(PropertyValue property)
        {
            // Cast to string should fail if this is not natively string.
            // This may seem odd but we have the SerializationValue Property and ToString
            // which will work to get a string representation regardless of
            // the native type. The purpose of the cast operators is
            // to extract the value as the 'native' type that corresponds
            // to the type specified on the object - not do a conversion.
            return CheckAndGetValueAs<string>(property);
        }

        /// Copy construct from native int type.
        /// <param name="value">The value as native int type.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(int value)
        {
            return new PropertyValue(PropertyType.Int32, value);
        }

        /// Cast value to native int type.
        /// <param name="property">The property.</param>
        /// <returns>The property value as native int.</returns>
        /// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
        public static implicit operator int(PropertyValue property)
        {
            return CheckAndGetValueAs<int>(property);
        }

        /// Copy construct from native long type.
        /// <param name="value">The value as native long type.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(long value)
        {
            return new PropertyValue(PropertyType.Int64, value);
        }

        /// Cast value to native long type.
        /// <param name="property">The property.</param>
        /// <returns>The property value as native long.</returns>
        /// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
        public static implicit operator long(PropertyValue property)
        {
            return CheckAndGetValueAs<long>(property);
        }

        /// Copy construct from native double type.
        /// <param name="value">The value as native double type.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(double value)
        {
            return new PropertyValue(PropertyType.Double, value);
        }

        /// Cast value to native double type.
        /// <param name="property">The property.</param>
        /// <returns>The property value as native double.</returns>
        /// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
        public static implicit operator double(PropertyValue property)
        {
            return CheckAndGetValueAs<double>(property);
        }

        ///
        /// Copy construct from native decimal type (will result in a PropertyType.Double).
        /// Note that values larger than about 792281625142643 will not round trip without
        /// rounding errors.
        ///
        /// <param name="value">The value as native decimal type.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(decimal value)
        {
            // This cannot overflow going this direction.
            var valueAsDouble = Convert.ToDouble(value);
            return new PropertyValue(PropertyType.Double, valueAsDouble);
        }

        ///
        /// Cast value to native decimal type.
        /// Note that values larger than about 792281625142643 will not round trip with
        /// rounding errors.
        ///
        /// <param name="property">The property.</param>
        /// <returns>The property value as native decimal.</returns>
        /// <exception cref="ArgumentException">If requested type is not compatible with defined type.</exception>
        /// <exception cref="OverflowException">If requested type will not hold defined type.</exception>
        public static implicit operator decimal(PropertyValue property)
        {
            return CheckAndGetValueAs<decimal>(property);
        }

        /// Copy construct from native DateTime type.
        /// <param name="value">The value as native DateTime type.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(DateTime value)
        {
            return new PropertyValue(PropertyType.Date, value);
        }

        /// Cast value to native DateTime type.
        /// <param name="property">The property.</param>
        /// <returns>The property value as native DateTime.</returns>
        /// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
        public static implicit operator DateTime(PropertyValue property)
        {
            return CheckAndGetValueAs<DateTime>(property);
        }

        /// Copy construct from native bool type.
        /// <param name="value">The value as native bool type.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(bool value)
        {
            return new PropertyValue(PropertyType.Bool, value);
        }

        /// Cast value to native bool type.
        /// <param name="property">The property.</param>
        /// <returns>The property value as native bool.</returns>
        /// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
        public static implicit operator bool(PropertyValue property)
        {
            return CheckAndGetValueAs<bool>(property);
        }

        /// Copy construct from native Guid type.
        /// <param name="value">The value as native Guid type.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(Guid value)
        {
            return new PropertyValue(PropertyType.Guid, value);
        }

        /// Cast value to EntityId type. At present this is mapped to a PropertyType of Guid.
        /// <param name="property">The property.</param>
        /// <returns>The property value as EntityId.</returns>
        /// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
        public static implicit operator EntityId(PropertyValue property)
        {
            return CheckAndGetValueAs<EntityId>(property);
        }

        /// Copy construct from EntityId type. At present this is mapped to a PropertyType of Guid.
        /// <param name="value">The value as EntityId.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(EntityId value)
        {
            return new PropertyValue(PropertyType.Guid, value);
        }

        /// Cast value to native Guid type.
        /// <param name="property">The property.</param>
        /// <returns>The property value as native Guid.</returns>
        /// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
        public static implicit operator Guid(PropertyValue property)
        {
            return CheckAndGetValueAs<Guid>(property);
        }

        /// Copy construct from native byte[] type.
        /// <param name="value">The value as native byte[] type.</param>
        /// <returns>A PropertyValue.</returns>
        public static implicit operator PropertyValue(byte[] value)
        {
            return new PropertyValue(PropertyType.Binary, value);
        }

        /// Cast value to native byte[] type.
        /// <param name="property">The property.</param>
        /// <returns>The property value as native byte[].</returns>
        /// <exception cref="ArgumentException">If requested type does not match defined type.</exception>
        public static implicit operator byte[](PropertyValue property)
        {
            return CheckAndGetValueAs<byte[]>(property);
        }

        /// Equality operator override.
        /// <param name="left">The left operand.</param>
        /// <param name="right">The right operand.</param>
        /// <returns>True if equal.</returns>
        public static bool operator ==(PropertyValue left, PropertyValue right)
        {
            return Equals(left, right);
        }

        /// Inequality operator override.
        /// <param name="left">The left operand.</param>
        /// <param name="right">The right operand.</param>
        /// <returns>False if equal.</returns>
        public static bool operator !=(PropertyValue left, PropertyValue right)
        {
            return !Equals(left, right);
        }

        ////
        // End Operator overloads
        ////

        ////
        // Begin Equality overloads
        // Two PropertyValue objects are considered equal if they have the same value
        // and type. Name is only used as a key and is not considered for equality.
        ////

        /// Equals method override.
        /// <param name="other">The other PropertyValue object being equated.</param>
        /// <returns>True if equal.</returns>
        public bool Equals(PropertyValue other)
        {
            // Degenerate cases
            if (ReferenceEquals(null, other))
            {
                return false;
            }

            if (ReferenceEquals(this, other))
            {
                return true;
            }

            // Test based on value equality only (not type)
            // There does not seem to be a useful scenario to test equality based
            // on type that would not be done explicity.

            // Binary is a little different - use serialization value since comparison is easier
            if (this.DynamicType == PropertyType.Binary)
            {
                return Equals(other.SerializationValue, this.SerializationValue);
            }

            return Equals(other.DynamicValue, this.DynamicValue);
        }

        /// Equals method override for generic object.
        /// <param name="obj">The other object being equated.</param>
        /// <returns>True if equal.</returns>
        public override bool Equals(object obj)
        {
            // Degenerate cases
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            if (obj.GetType() != typeof(PropertyValue))
            {
                return false;
            }

            // Defer to typed Equals
            return this.Equals((PropertyValue)obj);
        }

        /// Hash function for PropertyValue type.
        /// <returns>A hash code based on the member values.</returns>
        public override int GetHashCode()
        {
            unchecked
            {
                // (* 397 is just an arbitrary distribution function)
                return (this.DynamicType.GetHashCode() * 397) ^ (this.DynamicValue != null ? this.DynamicValue.GetHashCode() : 0);
            }
        }

        ////
        // End Equality overloads
        ////

        /// ToString override.
        /// <returns>String serialized representation of value.</returns>
        public override string ToString()
        {
            return this.SerializationValue;
        }

        /// Get the value as type T.
        /// <typeparam name="T">The type to return if possible.</typeparam>
        /// <returns>The value as T.</returns>
        public T GetValueAs<T>()
        {
            if (this.DynamicValue == null)
            {
                if (default(T) == null)
                {
                    return default(T);
                }

                throw new ArgumentException("Cannot return null for non-nullable requested type.");
            }

            // Nothing to do
            if (typeof(T) == this.DynamicValue.GetType())
            {
                return this.DynamicValue;
            }

            if (AllowedTypesMap.ContainsKey(typeof(T)))
            {
                var targetPropertyType = AllowedTypesMap[typeof(T)];

                // If it's a numeric type there are some allowed coercions
                if (targetPropertyType == PropertyType.Int32
                    || targetPropertyType == PropertyType.Int64
                    || targetPropertyType == PropertyType.Double)
                {
                    return this.CoerceNumericValue<T>();
                }

                // If it's not numeric the generic parameter must map to the supported PropertyType
                if (PropertyTypeFromString(this.SerializationType) == targetPropertyType)
                {
                    return this.DynamicValue;
                }
            }

            throw new ArgumentException("Could not coerce {0} to {1}."
                .FormatInvariant(this.SerializationType, typeof(T).FullName));
        }

        /// Get string serialized from of a PropertyType.
        /// <param name="type">The type as PropertyType.</param>
        /// <returns>The property type as a string.</returns>
        private static string StringFromPropertyType(PropertyType type)
        {
            return Enum.GetName(typeof(PropertyType), type);
        }

        /// Get PropertyType from a string serialized form.
        /// <param name="type">The type as string.</param>
        /// <returns>The property Type as PropertyType</returns>
        /// <exception cref="ArgumentException">Throws if the string does not map to one of our PropertyType's.</exception>
        private static PropertyType PropertyTypeFromString(string type)
        {
            PropertyType outType;
            if (!Enum.TryParse(type, out outType))
            {
                throw new ArgumentException("Property type not recognized: {0}"
                    .FormatInvariant(type));
            }

            return outType;
        }

        /// Helper to convert string serialized values to native types.
        /// <param name="type">The string form of the target type.</param>
        /// <param name="value">The string serialized value to convert.</param>
        /// <returns>A dynamic value representing a native type.</returns>
        private static dynamic StringToValue(PropertyType type, string value)
        {
            return ToValueMap[type](value);
        }

        /// Helper to convert native types to string serialized values.
        /// <param name="type">The target PropertyType.</param>
        /// <param name="value">A dynamic value representing a native type.</param>
        /// <returns>A string serialized representation of the native type.</returns>
        private static string ValueToString(PropertyType type, dynamic value)
        {
            return ToStringMap[type](value);
        }

        /// Test to determine if a double can be treated as integral type.
        /// <param name="value">The double value.</param>
        /// <returns>True if integral.</returns>
        private static bool IsIntegral(double value)
        {
            var integerPart = Math.Truncate(Math.Abs(value));
            return (Math.Abs(value) - integerPart) < double.Epsilon;
        }

        /// Coerce a numeric PropertyValue to a native decimal.
        /// <returns>A decimal value if successful.</returns>
        /// <exception cref="ArgumentException">If requested type is not compatible with defined type.</exception>
        /// <exception cref="OverflowException">If requested type will not hold defined type.</exception>
        /// <typeparam name="T">Target type of coercion.</typeparam>
        private T CoerceNumericValue<T>()
        {
            try
            {
                var sourceValue = this.DynamicValue;
                var sourceType = this.DynamicType;

                // First check for a string to numeric coercion. Always convert as double since this
                // is the most generous, then coerce to the requested type. This has the possibility
                // of loosing precision on extreme values of long but gains a few more allowed
                // conversions for things like "1.0" -> int
                if (sourceType == PropertyType.String)
                {
                    sourceValue = StringToValue(PropertyType.Double, this.SerializationValue);
                    sourceType = PropertyType.Double;
                }

                // double to decimal
                // int to decimal
                // long to decimal
                if (typeof(T) == typeof(decimal) && (sourceType == PropertyType.Double || sourceType == PropertyType.Int64
                    || sourceType == PropertyType.Int32))
                {
                    return Convert.ToDecimal(sourceValue);
                }

                // double to double
                // int to double
                // long to double
                if (typeof(T) == typeof(double) && (sourceType == PropertyType.Double || sourceType == PropertyType.Int64
                    || sourceType == PropertyType.Int32))
                {
                    return Convert.ToDouble(sourceValue);
                }

                // double to int
                if (typeof(T) == typeof(int) && sourceType == PropertyType.Double)
                {
                    if (IsIntegral(sourceValue))
                    {
                        return Convert.ToInt32(sourceValue);
                    }
                }

                // double to long
                if (typeof(T) == typeof(long) && sourceType == PropertyType.Double)
                {
                    if (IsIntegral(sourceValue))
                    {
                        return Convert.ToInt64(sourceValue);
                    }
                }

                // int to long
                // long to long
                if (typeof(T) == typeof(long) && (sourceType == PropertyType.Int64 || sourceType == PropertyType.Int32))
                {
                    return Convert.ToInt64(sourceValue);
                }

                // int to int
                // long to int
                if (typeof(T) == typeof(int) && (sourceType == PropertyType.Int64 || sourceType == PropertyType.Int32))
                {
                    return Convert.ToInt32(sourceValue);
                }
            }
            catch (OverflowException)
            {
            }

            throw new ArgumentException("Could not coerce {0} to {1}."
                .FormatInvariant(this.SerializationType, typeof(T).FullName));
        }

        /// Initialize from string serialized type and value.
        /// <param name="serializedType">The string serialized type.</param>
        /// <param name="serializedValue">The string serialized value.</param>
        private void Initialize(string serializedType, string serializedValue)
        {
            var type = PropertyTypeFromString(serializedType);
            this.Initialize(type, StringToValue(type, serializedValue));
        }

        ///
        /// Except for default construction (deserialized from the DataContract) all constructors
        /// and intializers will ultimately use this method.
        ///
        /// <param name="type">The type as PropertyType.</param>
        /// <param name="value">The value as dynamic value.</param>
        private void Initialize(PropertyType type, dynamic value)
        {
            this.DynamicType = type;
            this.DynamicValue = value;
        }
    }
}


text:
<?php if (!defined('APPLICATION')) exit();
echo Anchor(T('Start a New Conversation'), '/messages/add', 'BigButton NewConversation Popup');


text:
namespace leveldb {

// Creates LevelDBDatabases based scoped to a |directory|/|dbname|.
class LevelDBServiceImpl : public mojom::LevelDBService {
 public:
  LevelDBServiceImpl(scoped_refptr<base::SingleThreadTaskRunner> task_runner);
  ~LevelDBServiceImpl() override;

  // Overridden from LevelDBService:
  void Open(filesystem::mojom::DirectoryPtr directory,
            const std::string& dbname,
            leveldb::mojom::LevelDBDatabaseRequest database,
            const OpenCallback& callback) override;
  void OpenWithOptions(leveldb::mojom::OpenOptionsPtr open_options,
                       filesystem::mojom::DirectoryPtr directory,
                       const std::string& dbname,
                       leveldb::mojom::LevelDBDatabaseRequest database,
                       const OpenCallback& callback) override;
  void OpenInMemory(leveldb::mojom::LevelDBDatabaseRequest database,
                    const OpenInMemoryCallback& callback) override;

 private:
  // Thread to own the mojo message pipe. Because leveldb spawns multiple
  // threads that want to call file stuff, we create a dedicated thread to send
  // and receive mojo message calls.
  scoped_refptr<LevelDBMojoProxy> thread_;

  DISALLOW_COPY_AND_ASSIGN(LevelDBServiceImpl);
};

}  // namespace leveldb

#endif  // COMPONENTS_LEVELDB_LEVELDB_SERVICE_IMPL_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawerLayout_main"
    tools:context="com.oureda.thunder.pobooks.activity.main.MainActivity">
    <android.support.design.widget.CoordinatorLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteY="25dp"
            tools:layout_editor_absoluteX="8dp">
            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar_main"
                android:layout_width="match_parent"
                android:fitsSystemWindows="true"
                app:theme="@style/ToolBarTheme"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="enterAlways|scroll|snap">

            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.AppBarLayout>
        <LinearLayout
            android:layout_marginLeft="24dp"
            android:id="@+id/search_main_layout"
            android:visibility="gone"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:layout_marginRight="5dp"
                android:textSize="16sp"
                android:text="历史搜索"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <com.oureda.thunder.pobooks.CustomView.FlowLayout

                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="真武世界"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="大主宰"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="12dp"
                    app:lineColor="@color/colorMain"
                    app:text="龙王传说"
                    app:radius="12dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="一年永恒"
                    app:radius="12dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="雪鹰领主"
                    app:radius="12dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="圣墟"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="最强狂兵"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="仙侠"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="无量巅峰"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="从你的全世界路过,我再也不相信爱情"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="主要想展示流式布局"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="这个地方用来放置一些热门书籍"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="用户可以自由排列,也可以随意删除"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>

            </com.oureda.thunder.pobooks.CustomView.FlowLayout>
            <TextView
                android:layout_marginRight="5dp"
                android:textSize="16sp"
                android:text="热门搜索"
                android:paddingTop="20dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <com.oureda.thunder.pobooks.CustomView.FlowLayout

                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="真武世界"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="大主宰"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="龙王传说"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="一年永恒"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="雪鹰领主"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="圣墟"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="最强狂兵"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="仙侠"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="无量巅峰"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="从你的全世界路过,我再也不相信爱情"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="主要想展示流式布局"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="这个地方用来放置一些热门书籍"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>
                <com.oureda.thunder.pobooks.CustomView.RoundButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    app:lineColor="@color/colorMain"
                    app:text="用户可以自由排列,也可以随意删除"
                    app:radius="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    app:textSize="12sp"/>

            </com.oureda.thunder.pobooks.CustomView.FlowLayout>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/swift_refresh"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="30dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <android.support.v7.widget.RecyclerView
                android:layout_marginTop="24dp"
                android:layout_marginBottom="24dp"
                android:id="@+id/book_list_main"
                android:layout_width="fill_parent"
                android:layout_height="510dp"
                android:paddingLeft="20.0dip" />
        </LinearLayout>

        <com.oureda.thunder.pobooks.CustomView.CombineFAB
            android:id="@+id/combine_main"
            android:layout_width="wrap_content"
            android:layout_height="400.0dip"
            android:layout_gravity="bottom|center|right" />

        <LinearLayout
            android:id="@+id/bottom_main"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:orientation="horizontal"
            android:visibility="gone">

            <CheckBox
                android:id="@+id/check_all_main"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1.0"
                android:text="全选" />

            <ImageView
                android:id="@+id/share_main"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_marginLeft="5.0dip"
                android:src="@drawable/share_button" />

            <ImageView
                android:id="@+id/delete_main"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_marginRight="5.0dip"
                android:src="@drawable/delete_button" />

        </LinearLayout>

    </android.support.design.widget.CoordinatorLayout>

<com.oureda.thunder.pobooks.CustomView.MyNavigationView
    android:layout_width="match_parent"
    android:layout_gravity="start"
    android:layout_height="match_parent"/>
</android.support.v4.widget.DrawerLayout>


text:
<?php

require_once "loxberry_web.php";
require_once "Config/Lite.php";

##########################################################################
## Variables
###########################################################################
#
$helplink = "https://wiki.loxberry.de/konfiguration/widget_help/widget_loxberry_services/start";
$helptemplate = "help_services.html";
$template_title;
$error;

LBWeb::lbheader($template_title, $helplink, $helptemplate);

$tmp = exec(LBHOMEDIR."/sbin/testbashenv.sh");

if ($tmp === "") { $tmp = "nicht gesetzt"; }

echo "
Das System Configverzeichnis ist $tmp
";

LBWeb::lbfooter();
?>


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.							  */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib.  */
/*----------------------------------------------------------------------------*/

#include "Encoder.h"
#include "DigitalInput.h"
//#include "NetworkCommunication/UsageReporting.h"
#include "Resource.h"
#include "WPIErrors.h"
#include "LiveWindow/LiveWindow.h"

/**
 * Common initialization code for Encoders.
 * This code allocates resources for Encoders and is common to all constructors.
 *
 * The counter will start counting immediately.
 *
 * @param reverseDirection If true, counts down instead of up (this is all relative)
 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is
 * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder
 * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then
 * a counter object will be used and the returned value will either exactly match the spec'd count
 * or be double (2x) the spec'd count.
 */
void Encoder::InitEncoder(bool reverseDirection, EncodingType encodingType)
{
	m_table = NULL;
	m_encodingType = encodingType;
	m_index = 0;
	switch (encodingType)
	{
		case k4X:
		{
			m_encodingScale = 4;
			if (m_aSource->StatusIsFatal())
			{
				CloneError(m_aSource);
				return;
			}
			if (m_bSource->StatusIsFatal())
			{
				CloneError(m_bSource);
				return;
			}
			int32_t status = 0;
			m_encoder =  initializeEncoder(m_aSource->GetModuleForRouting(), m_aSource->GetChannelForRouting(),
										   m_aSource->GetAnalogTriggerForRouting(),
										   m_bSource->GetModuleForRouting(), m_bSource->GetChannelForRouting(),
										   m_bSource->GetAnalogTriggerForRouting(),
										   reverseDirection, &m_index, &status);
			  wpi_setErrorWithContext(status, getHALErrorMessage(status));
			m_counter = NULL;
			SetMaxPeriod(.5);
			break;
		}
		case k1X:
		case k2X:
		{
			m_encodingScale = encodingType == k1X ? 1 : 2;
			m_counter = new Counter(m_encodingType, m_aSource, m_bSource, reverseDirection);
			m_index = m_counter->GetFPGAIndex();
			break;
		}
		default:
			wpi_setErrorWithContext(-1, "Invalid encodingType argument");
			break;
	}
	m_distancePerPulse = 1.0;
	m_pidSource = kDistance;

	HALReport(HALUsageReporting::kResourceType_Encoder, m_index, encodingType);
	LiveWindow::GetInstance()->AddSensor("Encoder", m_aSource->GetChannelForRouting(), this);
}

/**
 * Encoder constructor.
 * Construct a Encoder given a and b channels.
 *
 * The counter will start counting immediately.
 *
 * @param aChannel The a channel DIO channel. 0-9 are on-board, 10-25 are on the MXP port
 * @param bChannel The b channel DIO channel. 0-9 are on-board, 10-25 are on the MXP port
 * @param reverseDirection represents the orientation of the encoder and inverts the output values
 * if necessary so forward represents positive values.
 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is
 * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder
 * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then
 * a counter object will be used and the returned value will either exactly match the spec'd count
 * or be double (2x) the spec'd count.
 */
Encoder::Encoder(uint32_t aChannel, uint32_t bChannel, bool reverseDirection, EncodingType encodingType) :
	m_encoder(NULL),
	m_counter(NULL)
{
	m_aSource = new DigitalInput(aChannel);
	m_bSource = new DigitalInput(bChannel);
	InitEncoder(reverseDirection, encodingType);
	m_allocatedASource = true;
	m_allocatedBSource = true;
}

/**
 * Encoder constructor.
 * Construct a Encoder given a and b channels as digital inputs. This is used in the case
 * where the digital inputs are shared. The Encoder class will not allocate the digital inputs
 * and assume that they already are counted.
 *
 * The counter will start counting immediately.
 *
 * @param aSource The source that should be used for the a channel.
 * @param bSource the source that should be used for the b channel.
 * @param reverseDirection represents the orientation of the encoder and inverts the output values
 * if necessary so forward represents positive values.
 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is
 * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder
 * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then
 * a counter object will be used and the returned value will either exactly match the spec'd count
 * or be double (2x) the spec'd count.
 */
Encoder::Encoder(DigitalSource *aSource, DigitalSource *bSource, bool reverseDirection, EncodingType encodingType) :
	m_encoder(NULL),
	m_counter(NULL)
{
	m_aSource = aSource;
	m_bSource = bSource;
	m_allocatedASource = false;
	m_allocatedBSource = false;
	if (m_aSource == NULL || m_bSource == NULL)
		wpi_setWPIError(NullParameter);
	else
		InitEncoder(reverseDirection, encodingType);
}

/**
 * Encoder constructor.
 * Construct a Encoder given a and b channels as digital inputs. This is used in the case
 * where the digital inputs are shared. The Encoder class will not allocate the digital inputs
 * and assume that they already are counted.
 *
 * The counter will start counting immediately.
 *
 * @param aSource The source that should be used for the a channel.
 * @param bSource the source that should be used for the b channel.
 * @param reverseDirection represents the orientation of the encoder and inverts the output values
 * if necessary so forward represents positive values.
 * @param encodingType either k1X, k2X, or k4X to indicate 1X, 2X or 4X decoding. If 4X is
 * selected, then an encoder FPGA object is used and the returned counts will be 4x the encoder
 * spec'd value since all rising and falling edges are counted. If 1X or 2X are selected then
 * a counter object will be used and the returned value will either exactly match the spec'd count
 * or be double (2x) the spec'd count.
 */
Encoder::Encoder(DigitalSource &aSource, DigitalSource &bSource, bool reverseDirection, EncodingType encodingType) :
	m_encoder(NULL),
	m_counter(NULL)
{
	m_aSource = &aSource;
	m_bSource = &bSource;
	m_allocatedASource = false;
	m_allocatedBSource = false;
	InitEncoder(reverseDirection, encodingType);
}

/**
 * Free the resources for an Encoder.
 * Frees the FPGA resources associated with an Encoder.
 */
Encoder::~Encoder()
{
	if (m_allocatedASource) delete m_aSource;
	if (m_allocatedBSource) delete m_bSource;
	if (m_counter)
	{
		delete m_counter;
	}
	else
	{
	  	int32_t status = 0;
		freeEncoder(m_encoder, &status);
		wpi_setErrorWithContext(status, getHALErrorMessage(status));
	}
}

/**
 * The encoding scale factor 1x, 2x, or 4x, per the requested encodingType.
 * Used to divide raw edge counts down to spec'd counts.
 */
int32_t Encoder::GetEncodingScale() { return m_encodingScale; }

/**
 * Gets the raw value from the encoder.
 * The raw value is the actual count unscaled by the 1x, 2x, or 4x scale
 * factor.
 * @return Current raw count from the encoder
 */
int32_t Encoder::GetRaw()
{
	if (StatusIsFatal()) return 0;
	int32_t value;
	if (m_counter)
		value = m_counter->Get();
	else
	{
		int32_t status = 0;
		value = getEncoder(m_encoder, &status);
		wpi_setErrorWithContext(status, getHALErrorMessage(status));
	}
	return value;
}

/**
 * Gets the current count.
 * Returns the current count on the Encoder.
 * This method compensates for the decoding type.
 *
 * @return Current count from the Encoder adjusted for the 1x, 2x, or 4x scale factor.
 */
int32_t Encoder::Get()
{
	if (StatusIsFatal()) return 0;
	return (int32_t) (GetRaw() * DecodingScaleFactor());
}

/**
 * Reset the Encoder distance to zero.
 * Resets the current count to zero on the encoder.
 */
void Encoder::Reset()
{
	if (StatusIsFatal()) return;
	if (m_counter)
		m_counter->Reset();
	else
	{
		int32_t status = 0;
		resetEncoder(m_encoder, &status);
		wpi_setErrorWithContext(status, getHALErrorMessage(status));
	}
}

/**
 * Returns the period of the most recent pulse.
 * Returns the period of the most recent Encoder pulse in seconds.
 * This method compensates for the decoding type.
 *
 * @deprecated Use GetRate() in favor of this method.  This returns unscaled periods and GetRate() scales using value from SetDistancePerPulse().
 *
 * @return Period in seconds of the most recent pulse.
 */
double Encoder::GetPeriod()
{
	if (StatusIsFatal()) return 0.0;
	if (m_counter)
	{
		return m_counter->GetPeriod() / DecodingScaleFactor();
	}
	else
	{
		int32_t status = 0;
		double period = getEncoderPeriod(m_encoder, &status);
		wpi_setErrorWithContext(status, getHALErrorMessage(status));
		return period;
	}

}

/**
 * Sets the maximum period for stopped detection.
 * Sets the value that represents the maximum period of the Encoder before it will assume
 * that the attached device is stopped. This timeout allows users to determine if the wheels or
 * other shaft has stopped rotating.
 * This method compensates for the decoding type.
 *
 * @deprecated Use SetMinRate() in favor of this method.  This takes unscaled periods and SetMinRate() scales using value from SetDistancePerPulse().
 *
 * @param maxPeriod The maximum time between rising and falling edges before the FPGA will
 * report the device stopped. This is expressed in seconds.
 */
void Encoder::SetMaxPeriod(double maxPeriod)
{
	if (StatusIsFatal()) return;
	if (m_counter)
	{
		m_counter->SetMaxPeriod(maxPeriod * DecodingScaleFactor());
	}
	else
	{
		int32_t status = 0;
		setEncoderMaxPeriod(m_encoder, maxPeriod, &status);
		wpi_setErrorWithContext(status, getHALErrorMessage(status));
	}
}

/**
 * Determine if the encoder is stopped.
 * Using the MaxPeriod value, a boolean is returned that is true if the encoder is considered
 * stopped and false if it is still moving. A stopped encoder is one where the most recent pulse
 * width exceeds the MaxPeriod.
 * @return True if the encoder is considered stopped.
 */
bool Encoder::GetStopped()
{
	if (StatusIsFatal()) return true;
	if (m_counter)
	{
		return m_counter->GetStopped();
	}
	else
	{
		int32_t status = 0;
		bool value = getEncoderStopped(m_encoder, &status);
		wpi_setErrorWithContext(status, getHALErrorMessage(status));
		return value;
	}
}

/**
 * The last direction the encoder value changed.
 * @return The last direction the encoder value changed.
 */
bool Encoder::GetDirection()
{
	if (StatusIsFatal()) return false;
	if (m_counter)
	{
		return m_counter->GetDirection();
	}
	else
	{
		int32_t status = 0;
		bool value = getEncoderDirection(m_encoder, &status);
		wpi_setErrorWithContext(status, getHALErrorMessage(status));
		return value;
	}
}

/**
 * The scale needed to convert a raw counter value into a number of encoder pulses.
 */
double Encoder::DecodingScaleFactor()
{
	if (StatusIsFatal()) return 0.0;
	switch (m_encodingType)
	{
	case k1X:
		return 1.0;
	case k2X:
		return 0.5;
	case k4X:
		return 0.25;
	default:
		return 0.0;
	}
}

/**
 * Get the distance the robot has driven since the last reset.
 *
 * @return The distance driven since the last reset as scaled by the value from SetDistancePerPulse().
 */
double Encoder::GetDistance()
{
	if (StatusIsFatal()) return 0.0;
	return GetRaw() * DecodingScaleFactor() * m_distancePerPulse;
}

/**
 * Get the current rate of the encoder.
 * Units are distance per second as scaled by the value from SetDistancePerPulse().
 *
 * @return The current rate of the encoder.
 */
double Encoder::GetRate()
{
	if (StatusIsFatal()) return 0.0;
	return (m_distancePerPulse / GetPeriod());
}

/**
 * Set the minimum rate of the device before the hardware reports it stopped.
 *
 * @param minRate The minimum rate.  The units are in distance per second as scaled by the value from SetDistancePerPulse().
 */
void Encoder::SetMinRate(double minRate)
{
	if (StatusIsFatal()) return;
	SetMaxPeriod(m_distancePerPulse / minRate);
}

/**
 * Set the distance per pulse for this encoder.
 * This sets the multiplier used to determine the distance driven based on the count value
 * from the encoder.
 * Do not include the decoding type in this scale.  The library already compensates for the decoding type.
 * Set this value based on the encoder's rated Pulses per Revolution and
 * factor in gearing reductions following the encoder shaft.
 * This distance can be in any units you like, linear or angular.
 *
 * @param distancePerPulse The scale factor that will be used to convert pulses to useful units.
 */
void Encoder::SetDistancePerPulse(double distancePerPulse)
{
	if (StatusIsFatal()) return;
	m_distancePerPulse = distancePerPulse;
}

/**
 * Set the direction sensing for this encoder.
 * This sets the direction sensing on the encoder so that it could count in the correct
 * software direction regardless of the mounting.
 * @param reverseDirection true if the encoder direction should be reversed
 */
void Encoder::SetReverseDirection(bool reverseDirection)
{
	if (StatusIsFatal()) return;
	if (m_counter)
	{
		m_counter->SetReverseDirection(reverseDirection);
	}
	else
	{
		int32_t status = 0;
		setEncoderReverseDirection(m_encoder, reverseDirection, &status);
		wpi_setErrorWithContext(status, getHALErrorMessage(status));
	}
}

/**
 * Set the Samples to Average which specifies the number of samples of the timer to
 * average when calculating the period. Perform averaging to account for
 * mechanical imperfections or as oversampling to increase resolution.
 * @param samplesToAverage The number of samples to average from 1 to 127.
 */
void Encoder::SetSamplesToAverage(int samplesToAverage)
{
	if (samplesToAverage < 1 || samplesToAverage > 127)
	{
		wpi_setWPIErrorWithContext(ParameterOutOfRange, "Average counter values must be between 1 and 127");
	}
	int32_t status = 0;
	switch (m_encodingType) {
		case k4X:
			setEncoderSamplesToAverage(m_encoder, samplesToAverage, &status);
			wpi_setErrorWithContext(status, getHALErrorMessage(status));
			break;
		case k1X:
		case k2X:
			m_counter->SetSamplesToAverage(samplesToAverage);
			break;
	}
}

/**
 * Get the Samples to Average which specifies the number of samples of the timer to
 * average when calculating the period. Perform averaging to account for
 * mechanical imperfections or as oversampling to increase resolution.
 * @return SamplesToAverage The number of samples being averaged (from 1 to 127)
 */
int Encoder::GetSamplesToAverage()
{
	int result = 1;
	int32_t status = 0;
	switch (m_encodingType) {
		case k4X:
			result = getEncoderSamplesToAverage(m_encoder, &status);
			wpi_setErrorWithContext(status, getHALErrorMessage(status));
			break;
		case k1X:
		case k2X:
			result = m_counter->GetSamplesToAverage();
			break;
	}
	return result;
}

/**
 * Set which parameter of the encoder you are using as a process control variable.
 *
 * @param pidSource An enum to select the parameter.
 */
void Encoder::SetPIDSourceParameter(PIDSourceParameter pidSource)
{
	if (StatusIsFatal()) return;
	m_pidSource = pidSource;
}

/**
 * Implement the PIDSource interface.
 *
 * @return The current value of the selected source parameter.
 */
double Encoder::PIDGet()
{
	if (StatusIsFatal()) return 0.0;
	switch (m_pidSource)
	{
	case kDistance:
		return GetDistance();
	case kRate:
		return GetRate();
	default:
		return 0.0;
	}
}

void Encoder::UpdateTable() {
	if (m_table != NULL) {
        m_table->PutNumber("Speed", GetRate());
        m_table->PutNumber("Distance", GetDistance());
        m_table->PutNumber("Distance per Tick", m_distancePerPulse);
	}
}

void Encoder::StartLiveWindowMode() {

}

void Encoder::StopLiveWindowMode() {

}

std::string Encoder::GetSmartDashboardType() {
	if (m_encodingType == k4X)
		return "Quadrature Encoder";
	else
		return "Encoder";
}

void Encoder::InitTable(ITable *subTable) {
	m_table = subTable;
	UpdateTable();
}

ITable * Encoder::GetTable() {
	return m_table;
}


text:
<?php

namespace wardormeur\phpbbwpunicorn\tests;

class phpbbwpunicorn_module extends \phpbb_functional_test_case
{

	function path_changed_test()
	{
		$this->assertTrue(true);
	}

	function recache_test()
	{
		$this->assertTrue(true);
	}

	function default_role_changed_test()
	{
		$this->assertTrue(true);
	}

	function associated_roles_changed_test()
	{
		$this->assertTrue(true);
	}

}


text:
package mezz.jeiaddons.plugins.thaumcraft.arcane;

import javax.annotation.Nonnull;

import mezz.jei.api.recipe.IRecipeWrapper;
import mezz.jeiaddons.plugins.thaumcraft.ThaumcraftRecipeHandler;
import mezz.jeiaddons.plugins.thaumcraft.ThaumcraftRecipeUids;

public class ArcaneWandRecipeHandler extends ThaumcraftRecipeHandler<ArcaneWandRecipeWrapper> {
	@Nonnull
	@Override
	public Class<ArcaneWandRecipeWrapper> getRecipeClass() {
		return ArcaneWandRecipeWrapper.class;
	}

	@Nonnull
	@Override
	public String getRecipeCategoryUid() {
		return ThaumcraftRecipeUids.ARCANE;
	}

	@Nonnull
	@Override
	public IRecipeWrapper getRecipeWrapper(@Nonnull ArcaneWandRecipeWrapper recipe) {
		return recipe;
	}
}


text:
/*
 * 系统名称: JRES 应用快速开发企业套件
 * 模块名称: JRES内核
 * 文件名称: FToolGroupTag.java
 * 软件版权: 恒生电子股份有限公司
 * 修改记录:
 * 修改日期            修改人员                     修改说明

 * ========    =======  ============================================
 *
 * ========    =======  ============================================
 */

package com.hundsun.jres.fui.jsp.tag.container;

import com.hundsun.jres.fui.core.page.tag.FTagProcessor;
import com.hundsun.jres.fui.jsp.FTagWithContent;
import com.hundsun.jres.fui.tag.container.FButtonGroupProcessor;

/**
 * 按钮group
 *

 * 系统版本: v1.0

 * 开发人员: hanyin

 * 开发时间: 2012-8-15

 */
public class FButtonGroupTag extends FTagWithContent
{
	private static final long	serialVersionUID	= 1L;

	private String				id;
	private String				style;
	private String				clz;
	private String				width;
	private String				height;
	private String				buttonAlign;
	private String				toolspacing;
	private String				toolpadding;

	public void setId(String id)
	{
		this.id = id;
	}

	public void setStyle(String style)
	{
		this.style = style;
	}

	public void setClasses(String clz)
	{
		this.clz = clz;
	}

	public void setWidth(String width)
	{
		this.width = width;
	}

	public void setHeight(String height)
	{
		this.height = height;
	}

	public void setButtonAlign(String toolAlign)
	{
		this.buttonAlign = toolAlign;
	}

	public void setToolspacing(String toolspacing)
	{
		this.toolspacing = toolspacing;
	}

	public void setToolpadding(String toolpadding)
	{
		this.toolpadding = toolpadding;
	}

	/*
	 * (non-Javadoc)
	 * @see com.hundsun.jres.fui.core.page.tag.FBaseTagSupport#getProcessor()
	 */
	public FTagProcessor getProcessor()
	{
		return new FButtonGroupProcessor();
	}

	/*
	 * (non-Javadoc)
	 * @see com.hundsun.jres.fui.jsp.FBaseJspSupport#getName()
	 */
	@Override
	public String getName()
	{
		return "container";
	}

	/*
	 * (non-Javadoc)
	 * @see com.hundsun.jres.fui.jsp.FBaseJspSupport#doBeforeProcess()
	 */
	@Override
	protected void doBeforeProcess()
	{
		parameters.put("id", id);
		parameters.put("style", style);
		parameters.put("class", clz);
		parameters.put("width", width);
		parameters.put("height", height);
		parameters.put("buttonAlign", buttonAlign);
		parameters.put("toolspacing", toolspacing);
		parameters.put("toolpadding", toolpadding);
	}

}


text:
'use strict';

var utils = require('../utils');
var onFileProgress = utils.onFileProgress;
var handleFileUpload = require('../handlefileupload').handleFileUpload;
var initSocket = require('../socket').initSocket;
var showError = require('./showerror').showError;
var effects = require('./effects');

var LOOKUP_TABLE = {
  a: ['STH.flac', 'Us_English_Broadband_Sample_2.wav'],
};

var playSample = (function() {

  var running = false;
  localStorage.setItem('currentlyDisplaying', false);

  return function(token, imageTag, iconName, url, callback) {

    $.publish('clearscreen');

    var currentlyDisplaying = JSON.parse(localStorage.getItem('currentlyDisplaying'));

    console.log('CURRENTLY DISPLAYING', currentlyDisplaying);

    // This error handling needs to be expanded to accomodate
    // the two different play samples files
    if (currentlyDisplaying) {
      console.log('HARD SOCKET STOP');
      $.publish('socketstop');
      localStorage.setItem('currentlyDisplaying', false);
      effects.stopToggleImage(timer, imageTag, iconName);
      effects.restoreImage(imageTag, iconName);
      running = false;
      return;
    }

    if (currentlyDisplaying && running) {
      showError('Currently another file is playing, please stop the file or wait until it finishes');
      return;
    }

    localStorage.setItem('currentlyDisplaying', true);
    running = true;

    var timer = setInterval(effects.toggleImage, 750, imageTag, iconName);

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
      var blob = xhr.response;
      var currentModel = localStorage.getItem('currentModel') || 'en-US_BroadbandModel';
      var reader = new FileReader();
      var blobToText = new Blob([blob]).slice(0, 4);
      reader.readAsText(blobToText);
      reader.onload = function() {
        var contentType = reader.result === 'fLaC' ? 'audio/flac' : 'audio/wav';
        console.log('Uploading file', reader.result);
        var mediaSourceURL = URL.createObjectURL(blob);
        var audio = new Audio();
        audio.src = mediaSourceURL;
        audio.play();
        $.subscribe('hardsocketstop', function() {
          audio.pause();
          audio.currentTime = 0;
        });
        $.subscribe('socketstop', function() {
          audio.pause();
          audio.currentTime = 0;
        });
        handleFileUpload(token, currentModel, blob, contentType, function(socket) {
          var parseOptions = {
            file: blob
          };
          onFileProgress(parseOptions,
            // On data chunk
            function(chunk) {
              socket.send(chunk);
            },
            // On file read error
            function(evt) {
              console.log('Error reading file: ', evt.message);
              // showError(evt.message);
            },
            // On load end
            function() {
              socket.send(JSON.stringify({'action': 'stop'}));
            });
        },
        // On connection end
          function(evt) {
            effects.stopToggleImage(timer, imageTag, iconName);
            effects.restoreImage(imageTag, iconName);
            localStorage.getItem('currentlyDisplaying', false);
          }
        );
      };
    };
    xhr.send();
  };
})();

exports.initPlaySample = function(ctx) {

  (function() {
    var fileName = 'audio/' + LOOKUP_TABLE.a[0];
    var el = $('.play-sample-1');
    var progressName = $('.intro-text');
    el.off('click');
    var iconName = 'play';
    var imageTag = el.find('img');
    var startRecord = progressName.find(".start-record");
    var recording = progressName.find(".recording");
    var preparing = progressName.find(".preparing");

    preparing.hide();
    startRecord.show();
    recording.hide();

    el.click( function(evt) {
        startRecord.hide();
        preparing.show();
        recording.hide();
      playSample(ctx.token, imageTag, iconName, fileName, function(result) {
        console.log('Play sample result', result);
      });
    });
  })(ctx, LOOKUP_TABLE);

};


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { NgaModule } from '../../theme/nga.module';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import { DataTableModule } from "angular2-datatable";
import { HttpModule, JsonpModule } from "@angular/http";
import { DataFilterPipe } from './components/newsList/data-filter.pipe';
import { HotTable, HotTableModule } from 'ng2-handsontable';

import { routing } from './tables.routing';
import { Tables } from './tables.component';
import { BasicTables } from './components/basicTables/basicTables.component';
import { BasicTablesService } from './components/basicTables/basicTables.service';
import { ResponsiveTable } from './components/basicTables/components/responsiveTable';
import { StripedTable } from './components/basicTables/components/stripedTable';
import { BorderedTable } from './components/basicTables/components/borderedTable';
import { HoverTable } from './components/basicTables/components/hoverTable';
import { CondensedTable } from './components/basicTables/components/condensedTable';
import { ContextualTable } from './components/basicTables/components/contextualTable';
import { SmartTables } from './components/smartTables/smartTables.component';
import { SmartTablesService } from './components/smartTables/smartTables.service';
import { HotTablesComponent } from './components/hotTables/hotTables.component';
import { HandsontableSectionComponent } from './components/hotTables/handsontable-section';
import { BasicDemoComponent } from './components/hotTables/handsontable/basic-demo';
import { SheetDemoComponent } from './components/hotTables/handsontable/sheet-demo';
import { FinanceDemoComponent } from './components/hotTables/handsontable/finance-demo';
import { ScienceDemoComponent } from './components/hotTables/handsontable/science-demo';
import { SportDemoComponent } from './components/hotTables/handsontable/sport-demo';
import { AdvancedDemoComponent } from './components/hotTables/handsontable/advanced-demo';
import {ActualiteService} from "./components/newsList/actualite.service";
import {NewsList} from "./components/newsList/newsList.component";
import {AddNewsComponent} from "./components/newsList/add-news.component";
import {FileSelectDirective} from "ng2-file-upload/index";
import {UpdateNewsComponent} from "./components/newsList/update-news.component";

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    NgaModule,
    routing,
    Ng2SmartTableModule,
    DataTableModule,
    HttpModule,
    JsonpModule,
    HotTableModule
  ],
  declarations: [
    Tables,
    BasicTables,
    HoverTable,
    BorderedTable,
    CondensedTable,
    StripedTable,
    ContextualTable,
    ResponsiveTable,
    SmartTables,
    NewsList,
    AddNewsComponent,
    UpdateNewsComponent,
    DataFilterPipe,
    HotTablesComponent,
    HandsontableSectionComponent,
    BasicDemoComponent,
    AdvancedDemoComponent,
    FinanceDemoComponent,
    ScienceDemoComponent,
    SportDemoComponent,
    SheetDemoComponent,
    FileSelectDirective

  ],
  providers: [
    ActualiteService
  ]
})
export class TablesModule {
}


text: **Application parses site [sql.ru](http://sql.ru) for searching vacancies for java developers**


text:
<?php

final class PhabricatorPolicyFilter {

  private $viewer;
  private $objects;
  private $capabilities;
  private $raisePolicyExceptions;
  private $userProjects;
  private $customPolicies = array();
  private $forcedPolicy;

  public static function mustRetainCapability(
    PhabricatorUser $user,
    PhabricatorPolicyInterface $object,
    $capability) {

    if (!self::hasCapability($user, $object, $capability)) {
      throw new Exception(
        "You can not make that edit, because it would remove your ability ".
        "to '{$capability}' the object.");
    }
  }

  public static function requireCapability(
    PhabricatorUser $user,
    PhabricatorPolicyInterface $object,
    $capability) {
    $filter = id(new PhabricatorPolicyFilter())
      ->setViewer($user)
      ->requireCapabilities(array($capability))
      ->raisePolicyExceptions(true)
      ->apply(array($object));
  }

  /**
   * Perform a capability check, acting as though an object had a specific
   * policy. This is primarily used to check if a policy is valid (for example,
   * to prevent users from editing away their ability to edit an object).
   *
   * Specifically, a check like this:
   *
   *   PhabricatorPolicyFilter::requireCapabilityWithForcedPolicy(
   *     $viewer,
   *     $object,
   *     PhabricatorPolicyCapability::CAN_EDIT,
   *     $potential_new_policy);
   *
   * ...will throw a @{class:PhabricatorPolicyException} if the new policy would
   * remove the user's ability to edit the object.
   *
   * @param PhabricatorUser   The viewer to perform a policy check for.
   * @param PhabricatorPolicyInterface The object to perform a policy check on.
   * @param string            Capability to test.
   * @param string            Perform the test as though the object has this
   *                          policy instead of the policy it actually has.
   * @return void
   */
  public static function requireCapabilityWithForcedPolicy(
    PhabricatorUser $viewer,
    PhabricatorPolicyInterface $object,
    $capability,
    $forced_policy) {

    id(new PhabricatorPolicyFilter())
      ->setViewer($viewer)
      ->requireCapabilities(array($capability))
      ->raisePolicyExceptions(true)
      ->forcePolicy($forced_policy)
      ->apply(array($object));
  }

  public static function hasCapability(
    PhabricatorUser $user,
    PhabricatorPolicyInterface $object,
    $capability) {

    $filter = new PhabricatorPolicyFilter();
    $filter->setViewer($user);
    $filter->requireCapabilities(array($capability));
    $result = $filter->apply(array($object));

    return (count($result) == 1);
  }

  public function setViewer(PhabricatorUser $user) {
    $this->viewer = $user;
    return $this;
  }

  public function requireCapabilities(array $capabilities) {
    $this->capabilities = $capabilities;
    return $this;
  }

  public function raisePolicyExceptions($raise) {
    $this->raisePolicyExceptions = $raise;
    return $this;
  }

  public function forcePolicy($forced_policy) {
    $this->forcedPolicy = $forced_policy;
    return $this;
  }

  public function apply(array $objects) {
    assert_instances_of($objects, 'PhabricatorPolicyInterface');

    $viewer       = $this->viewer;
    $capabilities = $this->capabilities;

    if (!$viewer || !$capabilities) {
      throw new Exception(
        'Call setViewer() and requireCapabilities() before apply()!');
    }

    // If the viewer is omnipotent, short circuit all the checks and just
    // return the input unmodified. This is an optimization; we know the
    // result already.
    if ($viewer->isOmnipotent()) {
      return $objects;
    }

    $filtered = array();
    $viewer_phid = $viewer->getPHID();

    if (empty($this->userProjects[$viewer_phid])) {
      $this->userProjects[$viewer_phid] = array();
    }

    $need_projects = array();
    $need_policies = array();
    foreach ($objects as $key => $object) {
      $object_capabilities = $object->getCapabilities();
      foreach ($capabilities as $capability) {
        if (!in_array($capability, $object_capabilities)) {
          throw new Exception(
            "Testing for capability '{$capability}' on an object which does ".
            "not have that capability!");
        }

        $policy = $this->getObjectPolicy($object, $capability);
        $type = phid_get_type($policy);
        if ($type == PhabricatorProjectProjectPHIDType::TYPECONST) {
          $need_projects[$policy] = $policy;
        }

        if ($type == PhabricatorPolicyPHIDTypePolicy::TYPECONST) {
          $need_policies[$policy] = $policy;
        }
      }
    }

    if ($need_policies) {
      $this->loadCustomPolicies(array_keys($need_policies));
    }

    // If we need projects, check if any of the projects we need are also the
    // objects we're filtering. Because of how project rules work, this is a
    // common case.
    if ($need_projects) {
      foreach ($objects as $object) {
        if ($object instanceof PhabricatorProject) {
          $project_phid = $object->getPHID();
          if (isset($need_projects[$project_phid])) {
            $is_member = $object->isUserMember($viewer_phid);
            $this->userProjects[$viewer_phid][$project_phid] = $is_member;
            unset($need_projects[$project_phid]);
          }
        }
      }
    }

    if ($need_projects) {
      $need_projects = array_unique($need_projects);

      // NOTE: We're using the omnipotent user here to avoid a recursive
      // descent into madness. We don't actually need to know if the user can
      // see these projects or not, since: the check is "user is member of
      // project", not "user can see project"; and membership implies
      // visibility anyway. Without this, we may load other projects and
      // re-enter the policy filter and generally create a huge mess.

      $projects = id(new PhabricatorProjectQuery())
        ->setViewer(PhabricatorUser::getOmnipotentUser())
        ->withMemberPHIDs(array($viewer->getPHID()))
        ->withPHIDs($need_projects)
        ->execute();

      foreach ($projects as $project) {
        $this->userProjects[$viewer_phid][$project->getPHID()] = true;
      }
    }

    foreach ($objects as $key => $object) {
      $object_capabilities = $object->getCapabilities();
      foreach ($capabilities as $capability) {
        if (!$this->checkCapability($object, $capability)) {
          // If we're missing any capability, move on to the next object.
          continue 2;
        }
      }

      // If we make it here, we have all of the required capabilities.
      $filtered[$key] = $object;
    }

    return $filtered;
  }

  private function checkCapability(
    PhabricatorPolicyInterface $object,
    $capability) {

    $policy = $this->getObjectPolicy($object, $capability);

    if (!$policy) {
      // TODO: Formalize this somehow?
      $policy = PhabricatorPolicies::POLICY_USER;
    }

    if ($policy == PhabricatorPolicies::POLICY_PUBLIC) {
      // If the object is set to "public" but that policy is disabled for this
      // install, restrict the policy to "user".
      if (!PhabricatorEnv::getEnvConfig('policy.allow-public')) {
        $policy = PhabricatorPolicies::POLICY_USER;
      }

      // If the object is set to "public" but the capability is not a public
      // capability, restrict the policy to "user".
      $capobj = PhabricatorPolicyCapability::getCapabilityByKey($capability);
      if (!$capobj || !$capobj->shouldAllowPublicPolicySetting()) {
        $policy = PhabricatorPolicies::POLICY_USER;
      }
    }

    $viewer = $this->viewer;

    if ($viewer->isOmnipotent()) {
      return true;
    }

    if ($object->hasAutomaticCapability($capability, $viewer)) {
      return true;
    }

    switch ($policy) {
      case PhabricatorPolicies::POLICY_PUBLIC:
        return true;
      case PhabricatorPolicies::POLICY_USER:
        if ($viewer->getPHID()) {
          return true;
        } else {
          $this->rejectObject($object, $policy, $capability);
        }
        break;
      case PhabricatorPolicies::POLICY_ADMIN:
        if ($viewer->getIsAdmin()) {
          return true;
        } else {
          $this->rejectObject($object, $policy, $capability);
        }
        break;
      case PhabricatorPolicies::POLICY_NOONE:
        $this->rejectObject($object, $policy, $capability);
        break;
      default:
        $type = phid_get_type($policy);
        if ($type == PhabricatorProjectProjectPHIDType::TYPECONST) {
          if (!empty($this->userProjects[$viewer->getPHID()][$policy])) {
            return true;
          } else {
            $this->rejectObject($object, $policy, $capability);
          }
        } else if ($type == PhabricatorPeopleUserPHIDType::TYPECONST) {
          if ($viewer->getPHID() == $policy) {
            return true;
          } else {
            $this->rejectObject($object, $policy, $capability);
          }
        } else if ($type == PhabricatorPolicyPHIDTypePolicy::TYPECONST) {
          if ($this->checkCustomPolicy($policy)) {
            return true;
          } else {
            $this->rejectObject($object, $policy, $capability);
          }
        } else {
          // Reject objects with unknown policies.
          $this->rejectObject($object, false, $capability);
        }
    }

    return false;
  }

  public function rejectObject(
    PhabricatorPolicyInterface $object,
    $policy,
    $capability) {

    if (!$this->raisePolicyExceptions) {
      return;
    }

    if ($this->viewer->isOmnipotent()) {
      // Never raise policy exceptions for the omnipotent viewer. Although we
      // will never normally issue a policy rejection for the omnipotent
      // viewer, we can end up here when queries blanket reject objects that
      // have failed to load, without distinguishing between nonexistent and
      // nonvisible objects.
      return;
    }

    $capobj = PhabricatorPolicyCapability::getCapabilityByKey($capability);
    $rejection = null;
    if ($capobj) {
      $rejection = $capobj->describeCapabilityRejection();
      $capability_name = $capobj->getCapabilityName();
    } else {
      $capability_name = $capability;
    }

    if (!$rejection) {
      // We couldn't find the capability object, or it doesn't provide a
      // tailored rejection string.
      $rejection = pht(
        'You do not have the required capability ("%s") to do whatever you '.
        'are trying to do.',
        $capability);
    }

    $more = PhabricatorPolicy::getPolicyExplanation($this->viewer, $policy);
    $exceptions = $object->describeAutomaticCapability($capability);

    $details = array_filter(array_merge(array($more), (array)$exceptions));

    // NOTE: Not every type of policy object has a real PHID; just load an
    // empty handle if a real PHID isn't available.
    $phid = nonempty($object->getPHID(), PhabricatorPHIDConstants::PHID_VOID);

    $handle = id(new PhabricatorHandleQuery())
      ->setViewer($this->viewer)
      ->withPHIDs(array($phid))
      ->executeOne();

    $is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business');
    if ($is_serious) {
      $title = pht(
        'Access Denied: %s',
        $handle->getObjectName());
    } else {
      $title = pht(
        'You Shall Not Pass: %s',
        $handle->getObjectName());
    }

    $full_message = pht(
      '[%s] (%s) %s // %s',
      $title,
      $capability_name,
      $rejection,
      implode(' ', $details));

    $exception = id(new PhabricatorPolicyException($full_message))
      ->setTitle($title)
      ->setRejection($rejection)
      ->setCapabilityName($capability_name)
      ->setMoreInfo($details);

    throw $exception;
  }

  private function loadCustomPolicies(array $phids) {
    $viewer = $this->viewer;
    $viewer_phid = $viewer->getPHID();

    $custom_policies = id(new PhabricatorPolicyQuery())
      ->setViewer($viewer)
      ->withPHIDs($phids)
      ->execute();
    $custom_policies = mpull($custom_policies, null, 'getPHID');

    $classes = array();
    $values = array();
    foreach ($custom_policies as $policy) {
      foreach ($policy->getCustomRuleClasses() as $class) {
        $classes[$class] = $class;
        $values[$class][] = $policy->getCustomRuleValues($class);
      }
    }

    foreach ($classes as $class => $ignored) {
      $object = newv($class, array());
      $object->willApplyRules($viewer, array_mergev($values[$class]));
      $classes[$class] = $object;
    }

    foreach ($custom_policies as $policy) {
      $policy->attachRuleObjects($classes);
    }

    if (empty($this->customPolicies[$viewer_phid])) {
      $this->customPolicies[$viewer_phid] = array();
    }

    $this->customPolicies[$viewer->getPHID()] += $custom_policies;
  }

  private function checkCustomPolicy($policy_phid) {
    $viewer = $this->viewer;
    $viewer_phid = $viewer->getPHID();

    $policy = $this->customPolicies[$viewer_phid][$policy_phid];

    $objects = $policy->getRuleObjects();
    $action = null;
    foreach ($policy->getRules() as $rule) {
      $object = idx($objects, idx($rule, 'rule'));
      if (!$object) {
        // Reject, this policy has a bogus rule.
        return false;
      }

      // If the user matches this rule, use this action.
      if ($object->applyRule($viewer, idx($rule, 'value'))) {
        $action = idx($rule, 'action');
        break;
      }
    }

    if ($action === null) {
      $action = $policy->getDefaultAction();
    }

    if ($action === PhabricatorPolicy::ACTION_ALLOW) {
      return true;
    }

    return false;
  }

  private function getObjectPolicy(
    PhabricatorPolicyInterface $object,
    $capability) {

    if ($this->forcedPolicy) {
      return $this->forcedPolicy;
    } else {
      return $object->getPolicy($capability);
    }
  }

}