text:
package io.atomix.protocols.raft.test.protocol;

import com.google.common.collect.Maps;
import io.atomix.cluster.MemberId;
import io.atomix.primitive.session.SessionId;
import io.atomix.protocols.raft.protocol.AppendRequest;
import io.atomix.protocols.raft.protocol.AppendResponse;
import io.atomix.protocols.raft.protocol.CloseSessionRequest;
import io.atomix.protocols.raft.protocol.CloseSessionResponse;
import io.atomix.protocols.raft.protocol.CommandRequest;
import io.atomix.protocols.raft.protocol.CommandResponse;
import io.atomix.protocols.raft.protocol.ConfigureRequest;
import io.atomix.protocols.raft.protocol.ConfigureResponse;
import io.atomix.protocols.raft.protocol.HeartbeatRequest;
import io.atomix.protocols.raft.protocol.HeartbeatResponse;
import io.atomix.protocols.raft.protocol.InstallRequest;
import io.atomix.protocols.raft.protocol.InstallResponse;
import io.atomix.protocols.raft.protocol.JoinRequest;
import io.atomix.protocols.raft.protocol.JoinResponse;
import io.atomix.protocols.raft.protocol.KeepAliveRequest;
import io.atomix.protocols.raft.protocol.KeepAliveResponse;
import io.atomix.protocols.raft.protocol.LeaveRequest;
import io.atomix.protocols.raft.protocol.LeaveResponse;
import io.atomix.protocols.raft.protocol.MetadataRequest;
import io.atomix.protocols.raft.protocol.MetadataResponse;
import io.atomix.protocols.raft.protocol.OpenSessionRequest;
import io.atomix.protocols.raft.protocol.OpenSessionResponse;
import io.atomix.protocols.raft.protocol.PollRequest;
import io.atomix.protocols.raft.protocol.PollResponse;
import io.atomix.protocols.raft.protocol.PublishRequest;
import io.atomix.protocols.raft.protocol.QueryRequest;
import io.atomix.protocols.raft.protocol.QueryResponse;
import io.atomix.protocols.raft.protocol.RaftServerProtocol;
import io.atomix.protocols.raft.protocol.ReconfigureRequest;
import io.atomix.protocols.raft.protocol.ReconfigureResponse;
import io.atomix.protocols.raft.protocol.ResetRequest;
import io.atomix.protocols.raft.protocol.TransferRequest;
import io.atomix.protocols.raft.protocol.TransferResponse;
import io.atomix.protocols.raft.protocol.VoteRequest;
import io.atomix.protocols.raft.protocol.VoteResponse;
import io.atomix.utils.serializer.Serializer;
import io.atomix.utils.concurrent.Futures;

import java.net.ConnectException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * Test server protocol.
 */
public class LocalRaftServerProtocol extends LocalRaftProtocol implements RaftServerProtocol {
  private Function<OpenSessionRequest, CompletableFuture<OpenSessionResponse>> openSessionHandler;
  private Function<CloseSessionRequest, CompletableFuture<CloseSessionResponse>> closeSessionHandler;
  private Function<KeepAliveRequest, CompletableFuture<KeepAliveResponse>> keepAliveHandler;
  private Function<QueryRequest, CompletableFuture<QueryResponse>> queryHandler;
  private Function<CommandRequest, CompletableFuture<CommandResponse>> commandHandler;
  private Function<MetadataRequest, CompletableFuture<MetadataResponse>> metadataHandler;
  private Function<JoinRequest, CompletableFuture<JoinResponse>> joinHandler;
  private Function<LeaveRequest, CompletableFuture<LeaveResponse>> leaveHandler;
  private Function<ConfigureRequest, CompletableFuture<ConfigureResponse>> configureHandler;
  private Function<ReconfigureRequest, CompletableFuture<ReconfigureResponse>> reconfigureHandler;
  private Function<InstallRequest, CompletableFuture<InstallResponse>> installHandler;
  private Function<PollRequest, CompletableFuture<PollResponse>> pollHandler;
  private Function<VoteRequest, CompletableFuture<VoteResponse>> voteHandler;
  private Function<TransferRequest, CompletableFuture<TransferResponse>> transferHandler;
  private Function<AppendRequest, CompletableFuture<AppendResponse>> appendHandler;
  private final Map<Long, Consumer<ResetRequest>> resetListeners = Maps.newConcurrentMap();

  public LocalRaftServerProtocol(MemberId memberId, Serializer serializer, Map<MemberId, LocalRaftServerProtocol> servers, Map<MemberId, LocalRaftClientProtocol> clients) {
    super(serializer, servers, clients);
    servers.put(memberId, this);
  }

