text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.IO;

namespace MvcApp4Demo.Module.Utils
{
    public class Logger
    {

        private string logTable = "Common_Log";

        public Logger()
        {

        }

        public Logger(string logTable)
        {
            if (!string.IsNullOrEmpty(logTable))
            {
                this.logTable = logTable;
            }
        }

        /// <summary>
        /// 记录异常
        /// </summary>
        /// <param name="ex"></param>
        public void Info(Exception ex)
        {
            string logInfo = "";
            if (ex != null)
            {
                logInfo = String.Format("{0}\r\n{1}", ex.Message, ex.StackTrace);
                Info(logInfo, -1);
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="appendInfo"></param>
        public void Info(Exception ex, string appendInfo)
        {
            Info(ex, appendInfo, -1);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="appendInfo"></param>
        /// <param name="logType"> </param>
        public void Info(Exception ex, string appendInfo, int logType)
        {
            if (appendInfo == null)
            {
                appendInfo = "";
            }

            string logInfo = "";
            if (ex != null)
            {
                logInfo = String.Format("[{0}]\r\n{1}\r\n{2}", appendInfo, ex.Message, ex.StackTrace);
                ex = ex.InnerException;
                while (ex != null)
                {
                    logInfo += string.Format("\r\n{0}\r\n{1}", ex.Message, ex.StackTrace);
                    ex = ex.InnerException;
                }
            }
            else
            {
                logInfo = String.Format("[{0}]", appendInfo);
            }
            Info(logInfo, logType);
        }

        /// <summary>
        /// 记录异常
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="logType"></param>
        public void Info(Exception ex, int logType)
        {
            if (ex != null)
            {
                string logInfo = String.Format("{0}\r\n{1}", ex.Message, ex.StackTrace);
                Info(logInfo, logType);
            }
        }

        /// <summary>
        /// 记录日志,非异常
        /// </summary>
        /// <param name="logInfo"></param>
        /// <param name="appendInfo"> </param>
        public void Info(string logInfo, string appendInfo)
        {
            string info = String.Format("[{0}]{1}", appendInfo, logInfo);
            Info(info, 0);
        }

        /// <summary>
        /// 记录日志,非异常
        /// </summary>
        /// <param name="logInfo"></param>
        public void Info(string logInfo)
        {
            Info(logInfo, 0);
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="logInfo"></param>
        /// <param name="type">0信息,-1异常</param>
        public static void Info(string logInfo, int type)
        {
            if (logInfo == null)
            {
                logInfo = "";
            }
            string sClassName = "";
            try
            {
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace();
                for (int i = 0; i < trace.FrameCount; i++)
                {
                    System.Reflection.MethodBase mb = trace.GetFrame(i).GetMethod();
                    //只记录最多5层堆栈
                    if (mb.DeclaringType.FullName == "System.RuntimeMethodHandle" || i >= 5)
                        break;
                    sClassName += " | " + mb.DeclaringType.FullName + "." + mb.Name;
                }
            }
            catch (Exception ex)
            {
                sClassName = ex.Message + ex.Source + ex.StackTrace;
            }

            logInfo = string.Format("{0}:{1},{2}", Environment.MachineName, logInfo, sClassName);

            string sql = String.Format(
                "insert into {0} (Info, Type) values(@Info, @Type) ", Database.ErrorLogTable);

            SqlParameter[] paras = new SqlParameter[]{
                            new SqlParameter("@Info", logInfo),
                            new SqlParameter("@Type", type)
                        };
            string strpath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Replace("/", "\\");
            strpath = strpath.Substring(0, strpath.LastIndexOf("\\")).Replace(@"file:\\\", "");

            try
            {
                //TODO:已注释掉往数据库写日志
                //SqlHelper.ExecuteSql(sql, paras, BaseCommon.ConnectionString);
                string content = string.Format(@"{0}:Info:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), logInfo + "\r\n");
                WriteToDisk(strpath, content);
            }
            catch (Exception ex)
            {
                string content = string.Format(@"{0}:ERROR:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ex.Message + ex.Source + ex.StackTrace + "\r\n");
                WriteToDisk(strpath, content);
            }
        }

        #region 错误写到硬盘文件
        /// <summary>
        /// 同步锁
        /// </summary>
        public static object syncWriteTxtLock = new object();

        /// <summary>
        /// 向指定路径写入日志,写到文本文件中
        /// </summary>
        /// <param name="strpath">只要给出路径就可以,e.g: d:\</param>
        public static void WriteToDisk(string strpath, string content)
        {
            lock (syncWriteTxtLock)
            {
                try
                {
                    string path = strpath + @"\log_" + DateTime.Now.ToString("yyyyMM") + ".txt";
                    if (!File.Exists(path))
                    {
                        using (FileStream fs = File.Create(path))
                        {
                            Byte[] info = new UTF8Encoding(true).GetBytes(content);
                            // Add some information to the file.
                            fs.Write(info, 0, info.Length);
                        }
                    }
                    else
                    {
                        System.IO.StreamWriter sw = new StreamWriter(path, true);
                        sw.Write(content + "\r\n");
                        sw.Close();
                        sw.Dispose();
                    }
                }
                catch { }
            }
        }

        #endregion

        #region write log

        /// <summary>
        ///
        /// </summary>
        /// <param name="ex"></param>
        public static void WriteLog(Exception ex)
        {
            string fileName = string.Format(
                AppDomain.CurrentDomain.BaseDirectory + "/AtallServiceLog_Exception_{0}.txt",
                DateTime.Now.ToString("yyyyMMdd"));

            var writer = new StreamWriter(fileName, true);
            string str = string.Format("-----------------{0}-BEGIN-----------------------------", DateTime.Now);
            writer.WriteLine(str);
            while (ex != null)
            {
                writer.WriteLine(ex.Message);
                writer.WriteLine(ex.StackTrace);
                ex = ex.InnerException;
            }

            str = string.Format("-----------------{0}-THE END-----------------------------", DateTime.Now);
            writer.WriteLine(str);
            writer.Close();
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="msg"></param>
        public static void WriteLog(string msg)
        {
            string fileName = string.Format(AppDomain.CurrentDomain.BaseDirectory + "/AtallServiceLog_info_{0}.txt",
                DateTime.Now.ToString("yyyyMMdd"));

            var writer = new StreamWriter(fileName, true);
            string str = string.Format("-----------------{0}-BEGIN-----------------------------\r\n", DateTime.Now);
            writer.WriteLine(str);
            if (!string.IsNullOrEmpty(msg))
            {
                writer.WriteLine(msg);
            }

            str = string.Format("-----------------{0}-THE END-----------------------------\r\n", DateTime.Now);
            writer.WriteLine(str);
            writer.Close();
        }

        #endregion
    }

}


text:
const styles = require('./styles.css');

const div = `<div class="${styles['class-name-1']}"></div>`;
const div2 = `<div class="${styles['class-name-2']}"></div>`;
document.body.insertAdjacentHTML('beforeend', div);
document.body.insertAdjacentHTML('beforeend', div2);

redpajama_set_name: RedPajamaGithub


text:
FROM alpine

ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/.local/bin

COPY requirements.txt /mkdocs/
WORKDIR /mkdocs

RUN apk --update upgrade \
&& apk --no-cache --no-progress add py-pip \
&& rm -rf /var/cache/apk/* \
&& pip install --user -r requirements.txt


text:
export default function() {
  this.namespace = '/api';

  this.get('/users');
  this.get('/users/:id', function(db, request) {
    let id = request.params.id;
    let userExtended = db.user_extendeds.find(id);

    return {
      user: userExtended
    };
  });

  this.post('/users', function(db, request) {
    let attrs = JSON.parse(request.requestBody)['user'];
    let user = db.users.insert({ name: attrs.name });
    let userExtended = db.user_extendeds.insert(attrs);

    return {
      user: userExtended
    };
  });

  this.put('/users/:id', function(db, request) {
    let id = request.params.id;
    let attrs = JSON.parse(request.requestBody)['user'];
    let user = db.users.update(id, { name: attrs.name });
    let userExtended = db.user_extendeds.update(id, attrs);

    return {
      user: userExtended
    };
  });

  this.get('/rentals', function(db, request) {
    return {
      data: db.rentals.map(attrs => (
        {type: 'rentals', id: attrs.id, attributes: attrs }
      ))
    };
  });

  this.get('/rentals/:id', function(db, request) {
    let id = request.params.id;
    let rentalExtended = db.rental_extendeds.find(id);

    return {
      data: {
        type: 'rentals',
        id: id,
        attributes: rentalExtended
      }
    };
  });

  this.post('/rentals', function(db, request) {
    let attrs = JSON.parse(request.requestBody)['data'].attributes;
    let rental = db.rentals.insert({ name: attrs.name });
    let rentalExtended = db.rental_extendeds.insert(attrs);

    return {
      data: {
        type: 'rentals',
        id: rentalExtended.id,
        attributes: rentalExtended
      }
    };
  });

  this.put('/rentals/:id', function(db, request) {
    let id = request.params.id;
    let attrs = JSON.parse(request.requestBody)['data'].attributes;
    let rental = db.rentals.update(id, { name: attrs.name });
    let rentalExtended = db.rental_extendeds.update(id, attrs);

    return {
      data: {
        type: 'rentals',
        id: rentalExtended.id,
        attributes: rentalExtended
      }
    };
  });
}


text:
package com.sirweb.miro;

import com.sirweb.miro.ast.converter.MiroToCssConverter;
import com.sirweb.miro.ast.css.CssStylesheet;
import com.sirweb.miro.ast.miro.MiroStylesheet;
import com.sirweb.miro.exceptions.MiroException;
import com.sirweb.miro.export.CssExporter;
import com.sirweb.miro.export.Exporter;
import com.sirweb.miro.lexer.Tokenizer;
import com.sirweb.miro.parsing.Parser;
import com.sirweb.miro.util.Reader;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;

public class Miro {
    private MiroStylesheet stylesheet;
    public Miro (String content) throws MiroException {

        Tokenizer tokenizer = new Tokenizer(content);
        tokenizer.tokenize();
        Parser parser = new Parser(tokenizer);
        this.stylesheet = parser.parse();
    }

    public Miro (File file, File out) throws MiroException, IOException {
        Tokenizer tokenizer = new Tokenizer(new Reader(file.getAbsolutePath()).read());
        tokenizer.tokenize();
        Parser parser = new Parser(tokenizer, file.getAbsolutePath());
        this.stylesheet = parser.parse();

        MiroToCssConverter converter = new MiroToCssConverter(stylesheet);
        CssStylesheet cssStylesheet = converter.convert();
        Exporter exporter = new CssExporter(cssStylesheet);
        PrintStream ps = new PrintStream(out);
        exporter.export(ps);
        ps.close();
    }

    public String toCss () throws IOException {
        MiroToCssConverter converter = new MiroToCssConverter(stylesheet);
        CssStylesheet cssStylesheet = converter.convert();
        Exporter exporter = new CssExporter(cssStylesheet);
        //PrintWriter pw = new PrintWriter(new File("/Users/taminolaub/Desktop/test.css"));
        //PrintStream ps = new PrintStream(new File("/Users/taminolaub/Desktop/test.css"));
        //exporter.export(ps);
        //ps.close();
        return exporter.export();
    }
}


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ec2/model/Tag.h>
#include <utility>

namespace Aws
{
namespace EC2
{
namespace Model
{

  /**
   *
Contains the parameters for CreateTags.

See Also:
   AWS
   * API Reference

   */
  class AWS_EC2_API CreateTagsRequest : public EC2Request
  {
  public:
    CreateTagsRequest();
    Aws::String SerializePayload() const override;

  protected:
    void DumpBodyToUrl(Aws::Http::URI& uri ) const override;

  public:
    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline bool GetDryRun() const{ return m_dryRun; }

    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; }

    /**
     *
Checks whether you have the required permissions for the action, without
     * actually making the request, and provides an error response. If you have the
     * required permissions, the error response is DryRunOperation.
     * Otherwise, it is UnauthorizedOperation.

     */
    inline CreateTagsRequest& WithDryRun(bool value) { SetDryRun(value); return *this;}

    /**
     *
The IDs of one or more resources to tag. For example, ami-1a2b3c4d.

     */
    inline const Aws::Vector<Aws::String>& GetResources() const{ return m_resources; }

    /**
     *
The IDs of one or more resources to tag. For example, ami-1a2b3c4d.

     */
    inline void SetResources(const Aws::Vector<Aws::String>& value) { m_resourcesHasBeenSet = true; m_resources = value; }

    /**
     *
The IDs of one or more resources to tag. For example, ami-1a2b3c4d.

     */
    inline void SetResources(Aws::Vector<Aws::String>&& value) { m_resourcesHasBeenSet = true; m_resources = std::move(value); }

    /**
     *
The IDs of one or more resources to tag. For example, ami-1a2b3c4d.

     */
    inline CreateTagsRequest& WithResources(const Aws::Vector<Aws::String>& value) { SetResources(value); return *this;}

    /**
     *
The IDs of one or more resources to tag. For example, ami-1a2b3c4d.

     */
    inline CreateTagsRequest& WithResources(Aws::Vector<Aws::String>&& value) { SetResources(std::move(value)); return *this;}

    /**
     *
The IDs of one or more resources to tag. For example, ami-1a2b3c4d.

     */
    inline CreateTagsRequest& AddResources(const Aws::String& value) { m_resourcesHasBeenSet = true; m_resources.push_back(value); return *this; }

    /**
     *
The IDs of one or more resources to tag. For example, ami-1a2b3c4d.

     */
    inline CreateTagsRequest& AddResources(Aws::String&& value) { m_resourcesHasBeenSet = true; m_resources.push_back(std::move(value)); return *this; }

    /**
     *
The IDs of one or more resources to tag. For example, ami-1a2b3c4d.

     */
    inline CreateTagsRequest& AddResources(const char* value) { m_resourcesHasBeenSet = true; m_resources.push_back(value); return *this; }

    /**
     *
One or more tags. The value parameter is required, but if you
     * don't want the tag to have a value, specify the parameter with no value, and we
     * set the value to an empty string.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
One or more tags. The value parameter is required, but if you
     * don't want the tag to have a value, specify the parameter with no value, and we
     * set the value to an empty string.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tagsHasBeenSet = true; m_tags = value; }

    /**
     *
One or more tags. The value parameter is required, but if you
     * don't want the tag to have a value, specify the parameter with no value, and we
     * set the value to an empty string.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); }

    /**
     *
One or more tags. The value parameter is required, but if you
     * don't want the tag to have a value, specify the parameter with no value, and we
     * set the value to an empty string.

     */
    inline CreateTagsRequest& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
One or more tags. The value parameter is required, but if you
     * don't want the tag to have a value, specify the parameter with no value, and we
     * set the value to an empty string.

     */
    inline CreateTagsRequest& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
One or more tags. The value parameter is required, but if you
     * don't want the tag to have a value, specify the parameter with no value, and we
     * set the value to an empty string.

     */
    inline CreateTagsRequest& AddTags(const Tag& value) { m_tagsHasBeenSet = true; m_tags.push_back(value); return *this; }

    /**
     *
One or more tags. The value parameter is required, but if you
     * don't want the tag to have a value, specify the parameter with no value, and we
     * set the value to an empty string.

     */
    inline CreateTagsRequest& AddTags(Tag&& value) { m_tagsHasBeenSet = true; m_tags.push_back(std::move(value)); return *this; }

  private:
    bool m_dryRun;
    bool m_dryRunHasBeenSet;
    Aws::Vector<Aws::String> m_resources;
    bool m_resourcesHasBeenSet;
    Aws::Vector<Tag> m_tags;
    bool m_tagsHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
package kikaha.core.modules.security;

import lombok.RequiredArgsConstructor;

/**
 * The AuthenticationOutcome is used by an AuthenticationMechanism (or IdentityManager) to indicate the outcome of the call to authenticate, the
 * overall authentication process will onFinish used this along with the current AuthenticationState to decide how to proceed
 * with the current request.
 */
@RequiredArgsConstructor
public enum AuthenticationOutcome {

    /**
     * Based on the current request the mechanism has successfully performed authentication.
     */
    AUTHENTICATED,

    /**
     * The mechanism attempted authentication but it did not complete, this could either be due to a failure validating the
     * tokens from the client or it could be due to the mechanism requiring at least one additional round trip with the
     * client - either way the request will return challenges to the client.
     */
    NOT_AUTHENTICATED,

    /**
     * The mechanism did not attempt authentication on this request, most likely due to not discovering any applicable
     * security tokens for this mechanisms in the request.
     */
    NOT_ATTEMPTED;
}


text:
package org.vash.vate.startup;

import org.vash.vate.VT;
import org.vash.vate.client.VTClient;
import org.vash.vate.console.VTConsole;
import org.vash.vate.help.VTHelpManager;
import org.vash.vate.server.VTServer;

public final class VTStandardStart
{
  private static String option;

  public static final void main(String[] args)
  {
    //System.setProperty("java.awt.headless", "true");
    VTConsole.setLanterna(true);
    VTConsole.setGraphical(false);
    VTConsole.setRemoteIcon(true);
    if (args.length == 0)
    {
      VTConsole.initialize();
      VTConsole.clear();
      VTConsole.setTitle("Variable-Terminal " + VT.VT_VERSION + " - Console");
      VTConsole.print("VT>Variable-Terminal " + VT.VT_VERSION + "\n" +
      "VT>Copyright (c) " + VT.VT_YEAR + " - wknishio@gmail.com\n" +
      "VT>This software is under MIT license, see license.txt!\n" +
      "VT>This software comes with no warranty, use at your own risk!\n");
      VTConsole.print("VT>Enter module(client as C or server as S, default:C):");
      if (VTConsole.isGraphical())
      {
        VTGraphicalStartDialog dialog = new VTGraphicalStartDialog(VTConsole.getFrame());
        dialog.setVisible(true);
        if (dialog.getMode() == 1)
        {
          try
          {
            VTClient client = new VTClient();
            // client.initialize();
            // client.configure();
            client.start();
            return;
          }
          catch (Throwable e)
          {

          }
        }
        else if (dialog.getMode() == 2)
        {
          try
          {
            VTServer server = new VTServer();
            server.setDaemon(false);
            // server.initialize();
            // server.configure();
            server.start();
            return;
          }
          catch (Throwable e)
          {

          }
        }
      }
      try
      {
        option = VTConsole.readLine(true);
        if (option.toUpperCase().startsWith("S"))
        {
          VTServer server = new VTServer();
          server.setDaemon(false);
          // server.initialize();
          // server.configure();
          server.start();
        }
        else if (option != null)
        {
          VTClient client = new VTClient();
          // client.initialize();
          // client.configure();
          client.start();
        }
        else
        {
          System.exit(0);
        }
      }
      catch (Throwable e)
      {
        System.exit(0);
      }
    }
    else
    {
      int type = 0;
      for (int i = 0; i < args.length; i++)
      {
        if ("-C".equalsIgnoreCase(args[i]))
        {
          type = 1;
        }
        if ("-S".equalsIgnoreCase(args[i]))
        {
          type = 2;
        }
        if ("-D".equalsIgnoreCase(args[i]))
        {
          type = 3;
        }
        if ("-H".equalsIgnoreCase(args[i]))
        {
          type = 4;
        }
        if ("-A".equalsIgnoreCase(args[i]))
        {
          type = 5;
        }
      }
      if (type == 1)
      {
        VTClient client = new VTClient();
        try
        {
          client.parseParameters(args);
        }
        catch (Throwable e)
        {
          System.exit(-1);
        }
        // client.initialize();
        client.start();
      }
      else if (type == 2)
      {
        VTServer server = new VTServer();
        try
        {
          server.parseParameters(args);
        }
        catch (Throwable e)
        {
          System.exit(-1);
        }
        // server.initialize();
        server.setDaemon(false);
        server.start();
      }
      else if (type == 3)
      {
        VTConsole.setDaemon(true);
        VTServer server = new VTServer();
        try
        {
          server.parseParameters(args);
        }
        catch (Throwable e)
        {
          System.exit(-1);
        }
        // server.initialize();
        server.setDaemon(true);
        server.start();
      }
      else if (type == 4)
      {
        VTConsole.initialize();
        VTConsole.clear();
        VTConsole.setTitle("Variable-Terminal " + VT.VT_VERSION + " - Console");
        // VTConsole.print(VTHelpManager.printApplicationParametersHelp());
        VTConsole.print(VTHelpManager.printGeneralModeParameterHelp());
        VTConsole.print(VTHelpManager.printConnnectionParametersHelp());
        if (VTConsole.isGraphical())
        {
          try
          {
            VTConsole.readLine();
          }
          catch (Throwable e)
          {

          }
        }
        // VTConsole.println("VT>Invalid parameter syntax!" + "\nVT>Mode parameter:" +
        // "\nVT>c(client)|s(server)|d(daemon)" + "\nVT>Host parameter:" +
        // "\nVT>[connectionhost/]connectionport[;natport]" + "\nVT>Settings file
        // parameter:" + "\nVT>settingsfile" + "\nVT>Optional parameters:" +
        // "\nVT>[login/password]" + "\nVT>[encryptiontype;encryptionpassword]" +
        // "\nVT>[proxytype/proxyhost/proxyport[/proxyuser/proxypassword]]" +
        // "\nVT>[sessionslimit]");
        System.exit(0);
      }
      else if (type == 5)
      {
        VTClient client = new VTClient();
        try
        {
          client.parseParameters(args);
        }
        catch (Throwable e)
        {
          System.exit(-1);
        }
        client.setDaemon(true);
        // client.initialize();
        client.start();
      }
      else
      {
        VTConsole.initialize();
        VTConsole.clear();
        VTConsole.setTitle("Variable-Terminal " + VT.VT_VERSION + " - Console");
        VTConsole.print("VT>Variable-Terminal " + VT.VT_VERSION + "\n" +
        "VT>Copyright (c) " + VT.VT_YEAR + " - wknishio@gmail.com\n" +
        "VT>This software is under MIT license, see license.txt!\n" +
        "VT>This software comes with no warranty, use at your own risk!\n");
        VTConsole.print("VT>Enter module(client as C or server as S, default:C):");
        if (VTConsole.isGraphical())
        {
          VTGraphicalStartDialog dialog = new VTGraphicalStartDialog(VTConsole.getFrame());
          dialog.setVisible(true);
          if (dialog.getMode() == 1)
          {
            try
            {
              VTClient client = new VTClient();
              // client.initialize();
              // client.configure();
              try
              {
                client.parseParameters(args);
              }
              catch (Throwable e)
              {

              }
              client.start();
              return;
            }
            catch (Throwable e)
            {
              // e.printStackTrace();
            }
          }
          else if (dialog.getMode() == 2)
          {
            try
            {
              VTServer server = new VTServer();
              server.setDaemon(false);
              // server.initialize();
              // server.configure();
              try
              {
                server.parseParameters(args);
              }
              catch (Throwable e)
              {

              }
              server.start();
              return;
            }
            catch (Throwable e)
            {
              // e.printStackTrace();
            }
          }
        }
        try
        {
          option = VTConsole.readLine(true);
          if (option.toUpperCase().startsWith("S"))
          {
            VTServer server = new VTServer();
            server.setDaemon(false);
            try
            {
              server.parseParameters(args);
            }
            catch (Throwable e)
            {

            }
            // server.initialize();
            // server.configure();
            server.start();
          }
          else
          {
            VTClient client = new VTClient();
            try
            {
              client.parseParameters(args);
            }
            catch (Throwable e)
            {

            }
            // client.initialize();
            // client.configure();
            client.start();
          }
        }
        catch (Throwable e)
        {
          System.exit(0);
        }
      }
    }
  }
}


text:
#ifndef TEE_API_PRIVATE
#define TEE_API_PRIVATE

#include <tee_api_types.h>
#include <utee_types.h>

void __utee_from_attr(struct utee_attribute *ua, const TEE_Attribute *attrs,
			uint32_t attr_count);

void __utee_from_param(struct utee_params *up, uint32_t param_types,
			const TEE_Param params[TEE_NUM_PARAMS]);

void __utee_to_param(TEE_Param params[TEE_NUM_PARAMS],
			uint32_t *param_types, const struct utee_params *up);

void __utee_entry(unsigned long func, unsigned long session_id,
			struct utee_params *up, unsigned long cmd_id);

#endif /*TEE_API_PRIVATE*/


text:
module API
  module V1
    # Concern for declaration of ordering parameters.
    #
    # @example
    #   class ApiResource < Grape::API
    #     include OrderingParams
    #
    #     params do
    #       use :ordering
    #     end
    #   end
    module OrderingParams
      extend ActiveSupport::Concern

      included do
        helpers do
          params :ordering do
            optional :sort_attr, type: String, default: :id, desc: "Current page number"
            optional :sort_order, type: String, default: :asc, desc: "Number of items per page"
          end
        end
      end
    end
  end
end


text:
package com.gs.fw.common.freyaxml.test;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

import com.gs.fw.common.freyaxml.test.gsglui.layout.GsGluiLayoutMarshaller;
import com.gs.fw.common.freyaxml.test.gsglui.layout.GsGluiLayoutUnmarshaller;
import org.junit.Assert;
import org.junit.Test;

public class GsGluiLayoutTest
{
    @Test
    public void testAllFiles() throws IOException
    {
        File dir = new File("./src/test/testdata/gs-glui");
        File[] files = dir.listFiles();
        Assert.assertTrue(files.length > 0);
        long start = System.currentTimeMillis();
        for(File f: files)
        {
            if (f.getName().endsWith(".gml2"))
            {
                new GsGluiLayoutUnmarshaller().parse(f.getCanonicalPath());
            }
        }
        System.out.println("took " + (System.currentTimeMillis() - start) + " ms");
    }

    @Test
    public void testRoundTripFiles() throws Exception
    {
        File dir = new File("./src/test/testdata/gs-glui");
        File[] files = dir.listFiles();
        Assert.assertTrue(files.length > 0);
        long start = System.currentTimeMillis();
        for(File f: files)
        {
            if (f.getName().endsWith(".gml2"))
            {
                Object parsed = new GsGluiLayoutUnmarshaller().parse(f.getCanonicalPath());
                StringBuilder marshalled = marshall(parsed);
                Object parsedAgain = parse(marshalled, f.getName());
                StringBuilder marshalledAgain = marshall(parsedAgain);
                Assert.assertEquals(marshalled.toString(), marshalledAgain.toString());
            }
        }
        System.out.println("took "+(System.currentTimeMillis() - start)+" ms");
    }

    private Object parse(StringBuilder marshalled, String originalFilename) throws Exception
    {
        try
        {
            return new GsGluiLayoutUnmarshaller().parse(new ByteArrayInputStream(marshalled.toString().getBytes()), "remarshalled "+originalFilename);
        }
        catch (Exception e)
        {
            System.out.println(marshalled);
            throw e;
        }
    }

    public StringBuilder marshall(Object parsed) throws Exception
    {
        GsGluiLayoutMarshaller marshaller = new GsGluiLayoutMarshaller();
        marshaller.setIndent(true);
        StringBuilder builder = new StringBuilder();
        Method method = GsGluiLayoutMarshaller.class.getMethod("marshall", Appendable.class, parsed.getClass());
        method.invoke(marshaller, builder, parsed);
        return builder;
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('taxbrain', '0086_auto_20150314_2208'),
    ]

    operations = [
        migrations.RenameField(
            model_name='taxsaveinputs',
            old_name='qualify_number_child',
            new_name='_ACTC_ChildNum',
        ),
        migrations.RenameField(
            model_name='taxsaveinputs',
            old_name='additional_child_rate',
            new_name='_ACTC_rt',
        ),
        migrations.RenameField(
            model_name='taxsaveinputs',
            old_name='child_max_credit',
            new_name='_CTC_c',
        ),
        migrations.RenameField(
            model_name='taxsaveinputs',
            old_name='child_phase_out_rate',
            new_name='_CTC_prt',
        ),
        migrations.RenameField(
            model_name='taxsaveinputs',
            old_name='child_phase_out_threshold_single',
            new_name='_CTC_ps_0',
        ),
        migrations.RenameField(
            model_name='taxsaveinputs',
            old_name='child_phase_out_threshold_jointly',
            new_name='_CTC_ps_1',
        ),
        migrations.RenameField(
            model_name='taxsaveinputs',
            old_name='child_phase_out_threshold_head',
            new_name='_CTC_ps_2',
        ),
        migrations.RenameField(
            model_name='taxsaveinputs',
            old_name='child_phase_out_threshold_separately',
            new_name='_CTC_ps_3',
        ),
    ]


text:
package org.xmlcml.ami2;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.junit.Ignore;
import org.junit.Test;
import org.xmlcml.ami2.plugins.AMIArgProcessor;
import org.xmlcml.ami2.plugins.gene.GenePlugin;
import org.xmlcml.ami2.plugins.identifier.IdentifierPlugin;
import org.xmlcml.ami2.plugins.regex.RegexPlugin;
import org.xmlcml.ami2.plugins.species.SpeciesPlugin;
import org.xmlcml.ami2.plugins.word.WordArgProcessor;
import org.xmlcml.ami2.plugins.word.WordPlugin;

public class TutorialTest {

	@Test
	public void testSpecies() throws Exception {
		FileUtils.copyDirectory(new File(AMIFixtures.TEST_AMI_DIR, "tutorial/plos10"), new File("target/species10"));
		String args = "-q target/species10 -i scholarly.html --sp.species --context 35 50 --sp.type binomial genus genussp";
		SpeciesPlugin speciesPlugin = new SpeciesPlugin(args);
		speciesPlugin.runAndOutput();
		AMIFixtures.compareExpectedAndResults(new File(AMIFixtures.TEST_AMI_DIR, "tutorial/plos10/e0115544"),
				new File("target/species10/e0115544"), "species/binomial", AMIFixtures.RESULTS_XML);
	}

	@Test
	@Ignore // not working
	public void testSpeciesLookup() throws Exception {
		FileUtils.copyDirectory(new File("src/test/resources/org/xmlcml/ami2/tutorial/plos10"), new File("target/specieslook10"));
		String args = "-q target/specieslook10 -i scholarly.html --sp.species --context 35 50 --sp.type binomial genus genussp --lookup wikipedia genbank";
		SpeciesPlugin speciesPlugin = new SpeciesPlugin(args);
		speciesPlugin.runAndOutput();

	}

	@Test
	// FIXME
	public void testRegex() throws Exception {
		FileUtils.copyDirectory(new File("src/test/resources/org/xmlcml/ami2/tutorial/plos10"), new File("target/regex10"));
		String args = "-q target/regex10/ -i scholarly.html --context 35 50 --r.regex regex/consort0.xml";
		RegexPlugin regexPlugin = new RegexPlugin(args);
		regexPlugin.runAndOutput();
		/** omit as slightly different outout.
		Fixtures.compareExpectedAndResults(new File(Fixtures.TEST_AMI_DIR, "tutorial/plos10/e0115544"),
				new File("target/regex10/e0115544"), "regex/consort0", Fixtures.RESULTS_XML);
				*/
	}

	@Test
	public void testIdentifier() throws Exception {
		FileUtils.copyDirectory(new File("src/test/resources/org/xmlcml/ami2/tutorial/plos10"), new File("target/ident10"));
		String args = "-q target/ident10/ -i scholarly.html --context 35 50 --id.identifier --id.regex regex/identifiers.xml --id.type bio.ena";
		IdentifierPlugin identifierPlugin = new IdentifierPlugin(args);
		identifierPlugin.runAndOutput();
		AMIFixtures.compareExpectedAndResults(new File(AMIFixtures.TEST_AMI_DIR, "tutorial/plos10/e0115544"),
				new File("target/ident10/e0115544"), "identifier/bio.ena", AMIFixtures.RESULTS_XML);

	}

	@Test
	public void testIdentifierClin() throws Exception {
		FileUtils.copyDirectory(new File("src/test/resources/org/xmlcml/ami2/tutorial/plos10"), new File("target/clin10"));
		String args = "-q target/clin10/ -i scholarly.html --context 35 50 --id.identifier --id.regex regex/identifiers.xml --id.type clin.nct clin.isrctn";
		IdentifierPlugin identifierPlugin = new IdentifierPlugin(args);
		identifierPlugin.runAndOutput();
		AMIFixtures.compareExpectedAndResults(new File(AMIFixtures.TEST_AMI_DIR, "tutorial/plos10/e0115544"),
				new File("target/clin10/e0115544"), "identifier/clin.nct", AMIFixtures.RESULTS_XML);
	}

	@Test
	// FIXME

	public void testBagOfWords() throws Exception {
		FileUtils.copyDirectory(new File("src/test/resources/org/xmlcml/ami2/tutorial/plos10"), new File("target/word10"));
		String args = "-q target/word10/"
				+ " -i scholarly.html"
				+ " --context 35 50"
				+ " --w.words wordFrequencies"
				+ " --w.stopwords /org/xmlcml/ami2/plugins/word/stopwords.txt";
		WordPlugin wordPlugin = new WordPlugin(args);
		wordPlugin.runAndOutput();
		AMIFixtures.compareExpectedAndResults(new File(AMIFixtures.TEST_AMI_DIR, "tutorial/plos10/e0115544"),
				new File("target/word10/e0115544"), "word/frequencies", AMIFixtures.RESULTS_XML);
	}

	@Test
	// FIXME

	public void testBagOfWordsNatureNano() throws Exception {
		FileUtils.copyDirectory(new File("src/test/resources/org/xmlcml/ami2/nature/nnano"), new File("target/nature/nnano"));
		String args = "-q target/nature/nnano/"
				+ " -i scholarly.html"
				+ " --context 35 50"
				+ " --w.words wordFrequencies"
				+ " --w.stopwords /org/xmlcml/ami2/plugins/word/stopwords.txt";
		WordPlugin wordPlugin = new WordPlugin(args);
		wordPlugin.runAndOutput();
	}

	@Test
	public void testGene() throws Exception {
		FileUtils.copyDirectory(new File("src/test/resources/org/xmlcml/ami2/tutorial/plos10"), new File("target/gene10"));
		String args = "-q target/gene10/ -i scholarly.html --context 35 50 --g.gene --g.type human mouse";
		GenePlugin genePlugin = new GenePlugin(args);
		genePlugin.runAndOutput();
		AMIFixtures.compareExpectedAndResults(new File(AMIFixtures.TEST_AMI_DIR, "tutorial/plos10/e0115544"),
				new File("target/gene10/e0115544"), "gene/human", AMIFixtures.RESULTS_XML);

	}

	@Test
	public void testNorma() throws IOException {
			FileUtils.copyDirectory(new File("src/test/resources/org/xmlcml/ami2/tutorial/plos10"), new File("target/word10a"));
			String args = "-q target/word10a/"
					+ " -i fulltext.xml"
					+ " --w.words wordFrequencies"
					+ " -o scholarly.html";
			AMIArgProcessor amiArgProcessor = new WordArgProcessor(args);
			amiArgProcessor.runAndOutput();
	}
}


text:
namespace JSON
{
//#####################################################################################################################
    ArrayBuilder::ArrayBuilder(JSON::StringificationOptions options)
        : result_{}
        , fresh_{}
        , options_{std::move(options)}
    {
        result_ << '[';
    }
//---------------------------------------------------------------------------------------------------------------------
    void ArrayBuilder::comma()
    {
        if (!fresh_)
        {
            result_ << ",";
        }
        else
            fresh_ = false;
    }
//---------------------------------------------------------------------------------------------------------------------
    void ArrayBuilder::setOptions(JSON::StringificationOptions options)
    {
        options_ = options;
    }
//---------------------------------------------------------------------------------------------------------------------
    JSON::StringificationOptions& ArrayBuilder::getOptions()
    {
        return options_;
    }
//#####################################################################################################################
    ArrayReader::ArrayReader(PropertyTree const& tree, std::string const& path, JSON::ParsingOptions options)
        : name_{path}
        , options_{std::move(options)}
    {
        tree_.tree = tree.tree.get_child (path);
        reset();
    }
//---------------------------------------------------------------------------------------------------------------------
    ArrayReader::ArrayReader(PropertyTree const& tree, JSON::ParsingOptions options)
        : name_{}
        , options_{std::move(options)}
    {
        tree_.tree = tree.tree.get_child ("");
        reset();
    }
//---------------------------------------------------------------------------------------------------------------------
    ArrayReader::operator bool() const
    {
        return iter_ != tree_.tree.end();
    }
//---------------------------------------------------------------------------------------------------------------------
    void ArrayReader::reset()
    {
        iter_ = tree_.tree.begin();
    }
//---------------------------------------------------------------------------------------------------------------------
    void ArrayReader::setOptions(JSON::ParsingOptions options)
    {
        options_ = options;
    }
//---------------------------------------------------------------------------------------------------------------------
    JSON::ParsingOptions& ArrayReader::getOptions()
    {
        return options_;
    }
//#####################################################################################################################
}


text:
package com.thinkaurelius.titan.diskstorage;

import java.nio.ByteBuffer;

/**
 * An entry is the primitive persistence unit used in the graph database middleware.
 *
 * An entry consists of a column and value both of which are general {@link java.nio.ByteBuffer}s.
 *
 * @author	Matthias Bröcheler (me@matthiasb.com);
 *
 */
public class Entry {

	private final ByteBuffer column;
	private final ByteBuffer value;

	public Entry(ByteBuffer column, ByteBuffer value) {
		assert column!=null;
		this.column=column;
		this.value=value;
	}

	/**
	 * Returns the column ByteBuffer of this entry.
	 *
	 * @return Column ByteBuffer
	 */
	public ByteBuffer getColumn() {
		return column;
	}

	/**
	 * Returns the value ByteBuffer of this entry.
	 *
	 * @return Value ByteBuffer
	 */
	public ByteBuffer getValue() {
		return value;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((column == null) ? 0 : column.hashCode());
		result = prime * result + ((value == null) ? 0 : value.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Entry other = (Entry) obj;
		if (column == null) {
			if (other.column != null)
				return false;
		} else if (!column.equals(other.column))
			return false;
		if (value == null) {
			if (other.value != null)
				return false;
		} else if (!value.equals(other.value))
			return false;
		return true;
	}
}


text:
package org.gemini.markdown.syntax;

import java.util.regex.Pattern;

/**
 * Created by geminiwen on 15/3/14.
 */
public class SyntaxPattern {
    public static Pattern MarkdownSyntaxHeaders = Pattern.compile("(?:^|\\n)(#+ +.+)", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxLinks = Pattern.compile("\\[([^\\[]+)\\]\\(([^\\)]+)\\)", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxBold = Pattern.compile("(\\*\\*|__)(.*?)\\1", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxItalic = Pattern.compile("\\*[^*]+\\*", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxEmphasis = Pattern.compile("\\s(\\*|_)(.*?)\\1\\s", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxDeletions = Pattern.compile("~~(.*?)~~", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxQuotes = Pattern.compile(":\"(.*?)\":", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxCodeBlock = Pattern.compile("```([\\s\\S]*?)```", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxInlineCode = Pattern.compile("`[^`\\s]+`", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxBlockquotes = Pattern.compile("\n(>|>)(.*)", Pattern.CASE_INSENSITIVE);
    public static Pattern MarkdownSyntaxULLists = Pattern.compile("^\\*([^\\*]*)", Pattern.MULTILINE);
    public static Pattern MarkdownSyntaxOLLists = Pattern.compile("^[0-9]+\\.(.*)", Pattern.MULTILINE);
}


text:
#ifndef __CC_EGLVIEWIMPL_WINRT_H__
#define __CC_EGLVIEWIMPL_WINRT_H__

#include "CCStdC.h"
#include "platform/CCCommon.h"
#include "platform/CCGLView.h"
#include "InputEvent.h"

#include <agile.h>

#include <wrl/client.h>
#include <d3d11_1.h>
#include <concurrent_queue.h>

#include <agile.h>
#include <DirectXMath.h>

#include <EGL/egl.h>

NS_CC_BEGIN

class GLViewImpl;

class CC_DLL GLViewImpl : public GLView
{
public:
    static GLViewImpl* create(const std::string& viewName);

    /* override functions */
    virtual bool isOpenGLReady();
    virtual void end();
    virtual void swapBuffers();
    virtual void setViewPortInPoints(float x , float y , float w , float h);
    virtual void setScissorInPoints(float x , float y , float w , float h);
    const Mat4& getOrientationMatrix() const;
    const Mat4& getReverseOrientationMatrix () const {return m_reverseOrientationMatrix;};

    Windows::Graphics::Display::DisplayOrientations getDeviceOrientation() {return m_orientation;};
    Size getRenerTargetSize() const { return Size(m_width, m_height); }

    virtual void setIMEKeyboardState(bool bOpen);
    virtual void setIMEKeyboardState(bool bOpen, std::string str);
    Platform::String^ stringToPlatformString(std::string strSrc);
    void ShowKeyboard(Windows::Foundation::Rect r);
    void HideKeyboard(Windows::Foundation::Rect r);

    // WP8 XAML app
    virtual bool Create(EGLDisplay eglDisplay, EGLContext eglContext, EGLSurface eglSurface, float width, float height
        ,Windows::Graphics::Display::DisplayOrientations orientation);
    virtual void UpdateDevice(EGLDisplay eglDisplay, EGLContext eglContext, EGLSurface eglSurface);

	void OnPointerPressed(Windows::UI::Core::PointerEventArgs^ args);
	void OnPointerMoved(Windows::UI::Core::PointerEventArgs^ args);
	void OnPointerReleased(Windows::UI::Core::PointerEventArgs^ args);
	void OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
	void OnPointerWheelChanged(Windows::UI::Core::CoreWindow^, Windows::UI::Core::PointerEventArgs^ args);
	void OnPointerMoved(Windows::UI::Core::CoreWindow^, Windows::UI::Core::PointerEventArgs^ args);
	void OnPointerReleased(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
	void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
	void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
	void OnResuming(Platform::Object^ sender, Platform::Object^ args);
	void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
    void OnBackKeyPress();

    void QueueBackKeyPress();
    void QueuePointerEvent(PointerEventType type, Windows::UI::Core::PointerEventArgs^ args);
    void GLViewImpl::QueueEvent(std::shared_ptr<InputEvent>& event);

    void SetXamlEventDelegate(Cocos2dEventDelegate^ delegate) { m_delegate = delegate; };
    void SetXamlMessageBoxDelegate(Cocos2dMessageBoxDelegate^ delegate) { m_messageBoxDelegate = delegate; };
    void SetXamlEditBoxDelegate(Cocos2dEditBoxDelegate^ delegate) { m_editBoxDelegate = delegate; };

    bool ShowMessageBox(Platform::String^ title, Platform::String^ message);
    bool OpenXamlEditBox(Platform::String^ strPlaceHolder, Platform::String^ strText, int maxLength, int inputMode, int inputFlag, Windows::Foundation::EventHandler<Platform::String^>^ receiveHandler);

	int Run();
	void Render();

    void resize(int width, int height);

	float getFrameZoomFactor();
    void centerWindow();

 	void UpdateOrientation(Windows::Graphics::Display::DisplayOrientations orientation);
 	void UpdateForWindowSizeChange(float width, float height);

    // static function
    /**
    @brief    get the shared main open gl window
    */
	static GLViewImpl* sharedOpenGLView();

    void ProcessEvents();
    void AddPointerEvent(PointerEventType type, Windows::UI::Core::PointerEventArgs^ args);

protected:
    GLViewImpl();
    virtual ~GLViewImpl();

    bool initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor);
    bool initWithFullScreen(const std::string& viewName);

    /*
     * Set zoom factor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop.
     */
    void setFrameZoomFactor(float zoomFactor);

    inline bool isRetina() { return _isRetina; };

    float _frameZoomFactor;
    bool _supportTouch;
    bool _isRetina;

private:
    CC_DISALLOW_COPY_AND_ASSIGN(GLViewImpl);

	void OnRendering();
	void UpdateWindowSize();
    void UpdateOrientationMatrix();

    cocos2d::Vec2 TransformToOrientation(Windows::Foundation::Point point);
 	cocos2d::Vec2  GetPoint(Windows::UI::Core::PointerEventArgs^ args);

    Windows::Foundation::Rect m_windowBounds;
	Windows::Foundation::EventRegistrationToken m_eventToken;
	Windows::Foundation::Point m_lastPoint;

    float m_width;
    float m_height;

    Windows::Graphics::Display::DisplayOrientations m_orientation;
	Windows::Foundation::Rect m_keyboardRect;

	bool m_lastPointValid;
	bool m_windowClosed;
	bool m_windowVisible;
    Mat4 m_orientationMatrix;
    Mat4 m_reverseOrientationMatrix;

    bool m_running;
	bool m_initialized;

	Microsoft::WRL::ComPtr<IWinrtEglWindow> m_eglWindow;

	EGLDisplay m_eglDisplay;
	EGLContext m_eglContext;
	EGLSurface m_eglSurface;
    Cocos2dEventDelegate^ m_delegate;
    Cocos2dMessageBoxDelegate^ m_messageBoxDelegate;
    Cocos2dEditBoxDelegate^ m_editBoxDelegate;

    Concurrency::concurrent_queue<std::shared_ptr<InputEvent>> mInputEvents;
};

NS_CC_END

#endif    // end of __CC_EGLVIEWIMPL_WINRT_H__


text:
package bleve

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/blevesearch/bleve/analysis"
	"github.com/blevesearch/bleve/search"
	"github.com/blevesearch/bleve/search/query"
)

type numericRange struct {
	Name string   `json:"name,omitempty"`
	Min  *float64 `json:"min,omitempty"`
	Max  *float64 `json:"max,omitempty"`
}

type dateTimeRange struct {
	Name        string    `json:"name,omitempty"`
	Start       time.Time `json:"start,omitempty"`
	End         time.Time `json:"end,omitempty"`
	startString *string
	endString   *string
}

func (dr *dateTimeRange) ParseDates(dateTimeParser analysis.DateTimeParser) (start, end time.Time) {
	start = dr.Start
	if dr.Start.IsZero() && dr.startString != nil {
		s, err := dateTimeParser.ParseDateTime(*dr.startString)
		if err == nil {
			start = s
		}
	}
	end = dr.End
	if dr.End.IsZero() && dr.endString != nil {
		e, err := dateTimeParser.ParseDateTime(*dr.endString)
		if err == nil {
			end = e
		}
	}
	return start, end
}

func (dr *dateTimeRange) UnmarshalJSON(input []byte) error {
	var temp struct {
		Name  string  `json:"name,omitempty"`
		Start *string `json:"start,omitempty"`
		End   *string `json:"end,omitempty"`
	}

	err := json.Unmarshal(input, &temp)
	if err != nil {
		return err
	}

	dr.Name = temp.Name
	if temp.Start != nil {
		dr.startString = temp.Start
	}
	if temp.End != nil {
		dr.endString = temp.End
	}

	return nil
}

func (dr *dateTimeRange) MarshalJSON() ([]byte, error) {
	rv := map[string]interface{}{
		"name":  dr.Name,
		"start": dr.Start,
		"end":   dr.End,
	}
	if dr.Start.IsZero() && dr.startString != nil {
		rv["start"] = dr.startString
	}
	if dr.End.IsZero() && dr.endString != nil {
		rv["end"] = dr.endString
	}
	return json.Marshal(rv)
}

// A FacetRequest describes a facet or aggregation
// of the result document set you would like to be
// built.
type FacetRequest struct {
	Size           int              `json:"size"`
	Field          string           `json:"field"`
	NumericRanges  []*numericRange  `json:"numeric_ranges,omitempty"`
	DateTimeRanges []*dateTimeRange `json:"date_ranges,omitempty"`
}

func (fr *FacetRequest) Validate() error {
	if len(fr.NumericRanges) > 0 && len(fr.DateTimeRanges) > 0 {
		return fmt.Errorf("facet can only conain numeric ranges or date ranges, not both")
	}

	nrNames := map[string]interface{}{}
	for _, nr := range fr.NumericRanges {
		if _, ok := nrNames[nr.Name]; ok {
			return fmt.Errorf("numeric ranges contains duplicate name '%s'", nr.Name)
		}
		nrNames[nr.Name] = struct{}{}
	}

	drNames := map[string]interface{}{}
	for _, dr := range fr.DateTimeRanges {
		if _, ok := drNames[dr.Name]; ok {
			return fmt.Errorf("date ranges contains duplicate name '%s'", dr.Name)
		}
		drNames[dr.Name] = struct{}{}
	}

	return nil
}

// NewFacetRequest creates a facet on the specified
// field that limits the number of entries to the
// specified size.
func NewFacetRequest(field string, size int) *FacetRequest {
	return &FacetRequest{
		Field: field,
		Size:  size,
	}
}

// AddDateTimeRange adds a bucket to a field
// containing date values.  Documents with a
// date value falling into this range are tabulated
// as part of this bucket/range.
func (fr *FacetRequest) AddDateTimeRange(name string, start, end time.Time) {
	if fr.DateTimeRanges == nil {
		fr.DateTimeRanges = make([]*dateTimeRange, 0, 1)
	}
	fr.DateTimeRanges = append(fr.DateTimeRanges, &dateTimeRange{Name: name, Start: start, End: end})
}

// AddNumericRange adds a bucket to a field
// containing numeric values.  Documents with a
// numeric value falling into this range are
// tabulated as part of this bucket/range.
func (fr *FacetRequest) AddNumericRange(name string, min, max *float64) {
	if fr.NumericRanges == nil {
		fr.NumericRanges = make([]*numericRange, 0, 1)
	}
	fr.NumericRanges = append(fr.NumericRanges, &numericRange{Name: name, Min: min, Max: max})
}

// FacetsRequest groups together all the
// FacetRequest objects for a single query.
type FacetsRequest map[string]*FacetRequest

func (fr FacetsRequest) Validate() error {
	for _, v := range fr {
		err := v.Validate()
		if err != nil {
			return err
		}
	}
	return nil
}

// HighlightRequest describes how field matches
// should be highlighted.
type HighlightRequest struct {
	Style  *string  `json:"style"`
	Fields []string `json:"fields"`
}

// NewHighlight creates a default
// HighlightRequest.
func NewHighlight() *HighlightRequest {
	return &HighlightRequest{}
}

// NewHighlightWithStyle creates a HighlightRequest
// with an alternate style.
func NewHighlightWithStyle(style string) *HighlightRequest {
	return &HighlightRequest{
		Style: &style,
	}
}

func (h *HighlightRequest) AddField(field string) {
	if h.Fields == nil {
		h.Fields = make([]string, 0, 1)
	}
	h.Fields = append(h.Fields, field)
}

// A SearchRequest describes all the parameters
// needed to search the index.
// Query is required.
// Size/From describe how much and which part of the
// result set to return.
// Highlight describes optional search result
// highlighting.
// Fields describes a list of field values which
// should be retrieved for result documents, provided they
// were stored while indexing.
// Facets describe the set of facets to be computed.
// Explain triggers inclusion of additional search
// result score explanations.
// Sort describes the desired order for the results to be returned.
//
// A special field named "*" can be used to return all fields.
type SearchRequest struct {
	Query            query.Query       `json:"query"`
	Size             int               `json:"size"`
	From             int               `json:"from"`
	Highlight        *HighlightRequest `json:"highlight"`
	Fields           []string          `json:"fields"`
	Facets           FacetsRequest     `json:"facets"`
	Explain          bool              `json:"explain"`
	Sort             search.SortOrder  `json:"sort"`
	IncludeLocations bool              `json:"includeLocations"`
}

func (r *SearchRequest) Validate() error {
	if srq, ok := r.Query.(query.ValidatableQuery); ok {
		err := srq.Validate()
		if err != nil {
			return err
		}
	}

	return r.Facets.Validate()
}

// AddFacet adds a FacetRequest to this SearchRequest
func (r *SearchRequest) AddFacet(facetName string, f *FacetRequest) {
	if r.Facets == nil {
		r.Facets = make(FacetsRequest, 1)
	}
	r.Facets[facetName] = f
}

// SortBy changes the request to use the requested sort order
// this form uses the simplified syntax with an array of strings
// each string can either be a field name
// or the magic value _id and _score which refer to the doc id and search score
// any of these values can optionally be prefixed with - to reverse the order
func (r *SearchRequest) SortBy(order []string) {
	so := search.ParseSortOrderStrings(order)
	r.Sort = so
}

// SortByCustom changes the request to use the requested sort order
func (r *SearchRequest) SortByCustom(order search.SortOrder) {
	r.Sort = order
}

// UnmarshalJSON deserializes a JSON representation of
// a SearchRequest
func (r *SearchRequest) UnmarshalJSON(input []byte) error {
	var temp struct {
		Q                json.RawMessage   `json:"query"`
		Size             *int              `json:"size"`
		From             int               `json:"from"`
		Highlight        *HighlightRequest `json:"highlight"`
		Fields           []string          `json:"fields"`
		Facets           FacetsRequest     `json:"facets"`
		Explain          bool              `json:"explain"`
		Sort             []json.RawMessage `json:"sort"`
		IncludeLocations bool              `json:"includeLocations"`
	}

	err := json.Unmarshal(input, &temp)
	if err != nil {
		return err
	}

	if temp.Size == nil {
		r.Size = 10
	} else {
		r.Size = *temp.Size
	}
	if temp.Sort == nil {
		r.Sort = search.SortOrder{&search.SortScore{Desc: true}}
	} else {
		r.Sort, err = search.ParseSortOrderJSON(temp.Sort)
		if err != nil {
			return err
		}
	}
	r.From = temp.From
	r.Explain = temp.Explain
	r.Highlight = temp.Highlight
	r.Fields = temp.Fields
	r.Facets = temp.Facets
	r.IncludeLocations = temp.IncludeLocations
	r.Query, err = query.ParseQuery(temp.Q)
	if err != nil {
		return err
	}

	if r.Size < 0 {
		r.Size = 10
	}
	if r.From < 0 {
		r.From = 0
	}

	return nil

}

// NewSearchRequest creates a new SearchRequest
// for the Query, using default values for all
// other search parameters.
func NewSearchRequest(q query.Query) *SearchRequest {
	return NewSearchRequestOptions(q, 10, 0, false)
}

// NewSearchRequestOptions creates a new SearchRequest
// for the Query, with the requested size, from
// and explanation search parameters.
// By default results are ordered by score, descending.
func NewSearchRequestOptions(q query.Query, size, from int, explain bool) *SearchRequest {
	return &SearchRequest{
		Query:   q,
		Size:    size,
		From:    from,
		Explain: explain,
		Sort:    search.SortOrder{&search.SortScore{Desc: true}},
	}
}

// IndexErrMap tracks errors with the name of the index where it occurred
type IndexErrMap map[string]error

// MarshalJSON seralizes the error into a string for JSON consumption
func (iem IndexErrMap) MarshalJSON() ([]byte, error) {
	tmp := make(map[string]string, len(iem))
	for k, v := range iem {
		tmp[k] = v.Error()
	}
	return json.Marshal(tmp)
}

func (iem IndexErrMap) UnmarshalJSON(data []byte) error {
	var tmp map[string]string
	err := json.Unmarshal(data, &tmp)
	if err != nil {
		return err
	}
	for k, v := range tmp {
		iem[k] = fmt.Errorf("%s", v)
	}
	return nil
}

// SearchStatus is a secion in the SearchResult reporting how many
// underlying indexes were queried, how many were successful/failed
// and a map of any errors that were encountered
type SearchStatus struct {
	Total      int         `json:"total"`
	Failed     int         `json:"failed"`
	Successful int         `json:"successful"`
	Errors     IndexErrMap `json:"errors,omitempty"`
}

// Merge will merge together multiple SearchStatuses during a MultiSearch
func (ss *SearchStatus) Merge(other *SearchStatus) {
	ss.Total += other.Total
	ss.Failed += other.Failed
	ss.Successful += other.Successful
	if len(other.Errors) > 0 {
		if ss.Errors == nil {
			ss.Errors = make(map[string]error)
		}
		for otherIndex, otherError := range other.Errors {
			ss.Errors[otherIndex] = otherError
		}
	}
}

// A SearchResult describes the results of executing
// a SearchRequest.
type SearchResult struct {
	Status   *SearchStatus                  `json:"status"`
	Request  *SearchRequest                 `json:"request"`
	Hits     search.DocumentMatchCollection `json:"hits"`
	Total    uint64                         `json:"total_hits"`
	MaxScore float64                        `json:"max_score"`
	Took     time.Duration                  `json:"took"`
	Facets   search.FacetResults            `json:"facets"`
}

func (sr *SearchResult) String() string {
	rv := ""
	if sr.Total > 0 {
		if sr.Request.Size > 0 {
			rv = fmt.Sprintf("%d matches, showing %d through %d, took %s\n", sr.Total, sr.Request.From+1, sr.Request.From+len(sr.Hits), sr.Took)
			for i, hit := range sr.Hits {
				rv += fmt.Sprintf("%5d. %s (%f)\n", i+sr.Request.From+1, hit.ID, hit.Score)
				for fragmentField, fragments := range hit.Fragments {
					rv += fmt.Sprintf("\t%s\n", fragmentField)
					for _, fragment := range fragments {
						rv += fmt.Sprintf("\t\t%s\n", fragment)
					}
				}
				for otherFieldName, otherFieldValue := range hit.Fields {
					if _, ok := hit.Fragments[otherFieldName]; !ok {
						rv += fmt.Sprintf("\t%s\n", otherFieldName)
						rv += fmt.Sprintf("\t\t%v\n", otherFieldValue)
					}
				}
			}
		} else {
			rv = fmt.Sprintf("%d matches, took %s\n", sr.Total, sr.Took)
		}
	} else {
		rv = "No matches"
	}
	if len(sr.Facets) > 0 {
		rv += fmt.Sprintf("Facets:\n")
		for fn, f := range sr.Facets {
			rv += fmt.Sprintf("%s(%d)\n", fn, f.Total)
			for _, t := range f.Terms {
				rv += fmt.Sprintf("\t%s(%d)\n", t.Term, t.Count)
			}
			if f.Other != 0 {
				rv += fmt.Sprintf("\tOther(%d)\n", f.Other)
			}
		}
	}
	return rv
}

// Merge will merge together multiple SearchResults during a MultiSearch
func (sr *SearchResult) Merge(other *SearchResult) {
	sr.Status.Merge(other.Status)
	sr.Hits = append(sr.Hits, other.Hits...)
	sr.Total += other.Total
	if other.MaxScore > sr.MaxScore {
		sr.MaxScore = other.MaxScore
	}
	sr.Facets.Merge(other.Facets)
}


text:
/*
 *  (c) 2017 Michael A. Beck, Sebastian Henningsen
 *  		disco | Distributed Computer Systems Lab
 *  		University of Kaiserslautern, Germany
 *  All Rights Reserved.
 *
 * This software is work in progress and is released in the hope that it will
 * be useful to the scientific community. It is provided "as is" without
 * express or implied warranty, including but not limited to the correctness
 * of the code or its suitability for any particular purpose.
 *
 * This software is provided under the MIT License, however, we would
 * appreciate it if you contacted the respective authors prior to commercial use.
 *
 * If you find our software useful, we would appreciate if you mentioned it
 * in any publication arising from the use of this software or acknowledge
 * our work otherwise. We would also like to hear of any fixes or useful
 */
package unikl.disco.calculator.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

/**
 * The main window of the GUI. This is where all the initialization and composition of
 * different components takes place.
 * @author Sebastian Henningsen
 */
public class MainWindow {

    private JFrame mainFrame;
    private MenuBar menuBar;
    private VertexTablePanel vertexTablePanel;
    private FlowTablePanel flowTablePanel;
    private ConsoleOutputPanel consolePanel;
    private GridBagLayout layoutManager;
    private JSplitPane horizontalSplitPane;
    private JSplitPane verticalSplitPane;
    private JSplitPane rightHorizontalSplitPane;
    private ControlPanel controllerPanel;
    private NetworkVisualizationPanel visPanel;

    /**
     * Creates all necessary components and adds them to the main JFrame.
     * Since this method contains Swing components, it should only be called inside
     * the event queue. For example (from {@link SNC}):
     * <code>Runnable runnable = new Runnable() {
            @Override
            public void run() {
                main.createGUI();
            }
        };
        EventQueue.invokeLater(runnable);
        </code>
     */
    public void createGUI() {
        mainFrame = new JFrame("Disco Stochastic Network Calculator");
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);

        menuBar = new MenuBar(this);
        mainFrame.setJMenuBar(menuBar.getMenuBar());

        horizontalSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true);
        mainFrame.add(horizontalSplitPane);
        verticalSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
        horizontalSplitPane.setBottomComponent(verticalSplitPane);

        vertexTablePanel = new VertexTablePanel();
        flowTablePanel = new FlowTablePanel();
        JPanel tables = new JPanel();
        tables.add(vertexTablePanel.getPanel());
        tables.add(flowTablePanel.getPanel());
        horizontalSplitPane.setTopComponent(tables);

        rightHorizontalSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true);
        verticalSplitPane.setBottomComponent(rightHorizontalSplitPane);

        consolePanel = new ConsoleOutputPanel();
        consolePanel.redirectOut();
        consolePanel.redirectErr(Color.RED);
        rightHorizontalSplitPane.setBottomComponent(consolePanel.getPanel());

        visPanel = new NetworkVisualizationPanel(new Dimension(350, 350));
        rightHorizontalSplitPane.setTopComponent(visPanel.getPanel());

        controllerPanel = new ControlPanel();
        verticalSplitPane.setTopComponent(controllerPanel.getPanel());

        // Layout Part: Set the Layout Manager and arrange the components
        layoutManager = new GridBagLayout();
        //mainFrame.setLayout(layoutManager);
        mainFrame.pack();
        mainFrame.setVisible(true);
    }

    /**
     * Closes the main window.
     */
    public void close() {
        mainFrame.dispose();
    }

    /**
     * Converts a map of {@link Displayable} elements to an array. This is used
     * to convert from the output of SNC to {@link JComboBox}.
     * @param <T>
     * @param map
     * @return
     */
    public static <T extends Displayable> Displayable[] convertDisplayables(Map<Integer, T> map) {
        Displayable[] selectables = new Displayable[map.size()];
        int counter = 0;
        for (Map.Entry<Integer, T> entry : map.entrySet()) {
            T val = entry.getValue();
            selectables[counter] = val;
            counter++;
        }
        return selectables;
    }
}


text:
@implementation GPUImageThresholdEdgeDetection

// Invert the colorspace for a sketch
NSString *const kGPUImageThresholdEdgeDetectionFragmentShaderString = SHADER_STRING
(
 precision highp float;

 varying vec2 textureCoordinate;
 varying vec2 leftTextureCoordinate;
 varying vec2 rightTextureCoordinate;

 varying vec2 topTextureCoordinate;
 varying vec2 topLeftTextureCoordinate;
 varying vec2 topRightTextureCoordinate;

 varying vec2 bottomTextureCoordinate;
 varying vec2 bottomLeftTextureCoordinate;
 varying vec2 bottomRightTextureCoordinate;

 uniform sampler2D inputImageTexture;
 uniform lowp float threshold;

 const highp vec3 W = vec3(0.2125, 0.7154, 0.0721);

 void main()
 {
     float bottomLeftIntensity = texture2D(inputImageTexture, bottomLeftTextureCoordinate).r;
     float topRightIntensity = texture2D(inputImageTexture, topRightTextureCoordinate).r;
     float topLeftIntensity = texture2D(inputImageTexture, topLeftTextureCoordinate).r;
     float bottomRightIntensity = texture2D(inputImageTexture, bottomRightTextureCoordinate).r;
     float leftIntensity = texture2D(inputImageTexture, leftTextureCoordinate).r;
     float rightIntensity = texture2D(inputImageTexture, rightTextureCoordinate).r;
     float bottomIntensity = texture2D(inputImageTexture, bottomTextureCoordinate).r;
     float topIntensity = texture2D(inputImageTexture, topTextureCoordinate).r;
     float h = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity;
     float v = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity;

     float mag = 1.0 - length(vec2(h, v));
     mag = step(threshold, mag);

     gl_FragColor = vec4(vec3(mag), 1.0);
 }
 );

#pragma mark -
#pragma mark Initialization and teardown

@synthesize threshold = _threshold;

- (id)init;
{
    if (!(self = [self initWithFragmentShaderFromString:kGPUImageThresholdEdgeDetectionFragmentShaderString]))
    {
		return nil;
    }

    thresholdUniform = [secondFilterProgram uniformIndex:@"threshold"];
    self.threshold = 0.9;

    return self;
}

#pragma mark -
#pragma mark Accessors

- (void)setThreshold:(CGFloat)newValue;
{
    _threshold = newValue;

    [self setFloat:_threshold forUniform:thresholdUniform program:secondFilterProgram];
}

@end


text:
package org.apache.flink.table.planner.plan.nodes.physical.stream

import org.apache.flink.api.dag.Transformation
import org.apache.flink.streaming.api.operators.KeyedProcessOperator
import org.apache.flink.streaming.api.transformations.OneInputTransformation
import org.apache.flink.table.api.config.ExecutionConfigOptions
import org.apache.flink.table.dataformat.BaseRow
import org.apache.flink.table.planner.calcite.FlinkTypeFactory
import org.apache.flink.table.planner.codegen.agg.AggsHandlerCodeGenerator
import org.apache.flink.table.planner.codegen.{CodeGeneratorContext, EqualiserCodeGenerator}
import org.apache.flink.table.planner.delegation.StreamPlanner
import org.apache.flink.table.planner.plan.PartialFinalType
import org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery
import org.apache.flink.table.planner.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.flink.table.planner.plan.rules.physical.stream.StreamExecRetractionRules
import org.apache.flink.table.planner.plan.utils.{AggregateInfoList, AggregateUtil, KeySelectorUtil, RelExplainUtil}
import org.apache.flink.table.runtime.operators.aggregate.{GroupAggFunction, MiniBatchGroupAggFunction}
import org.apache.flink.table.runtime.operators.bundle.KeyedMapBundleOperator
import org.apache.flink.table.runtime.types.LogicalTypeDataTypeConverter.fromDataTypeToLogicalType
import org.apache.flink.table.runtime.typeutils.BaseRowTypeInfo

import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rel.core.AggregateCall
import org.apache.calcite.rel.{RelNode, RelWriter}

import java.util

import scala.collection.JavaConversions._

/**
  * Stream physical RelNode for unbounded group aggregate.
  *
  * This node does support un-splittable aggregate function (e.g. STDDEV_POP).
  *
  * @see [[StreamExecGroupAggregateBase]] for more info.
  */
class StreamExecGroupAggregate(
    cluster: RelOptCluster,
    traitSet: RelTraitSet,
    inputRel: RelNode,
    outputRowType: RelDataType,
    val grouping: Array[Int],
    val aggCalls: Seq[AggregateCall],
    var partialFinalType: PartialFinalType = PartialFinalType.NONE)
  extends StreamExecGroupAggregateBase(cluster, traitSet, inputRel)
  with StreamExecNode[BaseRow] {

  val aggInfoList: AggregateInfoList = {
    val needRetraction = StreamExecRetractionRules.isAccRetract(getInput)
    val fmq = FlinkRelMetadataQuery.reuseOrCreate(cluster.getMetadataQuery)
    val monotonicity = fmq.getRelModifiedMonotonicity(this)
    val needRetractionArray = AggregateUtil.getNeedRetractions(
      grouping.length, needRetraction, monotonicity, aggCalls)
    AggregateUtil.transformToStreamAggregateInfoList(
      aggCalls,
      getInput.getRowType,
      needRetractionArray,
      needInputCount = needRetraction,
      isStateBackendDataViews = true)
  }

  override def producesUpdates = true

  override def needsUpdatesAsRetraction(input: RelNode) = true

  override def consumesRetractions = true

  override def producesRetractions: Boolean = false

  override def requireWatermark: Boolean = false

  override def deriveRowType(): RelDataType = outputRowType

  override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = {
    new StreamExecGroupAggregate(
      cluster,
      traitSet,
      inputs.get(0),
      outputRowType,
      grouping,
      aggCalls,
      partialFinalType)
  }

  override def explainTerms(pw: RelWriter): RelWriter = {
    val inputRowType = getInput.getRowType
    super.explainTerms(pw)
      .itemIf("groupBy",
        RelExplainUtil.fieldToString(grouping, inputRowType), grouping.nonEmpty)
      .itemIf("partialFinalType", partialFinalType, partialFinalType != PartialFinalType.NONE)
      .item("select", RelExplainUtil.streamGroupAggregationToString(
        inputRowType,
        getRowType,
        aggInfoList,
        grouping))
  }

  //~ ExecNode methods -----------------------------------------------------------

  override def getInputNodes: util.List[ExecNode[StreamPlanner, _]] = {
    getInputs.map(_.asInstanceOf[ExecNode[StreamPlanner, _]])
  }

  override def replaceInputNode(
      ordinalInParent: Int,
      newInputNode: ExecNode[StreamPlanner, _]): Unit = {
    replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
  }

  override protected def translateToPlanInternal(
      planner: StreamPlanner): Transformation[BaseRow] = {

    val tableConfig = planner.getTableConfig

    if (grouping.length > 0 && tableConfig.getMinIdleStateRetentionTime < 0) {
      LOG.warn("No state retention interval configured for a query which accumulates state. " +
        "Please provide a query configuration with valid retention interval to prevent excessive " +
        "state size. You may specify a retention time of 0 to not clean up the state.")
    }

    val inputTransformation = getInputNodes.get(0).translateToPlan(planner)
      .asInstanceOf[Transformation[BaseRow]]

    val outRowType = FlinkTypeFactory.toLogicalRowType(outputRowType)
    val inputRowType = FlinkTypeFactory.toLogicalRowType(getInput.getRowType)

    val generateRetraction = StreamExecRetractionRules.isAccRetract(this)
    val needRetraction = StreamExecRetractionRules.isAccRetract(getInput)

    val generator = new AggsHandlerCodeGenerator(
      CodeGeneratorContext(tableConfig),
      planner.getRelBuilder,
      inputRowType.getChildren,
      // TODO: heap state backend do not copy key currently, we have to copy input field
      // TODO: copy is not need when state backend is rocksdb, improve this in future
      // TODO: but other operators do not copy this input field.....
      copyInputField = true)

    if (needRetraction) {
      generator.needRetract()
    }

    val aggsHandler = generator
      .needAccumulate()
      .generateAggsHandler("GroupAggsHandler", aggInfoList)
    val accTypes = aggInfoList.getAccTypes.map(fromDataTypeToLogicalType)
    val aggValueTypes = aggInfoList.getActualValueTypes.map(fromDataTypeToLogicalType)
    val recordEqualiser = new EqualiserCodeGenerator(aggValueTypes)
      .generateRecordEqualiser("GroupAggValueEqualiser")
    val inputCountIndex = aggInfoList.getIndexOfCountStar

    val isMiniBatchEnabled = tableConfig.getConfiguration.getBoolean(
      ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ENABLED)

    val operator = if (isMiniBatchEnabled) {
      val aggFunction = new MiniBatchGroupAggFunction(
        aggsHandler,
        recordEqualiser,
        accTypes,
        inputRowType,
        inputCountIndex,
        generateRetraction)

      new KeyedMapBundleOperator(
        aggFunction,
        AggregateUtil.createMiniBatchTrigger(tableConfig))
    } else {
      val aggFunction = new GroupAggFunction(
        tableConfig.getMinIdleStateRetentionTime,
        tableConfig.getMaxIdleStateRetentionTime,
        aggsHandler,
        recordEqualiser,
        accTypes,
        inputCountIndex,
        generateRetraction)

      val operator = new KeyedProcessOperator[BaseRow, BaseRow, BaseRow](aggFunction)
      operator
    }

    val selector = KeySelectorUtil.getBaseRowSelector(
      grouping,
      BaseRowTypeInfo.of(inputRowType))

    // partitioned aggregation
    val ret = new OneInputTransformation(
      inputTransformation,
      getRelDetailedDescription,
      operator,
      BaseRowTypeInfo.of(outRowType),
      inputTransformation.getParallelism)

    if (inputsContainSingleton()) {
      ret.setParallelism(1)
      ret.setMaxParallelism(1)
    }

    // set KeyType and Selector for state
    ret.setStateKeySelector(selector)
    ret.setStateKeyType(selector.getProducedType)
    ret
  }
}