text:
package mu.nu.nullpo.gui.swing;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;

/**
 * チューニング設定画面の frame
 */
public class GameTuningFrame extends JFrame implements ActionListener {
	/** Serial version ID */
	private static final long serialVersionUID = 1L;

	/** Outline type names (before translation) */
	protected static final String[] OUTLINE_TYPE_NAMES = {
		"GameTuning_OutlineType_Auto", "GameTuning_OutlineType_None", "GameTuning_OutlineType_Normal",
		"GameTuning_OutlineType_Connect", "GameTuning_OutlineType_SameColor"
	};

	/** 親ウィンドウ */
	protected NullpoMinoSwing owner;

	/** Player number */
	protected int playerID;

	/** A buttonでのrotationDirectionはルールに従う */
	protected JRadioButton radioRotateButtonDefaultRightAuto;
	/** A buttonでのrotationDirectionを左rotationに固定 */
	protected JRadioButton radioRotateButtonDefaultRightLeft;
	/** A buttonでのrotationDirectionを右rotationに固定 */
	protected JRadioButton radioRotateButtonDefaultRightRight;

	/** 絵柄のComboボックス */
	protected JComboBox comboboxSkin;
	/** Block画像 */
	protected BufferedImage[] imgBlockSkins;

	/** Outline type combobox */
	protected JComboBox comboboxBlockOutlineType;

	/** 最小DAS */
	protected JTextField txtfldMinDAS;
	/** MaximumDAS */
	protected JTextField txtfldMaxDAS;

	/** 横移動速度 */
	protected JTextField txtfldDasDelay;

	/** Checkbox to enable swapping the roles of up/down buttons in-game */
	protected JCheckBox chkboxReverseUpDown;

	/** Diagonal move: Auto */
	protected JRadioButton radioMoveDiagonalAuto;
	/** Diagonal move: Disable */
	protected JRadioButton radioMoveDiagonalDisable;
	/** Diagonal move: Enable */
	protected JRadioButton radioMoveDiagonalEnable;

	/** Show Outline Only: Auto */
	protected JRadioButton radioBlockShowOutlineOnlyAuto;
	/** Show Outline Only: Disable */
	protected JRadioButton radioBlockShowOutlineOnlyDisable;
	/** Show Outline Only: Enable */
	protected JRadioButton radioBlockShowOutlineOnlyEnable;

	/**
	 * Constructor
	 * @param owner 親ウィンドウ
	 * @throws HeadlessException キーボード, マウス, ディスプレイなどが存在しない場合の例外
	 */
	public GameTuningFrame(NullpoMinoSwing owner) throws HeadlessException {
		super();
		this.owner = owner;

		// Block画像の読み込み
		loadBlockSkins();

		// GUIのInitialization
		setTitle(NullpoMinoSwing.getUIText("Title_GameTuning"));
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		setResizable(false);
		initUI();
		pack();
	}

	/**
	 * GUIのInitialization
	 */
	protected void initUI() {
		this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));

		// ---------- A buttonでのrotationDirection ----------
		JPanel pRotateButtonDefaultRight = new JPanel();
		pRotateButtonDefaultRight.setLayout(new BoxLayout(pRotateButtonDefaultRight, BoxLayout.Y_AXIS));
		pRotateButtonDefaultRight.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pRotateButtonDefaultRight);

		JLabel lRotateButtonDefaultRight = new JLabel(NullpoMinoSwing.getUIText("GameTuning_RotateButtonDefaultRight_Label"));
		pRotateButtonDefaultRight.add(lRotateButtonDefaultRight);

		ButtonGroup gRotateButtonDefaultRight = new ButtonGroup();

		radioRotateButtonDefaultRightAuto = new JRadioButton(NullpoMinoSwing.getUIText("GameTuning_RotateButtonDefaultRight_Auto"));
		pRotateButtonDefaultRight.add(radioRotateButtonDefaultRightAuto);
		gRotateButtonDefaultRight.add(radioRotateButtonDefaultRightAuto);

		radioRotateButtonDefaultRightLeft = new JRadioButton(NullpoMinoSwing.getUIText("GameTuning_RotateButtonDefaultRight_Left"));
		pRotateButtonDefaultRight.add(radioRotateButtonDefaultRightLeft);
		gRotateButtonDefaultRight.add(radioRotateButtonDefaultRightLeft);

		radioRotateButtonDefaultRightRight = new JRadioButton(NullpoMinoSwing.getUIText("GameTuning_RotateButtonDefaultRight_Right"));
		pRotateButtonDefaultRight.add(radioRotateButtonDefaultRightRight);
		gRotateButtonDefaultRight.add(radioRotateButtonDefaultRightRight);

		// ---------- Diagonal Move ----------
		JPanel pMoveDiagonal = new JPanel();
		pMoveDiagonal.setLayout(new BoxLayout(pMoveDiagonal, BoxLayout.Y_AXIS));
		pMoveDiagonal.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pMoveDiagonal);

		JLabel lMoveDiagonal = new JLabel(NullpoMinoSwing.getUIText("GameTuning_MoveDiagonal_Label"));
		pMoveDiagonal.add(lMoveDiagonal);

		ButtonGroup gMoveDiagonal = new ButtonGroup();

		radioMoveDiagonalAuto = new JRadioButton(NullpoMinoSwing.getUIText("GameTuning_MoveDiagonal_Auto"));
		pMoveDiagonal.add(radioMoveDiagonalAuto);
		gMoveDiagonal.add(radioMoveDiagonalAuto);

		radioMoveDiagonalDisable = new JRadioButton(NullpoMinoSwing.getUIText("GameTuning_MoveDiagonal_Disable"));
		pMoveDiagonal.add(radioMoveDiagonalDisable);
		gMoveDiagonal.add(radioMoveDiagonalDisable);

		radioMoveDiagonalEnable = new JRadioButton(NullpoMinoSwing.getUIText("GameTuning_MoveDiagonal_Enable"));
		pMoveDiagonal.add(radioMoveDiagonalEnable);
		gMoveDiagonal.add(radioMoveDiagonalEnable);

		// ---------- Show Outline Only ----------
		JPanel pBlockShowOutlineOnly = new JPanel();
		pBlockShowOutlineOnly.setLayout(new BoxLayout(pBlockShowOutlineOnly, BoxLayout.Y_AXIS));
		pBlockShowOutlineOnly.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pBlockShowOutlineOnly);

		JLabel lBlockShowOutlineOnly = new JLabel(NullpoMinoSwing.getUIText("GameTuning_BlockShowOutlineOnly_Label"));
		pBlockShowOutlineOnly.add(lBlockShowOutlineOnly);

		ButtonGroup gBlockShowOutlineOnly = new ButtonGroup();

		radioBlockShowOutlineOnlyAuto = new JRadioButton(NullpoMinoSwing.getUIText("GameTuning_BlockShowOutlineOnly_Auto"));
		pBlockShowOutlineOnly.add(radioBlockShowOutlineOnlyAuto);
		gBlockShowOutlineOnly.add(radioBlockShowOutlineOnlyAuto);

		radioBlockShowOutlineOnlyDisable = new JRadioButton(NullpoMinoSwing.getUIText("GameTuning_BlockShowOutlineOnly_Disable"));
		pBlockShowOutlineOnly.add(radioBlockShowOutlineOnlyDisable);
		gBlockShowOutlineOnly.add(radioBlockShowOutlineOnlyDisable);

		radioBlockShowOutlineOnlyEnable = new JRadioButton(NullpoMinoSwing.getUIText("GameTuning_BlockShowOutlineOnly_Enable"));
		pBlockShowOutlineOnly.add(radioBlockShowOutlineOnlyEnable);
		gBlockShowOutlineOnly.add(radioBlockShowOutlineOnlyEnable);

		// ---------- 絵柄 ----------
		JPanel pSkin = new JPanel();
		pSkin.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pSkin);

		JLabel lSkin = new JLabel(NullpoMinoSwing.getUIText("GameTuning_Skin_Label"));
		pSkin.add(lSkin);

		DefaultComboBoxModel model = new DefaultComboBoxModel();
		model.addElement(new ComboLabel(NullpoMinoSwing.getUIText("GameTuning_Skin_Auto")));
		for(int i = 0; i < imgBlockSkins.length; i++) {
			model.addElement(new ComboLabel("" + i, new ImageIcon(imgBlockSkins[i])));
		}

		comboboxSkin = new JComboBox(model);
		comboboxSkin.setRenderer(new ComboLabelCellRenderer());
		comboboxSkin.setPreferredSize(new Dimension(190, 30));
		pSkin.add(comboboxSkin);

		// ---------- Outline Type ----------
		JPanel pOutlineType = new JPanel();
		pOutlineType.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pOutlineType);

		JLabel lOutlineType = new JLabel(NullpoMinoSwing.getUIText("GameTuning_OutlineType_Label"));
		pOutlineType.add(lOutlineType);

		String[] strArrayOutlineType = new String[OUTLINE_TYPE_NAMES.length];
		for(int i = 0; i < OUTLINE_TYPE_NAMES.length; i++) {
			strArrayOutlineType[i] = NullpoMinoSwing.getUIText(OUTLINE_TYPE_NAMES[i]);
		}
		DefaultComboBoxModel modelOutlineType = new DefaultComboBoxModel(strArrayOutlineType);
		comboboxBlockOutlineType = new JComboBox(modelOutlineType);
		comboboxBlockOutlineType.setPreferredSize(new Dimension(190, 30));
		pOutlineType.add(comboboxBlockOutlineType);

		// ---------- 最低DAS ----------
		JPanel pMinDAS = new JPanel();
		pMinDAS.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pMinDAS);

		JLabel lMinDAS = new JLabel(NullpoMinoSwing.getUIText("GameTuning_MinDAS_Label"));
		pMinDAS.add(lMinDAS);

		txtfldMinDAS = new JTextField(5);
		pMinDAS.add(txtfldMinDAS);

		// ---------- MaximumDAS ----------
		JPanel pMaxDAS = new JPanel();
		pMaxDAS.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pMaxDAS);

		JLabel lMaxDAS = new JLabel(NullpoMinoSwing.getUIText("GameTuning_MaxDAS_Label"));
		pMaxDAS.add(lMaxDAS);

		txtfldMaxDAS = new JTextField(5);
		pMaxDAS.add(txtfldMaxDAS);

		// ---------- 横移動速度 ----------
		JPanel pDasDelay = new JPanel();
		pDasDelay.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pDasDelay);

		JLabel lDasDelay = new JLabel(NullpoMinoSwing.getUIText("GameTuning_DasDelay_Label"));
		pDasDelay.add(lDasDelay);

		txtfldDasDelay = new JTextField(5);
		pDasDelay.add(txtfldDasDelay);

		// ---------- Reverse Up/Down ----------
		JPanel pReverseUpDown = new JPanel();
		pReverseUpDown.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pReverseUpDown);

		JLabel lReverseUpDown = new JLabel(NullpoMinoSwing.getUIText("GameTuning_ReverseUpDown_Label"));
		pReverseUpDown.add(lReverseUpDown);

		chkboxReverseUpDown = new JCheckBox();
		pReverseUpDown.add(chkboxReverseUpDown);

		// ---------- 画面下の button ----------
		JPanel pButtons = new JPanel();
		pButtons.setAlignmentX(LEFT_ALIGNMENT);
		this.add(pButtons);

		JButton buttonOK = new JButton(NullpoMinoSwing.getUIText("GameTuning_OK"));
		buttonOK.setMnemonic('O');
		buttonOK.addActionListener(this);
		buttonOK.setActionCommand("GameTuning_OK");
		pButtons.add(buttonOK);

		JButton buttonCancel = new JButton(NullpoMinoSwing.getUIText("GameTuning_Cancel"));
		buttonCancel.setMnemonic('C');
		buttonCancel.addActionListener(this);
		buttonCancel.setActionCommand("GameTuning_Cancel");
		pButtons.add(buttonCancel);
	}

	/**
	 * Block画像を読み込み
	 */
	protected void loadBlockSkins() {
		int numSkins = ResourceHolderSwing.imgNormalBlockList.size();
		imgBlockSkins = new BufferedImage[numSkins];

		for(int i = 0; i < numSkins; i++) {
			BufferedImage imgBlock = (BufferedImage) ResourceHolderSwing.imgNormalBlockList.get(i);
			boolean isSticky = ResourceHolderSwing.blockStickyFlagList.get(i);

			imgBlockSkins[i] = new BufferedImage(144, 16, BufferedImage.TYPE_INT_RGB);

			if(isSticky) {
				for(int j = 0; j < 9; j++) {
					imgBlockSkins[i].getGraphics().drawImage(imgBlock, j * 16, 0, (j * 16) + 16, 16, 0, j * 16, 16, (j * 16) + 16, null);
				}
			} else {
				imgBlockSkins[i].getGraphics().drawImage(imgBlock, 0, 0, 144, 16, 0, 0, 144, 16, null);
			}
		}
	}

	/**
	 * この frame を表示するときに実行する処理
	 * @param pl Player number
	 */
	public void load(int pl) {
		this.playerID = pl;

		setTitle(NullpoMinoSwing.getUIText("Title_GameTuning") + " (" + (playerID+1) + "P)");

		int owRotateButtonDefaultRight = NullpoMinoSwing.propGlobal.getProperty(playerID + ".tuning.owRotateButtonDefaultRight", -1);
		if(owRotateButtonDefaultRight == -1) radioRotateButtonDefaultRightAuto.setSelected(true);
		if(owRotateButtonDefaultRight ==  0) radioRotateButtonDefaultRightLeft.setSelected(true);
		if(owRotateButtonDefaultRight ==  1) radioRotateButtonDefaultRightRight.setSelected(true);

		int owMoveDiagonal = NullpoMinoSwing.propGlobal.getProperty(playerID + ".tuning.owMoveDiagonal", -1);
		if(owMoveDiagonal == -1) radioMoveDiagonalAuto.setSelected(true);
		if(owMoveDiagonal ==  0) radioMoveDiagonalDisable.setSelected(true);
		if(owMoveDiagonal ==  1) radioMoveDiagonalEnable.setSelected(true);

		int owBlockShowOutlineOnly = NullpoMinoSwing.propGlobal.getProperty(playerID + ".tuning.owBlockShowOutlineOnly", -1);
		if(owBlockShowOutlineOnly == -1) radioBlockShowOutlineOnlyAuto.setSelected(true);
		if(owBlockShowOutlineOnly ==  0) radioBlockShowOutlineOnlyDisable.setSelected(true);
		if(owBlockShowOutlineOnly ==  1) radioBlockShowOutlineOnlyEnable.setSelected(true);

		int owSkin = NullpoMinoSwing.propGlobal.getProperty(playerID + ".tuning.owSkin", -1);
		comboboxSkin.setSelectedIndex(owSkin + 1);

		int owBlockOutlineType = NullpoMinoSwing.propGlobal.getProperty(playerID + ".tuning.owBlockOutlineType", -1);
		comboboxBlockOutlineType.setSelectedIndex(owBlockOutlineType + 1);

		txtfldMinDAS.setText(NullpoMinoSwing.propGlobal.getProperty(playerID + ".tuning.owMinDAS", "-1"));
		txtfldMaxDAS.setText(NullpoMinoSwing.propGlobal.getProperty(playerID + ".tuning.owMaxDAS", "-1"));
		txtfldDasDelay.setText(NullpoMinoSwing.propGlobal.getProperty(playerID + ".tuning.owDasDelay", "-1"));
		chkboxReverseUpDown.setSelected(NullpoMinoSwing.propGlobal.getProperty(playerID + ".tuning.owReverseUpDown", false));
	}

	/**
	 * 保存
	 */
	protected void save() {
		int owRotateButtonDefaultRight = -1;
		if(radioRotateButtonDefaultRightAuto.isSelected()) owRotateButtonDefaultRight = -1;
		if(radioRotateButtonDefaultRightLeft.isSelected()) owRotateButtonDefaultRight =  0;
		if(radioRotateButtonDefaultRightRight.isSelected()) owRotateButtonDefaultRight = 1;
		NullpoMinoSwing.propGlobal.setProperty(playerID + ".tuning.owRotateButtonDefaultRight", owRotateButtonDefaultRight);

		int owMoveDiagonal = -1;
		if(radioMoveDiagonalAuto.isSelected()) owMoveDiagonal = -1;
		if(radioMoveDiagonalDisable.isSelected()) owMoveDiagonal = 0;
		if(radioMoveDiagonalEnable.isSelected()) owMoveDiagonal = 1;
		NullpoMinoSwing.propGlobal.setProperty(playerID + ".tuning.owMoveDiagonal", owMoveDiagonal);

		int owBlockShowOutlineOnly = -1;
		if(radioBlockShowOutlineOnlyAuto.isSelected()) owBlockShowOutlineOnly = -1;
		if(radioBlockShowOutlineOnlyDisable.isSelected()) owBlockShowOutlineOnly = 0;
		if(radioBlockShowOutlineOnlyEnable.isSelected()) owBlockShowOutlineOnly = 1;
		NullpoMinoSwing.propGlobal.setProperty(playerID + ".tuning.owBlockShowOutlineOnly", owBlockShowOutlineOnly);

		int owSkin = comboboxSkin.getSelectedIndex() - 1;
		NullpoMinoSwing.propGlobal.setProperty(playerID + ".tuning.owSkin", owSkin);

		int owBlockOutlineType = comboboxBlockOutlineType.getSelectedIndex() - 1;
		NullpoMinoSwing.propGlobal.setProperty(playerID + ".tuning.owBlockOutlineType", owBlockOutlineType);

		int owMinDAS = NullpoMinoSwing.getIntTextField(-1, txtfldMinDAS);
		NullpoMinoSwing.propGlobal.setProperty(playerID + ".tuning.owMinDAS", owMinDAS);
		int owMaxDAS = NullpoMinoSwing.getIntTextField(-1, txtfldMaxDAS);
		NullpoMinoSwing.propGlobal.setProperty(playerID + ".tuning.owMaxDAS", owMaxDAS);
		int owDasDelay = NullpoMinoSwing.getIntTextField(-1, txtfldDasDelay);
		NullpoMinoSwing.propGlobal.setProperty(playerID + ".tuning.owDasDelay", owDasDelay);
		boolean owReverseUpDown = chkboxReverseUpDown.isSelected();
		NullpoMinoSwing.propGlobal.setProperty(playerID + ".tuning.owReverseUpDown", owReverseUpDown);

		NullpoMinoSwing.saveConfig();
	}

	/*
	 *  Called when button clicked
	 */
	public void actionPerformed(ActionEvent e) {
		// OK
		if(e.getActionCommand() == "GameTuning_OK") {
			save();
			this.setVisible(false);
		}
		// Cancel
		else if(e.getActionCommand() == "GameTuning_Cancel") {
			this.setVisible(false);
		}
	}

	/**
	 * 画像表示Comboボックスの項目

	 * 出典
	 */
	protected class ComboLabel {
		private String text = "";
		private Icon icon = null;

		public ComboLabel() {
		}

		public ComboLabel(String text) {
			this.text = text;
		}

		public ComboLabel(Icon icon) {
			this.icon = icon;
		}

		public ComboLabel(String text, Icon icon) {
			this.text = text;
			this.icon = icon;
		}

		public void setText(String text) {
			this.text = text;
		}

		public String getText() {
			return text;
		}

		public void setIcon(Icon icon) {
			this.icon = icon;
		}

		public Icon getIcon() {
			return icon;
		}
	}

	/**
	 * 画像表示ComboボックスのListCellRenderer

	 * 出典
	 */
	protected class ComboLabelCellRenderer extends JLabel implements ListCellRenderer {
		private static final long serialVersionUID = 1L;

		public ComboLabelCellRenderer() {
			this.setOpaque(true);
		}

		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
			ComboLabel data = (ComboLabel)value;
			setText(data.getText());
			setIcon(data.getIcon());

			if(isSelected) {
				setForeground(Color.white);
				setBackground(Color.black);
			} else {
				setForeground(Color.black);
				setBackground(Color.white);
			}

			return this;
		}
	}
}


