text:
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using Analyzer.Utilities;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Semantics;

namespace System.Runtime.Analyzers
{
    /// <summary>
    /// CA1305: Specify IFormatProvider
    /// </summary>
    [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
    public sealed class SpecifyIFormatProviderAnalyzer : DiagnosticAnalyzer
    {
        internal const string RuleId = "CA1305";
        internal const string Uri = @"https://msdn.microsoft.com/en-us/library/ms182190.aspx";

        private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderTitle), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));

        private static readonly LocalizableString s_localizableMessageIFormatProviderAlternateString = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderMessageIFormatProviderAlternateString), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
        private static readonly LocalizableString s_localizableMessageIFormatProviderAlternate = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderMessageIFormatProviderAlternate), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
        private static readonly LocalizableString s_localizableMessageUICultureString = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderMessageUICultureString), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
        private static readonly LocalizableString s_localizableMessageUICulture = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderMessageUICulture), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
        private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.SpecifyIFormatProviderDescription), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));

        internal static DiagnosticDescriptor IFormatProviderAlternateStringRule = new DiagnosticDescriptor(RuleId,
                                                                             s_localizableTitle,
                                                                             s_localizableMessageIFormatProviderAlternateString,
                                                                             DiagnosticCategory.Globalization,
                                                                             DiagnosticSeverity.Warning,
                                                                             isEnabledByDefault: true,
                                                                             description: s_localizableDescription,
                                                                             helpLinkUri: Uri,
                                                                             customTags: WellKnownDiagnosticTags.Telemetry);
        internal static DiagnosticDescriptor IFormatProviderAlternateRule = new DiagnosticDescriptor(RuleId,
                                                                             s_localizableTitle,
                                                                             s_localizableMessageIFormatProviderAlternate,
                                                                             DiagnosticCategory.Globalization,
                                                                             DiagnosticSeverity.Warning,
                                                                             isEnabledByDefault: true,
                                                                             description: s_localizableDescription,
                                                                             helpLinkUri: Uri,
                                                                             customTags: WellKnownDiagnosticTags.Telemetry);
        internal static DiagnosticDescriptor UICultureStringRule = new DiagnosticDescriptor(RuleId,
                                                                             s_localizableTitle,
                                                                             s_localizableMessageUICultureString,
                                                                             DiagnosticCategory.Globalization,
                                                                             DiagnosticSeverity.Warning,
                                                                             isEnabledByDefault: true,
                                                                             description: s_localizableDescription,
                                                                             helpLinkUri: Uri,
                                                                             customTags: WellKnownDiagnosticTags.Telemetry);
        internal static DiagnosticDescriptor UICultureRule = new DiagnosticDescriptor(RuleId,
                                                                             s_localizableTitle,
                                                                             s_localizableMessageUICulture,
                                                                             DiagnosticCategory.Globalization,
                                                                             DiagnosticSeverity.Warning,
                                                                             isEnabledByDefault: true,
                                                                             description: s_localizableDescription,
                                                                             helpLinkUri: Uri,
                                                                             customTags: WellKnownDiagnosticTags.Telemetry);

        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(IFormatProviderAlternateStringRule, IFormatProviderAlternateRule, UICultureStringRule, UICultureRule);

        public override void Initialize(AnalysisContext analysisContext)
        {
            analysisContext.RegisterCompilationStartAction(csaContext =>
            {
                #region "Get All the WellKnown Types and Members"
                var iformatProviderType = csaContext.Compilation.GetTypeByMetadataName("System.IFormatProvider");
                var cultureInfoType = csaContext.Compilation.GetTypeByMetadataName("System.Globalization.CultureInfo");
                if (iformatProviderType == null || cultureInfoType == null)
                {
                    return;
                }

                var objectType = csaContext.Compilation.GetSpecialType(SpecialType.System_Object);
                var stringType = csaContext.Compilation.GetSpecialType(SpecialType.System_String);
                var stringFormatMembers = stringType?.GetMembers("Format").OfType<IMethodSymbol>();

                var stringFormatMemberWithStringAndObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
                                                                         GetParameterInfo(stringType),
                                                                         GetParameterInfo(objectType));
                var stringFormatMemberWithStringObjectAndObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
                                                                               GetParameterInfo(stringType),
                                                                               GetParameterInfo(objectType),
                                                                               GetParameterInfo(objectType));
                var stringFormatMemberWithStringObjectObjectAndObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
                                                                                GetParameterInfo(stringType),
                                                                                GetParameterInfo(objectType),
                                                                                GetParameterInfo(objectType),
                                                                                GetParameterInfo(objectType));
                var stringFormatMemberWithStringAndParamsObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
                                                                               GetParameterInfo(stringType),
                                                                               GetParameterInfo(objectType, isArray: true, arrayRank: 1, isParams: true));
                var stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter = stringFormatMembers.GetSingleOrDefaultMemberWithParameterInfos(
                                                                                GetParameterInfo(iformatProviderType),
                                                                                GetParameterInfo(stringType),
                                                                                GetParameterInfo(objectType, isArray: true, arrayRank: 1, isParams: true));

                var currentCultureProperty = cultureInfoType?.GetMembers("CurrentCulture").OfType<IPropertySymbol>().SingleOrDefault();
                var invariantCultureProperty = cultureInfoType?.GetMembers("InvariantCulture").OfType<IPropertySymbol>().SingleOrDefault();
                var currentUICultureProperty = cultureInfoType?.GetMembers("CurrentUICulture").OfType<IPropertySymbol>().SingleOrDefault();
                var installedUICultureProperty = cultureInfoType?.GetMembers("InstalledUICulture").OfType<IPropertySymbol>().SingleOrDefault();

                var threadType = csaContext.Compilation.GetTypeByMetadataName("System.Threading.Thread");
                var currentThreadCurrentUICultureProperty = threadType?.GetMembers("CurrentUICulture").OfType<IPropertySymbol>().SingleOrDefault();

                var activatorType = csaContext.Compilation.GetTypeByMetadataName("System.Activator");
                var resourceManagerType = csaContext.Compilation.GetTypeByMetadataName("System.Resources.ResourceManager");

                var computerInfoType = csaContext.Compilation.GetTypeByMetadataName("Microsoft.VisualBasic.Devices.ComputerInfo");
                var installedUICulturePropertyOfComputerInfoType = computerInfoType?.GetMembers("InstalledUICulture").OfType<IPropertySymbol>().SingleOrDefault();
                #endregion

                csaContext.RegisterOperationAction(oaContext =>
                {
                    var invocationExpression = (IInvocationExpression)oaContext.Operation;
                    var targetMethod = invocationExpression.TargetMethod;

                    #region "Exceptions"
                    if (targetMethod.IsGenericMethod || targetMethod.ContainingType == null || targetMethod.ContainingType.IsErrorType() ||
                        (targetMethod.ContainingType != null &&
                         (activatorType != null && activatorType.Equals(targetMethod.ContainingType)) ||
                         (resourceManagerType != null && resourceManagerType.Equals(targetMethod.ContainingType))))
                    {
                        return;
                    }
                    #endregion

                    #region "IFormatProviderAlternateStringRule Only"
                    if (stringType != null && cultureInfoType != null &&
                        (targetMethod.Equals(stringFormatMemberWithStringAndObjectParameter) ||
                         targetMethod.Equals(stringFormatMemberWithStringObjectAndObjectParameter) ||
                         targetMethod.Equals(stringFormatMemberWithStringObjectObjectAndObjectParameter) ||
                         targetMethod.Equals(stringFormatMemberWithStringAndParamsObjectParameter)))
                    {
                        // Sample message for IFormatProviderAlternateStringRule: Because the behavior of string.Format(string, object) could vary based on the current user's locale settings,
                        // replace this call in IFormatProviderStringTest.M() with a call to string.Format(IFormatProvider, string, params object[]).
                        oaContext.ReportDiagnostic(
                            invocationExpression.Syntax.CreateDiagnostic(
                                IFormatProviderAlternateStringRule,
                                targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));

                        return;
                    }
                    #endregion

                    #region "IFormatProviderAlternateStringRule & IFormatProviderAlternateRule"
                    IEnumerable<IMethodSymbol> methodsWithSameNameAsTargetMethod = targetMethod.ContainingType.GetMembers(targetMethod.Name).OfType<IMethodSymbol>();
                    if (methodsWithSameNameAsTargetMethod.Count() > 1)
                    {
                        var correctOverloads = methodsWithSameNameAsTargetMethod.GetMethodOverloadsWithDesiredParameterAtLeadingOrTrailing(targetMethod, iformatProviderType);

                        // If there are two matching overloads, one with CultureInfo as the first parameter and one with CultureInfo as the last parameter,
                        // report the diagnostic on the overload with CultureInfo as the last parameter, to match the behavior of FxCop.
                        var correctOverload = correctOverloads
                                              .Where(overload => overload.Parameters.Last().Type.Equals(iformatProviderType))
                                              .FirstOrDefault() ?? correctOverloads.FirstOrDefault();

                        // Sample message for IFormatProviderAlternateRule: Because the behavior of Convert.ToInt64(string) could vary based on the current user's locale settings,
                        // replace this call in IFormatProviderStringTest.TestMethod() with a call to Convert.ToInt64(string, IFormatProvider).
                        if (correctOverload != null)
                        {
                            oaContext.ReportDiagnostic(
                                invocationExpression.Syntax.CreateDiagnostic(
                                    targetMethod.ReturnType.Equals(stringType) ?
                                     IFormatProviderAlternateStringRule :
                                     IFormatProviderAlternateRule,
                                    targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                    oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                    correctOverload.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
                        }
                    }
                    #endregion

                    #region "UICultureStringRule & UICultureRule"
                    IEnumerable<int> IformatProviderParameterIndices = GetIndexesOfParameterType(targetMethod, iformatProviderType);
                    foreach (var index in IformatProviderParameterIndices)
                    {
                        var argument = invocationExpression.ArgumentsInParameterOrder[index];
                        if (argument != null && currentUICultureProperty != null &&
                            installedUICultureProperty != null && currentThreadCurrentUICultureProperty != null)
                        {
                            var semanticModel = oaContext.Compilation.GetSemanticModel(argument.Syntax.SyntaxTree);
                            var symbol = semanticModel.GetSymbolInfo(argument.Syntax).Symbol;

                            if (symbol != null &
                                (symbol.Equals(currentUICultureProperty) ||
                                 symbol.Equals(installedUICultureProperty) ||
                                 symbol.Equals(currentThreadCurrentUICultureProperty) ||
                                 (installedUICulturePropertyOfComputerInfoType != null && symbol.Equals(installedUICulturePropertyOfComputerInfoType))))
                            {
                                // Sample message
                                // 1. UICultureStringRule - 'TestClass.TestMethod()' passes 'Thread.CurrentUICulture' as the 'IFormatProvider' parameter to 'TestClass.CalleeMethod(string, IFormatProvider)'.
                                // This property returns a culture that is inappropriate for formatting methods.
                                // 2. UICultureRule -'TestClass.TestMethod()' passes 'CultureInfo.CurrentUICulture' as the 'IFormatProvider' parameter to 'TestClass.Callee(IFormatProvider, string)'.
                                // This property returns a culture that is inappropriate for formatting methods.

                                oaContext.ReportDiagnostic(
                                    invocationExpression.Syntax.CreateDiagnostic(
                                        targetMethod.ReturnType.Equals(stringType) ?
                                            UICultureStringRule :
                                            UICultureRule,
                                        oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                        symbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
                                        targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
                            }
                        }
                    }
                    #endregion

                }, OperationKind.InvocationExpression);
            });
        }

        private IEnumerable<int> GetIndexesOfParameterType(IMethodSymbol targetMethod, INamedTypeSymbol formatProviderType)
        {
            return targetMethod.Parameters
                .Select((Parameter, Index) => new { Parameter, Index })
                .Where(x => x.Parameter.Type.Equals(formatProviderType))
                .Select(x => x.Index);
        }

        private ParameterInfo GetParameterInfo(INamedTypeSymbol type, bool isArray = false, int arrayRank = 0, bool isParams = false)
        {
            return ParameterInfo.GetParameterInfo(type, isArray, arrayRank, isParams);
        }
    }
}