  private CompletableFuture<LocalRaftServerProtocol> getServer(MemberId memberId) {
    LocalRaftServerProtocol server = server(memberId);
    if (server != null) {
      return Futures.completedFuture(server);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  private CompletableFuture<LocalRaftClientProtocol> getClient(MemberId memberId) {
    LocalRaftClientProtocol client = client(memberId);
    if (client != null) {
      return Futures.completedFuture(client);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public CompletableFuture<OpenSessionResponse> openSession(MemberId memberId, OpenSessionRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.openSession(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<CloseSessionResponse> closeSession(MemberId memberId, CloseSessionRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.closeSession(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<KeepAliveResponse> keepAlive(MemberId memberId, KeepAliveRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.keepAlive(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<QueryResponse> query(MemberId memberId, QueryRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.query(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<CommandResponse> command(MemberId memberId, CommandRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.command(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<MetadataResponse> metadata(MemberId memberId, MetadataRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.metadata(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<JoinResponse> join(MemberId memberId, JoinRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.join(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<LeaveResponse> leave(MemberId memberId, LeaveRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.leave(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<ConfigureResponse> configure(MemberId memberId, ConfigureRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.configure(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<ReconfigureResponse> reconfigure(MemberId memberId, ReconfigureRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.reconfigure(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<InstallResponse> install(MemberId memberId, InstallRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.install(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<TransferResponse> transfer(MemberId memberId, TransferRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.install(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<PollResponse> poll(MemberId memberId, PollRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.poll(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<VoteResponse> vote(MemberId memberId, VoteRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.vote(encode(request))).thenApply(this::decode);
  }

  @Override
  public CompletableFuture<AppendResponse> append(MemberId memberId, AppendRequest request) {
    return getServer(memberId).thenCompose(listener -> listener.append(encode(request))).thenApply(this::decode);
  }

  @Override
  public void publish(MemberId memberId, PublishRequest request) {
    getClient(memberId).thenAccept(protocol -> protocol.publish(request.session(), encode(request)));
  }

  @Override
  public CompletableFuture<HeartbeatResponse> heartbeat(MemberId memberId, HeartbeatRequest request) {
    return getClient(memberId).thenCompose(protocol -> protocol.heartbeat(encode(request))).thenApply(this::decode);
  }

  CompletableFuture<byte[]> openSession(byte[] request) {
    if (openSessionHandler != null) {
      return openSessionHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerOpenSessionHandler(Function<OpenSessionRequest, CompletableFuture<OpenSessionResponse>> handler) {
    this.openSessionHandler = handler;
  }

  @Override
  public void unregisterOpenSessionHandler() {
    this.openSessionHandler = null;
  }

  CompletableFuture<byte[]> closeSession(byte[] request) {
    if (closeSessionHandler != null) {
      return closeSessionHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerCloseSessionHandler(Function<CloseSessionRequest, CompletableFuture<CloseSessionResponse>> handler) {
    this.closeSessionHandler = handler;
  }

  @Override
  public void unregisterCloseSessionHandler() {
    this.closeSessionHandler = null;
  }

  CompletableFuture<byte[]> keepAlive(byte[] request) {
    if (keepAliveHandler != null) {
      return keepAliveHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerKeepAliveHandler(Function<KeepAliveRequest, CompletableFuture<KeepAliveResponse>> handler) {
    this.keepAliveHandler = handler;
  }

  @Override
  public void unregisterKeepAliveHandler() {
    this.keepAliveHandler = null;
  }

  CompletableFuture<byte[]> query(byte[] request) {
    if (queryHandler != null) {
      return queryHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerQueryHandler(Function<QueryRequest, CompletableFuture<QueryResponse>> handler) {
    this.queryHandler = handler;
  }

  @Override
  public void unregisterQueryHandler() {
    this.queryHandler = null;
  }

  CompletableFuture<byte[]> command(byte[] request) {
    if (commandHandler != null) {
      return commandHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerCommandHandler(Function<CommandRequest, CompletableFuture<CommandResponse>> handler) {
    this.commandHandler = handler;
  }

  @Override
  public void unregisterCommandHandler() {
    this.commandHandler = null;
  }

  CompletableFuture<byte[]> metadata(byte[] request) {
    if (metadataHandler != null) {
      return metadataHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerMetadataHandler(Function<MetadataRequest, CompletableFuture<MetadataResponse>> handler) {
    this.metadataHandler = handler;
  }

  @Override
  public void unregisterMetadataHandler() {
    this.metadataHandler = null;
  }

  CompletableFuture<byte[]> join(byte[] request) {
    if (joinHandler != null) {
      return joinHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerJoinHandler(Function<JoinRequest, CompletableFuture<JoinResponse>> handler) {
    this.joinHandler = handler;
  }

  @Override
  public void unregisterJoinHandler() {
    this.joinHandler = null;
  }

  CompletableFuture<byte[]> leave(byte[] request) {
    if (leaveHandler != null) {
      return leaveHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerLeaveHandler(Function<LeaveRequest, CompletableFuture<LeaveResponse>> handler) {
    this.leaveHandler = handler;
  }

  @Override
  public void unregisterLeaveHandler() {
    this.leaveHandler = null;
  }

  CompletableFuture<byte[]> configure(byte[] request) {
    if (configureHandler != null) {
      return configureHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerConfigureHandler(Function<ConfigureRequest, CompletableFuture<ConfigureResponse>> handler) {
    this.configureHandler = handler;
  }

  @Override
  public void unregisterConfigureHandler() {
    this.configureHandler = null;
  }

  CompletableFuture<byte[]> reconfigure(byte[] request) {
    if (reconfigureHandler != null) {
      return reconfigureHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerReconfigureHandler(Function<ReconfigureRequest, CompletableFuture<ReconfigureResponse>> handler) {
    this.reconfigureHandler = handler;
  }

  @Override
  public void unregisterReconfigureHandler() {
    this.reconfigureHandler = null;
  }

  CompletableFuture<byte[]> install(byte[] request) {
    if (installHandler != null) {
      return installHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerInstallHandler(Function<InstallRequest, CompletableFuture<InstallResponse>> handler) {
    this.installHandler = handler;
  }

  @Override
  public void unregisterInstallHandler() {
    this.installHandler = null;
  }

  CompletableFuture<byte[]> poll(byte[] request) {
    if (pollHandler != null) {
      return pollHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerPollHandler(Function<PollRequest, CompletableFuture<PollResponse>> handler) {
    this.pollHandler = handler;
  }

  @Override
  public void unregisterPollHandler() {
    this.pollHandler = null;
  }

  CompletableFuture<byte[]> vote(byte[] request) {
    if (voteHandler != null) {
      return voteHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerVoteHandler(Function<VoteRequest, CompletableFuture<VoteResponse>> handler) {
    this.voteHandler = handler;
  }

  @Override
  public void unregisterVoteHandler() {
    this.voteHandler = null;
  }

  @Override
  public void registerTransferHandler(Function<TransferRequest, CompletableFuture<TransferResponse>> handler) {
    this.transferHandler = handler;
  }

  @Override
  public void unregisterTransferHandler() {
    this.transferHandler = null;
  }

  CompletableFuture<byte[]> transfer(byte[] request) {
    if (transferHandler != null) {
      return transferHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  CompletableFuture<byte[]> append(byte[] request) {
    if (appendHandler != null) {
      return appendHandler.apply(decode(request)).thenApply(this::encode);
    } else {
      return Futures.exceptionalFuture(new ConnectException());
    }
  }

  @Override
  public void registerAppendHandler(Function<AppendRequest, CompletableFuture<AppendResponse>> handler) {
    this.appendHandler = handler;
  }

  @Override
  public void unregisterAppendHandler() {
    this.appendHandler = null;
  }

  void reset(long sessionId, byte[] request) {
    Consumer<ResetRequest> listener = resetListeners.get(sessionId);
    if (listener != null) {
      listener.accept(decode(request));
    }
  }

  @Override
  public void registerResetListener(SessionId sessionId, Consumer<ResetRequest> listener, Executor executor) {
    resetListeners.put(sessionId.id(), request -> executor.execute(() -> listener.accept(request)));
  }

  @Override
  public void unregisterResetListener(SessionId sessionId) {
    resetListeners.remove(sessionId.id());
  }
}


text:
namespace YAF.Core.Helpers
{
    using System;
    using System.Data;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Xml;
    using YAF.Classes;
    using YAF.Core.Extensions;
    using YAF.Core.Services.Localization;
    using YAF.Types.Extensions;
    using YAF.Types.Interfaces;
    using YAF.Utils;

    /// <summary>
    /// The static data helper.
    /// </summary>
    public class StaticDataHelper
    {
        #region Public Methods

        /// <summary>
        /// The allow disallow.
        /// </summary>
        /// <returns>
        /// Returns a Data Table with allow disallow values.
        /// </returns>
        public static DataTable AllowDisallow()
        {
            using (var dt = new DataTable("AllowDisallow"))
            {
                dt.Columns.Add("Text", typeof(string));
                dt.Columns.Add("Value", typeof(int));

                string[] tTextArray =
                    {
                        YafContext.Current.Get<ILocalization>().GetText("COMMON", "ALLOWED"),
                        YafContext.Current.Get<ILocalization>().GetText("COMMON", "DISALLOWED")
                    };

                for (var i = 0; i < tTextArray.Length; i++)
                {
                    var dr = dt.NewRow();
                    dr["Text"] = tTextArray[i];
                    dr["Value"] = i;
                    dt.Rows.Add(dr);
                }

                return dt;
            }
        }

        /// <summary>
        /// Gets all country names (localized).
        /// </summary>
        /// <param name="localization">
        /// The localization.
        /// </param>
        /// <returns>
        /// Returns a Data Table with all country names (localized).
        /// </returns>
        public static DataTable Country(ILocalization localization)
        {
            using (var dt = new DataTable("Country"))
            {
                dt.Columns.Add("Value", typeof(string));
                dt.Columns.Add("Name", typeof(string));

                // Add empty row to data table for dropdown lists with empty selection option.
                var drow = dt.NewRow();
                drow["Value"] = null;
                drow["Name"] = "None";
                dt.Rows.Add(drow);

                var countries =
                    localization.GetRegionNodesUsingQuery("COUNTRY", x => x.tag.StartsWith(string.Empty))
                        .OrderBy(c => c.Value)
                        .ToList();

                // vzrus: a temporary hack - it returns all tags if the page is not found
                if (countries.Count > 2000)
                {
                    return dt;
                }

                foreach (var node in countries)
                {
                    dt.Rows.Add(node.tag, node.Value);
                }

                return dt;
            }
        }

        /// <summary>
        /// Gets all country names list(localized).
        /// </summary>
        /// <returns>
        /// Returns a Data Table with all country names list(localized)
        /// </returns>
        public static DataTable Country()
        {
            return Country(YafContext.Current.Get<ILocalization>());
        }

        /// <summary>
        /// Gets all country names list(localized).
        /// </summary>
        /// <param name="forceLanguage">
        /// The force a specific language.
        /// </param>
        /// <returns>
        /// Returns a Data Table with all country names list(localized)
        /// </returns>
        public static DataTable Country(string forceLanguage)
        {
            var localization = new YafLocalization();
            localization.LoadTranslation(forceLanguage);

            return Country(localization);
        }

        /// <summary>
        /// Gets all country names list(localized).
        /// </summary>
        /// <param name="localization">The localization.</param>
        /// <param name="culture">The culture.</param>
        /// <returns>
        /// Returns a Data Table with all country names list(localized)
        /// </returns>
        public static DataTable Region(ILocalization localization, string culture)
        {
            using (var dt = new DataTable("Region"))
            {
                dt.Columns.Add("Value", typeof(string));
                dt.Columns.Add("Name", typeof(string));

                // Add empty row to data table for dropdown lists with empty selection option.
                var drow = dt.NewRow();

                drow["Value"] = null;
                drow["Name"] = null;

                dt.Rows.Add(drow);

                var countries =
                 localization.GetCountryNodesUsingQuery("REGION", x => x.tag.StartsWith("RGN_{0}_".FormatWith(culture))).ToList();

                foreach (var node in countries)
                {
                    dt.Rows.Add(node.tag.Replace("RGN_{0}_".FormatWith(culture), string.Empty), node.Value);
                }

                return dt;
            }
        }

        /// <summary>
        /// Gets all region names (localized)
        /// </summary>
        /// <param name="culture">The culture.</param>
        /// <returns>
        /// Returns a Data Table with all region names (localized)
        /// </returns>
        public static DataTable Region(string culture)
        {
            return Region(YafContext.Current.Get<ILocalization>(), culture);
        }

        /// <summary>
        /// The cultures IetfLangTags (4-letter).
        /// </summary>
        /// <returns>
        /// The cultures filtered by first 2 letters in the language tag in a language file
        /// </returns>
        public static DataTable Cultures()
        {
            using (var dt = new DataTable("Cultures"))
            {
                dt.Columns.Add("CultureTag", typeof(string));
                dt.Columns.Add("CultureFile", typeof(string));
                dt.Columns.Add("CultureEnglishName", typeof(string));
                dt.Columns.Add("CultureNativeName", typeof(string));
                dt.Columns.Add("CultureDisplayName", typeof(string));

                // Get all language files info
                var dir =
                    new DirectoryInfo(
                        YafContext.Current.Get<HttpRequestBase>()
                            .MapPath("{0}languages".FormatWith(YafForumInfo.ForumServerFileRoot)));
                var files = dir.GetFiles("*.xml");

                // Create an array with tags
                var tags = new string[2, files.Length];

                // Extract available language tags into the array
                for (var i = 0; i < files.Length; i++)
                {
                    try
                    {
                        var doc = new XmlDocument();
                        doc.Load(files[i].FullName);
                        tags[0, i] = files[i].Name;
                        var attr = doc.DocumentElement.Attributes["code"];
                        if (attr != null)
                        {
                            tags[1, i] = attr.Value.Trim();
                        }
                        else
                        {
                            tags[1, i] = "en-US";
                        }
                    }
                    catch (Exception)
                    {
                    }
                }

                var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
                foreach (var ci in cultures)
                {
                    for (var j = 0; j < files.Length; j++)
                    {
                        if (ci.IsNeutralCulture || !tags[1, j].ToLower().Substring(0, 2).Contains(ci.TwoLetterISOLanguageName.ToLower()))
                        {
                            continue;
                        }

                        var dr = dt.NewRow();
                        dr["CultureTag"] = ci.IetfLanguageTag;
                        dr["CultureFile"] = tags[0, j];
                        dr["CultureEnglishName"] = ci.EnglishName;
                        dr["CultureNativeName"] = ci.NativeName;
                        dr["CultureDisplayName"] = ci.DisplayName;
                        dt.Rows.Add(dr);
                    }
                }

                return dt;
            }
        }

        /// <summary>
        /// Gets language tag info from language file tag.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>
        /// A default full 4-letter culture from the existing language file.
        /// </returns>
        public static string CultureDefaultFromFile(string fileName)
        {
            if (fileName.IsNotSet())
            {
                return "en-US";
            }

            string rawTag = null;

            // Get all language files info
            var dir =
              new DirectoryInfo(
                YafContext.Current.Get<HttpRequestBase>().MapPath("{0}languages".FormatWith(YafForumInfo.ForumServerFileRoot)));
            var files = dir.GetFiles(fileName);

            if (files.Length <= 0)
            {
                return null;
            }

            try
            {
                var doc = new XmlDocument();
                doc.Load(files[0].FullName);
                rawTag = doc.DocumentElement.Attributes["code"].Value.Trim();
            }
            catch (Exception)
            {
            }

            var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);

            foreach (
                var ci in
                    cultures.Where(
                        ci =>
                        !ci.IsNeutralCulture
                        && rawTag.ToLower().Substring(0, 2).Contains(ci.TwoLetterISOLanguageName.ToLower())
                        && ci.IetfLanguageTag.Length == 5))
            {
                return ci.IetfLanguageTag;
            }

            return "en-US";
        }

        /// <summary>
        /// The languages.
        /// </summary>
        /// <returns>
        /// Returns a Data Table with all Languages
        /// </returns>
        public static DataTable Languages()
        {
            using (var dt = new DataTable("Languages"))
            {
                dt.Columns.Add("Language", typeof(string));
                dt.Columns.Add("FileName", typeof(string));

                var dir =
                  new DirectoryInfo(
                    YafContext.Current.Get<HttpRequestBase>().MapPath("{0}languages".FormatWith(YafForumInfo.ForumServerFileRoot)));
                var files = dir.GetFiles("*.xml");
                foreach (var file in files)
                {
                    try
                    {
                        var doc = new XmlDocument();
                        doc.Load(file.FullName);
                        var dr = dt.NewRow();
                        dr["Language"] = doc.DocumentElement.Attributes["language"].Value;
                        dr["FileName"] = file.Name;
                        dt.Rows.Add(dr);
                    }
                    catch (Exception)
                    {
                    }
                }

                return dt;
            }
        }

        /// <summary>
        /// Get All Themes
        /// </summary>
        /// <returns>
        /// Returns a Data Table with all Themes
        /// </returns>
        public static DataTable Themes()
        {
            using (var dt = new DataTable("Themes"))
            {
                dt.Columns.Add("Theme", typeof(string));
                dt.Columns.Add("FileName", typeof(string));
                dt.Columns.Add("IsMobile", typeof(bool));

                var dir = new DirectoryInfo(YafContext.Current.Get<HttpRequestBase>().MapPath("{0}{1}".FormatWith(YafForumInfo.ForumServerFileRoot, YafBoardFolders.Current.Themes)));

                foreach (var file in dir.GetFiles("*.xml"))
                {
                    try
                    {
                        var doc = new XmlDocument();
                        doc.Load(file.FullName);

                        var dr = dt.NewRow();
                        dr["Theme"] = doc.DocumentElement.Attributes["theme"].Value;
                        dr["IsMobile"] = false;

                        if (doc.DocumentElement.HasAttribute("ismobile"))
                        {
                            dr["IsMobile"] = Convert.ToBoolean(doc.DocumentElement.Attributes["ismobile"].Value ?? "false");
                        }

                        dr["FileName"] = file.Name;
                        dt.Rows.Add(dr);
                    }
                    catch (Exception)
                    {
                    }
                }

                return dt;
            }
        }

        /// <summary>
        /// Gets all jQuery-UI Themes
        /// </summary>
        /// <returns>
        /// Returns a Data Table with all jQuery-UI Themes
        /// </returns>
        public static DataTable JqueryUIThemes()
        {
            using (var dt = new DataTable("JqueryUIThemes"))
            {
                dt.Columns.Add("Theme", typeof(string));

                var themeDir = new DirectoryInfo(HttpContext.Current.Request.MapPath(YafForumInfo.GetURLToContent("themes")));

                foreach (var dir in themeDir.GetDirectories())
                {
                    try
                    {
                        var dr = dt.NewRow();
                        dr["Theme"] = dir.Name;

                        dt.Rows.Add(dr);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }

                return dt;
            }
        }

        /// <summary>
        /// Gets all Time Zones
        /// </summary>
        /// <param name="localization">
        /// The localization.
        /// </param>
        /// <returns>
        /// Returns a Data Table with all Time Zones
        /// </returns>
        public static DataTable TimeZones(ILocalization localization)
        {
            using (var dt = new DataTable("TimeZone"))
            {
                dt.Columns.Add("Value", typeof(string));
                dt.Columns.Add("Name", typeof(string));

                var timezones =
                  localization.GetNodesUsingQuery("TIMEZONES", x => x.tag.StartsWith("UTC")).ToList();

                foreach (var node in timezones.OrderBy(tz => tz.tag))
                {
                    dt.Rows.Add((node.GetHoursOffset() * 60).ToType<int>(), node.Value);
                }

                return dt;
            }
        }

        /// <summary>
        /// Get all time zones.
        /// </summary>
        /// <returns>
        /// Returns a Data Table with all time zones.
        /// </returns>
        public static DataTable TimeZones()
        {
            return TimeZones(YafContext.Current.Get<ILocalization>());
        }

        /// <summary>
        /// Get all time zones.
        /// </summary>
        /// <param name="forceLanguage">
        /// The force language.
        /// </param>
        /// <returns>
        /// Returns a Data Table with all time zones.
        /// </returns>
        public static DataTable TimeZones(string forceLanguage)
        {
            var localization = new YafLocalization();
            localization.LoadTranslation(forceLanguage);

            return TimeZones(localization);
        }

        /// <summary>
        /// Gets all topic times.
        /// </summary>
        /// <returns>
        /// Returns a Data Table with all topic times.
        /// </returns>
        public static DataTable TopicTimes()
        {
            using (var dt = new DataTable("TopicTimes"))
            {
                dt.Columns.Add("TopicText", typeof(string));
                dt.Columns.Add("TopicValue", typeof(int));

                string[] tTextArray =
                    {
                        "all", "last_day", "last_two_days", "last_week", "last_two_weeks", "last_month",
                        "last_two_months", "last_six_months", "last_year"
                    };

                string[] tTextArrayProp =
                    {
                        "All", "Last Day", "Last Two Days", "Last Week", "Last Two Weeks",
                        "Last Month", "Last Two Months", "Last Six Months", "Last Year"
                    };

                for (var i = 0; i < 8; i++)
                {
                    var dr = dt.NewRow();
                    dr["TopicText"] = (YafContext.Current.Get<ILocalization>().TransPage == null)
                                        ? tTextArrayProp[i]
                                        : YafContext.Current.Get<ILocalization>().GetText(tTextArray[i]);
                    dr["TopicValue"] = i;
                    dt.Rows.Add(dr);
                }

                return dt;
            }
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace app { namespace Uno { namespace Collections { struct List1_Enumerator__int; } } }

namespace app {
namespace Uno {
namespace Collections {

struct List__int;

struct List__int__uType : ::uClassType
{
    ::app::Uno::Collections::IEnumerable__int __interface_0;
};

List__int__uType* List__int__typeof();

::uObject* List__int__GetEnumerator_boxed(List__int* __this);
void List__int___ObjInit(List__int* __this);
void List__int___ObjInit_1(List__int* __this, int capacity);
void List__int__Add(List__int* __this, int item);
void List__int__AddRange(List__int* __this, ::uObject* items);
void List__int__BoundsCheck(List__int* __this, int index);
void List__int__Clear(List__int* __this);
bool List__int__Contains(List__int* __this, int item);
void List__int__EnsureCapacity(List__int* __this);
int List__int__get_Count(List__int* __this);
int List__int__get_Item(List__int* __this, int index);
::app::Uno::Collections::List1_Enumerator__int List__int__GetEnumerator(List__int* __this);
int List__int__IndexOf(List__int* __this, int item);
void List__int__Insert(List__int* __this, int index, int item);
List__int* List__int__New_1(::uStatic* __this);
List__int* List__int__New_2(::uStatic* __this, int capacity);
bool List__int__Remove(List__int* __this, int item);
void List__int__RemoveAt(List__int* __this, int index);
void List__int__set_Item(List__int* __this, int index, int value);
void List__int__Sort(List__int* __this, ::uDelegate* comparer);
::uArray* List__int__ToArray(List__int* __this);

struct List__int : ::uObject
{
    ::uStrong< ::uArray*> _data;
    int _used;
    int _version;

    ::uObject* GetEnumerator_boxed() { return List__int__GetEnumerator_boxed(this); }
    void _ObjInit() { List__int___ObjInit(this); }
    void _ObjInit_1(int capacity) { List__int___ObjInit_1(this, capacity); }
    void Add(int item) { List__int__Add(this, item); }
    void AddRange(::uObject* items) { List__int__AddRange(this, items); }
    void BoundsCheck(int index) { List__int__BoundsCheck(this, index); }
    void Clear() { List__int__Clear(this); }
    bool Contains(int item) { return List__int__Contains(this, item); }
    void EnsureCapacity() { List__int__EnsureCapacity(this); }
    int Count() { return List__int__get_Count(this); }
    int Item(int index) { return List__int__get_Item(this, index); }
    ::app::Uno::Collections::List1_Enumerator__int GetEnumerator();
    int IndexOf(int item) { return List__int__IndexOf(this, item); }
    void Insert(int index, int item) { List__int__Insert(this, index, item); }
    bool Remove(int item) { return List__int__Remove(this, item); }
    void RemoveAt(int index) { List__int__RemoveAt(this, index); }
    void Item(int index, int value) { List__int__set_Item(this, index, value); }
    void Sort(::uDelegate* comparer) { List__int__Sort(this, comparer); }
    ::uArray* ToArray() { return List__int__ToArray(this); }
};

}}}

#include <app/Uno.Collections.List1_Enumerator__int.h>

namespace app {
namespace Uno {
namespace Collections {

inline ::app::Uno::Collections::List1_Enumerator__int List__int::GetEnumerator() { return List__int__GetEnumerator(this); }

}}}

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<application xmlns="http://www.kinoma.com/kpr/application/1" id="licensesimple.example.kinoma.marvell.com" program="src/main" title="Open Source License Viewer">

</application>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sbe:messageSchema xmlns:sbe="http://fixprotocol.io/sbe/rc4"
    package="org.helios.mmb.sbe"
    id="1"
    version="0"
    semanticVersion="1.0"
    description="Message header schema for Helios Multi-Message Bus (MMB)"
    byteOrder="littleEndian">

    <types>
        <type name="Text" description="Text" length="180" primitiveType="char" semanticType="String"/>
        <composite name="messageHeader" description="Template ID and length of message root">
            <type name="blockLength" primitiveType="uint16"/>
            <type name="templateId" primitiveType="uint16"/>
            <type name="schemaId" primitiveType="uint16"/>
            <type name="version" primitiveType="uint16"/>
        </composite>
        <composite name="groupSizeEncoding" description="Repeating group dimensions">
            <type name="blockLength" primitiveType="uint16"/>
            <type name="numInGroup" primitiveType="uint8"/>
        </composite>
        <composite name="varDataEncoding">
            <type name="length" primitiveType="uint16"/>
            <type name="varData" primitiveType="uint8" length="0" characterEncoding="UTF-8"/>
        </composite>
        <enum name="Boolean" encodingType="uint8" semanticType="Boolean">
            <validValue name="False">0</validValue>
            <validValue name="True">1</validValue>
        </enum>
    </types>

    <types>
        <composite name="Component" description="MMB message identifiers">
            <enum name="ComponentType" encodingType="uint8">
                <validValue name="Service">0</validValue>
                <validValue name="Gateway">1</validValue>
            </enum>
            <type name="componentId" primitiveType="uint8"/>
        </composite>
        <composite name="MMBHeaderType" description="MMB message identifiers">
            <type name="messageNumber" primitiveType="uint64"/>
            <type name="nodeId" primitiveType="uint8"/>
            <type name="timestamp" primitiveType="uint64"/>
            <ref name="component" type="Component"/>
        </composite>
    </types>

    <sbe:message name="Acknowledge" id="0" description="Acknowledge message">
        <field name="mmbHeader" id="1" type="MMBHeaderType" description="MMB header" offset="0"/>
        <field name="isACK" id="2" type="Boolean" description="ACK/NACK flag"/>
    </sbe:message>

    <sbe:message name="Startup" id="1" description="Startup message">
        <field name="mmbHeader" id="1" type="MMBHeaderType" description="MMB header" offset="0"/>
    </sbe:message>

    <sbe:message name="Shutdown" id="2" description="Shutdown message">
        <field name="mmbHeader" id="1" type="MMBHeaderType" description="MMB header" offset="0"/>
    </sbe:message>

    <sbe:message name="Heartbeat" id="3" description="Heartbeat message">
        <field name="mmbHeader" id="1" type="MMBHeaderType" description="MMB header" offset="0"/>
    </sbe:message>

    <sbe:message name="SaveSnapshot" id="4" description="Save snapshot message">
        <field name="mmbHeader" id="1" type="MMBHeaderType" description="MMB header" offset="0"/>
    </sbe:message>

    <sbe:message name="LoadSnapshot" id="5" description="Load snapshot message">
        <field name="mmbHeader" id="1" type="MMBHeaderType" description="MMB header" offset="0"/>
    </sbe:message>

    <sbe:message name="Data" id="6" description="Data message">
        <field name="mmbHeader" id="1" type="MMBHeaderType" description="MMB header" offset="0"/>
    </sbe:message>
</sbe:messageSchema>


text:
package ch.trivadis.contactvalidator.internal;
import ch.trivadis.contactvalidator.api.ContactValidator;
import ch.trivadis.phoneValidator.api.PhoneValidatorFactory;

/**
 * Created by Andy Moncsek on 08/02/16.
 */
public class ContactValidatorImpl implements ContactValidator{

    public boolean checkContact(String phoneNumber){
      return PhoneValidatorFactory.getInstance().checkPhone(phoneNumber);
    }

}


text:
package org.apache.flink.table.api

import org.apache.flink.annotation.VisibleForTesting
import org.apache.flink.api.common.JobExecutionResult
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.configuration.Configuration
import org.apache.flink.runtime.state.filesystem.FsStateBackend
import org.apache.flink.runtime.state.memory.MemoryStateBackend
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.datastream.DataStream
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment
import org.apache.flink.streaming.api.graph.{StreamGraph, StreamGraphGenerator}
import org.apache.flink.table.catalog.CatalogManager
import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.operations.DataStreamQueryOperation
import org.apache.flink.table.plan.`trait`.{AccModeTraitDef, FlinkRelDistributionTraitDef, MiniBatchIntervalTraitDef, UpdateAsRetractionTraitDef}
import org.apache.flink.table.plan.nodes.calcite.LogicalSink
import org.apache.flink.table.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.flink.table.plan.nodes.process.DAGProcessContext
import org.apache.flink.table.plan.nodes.resource.parallelism.ParallelismProcessor
import org.apache.flink.table.plan.optimize.{Optimizer, StreamCommonSubGraphBasedOptimizer}
import org.apache.flink.table.plan.stats.FlinkStatistic
import org.apache.flink.table.plan.util.{ExecNodePlanDumper, FlinkRelOptUtil}
import org.apache.flink.table.sinks.DataStreamTableSink
import org.apache.flink.table.sources.{LookupableTableSource, StreamTableSource, TableSource}
import org.apache.flink.table.types.logical.{LogicalType, RowType}
import org.apache.flink.table.types.utils.TypeConversions.fromLegacyInfoToDataType
import org.apache.flink.table.types.{DataType, LogicalTypeDataTypeConverter}
import org.apache.flink.table.typeutils.{TimeIndicatorTypeInfo, TypeCheckUtils}
import org.apache.flink.table.util.PlanUtil
import org.apache.calcite.plan.{ConventionTraitDef, RelTrait, RelTraitDef}
import org.apache.calcite.rel.RelNode
import org.apache.calcite.sql.SqlExplainLevel
import org.apache.flink.api.dag.Transformation

import _root_.scala.collection.JavaConversions._

/**
  * The base class for stream TableEnvironments.
  *
  * A TableEnvironment can be used to:
  * - convert [[DataStream]] to a [[Table]]
  * - register a [[DataStream]] as a table in the catalog
  * - register a [[Table]] in the catalog
  * - scan a registered table to obtain a [[Table]]
  * - specify a SQL query on registered tables to obtain a [[Table]]
  * - convert a [[Table]] into a [[DataStream]]
  *
  * @param execEnv The [[StreamExecutionEnvironment]] which is wrapped in this
  *                [[StreamTableEnvironment]].
  * @param config The [[TableConfig]] of this [[StreamTableEnvironment]].
  */
abstract class StreamTableEnvironment(
    private[flink] val execEnv: StreamExecutionEnvironment,
    config: TableConfig,
    catalogManager: CatalogManager)
  extends TableEnvironment(execEnv, config, catalogManager) {

  // prefix  for unique table names.
  override private[flink] val tableNamePrefix = "_DataStreamTable_"

  // the naming pattern for internally registered tables.
  private val internalNamePattern = "^_DataStreamTable_[0-9]+$".r

  private var isConfigMerged: Boolean = false

  override def queryConfig: StreamQueryConfig = new StreamQueryConfig

  override protected def getTraitDefs: Array[RelTraitDef[_ <: RelTrait]] = {
    Array(
      ConventionTraitDef.INSTANCE,
      FlinkRelDistributionTraitDef.INSTANCE,
      MiniBatchIntervalTraitDef.INSTANCE,
      UpdateAsRetractionTraitDef.INSTANCE,
      AccModeTraitDef.INSTANCE)
  }

  override protected def getOptimizer: Optimizer = new StreamCommonSubGraphBasedOptimizer(this)

  override private[flink] def isBatch = false

  /**
    * Checks if the chosen table name is valid.
    *
    * @param name The table name to check.
    */
  override protected def checkValidTableName(name: String): Unit = {
    val m = internalNamePattern.findFirstIn(name)
    m match {
      case Some(_) =>
        throw new TableException(s"Illegal Table name. " +
          s"Please choose a name that does not contain the pattern $internalNamePattern")
      case None =>
    }
  }

  override protected def validateTableSource(tableSource: TableSource[_]): Unit = {
    // TODO TableSourceUtil.validateTableSource(tableSource)
    tableSource match {
      // check for proper stream table source
      case _: StreamTableSource[_] => // StreamEnv can handle both bounded and unbounded ok
      // TODO `TableSourceUtil.hasRowtimeAttribute` depends on [Expression]
      // check that event-time is enabled if table source includes rowtime attributes
      // if (TableSourceUtil.hasRowtimeAttribute(streamTableSource) &&
      //  execEnv.getStreamTimeCharacteristic != TimeCharacteristic.EventTime) {
      //  throw new TableException(
      //    s"A rowtime attribute requires an EventTime time characteristic in stream " +
      //      s"environment. But is: ${execEnv.getStreamTimeCharacteristic}")
      // }

      // a lookupable table source can also be registered in the env
      case _: LookupableTableSource[_] =>
      // not a stream table source
      case _ =>
        throw new TableException("Only LookupableTableSource and unbounded StreamTableSource " +
          "can be registered in StreamTableEnvironment")
    }
  }

  override def execute(jobName: String): JobExecutionResult = {
    generateStreamGraph(jobName)
    // TODO supports execEnv.execute(streamGraph)
    execEnv.execute(jobName)
  }

  protected override def translateStreamGraph(
      streamingTransformations: Seq[Transformation[_]],
      jobName: Option[String] = None): StreamGraph = {
    mergeParameters()

    new StreamGraphGenerator(
        streamingTransformations.toList, execEnv.getConfig, execEnv.getCheckpointConfig)
      .setChaining(execEnv.isChainingEnabled)
      .setDefaultBufferTimeout(execEnv.getBufferTimeout)
      .setStateBackend(execEnv.getStateBackend)
      .setTimeCharacteristic(execEnv.getStreamTimeCharacteristic)
      .setUserArtifacts(execEnv.getCachedFiles)
      .setJobName(jobName.getOrElse(DEFAULT_JOB_NAME))
      .generate()
  }

  /**
    * Merge global job parameters and table config parameters,
    * and set the merged result to GlobalJobParameters
    */
  private def mergeParameters(): Unit = {
    if (!isConfigMerged && execEnv != null && execEnv.getConfig != null) {
      val parameters = new Configuration()
      if (config != null && config.getConf != null) {
        parameters.addAll(config.getConf)
      }

      if (execEnv.getConfig.getGlobalJobParameters != null) {
        execEnv.getConfig.getGlobalJobParameters.toMap.foreach {
          kv => parameters.setString(kv._1, kv._2)
        }
      }
      val isHeapState = Option(execEnv.getStateBackend) match {
        case Some(backend) if backend.isInstanceOf[MemoryStateBackend] ||
          backend.isInstanceOf[FsStateBackend]=> true
        case None => true
        case _ => false
      }
      parameters.setBoolean(TableConfigOptions.SQL_EXEC_STATE_BACKEND_ON_HEAP, isHeapState)
      execEnv.getConfig.setGlobalJobParameters(parameters)
      isConfigMerged = true
    }
  }

  override private[flink] def translateToExecNodeDag(rels: Seq[RelNode]): Seq[ExecNode[_, _]] = {
    val nodeDag = super.translateToExecNodeDag(rels)
    val context = new DAGProcessContext(this)
    new ParallelismProcessor().process(nodeDag, context)
  }

  /**
    * Translates a [[Table]] into a [[DataStream]].
    *
    * The transformation involves optimizing the relational expression tree as defined by
    * Table API calls and / or SQL queries and generating corresponding [[DataStream]] operators.
    *
    * @param table               The root node of the relational expression tree.
    * @param updatesAsRetraction Set to true to encode updates as retraction messages.
    * @param withChangeFlag      Set to true to emit records with change flags.
    * @param resultType          The [[org.apache.flink.api.common.typeinfo.TypeInformation[_]] of
    *                            the resulting [[DataStream]].
    * @tparam T The type of the resulting [[DataStream]].
    * @return The [[DataStream]] that corresponds to the translated [[Table]].
    */
  protected def translateToDataStream[T](
      table: Table,
      updatesAsRetraction: Boolean,
      withChangeFlag: Boolean,
      resultType: TypeInformation[T]): DataStream[T] = {
    val sink = new DataStreamTableSink[T](table, resultType, updatesAsRetraction, withChangeFlag)
    val sinkName = createUniqueTableName()
    val input = getRelBuilder.queryOperation(table.getQueryOperation).build()
    val sinkNode = LogicalSink.create(input, sink, sinkName)
    val transformation = translateSink(sinkNode)
    new DataStream(execEnv, transformation).asInstanceOf[DataStream[T]]
  }

  private def translateSink(sink: LogicalSink): Transformation[_] = {
    mergeParameters()

    val optimizedPlan = optimize(sink)
    val optimizedNodes = translateToExecNodeDag(Seq(optimizedPlan))
    require(optimizedNodes.size() == 1)
    translateToPlan(optimizedNodes.head)
  }

  override protected def translateToPlan(
      sinks: Seq[ExecNode[_, _]]): Seq[Transformation[_]] = sinks.map(translateToPlan)

  /**
    * Translates a [[StreamExecNode]] plan into a [[Transformation]].
    *
    * @param node The plan to translate.
    * @return The [[Transformation]] of type [[BaseRow]].
    */
  private def translateToPlan(node: ExecNode[_, _]): Transformation[_] = {
    node match {
      case node: StreamExecNode[_] => node.translateToPlan(this)
      case _ =>
        throw new TableException("Cannot generate DataStream due to an invalid logical plan. " +
                                   "This is a bug and should not happen. Please file an issue.")
    }
  }

  /**
    * Returns the AST of the specified Table API and SQL queries and the execution plan to compute
    * the result of the given [[Table]].
    *
    * @param table The table for which the AST and execution plan will be returned.
    */
  def explain(table: Table): String = explain(table, extended = false)

  /**
    * Returns the AST of the specified Table API and SQL queries and the execution plan to compute
    * the result of the given [[Table]].
    *
    * @param table    The table for which the AST and execution plan will be returned.
    * @param extended Flag to include detailed optimizer estimates.
    */
  def explain(table: Table, extended: Boolean): String = {
    val ast = getRelBuilder.queryOperation(table.getQueryOperation).build()
    val execNodeDag = compileToExecNodePlan(ast)
    val transformations = translateToPlan(execNodeDag)
    val streamGraph = translateStreamGraph(transformations)
    val executionPlan = PlanUtil.explainStreamGraph(streamGraph)

    val (explainLevel, withRetractTraits) = if (extended) {
      (SqlExplainLevel.ALL_ATTRIBUTES, true)
    } else {
      (SqlExplainLevel.EXPPLAN_ATTRIBUTES, false)
    }

    s"== Abstract Syntax Tree ==" +
      System.lineSeparator +
      s"${FlinkRelOptUtil.toString(ast)}" +
      System.lineSeparator +
      s"== Optimized Logical Plan ==" +
      System.lineSeparator +
      s"${
        ExecNodePlanDumper.dagToString(
          execNodeDag,
          explainLevel,
          withRetractTraits = withRetractTraits)
      }" +
      System.lineSeparator +
      s"== Physical Execution Plan ==" +
      System.lineSeparator +
      s"$executionPlan"
  }

  /**
    * Explain the whole plan, and returns the AST(s) of the specified Table API and SQL queries
    * and the execution plan.
    */
  def explain(): String = explain(extended = false)

  /**
    * Explain the whole plan, and returns the AST(s) of the specified Table API and SQL queries
    * and the execution plan.
    *
    * @param extended Flag to include detailed optimizer estimates.
    */
  def explain(extended: Boolean): String = {
    val sinkExecNodes = compileToExecNodePlan(sinkNodes: _*)
    // translate relNodes to Transformations
    val sinkTransformations = translateToPlan(sinkExecNodes)
    val streamGraph = translateStreamGraph(sinkTransformations)
    val sqlPlan = PlanUtil.explainStreamGraph(streamGraph)

    val sb = new StringBuilder
    sb.append("== Abstract Syntax Tree ==")
    sb.append(System.lineSeparator)
    sinkNodes.foreach { sink =>
      sb.append(FlinkRelOptUtil.toString(sink))
      sb.append(System.lineSeparator)
    }

    sb.append("== Optimized Logical Plan ==")
    sb.append(System.lineSeparator)
    val (explainLevel, withRetractTraits) = if (extended) {
      (SqlExplainLevel.ALL_ATTRIBUTES, true)
    } else {
      (SqlExplainLevel.EXPPLAN_ATTRIBUTES, false)
    }
    sb.append(ExecNodePlanDumper.dagToString(
      sinkExecNodes,
      explainLevel,
      withRetractTraits = withRetractTraits))
    sb.append(System.lineSeparator)

    sb.append("== Physical Execution Plan ==")
    sb.append(System.lineSeparator)
    sb.append(sqlPlan)
    sb.toString()
  }

  @VisibleForTesting
  private[flink] def asQueryOperation[T](
      dataStream: DataStream[T],
      fields: Option[Array[String]],
      fieldNullables: Option[Array[Boolean]] = None,
      statistic: Option[FlinkStatistic] = None): DataStreamQueryOperation[T] = {
    val streamType = dataStream.getType
    val streamDataType = fromLegacyInfoToDataType(streamType)

    // get field names and types for all non-replaced fields
    val (indices, names) = fields match {
      case Some(f) =>
        // validate and extract time attributes
        // TODO should use FieldInfoUtils#getFieldsInfo instead of getFieldInfo
        // TODO: validate and extract time attributes after we introduce [Expression],
        //  return None currently
        val (rowtime, proctime) = validateAndExtractTimeAttributes(streamDataType, f)
        val (fieldNames, fieldIndexes) = getFieldInfo(streamDataType, f)

        // check if event-time is enabled
        if (rowtime.isDefined &&
          execEnv.getStreamTimeCharacteristic != TimeCharacteristic.EventTime) {
          throw new TableException(
            s"A rowtime attribute requires an EventTime time characteristic in stream environment" +
              s". But is: ${execEnv.getStreamTimeCharacteristic}")
        }

        // adjust field indexes and field names
        val indexesWithIndicatorFields = adjustFieldIndexes(fieldIndexes, rowtime, proctime)
        val namesWithIndicatorFields = adjustFieldNames(fieldNames, rowtime, proctime)

        (indexesWithIndicatorFields, namesWithIndicatorFields)
      case None =>
        val (fieldNames, fieldIndexes) = getFieldInfo[T](streamDataType)
        (fieldIndexes, fieldNames)
    }

    val dataStreamTable = new DataStreamQueryOperation(
      dataStream,
      indices,
      TableEnvironment.calculateTableSchema(streamType, indices, names),
      fieldNullables.getOrElse(Array.fill(indices.length)(true)),
      false,
      false,
      statistic.getOrElse(FlinkStatistic.UNKNOWN))
    dataStreamTable
  }

  /**
    * Checks for at most one rowtime and proctime attribute.
    * Returns the time attributes.
    *
    * @return rowtime attribute and proctime attribute
    */
  // TODO: we should support Expression fields after we introduce [Expression]
  private[flink] def validateAndExtractTimeAttributes(
      streamType: DataType,
      fields: Array[String]): (Option[(Int, String)], Option[(Int, String)]) = {

    val streamLogicalType = LogicalTypeDataTypeConverter.fromDataTypeToLogicalType(streamType)

    val (isRefByPos, fieldTypes) = streamLogicalType match {
      case c: RowType =>
        // determine schema definition mode (by position or by name)
        (isReferenceByPosition(c, fields),
            (0 until c.getFieldCount).map(i => c.getTypeAt(i)).toArray)
      case t =>
        (false, Array(t))
    }

    var fieldNames: List[String] = Nil
    var rowtime: Option[(Int, String)] = None
    var proctime: Option[(Int, String)] = None

    def checkRowtimeType(t: LogicalType): Unit = {
      if (!(TypeCheckUtils.isLong(t) || TypeCheckUtils.isTimePoint(t))) {
        throw new TableException(
          s"The rowtime attribute can only replace a field with a valid time type, " +
            s"such as Timestamp or Long. But was: $t")
      }
    }

    def extractRowtime(idx: Int, name: String, origName: Option[String]): Unit = {
      if (rowtime.isDefined) {
        throw new TableException(
          "The rowtime attribute can only be defined once in a table schema.")
      } else {
        // if the fields are referenced by position,
        // it is possible to replace an existing field or append the time attribute at the end
        if (isRefByPos) {
          // aliases are not permitted
          if (origName.isDefined) {
            throw new TableException(
              s"Invalid alias '${origName.get}' because fields are referenced by position.")
          }
          // check type of field that is replaced
          if (idx < fieldTypes.length) {
            checkRowtimeType(fieldTypes(idx))
          }
        }
        // check reference-by-name
        else {
          val aliasOrName = origName.getOrElse(name)
          streamLogicalType match {
            // both alias and reference must have a valid type if they replace a field
            case ct: RowType if ct.getFieldIndex(aliasOrName) != -1 =>
              val t = ct.getTypeAt(ct.getFieldIndex(aliasOrName))
              checkRowtimeType(t)
            // alias could not be found
            case _ if origName.isDefined =>
              throw new TableException(s"Alias '${origName.get}' must reference an existing field.")
            case _ => // ok
          }
        }

        rowtime = Some(idx, name)
      }
    }

    def extractProctime(idx: Int, name: String): Unit = {
      if (proctime.isDefined) {
        throw new TableException(
          "The proctime attribute can only be defined once in a table schema.")
      } else {
        // if the fields are referenced by position,
        // it is only possible to append the time attribute at the end
        if (isRefByPos) {

          // check that proctime is only appended
          if (idx < fieldTypes.length) {
            throw new TableException(
              "The proctime attribute can only be appended to the table schema and not replace " +
                s"an existing field. Please move '$name' to the end of the schema.")
          }
        }
        // check reference-by-name
        else {
          streamLogicalType match {
            // proctime attribute must not replace a field
            case ct: RowType if ct.getFieldIndex(name) != -1 =>
              throw new TableException(
                s"The proctime attribute '$name' must not replace an existing field.")
            case _ => // ok
          }
        }
        proctime = Some(idx, name)
      }
    }

    fields.zipWithIndex.foreach { case (name, idx) =>
      if (name.endsWith("rowtime")) {
        extractRowtime(idx, name, None)
      } else if (name.endsWith("proctime")) {
        extractProctime(idx, name)
      } else {
        fieldNames = name :: fieldNames
      }
    }

    if (rowtime.isDefined && fieldNames.contains(rowtime.get._2)) {
      throw new TableException(
        "The rowtime attribute may not have the same name as an another field.")
    }

    if (proctime.isDefined && fieldNames.contains(proctime.get._2)) {
      throw new TableException(
        "The proctime attribute may not have the same name as an another field.")
    }

    (rowtime, proctime)
  }

  /**
    * Injects markers for time indicator fields into the field indexes.
    *
    * @param fieldIndexes The field indexes into which the time indicators markers are injected.
    * @param rowtime An optional rowtime indicator
    * @param proctime An optional proctime indicator
    * @return An adjusted array of field indexes.
    */
  private def adjustFieldIndexes(
    fieldIndexes: Array[Int],
    rowtime: Option[(Int, String)],
    proctime: Option[(Int, String)]): Array[Int] = {

    // inject rowtime field
    val withRowtime = rowtime match {
      case Some(rt) =>
        fieldIndexes.patch(rt._1, Seq(TimeIndicatorTypeInfo.ROWTIME_STREAM_MARKER), 0)
      case _ =>
        fieldIndexes
    }

    // inject proctime field
    val withProctime = proctime match {
      case Some(pt) =>
        withRowtime.patch(pt._1, Seq(TimeIndicatorTypeInfo.PROCTIME_STREAM_MARKER), 0)
      case _ =>
        withRowtime
    }

    withProctime
  }

  /**
    * Injects names of time indicator fields into the list of field names.
    *
    * @param fieldNames The array of field names into which the time indicator field names are
    *                   injected.
    * @param rowtime An optional rowtime indicator
    * @param proctime An optional proctime indicator
    * @return An adjusted array of field names.
    */
  private def adjustFieldNames(
    fieldNames: Array[String],
    rowtime: Option[(Int, String)],
    proctime: Option[(Int, String)]): Array[String] = {

    // inject rowtime field
    val withRowtime = rowtime match {
      case Some(rt) => fieldNames.patch(rt._1, Seq(rowtime.get._2), 0)
      case _ => fieldNames
    }

    // inject proctime field
    val withProctime = proctime match {
      case Some(pt) => withRowtime.patch(pt._1, Seq(proctime.get._2), 0)
      case _ => withRowtime
    }

    withProctime
  }

}


text:
package test.com.xceptance.xlt.visual.exact;

import org.junit.Before;
import org.junit.Test;

import com.xceptance.xlt.visualassertion.algorithm.ComparisonAlgorithm;
import com.xceptance.xlt.visualassertion.algorithm.ExactMatch;
import com.xceptance.xlt.visualassertion.util.RectangleMask;

import test.com.xceptance.xlt.visual.ImageTest;
import test.com.xceptance.xlt.visual.TestCompare;

public class TExactMatch extends ImageTest
{
    ComparisonAlgorithm a = new ExactMatch();

    // how should a difference maSked during training
    RectangleMask m = new RectangleMask(10, 10);

    // how difference should maRked in difference file
    int mX = 10;

    int mY = 10;

    TestCompare T;

    @Before
    public void setup()
    {
        T = new TestCompare(a, m, mX, mY);
    }

    @Test
    public void blank()
    {
        T.match("exact/blank.png").to("exact/blank.png").isEqual().hasNoMarking();
    }

    @Test
    public void photo()
    {
        T.match("exact/photo.png").to("exact/photo.png").isEqual().hasNoMarking();
    }

    @Test
    public void photoSameButDifferentFile()
    {
        T.match("exact/photo.png").to("exact/photo2.png").isEqual().hasNoMarking();
    }

    @Test
    public void noMatchPixelDiff()
    {
        T.match("exact/blank.png").to("exact/oneblackpixel.png").isNotEqual().hasMarking("exact/noMatchPixelDiff.png");
    }

    @Test
    public void noMatchDifferentSize()
    {
        T.match("exact/photo.png").to("exact/photo-205x205.png").isNotEqual().hasMarking("exact/photo-205x205-MaskExpected.png");
    }

    @Test
    public void noMatchDifferentSizeReversed()
    {
        T.match("exact/photo-205x205.png").to("exact/photo.png").isNotEqual().hasMarking("exact/photo-205x205-ReversedMaskExpected.png");
    }

    @Test
    public void noMatchNegated()
    {
        T.match("exact/blank.png").to("exact/negated-blank.png").isNotEqual().hasMarking("exact/negated-MaskExpected.png");
    }
}


text:
UmlCanvas.Interface = UmlCanvas.Class.extend( {
    preprocess: function( props ) {
	props = this._super(props);

	if( props['stereotype'] ) {
	    props['stereotype'] = "interface " + props['stereotype'];
	} else {
	    props['stereotype'] = "interface";
	}
	props.isAbstract = true;
	return props;
    },

    getFontForClassName : function() {
        return this.getFont();
    },

    getFontForOperationName : function(operation) {
        return this.getFont();
    },

    asConstruct: function() {
	var construct = this._super();
	delete construct.modifiers["abstract"];
	delete construct.modifiers.stereotype;
	return construct;
    }
} );

UmlCanvas.Interface.from = function( construct, diagram ) {
    var props = {};

    // NAME
    props.name = construct.name;

    // MINIMUM WIDTH
    var minimumWidth = construct.modifiers.get( "minimumWidth" );
    if( minimumWidth ) {
        props.minimumWidth = parseInt(minimumWidth.value.value);
    }

    // STEREOTYPE
    var stereotype = construct.modifiers.get("stereotype" );
    if( stereotype ) {
	props.stereotype = stereotype.value.value;
    }

    var elem = new UmlCanvas.Interface( props );

    // SUPERCLASS
    if( construct.supers && construct.supers.length > 0 ) {
	construct.supers.iterate(function(superConstruct) {
	    var zuper = diagram.getDiagramClass(superConstruct.constructName);
	    elem.addSuper(zuper);
	    diagram.addRelation(new UmlCanvas.Inheritance({from:zuper, to: elem}));
	});
    }

    return elem;
};

UmlCanvas.Interface.MANIFEST = {
    name         : "interface",
    propertyPath : [ Canvas2D.CompositeShape, Canvas2D.Rectangle, UmlCanvas.Class ],
    libraries    : [ "UmlCanvas", "Class Diagram", "Element" ]
}

Canvas2D.registerShape(UmlCanvas.Interface);


text:
<!DOCTYPE html>

	<title>three.js webgl - multiple canvases - circle</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

three.js webgl - multiple canvases - circle

		This example is shows how to setup multi-monitor displays like Google's Liquid Galaxy using three.js.
		Here 5 monitors are simulated using 3d css. WebGL is then rendered onto each one.

		Note: 3d css support required! Use Chrome, Safari or Firefox 10


text:
import mysql.connector
import keyring

class MySQLdb:
    instance = None

    # singleton class
    class __MySQLdb:
        def __init__(self):
            """
            create a database connection for MySQL database
            """
            try:
                # pick database credentials from keyring
                self.conn = mysql.connector.connect(user=keyring.get_password('mysql', 'username'),
                                                    password=keyring.get_password('mysql', 'password'),
                                                    host='localhost',
                                                    database='vulnapp')

            except mysql.connector.Error as err:
                print(err)
                exit(0)

    def __init__(self):
        if MySQLdb.instance is None:
            MySQLdb.instance = MySQLdb.__MySQLdb()

    @property
    def conn(self):
        return MySQLdb.instance.conn

    @staticmethod
    def close():
        if MySQLdb.instance is not None:
            MySQLdb.instance.conn.close()
            MySQLdb.instance = None