text:
package com.github.michaelfredeickson.progressivemetronome.metronome;

import android.media.AudioManager;
import android.media.ToneGenerator;

public class Metronome {

    private int tempo;
    private int measure;
    private ToneGenerator beep;
    private ToneGenerator firstBeep;
    private int timeSignatureNumerator;
    private int timeSignatureDenominator;
    private int accent;
    private int subdivision;

    public Metronome() {
        tempo = 120;
        measure = 4;
        beep = new ToneGenerator(AudioManager.FLAG_PLAY_SOUND, 10);
        firstBeep = new ToneGenerator(AudioManager.FLAG_PLAY_SOUND, 10);
        timeSignatureNumerator = 4;
        timeSignatureDenominator = 4;
        subdivision = 1;
        accent = 1;
    }

    public int getTempo() {
        return tempo;
    }

    public void setTempo(int tempo) {
        this.tempo = tempo;
    }

    public int getMeasure() {
        return measure;
    }

    public void upMeasure() {
        if (this.measure < 8) {
            this.measure++;
        }
    }

    public void downMeasure() {
        if (this.measure > 2) {
            this.measure--;

        }
    }

    public ToneGenerator getBeep() {
        return beep;
    }

    public void setBeep(ToneGenerator beep) {
        this.beep = beep;
    }

    public ToneGenerator getFirstBeep() {
        return firstBeep;
    }

    public void setFirstBeep(ToneGenerator firstBeep) {
        this.firstBeep = firstBeep;
    }

    public void setTimeSignatureNumerator(int timeSignatureNumerator){

        this.timeSignatureNumerator = timeSignatureNumerator;

    }

    public int getTimeSignatureNumerator(){

        return this.timeSignatureNumerator;

    }

    public void setTimeSignatureDenominator(int timeSignatureDenominator){

       this.timeSignatureDenominator = timeSignatureDenominator;

    }

    public int getTimeSignatureDenominator(){

        return this.timeSignatureDenominator;

    }

    public void setAccent(int accent){

        this.accent = accent;

    }

    public int getAccent(){

        return this.accent;

    }

    public void setSubdivision(int subdivision){

        this.subdivision = subdivision;

    }

    public int getSubdivision(){

        return this.subdivision;

    }
}

redpajama_set_name: RedPajamaGithub


text:
/* global describe, it*/
var expect = require('unexpected').clone().use(require('unexpected-stream')),
    OptiPng = require('../lib/OptiPng'),
    Path = require('path'),
    fs = require('fs');