text:
package com.baidu.disconf.core.common.restful;

import com.baidu.disconf.core.common.restful.core.RemoteUrl;

/**
 * Restful 抓取工具
 *
 * @author liaoqiqi
 * @version 2014-7-29
 */
public interface RestfulMgr {

    /**
     * 获取JSON数据
     *
     * @param clazz
     * @param remoteUrl
     *
     * @return
     *
     * @throws Exception
     */
    <T> T getJsonData(Class<T> clazz, RemoteUrl remoteUrl, int retryTimes, int retrySleepSeconds) throws Exception;

    /**
     * @param remoteUrl     远程地址
     * @param fileName      文件名
     * @param localFileDir  本地文件地址
     * @param targetDirPath 下载完后,配置文件放到此目录下
     *
     * @return 如果是放到Classpath目录下,则返回相对Classpath的路径,如果不是,则返回全路径
     *
     * @throws Exception
     */
    String downloadFromServer(RemoteUrl remoteUrl, String fileName, String localFileDir, String localFileDirTemp,
                              String targetDirPath,
                              boolean enableLocalDownloadDirInClassPath,
                              int retryTimes, int retrySleepSeconds) throws Exception;

    void close();

}

redpajama_set_name: RedPajamaGithub


text:
package org.efaps.admin.dbproperty;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Formatter;
import java.util.HashSet;
import java.util.Locale;
import java.util.MissingFormatArgumentException;
import java.util.Set;

import org.efaps.admin.EFapsSystemConfiguration;
import org.efaps.admin.KernelSettings;
import org.efaps.admin.common.SystemConfiguration;
import org.efaps.db.Context;
import org.efaps.db.transaction.ConnectionResource;
import org.efaps.db.wrapper.SQLPart;
import org.efaps.db.wrapper.SQLSelect;
import org.efaps.util.EFapsException;
import org.efaps.util.cache.CacheLogListener;
import org.efaps.util.cache.InfinispanCache;
import org.infinispan.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class reads the Properties for eFaps from the connected Database and
 * holds them in a cache to be accessed fast during normal runtime.

 * The Keys will be read from the database in the order of the Sequence of a
 * Bundle. That gives the possibility to override the key of a Bundle with the
 * same key of another Bundle by using a higher Sequence.

 * The value returned for a key is searched first in the localized version, if
 * no Value can be found or no localized version for this language is existing
 * than the default value will be returned.
 *
 * @author The eFaps Team
 * @version $Id$
 */
public final class DBProperties
{

    /**
     * Logger for this class.
     */
    private static final Logger LOG = LoggerFactory.getLogger(DBProperties.class);

    /**
     * Name of the Infinispan Cache.
     */
    private static final String CACHENAME = DBProperties.class.getName();

    /**
     * String used instead of a NULL value.
     */
    private static final String NULLVALUE = "org.efaps.admin.dbproperty.NULL";

    /**
     * SQL Statement used to find a property including as criteria the language.
     */
    private static final String SQLSELECT = new SQLSelect()
                    .column(0, "DEFAULTV")
                    .column(2, "VALUE")
                    .from("T_ADPROP", 0)
                    .leftJoin("T_ADPROPBUN", 1, "ID", 0, "BUNDLEID")
                    .leftJoin("T_ADPROPLOC", 2, "PROPID", 0, "ID")
                    .leftJoin("T_ADLANG", 3, "ID", 2, "LANGID")
                    .addPart(SQLPart.WHERE).addColumnPart(0, "PROPKEY").addPart(SQLPart.EQUAL).addValuePart("?")
                    .addPart(SQLPart.AND)
                    .addPart(SQLPart.PARENTHESIS_OPEN)
                    .addColumnPart(3, "LANG").addPart(SQLPart.EQUAL).addValuePart("?")
                    .addPart(SQLPart.OR)
                    .addColumnPart(3, "LANG").addPart(SQLPart.IS).addPart(SQLPart.NULL)
                    .addPart(SQLPart.PARENTHESIS_CLOSE)
                    .addPart(SQLPart.ORDERBY)
                    .addColumnPart(1, "SEQUENCE").addPart(SQLPart.DESC).addPart(SQLPart.COMMA)
                    .addColumnPart(3, "LANG").toString();

    /**
     * SQL Statement used to find a property used if with the previous Statement no
     * result where found.
     */
    private static final String SQLSELECTDEF = new SQLSelect()
                    .column(0, "DEFAULTV")
                    .from("T_ADPROP", 0)
                    .leftJoin("T_ADPROPBUN", 1, "ID", 0, "BUNDLEID")
                    .addPart(SQLPart.WHERE).addColumnPart(0, "PROPKEY").addPart(SQLPart.EQUAL).addValuePart("?")
                    .addPart(SQLPart.ORDERBY)
                    .addColumnPart(1, "SEQUENCE").addPart(SQLPart.DESC).toString();

    /**
     * SQL Statement used to get the properties that must be cached on start.
     */
    private static final String SQLSELECTONSTART = new SQLSelect()
                    .column(0, "PROPKEY")
                    .column(0, "DEFAULTV")
                    .column(2, "VALUE")
                    .column(3, "LANG")
                    .from("T_ADPROP", 0)
                    .innerJoin("T_ADPROPBUN", 1, "ID", 0, "BUNDLEID")
                    .leftJoin("T_ADPROPLOC", 2, "PROPID", 0, "ID")
                    .leftJoin("T_ADLANG", 3, "ID", 2, "LANGID")
                    .addPart(SQLPart.WHERE)
                    .addColumnPart(1, "CACHEONSTART").addPart(SQLPart.EQUAL).addBooleanValue(true)
                    .addPart(SQLPart.ORDERBY)
                    .addColumnPart(1, "SEQUENCE").addPart(SQLPart.ASC).addPart(SQLPart.COMMA)
                    .addColumnPart(0, "PROPKEY").toString();

    /**
     * SQL Statement to get a list of languages.
     */
    private static final String SQLLANG = new SQLSelect()
                    .column("LANG")
                    .from("T_ADLANG").toString();
    /**
     * Private Constructor for Utility class.
     */
    private DBProperties()
    {
    }

    /**
     * Method to find out if a specified key is existing.

     * It is only checked in the default.
     *
     * @param _key Key to search for
     * @return true if the key exists
     */
    public static boolean hasProperty(final String _key)
    {
        return DBProperties.getProperty(_key, false) != null;
    }

    /**
     * Method that returns the value, depending on the language of the Context,
     * for the given key.

     * The Search for the key, first searches for a localized Version and if not
     * found for a Default. If no value can be found, the key will be returned.
     *
     * @param _key Key to Search for
     * @return if key exists, the value for the key, otherwise the key
     */
    public static String getProperty(final String _key)
    {
        String language = null;
        try {
            language = Context.getThreadContext().getLanguage();
        } catch (final EFapsException e) {
            DBProperties.LOG.error("not able to read the language from the context", e);
        }
        return DBProperties.getProperty(_key, language);
    }

    /**
     * Method that returns the value, depending on the language of the Context,
     * for the given key.

     * The Search for the key, first searches for a localized Version and if not
     * found for a Default. If no value can be found, the key will be returned.
     *
     * @param _key Key to Search for
     * @param _returnKey return the key if no property found
     * @return if key exists, the value for the key, otherwise the key
     */
    public static String getProperty(final String _key,
                                     final boolean _returnKey)
    {
        String language = null;
        try {
            language = Context.getThreadContext().getLanguage();
        } catch (final EFapsException e) {
            DBProperties.LOG.error("not able to read the language from the context", e);
        }
        return DBProperties.getProperty(_key, language, _returnKey);
    }

    /**
     * Method that returns the value, depending on the parameter _language, for
     * the given key.

     * The Search for the key, first searches for a localized Version and if not
     * found for a Default. If no value can be found, the key will be returned.
     *
     * @param _key Key to Search for
     * @param _language language to use
     * @return if key exists, the value for the key, otherwise the key
     */
    public static String getProperty(final String _key,
                                     final String _language)
    {
        return DBProperties.getProperty(_key, _language, true);
    }

    /**
     * Method that returns the value, depending on the parameter _language, for
     * the given key.

     * The Search for the key, first searches for a localized Version and if not
     * found for a Default. If no value can be found, the key will be returned.
     *
     * @param _key Key to Search for
     * @param _language language to use
     * @param _returnKey return the key if no property found
     * @return if key exists, the value for the key, otherwise the key
     */
    public static String getProperty(final String _key,
                                     final String _language,
                                     final boolean _returnKey)
    {
        String value = null;
        try {
            final SystemConfiguration config = EFapsSystemConfiguration.get();
            final boolean showKey = config == null
                            ? false
                            : config.getAttributeValueAsBoolean(KernelSettings.SHOW_DBPROPERTIES_KEY);

            if (showKey) {
                value = _key;
            } else {
                final String cachKey = _language + ":" + _key;
                final Cache<String, String> cache = InfinispanCache.get().<String, String>getCache(
                                DBProperties.CACHENAME);
                if (cache.containsKey(cachKey)) {
                    value = cache.get(cachKey);
                    if (value.equals(DBProperties.NULLVALUE)) {
                        value = null;
                    }
                } else {
                    value = DBProperties.getValueFromDB(_key, _language);
                    if (value == null) {
                        cache.put(cachKey, DBProperties.NULLVALUE);
                    } else {
                        cache.put(cachKey, value);
                    }
                }
            }
        } catch (final EFapsException e) {
            DBProperties.LOG.error("not able to read ShowDBPropertiesKey from the webConfig", e);
        }
        return (value == null && _returnKey) ? "?? - " + _key + " - ??" : value;
    }

    /**
     * Get a DBProperty and apply a java.util.Formatter with the
     * given _args on it.
     *
     * @param _key key the DBProperty will be searched for
     * @param _args object to be used for the formated
     * @return formated value for the key
     */
    public static String getFormatedDBProperty(final String _key,
                                               final Object... _args)
    {
        String language = null;
        try {
            language = Context.getThreadContext().getLanguage();
        } catch (final EFapsException e) {
            DBProperties.LOG.error("not able to read the language from the context", e);
        }
        return DBProperties.getFormatedDBProperty(_key, language, _args);
    }