describe('OptiPng', function () {
    it('should produce a smaller file when run with -o7 on a suboptimal PNG', function () {
        return expect(
            fs.createReadStream(Path.resolve(__dirname, 'suboptimal.png')),
            'when piped through',
            new OptiPng(['-o7']),
            'to yield output satisfying',
            function (resultPngBuffer) {
                expect(resultPngBuffer.length, 'to be within', 0, 152);
            }
        );
    });

    it('should not emit data events while paused', function (done) {
        var optiPng = new OptiPng(['-o7']);

        function fail() {
            done(new Error('OptiPng emitted data while it was paused!'));
        }
        optiPng.pause();
        optiPng.on('data', fail).on('error', done);

        fs.createReadStream(Path.resolve(__dirname, 'suboptimal.png')).pipe(optiPng);

        setTimeout(function () {
            optiPng.removeListener('data', fail);
            var chunks = [];

            optiPng
                .on('data', function (chunk) {
                    chunks.push(chunk);
                })
                .on('end', function () {
                    var resultPngBuffer = Buffer.concat(chunks);
                    expect(resultPngBuffer.length, 'to be within', 0, 152);
                    done();
                });

            optiPng.resume();
        }, 1000);
    });

    it('should emit an error if an invalid image is processed', function (done) {
        var optiPng = new OptiPng();

        optiPng.on('error', function (err) {
            done();
        }).on('data', function (chunk) {
            if(chunk !== null)
            done(new Error('OptiPng emitted data when an error was expected'));
        });

        optiPng.end(new Buffer('qwvopeqwovkqvwiejvq', 'utf-8'));
    });

    it('should emit a single error if an invalid command line is specified', function (done) {
        var optiPng = new OptiPng(['-vqve']),
            seenError = false;

        optiPng.on('error', function (err) {
            expect(optiPng.commandLine, 'to match', /optipng(\.exe)? -vqve .*?\.png$/);
            if (seenError) {
                done(new Error('More than one error event was emitted'));
            } else {
                seenError = true;
                setTimeout(done, 100);
            }
        }).on('data', function (chunk) {
            if (chunk !== null)
            done(new Error('OptiPng emitted data when an error was expected'));
        });

        optiPng.end(new Buffer('qwvopeqwovkqvwiejvq', 'utf-8'));
    });
});


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.UseDeconstruction
{
    [ExportCodeFixProvider(LanguageNames.CSharp), Shared]
    internal class CSharpUseDeconstructionCodeFixProvider : SyntaxEditorBasedCodeFixProvider
    {
        public override ImmutableArray<string> FixableDiagnosticIds
            => ImmutableArray.Create(IDEDiagnosticIds.UseDeconstructionDiagnosticId);

        public override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            context.RegisterCodeFix(
                new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics[0], c)),
                context.Diagnostics);

            return Task.CompletedTask;
        }

        protected override Task FixAllAsync(
            Document document, ImmutableArray<Diagnostic> diagnostics,
            SyntaxEditor editor, CancellationToken cancellationToken)
        {
            var nodesToProcess = diagnostics.SelectAsArray(d => d.Location.FindToken(cancellationToken).Parent);

            // When doing a fix all, we have to avoid introducing the same name multiple times
            // into the same scope.  However, checking results after each change would be very
            // expensive (lots of forking + new semantic models, etc.).  So we use
            // ApplyMethodBodySemanticEditsAsync to help out here.  It will only do the forking
            // if there are multiple results in the same method body.  If there's only one
            // result in a method body, we will just apply it without doing any extra analysis.
            return editor.ApplyMethodBodySemanticEditsAsync(
                document, nodesToProcess,
                (semanticModel, node) => true,
                (semanticModel, currentRoot, node) => UpdateRoot(semanticModel, currentRoot, node, cancellationToken),
                cancellationToken);
        }

        private SyntaxNode UpdateRoot(SemanticModel semanticModel, SyntaxNode root, SyntaxNode node, CancellationToken cancellationToken)
        {
            var editor = new SyntaxEditor(root, CSharpSyntaxGenerator.Instance);

            // We use the callback form of ReplaceNode because we may have nested code that
            // needs to be updated in fix-all situations.  For example, nested foreach statements.
            // We need to see the results of the inner changes when making the outer changes.

            ImmutableArray<MemberAccessExpressionSyntax> memberAccessExpressions = default;
            if (node is VariableDeclaratorSyntax variableDeclarator)
            {
                var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
                if (CSharpUseDeconstructionDiagnosticAnalyzer.TryAnalyzeVariableDeclaration(
                        semanticModel, variableDeclaration,
                        out var tupleType, out memberAccessExpressions,
                        cancellationToken))
                {
                    editor.ReplaceNode(
                        variableDeclaration.Parent,
                        (current, _) =>
                        {
                            var currentDeclarationStatement = (LocalDeclarationStatementSyntax)current;
                            return CreateDeconstructionStatement(tupleType, currentDeclarationStatement, currentDeclarationStatement.Declaration.Variables[0]);
                        });
                }
            }
            else if (node is ForEachStatementSyntax forEachStatement)
            {
                if (CSharpUseDeconstructionDiagnosticAnalyzer.TryAnalyzeForEachStatement(
                        semanticModel, forEachStatement,
                        out var tupleType, out memberAccessExpressions,
                        cancellationToken))
                {
                    editor.ReplaceNode(
                        forEachStatement,
                        (current, _) => CreateForEachVariableStatement(tupleType, (ForEachStatementSyntax)current));
                }
            }

            foreach (var memberAccess in memberAccessExpressions.NullToEmpty())
            {
                editor.ReplaceNode(
                    memberAccess,
                    (current, _) =>
                    {
                        var currentMemberAccess = (MemberAccessExpressionSyntax)current;
                        return currentMemberAccess.Name.WithTriviaFrom(currentMemberAccess);
                    });
            }

            return editor.GetChangedRoot();
        }

        private ForEachVariableStatementSyntax CreateForEachVariableStatement(INamedTypeSymbol tupleType, ForEachStatementSyntax forEachStatement)
        {
            // Copy all the tokens/nodes from the existing foreach statement to the new foreach statement.
            // However, convert the existing declaration over to a "var (x, y)" declaration or (int x, int y)
            // tuple expression.
            return SyntaxFactory.ForEachVariableStatement(
                forEachStatement.ForEachKeyword,
                forEachStatement.OpenParenToken,
                CreateTupleOrDeclarationExpression(tupleType, forEachStatement.Type),
                forEachStatement.InKeyword,
                forEachStatement.Expression,
                forEachStatement.CloseParenToken,
                forEachStatement.Statement);
        }

        private ExpressionStatementSyntax CreateDeconstructionStatement(
            INamedTypeSymbol tupleType, LocalDeclarationStatementSyntax declarationStatement, VariableDeclaratorSyntax variableDeclarator)
        {
            // Copy all the tokens/nodes from the existing declaration statement to the new assignment
            // statement. However, convert the existing declaration over to a "var (x, y)" declaration
            // or (int x, int y) tuple expression.
            return SyntaxFactory.ExpressionStatement(
                SyntaxFactory.AssignmentExpression(
                    SyntaxKind.SimpleAssignmentExpression,
                    CreateTupleOrDeclarationExpression(tupleType, declarationStatement.Declaration.Type),
                    variableDeclarator.Initializer.EqualsToken,
                    variableDeclarator.Initializer.Value),
                declarationStatement.SemicolonToken);
        }

        private ExpressionSyntax CreateTupleOrDeclarationExpression(INamedTypeSymbol tupleType, TypeSyntax typeNode)
        {
            // If we have an explicit tuple type in code, convert that over to a tuple expression.
            // i.e.   (int x, int y) t = ...   will be converted to (int x, int y) = ...
            //
            // If we had the "var t" form we'll convert that to the declaration expression "var (x, y)"
            return typeNode.IsKind(SyntaxKind.TupleType)
                ? (ExpressionSyntax)CreateTupleExpression((TupleTypeSyntax)typeNode)
                : CreateDeclarationExpression(tupleType, typeNode);
        }

        private DeclarationExpressionSyntax CreateDeclarationExpression(INamedTypeSymbol tupleType, TypeSyntax typeNode)
            => SyntaxFactory.DeclarationExpression(
                typeNode, SyntaxFactory.ParenthesizedVariableDesignation(
                    SyntaxFactory.SeparatedList<VariableDesignationSyntax>(tupleType.TupleElements.Select(
                        e => SyntaxFactory.SingleVariableDesignation(SyntaxFactory.Identifier(e.Name))))));

        private TupleExpressionSyntax CreateTupleExpression(TupleTypeSyntax typeNode)
            => SyntaxFactory.TupleExpression(
                typeNode.OpenParenToken,
                SyntaxFactory.SeparatedList<ArgumentSyntax>(new SyntaxNodeOrTokenList(typeNode.Elements.GetWithSeparators().Select(ConvertTupleTypeElementComponent))),
                typeNode.CloseParenToken);

        private SyntaxNodeOrToken ConvertTupleTypeElementComponent(SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.IsToken)
            {
                // return commas directly as is.
                return nodeOrToken;
            }

            // "int x" as a tuple element directly translates to "int x" (a declaration expression
            // with a variable designation 'x').
            var node = (TupleElementSyntax)nodeOrToken.AsNode();
            return SyntaxFactory.Argument(
                SyntaxFactory.DeclarationExpression(
                    node.Type,
                    SyntaxFactory.SingleVariableDesignation(node.Identifier)));
        }

        private class MyCodeAction : CodeAction.DocumentChangeAction
        {
            public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
                : base(FeaturesResources.Deconstruct_variable_declaration, createChangedDocument, FeaturesResources.Deconstruct_variable_declaration)
            {
            }
        }
    }
}


text:
use crate::array::ArrayRef;

/// Returns the array, taking only the number of elements specified
///
/// Limit performs a zero-copy slice of the array, and is a convenience method on slice
/// where:
/// * it performs a bounds-check on the array
/// * it slices from offset 0
pub fn limit(array: &ArrayRef, num_elements: usize) -> ArrayRef {
    let lim = num_elements.min(array.len());
    array.slice(0, lim)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::array::*;
    use crate::buffer::Buffer;
    use crate::datatypes::{DataType, Field, ToByteSlice};
    use crate::util::bit_util;

    use std::sync::Arc;

    #[test]
    fn test_limit_array() {
        let a: ArrayRef = Arc::new(Int32Array::from(vec![5, 6, 7, 8, 9]));
        let b = limit(&a, 3);
        let c = b.as_ref().as_any().downcast_ref::<Int32Array>().unwrap();
        assert_eq!(3, c.len());
        assert_eq!(5, c.value(0));
        assert_eq!(6, c.value(1));
        assert_eq!(7, c.value(2));
    }

    #[test]
    fn test_limit_string_array() {
        let a: ArrayRef = Arc::new(StringArray::from(vec!["hello", " ", "world", "!"]));
        let b = limit(&a, 2);
        let c = b.as_ref().as_any().downcast_ref::<StringArray>().unwrap();
        assert_eq!(2, c.len());
        assert_eq!("hello", c.value(0));
        assert_eq!(" ", c.value(1));
    }

    #[test]
    fn test_limit_array_with_null() {
        let a: ArrayRef = Arc::new(Int32Array::from(vec![None, Some(5)]));
        let b = limit(&a, 1);
        let c = b.as_ref().as_any().downcast_ref::<Int32Array>().unwrap();
        assert_eq!(1, c.len());
        assert_eq!(true, c.is_null(0));
    }

    #[test]
    fn test_limit_array_with_limit_too_large() {
        let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
        let a_ref: ArrayRef = Arc::new(a);
        let b = limit(&a_ref, 6);
        let c = b.as_ref().as_any().downcast_ref::<Int32Array>().unwrap();

        assert_eq!(5, c.len());
        assert_eq!(5, c.value(0));
        assert_eq!(6, c.value(1));
        assert_eq!(7, c.value(2));
        assert_eq!(8, c.value(3));
        assert_eq!(9, c.value(4));
    }

    #[test]
    fn test_list_array_limit() {
        // adapted from crate::array::test::test_list_array_slice
        // Construct a value array
        let value_data = ArrayData::builder(DataType::Int32)
            .len(10)
            .add_buffer(Buffer::from(
                &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].to_byte_slice(),
            ))
            .build();

        // Construct a buffer for value offsets, for the nested array:
        //  [[0, 1], null, [2, 3], null, [4, 5], null, [6, 7, 8], null, [9]]
        let value_offsets =
            Buffer::from(&[0, 2, 2, 4, 4, 6, 6, 9, 9, 10].to_byte_slice());
        // 01010101 00000001
        let mut null_bits: [u8; 2] = [0; 2];
        bit_util::set_bit(&mut null_bits, 0);
        bit_util::set_bit(&mut null_bits, 2);
        bit_util::set_bit(&mut null_bits, 4);
        bit_util::set_bit(&mut null_bits, 6);
        bit_util::set_bit(&mut null_bits, 8);

        // Construct a list array from the above two
        let list_data_type =
            DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
        let list_data = ArrayData::builder(list_data_type)
            .len(9)
            .add_buffer(value_offsets)
            .add_child_data(value_data)
            .null_bit_buffer(Buffer::from(null_bits))
            .build();
        let list_array: ArrayRef = Arc::new(ListArray::from(list_data));

        let limit_array = limit(&list_array, 6);
        assert_eq!(6, limit_array.len());
        assert_eq!(0, limit_array.offset());
        assert_eq!(3, limit_array.null_count());

        // Check offset and length for each non-null value.
        let limit_array: &ListArray =
            limit_array.as_any().downcast_ref::<ListArray>().unwrap();
        for i in 0..limit_array.len() {
            let offset = limit_array.value_offset(i);
            let length = limit_array.value_length(i);
            if i % 2 == 0 {
                assert_eq!(2, length);
                assert_eq!(i as i32, offset);
            } else {
                assert_eq!(0, length);
            }
        }
    }

    #[test]
    fn test_struct_array_limit() {
        // adapted from crate::array::test::test_struct_array_slice
        let boolean_data = ArrayData::builder(DataType::Boolean)
            .len(5)
            .add_buffer(Buffer::from([0b00010000]))
            .null_bit_buffer(Buffer::from([0b00010001]))
            .build();
        let int_data = ArrayData::builder(DataType::Int32)
            .len(5)
            .add_buffer(Buffer::from([0, 28, 42, 0, 0].to_byte_slice()))
            .null_bit_buffer(Buffer::from([0b00000110]))
            .build();

        let mut field_types = vec![];
        field_types.push(Field::new("a", DataType::Boolean, false));
        field_types.push(Field::new("b", DataType::Int32, false));
        let struct_array_data = ArrayData::builder(DataType::Struct(field_types))
            .len(5)
            .add_child_data(boolean_data.clone())
            .add_child_data(int_data.clone())
            .null_bit_buffer(Buffer::from([0b00010111]))
            .build();
        let struct_array = StructArray::from(struct_array_data);

        assert_eq!(5, struct_array.len());
        assert_eq!(1, struct_array.null_count());
        assert_eq!(boolean_data, struct_array.column(0).data());
        assert_eq!(int_data, struct_array.column(1).data());

        let array: ArrayRef = Arc::new(struct_array);

        let sliced_array = limit(&array, 3);
        let sliced_array = sliced_array.as_any().downcast_ref::<StructArray>().unwrap();
        assert_eq!(3, sliced_array.len());
        assert_eq!(0, sliced_array.offset());
        assert_eq!(0, sliced_array.null_count());
        assert!(sliced_array.is_valid(0));
        assert!(sliced_array.is_valid(1));
        assert!(sliced_array.is_valid(2));

        let sliced_c0 = sliced_array.column(0);
        let sliced_c0 = sliced_c0.as_any().downcast_ref::<BooleanArray>().unwrap();
        assert_eq!(3, sliced_c0.len());
        assert_eq!(0, sliced_c0.offset());
        assert_eq!(2, sliced_c0.null_count());
        assert!(sliced_c0.is_valid(0));
        assert!(sliced_c0.is_null(1));
        assert!(sliced_c0.is_null(2));
        assert_eq!(false, sliced_c0.value(0));

        let sliced_c1 = sliced_array.column(1);
        let sliced_c1 = sliced_c1.as_any().downcast_ref::<Int32Array>().unwrap();
        assert_eq!(3, sliced_c1.len());
        assert_eq!(0, sliced_c1.offset());
        assert_eq!(1, sliced_c1.null_count());
        assert!(sliced_c1.is_null(0));
        assert_eq!(28, sliced_c1.value(1));
        assert_eq!(42, sliced_c1.value(2));
    }
}


text:
from app import init_app
from cache import cache

mono_app = init_app('config.py')


text:
package org.terasology.reflection.copy.strategy;

import org.terasology.math.geom.Vector3f;
import org.terasology.reflection.copy.CopyStrategy;
import org.terasology.reflection.copy.RegisterCopyStrategy;

/**
 */
@RegisterCopyStrategy
public class Vector3fCopyStrategy implements CopyStrategy<Vector3f> {

    @Override
    public Vector3f copy(Vector3f value) {
        if (value != null) {
            return new Vector3f(value);
        }
        return null;
    }
}


text:
CREATE TABLE [dbo].[ExternalShare]
(
	[Id] INT NOT NULL PRIMARY KEY IDENTITY,
	[UniqueIdentifier] UNIQUEIDENTIFIER NOT NULL,
    [SiteCollectionUrl] NVARCHAR(256) NOT NULL,
    [LoginName] NVARCHAR(128) NOT NULL,
	[UserId] INT NOT NULL,
	[InvitedBy] NVARCHAR(128) NOT NULL,
    [OriginalSharedDate] DATETIME NOT NULL,
    [RefreshSharedDate] DATETIME NULL,
    [LastProcessedDate] DATETIME NULL
)


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.petegerhat.webappinterview.Record" table="Records">
        <composite-id>
            <key-property name="username" type="string" column="username"/>
            <key-property name="av_ethnicity" column="av_ethnicity" type="int"/>
            <key-property name="av_gender" column="av_gender" type="int"/>
            <key-property name="av_maturity" column="av_maturity" type="int"/>
            <key-property name="av_expression" column="av_expression" type="int"/>
        </composite-id>
        <property name="T1" column="T1" type="int"/>
        <property name="T2" column="T2" type="int"/>
        <property name="L1" column="L1" type="int"/>
        <property name="L2" column="L2" type="int"/>
        <property name="av_comment" column="av_comment" type="string"/>
        <property name="entry_date" column="entry_date" type="timestamp"/>
    </class>
</hibernate-mapping>


text:
<?xml version="1.0"?>
<!-- List of Accelerator projects -->
<data>
    <channel name="Accelerator name">
        <tracker_key>tracker key</tracker_key>
        <cmp_key>code</cmp_key>
    </channel>

    ...

</data>


text:
#ifndef _INCLUDE_SPP_H_
#define _INCLUDE_SPP_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdbool.h>
#include <errno.h>

#ifndef VERSION
#define VERSION "1.2.0"
#endif

#ifdef S_API
#undef S_API
#endif
#if R_SWIG
  #define S_API export
#elif R_INLINE
  #define S_API inline
#else
  #if defined(__GNUC__) && __GNUC__ >= 4
    #define S_API __attribute__((visibility("default")))
  #elif defined(_MSC_VER)
    #define S_API __declspec(dllexport)
  #else
    #define S_API
  #endif
#endif

#if defined(EMSCRIPTEN) || defined(__linux__) || defined(__APPLE__) || defined(__GNU__) || defined(__ANDROID__) || defined(__QNX__)
  #define __BSD__ 0
  #define __UNIX__ 1
#endif
#if __KFBSD__ || defined(__NetBSD__) || defined(__OpenBSD__)
  #define __BSD__ 1
  #define __UNIX__ 1
#endif
#if __WIN32__ || __CYGWIN__ || MINGW32
  #define __addr_t_defined
  #include <windows.h>
#endif
#if __WIN32__ || MINGW32 && !__CYGWIN__ || _MSC_VER
  #ifndef _MSC_VER
    #include <winsock.h>
  #endif
  typedef int socklen_t;
  #undef USE_SOCKETS
  #define __WINDOWS__ 1
  #undef __UNIX__
  #undef __BSD__
#endif

#ifdef __WINDOWS__
#include <io.h>
#define popen    _popen
#define pclose   _pclose
#define srandom  srand
#define snprintf _snprintf
#endif

#define MAXIFL 128

#ifndef DLL_LOCAL
#ifdef _MSC_VER
#define DLL_LOCAL
#else
#define DLL_LOCAL  __attribute__ ((visibility ("hidden")))
#endif
#endif

#define GET_ARG(x,y,i) if (y[i][2]) x = y[i] + 2; else x = y[++i]

#define DEFAULT_PROC(x) \
struct Tag *tags = (struct Tag *)&x##_tags; \
struct Arg *args = (struct Arg *)&x##_args; \
struct Proc *proc = &x##_proc;

#if USE_R2
#include <r_util.h>
#define SStrBuf RStrBuf
#else
typedef struct s_strbuf_t {
	int len;
	char *ptr;
	int ptrlen;
	char buf[64];
} SStrBuf;
#endif

typedef struct {
	SStrBuf *cout;
	FILE *fout;
	int size;
} Output;

typedef struct SppState {
	int lineno;
	int echo[MAXIFL];
	int ifl;
} SppState;

typedef struct SppBuf {
    char *lbuf;
    int lbuf_s;
    int lbuf_n;
} SppBuf;

#define ARG_CALLBACK(x) int x (char *arg)
/* XXX swap arguments ?? */
#define TAG_CALLBACK(x) int x (SppState *state, Output *out, char *buf)
#define PUT_CALLBACK(x) int x (Output *out, char *buf)
#define IS_SPACE(x) ((x==' ')||(x=='\t')||(x=='\r')||(x=='\n'))

typedef struct Tag {
	const char *name;
	TAG_CALLBACK((*callback));
} SppTag;

typedef struct Arg {
	const char *flag;
	const char *desc;
	int has_arg;
	ARG_CALLBACK((*callback));
} SppArg;

typedef struct Proc {
	const char *name;
	struct Tag **tags;
	struct Arg **args;
	TAG_CALLBACK ((*eof));
	PUT_CALLBACK ((*fputs));
	char *tag_pre;
	char *tag_post;
	char *token;
	char *multiline;
	int chop;
	int tag_begin;
	int default_echo;
	SppState state;
	SppBuf buf;
} SppProc;

typedef struct spp_t {
	SppProc *proc;
	Output *out;
} Spp;

S_API int spp_file(const char *file, Output *out);
S_API int spp_run(char *buf, Output *out);
S_API void spp_eval(char *buf, Output *out);
S_API void spp_proc_eval(SppProc *p, char *buf, Output *out);
S_API void spp_io(FILE *in, Output *out);
S_API void spp_proc_list(void);
S_API void spp_proc_list_kw(void);
S_API void spp_proc_set(SppProc *p, const char *arg, int fail);

S_API Spp *spp_new(SppProc *proc);
S_API char *spp_parse(Spp *s, const char *input);
S_API void spp_free(Spp *s);

#if DEBUG
#define D if (1)
#else
#define D if (0)
#endif

#ifndef HAVE_FORK
#define HAVE_FORK 1
#endif

#endif


text:
define(function(require, exports, module) {

  var <%= moduleName %>Create = module.exports = {

    /* --------------------------------------- */
    /* --( <%= moduleName %>: Create )-- */
    /* --------------------------------------- */

    url: '/create', // This will turn into /<%= moduleName %>/create

    // View Configurations
    views: {

      /* --------------------------------------- */
      /* --( Page Actions )-- */
      /* --------------------------------------- */

      'pageActions': {
        template: '

',
        controller: ['$scope', function($scope) {

          // Define our Action objects
          $scope.actionConfig = [
            {id: 'create', title: 'Create <%= moduleLabel %>', trigger: 'submitUserForm', icon: '<%= iconClass %>'},
            {id: 'cancel', title: 'Cancel', route: '/<%= moduleName %>', icon: 'remove-sign'}
          ];

          // Setup listener for save submit
          $scope.submitUserForm = function() {
            $scope.$parent.$broadcast('submitUser');
          };

        }]
      },

      /* --------------------------------------- */
      /* --( Main Page Content )-- */
      /* --------------------------------------- */

      'pageContent': {
        templateUrl: 'app/<%= moduleName %>/templates/form.html',
        controller: ['$scope', '$state',
          function($scope, $state) {

            // Define Page Title
            $scope.$root.pageTitle = 'Create New <%= moduleLabel %>';

            // Listen for other views that want to save a user
            $scope.$on('submitUser', function() {
              $scope.saveUser();
            });

            // Save User Handler
            $scope.saveUser = function() {
            };
          }
        ]
      }
    },
  };
});


text:
.sc-contrib-group { padding-bottom: var(--default-padding); overflow: auto; }
.sc-contrib-group > .sc-contrib { float: left; margin-right: var(--default-padding); }
.sc-contrib-group .se-add-author { color: var(--link-color); }


text:
@implementation MovieViewController

@synthesize webView, textView, segmented;

- (void)dealloc {
	[queue cancelAllOperations];
	[webView release];
	[textView release];
	[segmented release];

    [super dealloc];
}

- (void)showMovie {
	NSString *htmlString = nil;

	if ([item.itemUrls count] == 0) {
		htmlString = @"This video format is not supported by iPhone.";
	} else if ([item.itemUrls count] == 1) {
		htmlString = [NSString stringWithFormat:@"<video width=\"270\" height=\"160\" src=\"%@\" poster=\"%@\"></video>", [[item.itemUrls objectAtIndex:0] absoluteString], [[item.thumbItemUrls lastObject] absoluteString]];
	} else {
		[segmented setHidden:NO];
		[segmented setEnabled:YES];

		if (movieNumber == 0) {
			[segmented setEnabled:NO forSegmentAtIndex:0];
		} else {
			[segmented setEnabled:YES forSegmentAtIndex:0];
		}

		if (movieNumber == [item.itemUrls count] - 1) {
			[segmented setEnabled:NO forSegmentAtIndex:1];
		} else {
			[segmented setEnabled:YES forSegmentAtIndex:1];
		}

		NSString *strItemUrl = [[item.itemUrls objectAtIndex:movieNumber] absoluteString];
		NSString *itemFilename = nil;
		if ([strItemUrl hasSuffix:@"512kb.mp4"]) {
			itemFilename = [strItemUrl substringToIndex:[strItemUrl length] - 10];
		} else {
			itemFilename = [strItemUrl substringToIndex:[strItemUrl length] - 4];
		}

		NSURL *thumbItemUrl = nil;
		for (thumbItemUrl in item.thumbItemUrls) {
			NSRange range = [[thumbItemUrl absoluteString] rangeOfString:itemFilename];
			if (range.location != NSNotFound) {
				break;
			}
		}
		if (thumbItemUrl == nil) {
			thumbItemUrl = [item.thumbItemUrls lastObject];
		}

		htmlString = [NSString stringWithFormat:@"<video width=\"270\" height=\"160\" src=\"%@\" poster=\"%@\"></video>", strItemUrl, thumbItemUrl];
	}

	[webView loadHTMLString:htmlString baseURL:nil];
}

- (IBAction)changeMovie:(id)sender {
	if ([segmented selectedSegmentIndex] == 0) {
		movieNumber--;
	} else if ([segmented selectedSegmentIndex] == 1) {
		movieNumber++;
	}
	[self showMovie];
}