    /**
     * Get a DBProperty and apply a java.util.Formatter with the
     * given _args on it.
     *
     * @param _key key the DBProperty will be searched for
     * @param _language language to be applied
     * @param _args object to be used for the formated
     * @return formated value for the key
     */
    public static String getFormatedDBProperty(final String _key,
                                               final String _language,
                                               final Object... _args)
    {
        String ret = "";
        try {
            ret = DBProperties.getProperty(_key, _language);
            final Locale local = Context.getThreadContext().getLocale();
            final Formatter formatter = new Formatter(local);
            formatter.format(ret, _args);
            ret = formatter.toString();
            formatter.close();
        } catch (final EFapsException e) {
            DBProperties.LOG.error("not able to read the locale from the context", e);
        } catch (final MissingFormatArgumentException e) {
            DBProperties.LOG.error("wrong format", e);
        }
        return ret;
    }

    /**
     * This method is initializing the cache.
     *
     * @param _key key to be read.
     * @param _language language to search for
     * @return value from the database, null if not found
     */
    private static String getValueFromDB(final String _key,
                                         final String _language)
    {
        String ret = null;
        try {
            boolean closeContext = false;
            if (!Context.isThreadActive()) {
                Context.begin();
                closeContext = true;
            }
            final ConnectionResource con = Context.getThreadContext().getConnectionResource();
            final PreparedStatement stmt = con.getConnection().prepareStatement(DBProperties.SQLSELECT);
            stmt.setString(1, _key);
            stmt.setString(2, _language);
            final ResultSet resultset = stmt.executeQuery();
            if (resultset.next()) {
                final String defaultValue = resultset.getString(1);
                final String value = resultset.getString(2);
                if (value != null) {
                    ret = value.trim();
                } else if (defaultValue != null) {
                    ret = defaultValue.trim();
                }
            } else {
                final PreparedStatement stmt2 = con.getConnection().prepareStatement(DBProperties.SQLSELECTDEF);
                stmt2.setString(1, _key);
                final ResultSet resultset2 = stmt2.executeQuery();
                if (resultset2.next()) {
                    final String defaultValue = resultset2.getString(1);
                    if (defaultValue != null) {
                        ret = defaultValue.trim();
                    }
                }
                resultset2.close();
                stmt2.close();
            }
            resultset.close();
            stmt.close();
            con.commit();
            if (closeContext) {
                Context.rollback();
            }
        } catch (final EFapsException e) {
            DBProperties.LOG.error("initialiseCache()", e);
        } catch (final SQLException e) {
            DBProperties.LOG.error("initialiseCache()", e);
        }
        return ret;
    }

    /**
     * Load the properties that must be cached on start.
     */
    private static void cacheOnStart()
    {
        try {
            boolean closeContext = false;
            if (!Context.isThreadActive()) {
                Context.begin();
                closeContext = true;
            }
            final ConnectionResource con = Context.getThreadContext().getConnectionResource();
            final PreparedStatement stmtLang = con.getConnection().prepareStatement(DBProperties.SQLLANG);
            final ResultSet rsLang = stmtLang.executeQuery();
            final Set<String> languages = new HashSet<String>();
            while (rsLang.next()) {
                languages.add(rsLang.getString(1).trim());
            }
            rsLang.close();
            stmtLang.close();
            final Cache<String, String> cache = InfinispanCache.get().<String, String>getCache(
                            DBProperties.CACHENAME);
            final PreparedStatement stmt = con.getConnection().prepareStatement(DBProperties.SQLSELECTONSTART);
            final ResultSet resultset = stmt.executeQuery();
            while (resultset.next()) {
                final String propKey = resultset.getString(1).trim();
                final String defaultValue = resultset.getString(2);
                if (defaultValue != null) {
                     final String value = defaultValue.trim();
                     for (final String lang : languages) {
                         final String cachKey = lang + ":" + propKey;
                         if (!cache.containsKey(cachKey)) {
                             cache.put(cachKey, value);
                         }
                     }
                }
                final String value = resultset.getString(3);
                final String lang = resultset.getString(4);
                if (value != null) {
                    final String cachKey = lang.trim() + ":" + propKey;
                    cache.put(cachKey, value.trim());
                }
            }
            resultset.close();
            stmt.close();
            con.commit();
            if (closeContext) {
                Context.rollback();
            }
        } catch (final EFapsException e) {
            DBProperties.LOG.error("initialiseCache()", e);
        } catch (final SQLException e) {
            DBProperties.LOG.error("initialiseCache()", e);
        }
    }

    /**
     * Initialize the Cache be calling it. Used from runtime level.
     */
    public static void initialize()
    {
        if (InfinispanCache.get().exists(DBProperties.CACHENAME)) {
            InfinispanCache.get().<String, String>getCache(DBProperties.CACHENAME).clear();
        } else {
            InfinispanCache.get().<String, String>getCache(DBProperties.CACHENAME)
                            .addListener(new CacheLogListener(DBProperties.LOG));
        }
        DBProperties.cacheOnStart();
    }
}


text:
using System.ComponentModel.DataAnnotations;

namespace DraftIt.Data
{
    public class Draft : IEntity
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }
    }
}


text:
<?php

namespace frontend\models;

use Yii;
use frontend\models\AuthInterface;
use common\models\User;