- (void)startReadingFilesXml {
	ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:[item getFilesXmlUrl]] autorelease];
	request.timeOutSeconds = 30;
	[request setDelegate:self];
	[request setDidFinishSelector:@selector(readingFilesXmlDone:)];
	[request setDidFailSelector:@selector(requestWentWrong:)];
	[queue addOperation:request];
}

- (void)readingFilesXmlDone:(ASIHTTPRequest *)request {
	[item setFileData:[request responseData]];
	[self showMovie];
	[super finishDataLoading];
}

- (void)startGettingItem {
	[self startDataLoading];
	if ([item.thumbItemUrls count] == 0 && [item.itemUrls count] == 0) {
		[self startReadingFilesXml];
	} else {
		[self showMovie];
		[super finishDataLoading];
	}
}

- (void)viewDidLoad {
    [super viewDidLoad];

	self.title = @"Movie";

	if ([super isNetworkConnectionOK] == NO) {
		return;
	}

	[self startGettingItem];

	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *fontSize = [defaults objectForKey:@"Font Size"];
	UIFont *font = nil;
	if ([fontSize isEqualToString:@"Medium"] || fontSize == nil) {
		font = [UIFont systemFontOfSize:14];
	} else if ([fontSize isEqualToString:@"Small"]) {
		font = [UIFont systemFontOfSize:12];
	} else if ([fontSize isEqualToString:@"Large"]) {
		font = [UIFont systemFontOfSize:16];
	}
	textView.font = font;
	textView.text = [item getInfoText];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 1) {
		[self startGettingItem];
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
	[super viewDidUnload];
}

@end


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace TapaoNovo
{
    public class KeyManager
    {
        //HashSet<Key> keys = new HashSet<Key>();
        List<Key> keys = new List<Key>();
        public void Add(Key key)
        {
            keys.Add(key);
        }

        public void Remove(Key key)
        {
            keys.Remove(key);
        }

        public bool isPressed(Key key)
        {
            return keys.Contains(key);
        }
    }
}


text:
package org.eigenbase.lurql;

import org.jgrapht.graph.*;

/**
 * LurqlPlanEdge is a follow edge in a LURQL plan graph. (TODO: factor out
 * subclass.)
 *
 * @author John V. Sichi
 * @version $Id$
 */
public class LurqlPlanEdge
    extends DefaultEdge
{
    //~ Instance fields --------------------------------------------------------

    /**
     * String representation of this edge.
     */
    protected String stringRep;

    private final LurqlPlanVertex source;

    private final LurqlPlanVertex target;

    //~ Constructors -----------------------------------------------------------

    LurqlPlanEdge(
        LurqlPlanVertex source,
        LurqlPlanVertex target)
    {
        this.source = source;
        this.target = target;
    }

    //~ Methods ----------------------------------------------------------------

    public LurqlPlanVertex getPlanSource()
    {
        return source;
    }

    public LurqlPlanVertex getPlanTarget()
    {
        return target;
    }

    public String toString()
    {
        return stringRep;
    }

    public boolean equals(Object obj)
    {
        if (!(obj instanceof LurqlPlanEdge)) {
            return false;
        }
        return stringRep.equals(obj.toString());
    }

    public int hashCode()
    {
        return stringRep.hashCode();
    }
}

// End LurqlPlanEdge.java


text: * Fixed by Mirko Heuegger


text:
package org.apache.flink.connector.hbase;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.connector.hbase.source.HBaseInputFormat;
import org.apache.flink.connector.hbase.source.HBaseTableSource;
import org.apache.flink.connector.hbase.util.HBaseTableSchema;
import org.apache.flink.connector.hbase.util.HBaseTestBase;
import org.apache.flink.connector.hbase.util.PlannerType;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.api.bridge.java.BatchTableEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentInternal;
import org.apache.flink.table.api.internal.TableImpl;
import org.apache.flink.table.descriptors.DescriptorProperties;
import org.apache.flink.table.factories.TableFactoryService;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.planner.runtime.utils.BatchTableEnvUtil;
import org.apache.flink.table.planner.runtime.utils.TableEnvUtil;
import org.apache.flink.table.planner.sinks.CollectRowTableSink;
import org.apache.flink.table.planner.sinks.CollectTableSink;
import org.apache.flink.table.planner.utils.JavaScalaConversionUtil;
import org.apache.flink.table.runtime.utils.StreamITCase;
import org.apache.flink.table.sinks.TableSink;
import org.apache.flink.table.sources.TableSource;
import org.apache.flink.test.util.TestBaseUtils;
import org.apache.flink.types.Row;

import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import scala.Option;

import static org.apache.flink.connector.hbase.util.PlannerType.OLD_PLANNER;
import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.descriptors.ConnectorDescriptorValidator.CONNECTOR_PROPERTY_VERSION;
import static org.apache.flink.table.descriptors.ConnectorDescriptorValidator.CONNECTOR_TYPE;
import static org.apache.flink.table.descriptors.ConnectorDescriptorValidator.CONNECTOR_VERSION;
import static org.apache.flink.table.descriptors.HBaseValidator.CONNECTOR_TABLE_NAME;
import static org.apache.flink.table.descriptors.HBaseValidator.CONNECTOR_TYPE_VALUE_HBASE;
import static org.apache.flink.table.descriptors.HBaseValidator.CONNECTOR_VERSION_VALUE_143;
import static org.apache.flink.table.descriptors.HBaseValidator.CONNECTOR_ZK_QUORUM;
import static org.apache.flink.table.descriptors.Schema.SCHEMA;
import static org.junit.Assert.assertEquals;

/**
 * IT cases for HBase connector (including HBaseTableSource and HBaseTableSink).
 */
@RunWith(Parameterized.class)
public class HBaseConnectorITCase extends HBaseTestBase {

	@Parameterized.Parameter
	public PlannerType planner;

	@Parameterized.Parameter(1)
	public boolean isLegacyConnector;

	@Override
	protected PlannerType planner() {
		return planner;
	}

	@Parameterized.Parameters(name = "planner = {0}, legacy = {1}")
	public static Object[] parameters() {
		return new Object[][]{
			new Object[]{PlannerType.BLINK_PLANNER, true},
			new Object[]{PlannerType.BLINK_PLANNER, false},
			new Object[]{PlannerType.OLD_PLANNER, true}
		};
	}

	// -------------------------------------------------------------------------------------
	// HBaseTableSource tests
	// -------------------------------------------------------------------------------------

	@Test
	public void testTableSourceFullScan() throws Exception {
		TableEnvironment tEnv = createBatchTableEnv();
		if (isLegacyConnector) {
			HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_1);
			hbaseTable.addColumn(FAMILY1, F1COL1, Integer.class);
			hbaseTable.addColumn(FAMILY2, F2COL1, String.class);
			hbaseTable.addColumn(FAMILY2, F2COL2, Long.class);
			hbaseTable.addColumn(FAMILY3, F3COL1, Double.class);
			hbaseTable.addColumn(FAMILY3, F3COL2, Boolean.class);
			hbaseTable.addColumn(FAMILY3, F3COL3, String.class);
			hbaseTable.setRowKey("rowkey", Integer.class);
			((TableEnvironmentInternal) tEnv).registerTableSourceInternal("hTable", hbaseTable);
		} else {
			tEnv.executeSql(
					"CREATE TABLE hTable (" +
					" family1 ROW<col1 INT>," +
					" family2 ROW<col1 STRING, col2 BIGINT>," +
					" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>," +
					" rowkey INT," +
					" PRIMARY KEY (rowkey) NOT ENFORCED" +
					") WITH (" +
					" 'connector' = 'hbase-1.4'," +
					" 'table-name' = '" + TEST_TABLE_1 + "'," +
					" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
					")");
		}

		Table table = tEnv.sqlQuery("SELECT " +
			"  h.family1.col1, " +
			"  h.family2.col1, " +
			"  h.family2.col2, " +
			"  h.family3.col1, " +
			"  h.family3.col2, " +
			"  h.family3.col3 " +
			"FROM hTable AS h");

		List<Row> results = collectBatchResult(table);
		String expected =
			"10,Hello-1,100,1.01,false,Welt-1\n" +
				"20,Hello-2,200,2.02,true,Welt-2\n" +
				"30,Hello-3,300,3.03,false,Welt-3\n" +
				"40,null,400,4.04,true,Welt-4\n" +
				"50,Hello-5,500,5.05,false,Welt-5\n" +
				"60,Hello-6,600,6.06,true,Welt-6\n" +
				"70,Hello-7,700,7.07,false,Welt-7\n" +
				"80,null,800,8.08,true,Welt-8\n";

		TestBaseUtils.compareResultAsText(results, expected);
	}

	@Test
	public void testTableSourceProjection() throws Exception {
		TableEnvironment tEnv = createBatchTableEnv();

		if (isLegacyConnector) {
			HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_1);
			hbaseTable.addColumn(FAMILY1, F1COL1, Integer.class);
			hbaseTable.addColumn(FAMILY2, F2COL1, String.class);
			hbaseTable.addColumn(FAMILY2, F2COL2, Long.class);
			hbaseTable.addColumn(FAMILY3, F3COL1, Double.class);
			hbaseTable.addColumn(FAMILY3, F3COL2, Boolean.class);
			hbaseTable.addColumn(FAMILY3, F3COL3, String.class);
			hbaseTable.setRowKey("rowkey", Integer.class);
			((TableEnvironmentInternal) tEnv).registerTableSourceInternal("hTable", hbaseTable);
		} else {
			tEnv.executeSql(
					"CREATE TABLE hTable (" +
					" family1 ROW<col1 INT>," +
					" family2 ROW<col1 STRING, col2 BIGINT>," +
					" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>," +
					" rowkey INT," +
					" PRIMARY KEY (rowkey) NOT ENFORCED" +
					") WITH (" +
					" 'connector' = 'hbase-1.4'," +
					" 'table-name' = '" + TEST_TABLE_1 + "'," +
					" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
					")");
		}

		Table table = tEnv.sqlQuery("SELECT " +
			"  h.family1.col1, " +
			"  h.family3.col1, " +
			"  h.family3.col2, " +
			"  h.family3.col3 " +
			"FROM hTable AS h");

		List<Row> results = collectBatchResult(table);
		String expected =
			"10,1.01,false,Welt-1\n" +
				"20,2.02,true,Welt-2\n" +
				"30,3.03,false,Welt-3\n" +
				"40,4.04,true,Welt-4\n" +
				"50,5.05,false,Welt-5\n" +
				"60,6.06,true,Welt-6\n" +
				"70,7.07,false,Welt-7\n" +
				"80,8.08,true,Welt-8\n";

		TestBaseUtils.compareResultAsText(results, expected);
	}

	@Test
	public void testTableSourceFieldOrder() throws Exception {
		TableEnvironment tEnv = createBatchTableEnv();

		if (isLegacyConnector) {
			HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_1);
			// shuffle order of column registration
			hbaseTable.setRowKey("rowkey", Integer.class);
			hbaseTable.addColumn(FAMILY2, F2COL1, String.class);
			hbaseTable.addColumn(FAMILY3, F3COL1, Double.class);
			hbaseTable.addColumn(FAMILY1, F1COL1, Integer.class);
			hbaseTable.addColumn(FAMILY2, F2COL2, Long.class);
			hbaseTable.addColumn(FAMILY3, F3COL2, Boolean.class);
			hbaseTable.addColumn(FAMILY3, F3COL3, String.class);
			((TableEnvironmentInternal) tEnv).registerTableSourceInternal("hTable", hbaseTable);
		} else {
			tEnv.executeSql(
					"CREATE TABLE hTable (" +
					" rowkey INT PRIMARY KEY," +
					" family2 ROW<col1 STRING, col2 BIGINT>," +
					" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>," +
					" family1 ROW<col1 INT>" +
					") WITH (" +
					" 'connector' = 'hbase-1.4'," +
					" 'table-name' = '" + TEST_TABLE_1 + "'," +
					" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
					")");
		}

		Table table = tEnv.sqlQuery("SELECT * FROM hTable AS h");

		List<Row> results = collectBatchResult(table);
		String expected =
			"1,Hello-1,100,1.01,false,Welt-1,10\n" +
				"2,Hello-2,200,2.02,true,Welt-2,20\n" +
				"3,Hello-3,300,3.03,false,Welt-3,30\n" +
				"4,null,400,4.04,true,Welt-4,40\n" +
				"5,Hello-5,500,5.05,false,Welt-5,50\n" +
				"6,Hello-6,600,6.06,true,Welt-6,60\n" +
				"7,Hello-7,700,7.07,false,Welt-7,70\n" +
				"8,null,800,8.08,true,Welt-8,80\n";

		TestBaseUtils.compareResultAsText(results, expected);
	}

	@Test
	public void testTableSourceReadAsByteArray() throws Exception {
		TableEnvironment tEnv = createBatchTableEnv();

		if (isLegacyConnector) {
			// fetch row2 from the table till the end
			HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_1);
			hbaseTable.addColumn(FAMILY2, F2COL1, byte[].class);
			hbaseTable.addColumn(FAMILY2, F2COL2, byte[].class);
			hbaseTable.setRowKey("rowkey", Integer.class);
			((TableEnvironmentInternal) tEnv).registerTableSourceInternal("hTable", hbaseTable);
		} else {
			tEnv.executeSql(
					"CREATE TABLE hTable (" +
					" family2 ROW<col1 BYTES, col2 BYTES>," +
					" rowkey INT" + // no primary key syntax
					") WITH (" +
					" 'connector' = 'hbase-1.4'," +
					" 'table-name' = '" + TEST_TABLE_1 + "'," +
					" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
					")");
		}
		tEnv.registerFunction("toUTF8", new ToUTF8());
		tEnv.registerFunction("toLong", new ToLong());

		Table table = tEnv.sqlQuery(
			"SELECT " +
				"  toUTF8(h.family2.col1), " +
				"  toLong(h.family2.col2) " +
				"FROM hTable AS h"
		);

		List<Row> results = collectBatchResult(table);
		String expected =
			"Hello-1,100\n" +
				"Hello-2,200\n" +
				"Hello-3,300\n" +
				"null,400\n" +
				"Hello-5,500\n" +
				"Hello-6,600\n" +
				"Hello-7,700\n" +
				"null,800\n";

		TestBaseUtils.compareResultAsText(results, expected);
	}

	@Test
	public void testTableInputFormat() throws Exception {
		ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

		DataSet<Tuple1<Integer>> result = env
			.createInput(new InputFormatForTestTable(getConf()))
			.reduce((ReduceFunction<Tuple1<Integer>>) (v1, v2) -> Tuple1.of(v1.f0 + v2.f0));

		List<Tuple1<Integer>> resultSet = result.collect();

		assertEquals(1, resultSet.size());
		assertEquals(360, (int) resultSet.get(0).f0);
	}

	// -------------------------------------------------------------------------------------
	// HBaseTableSink tests
	// -------------------------------------------------------------------------------------

	// prepare a source collection.
	private static final List<Row> testData1 = new ArrayList<>();
	private static final RowTypeInfo testTypeInfo1 = new RowTypeInfo(
		new TypeInformation[]{Types.INT, Types.INT, Types.STRING, Types.LONG, Types.DOUBLE,
			Types.BOOLEAN, Types.STRING, Types.SQL_TIMESTAMP, Types.SQL_DATE, Types.SQL_TIME},
		new String[]{"rowkey", "f1c1", "f2c1", "f2c2", "f3c1", "f3c2", "f3c3", "f4c1", "f4c2", "f4c3"});

	static {
		testData1.add(Row.of(1, 10, "Hello-1", 100L, 1.01, false, "Welt-1",
			Timestamp.valueOf("2019-08-18 19:00:00"), Date.valueOf("2019-08-18"), Time.valueOf("19:00:00")));
		testData1.add(Row.of(2, 20, "Hello-2", 200L, 2.02, true, "Welt-2",
			Timestamp.valueOf("2019-08-18 19:01:00"), Date.valueOf("2019-08-18"), Time.valueOf("19:01:00")));
		testData1.add(Row.of(3, 30, "Hello-3", 300L, 3.03, false, "Welt-3",
			Timestamp.valueOf("2019-08-18 19:02:00"), Date.valueOf("2019-08-18"), Time.valueOf("19:02:00")));
		testData1.add(Row.of(4, 40, null, 400L, 4.04, true, "Welt-4",
			Timestamp.valueOf("2019-08-18 19:03:00"), Date.valueOf("2019-08-18"), Time.valueOf("19:03:00")));
		testData1.add(Row.of(5, 50, "Hello-5", 500L, 5.05, false, "Welt-5",
			Timestamp.valueOf("2019-08-19 19:10:00"), Date.valueOf("2019-08-19"), Time.valueOf("19:10:00")));
		testData1.add(Row.of(6, 60, "Hello-6", 600L, 6.06, true, "Welt-6",
			Timestamp.valueOf("2019-08-19 19:20:00"), Date.valueOf("2019-08-19"), Time.valueOf("19:20:00")));
		testData1.add(Row.of(7, 70, "Hello-7", 700L, 7.07, false, "Welt-7",
			Timestamp.valueOf("2019-08-19 19:30:00"), Date.valueOf("2019-08-19"), Time.valueOf("19:30:00")));
		testData1.add(Row.of(8, 80, null, 800L, 8.08, true, "Welt-8",
			Timestamp.valueOf("2019-08-19 19:40:00"), Date.valueOf("2019-08-19"), Time.valueOf("19:40:00")));
	}

	@Test
	public void testTableSink() throws Exception {
		StreamExecutionEnvironment execEnv = StreamExecutionEnvironment.getExecutionEnvironment();
		StreamTableEnvironment tEnv = StreamTableEnvironment.create(execEnv, streamSettings);

		if (isLegacyConnector) {
			HBaseTableSchema schema = new HBaseTableSchema();
			schema.addColumn(FAMILY1, F1COL1, Integer.class);
			schema.addColumn(FAMILY2, F2COL1, String.class);
			schema.addColumn(FAMILY2, F2COL2, Long.class);
			schema.setRowKey("rk", Integer.class);
			schema.addColumn(FAMILY3, F3COL1, Double.class);
			schema.addColumn(FAMILY3, F3COL2, Boolean.class);
			schema.addColumn(FAMILY3, F3COL3, String.class);

			Map<String, String> tableProperties = new HashMap<>();
			tableProperties.put("connector.type", "hbase");
			tableProperties.put("connector.version", "1.4.3");
			tableProperties.put("connector.property-version", "1");
			tableProperties.put("connector.table-name", TEST_TABLE_2);
			tableProperties.put("connector.zookeeper.quorum", getZookeeperQuorum());
			tableProperties.put("connector.zookeeper.znode.parent", "/hbase");
			DescriptorProperties descriptorProperties = new DescriptorProperties(true);
			descriptorProperties.putTableSchema(SCHEMA, schema.convertsToTableSchema());
			descriptorProperties.putProperties(tableProperties);
			TableSink tableSink = TableFactoryService
				.find(HBaseTableFactory.class, descriptorProperties.asMap())
				.createTableSink(descriptorProperties.asMap());
			((TableEnvironmentInternal) tEnv).registerTableSinkInternal("hbase", tableSink);
		} else {
			tEnv.executeSql(
					"CREATE TABLE hbase (" +
					" family1 ROW<col1 INT>," +
					" family2 ROW<col1 STRING, col2 BIGINT>," +
					" rk INT," +
					" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>" +
					") WITH (" +
					" 'connector' = 'hbase-1.4'," +
					" 'table-name' = '" + TEST_TABLE_1 + "'," +
					" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'," +
					" 'zookeeper.znode.parent' = '/hbase'" +
					")");
		}

		DataStream<Row> ds = execEnv.fromCollection(testData1).returns(testTypeInfo1);
		tEnv.createTemporaryView("src", ds);

		String query = "INSERT INTO hbase SELECT ROW(f1c1), ROW(f2c1, f2c2), rowkey, ROW(f3c1, f3c2, f3c3) FROM src";
		TableEnvUtil.execInsertSqlAndWaitResult(tEnv, query);

		// start a batch scan job to verify contents in HBase table
		// start a batch scan job to verify contents in HBase table
		TableEnvironment batchTableEnv = createBatchTableEnv();

		if (isLegacyConnector) {
			HBaseTableSource hbaseTable = new HBaseTableSource(getConf(), TEST_TABLE_2);
			hbaseTable.setRowKey("rowkey", Integer.class);
			hbaseTable.addColumn(FAMILY1, F1COL1, Integer.class);
			hbaseTable.addColumn(FAMILY2, F2COL1, String.class);
			hbaseTable.addColumn(FAMILY2, F2COL2, Long.class);
			hbaseTable.addColumn(FAMILY3, F3COL1, Double.class);
			hbaseTable.addColumn(FAMILY3, F3COL2, Boolean.class);
			hbaseTable.addColumn(FAMILY3, F3COL3, String.class);
			((TableEnvironmentInternal) batchTableEnv).registerTableSourceInternal("hTable", hbaseTable);
		} else {
			batchTableEnv.executeSql(
					"CREATE TABLE hTable (" +
					" rowkey INT," +
					" family1 ROW<col1 INT>," +
					" family2 ROW<col1 STRING, col2 BIGINT>," +
					" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>" +
					") WITH (" +
					" 'connector' = 'hbase-1.4'," +
					" 'table-name' = '" + TEST_TABLE_1 + "'," +
					" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
					")");
		}

		Table table = batchTableEnv.sqlQuery(
			"SELECT " +
				"  h.rowkey, " +
				"  h.family1.col1, " +
				"  h.family2.col1, " +
				"  h.family2.col2, " +
				"  h.family3.col1, " +
				"  h.family3.col2, " +
				"  h.family3.col3 " +
				"FROM hTable AS h"
		);

		List<Row> results = collectBatchResult(table);
		String expected =
				"1,10,Hello-1,100,1.01,false,Welt-1\n" +
				"2,20,Hello-2,200,2.02,true,Welt-2\n" +
				"3,30,Hello-3,300,3.03,false,Welt-3\n" +
				"4,40,null,400,4.04,true,Welt-4\n" +
				"5,50,Hello-5,500,5.05,false,Welt-5\n" +
				"6,60,Hello-6,600,6.06,true,Welt-6\n" +
				"7,70,Hello-7,700,7.07,false,Welt-7\n" +
				"8,80,null,800,8.08,true,Welt-8\n";

		TestBaseUtils.compareResultAsText(results, expected);
	}

	@Test
	public void testTableSourceSinkWithDDL() throws Exception {
		StreamExecutionEnvironment execEnv = StreamExecutionEnvironment.getExecutionEnvironment();
		StreamTableEnvironment tEnv = StreamTableEnvironment.create(execEnv, streamSettings);

		DataStream<Row> ds = execEnv.fromCollection(testData1).returns(testTypeInfo1);
		tEnv.createTemporaryView("src", ds);

		// register hbase table
		String quorum = getZookeeperQuorum();
		String ddl;
		if (isLegacyConnector) {
			ddl = "CREATE TABLE hbase (\n" +
				"    rowkey INT," +
				"    family1 ROW<col1 INT>,\n" +
				"    family2 ROW<col1 VARCHAR, col2 BIGINT>,\n" +
				"    family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 VARCHAR>,\n" +
				"    family4 ROW<col1 TIMESTAMP(3), col2 DATE, col3 TIME(3)>\n" +
				") WITH (\n" +
				"    'connector.type' = 'hbase',\n" +
				"    'connector.version' = '1.4.3',\n" +
				"    'connector.table-name' = 'testTable3',\n" +
				"    'connector.zookeeper.quorum' = '" + quorum + "',\n" +
				"    'connector.zookeeper.znode.parent' = '/hbase' " +
				")";
		} else {
			ddl = "CREATE TABLE hbase (\n" +
				"    rowkey INT," +
				"    family1 ROW<col1 INT>,\n" +
				"    family2 ROW<col1 VARCHAR, col2 BIGINT>,\n" +
				"    family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 VARCHAR>,\n" +
				"    family4 ROW<col1 TIMESTAMP(3), col2 DATE, col3 TIME(3)>\n" +
				") WITH (\n" +
				"    'connector' = 'hbase-1.4',\n" +
				"    'table-name' = 'testTable3',\n" +
				"    'zookeeper.quorum' = '" + quorum + "',\n" +
				"    'zookeeper.znode.parent' = '/hbase' " +
				")";
		}
		tEnv.executeSql(ddl);

		String query = "INSERT INTO hbase " +
			"SELECT rowkey, ROW(f1c1), ROW(f2c1, f2c2), ROW(f3c1, f3c2, f3c3), ROW(f4c1, f4c2, f4c3) " +
			"FROM src";
		TableEnvUtil.execInsertSqlAndWaitResult(tEnv, query);

		// start a batch scan job to verify contents in HBase table
		TableEnvironment batchTableEnv = createBatchTableEnv();
		batchTableEnv.executeSql(ddl);

		Table table = batchTableEnv.sqlQuery(
			"SELECT " +
				"  h.rowkey, " +
				"  h.family1.col1, " +
				"  h.family2.col1, " +
				"  h.family2.col2, " +
				"  h.family3.col1, " +
				"  h.family3.col2, " +
				"  h.family3.col3, " +
				"  h.family4.col1, " +
				"  h.family4.col2, " +
				"  h.family4.col3 " +
				"FROM hbase AS h"
		);

		List<Row> results = collectBatchResult(table);
		String expected =
				"1,10,Hello-1,100,1.01,false,Welt-1,2019-08-18 19:00:00.0,2019-08-18,19:00:00\n" +
				"2,20,Hello-2,200,2.02,true,Welt-2,2019-08-18 19:01:00.0,2019-08-18,19:01:00\n" +
				"3,30,Hello-3,300,3.03,false,Welt-3,2019-08-18 19:02:00.0,2019-08-18,19:02:00\n" +
				"4,40,null,400,4.04,true,Welt-4,2019-08-18 19:03:00.0,2019-08-18,19:03:00\n" +
				"5,50,Hello-5,500,5.05,false,Welt-5,2019-08-19 19:10:00.0,2019-08-19,19:10:00\n" +
				"6,60,Hello-6,600,6.06,true,Welt-6,2019-08-19 19:20:00.0,2019-08-19,19:20:00\n" +
				"7,70,Hello-7,700,7.07,false,Welt-7,2019-08-19 19:30:00.0,2019-08-19,19:30:00\n" +
				"8,80,null,800,8.08,true,Welt-8,2019-08-19 19:40:00.0,2019-08-19,19:40:00\n";

		TestBaseUtils.compareResultAsText(results, expected);
	}

	// -------------------------------------------------------------------------------------
	// HBase lookup source tests
	// -------------------------------------------------------------------------------------

	// prepare a source collection.
	private static final List<Row> testData2 = new ArrayList<>();
	private static final RowTypeInfo testTypeInfo2 = new RowTypeInfo(
		new TypeInformation[]{Types.INT, Types.LONG, Types.STRING},
		new String[]{"a", "b", "c"});

	static {
		testData2.add(Row.of(1, 1L, "Hi"));
		testData2.add(Row.of(2, 2L, "Hello"));
		testData2.add(Row.of(3, 2L, "Hello world"));
		testData2.add(Row.of(3, 3L, "Hello world!"));
	}

	@Test
	public void testHBaseLookupTableSource() throws Exception {
		if (OLD_PLANNER.equals(planner)) {
			// lookup table source is only supported in blink planner, skip for old planner
			return;
		}
		StreamExecutionEnvironment streamEnv = StreamExecutionEnvironment.getExecutionEnvironment();
		StreamTableEnvironment streamTableEnv = StreamTableEnvironment.create(streamEnv, streamSettings);
		StreamITCase.clear();

		// prepare a source table
		String srcTableName = "src";
		DataStream<Row> ds = streamEnv.fromCollection(testData2).returns(testTypeInfo2);
		Table in = streamTableEnv.fromDataStream(ds, $("a"), $("b"), $("c"), $("proc").proctime());
		streamTableEnv.registerTable(srcTableName, in);

		if (isLegacyConnector) {
			Map<String, String> tableProperties = hbaseTableProperties();
			TableSource<?> source = TableFactoryService
				.find(HBaseTableFactory.class, tableProperties)
				.createTableSource(tableProperties);
			((TableEnvironmentInternal) streamTableEnv).registerTableSourceInternal("hbaseLookup", source);
		} else {
			streamTableEnv.executeSql(
					"CREATE TABLE hbaseLookup (" +
					" family1 ROW<col1 INT>," +
					" rk INT," +
					" family2 ROW<col1 STRING, col2 BIGINT>," +
					" family3 ROW<col1 DOUBLE, col2 BOOLEAN, col3 STRING>" +
					") WITH (" +
					" 'connector' = 'hbase-1.4'," +
					" 'table-name' = '" + TEST_TABLE_1 + "'," +
					" 'zookeeper.quorum' = '" + getZookeeperQuorum() + "'" +
					")");
		}
		// perform a temporal table join query
		String query = "SELECT a,family1.col1, family3.col3 FROM src " +
			"JOIN hbaseLookup FOR SYSTEM_TIME AS OF src.proc as h ON src.a = h.rk";
		Table result = streamTableEnv.sqlQuery(query);

		DataStream<Row> resultSet = streamTableEnv.toAppendStream(result, Row.class);
		resultSet.addSink(new StreamITCase.StringSink<>());

		streamEnv.execute();

		List<String> expected = new ArrayList<>();
		expected.add("1,10,Welt-1");
		expected.add("2,20,Welt-2");
		expected.add("3,30,Welt-3");
		expected.add("3,30,Welt-3");

		StreamITCase.compareWithList(expected);
	}

	private static Map<String, String> hbaseTableProperties() {
		Map<String, String> properties = new HashMap<>();
		properties.put(CONNECTOR_TYPE, CONNECTOR_TYPE_VALUE_HBASE);
		properties.put(CONNECTOR_VERSION, CONNECTOR_VERSION_VALUE_143);
		properties.put(CONNECTOR_PROPERTY_VERSION, "1");
		properties.put(CONNECTOR_TABLE_NAME, TEST_TABLE_1);
		properties.put(CONNECTOR_ZK_QUORUM, getZookeeperQuorum());
		// schema
		String[] columnNames = {FAMILY1, ROWKEY, FAMILY2, FAMILY3};
		TypeInformation<Row> f1 = Types.ROW_NAMED(new String[]{F1COL1}, Types.INT);
		TypeInformation<Row> f2 = Types.ROW_NAMED(new String[]{F2COL1, F2COL2}, Types.STRING, Types.LONG);
		TypeInformation<Row> f3 = Types.ROW_NAMED(new String[]{F3COL1, F3COL2, F3COL3}, Types.DOUBLE, Types.BOOLEAN, Types.STRING);
		TypeInformation[] columnTypes = new TypeInformation[]{f1, Types.INT, f2, f3};

		DescriptorProperties descriptorProperties = new DescriptorProperties(true);
		TableSchema tableSchema = new TableSchema(columnNames, columnTypes);
		descriptorProperties.putTableSchema(SCHEMA, tableSchema);
		descriptorProperties.putProperties(properties);
		return descriptorProperties.asMap();
	}

	// ------------------------------- Utilities -------------------------------------------------

	/**
	 * Creates a Batch {@link TableEnvironment} depends on the {@link #planner} context.
	 */
	private TableEnvironment createBatchTableEnv() {
		if (OLD_PLANNER.equals(planner)) {
			ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
			return BatchTableEnvironment.create(env, new TableConfig());
		} else {
			return TableEnvironment.create(batchSettings);
		}
	}

	/**
	 * Collects batch result depends on the {@link #planner} context.
	 */
	private List<Row> collectBatchResult(Table table) throws Exception {
		TableImpl tableImpl = (TableImpl) table;
		if (OLD_PLANNER.equals(planner)) {
			BatchTableEnvironment batchTableEnv = (BatchTableEnvironment) tableImpl.getTableEnvironment();
			DataSet<Row> resultSet = batchTableEnv.toDataSet(table, Row.class);
			return resultSet.collect();
		} else {
			TableImpl t = (TableImpl) table;
			TableSchema schema = t.getSchema();
			List<TypeInformation> types = new ArrayList<>();
			for (TypeInformation typeInfo : t.getSchema().getFieldTypes()) {
				// convert LOCAL_DATE_TIME to legacy TIMESTAMP to make the output consistent with flink batch planner
				if (typeInfo.equals(Types.LOCAL_DATE_TIME)) {
					types.add(Types.SQL_TIMESTAMP);
				} else if (typeInfo.equals(Types.LOCAL_DATE)) {
					types.add(Types.SQL_DATE);
				} else if (typeInfo.equals(Types.LOCAL_TIME)) {
					types.add(Types.SQL_TIME);
				} else {
					types.add(typeInfo);
				}
			}
			CollectRowTableSink sink = new CollectRowTableSink();
			CollectTableSink<Row> configuredSink = (CollectTableSink<Row>) sink.configure(
				schema.getFieldNames(), types.toArray(new TypeInformation[0]));
			return JavaScalaConversionUtil.toJava(
				BatchTableEnvUtil.collect(
					t.getTableEnvironment(), table, configuredSink, Option.apply("JOB")));
		}
	}

	/**
	 * A {@link ScalarFunction} that maps byte arrays to UTF-8 strings.
	 */
	public static class ToUTF8 extends ScalarFunction {
		private static final long serialVersionUID = 1L;

		public String eval(byte[] bytes) {
			return Bytes.toString(bytes);
		}
	}

	/**
	 * A {@link ScalarFunction} that maps byte array to longs.
	 */
	public static class ToLong extends ScalarFunction {
		private static final long serialVersionUID = 1L;

		public long eval(byte[] bytes) {
			return Bytes.toLong(bytes);
		}
	}

	/**
	 * A {@link HBaseInputFormat} for testing.
	 */
	public static class InputFormatForTestTable extends HBaseInputFormat<Tuple1<Integer>> {
		private static final long serialVersionUID = 1L;

		public InputFormatForTestTable(org.apache.hadoop.conf.Configuration hConf) {
			super(hConf);
		}

		@Override
		protected Scan getScanner() {
			return new Scan();
		}

		@Override
		protected String getTableName() {
			return TEST_TABLE_1;
		}

		@Override
		protected Tuple1<Integer> mapResultToTuple(Result r) {
			return new Tuple1<>(Bytes.toInt(r.getValue(Bytes.toBytes(FAMILY1), Bytes.toBytes(F1COL1))));
		}
	}

}