class Twitter implements AuthInterface
{
    public function getData($client)
    {
        $userTwitter = $client->api('https://api.twitter.com/1.1/account/verify_credentials.json', 'GET');
        $this->signUp($userTwitter);
    }
    private function signUp($userTwitter)
    {
        $user = User::findByUsername($userTwitter['name']);
        if($user !== null) {

           return Yii::$app->user->login($user, 60 * 30) ?  true : false;
        }else{
            $user = new User();
            $user->username = $userTwitter['name'];
            $user->user_photo = str_replace('_normal', '', $userTwitter['profile_image_url']);
            return $user->save(false) ? true : false;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

	<title>modal</title>

This is the title

            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus nisl dolor, pulvinar id, pharetra a, egestas nec, ante. Duis scelerisque eleifend metus. Sed non odio id odio varius rutrum. Pellentesque congue commodo lacus. In semper pede lacinia felis. Morbi mollis molestie lorem. Morbi suscipit libero. Quisque ut erat sit amet elit aliquam nonummy. Donec tortor. Aliquam gravida ullamcorper pede. Praesent eros. Sed fringilla ligula sed odio pharetra imperdiet. Integer aliquet quam vitae nibh. Nam pretium, neque non congue vulputate, odio odio vehicula augue, sit amet gravida pede massa ac lectus. Curabitur a libero vitae dui sagittis aliquet. Ut suscipit. Curabitur accumsan sem a urna. Ut elit pede, vulputate sed, feugiat quis, congue sed, lacus.


text:
package com.jrestless.test;

import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.Objects;

import org.junit.jupiter.api.Test;

import com.jrestless.test.CopyConstructorEqualsTester.ConstructorInvocationException;

public class CopyConstructorEqualsTesterTest {

	@Test
	public void testEquals_NotAllParametersGiven_ShouldThrowIse() throws NoSuchMethodException, SecurityException {
		assertThrows(IllegalStateException.class, () -> {
			new CopyConstructorEqualsTester(CorrectValueObject.class.getDeclaredConstructor(Integer.class, double.class))
				.addArguments(0, 0, 1)
				.testEquals();
		});
	}

	@Test
	public void testEquals_InvalidArgumentTypeGiven_ShouldThrowIae() throws NoSuchMethodException, SecurityException {
		assertThrows(IllegalArgumentException.class, () -> {
			new CopyConstructorEqualsTester(CorrectValueObject.class.getDeclaredConstructor(Integer.class, double.class))
				.addArguments(0, 0, 1L);
		});
	}

	@Test
	public void testEquals_CorrectValueObjectGiven_ShouldPassEqualsTest() throws NoSuchMethodException, SecurityException {
		new CopyConstructorEqualsTester(CorrectValueObject.class.getDeclaredConstructor(Integer.class, double.class))
			.addArguments(0, 0, 1)
			.addArguments(1, 0.0, 0.1)
			.testEquals();
	}

	@Test
	public void testEquals_IncorrectValueObjectGiven_ShouldNotPassEqualsTest() throws NoSuchMethodException, SecurityException {
		assertThrows(AssertionError.class, () -> {
			new CopyConstructorEqualsTester(IncorrectValueObject.class.getDeclaredConstructor(Integer.class, double.class, char.class))
				.addArguments(0, 0, 1)
				.addArguments(1, 0.0, 0.1)
				.addArguments(2, 'a', 'b')
				.testEquals();
		});
	}

	@Test
	public void testEquals_ConstructorThrowsException_ShouldFail() throws NoSuchMethodException, SecurityException {
		assertThrows(ConstructorInvocationException.class, () -> {
			new CopyConstructorEqualsTester(ThrowingConstructor.class.getDeclaredConstructor(String.class))
				.addArguments(0, "abc")
				.testEquals();
		});
	}

	private static class IncorrectValueObject extends CorrectValueObject {

		private final char c;

		IncorrectValueObject(Integer a, double b, char c) {
			super(a, b);
			this.c = c;
		}

		@Override
		public String toString() {
			return "IncorrectValueObject [c=" + c + ", getA()=" + getA() + ", getB()=" + getB() + "]";
		}
	}

	private static class CorrectValueObject {

		private final Integer a;
		private final double b;

		CorrectValueObject(Integer a, double b) {
			this.a = a;
			this.b = b;
		}

		Integer getA() {
			return a;
		}

		double getB() {
			return b;
		}

		@Override
		public String toString() {
			return "SomeClass [a=" + a + ", b=" + b + "]";
		}

		@Override
		public boolean equals(final Object other) {
			if (this == other) {
				return true;
			}
			if (other == null) {
				return false;
			}
			if (!getClass().equals(other.getClass())) {
				return false;
			}
			CorrectValueObject castOther = (CorrectValueObject) other;
			return Objects.equals(a, castOther.a) && Objects.equals(b, castOther.b);
		}

		@Override
		public int hashCode() {
			return Objects.hash(a, b);
		}
	}

	private static class ThrowingConstructor {
		@SuppressWarnings("unused")
		ThrowingConstructor(String value) {
			throw new RuntimeException("whatever");
		}
	}
}


text:
package org.apache.commons.lang3.text;

import java.util.Map;

/**
 * Lookup a String key to a String value.
 *

 * This class represents the simplest form of a string to string map.
 * It has a benefit over a map in that it can create the result on
 * demand based on the key.
 *

 * This class comes complete with various factory methods.
 * If these do not suffice, you can subclass and implement your own matcher.
 *

 * For example, it would be possible to implement a lookup that used the
 * key as a primary key, and looked up the value on demand from the database
 *
 * @since 2.2
 * @version $Id$
 */
public abstract class StrLookup<V> {

    /**
     * Lookup that always returns null.
     */
    private static final StrLookup<String> NONE_LOOKUP;
    /**
     * Lookup that uses System properties.
     */
    private static final StrLookup<String> SYSTEM_PROPERTIES_LOOKUP;
    static {
        NONE_LOOKUP = new MapStrLookup<String>(null);
        StrLookup<String> lookup = null;
        try {
            final Map<?, ?> propMap = System.getProperties();
            @SuppressWarnings("unchecked") // System property keys and values are always Strings
            final Map<String, String> properties = (Map<String, String>) propMap;
            lookup = new MapStrLookup<String>(properties);
        } catch (final SecurityException ex) {
            lookup = NONE_LOOKUP;
        }
        SYSTEM_PROPERTIES_LOOKUP = lookup;
    }

    //-----------------------------------------------------------------------
    /**
     * Returns a lookup which always returns null.
     *
     * @return a lookup that always returns null, not null
     */
    public static StrLookup<?> noneLookup() {
        return NONE_LOOKUP;
    }

    /**
     * Returns a lookup which uses {@link System#getProperties() System properties}
     * to lookup the key to value.
     *

     * If a security manager blocked access to system properties, then null will
     * be returned from every lookup.
     *

     * If a null key is used, this lookup will throw a NullPointerException.
     *
     * @return a lookup using system properties, not null
     */
    public static StrLookup<String> systemPropertiesLookup() {
        return SYSTEM_PROPERTIES_LOOKUP;
    }

    /**
     * Returns a lookup which looks up values using a map.
     *

     * If the map is null, then null will be returned from every lookup.
     * The map result object is converted to a string using toString().
     *
     * @param <V> the type of the values supported by the lookup
     * @param map  the map of keys to values, may be null
     * @return a lookup using the map, not null
     */
    public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
        return new MapStrLookup<V>(map);
    }

    //-----------------------------------------------------------------------
    /**
     * Constructor.
     */
    protected StrLookup() {
        super();
    }

    /**
     * Looks up a String key to a String value.
     *

     * The internal implementation may use any mechanism to return the value.
     * The simplest implementation is to use a Map. However, virtually any
     * implementation is possible.
     *

     * For example, it would be possible to implement a lookup that used the
     * key as a primary key, and looked up the value on demand from the database
     * Or, a numeric based implementation could be created that treats the key
     * as an integer, increments the value and return the result as a string -
     * converting 1 to 2, 15 to 16 etc.
     *

     * The {@link #lookup(String)} method always returns a String, regardless of
     * the underlying data, by converting it as necessary. For example:
     *

     * Map<String, Object> map = new HashMap<String, Object>();
     * map.put("number", Integer.valueOf(2));
     * assertEquals("2", StrLookup.mapLookup(map).lookup("number"));
     *

     * @param key  the key to be looked up, may be null
     * @return the matching value, null if no match
     */
    public abstract String lookup(String key);

    //-----------------------------------------------------------------------
    /**
     * Lookup implementation that uses a Map.
     */
    static class MapStrLookup<V> extends StrLookup<V> {

        /** Map keys are variable names and value. */
        private final Map<String, V> map;

        /**
         * Creates a new instance backed by a Map.
         *
         * @param map  the map of keys to values, may be null
         */
        MapStrLookup(final Map<String, V> map) {
            this.map = map;
        }

        /**
         * Looks up a String key to a String value using the map.
         *

         * If the map is null, then null is returned.
         * The map result object is converted to a string using toString().
         *
         * @param key  the key to be looked up, may be null
         * @return the matching value, null if no match
         */
        @Override
        public String lookup(final String key) {
            if (map == null) {
                return null;
            }
            final Object obj = map.get(key);
            if (obj == null) {
                return null;
            }
            return obj.toString();
        }
    }
}


text:
package com.streamsets.pipeline.lib.generator.avro;

import com.google.common.collect.ImmutableSet;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.config.DestinationAvroSchemaSource;
import com.streamsets.pipeline.lib.generator.DataGenerator;
import com.streamsets.pipeline.lib.generator.DataGeneratorFactory;
import com.streamsets.pipeline.lib.util.AvroSchemaHelper;
import com.streamsets.pipeline.lib.util.SchemaRegistryException;
import org.apache.avro.Schema;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.streamsets.pipeline.config.DestinationAvroSchemaSource.INLINE;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.BASIC_AUTH_USER_INFO;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.BASIC_AUTH_USER_INFO_DEFAULT;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.COMPRESSION_CODEC_DEFAULT;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.COMPRESSION_CODEC_KEY;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.DEFAULT_VALUES_KEY;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.INCLUDE_SCHEMA_DEFAULT;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.INCLUDE_SCHEMA_KEY;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.REGISTER_SCHEMA_DEFAULT;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.REGISTER_SCHEMA_KEY;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SCHEMA_DEFAULT;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SCHEMA_ID_DEFAULT;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SCHEMA_ID_KEY;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SCHEMA_KEY;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SCHEMA_REPO_URLS_KEY;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SCHEMA_SOURCE_KEY;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SUBJECT_DEFAULT;
import static com.streamsets.pipeline.lib.util.AvroSchemaHelper.SUBJECT_KEY;

public class AvroDataGeneratorFactory extends DataGeneratorFactory {
  public static final Map<String, Object> CONFIGS;
  private static final DestinationAvroSchemaSource SCHEMA_SOURCE_DEFAULT = INLINE;

  static {
    Map<String, Object> configs = new HashMap<>();
    configs.put(SCHEMA_KEY, SCHEMA_DEFAULT);
    configs.put(SCHEMA_SOURCE_KEY, SCHEMA_SOURCE_DEFAULT);
    configs.put(SCHEMA_ID_KEY, SCHEMA_ID_DEFAULT);
    configs.put(SUBJECT_KEY, SUBJECT_DEFAULT);
    configs.put(SCHEMA_REPO_URLS_KEY, new ArrayList<>());
    configs.put(INCLUDE_SCHEMA_KEY, INCLUDE_SCHEMA_DEFAULT);
    configs.put(DEFAULT_VALUES_KEY, new HashMap<>());
    configs.put(COMPRESSION_CODEC_KEY, COMPRESSION_CODEC_DEFAULT);
    configs.put(REGISTER_SCHEMA_KEY, REGISTER_SCHEMA_DEFAULT);
    configs.put(BASIC_AUTH_USER_INFO, BASIC_AUTH_USER_INFO_DEFAULT);
    CONFIGS = Collections.unmodifiableMap(configs);
  }

  @SuppressWarnings("unchecked")
  public static final Set<Class<? extends Enum>> MODES = (Set) ImmutableSet.of(); // NOSONAR

  private final AvroSchemaHelper schemaHelper;
  private final String schemaSubject;
  private final DestinationAvroSchemaSource schemaSource;
  private final boolean includeSchema;
  private final String compressionCodec;

  private Schema schema;
  private Map<String, Object> defaultValuesFromSchema;
  private int schemaId = 0;

  public AvroDataGeneratorFactory(Settings settings) throws SchemaRegistryException {
    super(settings);

    schemaHelper = new AvroSchemaHelper(settings);

    includeSchema = settings.getConfig(INCLUDE_SCHEMA_KEY);
    schemaSource = settings.getConfig(SCHEMA_SOURCE_KEY);
    defaultValuesFromSchema = settings.getConfig(DEFAULT_VALUES_KEY);
    schemaId = settings.getConfig(SCHEMA_ID_KEY);
    schemaSubject = settings.getConfig(SUBJECT_KEY);

    switch (schemaSource) {
      case HEADER:
        schema = null;
        break;
      case REGISTRY:
        initFromRegistry(schemaSubject);
        break;
      case INLINE:
        initFromInline(settings, schemaSubject);
        break;
      default:
        throw new UnsupportedOperationException("Unsupported Avro Schema source: " + schemaSource.getLabel());
    }
    compressionCodec = settings.getConfig(COMPRESSION_CODEC_KEY);
  }

  private void initFromInline(Settings settings, String subject) throws SchemaRegistryException {
    schema = schemaHelper.loadFromString((String) settings.getConfig(SCHEMA_KEY));
    if (schemaHelper.hasRegistryClient()) {
      schemaId = schemaHelper.registerSchema(schema, subject);
    }
    Utils.checkNotNull(schema, "Avro Schema");
  }

  private void initFromRegistry(String subject) throws SchemaRegistryException {
    schema = schemaHelper.loadFromRegistry(subject, schemaId);
    defaultValuesFromSchema = AvroSchemaHelper.getDefaultValues(schema);
    // If subject configuration is specified, figure out schemaId
    if (!subject.isEmpty()) {
      schemaId = schemaHelper.getSchemaIdFromSubject(subject);
    }
  }

  @Override
  public DataGenerator getGenerator(OutputStream os) throws IOException {
    DataGenerator dataGenerator;
    boolean schemaInHeader = schemaSource == DestinationAvroSchemaSource.HEADER;

    if (includeSchema) {
      dataGenerator = new AvroDataOutputStreamGenerator(
          schemaInHeader,
          os,
          compressionCodec,
          schema,
          defaultValuesFromSchema,
          schemaSubject,
          schemaHelper,
          schemaId
      );
    } else {
      dataGenerator = new AvroMessageGenerator(
        schemaInHeader,
        os,
        schema,
        defaultValuesFromSchema,
        schemaSubject,
        schemaHelper,
        schemaId
      );
    }
    return dataGenerator;
  }

}


text:
package org.jfree.chart.renderer.xy;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;

import java.awt.Color;
import java.util.Date;

import org.jfree.chart.TestUtilities;

import org.jfree.data.Range;
import org.jfree.data.xy.DefaultOHLCDataset;
import org.jfree.data.xy.OHLCDataItem;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.util.PublicCloneable;
import org.junit.Test;

/**
 * Tests for the {@link HighLowRenderer} class.
 */
public class HighLowRendererTest {

    /**
     * Check that the equals() method distinguishes all fields.
     */
    @Test
    public void testEquals() {
        HighLowRenderer r1 = new HighLowRenderer();
        HighLowRenderer r2 = new HighLowRenderer();
        assertEquals(r1, r2);

        // drawOpenTicks
        r1.setDrawOpenTicks(false);
        assertFalse(r1.equals(r2));
        r2.setDrawOpenTicks(false);
        assertTrue(r1.equals(r2));

        // drawCloseTicks
        r1.setDrawCloseTicks(false);
        assertFalse(r1.equals(r2));
        r2.setDrawCloseTicks(false);
        assertTrue(r1.equals(r2));

        // openTickPaint
        r1.setOpenTickPaint(Color.red);
        assertFalse(r1.equals(r2));
        r2.setOpenTickPaint(Color.red);
        assertTrue(r1.equals(r2));

        // closeTickPaint
        r1.setCloseTickPaint(Color.blue);
        assertFalse(r1.equals(r2));
        r2.setCloseTickPaint(Color.blue);
        assertTrue(r1.equals(r2));

        // tickLength
        r1.setTickLength(99.9);
        assertFalse(r1.equals(r2));
        r2.setTickLength(99.9);
        assertTrue(r1.equals(r2));
    }

    /**
     * Two objects that are equal are required to return the same hashCode.
     */
    @Test
    public void testHashcode() {
        HighLowRenderer r1 = new HighLowRenderer();
        HighLowRenderer r2 = new HighLowRenderer();
        assertTrue(r1.equals(r2));
        int h1 = r1.hashCode();
        int h2 = r2.hashCode();
        assertEquals(h1, h2);
    }

    /**
     * Confirm that cloning works.
     */
    @Test
    public void testCloning() throws CloneNotSupportedException {
        HighLowRenderer r1 = new HighLowRenderer();
        r1.setCloseTickPaint(Color.green);
        HighLowRenderer r2 = (HighLowRenderer) r1.clone();
        assertTrue(r1 != r2);
        assertTrue(r1.getClass() == r2.getClass());
        assertTrue(r1.equals(r2));
    }

    /**
     * Verify that this class implements {@link PublicCloneable}.
     */
    @Test
    public void testPublicCloneable() {
        HighLowRenderer r1 = new HighLowRenderer();
        assertTrue(r1 instanceof PublicCloneable);
    }

    /**
     * Serialize an instance, restore it, and check for equality.
     */
    @Test
    public void testSerialization() {
        HighLowRenderer r1 = new HighLowRenderer();
        r1.setCloseTickPaint(Color.green);
        HighLowRenderer r2 = (HighLowRenderer) TestUtilities.serialised(r1);
        assertEquals(r1, r2);
    }

    /**
     * Some checks for the findRangeBounds() method.
     */
    @Test
    public void testFindRangeBounds() {
        HighLowRenderer renderer = new HighLowRenderer();

        OHLCDataItem item1 = new OHLCDataItem(new Date(1L), 2.0, 4.0, 1.0, 3.0,
                100);
        OHLCDataset dataset = new DefaultOHLCDataset("S1",
                new OHLCDataItem[] {item1});
        Range range = renderer.findRangeBounds(dataset);
        assertEquals(new Range(1.0, 4.0), range);

        OHLCDataItem item2 = new OHLCDataItem(new Date(1L), -1.0, 3.0, -1.0,
                3.0, 100);
        dataset = new DefaultOHLCDataset("S1", new OHLCDataItem[] {item1,
                item2});
        range = renderer.findRangeBounds(dataset);
        assertEquals(new Range(-1.0, 4.0), range);

        // try an empty dataset - should return a null range
        dataset = new DefaultOHLCDataset("S1", new OHLCDataItem[] {});
        range = renderer.findRangeBounds(dataset);
        assertNull(range);

        // try a null dataset - should return a null range
        range = renderer.findRangeBounds(null);
        assertNull(range);
    }

}


text:
/**
 * Representation of the C type that the C backend uses to
 * represent object slot offset maps
 *
 * @author colin.gordon
 */
package com.samsung.sjs.backend.asts.c.types;
// This type hard-codes a type name defined in a C header we always include
// in generated code.
public final class VTablePseudoType extends CType {
    public String toSource() { return "object_map"; }
    public VTablePseudoType() { super(1); }
}


text:
var debug = require('debug')('hci');

var events = require('events');
var util = require('util');

var BluetoothHciSocket = require('bluetooth-hci-socket');

var ATT_OP_ERROR                    = 0x01;
var ATT_OP_MTU_REQ                  = 0x02;
var ATT_OP_MTU_RESP                 = 0x03;
var ATT_OP_FIND_INFO_REQ            = 0x04;
var ATT_OP_FIND_INFO_RESP           = 0x05;
var ATT_OP_FIND_BY_TYPE_REQ         = 0x06;
var ATT_OP_FIND_BY_TYPE_RESP        = 0x07;
var ATT_OP_READ_BY_TYPE_REQ         = 0x08;
var ATT_OP_READ_BY_TYPE_RESP        = 0x09;
var ATT_OP_READ_REQ                 = 0x0a;
var ATT_OP_READ_RESP                = 0x0b;
var ATT_OP_READ_BLOB_REQ            = 0x0c;
var ATT_OP_READ_BLOB_RESP           = 0x0d;
var ATT_OP_READ_MULTI_REQ           = 0x0e;
var ATT_OP_READ_MULTI_RESP          = 0x0f;
var ATT_OP_READ_BY_GROUP_REQ        = 0x10;
var ATT_OP_READ_BY_GROUP_RESP       = 0x11;
var ATT_OP_WRITE_REQ                = 0x12;
var ATT_OP_WRITE_RESP               = 0x13;
var ATT_OP_WRITE_CMD                = 0x52;
var ATT_OP_PREP_WRITE_REQ           = 0x16;
var ATT_OP_PREP_WRITE_RESP          = 0x17;
var ATT_OP_EXEC_WRITE_REQ           = 0x18;
var ATT_OP_EXEC_WRITE_RESP          = 0x19;
var ATT_OP_HANDLE_NOTIFY            = 0x1b;
var ATT_OP_HANDLE_IND               = 0x1d;
var ATT_OP_HANDLE_CNF               = 0x1e;
var ATT_OP_WRITE_CMD                = 0x52;
var ATT_OP_SIGNED_WRITE_CMD         = 0xd2;

var HCI_COMMAND_PKT = 0x01;
var HCI_ACLDATA_PKT = 0x02;
var HCI_EVENT_PKT = 0x04;

var ACL_START_NO_FLUSH = 0x00;
var ACL_CONT  = 0x01;
var ACL_START = 0x02;

var EVT_DISCONN_COMPLETE = 0x05;
var EVT_ENCRYPT_CHANGE = 0x08;
var EVT_CMD_COMPLETE = 0x0e;
var EVT_CMD_STATUS = 0x0f;
var EVT_LE_META_EVENT = 0x3e;

var EVT_LE_CONN_COMPLETE = 0x01;
var EVT_LE_ADVERTISING_REPORT = 0x02;
var EVT_LE_CONN_UPDATE_COMPLETE = 0x03;

var OGF_LINK_CTL = 0x01;
var OCF_DISCONNECT = 0x0006;

var OGF_HOST_CTL = 0x03;
var OCF_SET_EVENT_MASK = 0x0001;

var OGF_INFO_PARAM = 0x04;
var OCF_READ_LOCAL_VERSION = 0x0001;
var OCF_READ_BD_ADDR = 0x0009;

var OGF_STATUS_PARAM = 0x05;
var OCF_READ_RSSI = 0x0005;

var OGF_LE_CTL = 0x08;
var OCF_LE_SET_EVENT_MASK = 0x0001;
var OCF_LE_SET_ADVERTISING_PARAMETERS = 0x0006;
var OCF_LE_SET_ADVERTISING_DATA = 0x0008;
var OCF_LE_SET_SCAN_RESPONSE_DATA = 0x0009;
var OCF_LE_SET_ADVERTISE_ENABLE = 0x000a;
var OCF_LE_LTK_NEG_REPLY = 0x001B;
var OCF_LE_SET_SCAN_PARAMETERS = 0x000b;
var OCF_LE_SET_SCAN_ENABLE = 0x000c;
var OCF_LE_CREATE_CONN = 0x000d;
var OCF_LE_START_ENCRYPTION = 0x0019;

var DISCONNECT_CMD = OCF_DISCONNECT | OGF_LINK_CTL << 10;

var SET_EVENT_MASK_CMD = OCF_SET_EVENT_MASK | OGF_HOST_CTL << 10;

var READ_LOCAL_VERSION_CMD = OCF_READ_LOCAL_VERSION | (OGF_INFO_PARAM << 10);
var READ_BD_ADDR_CMD = OCF_READ_BD_ADDR | (OGF_INFO_PARAM << 10);

var READ_RSSI_CMD = OCF_READ_RSSI | OGF_STATUS_PARAM << 10;

var LE_SET_EVENT_MASK_CMD = OCF_SET_EVENT_MASK | OGF_LE_CTL << 10;
var LE_SET_SCAN_PARAMETERS_CMD = OCF_LE_SET_SCAN_PARAMETERS | OGF_LE_CTL << 10;
var LE_SET_SCAN_ENABLE_CMD = OCF_LE_SET_SCAN_ENABLE | OGF_LE_CTL << 10;
var LE_CREATE_CONN_CMD = OCF_LE_CREATE_CONN | OGF_LE_CTL << 10;
var LE_START_ENCRYPTION_CMD = OCF_LE_START_ENCRYPTION | OGF_LE_CTL << 10;
var LE_SET_ADVERTISING_PARAMETERS_CMD = OCF_LE_SET_ADVERTISING_PARAMETERS | OGF_LE_CTL << 10;
var LE_SET_ADVERTISING_DATA_CMD = OCF_LE_SET_ADVERTISING_DATA | OGF_LE_CTL << 10;
var LE_SET_SCAN_RESPONSE_DATA_CMD = OCF_LE_SET_SCAN_RESPONSE_DATA | OGF_LE_CTL << 10;
var LE_SET_ADVERTISE_ENABLE_CMD = OCF_LE_SET_ADVERTISE_ENABLE | OGF_LE_CTL << 10;
var LE_LTK_NEG_REPLY_CMD = OCF_LE_LTK_NEG_REPLY | OGF_LE_CTL << 10;

var HCI_OE_USER_ENDED_CONNECTION = 0x13;

var STATUS_MAPPER = require('./hci-status');

var Hci = function() {
  this._socket = new BluetoothHciSocket();
  this._isDevUp = null;

  this._handleBuffers = {};
};

util.inherits(Hci, events.EventEmitter);

Hci.STATUS_MAPPER = STATUS_MAPPER;

Hci.prototype.init = function() {
  this._socket.on('data', this.onSocketData.bind(this));
  this._socket.on('error', this.onSocketError.bind(this));

  var deviceId = process.env.ABLE_HCI_DEVICE_ID ? parseInt(process.env.ABLE_HCI_DEVICE_ID, 10) : undefined;

  this._socket.bindRaw(deviceId);
  this._socket.start();

  this.pollIsDevUp();
};

Hci.prototype.pollIsDevUp = function() {
  var isDevUp = this._socket.isDevUp();

  if (this._isDevUp !== isDevUp) {
    if (isDevUp) {
      this.setSocketFilter();
      this.setEventMask();
      this.setLeEventMask();
      this.readLocalVersion();
      this.readBdAddr();
    } else {
      this.emit('stateChange', 'poweredOff');
    }

    this._isDevUp = isDevUp;
  }

  setTimeout(this.pollIsDevUp.bind(this), 1000);
};

Hci.prototype.setSocketFilter = function() {
  var filter = new Buffer(14);
  var typeMask = (1 << HCI_EVENT_PKT)| (1 << HCI_ACLDATA_PKT);
  var eventMask1 = (1 << EVT_DISCONN_COMPLETE) | (1 << EVT_ENCRYPT_CHANGE) | (1 << EVT_CMD_COMPLETE) | (1 << EVT_CMD_STATUS);
  var eventMask2 = (1 << (EVT_LE_META_EVENT - 32));
  var opcode = 0;

  filter.writeUInt32LE(typeMask, 0);
  filter.writeUInt32LE(eventMask1, 4);
  filter.writeUInt32LE(eventMask2, 8);
  filter.writeUInt16LE(opcode, 12);

  debug('setting filter to: ' + filter.toString('hex'));
  this._socket.setFilter(filter);
};

Hci.prototype.setEventMask = function() {
  var cmd = new Buffer(12);
  var eventMask = new Buffer('fffffbff07f8bf3d', 'hex');

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(SET_EVENT_MASK_CMD, 1);

  // length
  cmd.writeUInt8(eventMask.length, 3);

  eventMask.copy(cmd, 4);

  debug('set event mask - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.readLocalVersion = function() {
  var cmd = new Buffer(4);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(READ_LOCAL_VERSION_CMD, 1);

  // length
  cmd.writeUInt8(0x0, 3);

  debug('read local version - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.readBdAddr = function() {
  var cmd = new Buffer(4);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(READ_BD_ADDR_CMD, 1);

  // length
  cmd.writeUInt8(0x0, 3);

  debug('read bd addr - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.setLeEventMask = function() {
  var cmd = new Buffer(12);
  var leEventMask = new Buffer('1f00000000000000', 'hex');

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(LE_SET_EVENT_MASK_CMD, 1);

  // length
  cmd.writeUInt8(leEventMask.length, 3);

  leEventMask.copy(cmd, 4);

  debug('set le event mask - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.setAdvertisingParameters = function() {
  var cmd = new Buffer(19);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(LE_SET_ADVERTISING_PARAMETERS_CMD, 1);

  // length
  cmd.writeUInt8(15, 3);

  var advertisementInterval = Math.floor((process.env.BLENO_ADVERTISING_INTERVAL ? parseInt(process.env.BLENO_ADVERTISING_INTERVAL) : 20) * 1.6);

  // data
  cmd.writeUInt16LE(advertisementInterval, 4); // min interval
  cmd.writeUInt16LE(advertisementInterval, 6); // max interval
  cmd.writeUInt8(0x00, 8); // adv type
  cmd.writeUInt8(0x00, 9); // own addr typ
  cmd.writeUInt8(0x00, 10); // direct addr type
  (new Buffer('000000000000', 'hex')).copy(cmd, 11); // direct addr
  cmd.writeUInt8(0x07, 17);
  cmd.writeUInt8(0x00, 18);

  debug('set advertisement parameters - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.setAdvertisingData = function(data) {
  var cmd = new Buffer(36);

  cmd.fill(0x00);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(LE_SET_ADVERTISING_DATA_CMD, 1);

  // length
  cmd.writeUInt8(32, 3);

  // data
  cmd.writeUInt8(data.length, 4);
  data.copy(cmd, 5);

  debug('set advertisement data - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.setScanResponseData = function(data) {
  var cmd = new Buffer(36);

  cmd.fill(0x00);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(LE_SET_SCAN_RESPONSE_DATA_CMD, 1);

  // length
  cmd.writeUInt8(32, 3);

  // data
  cmd.writeUInt8(data.length, 4);
  data.copy(cmd, 5);

  debug('set scan response data - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.setAdvertiseEnable = function(enabled) {
  var cmd = new Buffer(5);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(LE_SET_ADVERTISE_ENABLE_CMD, 1);

  // length
  cmd.writeUInt8(0x01, 3);

  // data
  cmd.writeUInt8(enabled ? 0x01 : 0x00, 4); // enable: 0 -> disabled, 1 -> enabled

  debug('set advertise enable - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.setScanParameters = function() {
  var cmd = new Buffer(11);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(LE_SET_SCAN_PARAMETERS_CMD, 1);

  // length
  cmd.writeUInt8(0x07, 3);

  // data
  cmd.writeUInt8(0x01, 4); // type: 0 -> passive, 1 -> active
  cmd.writeUInt16LE(0x0010, 5); // internal, ms * 1.6
  cmd.writeUInt16LE(0x0010, 7); // window, ms * 1.6
  cmd.writeUInt8(0x00, 9); // own address type: 0 -> public, 1 -> random
  cmd.writeUInt8(0x00, 10); // filter: 0 -> all event types

  debug('set scan parameters - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.setScanEnabled = function(enabled, filterDuplicates) {
  var cmd = new Buffer(6);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(LE_SET_SCAN_ENABLE_CMD, 1);

  // length
  cmd.writeUInt8(0x02, 3);

  // data
  cmd.writeUInt8(enabled ? 0x01 : 0x00, 4); // enable: 0 -> disabled, 1 -> enabled
  cmd.writeUInt8(filterDuplicates ? 0x01 : 0x00, 5); // duplicates: 0 -> duplicates, 0 -> duplicates

  debug('set scan enabled - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.createLeConn = function(address, addressType) {
  var cmd = new Buffer(29);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(LE_CREATE_CONN_CMD, 1);

  // length
  cmd.writeUInt8(0x19, 3);

  // data
  cmd.writeUInt16LE(0x0060, 4); // interval
  cmd.writeUInt16LE(0x0030, 6); // window
  cmd.writeUInt8(0x00, 8); // initiator filter

  cmd.writeUInt8(addressType === 'random' ? 0x01 : 0x00, 9); // peer address type
  (new Buffer(address.split(':').reverse().join(''), 'hex')).copy(cmd, 10); // peer address

  cmd.writeUInt8(0x00, 16); // own address type

  cmd.writeUInt16LE(0x0006, 17); // min interval
  cmd.writeUInt16LE(0x000c, 19); // max interval
  cmd.writeUInt16LE(0x0000, 21); // latency
  cmd.writeUInt16LE(0x00c8, 23); // supervision timeout
  cmd.writeUInt16LE(0x0004, 25); // min ce length
  cmd.writeUInt16LE(0x0006, 27); // max ce length

  debug('create le conn - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.startLeEncryption = function(handle, random, diversifier, key) {
  var cmd = new Buffer(32);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(LE_START_ENCRYPTION_CMD, 1);

  // length
  cmd.writeUInt8(0x1c, 3);

  // data
  cmd.writeUInt16LE(handle, 4); // handle
  random.copy(cmd, 6);
  diversifier.copy(cmd, 14);
  key.copy(cmd, 16);

  debug('start le encryption - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.disconnect = function(handle, reason) {
  var cmd = new Buffer(7);

  reason = reason || HCI_OE_USER_ENDED_CONNECTION;

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(DISCONNECT_CMD, 1);

  // length
  cmd.writeUInt8(0x03, 3);

  // data
  cmd.writeUInt16LE(handle, 4); // handle
  cmd.writeUInt8(reason, 6); // reason

  debug('disconnect - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.readRssi = function(handle) {
  var cmd = new Buffer(6);

  // header
  cmd.writeUInt8(HCI_COMMAND_PKT, 0);
  cmd.writeUInt16LE(READ_RSSI_CMD, 1);

  // length
  cmd.writeUInt8(0x02, 3);

  // data
  cmd.writeUInt16LE(handle, 4); // handle

  debug('read rssi - writing: ' + cmd.toString('hex'));
  this._socket.write(cmd);
};

Hci.prototype.writeAclDataPkt = function(handle, cid, data) {
  var pkt = new Buffer(9 + data.length);

  // header
  pkt.writeUInt8(HCI_ACLDATA_PKT, 0);
  pkt.writeUInt16LE(handle | ACL_START_NO_FLUSH << 12, 1);
  pkt.writeUInt16LE(data.length + 4, 3); // data length 1
  pkt.writeUInt16LE(data.length, 5); // data length 2
  pkt.writeUInt16LE(cid, 7);

  data.copy(pkt, 9);

  debug('write acl data pkt - writing: ' + pkt.toString('hex'));
  this._socket.write(pkt);
};

Hci.prototype.debugPacketType = function(type) {
  switch(type) {
    case ATT_OP_ERROR:
      debug('\t\ttype = ATT_OP_ERROR: ');
      break;

    case ATT_OP_MTU_REQ:
      debug('\t\ttype = ATT_OP_MTU_REQ: ');
      break;

    case ATT_OP_FIND_INFO_REQ:
      debug('\t\ttype = ATT_OP_FIND_INFO_REQ: ');
      break;

    case ATT_OP_FIND_BY_TYPE_REQ:
      debug('\t\ttype = ATT_OP_FIND_BY_TYPE_REQ: ');
      break;

    case ATT_OP_READ_BY_TYPE_REQ:
      debug('\t\ttype = ATT_OP_READ_BY_TYPE_REQ:');
      break;

    case ATT_OP_READ_REQ:
    case ATT_OP_READ_BLOB_REQ:
      debug('\t\ttype = ATT_OP_READ_REQ: ');
      break;

    case ATT_OP_READ_BY_GROUP_REQ:
      debug('\t\ttype = ATT_OP_READ_BY_GROUP_REQ: ');
      break;

    case ATT_OP_WRITE_REQ:
    case ATT_OP_WRITE_CMD:
      debug('\t\ttype = ATT_OP_WRITE_REQ: ');
      break;

    case ATT_OP_HANDLE_CNF:
      debug('\t\ttype = ATT_OP_HANDLE_CNF: ');
      break;
    case ATT_OP_ERROR:
      debug('\t\ttype = ATT_OP_ERROR: ' );

      break;
    case ATT_OP_READ_BY_TYPE_RESP:
      debug('\t\ttype = ATT_OP_READ_BY_TYPE_RESP: ' );
      break;
    case ATT_OP_READ_BY_GROUP_RESP:
      debug('\t\ttype = ATT_OP_READ_BY_GROUP_RESP: ' );
      break;
    case ATT_OP_HANDLE_NOTIFY:
    case ATT_OP_HANDLE_IND:
      debug('\t\ttype = ATT_OP_HANDLE_NOTIFY: ' );

    default:
    case ATT_OP_READ_MULTI_REQ:
    case ATT_OP_PREP_WRITE_REQ:
    case ATT_OP_EXEC_WRITE_REQ:
    case ATT_OP_SIGNED_WRITE_CMD:
      debug('\t\ttype =  Unhandled: ' );
      break;
  }
};
Hci.prototype.onSocketData = function(data) {

  var eventType = data.readUInt8(0);
  var handle;

  debug('onSocketData: ' + data.toString('hex') + '\tevent type = ' + eventType);

  if (HCI_EVENT_PKT === eventType) {
    var subEventType = data.readUInt8(1);

    debug('\tsub event type = ' + subEventType);

    if (subEventType === EVT_DISCONN_COMPLETE) {
      handle =  data.readUInt16LE(4);
      var reason = data.readUInt8(6);

      debug('\t\tEVT_DISCONN_COMPLETE');
      debug('\t\thandle = ' + handle);
      debug('\t\treason = ' + reason);
      debug('emitting disconnComplete');
      this.emit('disconnComplete', handle, reason);
    } else if (subEventType === EVT_ENCRYPT_CHANGE) {
      handle =  data.readUInt16LE(4);
      var encrypt = data.readUInt8(6);

      debug('\t\tEVT_ENCRYPT_CHANGE');
      debug('\t\thandle = ' + handle);
      debug('\t\tencrypt = ' + encrypt);

      this.emit('encryptChange', handle, encrypt);
    } else if (subEventType === EVT_CMD_COMPLETE) {
      var cmd = data.readUInt16LE(4);
      var status = data.readUInt8(6);
      var result = data.slice(7);

      debug('\t\tEVT_CMD_COMPLETE');
      debug('\t\tcmd = ' + cmd);
      debug('\t\tstatus = ' + status);
      debug('\t\tresult = ' + result.toString('hex'));

      this.processCmdCompleteEvent(cmd, status, result);
    } else if (subEventType === EVT_LE_META_EVENT) {
      var leMetaEventType = data.readUInt8(3);
      var leMetaEventStatus = data.readUInt8(4);
      var leMetaEventData = data.slice(5);

      debug('\t\tEVT_LE_META_EVENT');
      debug('\t\tLE meta event type = ' + leMetaEventType);
      debug('\t\tLE meta event status = ' + leMetaEventStatus);
      debug('\t\tLE meta event data = ' + leMetaEventData.toString('hex'));

      this.processLeMetaEvent(leMetaEventType, leMetaEventStatus, leMetaEventData);
    } else {
      debug('\t\tUnknown Command');
    }
  } else if (HCI_ACLDATA_PKT === eventType) {
    var flags = data.readUInt16LE(1) >> 12;
    handle = data.readUInt16LE(1) & 0x0fff;

    if (ACL_START === flags) {
      var cid = data.readUInt16LE(7);

      var length = data.readUInt16LE(5);
      var pktData = data.slice(9);

      debug('\t\tHCI_ACLDATA_PKT - ACL_START');
      debug('\t\tcid = ' + cid);
      this.debugPacketType(pktData[0]);
      if (length === pktData.length) {
        debug('\t\thandle = ' + handle);
        debug('\t\tdata = ' + pktData.toString('hex'));

        this.emit('aclDataPkt', handle, cid, pktData);
      } else {
        this._handleBuffers[handle] = {
          length: length,
          cid: cid,
          data: pktData
        };
      }
    } /*else if (ACL_START_NO_FLUSH === flags) {
      var cid = data.readUInt16LE(7);

      var length = data.readUInt16LE(5);
      var pktData = data.slice(9);

      debug('\t\tHCI_ACLDATA_PKT - ACL_START_NO_FLUSH');
      debug('\t\tcid = ' + cid);
      this.debugPacketType(pktData[0]);
      if (length === pktData.length) {
        debug('\t\thandle = ' + handle);
        debug('\t\tdata = ' + pktData.toString('hex'));

        this.emit('aclDataPkt', handle, cid, pktData);
      } else {
        this._handleBuffers[handle] = {
          length: length,
          cid: cid,
          data: pktData
        };
      }

    } */else if (ACL_CONT === flags) {
      debug('\t\tHCI_ACLDATA_PKT - ACL_CONT');
      if (!this._handleBuffers[handle] || !this._handleBuffers[handle].data) {
        debug('!\tUnable to find previous packets');
        return;
      }

      this._handleBuffers[handle].data = Buffer.concat([
        this._handleBuffers[handle].data,
        data.slice(5)
      ]);

      if (this._handleBuffers[handle].data.length === this._handleBuffers[handle].length) {
        debug('\t\tCOMPLETE');
        this.emit('aclDataPkt', handle, this._handleBuffers[handle].cid, this._handleBuffers[handle].data);
        delete this._handleBuffers[handle];
      }
    } else {
      debug('\t\tUnknown Flags for HCI_ACLDATA_PKT: ' + flags)
    }
  } else {
    debug('!\tPacket unhandled');
  }
};

Hci.prototype.onSocketError = function(error) {
  debug('onSocketError: ' + error.message);

  if (error.message === 'Operation not permitted') {
    this.emit('stateChange', 'unauthorized');
  } else if (error.message === 'Network is down') {
    // no-op
  }
};

Hci.prototype.processCmdCompleteEvent = function(cmd, status, result) {
  var handle;

  if (cmd === READ_LOCAL_VERSION_CMD) {
    var hciVer = result.readUInt8(0);
    var hciRev = result.readUInt16LE(1);
    var lmpVer = result.readInt8(3);
    var manufacturer = result.readUInt16LE(4);
    var lmpSubVer = result.readUInt16LE(6);

    if (hciVer < 0x06) {
      this.emit('stateChange', 'unsupported');
    } else {
      this.setScanEnabled(false, true);
      this.setScanParameters();
    }
    debug('\t\tREAD_LOCAL_VERSION_CMD');
    this.emit('readLocalVersion', hciVer, hciRev, lmpVer, manufacturer, lmpSubVer);
  } else if (cmd === READ_BD_ADDR_CMD) {
    this.addressType = 'public';
    this.address = result.toString('hex').match(/.{1,2}/g).reverse().join(':');

    debug('\t\tREAD_BD_ADDR_CMD');
    this.emit('addressChange', this.address);
  } else if (cmd === LE_SET_ADVERTISING_PARAMETERS_CMD) {
    this.emit('stateChange', 'poweredOn');

    debug('\t\tLE_SET_ADVERTISING_PARAMETERS_CMD');
    this.emit('leAdvertisingParametersSet', status);
  } else if (cmd === LE_SET_SCAN_PARAMETERS_CMD) {
    this.emit('stateChange', 'poweredOn');

    debug('\t\tLE_SET_SCAN_PARAMETERS_CMD');
    this.emit('leScanParametersSet');
  } else if (cmd === LE_SET_SCAN_ENABLE_CMD) {
    debug('\t\tLE_SET_SCAN_ENABLE_CMD');
    this.emit('leScanEnableSet');
  } else if (cmd === LE_SET_ADVERTISING_DATA_CMD) {
    debug('\t\tLE_SET_ADVERTISING_DATA_CMD');
    this.emit('leAdvertisingDataSet', status);
  } else if (cmd === LE_SET_SCAN_RESPONSE_DATA_CMD) {
    debug('\t\tLE_SET_SCAN_RESPONSE_DATA_CMD');
    this.emit('leScanResponseDataSet', status);
  } else if (cmd === LE_SET_ADVERTISE_ENABLE_CMD) {
    debug('\t\tLE_SET_ADVERTISE_ENABLE_CMD');
    this.emit('leAdvertiseEnableSet', status);
  } else if (cmd === READ_RSSI_CMD) {
    handle = result.readUInt16LE(0);
    var rssi = result.readInt8(2);
    debug('\t\tREAD_RSSI_CMD');
    debug('\t\t\thandle = ' + handle);
    debug('\t\t\trssi = ' + rssi);

    this.emit('rssiRead', handle, rssi);
  } else if (cmd === LE_LTK_NEG_REPLY_CMD) {
    handle = result.readUInt16LE(0);
    debug('\t\tLE_LTK_NEG_REPLY_CMD');
    debug('\t\t\thandle = ' + handle);
    this.emit('leLtkNegReply', handle);
  } else {
    debug('!\tUnhandled Command');
  }
};

Hci.prototype.processLeMetaEvent = function(eventType, status, data) {
  if (eventType === EVT_LE_CONN_COMPLETE) {
    this.processLeConnComplete(status, data);
  } else if (eventType === EVT_LE_ADVERTISING_REPORT) {
    this.processLeAdvertisingReport(status, data);
  } else if (eventType === EVT_LE_CONN_UPDATE_COMPLETE) {
    this.processLeConnUpdateComplete(status, data);
  }
};

Hci.prototype.processLeConnComplete = function(status, data) {
  var handle = data.readUInt16LE(0);
  var role = data.readUInt8(2);
  var addressType = data.readUInt8(3) === 0x01 ? 'random': 'public';
  var address = data.slice(4, 10).toString('hex').match(/.{1,2}/g).reverse().join(':');
  var interval = data.readUInt16LE(10) * 1.25;
  var latency = data.readUInt16LE(12); // TODO: multiplier?
  var supervisionTimeout = data.readUInt16LE(14) * 10;
  var masterClockAccuracy = data.readUInt8(15); // TODO: multiplier?

  debug('\t\t\thandle = ' + handle);
  debug('\t\t\trole = ' + role);
  debug('\t\t\taddress type = ' + addressType);
  debug('\t\t\taddress = ' + address);
  debug('\t\t\tinterval = ' + interval);
  debug('\t\t\tlatency = ' + latency);
  debug('\t\t\tsupervision timeout = ' + supervisionTimeout);
  debug('\t\t\tmaster clock accuracy = ' + masterClockAccuracy);

  this.emit('leConnComplete', status, handle, role, addressType, address, interval, latency, supervisionTimeout, masterClockAccuracy);
};

Hci.prototype.processLeAdvertisingReport = function(status, data) {
  var type = data.readUInt8(0); // ignore for now
  var addressType = data.readUInt8(1) === 0x01 ? 'random' : 'public';
  var address = data.slice(2, 8).toString('hex').match(/.{1,2}/g).reverse().join(':');
  var eir = data.slice(9, data.length - 1);
  var rssi = data.readInt8(data.length - 1);

  debug('\t\t\ttype = ' + type);
  debug('\t\t\taddress = ' + address);
  debug('\t\t\taddress type = ' + addressType);
  debug('\t\t\teir = ' + eir.toString('hex'));
  debug('\t\t\trssi = ' + rssi);

  this.emit('leAdvertisingReport', status, type, address, addressType, eir, rssi);
};

Hci.prototype.processLeConnUpdateComplete = function(status, data) {
  var handle = data.readUInt16LE(0);
  var interval = data.readUInt16LE(2) * 1.25;
  var latency = data.readUInt16LE(4); // TODO: multiplier?
  var supervisionTimeout = data.readUInt16LE(6) * 10;

  debug('\t\t\thandle = ' + handle);
  debug('\t\t\tinterval = ' + interval);
  debug('\t\t\tlatency = ' + latency);
  debug('\t\t\tsupervision timeout = ' + supervisionTimeout);

  this.emit('leConnUpdateComplete', status, handle, interval, latency, supervisionTimeout);
};

module.exports = Hci;


text:
#ifndef WebAudioBus_h
#define WebAudioBus_h

#include "WebCommon.h"

#if INSIDE_BLINK
namespace WTF {
template <typename T>
class PassRefPtr;
}
#endif

namespace blink {

class AudioBus;

// A container for multi-channel linear PCM audio data.
//
// WARNING: It is not safe to pass a WebAudioBus across threads!!!
//
class BLINK_PLATFORM_EXPORT WebAudioBus {
 public:
  WebAudioBus() : m_private(0) {}
  ~WebAudioBus() { reset(); }

  // initialize() allocates memory of the given length for the given number of
  // channels.
  void initialize(unsigned numberOfChannels, size_t length, double sampleRate);

  // resizeSmaller() can only be called after initialize() with a new length <=
  // the initialization length.  The data stored in the bus will remain
  // undisturbed.
  void resizeSmaller(size_t newLength);

  // reset() releases the memory allocated from initialize().
  void reset();

  unsigned numberOfChannels() const;
  size_t length() const;
  double sampleRate() const;

  float* channelData(unsigned channelIndex);

#if INSIDE_BLINK
  WTF::PassRefPtr<AudioBus> release();
#endif

 private:
  // Disallow copy and assign.
  WebAudioBus(const WebAudioBus&);
  void operator=(const WebAudioBus&);

  AudioBus* m_private;
};

}  // namespace blink

#endif  // WebAudioBus_h


text:
=============
PhotoDirector
=============

`CyberLink PhotoDirector <https://www.cyberlink.com/products/photodirector-ultra/features_en_US.html>`_ is the program I use to manage my photo collection.

I do have my photos indexed in :doc:`Plex <../serve/plex>` for easy viewing, but for general management, tagging, etc., I'm using PhotoDirector. I picked this up after Google dropped support for :doc:`Picasa <../deprecated/picasa>`.

From a general photo management standpoint the software works really well, however, I have found no end of trouble with the face tagging feature. The more face tags you have, the slower the tagging feature works to detect new faces. Also I have lost my face tag data twice now over software upgrades. As such, I've stopped doing face tagging.

In the future I'm considering looking at one of these server-based self-hosted packages:

* `PhotoStructure <https://photostructure.com/>`_
* `Piwigo <https://piwigo.org/>`_
* `Lychee <https://lychee.electerious.com/>`_


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        src/common/anidecod.cpp
// Purpose:     wxANIDecoder, ANI reader for wxImage and wxAnimation
// Author:      Francesco Montorsi
// RCS-ID:      $Id$
// Copyright:   (c) Francesco Montorsi
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_STREAMS && wxUSE_ICO_CUR

#include "wx/anidecod.h"

#ifndef WX_PRECOMP
    #include "wx/palette.h"
#endif

#include <stdlib.h>
#include <string.h>

// static
wxCURHandler wxANIDecoder::sm_handler;

//---------------------------------------------------------------------------
// wxANIFrameInfo
//---------------------------------------------------------------------------

class wxANIFrameInfo
{
public:
    wxANIFrameInfo(unsigned int delay = 0, int idx = -1)
        { m_delay=delay; m_imageIndex=idx; }

    unsigned int m_delay;
    int m_imageIndex;
};

#include "wx/arrimpl.cpp" // this is a magic incantation which must be done!
WX_DEFINE_OBJARRAY(wxImageArray)

#include "wx/arrimpl.cpp" // this is a magic incantation which must be done!
WX_DEFINE_OBJARRAY(wxANIFrameInfoArray)

//---------------------------------------------------------------------------
// wxANIDecoder
//---------------------------------------------------------------------------

wxANIDecoder::wxANIDecoder()
{
}

wxANIDecoder::~wxANIDecoder()
{
}

bool wxANIDecoder::ConvertToImage(unsigned int frame, wxImage *image) const
{
    unsigned int idx = m_info[frame].m_imageIndex;
    *image = m_images[idx];       // copy
    return image->IsOk();
}

//---------------------------------------------------------------------------
// Data accessors
//---------------------------------------------------------------------------

wxSize wxANIDecoder::GetFrameSize(unsigned int WXUNUSED(frame)) const
{
    // all frames are of the same size...
    return m_szAnimation;
}

wxPoint wxANIDecoder::GetFramePosition(unsigned int WXUNUSED(frame)) const
{
    // all frames are of the same size...
    return wxPoint(0,0);
}

wxAnimationDisposal wxANIDecoder::GetDisposalMethod(unsigned int WXUNUSED(frame)) const
{
    // this disposal is implicit for all frames inside an ANI file
    return wxANIM_TOBACKGROUND;
}

long wxANIDecoder::GetDelay(unsigned int frame) const
{
    return m_info[frame].m_delay;
}

wxColour wxANIDecoder::GetTransparentColour(unsigned int frame) const
{
    unsigned int idx = m_info[frame].m_imageIndex;

    if (!m_images[idx].HasMask())
        return wxNullColour;

    return wxColour(m_images[idx].GetMaskRed(),
                    m_images[idx].GetMaskGreen(),
                    m_images[idx].GetMaskBlue());
}

//---------------------------------------------------------------------------
// ANI reading and decoding
//---------------------------------------------------------------------------

bool wxANIDecoder::DoCanRead(wxInputStream& stream) const
{
    wxInt32 FCC1, FCC2;
    wxUint32 datalen;

    wxInt32 riff32;
    memcpy( &riff32, "RIFF", 4 );
    wxInt32 list32;
    memcpy( &list32, "LIST", 4 );
    wxInt32 ico32;
    memcpy( &ico32, "icon", 4 );
    wxInt32 anih32;
    memcpy( &anih32, "anih", 4 );

    if ( !stream.Read(&FCC1, 4) )
        return false;

    if ( FCC1 != riff32 )
        return false;

    // we have a riff file:
    while ( stream.IsOk() )
    {
        if ( FCC1 == anih32 )
            return true;        // found the ANIH chunk - this should be an ANI file

        // we always have a data size:
        stream.Read(&datalen, 4);
        datalen = wxINT32_SWAP_ON_BE(datalen) ;

        // data should be padded to make even number of bytes
        if (datalen % 2 == 1) datalen ++ ;

        // now either data or a FCC:
        if ( (FCC1 == riff32) || (FCC1 == list32) )
        {
            stream.Read(&FCC2, 4);
        }
        else
        {
            if ( stream.SeekI(stream.TellI() + datalen) == wxInvalidOffset )
                return false;
        }

        // try to read next data chunk:
        if ( !stream.Read(&FCC1, 4) )
        {
            // reading failed -- either EOF or IO error, bail out anyhow
            return false;
        }
    }

    return false;
}

// the "anih" RIFF chunk
struct wxANIHeader
{
    wxInt32 cbSizeOf;     // Num bytes in AniHeader (36 bytes)
    wxInt32 cFrames;      // Number of unique Icons in this cursor
    wxInt32 cSteps;       // Number of Blits before the animation cycles
    wxInt32 cx;           // width of the frames
    wxInt32 cy;           // height of the frames
    wxInt32 cBitCount;    // bit depth
    wxInt32 cPlanes;      // 1
    wxInt32 JifRate;      // Default Jiffies (1/60th of a second) if rate chunk not present.
    wxInt32 flags;        // Animation Flag (see AF_ constants)

    // ANI files are always little endian so we need to swap bytes on big
    // endian architectures
#ifdef WORDS_BIGENDIAN
    void AdjustEndianness()
    {
        // this works because all our fields are wxInt32 and they must be
        // packed without holes between them (if they're not, they wouldn't map
        // to the file header!)
        wxInt32 * const start = (wxInt32 *)this;
        wxInt32 * const end = start + sizeof(wxANIHeader)/sizeof(wxInt32);
        for ( wxInt32 *p = start; p != end; p++ )
        {
            *p = wxINT32_SWAP_ALWAYS(*p);
        }
    }
#else
    void AdjustEndianness() { }
#endif
};

bool wxANIDecoder::Load( wxInputStream& stream )
{
    wxInt32 FCC1, FCC2;
    wxUint32 datalen;
    unsigned int globaldelay=0;

    wxInt32 riff32;
    memcpy( &riff32, "RIFF", 4 );
    wxInt32 list32;
    memcpy( &list32, "LIST", 4 );
    wxInt32 ico32;
    memcpy( &ico32, "icon", 4 );
    wxInt32 anih32;
    memcpy( &anih32, "anih", 4 );
    wxInt32 rate32;
    memcpy( &rate32, "rate", 4 );
    wxInt32 seq32;
    memcpy( &seq32, "seq ", 4 );

    if ( !stream.Read(&FCC1, 4) )
        return false;
    if ( FCC1 != riff32 )
        return false;

    m_nFrames = 0;
    m_szAnimation = wxDefaultSize;

    m_images.Clear();
    m_info.Clear();

    // we have a riff file:
    while ( !stream.Eof() )
    {
        // we always have a data size:
        if (!stream.Read(&datalen, 4))
            return false;

        datalen = wxINT32_SWAP_ON_BE(datalen);

        //data should be padded to make even number of bytes
        if (datalen % 2 == 1) datalen++;

        // now either data or a FCC:
        if ( (FCC1 == riff32) || (FCC1 == list32) )
        {
            if (!stream.Read(&FCC2, 4))
                return false;
        }
        else if ( FCC1 == anih32 )
        {
            if ( datalen != sizeof(wxANIHeader) )
                return false;

            if (m_nFrames > 0)
                return false;       // already parsed an ani header?

            struct wxANIHeader header;
            if (!stream.Read(&header, sizeof(wxANIHeader)))
                return false;
            header.AdjustEndianness();

            // we should have a global frame size
            m_szAnimation = wxSize(header.cx, header.cy);

            // save interesting info from the header
            m_nFrames = header.cSteps;   // NB: not cFrames!!
            if ( m_nFrames == 0 )
                return false;

            globaldelay = header.JifRate * 1000 / 60;

            m_images.Alloc(header.cFrames);
            m_info.Add(wxANIFrameInfo(), m_nFrames);
        }
        else if ( FCC1 == rate32 )
        {
            // did we already process the anih32 chunk?
            if (m_nFrames == 0)
                return false;       // rate chunks should always be placed after anih chunk

            wxASSERT(m_info.GetCount() == m_nFrames);
            for (unsigned int i=0; i<m_nFrames; i++)
            {
                if (!stream.Read(&FCC2, 4))
                    return false;
                m_info[i].m_delay = wxINT32_SWAP_ON_BE(FCC2) * 1000 / 60;
            }
        }
        else if ( FCC1 == seq32 )
        {
            // did we already process the anih32 chunk?
            if (m_nFrames == 0)
                return false;       // seq chunks should always be placed after anih chunk

            wxASSERT(m_info.GetCount() == m_nFrames);
            for (unsigned int i=0; i<m_nFrames; i++)
            {
                if (!stream.Read(&FCC2, 4))
                    return false;
                m_info[i].m_imageIndex = wxINT32_SWAP_ON_BE(FCC2);
            }
        }
        else if ( FCC1 == ico32 )
        {
            // use DoLoadFile() and not LoadFile()!
            wxImage image;
            if (!sm_handler.DoLoadFile(&image, stream, false /* verbose */, -1))
                return false;

            image.SetType(wxBITMAP_TYPE_ANI);
            m_images.Add(image);
        }
        else
        {
            if ( stream.SeekI(stream.TellI() + datalen) == wxInvalidOffset )
                return false;
        }

        // try to read next data chunk:
        if ( !stream.Read(&FCC1, 4) && !stream.Eof())
        {
            // we didn't reach the EOF! An other kind of error has occurred...
            return false;
        }
        //else: proceed with the parsing of the next header block or
        //      exiting this loop (if stream.Eof() == true)
    }

    if (m_nFrames==0)
        return false;

    if (m_nFrames==m_images.GetCount())
    {
        // if no SEQ chunk is available, display the frames in the order
        // they were loaded
        for (unsigned int i=0; i<m_nFrames; i++)
            if (m_info[i].m_imageIndex == -1)
                m_info[i].m_imageIndex = i;
    }

    // if some frame has an invalid delay, use the global delay given in the
    // ANI header
    for (unsigned int i=0; i<m_nFrames; i++)
        if (m_info[i].m_delay == 0)
            m_info[i].m_delay = globaldelay;

    // if the header did not contain a valid frame size, try to grab
    // it from the size of the first frame (all frames are of the same size)
    if (m_szAnimation.GetWidth() == 0 ||
        m_szAnimation.GetHeight() == 0)
        m_szAnimation = wxSize(m_images[0].GetWidth(), m_images[0].GetHeight());

    return m_szAnimation != wxDefaultSize;
}

#endif // wxUSE_STREAMS && wxUSE_ICO_CUR


text:
"""Command line interface to aclcheck library."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

__author__ = 'watson@google.com (Tony Watson)'

from optparse import OptionParser

from lib import aclcheck
from lib import naming
from lib import policy

def main():
  # TODO(robankeny): Lets move this to gflags
  usage = 'usage: %prog [options] arg'
  _parser = OptionParser(usage)
  _parser.add_option('--definitions-directory', dest='definitions',
                     help='definitions directory', default='./def')
  _parser.add_option('-p', '--policy-file', dest='pol',
                     help='policy file', default='./policies/sample.pol')
  _parser.add_option('-d', '--destination', dest='dst',
                     help='destination IP', default='200.1.1.1')
  _parser.add_option('-s', '--source', dest='src',
                     help='source IP', default='any')
  _parser.add_option('--proto', '--protocol', dest='proto',
                     help='Protocol (tcp, udp, icmp, etc.)', default='tcp')
  _parser.add_option('--dport', '--destination-port', dest='dport',
                     help='destination port', default='80')
  _parser.add_option('--sport', '--source-port', dest='sport',
                     help='source port', default='1025')
  (FLAGS, unused_args) = _parser.parse_args()

  defs = naming.Naming(FLAGS.definitions)
  policy_obj = policy.ParsePolicy(open(FLAGS.pol).read(), defs)
  check = aclcheck.AclCheck(policy_obj, src=FLAGS.src, dst=FLAGS.dst,
                            sport=FLAGS.sport, dport=FLAGS.dport,
                            proto=FLAGS.proto)
  print(str(check))

if __name__ == '__main__':
  main()


text:
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width">
  <meta charset="UTF-8">

  <link href="css/main.css" rel="stylesheet" type="text/css"></link>
  <link href="css/simple-sidebar.css" rel="stylesheet" type="text/css"></link>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

          Destinations

      <form class="query-container">
        <input type="text" data-bind="textInput: query" name="query" placeholder="Filter">
      </form>

The Neighborhood of Kaimuki, Honolulu

    Menu