text:
package xyz.upperlevel.uppercore.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation that defines the constructor for a class.
 *
 This can be declared both on a method or a constructor but with two different meanings:
 *
 In the constructor it means that the current class can be Config-parsed using that constructor,
 *
 In a method it means that the method can be used to parse the class returned by it
 */
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ConfigConstructor {
    /**
     * When true the object will be parsed even when in an array form,
     * this is desirable for objects as vectors as they are mostly written as [x, y, z] instead of a map.
     * This could also be used when a constructor has only one type as argument, then it would not need an
     * array to be constructed.
     * @return
     */
    boolean inlineable() default false;
}


text:
/* Mongolian DeadBeef by Marcello Bastea-Forte - zlib license */

var Mongolian = require('../mongolian')

var db,collection

module.exports = {
    "create connection": function(test) {
        db = new Mongolian('mongo://localhost/mongolian_test', { log:false })
        db.dropDatabase(function(error) {
            test.ifError(error)
            test.done()
        })
    },

    "db is not null": function(test) {
        test.ok(db)
        test.done()
    },
    "its name is right": function(test) {
        test.equal(db.name, "mongolian_test")
        test.done()
    },
    "its collectionNames": function(test) {
        db.collectionNames(function(error, names) {
            test.ifError(error)
            test.equal(names.length, 0)
            test.done()
        })
    },
    "eval": function(test) {
        db.eval(function() {
            return 5
        }, function(error, result) {
            test.ifError(error)
            test.equal(result,5)
            test.done()
        })
    },
    "eval with parameter": function(test) {
        db.eval(
            function(x) {
                return x
            },
            5,
            function(error, result) {
                test.ifError(error)
                test.equal(result,5)
                test.done()
            }
        )
    },
    "eval with two parameters": function(test) {
        db.eval(
            function(x, y) {
                return x + y
            },
            5, 6,
            function(error, result) {
                test.ifError(error)
                test.equal(result,11)
                test.done()
            }
        )
    },

    "close connection": function(test) {
        db.server.close()
        test.done()
    }
}


text:
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace ExternalProcessing {

class Filter;

class QueuedChunk {
public:
  // True if this represents the last chunk in the stream
  bool end_stream = false;
  // True if the chunk was actually sent to the gRPC stream
  bool delivered = false;
  Buffer::OwnedImpl data;
};
using QueuedChunkPtr = std::unique_ptr<QueuedChunk>;

class ChunkQueue {
public:
  ChunkQueue() = default;
  ChunkQueue(const ChunkQueue&) = delete;
  ChunkQueue& operator=(const ChunkQueue&) = delete;
  uint32_t bytesEnqueued() const { return bytes_enqueued_; }
  bool empty() const { return queue_.empty(); }
  void push(Buffer::Instance& data, bool end_stream, bool delivered);
  absl::optional<QueuedChunkPtr> pop(bool undelivered_only);
  const QueuedChunk& consolidate(bool delivered);

private:
  // If we are in either streaming mode, store chunks that we received here,
  // and use the "delivered" flag to keep track of which ones were pushed
  // to the external processor. When matching responses come back for these
  // chunks, then they will be removed.
  std::deque<QueuedChunkPtr> queue_;
  // The total size of chunks in the queue.
  uint32_t bytes_enqueued_{};
};

class ProcessorState : public Logger::Loggable<Logger::Id::ext_proc> {
public:
  // This describes whether the filter is waiting for a response to a gRPC message.
  // We use it to determine how to respond to stream messages send back from
  // the external processor.
  enum class CallbackState {
    // Not waiting for anything
    Idle,
    // Waiting for a "headers" response. This may be true even if we started
    // to receive data frames for a message.
    HeadersCallback,
    // Waiting for a "body" response in buffered mode.
    BufferedBodyCallback,
    // Waiting for a "body" response in streaming mode.
    StreamedBodyCallback,
    // Waiting for a "body" response in streaming mode in the special case
    // in which the processing mode was changed while there were outstanding
    // messages sent to the processor.
    StreamedBodyCallbackFinishing,
    // Waiting for a body callback in "buffered partial" mode.
    BufferedPartialBodyCallback,
    // Waiting for a "trailers" response.
    TrailersCallback,
  };

  explicit ProcessorState(Filter& filter,
                          envoy::config::core::v3::TrafficDirection traffic_direction)
      : filter_(filter), watermark_requested_(false), paused_(false), no_body_(false),
        complete_body_available_(false), trailers_available_(false), body_replaced_(false),
        partial_body_processed_(false), traffic_direction_(traffic_direction) {}
  ProcessorState(const ProcessorState&) = delete;
  virtual ~ProcessorState() = default;
  ProcessorState& operator=(const ProcessorState&) = delete;

  envoy::config::core::v3::TrafficDirection trafficDirection() const { return traffic_direction_; }
  CallbackState callbackState() const { return callback_state_; }
  void setPaused(bool paused) { paused_ = paused; }

  bool completeBodyAvailable() const { return complete_body_available_; }
  void setCompleteBodyAvailable(bool d) { complete_body_available_ = d; }
  void setHasNoBody(bool b) { no_body_ = b; }
  void setTrailersAvailable(bool d) { trailers_available_ = d; }
  bool bodyReplaced() const { return body_replaced_; }
  bool partialBodyProcessed() const { return partial_body_processed_; }

  virtual void setProcessingMode(
      const envoy::extensions::filters::http::ext_proc::v3::ProcessingMode& mode) PURE;
  bool sendHeaders() const { return send_headers_; }
  bool sendTrailers() const { return send_trailers_; }
  envoy::extensions::filters::http::ext_proc::v3::ProcessingMode_BodySendMode bodyMode() const {
    return body_mode_;
  }

  void setHeaders(Http::RequestOrResponseHeaderMap* headers) { headers_ = headers; }
  void setTrailers(Http::HeaderMap* trailers) { trailers_ = trailers; }

  void onStartProcessorCall(Event::TimerCb cb, std::chrono::milliseconds timeout,
                            CallbackState callback_state);
  void onFinishProcessorCall(Grpc::Status::GrpcStatus call_status,
                             CallbackState next_state = CallbackState::Idle);
  void stopMessageTimer();

  // Idempotent methods for watermarking the body
  virtual void requestWatermark() PURE;
  virtual void clearWatermark() PURE;

  absl::Status handleHeadersResponse(const envoy::service::ext_proc::v3::HeadersResponse& response);
  absl::Status handleBodyResponse(const envoy::service::ext_proc::v3::BodyResponse& response);
  absl::Status
  handleTrailersResponse(const envoy::service::ext_proc::v3::TrailersResponse& response);

  virtual const Buffer::Instance* bufferedData() const PURE;
  bool hasBufferedData() const { return bufferedData() != nullptr && bufferedData()->length() > 0; }
  virtual void addBufferedData(Buffer::Instance& data) const PURE;
  virtual void modifyBufferedData(std::function<void(Buffer::Instance&)> cb) const PURE;
  virtual void injectDataToFilterChain(Buffer::Instance& data, bool end_stream) PURE;
  virtual uint32_t bufferLimit() const PURE;

  // Move the contents of "data" into a QueuedChunk object on the streaming queue.
  void enqueueStreamingChunk(Buffer::Instance& data, bool end_stream, bool delivered);
  // If the queue has chunks, return the head of the queue.
  absl::optional<QueuedChunkPtr> dequeueStreamingChunk(bool undelivered_only) {
    return chunk_queue_.pop(undelivered_only);
  }
  // Consolidate all the chunks on the queue into a single one and return a reference.
  const QueuedChunk& consolidateStreamedChunks(bool delivered) {
    return chunk_queue_.consolidate(delivered);
  }
  bool queueOverHighLimit() const { return chunk_queue_.bytesEnqueued() > bufferLimit(); }
  bool queueBelowLowLimit() const { return chunk_queue_.bytesEnqueued() < bufferLimit() / 2; }

  virtual Http::HeaderMap* addTrailers() PURE;

  virtual void continueProcessing() const PURE;
  void continueIfNecessary();
  void clearAsyncState();

  virtual envoy::service::ext_proc::v3::HttpHeaders*
  mutableHeaders(envoy::service::ext_proc::v3::ProcessingRequest& request) const PURE;
  virtual envoy::service::ext_proc::v3::HttpBody*
  mutableBody(envoy::service::ext_proc::v3::ProcessingRequest& request) const PURE;
  virtual envoy::service::ext_proc::v3::HttpTrailers*
  mutableTrailers(envoy::service::ext_proc::v3::ProcessingRequest& request) const PURE;

protected:
  void setBodyMode(
      envoy::extensions::filters::http::ext_proc::v3::ProcessingMode_BodySendMode body_mode);

  Filter& filter_;
  Http::StreamFilterCallbacks* filter_callbacks_;
  CallbackState callback_state_ = CallbackState::Idle;

  // Keep track of whether we requested a watermark.
  bool watermark_requested_ : 1;
  // Keep track of whether we paused processing and may require
  // a "continue."
  bool paused_ : 1;

  // If true, then there is not going to be a body
  bool no_body_ : 1;
  // If true, then the filter received the complete body
  bool complete_body_available_ : 1;
  // If true, then the filter received the trailers
  bool trailers_available_ : 1;
  // If true, then a CONTINUE_AND_REPLACE status was used on a response
  bool body_replaced_ : 1;
  // If true, we are in "buffered partial" mode and we already reached the buffer
  // limit, sent the body in a message, and got back a reply.
  bool partial_body_processed_ : 1;

  // If true, the server wants to see the headers
  bool send_headers_ : 1;
  // If true, the server wants to see the trailers
  bool send_trailers_ : 1;

  // The specific mode for body handling
  envoy::extensions::filters::http::ext_proc::v3::ProcessingMode_BodySendMode body_mode_;

  Http::RequestOrResponseHeaderMap* headers_ = nullptr;
  Http::HeaderMap* trailers_ = nullptr;
  Event::TimerPtr message_timer_;
  ChunkQueue chunk_queue_;
  absl::optional<MonotonicTime> call_start_time_ = absl::nullopt;
  const envoy::config::core::v3::TrafficDirection traffic_direction_;
};

class DecodingProcessorState : public ProcessorState {
public:
  explicit DecodingProcessorState(
      Filter& filter, const envoy::extensions::filters::http::ext_proc::v3::ProcessingMode& mode)
      : ProcessorState(filter, envoy::config::core::v3::TrafficDirection::INBOUND) {
    setProcessingModeInternal(mode);
  }
  DecodingProcessorState(const DecodingProcessorState&) = delete;
  DecodingProcessorState& operator=(const DecodingProcessorState&) = delete;

  void setDecoderFilterCallbacks(Http::StreamDecoderFilterCallbacks& callbacks) {
    decoder_callbacks_ = &callbacks;
    filter_callbacks_ = &callbacks;
  }

  const Buffer::Instance* bufferedData() const override {
    return decoder_callbacks_->decodingBuffer();
  }

  void addBufferedData(Buffer::Instance& data) const override {
    decoder_callbacks_->addDecodedData(data, false);
  }

  void modifyBufferedData(std::function<void(Buffer::Instance&)> cb) const override {
    decoder_callbacks_->modifyDecodingBuffer(cb);
  }

  void injectDataToFilterChain(Buffer::Instance& data, bool end_stream) override {
    decoder_callbacks_->injectDecodedDataToFilterChain(data, end_stream);
  }

  uint32_t bufferLimit() const override { return decoder_callbacks_->decoderBufferLimit(); }

  Http::HeaderMap* addTrailers() override {
    trailers_ = &decoder_callbacks_->addDecodedTrailers();
    return trailers_;
  }

  void continueProcessing() const override { decoder_callbacks_->continueDecoding(); }

  envoy::service::ext_proc::v3::HttpHeaders*
  mutableHeaders(envoy::service::ext_proc::v3::ProcessingRequest& request) const override {
    return request.mutable_request_headers();
  }

  envoy::service::ext_proc::v3::HttpBody*
  mutableBody(envoy::service::ext_proc::v3::ProcessingRequest& request) const override {
    return request.mutable_request_body();
  }

  envoy::service::ext_proc::v3::HttpTrailers*
  mutableTrailers(envoy::service::ext_proc::v3::ProcessingRequest& request) const override {
    return request.mutable_request_trailers();
  }

  void setProcessingMode(
      const envoy::extensions::filters::http::ext_proc::v3::ProcessingMode& mode) override {
    setProcessingModeInternal(mode);
  }

  void requestWatermark() override;
  void clearWatermark() override;

private:
  void setProcessingModeInternal(
      const envoy::extensions::filters::http::ext_proc::v3::ProcessingMode& mode);

  Http::StreamDecoderFilterCallbacks* decoder_callbacks_{};
};

class EncodingProcessorState : public ProcessorState {
public:
  explicit EncodingProcessorState(
      Filter& filter, const envoy::extensions::filters::http::ext_proc::v3::ProcessingMode& mode)
      : ProcessorState(filter, envoy::config::core::v3::TrafficDirection::OUTBOUND) {
    setProcessingModeInternal(mode);
  }
  EncodingProcessorState(const EncodingProcessorState&) = delete;
  EncodingProcessorState& operator=(const EncodingProcessorState&) = delete;

  void setEncoderFilterCallbacks(Http::StreamEncoderFilterCallbacks& callbacks) {
    encoder_callbacks_ = &callbacks;
    filter_callbacks_ = &callbacks;
  }

  const Buffer::Instance* bufferedData() const override {
    return encoder_callbacks_->encodingBuffer();
  }

  void addBufferedData(Buffer::Instance& data) const override {
    encoder_callbacks_->addEncodedData(data, false);
  }

  void modifyBufferedData(std::function<void(Buffer::Instance&)> cb) const override {
    encoder_callbacks_->modifyEncodingBuffer(cb);
  }

  void injectDataToFilterChain(Buffer::Instance& data, bool end_stream) override {
    encoder_callbacks_->injectEncodedDataToFilterChain(data, end_stream);
  }

  uint32_t bufferLimit() const override { return encoder_callbacks_->encoderBufferLimit(); }

  Http::HeaderMap* addTrailers() override {
    trailers_ = &encoder_callbacks_->addEncodedTrailers();
    return trailers_;
  }

  void continueProcessing() const override { encoder_callbacks_->continueEncoding(); }

  envoy::service::ext_proc::v3::HttpHeaders*
  mutableHeaders(envoy::service::ext_proc::v3::ProcessingRequest& request) const override {
    return request.mutable_response_headers();
  }

  envoy::service::ext_proc::v3::HttpBody*
  mutableBody(envoy::service::ext_proc::v3::ProcessingRequest& request) const override {
    return request.mutable_response_body();
  }

  envoy::service::ext_proc::v3::HttpTrailers*
  mutableTrailers(envoy::service::ext_proc::v3::ProcessingRequest& request) const override {
    return request.mutable_response_trailers();
  }

  void setProcessingMode(
      const envoy::extensions::filters::http::ext_proc::v3::ProcessingMode& mode) override {
    setProcessingModeInternal(mode);
  }

  void requestWatermark() override;
  void clearWatermark() override;

private:
  void setProcessingModeInternal(
      const envoy::extensions::filters::http::ext_proc::v3::ProcessingMode& mode);

  Http::StreamEncoderFilterCallbacks* encoder_callbacks_{};
};

} // namespace ExternalProcessing
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy