text:
require 'delegate'
require 'tmpdir'
require 'thread'

# A utility class for managing temporary files. When you create a Tempfile
# object, it will create a temporary file with a unique filename. A Tempfile
# objects behaves just like a File object, and you can perform all the usual
# file operations on it: reading data, writing data, changing its permissions,
# etc. So although this class does not explicitly document all instance methods
# supported by File, you can in fact call any File instance method on a
# Tempfile object.
#
# == Synopsis
#
#   require 'tempfile'
#
#   file = Tempfile.new('foo')
#   file.path      # => A unique filename in the OS's temp directory,
#                  #    e.g.: "/tmp/foo.24722.0"
#                  #    This filename contains 'foo' in its basename.
#   file.write("hello world")
#   file.rewind
#   file.read      # => "hello world"
#   file.close
#   file.unlink    # deletes the temp file
#
# == Good practices
#
# === Explicit close
#
# When a Tempfile object is garbage collected, or when the Ruby interpreter
# exits, its associated temporary file is automatically deleted. This means
# that's it's unnecessary to explicitly delete a Tempfile after use, though
# it's good practice to do so: not explicitly deleting unused Tempfiles can
# potentially leave behind large amounts of tempfiles on the filesystem
# until they're garbage collected. The existence of these temp files can make
# it harder to determine a new Tempfile filename.
#
# Therefore, one should always call #unlink or close in an ensure block, like
# this:
#
#   file = Tempfile.new('foo')
#   begin
#      ...do something with file...
#   ensure
#      file.close
#      file.unlink   # deletes the temp file
#   end
#
# === Unlink after creation
#
# On POSIX systems, it's possible to unlink a file right after creating it,
# and before closing it. This removes the filesystem entry without closing
# the file handle, so it ensures that only the processes that already had
# the file handle open can access the file's contents. It's strongly
# recommended that you do this if you do not want any other processes to
# be able to read from or write to the Tempfile, and you do not need to
# know the Tempfile's filename either.
#
# For example, a practical use case for unlink-after-creation would be this:
# you need a large byte buffer that's too large to comfortably fit in RAM,
# e.g. when you're writing a web server and you want to buffer the client's
# file upload data.
#
# Please refer to #unlink for more information and a code example.
#
# == Minor notes
#
# Tempfile's filename picking method is both thread-safe and inter-process-safe:
# it guarantees that no other threads or processes will pick the same filename.
#
# Tempfile itself however may not be entirely thread-safe. If you access the
# same Tempfile object from multiple threads then you should protect it with a
# mutex.
class Tempfile < DelegateClass(File)
  include Dir::Tmpname

  # call-seq:
  #    new(basename, [tmpdir = Dir.tmpdir], [options])
  #
  # Creates a temporary file with permissions 0600 (= only readable and
  # writable by the owner) and opens it with mode "w+".
  #
  # The +basename+ parameter is used to determine the name of the
  # temporary file. You can either pass a String or an Array with
  # 2 String elements. In the former form, the temporary file's base
  # name will begin with the given string. In the latter form,
  # the temporary file's base name will begin with the array's first
  # element, and end with the second element. For example:
  #
  #   file = Tempfile.new('hello')
  #   file.path  # => something like: "/tmp/hello2843-8392-92849382--0"
  #
  #   # Use the Array form to enforce an extension in the filename:
  #   file = Tempfile.new(['hello', '.jpg'])
  #   file.path  # => something like: "/tmp/hello2843-8392-92849382--0.jpg"
  #
  # The temporary file will be placed in the directory as specified
  # by the +tmpdir+ parameter. By default, this is +Dir.tmpdir+.
  # When $SAFE > 0 and the given +tmpdir+ is tainted, it uses
  # '/tmp' as the temporary directory. Please note that ENV values
  # are tainted by default, and +Dir.tmpdir+'s return value might
  # come from environment variables (e.g. <tt>$TMPDIR</tt>).
  #
  #   file = Tempfile.new('hello', '/home/aisaka')
  #   file.path  # => something like: "/home/aisaka/hello2843-8392-92849382--0"
  #
  # You can also pass an options hash. Under the hood, Tempfile creates
  # the temporary file using +File.open+. These options will be passed to
  # +File.open+. This is mostly useful for specifying encoding
  # options, e.g.:
  #
  #   Tempfile.new('hello', '/home/aisaka', :encoding => 'ascii-8bit')
  #
  #   # You can also omit the 'tmpdir' parameter:
  #   Tempfile.new('hello', :encoding => 'ascii-8bit')
  #
  # === Exceptions
  #
  # If Tempfile.new cannot find a unique filename within a limited
  # number of tries, then it will raise an exception.
  def initialize(basename, *rest)
    if block_given?
      warn "Tempfile.new doesn't call the given block."
    end
    @data = []
    @clean_proc = Remover.new(@data)
    ObjectSpace.define_finalizer(self, @clean_proc)

    create(basename, *rest) do |tmpname, n, opts|
      mode = File::RDWR|File::CREAT|File::EXCL
      perm = 0600
      if opts
        mode |= opts.delete(:mode) || 0
        opts[:perm] = perm
        perm = nil
      else
        opts = perm
      end
      @data[1] = @tmpfile = File.open(tmpname, mode, opts)
      @data[0] = @tmpname = tmpname
      @mode = mode & ~(File::CREAT|File::EXCL)
      perm or opts.freeze
      @opts = opts
    end

    super(@tmpfile)
  end

  # Opens or reopens the file with mode "r+".
  def open
    @tmpfile.close if @tmpfile
    @tmpfile = File.open(@tmpname, @mode, @opts)
    @data[1] = @tmpfile
    __setobj__(@tmpfile)
  end

  def _close    # :nodoc:
    begin
      @tmpfile.close if @tmpfile
    ensure
      @tmpfile = nil
      @data[1] = nil if @data
    end
  end
  protected :_close

  # Closes the file. If +unlink_now+ is true, then the file will be unlinked
  # (deleted) after closing. Of course, you can choose to later call #unlink
  # if you do not unlink it now.
  #
  # If you don't explicitly unlink the temporary file, the removal
  # will be delayed until the object is finalized.
  def close(unlink_now=false)
    if unlink_now
      close!
    else
      _close
    end
  end

  # Closes and unlinks (deletes) the file. Has the same effect as called
  # <tt>close(true)</tt>.
  def close!
    _close
    unlink
  end

  # Unlinks (deletes) the file from the filesystem. One should always unlink
  # the file after using it, as is explained in the "Explicit close" good
  # practice section in the Tempfile overview:
  #
  #   file = Tempfile.new('foo')
  #   begin
  #      ...do something with file...
  #   ensure
  #      file.close
  #      file.unlink   # deletes the temp file
  #   end
  #
  # === Unlink-before-close
  #
  # On POSIX systems it's possible to unlink a file before closing it. This
  # practice is explained in detail in the Tempfile overview (section
  # "Unlink after creation"); please refer there for more information.
  #
  # However, unlink-before-close may not be supported on non-POSIX operating
  # systems. Microsoft Windows is the most notable case: unlinking a non-closed
  # file will result in an error, which this method will silently ignore. If
  # you want to practice unlink-before-close whenever possible, then you should
  # write code like this:
  #
  #   file = Tempfile.new('foo')
  #   file.unlink   # On Windows this silently fails.
  #   begin
  #      ... do something with file ...
  #   ensure
  #      file.close!   # Closes the file handle. If the file wasn't unlinked
  #                    # because #unlink failed, then this method will attempt
  #                    # to do so again.
  #   end
  def unlink
    return unless @tmpname
    begin
      File.unlink(@tmpname)
    rescue Errno::ENOENT
    rescue Errno::EACCES
      # may not be able to unlink on Windows; just ignore
      return
    end
    # remove tmpname from remover
    @data[0] = @data[1] = nil
    @tmpname = nil
    ObjectSpace.undefine_finalizer(self)
  end
  alias delete unlink

  # Returns the full path name of the temporary file.
  # This will be nil if #unlink has been called.
  def path
    @tmpname
  end

  # Returns the size of the temporary file.  As a side effect, the IO
  # buffer is flushed before determining the size.
  def size
    if @tmpfile
      @tmpfile.flush
      @tmpfile.stat.size
    elsif @tmpname
      File.size(@tmpname)
    else
      0
    end
  end
  alias length size

  # :stopdoc:
  def inspect
    "#<#{self.class}:#{path}>"
  end

  class Remover
    def initialize(data)
      @pid = $$
      @data = data
    end

    def call(*args)
      return if @pid != $$

      path, tmpfile = *@data

      STDERR.print "removing ", path, "..." if $DEBUG

      tmpfile.close if tmpfile

      if path
        begin
          File.unlink(path)
        rescue Errno::ENOENT
        end
      end

      STDERR.print "done\n" if $DEBUG
    end
  end
  # :startdoc:

  class << self
    # Creates a new Tempfile.
    #
    # If no block is given, this is a synonym for Tempfile.new.
    #
    # If a block is given, then a Tempfile object will be constructed,
    # and the block is run with said object as argument. The Tempfile
    # object will be automatically closed after the block terminates.
    # The call returns the value of the block.
    #
    # In any case, all arguments (+*args+) will be passed to Tempfile.new.
    #
    #   Tempfile.open('foo', '/home/temp') do |f|
    #      ... do something with f ...
    #   end
    #
    #   # Equivalent:
    #   f = Tempfile.open('foo', '/home/temp')
    #   begin
    #      ... do something with f ...
    #   ensure
    #      f.close
    #   end
    def open(*args)
      tempfile = new(*args)

      if block_given?
        begin
          yield(tempfile)
        ensure
          tempfile.close
        end
      else
        tempfile
      end
    end
  end
end

# Creates a temporally file as usual File object (not Tempfile).
# It don't use finalizer and delegation.
#
# If no block is given, this is similar to Tempfile.new except
# creating File instead of Tempfile.
# The created file is not removed automatically.
# You should use File.unlink to remove it.
#
# If a block is given, then a File object will be constructed,
# and the block is invoked with the object as the argument.
# The File object will be automatically closed and
# the temporally file is removed after the block terminates.
# The call returns the value of the block.
#
# In any case, all arguments (+*args+) will be treated as Tempfile.new.
#
#   Tempfile.create('foo', '/home/temp') do |f|
#      ... do something with f ...
#   end
#
def Tempfile.create(basename, *rest)
  tmpfile = nil
  Dir::Tmpname.create(basename, *rest) do |tmpname, n, opts|
    mode = File::RDWR|File::CREAT|File::EXCL
    perm = 0600
    if opts
      mode |= opts.delete(:mode) || 0
      opts[:perm] = perm
      perm = nil
    else
      opts = perm
    end
    tmpfile = File.open(tmpname, mode, opts)
  end
  if block_given?
    begin
      yield tmpfile
    ensure
      tmpfile.close if !tmpfile.closed?
      File.unlink tmpfile
    end
  else
    tmpfile
  end
end

if __FILE__ == $0
#  $DEBUG = true
  f = Tempfile.new("foo")
  f.print("foo\n")
  f.close
  f.open
  p f.gets # => "foo\n"
  f.close!
end


text:
/**
* Test
*
* @author Vadim Mironov (multik6292@mail.ru/mironov6292@gmail.ru)
* @version $Id$
* @since 0.1
*/

package ru.job4j.condition;

import org.junit.Test;

import static org.hamcrest.number.IsCloseTo.closeTo;
import static org.junit.Assert.assertThat;

/**
* Test class.
*/
public class TriangleTest {
	/**
	* Test method.
	*/
	@Test
	public void whenOneTwoAndThreeFourAndFiveSixThenZero() {
		Point point1 = new Point(1, 2);
		Point point2 = new Point(3, 4);
		Point point3 = new Point(5, 6);

		Triangle triangle = new Triangle(point1, point2, point3);
		double result = triangle.area();
		double expected = 0D;
		assertThat(result, closeTo(expected, 0.01));
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.cloud.examples.pubsub.snippets;

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

import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.Role;
import com.google.cloud.pubsub.deprecated.Message;
import com.google.cloud.pubsub.deprecated.PubSub;
import com.google.cloud.pubsub.deprecated.PubSubOptions;
import com.google.cloud.pubsub.deprecated.ReceivedMessage;
import com.google.cloud.pubsub.deprecated.Subscription;
import com.google.cloud.pubsub.deprecated.SubscriptionInfo;
import com.google.cloud.pubsub.deprecated.Topic;
import com.google.cloud.pubsub.deprecated.TopicInfo;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class ITSubscriptionSnippets {

  private static final String TOPIC =
      "it-subscription-snippets-topic-" + UUID.randomUUID().toString();
  private static final String SUBSCRIPTION =
      "it-subscription-snippets-subscription-" + UUID.randomUUID().toString();
  private static final Message MESSAGE1 = Message.of("message1");
  private static final Message MESSAGE2 = Message.of("message2");

  private static PubSub pubsub;
  private static Topic topic;
  private static Subscription subscription;

  @BeforeClass
  public static void beforeClass() {
    pubsub = PubSubOptions.getDefaultInstance().getService();
    topic = pubsub.create(TopicInfo.of(TOPIC));
    subscription = pubsub.create(SubscriptionInfo.of(TOPIC, SUBSCRIPTION));
  }

  @AfterClass
  public static void afterClass() throws Exception {
    if (pubsub != null) {
      topic.delete();
      subscription.delete();
      pubsub.close();
    }
  }

  @Test
  public void testPushConfig() throws ExecutionException, InterruptedException {
    SubscriptionSnippets subscriptionSnippets = new SubscriptionSnippets(subscription);
    String endpoint = "https://" + pubsub.getOptions().getProjectId() + ".appspot.com/push";
    subscriptionSnippets.replacePushConfig(endpoint);
    Subscription updatedSubscription = pubsub.getSubscription(SUBSCRIPTION);
    assertEquals(endpoint, updatedSubscription.getPushConfig().getEndpoint());
    subscriptionSnippets.replacePushConfigToPull();
    updatedSubscription = pubsub.getSubscription(SUBSCRIPTION);
    assertNull(updatedSubscription.getPushConfig());
    subscriptionSnippets.replacePushConfigAsync(endpoint);
    updatedSubscription = pubsub.getSubscription(SUBSCRIPTION);
    assertEquals(endpoint, updatedSubscription.getPushConfig().getEndpoint());
    subscriptionSnippets.replacePushConfigToPullAsync();
    updatedSubscription = pubsub.getSubscription(SUBSCRIPTION);
    assertNull(updatedSubscription.getPushConfig());
  }

  @Test
  public void testPull() throws ExecutionException, InterruptedException {
    SubscriptionSnippets subscriptionSnippets = new SubscriptionSnippets(subscription);
    pubsub.publish(TOPIC, MESSAGE1, MESSAGE2);
    subscriptionSnippets.pull();
    // messages have been acked, we should pull nothing
    Iterator<ReceivedMessage> iterator = pubsub.pull(SUBSCRIPTION, 2);
    assertFalse(iterator.hasNext());
    pubsub.publish(TOPIC, MESSAGE1, MESSAGE2);
    subscriptionSnippets.pullAsync();
    // messages have been acked, we should pull nothing
    iterator = pubsub.pull(SUBSCRIPTION, 2);
    assertFalse(iterator.hasNext());
    subscriptionSnippets.pullAsync();
  }

  @Test
  public void testPolicy() throws ExecutionException, InterruptedException {
    SubscriptionSnippets subscriptionSnippets = new SubscriptionSnippets(subscription);
    Policy policy = subscriptionSnippets.getPolicy();
    assertNotNull(policy);
    assertEquals(policy, subscriptionSnippets.getPolicyAsync());
    policy = subscriptionSnippets.replacePolicy();
    assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers()));
    policy = subscription.replacePolicy(policy.toBuilder()
        .removeIdentity(Role.viewer(), Identity.allAuthenticatedUsers())
        .build());
    assertFalse(policy.getBindings().containsKey(Role.viewer()));
    policy = subscriptionSnippets.replacePolicyAsync();
    assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers()));
    assertTrue(subscriptionSnippets.delete());
    assertFalse(subscriptionSnippets.deleteAsync());
  }
}


text:
<?php

namespace Google\Service\Dataproc;

class JobScheduling extends \Google\Model
{
  /**
   * @var int
   */
  public $maxFailuresPerHour;
  /**
   * @var int
   */
  public $maxFailuresTotal;

  /**
   * @param int
   */
  public function setMaxFailuresPerHour($maxFailuresPerHour)
  {
    $this->maxFailuresPerHour = $maxFailuresPerHour;
  }
  /**
   * @return int
   */
  public function getMaxFailuresPerHour()
  {
    return $this->maxFailuresPerHour;
  }
  /**
   * @param int
   */
  public function setMaxFailuresTotal($maxFailuresTotal)
  {
    $this->maxFailuresTotal = $maxFailuresTotal;
  }
  /**
   * @return int
   */
  public function getMaxFailuresTotal()
  {
    return $this->maxFailuresTotal;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(JobScheduling::class, 'Google_Service_Dataproc_JobScheduling');


text: /austinteer@gmail.com/


text:
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Wirly.web.Models
{
    public class AppUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string StartPage { get; set; }

        public virtual ICollection<Project> Projects { get; set; }
    }
}


text:
<?xml version="1.0" encoding="windows-1252" ?>
<!DOCTYPE ViewObject SYSTEM "jbo_03_01.dtd">
<!---->
<ViewObject
  xmlns="http://xmlns.oracle.com/bc4j"
  Name="DocumentAccessView"
  Version="12.1.3.13.52"
  InheritPersonalization="merge"
  SelectListFlags="1"
  FromListFlags="1"
  WhereFlags="1"
  BindingStyle="OracleName"
  CustomQuery="false"
  SelectAllAttributes="false"
  RowClass="nl.amis.bth.model.DocumentAccessViewRowImpl"
  ComponentClass="nl.amis.bth.model.DocumentAccessViewImpl"
  PageIterMode="Full"
  ComponentInterface="nl.amis.bth.model.common.DocumentAccessView"
  ClientProxyName="nl.amis.bth.model.client.DocumentAccessViewClient"
  RowInterface="nl.amis.bth.model.common.DocumentAccessViewRow"
  ClientRowProxyName="nl.amis.bth.model.client.DocumentAccessViewRowClient">
  <DesignTime>
    <Attr Name="_codeGenFlag2" Value="Access|Coll|Prog|VarAccess"/>
    <Attr Name="_isCodegen" Value="true"/>
  </DesignTime>
  <Properties>
    <SchemaBasedProperties>
      <LABEL
        ResId="nl.amis.bth.model.DocumentAccessView_LABEL"/>
    </SchemaBasedProperties>
  </Properties>
  <Variable
    Name="bind_DocumentId"
    Kind="where"
    Type="oracle.jbo.domain.Number"/>
  <EntityUsage
    Name="BthDocument"
    Entity="nl.amis.bth.model.BthDocument"/>
  <ViewAttribute
    Name="ContentData"
    IsQueriable="false"
    PrecisionRule="true"
    EntityAttrName="ContentData"
    EntityUsage="BthDocument"
    AliasName="CONTENT_DATA"/>
  <ViewAttribute
    Name="ContentType"
    PrecisionRule="true"
    EntityAttrName="ContentType"
    EntityUsage="BthDocument"
    AliasName="CONTENT_TYPE"/>
  <ViewAttribute
    Name="Description"
    PrecisionRule="true"
    EntityAttrName="Description"
    EntityUsage="BthDocument"
    AliasName="DESCRIPTION"/>
  <ViewAttribute
    Name="Id"
    IsNotNull="true"
    PrecisionRule="true"
    EntityAttrName="Id"
    EntityUsage="BthDocument"
    AliasName="ID"/>
  <ViewAttribute
    Name="MasterId"
    PrecisionRule="true"
    EntityAttrName="MasterId"
    EntityUsage="BthDocument"
    AliasName="MASTER_ID"/>
  <ViewAttribute
    Name="Name"
    PrecisionRule="true"
    EntityAttrName="Name"
    EntityUsage="BthDocument"
    AliasName="NAME"/>
  <ClientInterface
    Name="__clientInterface">
    <Method
      Name="setbind_DocumentId"
      MethodName="setbind_DocumentId">
      <Return
        Name="_return_type_"
        Type="void"/>
      <Parameter
        Name="value"
        Type="oracle.jbo.domain.Number"/>
    </Method>
    <Method
      Name="getImageById"
      MethodName="getImageById">
      <Return
        Name="_return_type_"
        Type="oracle.jbo.Row"/>
      <Parameter
        Name="aId"
        Type="oracle.jbo.domain.Number"/>
    </Method>
  </ClientInterface>
  <ResourceBundle>
    <PropertiesBundle
      PropertiesFile="nl.amis.bth.model.ModelBundle"/>
  </ResourceBundle>
  <DeclarativeWhereClause
    Name="DeclarativeWhereClause">
    <ViewCriteria
      Name="DocumentAccessViewWhereCriteria"
      ViewObjectName="nl.amis.bth.model.DocumentAccessView"
      Conjunction="AND"
      Mode="3">
      <ViewCriteria
        Name="DocumentAccessViewSubCriteria1"
        ViewObjectName="nl.amis.bth.model.DocumentAccessView"
        Conjunction="AND">
        <ViewCriteriaRow
          Name="DocumentAccessViewSubCriteria1_row_0"
          UpperColumns="1">
          <ViewCriteriaItem
            Name="Id"
            ViewAttribute="Id"
            Operator="="
            Conjunction="AND"
            Value=":bind_DocumentId"
            GenerateIsNullClauseForBindVars="false"
            IsBindVarValue="true"
            Required="Optional"/>
        </ViewCriteriaRow>
      </ViewCriteria>
    </ViewCriteria>
  </DeclarativeWhereClause>
</ViewObject>


text:
/********************************************************************************
** Form generated from reading UI file 'qttrajectoryanalysis.ui'
**
** Created by: Qt User Interface Compiler version 4.8.6
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_QTTRAJECTORYANALYSIS_H
#define UI_QTTRAJECTORYANALYSIS_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QGraphicsView>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QProgressBar>
#include <QtGui/QPushButton>
#include <QtGui/QToolButton>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_QtTrajectoryAnalysisClass
{
public:
    QWidget *widget_background;
    QGraphicsView *srcImgView;
    QGraphicsView *dstImgView;
    QLineEdit *lEd_OutputFolder;
    QPushButton *pBtn_OutputFolder;
    QProgressBar *progress_bar;
    QLabel *label;
    QPushButton *pBtn_quit;
    QToolButton *pBtn_Run;
    QToolButton *pBtn_Check;
    QToolButton *pBtn_Analysis;

    void setupUi(QDialog *QtTrajectoryAnalysisClass)
    {
        if (QtTrajectoryAnalysisClass->objectName().isEmpty())
            QtTrajectoryAnalysisClass->setObjectName(QString::fromUtf8("QtTrajectoryAnalysisClass"));
        QtTrajectoryAnalysisClass->resize(900, 600);
        QtTrajectoryAnalysisClass->setMinimumSize(QSize(900, 600));
        QtTrajectoryAnalysisClass->setMaximumSize(QSize(900, 600));
        QIcon icon;
        icon.addFile(QString::fromUtf8(":/QtTrajectoryAnalysis/Resources/trajectoryAnalysis.ico"), QSize(), QIcon::Normal, QIcon::Off);
        QtTrajectoryAnalysisClass->setWindowIcon(icon);
        widget_background = new QWidget(QtTrajectoryAnalysisClass);
        widget_background->setObjectName(QString::fromUtf8("widget_background"));
        widget_background->setGeometry(QRect(0, 0, 900, 600));
        widget_background->setAutoFillBackground(false);
        widget_background->setStyleSheet(QString::fromUtf8("QWidget#widget_background{border-image: url(:/QtTrajectoryAnalysis/Resources/background.png)}"));
        srcImgView = new QGraphicsView(widget_background);
        srcImgView->setObjectName(QString::fromUtf8("srcImgView"));
        srcImgView->setGeometry(QRect(70, 115, 360, 270));
        srcImgView->setMinimumSize(QSize(200, 200));
        srcImgView->setMaximumSize(QSize(1600, 1600));
        srcImgView->setAutoFillBackground(true);
        srcImgView->setStyleSheet(QString::fromUtf8(""));
        dstImgView = new QGraphicsView(widget_background);
        dstImgView->setObjectName(QString::fromUtf8("dstImgView"));
        dstImgView->setGeometry(QRect(470, 115, 360, 270));
        dstImgView->setStyleSheet(QString::fromUtf8(""));
        lEd_OutputFolder = new QLineEdit(widget_background);
        lEd_OutputFolder->setObjectName(QString::fromUtf8("lEd_OutputFolder"));
        lEd_OutputFolder->setGeometry(QRect(140, 415, 291, 21));
        lEd_OutputFolder->setStyleSheet(QString::fromUtf8("font: 75 10pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n"
"color: #4f4f4f;\n"
"background-color: #e4e9e9;"));
        pBtn_OutputFolder = new QPushButton(widget_background);
        pBtn_OutputFolder->setObjectName(QString::fromUtf8("pBtn_OutputFolder"));
        pBtn_OutputFolder->setGeometry(QRect(70, 415, 61, 21));
        pBtn_OutputFolder->setStyleSheet(QString::fromUtf8("font: 75 9pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n"
"color: #4f4f4f;\n"
"background-color: #f7a562"));
        pBtn_OutputFolder->setIconSize(QSize(32, 32));
        progress_bar = new QProgressBar(widget_background);
        progress_bar->setObjectName(QString::fromUtf8("progress_bar"));
        progress_bar->setGeometry(QRect(70, 385, 360, 21));
        QFont font;
        font.setFamily(QString::fromUtf8("\345\276\256\350\275\257\351\233\205\351\273\221"));
        font.setPointSize(10);
        font.setBold(false);
        font.setItalic(false);
        font.setWeight(9);
        progress_bar->setFont(font);
        progress_bar->setStyleSheet(QString::fromUtf8("font: 75 10pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n"
"color: #4f4f4f;"));
        progress_bar->setValue(0);
        progress_bar->setAlignment(Qt::AlignCenter);
        label = new QLabel(widget_background);
        label->setObjectName(QString::fromUtf8("label"));
        label->setGeometry(QRect(630, 470, 201, 61));
        label->setLayoutDirection(Qt::RightToLeft);
        label->setStyleSheet(QString::fromUtf8("font: 75 16pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n"
"color: #4f4f4f;"));
        label->setAlignment(Qt::AlignCenter);
        pBtn_quit = new QPushButton(widget_background);
        pBtn_quit->setObjectName(QString::fromUtf8("pBtn_quit"));
        pBtn_quit->setEnabled(true);
        pBtn_quit->setGeometry(QRect(820, 515, 25, 25));
        pBtn_quit->setStyleSheet(QString::fromUtf8("border-style:hidden"));
        QIcon icon1;
        icon1.addFile(QString::fromUtf8(":/QtTrajectoryAnalysis/Resources/quit.png"), QSize(), QIcon::Normal, QIcon::Off);
        pBtn_quit->setIcon(icon1);
        pBtn_quit->setIconSize(QSize(25, 25));
        pBtn_Run = new QToolButton(widget_background);
        pBtn_Run->setObjectName(QString::fromUtf8("pBtn_Run"));
        pBtn_Run->setGeometry(QRect(620, 395, 60, 80));
        pBtn_Run->setStyleSheet(QString::fromUtf8("border-style:hidden;\n"
"font: 75 10pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n"
"color: #4f4f4f;"));
        QIcon icon2;
        icon2.addFile(QString::fromUtf8(":/QtTrajectoryAnalysis/Resources/startanalyze.png"), QSize(), QIcon::Normal, QIcon::Off);
        pBtn_Run->setIcon(icon2);
        pBtn_Run->setIconSize(QSize(60, 60));
        pBtn_Run->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        pBtn_Check = new QToolButton(widget_background);
        pBtn_Check->setObjectName(QString::fromUtf8("pBtn_Check"));
        pBtn_Check->setGeometry(QRect(490, 395, 60, 80));
        pBtn_Check->setStyleSheet(QString::fromUtf8("border-style:hidden;\n"
"font: 75 10pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n"
"color: #4f4f4f;"));
        QIcon icon3;
        icon3.addFile(QString::fromUtf8(":/QtTrajectoryAnalysis/Resources/check.png"), QSize(), QIcon::Normal, QIcon::Off);
        pBtn_Check->setIcon(icon3);
        pBtn_Check->setIconSize(QSize(60, 60));
        pBtn_Check->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        pBtn_Analysis = new QToolButton(widget_background);
        pBtn_Analysis->setObjectName(QString::fromUtf8("pBtn_Analysis"));
        pBtn_Analysis->setGeometry(QRect(750, 395, 60, 80));
        pBtn_Analysis->setStyleSheet(QString::fromUtf8("border-style:hidden;\n"
"font: 75 10pt \"\345\276\256\350\275\257\351\233\205\351\273\221\";\n"
"color: #4f4f4f;"));
        QIcon icon4;
        icon4.addFile(QString::fromUtf8(":/QtTrajectoryAnalysis/Resources/graphique.png"), QSize(), QIcon::Normal, QIcon::Off);
        pBtn_Analysis->setIcon(icon4);
        pBtn_Analysis->setIconSize(QSize(60, 60));
        pBtn_Analysis->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);

        retranslateUi(QtTrajectoryAnalysisClass);

        QMetaObject::connectSlotsByName(QtTrajectoryAnalysisClass);
    } // setupUi

    void retranslateUi(QDialog *QtTrajectoryAnalysisClass)
    {
        QtTrajectoryAnalysisClass->setWindowTitle(QApplication::translate("QtTrajectoryAnalysisClass", "QtTrajectoryAnalysis", 0, QApplication::UnicodeUTF8));
        pBtn_OutputFolder->setText(QApplication::translate("QtTrajectoryAnalysisClass", "\344\277\235\345\255\230\350\267\257\345\276\204", 0, QApplication::UnicodeUTF8));
        label->setText(QApplication::translate("QtTrajectoryAnalysisClass", "\344\272\272\346\265\201\350\275\250\350\277\271\345\210\206\346\236\220\346\234\215\345\212\241", 0, QApplication::UnicodeUTF8));
        pBtn_quit->setText(QString());
        pBtn_Run->setText(QApplication::translate("QtTrajectoryAnalysisClass", "\346\231\272\350\203\275\345\210\206\346\236\220", 0, QApplication::UnicodeUTF8));
        pBtn_Check->setText(QApplication::translate("QtTrajectoryAnalysisClass", "\346\237\245\347\234\213\346\226\207\344\273\266", 0, QApplication::UnicodeUTF8));
        pBtn_Analysis->setText(QApplication::translate("QtTrajectoryAnalysisClass", "\345\210\206\346\236\220\346\225\260\346\215\256", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class QtTrajectoryAnalysisClass: public Ui_QtTrajectoryAnalysisClass {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_QTTRAJECTORYANALYSIS_H


text:
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
$process = $null
$bits = Get-ProcessorBits
if ($bits -eq '64')
    {
    Start-Process "${env:ProgramFiles(x86)}\MP3Gain\uninst-mp3gain.exe"
    }
    else
    {
    Start-Process "$env:ProgramFiles\MP3Gain\uninst-mp3gain.exe"
    }
$processname = 'A~NSISu_'
while($process.MainWindowTitle -eq "MP3Gain Uninstall" -eq $false)
{
    $process = Get-Process $processname -ErrorAction SilentlyContinue
}
[System.Windows.Forms.SendKeys]::SendWait("{LEFT}")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
sleep 3
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
sleep 3
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")


text:
class AddDistrictAssociationToClerksAndAdmins < ActiveRecord::Migration
  def change
    add_column :admins, :district_id, :integer
    add_column :clerks, :district_id, :integer
  end
end


text:
package com.sequenceiq.cloudbreak.api.endpoint.v4.userprofile.responses;

import com.sequenceiq.cloudbreak.api.endpoint.v4.userprofile.requests.DurationV4Base;

import io.swagger.annotations.ApiModel;

@ApiModel
public class DurationV4Response extends DurationV4Base {
}


text:
package org.apache.rahas;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.util.Base64;
import org.apache.neethi.Policy;
import org.apache.rampart.handler.config.InflowConfiguration;
import org.apache.rampart.handler.config.OutflowConfiguration;
import org.apache.ws.secpolicy.SP12Constants;
import org.apache.ws.secpolicy.SPConstants;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.util.WSSecurityUtil;
import org.opensaml.XML;

public class RahasSAMLTokenUTForHoKV1205Test extends TestClient {

    byte[] clientEntr;

    /**
     * @param name
     */
    public RahasSAMLTokenUTForHoKV1205Test(String name) {
        super(name);
    }

    public OMElement getRequest() {
        try {
            OMElement rstElem = TrustUtil.createRequestSecurityTokenElement(RahasConstants.VERSION_05_12);
            TrustUtil.createRequestTypeElement(RahasConstants.VERSION_05_12, rstElem, RahasConstants.REQ_TYPE_ISSUE);
            OMElement tokenTypeElem = TrustUtil.createTokenTypeElement(RahasConstants.VERSION_05_12, rstElem);
            tokenTypeElem.setText(RahasConstants.TOK_TYPE_SAML_10);

            TrustUtil.createAppliesToElement(rstElem,
//                    "https://207.200.37.116/Ping/Scenario1", this.getWSANamespace());
                    "http://localhost:5555/axis2/services/SecureService", this.getWSANamespace());
            TrustUtil.createKeyTypeElement(RahasConstants.VERSION_05_12,
                    rstElem, RahasConstants.KEY_TYPE_SYMM_KEY);
            TrustUtil.createKeySizeElement(RahasConstants.VERSION_05_12, rstElem, 256);

            byte[] nonce = WSSecurityUtil.generateNonce(16);
            clientEntr = nonce;
            OMElement entrElem = TrustUtil.createEntropyElement(RahasConstants.VERSION_05_12, rstElem);
            TrustUtil.createBinarySecretElement(RahasConstants.VERSION_05_12, entrElem, RahasConstants.BIN_SEC_TYPE_NONCE).setText(Base64.encode(nonce));
            TrustUtil.createComputedKeyAlgorithm(RahasConstants.VERSION_05_12,rstElem, RahasConstants.COMPUTED_KEY_PSHA1);

            return rstElem;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public OutflowConfiguration getClientOutflowConfiguration() {
        OutflowConfiguration ofc = new OutflowConfiguration();

        ofc.setActionItems("UsernameToken Timestamp");
        ofc.setUser("joe");
        ofc.setPasswordType(WSConstants.PW_TEXT);
        ofc.setPasswordCallbackClass(PWCallback.class.getName());
        return ofc;
    }

    public InflowConfiguration getClientInflowConfiguration() {
        InflowConfiguration ifc = new InflowConfiguration();

        ifc.setActionItems("Timestamp");

        return ifc;
    }

    public String getServiceRepo() {
        return "rahas_service_repo_3";
    }

    public String getRequestAction() throws TrustException {
        return TrustUtil.getActionValue(RahasConstants.VERSION_05_12, RahasConstants.RST_ACTION_ISSUE);
    }

    public void validateRsponse(OMElement resp) {
        OMElement rstr = resp.getFirstChildWithName(new QName(RahasConstants.WST_NS_05_12,
                                                              RahasConstants.LocalNames.
                                                                      REQUEST_SECURITY_TOKEN_RESPONSE));
        assertNotNull("RequestedSecurityTokenResponse missing", rstr);
        OMElement rst = rstr.getFirstChildWithName(new QName(RahasConstants.WST_NS_05_12,
                                                             RahasConstants.IssuanceBindingLocalNames.
                                                                     REQUESTED_SECURITY_TOKEN));
        assertNotNull("RequestedSecurityToken missing", rst);

        OMElement elem = rst.getFirstChildWithName(new QName(XML.SAML_NS, "Assertion"));
        assertNotNull("Missing SAML Assertoin", elem);

        //Uncomment for inteorp - START
//        String respEntrB64 = rstr.getFirstChildWithName(new QName(RahasConstants.WST_NS_05_12, RahasConstants.ENTROPY_LN)).getFirstChildWithName(new QName(RahasConstants.WST_NS_05_12, RahasConstants.BINARY_SECRET_LN)).getText().trim();
//
//
//
//        OMElement attrStmtElem = elem.getFirstChildWithName(new QName(XML.SAML_NS, "AttributeStatement"));
//        OMElement kiElem = attrStmtElem.getFirstChildWithName(new QName(XML.SAML_NS,"Subject")).getFirstChildWithName(new QName(XML.SAML_NS,"SubjectConfirmation")).getFirstChildWithName(new QName("http://www.w3.org/2000/09/xmldsig#", "KeyInfo"));
//        OMElement encrKey = kiElem.getFirstChildWithName(new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"));
//
//
//        String cipherValue = encrKey.getFirstChildWithName(new QName("http://www.w3.org/2001/04/xmlenc#", "CipherData")).getFirstChildWithName(new QName("http://www.w3.org/2001/04/xmlenc#", "CipherValue")).getText();
//
//        byte[] serviceEntr = Base64.decode(respEntrB64);

//      try {
//          this.requestService(elem, clientEntr, serviceEntr);
//      } catch (Exception e) {
//          e.printStackTrace();
//      }

        //Uncomment for inteorp - END

    }

    public Policy getServicePolicy() throws Exception {
        return this.getPolicy("test-resources/rahas/policy/service-policy-transport-binding.xml");
    }

    public Policy getSTSPolicy() throws Exception {
        return this.getPolicy("test-resources/rahas/policy/sts-policy-transport-binding.xml");
    }

    /* (non-Javadoc)
     * @see org.apache.rahas.TestClient#getRSTTemplate()
     */
    public OMElement getRSTTemplate() throws TrustException {
        OMFactory factory = OMAbstractFactory.getOMFactory();
        OMElement elem = factory.createOMElement(SP12Constants.REQUEST_SECURITY_TOKEN_TEMPLATE);

        TrustUtil.createTokenTypeElement(RahasConstants.VERSION_05_12, elem).setText(RahasConstants.TOK_TYPE_SAML_10);
        TrustUtil.createKeyTypeElement(RahasConstants.VERSION_05_12, elem, RahasConstants.KEY_TYPE_SYMM_KEY);
        TrustUtil.createKeySizeElement(RahasConstants.VERSION_05_12, elem, 256);

        return elem;
    }

    public int getTrstVersion() {
        return RahasConstants.VERSION_05_12;
    }

//    private void requestService(OMElement assertion, byte[] reqEnt, byte[] respEnt) throws Exception {
//
//        StAXOMBuilder builder = new StAXOMBuilder(new OMDOMFactory(), assertion.getXMLStreamReader());
//        Element domAssertionElem = (Element)builder.getDocumentElement();
//
//        DocumentBuilderFactoryImpl.setDOOMRequired(true);
//        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
//
//        SOAPFactory fac = new SOAP11Factory((DocumentImpl)doc);
//        SOAPEnvelope envelope = fac.getDefaultEnvelope();
//        this.addPayload(envelope);
//
//        WSSecHeader secHeader = new WSSecHeader();
//        secHeader.insertSecurityHeader(doc);
//
//        WSSecTimestamp ts = new WSSecTimestamp();
//        ts.prepare(doc);
//        ts.prependToHeader(secHeader);
//
//        WSSecDKSign sig = new WSSecDKSign();
//        sig.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
//        P_SHA1 p_sha1 = new P_SHA1();
//        SecurityTokenReference ref = new SecurityTokenReference(doc);
//        ref.setSAMLKeyIdentifier(assertion.getAttributeValue(new QName("AssertionID")));
//
//        System.out.println("\nRequest Entropy: " + Base64.encode(reqEnt));
//        System.out.println("Response Entropy: " + Base64.encode(respEnt));
//
//        byte[] ephmeralKey = p_sha1.createKey(reqEnt, respEnt, 0, 32);
//
//        System.out.println( ephmeralKey.length * 8 + " bit Key: " + Base64.encode(ephmeralKey));
//
//        sig.setExternalKey(ephmeralKey, ref.getElement());
//
//        WSEncryptionPart part = new WSEncryptionPart(WSConstants.TIMESTAMP_TOKEN_LN, WSConstants.WSU_NS, "Element");
//        Vector partsVector = new Vector();
//        partsVector.add(part);
//        sig.setParts(partsVector);
//
//        sig.prepare(doc, secHeader);
//        sig.addReferencesToSign(partsVector, secHeader);
//        sig.computeSignature();
//
//        Element importedAssertionElement = (Element) doc.importNode(domAssertionElem, true);
//        WSSecurityUtil.appendChildElement(doc, secHeader.getSecurityHeader(), importedAssertionElement);
//        sig.appendDKElementToHeader(secHeader);
//        sig.appendSigToHeader(secHeader);
//
//
//        System.out.println(envelope);
//
//
//        //Create a service client and send the request
//        AxisService service = new AxisService("ping");
//        AxisOperation op = new OutInAxisOperation(new QName("Ping"));
//        service.addChild(op);
//
//        ServiceClient client = new ServiceClient(ConfigurationContextFactory.createConfigurationContextFromFileSystem(Constants.TESTING_PATH + "rahas_client_repo", null), service);
//
//
//        OperationClient opClient = client.createClient(new QName("Ping"));
//        MessageContext mc = new MessageContext();
//        mc.setEnvelope(envelope);
//
//        client.engageModule(new QName("addressing"));
//        client.engageModule(new QName("rampart"));
//
//        opClient.addMessageContext(mc);
////        opClient.getOptions().setTo(new EndpointReference("https://131.107.72.15/PingService/OasisScenario1"));
//        opClient.getOptions().setTo(new EndpointReference("https://207.200.37.116/Ping/Scenario1"));
//
//        opClient.getOptions().setAction("http://example.org/Ping");
////        opClient.getOptions().setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE);
//
//        opClient.execute(true);
//        MessageContext response = opClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
//        System.out.println("------------------------------RESPONSE------------------------------\n" + response.getEnvelope());
//
//    }
//
//    private void addPayload(SOAPEnvelope env) {
//        //<Ping xmlns="http://example.org/Ping">Ping</Ping>
//        OMNamespace ns = env.getOMFactory().createOMNamespace("http://example.org/Ping", "");
//        OMElement elem = env.getOMFactory().createOMElement("Ping", ns);
//        elem.setText("Ping");
//
//        env.getBody().addChild(elem);
//    }

}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\CoreBundle\Fixture;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;

class CatalogPromotionFixture extends AbstractResourceFixture
{
    public function getName(): string
    {
        return 'catalog_promotion';
    }

    protected function configureResourceNode(ArrayNodeDefinition $resourceNode): void
    {
        $resourceNode
            ->children()
                ->scalarNode('code')->cannotBeEmpty()->end()
                ->scalarNode('name')->cannotBeEmpty()->end()
                ->scalarNode('label')->cannotBeEmpty()->end()
                ->scalarNode('description')->cannotBeEmpty()->end()
                ->booleanNode('exclusive')->end()
                ->integerNode('priority')->end()
                ->scalarNode('start_date')->cannotBeEmpty()->end()
                ->scalarNode('end_date')->cannotBeEmpty()->end()
                ->variableNode('channels')
                    ->beforeNormalization()
                        ->ifNull()->thenUnset()
                    ->end()
                ->end()
                ->arrayNode('scopes')
                    ->requiresAtLeastOneElement()
                    ->arrayPrototype()
                        ->children()
                            ->scalarNode('type')->cannotBeEmpty()->end()
                            ->scalarNode('catalogPromotion')->cannotBeEmpty()->end()
                            ->variableNode('configuration')->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('actions')
                    ->requiresAtLeastOneElement()
                    ->arrayPrototype()
                        ->children()
                            ->scalarNode('type')->cannotBeEmpty()->end()
                            ->scalarNode('catalogPromotion')->cannotBeEmpty()->end()
                            ->variableNode('configuration')->end()
                        ->end()
                    ->end()
                ->end()
        ;
    }
}


text:
Generate static pages with the asset pipeline on Rails.

## Installation

Put this line in your Gemfile:

```
gem 'stopover'
```

Run the bundle command to install it.

After you install Stopover, you need to run the generator:

```
rails generate stopover:install
```

And add to your routes.rb if you want to check pages on your browser:

```
mount Stopover::Engine, at: '/stopover', as: :stopover if Rails.env.development?
```

Then visit http://localhost:3000/stopover.

## Usage

Stopover is called after `rake assets:precompile` automatically.
And for example,  `app/views/stopover/404.html.erb` is compiled to `public/404.html`.

You can also stop the hook with `disable_hook_assets_precompile = true` in [stopover.rb](https://github.com/rono23/stopover/blob/master/lib/generators/stopover/templates/stopover.rb#L5) and call `rake stopover:create` by yourself.

#### Heroku

Using Stopover on Heroku requires settings:

```
# config/environments/production.rb
config.action_controller.asset_host = 'https://xxx.herokuapp.com'

# config/initializers/stopover.rb
config.disable_hook_assets_precompile = false
```

## Notice

Before deploy, please run `rake assets:precompile` or  `rake stopover:create` and check compiled html in local when created/updated views in stopover.
Because there are some differences between a browser and rake.

For example, when you are using devise and a view calls `user_signed_in?`, it will return true/false on a browser, but raise an error on rake because of `request.env['warden']` is nil.
In this case, you can set `current_user` in [stopover.rb](https://github.com/rono23/stopover/blob/master/lib/generators/stopover/templates/stopover.rb#L27) and it is always handled as a guest on both.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package org.apache.flink.table.client.gateway.local;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.JobID;
import org.apache.flink.client.cli.ClientOptions;
import org.apache.flink.client.deployment.ClusterClientFactory;
import org.apache.flink.client.deployment.ClusterClientServiceLoader;
import org.apache.flink.client.deployment.ClusterDescriptor;
import org.apache.flink.client.deployment.DefaultClusterClientServiceLoader;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.core.execution.SavepointFormatType;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentInternal;
import org.apache.flink.table.api.internal.TableResultInternal;
import org.apache.flink.table.client.gateway.Executor;
import org.apache.flink.table.client.gateway.ResultDescriptor;
import org.apache.flink.table.client.gateway.SqlExecutionException;
import org.apache.flink.table.client.gateway.TypedResult;
import org.apache.flink.table.client.gateway.context.DefaultContext;
import org.apache.flink.table.client.gateway.context.ExecutionContext;
import org.apache.flink.table.client.gateway.context.SessionContext;
import org.apache.flink.table.client.gateway.local.result.ChangelogResult;
import org.apache.flink.table.client.gateway.local.result.DynamicResult;
import org.apache.flink.table.client.gateway.local.result.MaterializedResult;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.operations.ModifyOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.Preconditions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import static org.apache.flink.table.client.cli.CliStrings.MESSAGE_SQL_EXECUTION_ERROR;
import static org.apache.flink.util.Preconditions.checkArgument;

/**
 * Executor that performs the Flink communication locally. The calls are blocking depending on the
 * response time to the Flink cluster. Flink jobs are not blocking.
 */
public class LocalExecutor implements Executor {

    private static final Logger LOG = LoggerFactory.getLogger(LocalExecutor.class);

    // Map to hold all the available sessions. the key is session identifier, and the value is the
    // SessionContext
    private final ConcurrentHashMap<String, SessionContext> contextMap;

    // result maintenance
    private final ResultStore resultStore;
    private final DefaultContext defaultContext;

    private final ClusterClientServiceLoader clusterClientServiceLoader;

    /** Creates a local executor for submitting table programs and retrieving results. */
    public LocalExecutor(DefaultContext defaultContext) {
        this.contextMap = new ConcurrentHashMap<>();
        this.resultStore = new ResultStore();
        this.defaultContext = defaultContext;
        this.clusterClientServiceLoader = new DefaultClusterClientServiceLoader();
    }

    @Override
    public void start() {
        // nothing to do yet
    }

    @Override
    public String openSession(@Nullable String sessionId) throws SqlExecutionException {
        SessionContext sessionContext =
                LocalContextUtils.buildSessionContext(sessionId, defaultContext);
        sessionId = sessionContext.getSessionId();
        if (this.contextMap.containsKey(sessionId)) {
            throw new SqlExecutionException(
                    "Found another session with the same session identifier: " + sessionId);
        } else {
            this.contextMap.put(sessionId, sessionContext);
        }
        return sessionId;
    }

    @Override
    public void closeSession(String sessionId) throws SqlExecutionException {
        resultStore
                .getResults()
                .forEach(
                        (resultId) -> {
                            try {
                                cancelQuery(sessionId, resultId);
                            } catch (Throwable t) {
                                // ignore any throwable to keep the clean up running
                            }
                        });
        // Remove the session's ExecutionContext from contextMap and close it.
        SessionContext context = this.contextMap.remove(sessionId);
        if (context != null) {
            context.close();
        }
    }

    private SessionContext getSessionContext(String sessionId) {
        SessionContext context = this.contextMap.get(sessionId);
        if (context == null) {
            throw new SqlExecutionException("Invalid session identifier: " + sessionId);
        }
        return context;
    }

    /**
     * Get the existed {@link ExecutionContext} from contextMap, or thrown exception if does not
     * exist.
     */
    @VisibleForTesting
    protected ExecutionContext getExecutionContext(String sessionId) throws SqlExecutionException {
        return getSessionContext(sessionId).getExecutionContext();
    }

    @Override
    public Map<String, String> getSessionConfigMap(String sessionId) throws SqlExecutionException {
        return getSessionContext(sessionId).getConfigMap();
    }

    @Override
    public ReadableConfig getSessionConfig(String sessionId) throws SqlExecutionException {
        return getSessionContext(sessionId).getReadableConfig();
    }

    @Override
    public void resetSessionProperties(String sessionId) throws SqlExecutionException {
        SessionContext context = getSessionContext(sessionId);
        context.reset();
    }

    @Override
    public void resetSessionProperty(String sessionId, String key) throws SqlExecutionException {
        SessionContext context = getSessionContext(sessionId);
        context.reset(key);
    }

    @Override
    public void setSessionProperty(String sessionId, String key, String value)
            throws SqlExecutionException {
        SessionContext context = getSessionContext(sessionId);
        context.set(key, value);
    }

    @Override
    public Operation parseStatement(String sessionId, String statement)
            throws SqlExecutionException {
        final ExecutionContext context = getExecutionContext(sessionId);
        final TableEnvironment tableEnv = context.getTableEnvironment();
        Parser parser = ((TableEnvironmentInternal) tableEnv).getParser();

        List<Operation> operations;
        try {
            operations = parser.parse(statement);
        } catch (Throwable t) {
            throw new SqlExecutionException("Failed to parse statement: " + statement, t);
        }
        if (operations.isEmpty()) {
            throw new SqlExecutionException("Failed to parse statement: " + statement);
        }
        return operations.get(0);
    }

    @Override
    public List<String> completeStatement(String sessionId, String statement, int position) {
        final ExecutionContext context = getExecutionContext(sessionId);
        final TableEnvironmentInternal tableEnv =
                (TableEnvironmentInternal) context.getTableEnvironment();

        try {
            return Arrays.asList(tableEnv.getParser().getCompletionHints(statement, position));
        } catch (Throwable t) {
            // catch everything such that the query does not crash the executor
            if (LOG.isDebugEnabled()) {
                LOG.debug("Could not complete statement at " + position + ":" + statement, t);
            }
            return Collections.emptyList();
        }
    }

    @Override
    public TableResultInternal executeOperation(String sessionId, Operation operation)
            throws SqlExecutionException {
        final ExecutionContext context = getExecutionContext(sessionId);
        final TableEnvironmentInternal tEnv =
                (TableEnvironmentInternal) context.getTableEnvironment();
        try {
            return tEnv.executeInternal(operation);
        } catch (Throwable t) {
            throw new SqlExecutionException(MESSAGE_SQL_EXECUTION_ERROR, t);
        }
    }

    @Override
    public TableResultInternal executeModifyOperations(
            String sessionId, List<ModifyOperation> operations) throws SqlExecutionException {
        final ExecutionContext context = getExecutionContext(sessionId);
        final TableEnvironmentInternal tEnv =
                (TableEnvironmentInternal) context.getTableEnvironment();
        try {
            return tEnv.executeInternal(operations);
        } catch (Throwable t) {
            throw new SqlExecutionException(MESSAGE_SQL_EXECUTION_ERROR, t);
        }
    }

    @Override
    public ResultDescriptor executeQuery(String sessionId, QueryOperation query)
            throws SqlExecutionException {
        final TableResultInternal tableResult = executeOperation(sessionId, query);
        final SessionContext context = getSessionContext(sessionId);
        final ReadableConfig config = context.getReadableConfig();
        final DynamicResult result = resultStore.createResult(config, tableResult);
        checkArgument(tableResult.getJobClient().isPresent());
        String jobId = tableResult.getJobClient().get().getJobID().toString();
        // store the result under the JobID
        resultStore.storeResult(jobId, result);
        return new ResultDescriptor(
                jobId,
                tableResult.getResolvedSchema(),
                result.isMaterialized(),
                config,
                tableResult.getRowDataToStringConverter());
    }

    @Override
    public TypedResult<List<RowData>> retrieveResultChanges(String sessionId, String resultId)
            throws SqlExecutionException {
        final DynamicResult result = resultStore.getResult(resultId);
        if (result == null) {
            throw new SqlExecutionException(
                    "Could not find a result with result identifier '" + resultId + "'.");
        }
        if (result.isMaterialized()) {
            throw new SqlExecutionException("Invalid result retrieval mode.");
        }
        return ((ChangelogResult) result).retrieveChanges();
    }

    @Override
    public TypedResult<Integer> snapshotResult(String sessionId, String resultId, int pageSize)
            throws SqlExecutionException {
        final DynamicResult result = resultStore.getResult(resultId);
        if (result == null) {
            throw new SqlExecutionException(
                    "Could not find a result with result identifier '" + resultId + "'.");
        }
        if (!result.isMaterialized()) {
            throw new SqlExecutionException("Invalid result retrieval mode.");
        }
        return ((MaterializedResult) result).snapshot(pageSize);
    }

    @Override
    public List<RowData> retrieveResultPage(String resultId, int page)
            throws SqlExecutionException {
        final DynamicResult result = resultStore.getResult(resultId);
        if (result == null) {
            throw new SqlExecutionException(
                    "Could not find a result with result identifier '" + resultId + "'.");
        }
        if (!result.isMaterialized()) {
            throw new SqlExecutionException("Invalid result retrieval mode.");
        }
        return ((MaterializedResult) result).retrievePage(page);
    }

    @Override
    public void cancelQuery(String sessionId, String resultId) throws SqlExecutionException {
        final DynamicResult result = resultStore.getResult(resultId);
        if (result == null) {
            throw new SqlExecutionException(
                    "Could not find a result with result identifier '" + resultId + "'.");
        }

        // stop retrieval and remove the result
        LOG.info("Cancelling job {} and result retrieval.", resultId);
        try {
            // this operator will also stop flink job
            result.close();
        } catch (Throwable t) {
            throw new SqlExecutionException("Could not cancel the query execution", t);
        }
        resultStore.removeResult(resultId);
    }

    @Override
    public void removeJar(String sessionId, String jarUrl) {
        final SessionContext context = getSessionContext(sessionId);
        context.removeJar(jarUrl);
    }

    @Override
    public Optional<String> stopJob(
            String sessionId, String jobId, boolean isWithSavepoint, boolean isWithDrain)
            throws SqlExecutionException {
        Duration clientTimeout = getSessionConfig(sessionId).get(ClientOptions.CLIENT_TIMEOUT);
        try {
            return runClusterAction(
                    sessionId,
                    clusterClient -> {
                        if (isWithSavepoint) {
                            // blocking get savepoint path
                            try {
                                String savepoint =
                                        clusterClient
                                                .stopWithSavepoint(
                                                        JobID.fromHexString(jobId),
                                                        isWithDrain,
                                                        null,
                                                        SavepointFormatType.DEFAULT)
                                                .get(
                                                        clientTimeout.toMillis(),
                                                        TimeUnit.MILLISECONDS);
                                return Optional.of(savepoint);
                            } catch (Exception e) {
                                throw new FlinkException(
                                        "Could not stop job "
                                                + jobId
                                                + " in session "
                                                + sessionId
                                                + ".",
                                        e);
                            }
                        } else {
                            clusterClient.cancel(JobID.fromHexString(jobId));
                            return Optional.empty();
                        }
                    });
        } catch (Exception e) {
            throw new SqlExecutionException(
                    "Could not stop job " + jobId + " in session " + sessionId + ".", e);
        }
    }

    /**
     * Retrieves the {@link ClusterClient} from the session and runs the given {@link ClusterAction}
     * against it.
     *
     * @param sessionId the specified session ID
     * @param clusterAction the cluster action to run against the retrieved {@link ClusterClient}.
     * @param <ClusterID> type of the cluster id
     * @param <Result>> type of the result
     * @throws FlinkException if something goes wrong
     */
    private <ClusterID, Result> Result runClusterAction(
            String sessionId, ClusterAction<ClusterID, Result> clusterAction)
            throws FlinkException {
        final SessionContext context = getSessionContext(sessionId);
        final Configuration configuration = (Configuration) context.getReadableConfig();
        final ClusterClientFactory<ClusterID> clusterClientFactory =
                context.getExecutionContext()
                        .wrapClassLoader(
                                () ->
                                        clusterClientServiceLoader.getClusterClientFactory(
                                                configuration));

        final ClusterID clusterId = clusterClientFactory.getClusterId(configuration);
        Preconditions.checkNotNull(clusterId, "No cluster ID found for session " + sessionId);

        try (final ClusterDescriptor<ClusterID> clusterDescriptor =
                        clusterClientFactory.createClusterDescriptor(configuration);
                final ClusterClient<ClusterID> clusterClient =
                        clusterDescriptor.retrieve(clusterId).getClusterClient()) {
            return clusterAction.runAction(clusterClient);
        }
    }

    /**
     * Internal interface to encapsulate cluster actions which are executed via the {@link
     * ClusterClient}.
     *
     * @param <ClusterID> type of the cluster id
     * @param <Result>> type of the result
     */
    @FunctionalInterface
    private interface ClusterAction<ClusterID, Result> {

        /**
         * Run the cluster action with the given {@link ClusterClient}.
         *
         * @param clusterClient to run the cluster action against
         * @throws FlinkException if something goes wrong
         */
        Result runAction(ClusterClient<ClusterID> clusterClient) throws FlinkException;
    }
}


text:
/*	$OpenBSD: ravenreg.h,v 1.1 2001/06/26 21:57:41 smurph Exp $ */

/*
 * Copyright (c) 2001 Steve Murphree, Jr.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed under OpenBSD for RTMX Inc
 *	by Per Fogelstrom, Opsycon AB.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *
 * ravenreg.h: Motorola 'Raven' PowerPC to PCI bridge controller
 */

#ifndef _MACHINE_RAVENREG_H_
#define _MACHINE_RAVENREG_H_

#define RAVEN_REG		0xFEFF0000
#define RAVEN_VENDOR		0xFEFF0000
#define RAVEN_MAGIC		0x10574801 /* vendor information */
#define RAVEN_DEVICE		0xFEFF0002
#define RAVEN_REVID		0xFEFF0005
#define RAVEN_GCSR		0xFEFF0008
#define RAVEN_FEAT		0xFEFF000A
#define RAVEN_MARB		0xFEFF000E
#define RAVEN_PIACK		0xFEFF0030

#define RAVEN_MSADD0		0xFEFF0040
#define RAVEN_MSADD0_PREP	0xC000FCFF
#define RAVEN_MSOFF0		0xFEFF0044
#define RAVEN_MSOFF0_PREP	0x400000C2
#define RAVEN_MSADD1		0xFEFF0048
#define RAVEN_MSADD1_PREP	0x00000000
#define RAVEN_MSOFF1		0xFEFF004C
#define RAVEN_MSOFF1_PREP	0x00000002
#define RAVEN_MSADD2		0xFEFF0050
#define RAVEN_MSADD2_PREP	0x00000000
#define RAVEN_MSOFF2		0xFEFF0054
#define RAVEN_MSOFF2_PREP	0x00000002
#define RAVEN_MSADD3		0xFEFF0058
#define RAVEN_MSADD3_PREP	0x8000BFFF
#define RAVEN_MSOFF3		0xFEFF005C
#define RAVEN_MSOFF3_PREP	0x800000C0

/* Where we map the PCI memory space - MAP A*/
#define RAVEN_V_PCI_MEM_SPACE	0xc0000000	/* Viritual */
#define RAVEN_P_PCI_MEM_SPACE	0xc0000000	/* Physical */

/* Where we map the PCI I/O space - MAP A*/
#define RAVEN_P_ISA_IO_SPACE	0x80000000
#define RAVEN_V_ISA_IO_SPACE	0x80000000
#define RAVEN_V_PCI_IO_SPACE	0x80000000
#define RAVEN_P_PCI_IO_SPACE	0x80000000

#define PREP_CONFIG_ADD		0x80000CF8
#define PREP_CONFIG_DAT		0x80000CFC

/* Where we map the config space */
#define RAVEN_PCI_CONF_SPACE	(RAVEN_V_ISA_IO_SPACE + 0x00800000)

/* Where we map the PCI memory space - MAP B*/
#define RAVEN_P_PCI_MEM_SPACE_MAP_B	0x80000000	/* Physical */

/* Where we map the PCI I/O space - MAP B*/
#define RAVEN_P_PCI_IO_SPACE_MAP_B	0xfe000000

/* offsets from base pointer */
#define	RAVEN_REGOFFS(x)	((x) | 0x80000000)

/* Where PCI devices sees CPU memory. */
#define	RAVEN_PCI_CPUMEM	0x80000000

#define RAVEN_PCI_VENDOR	0x00
#define RAVEN_PCI_DEVICE	0x02
#define RAVEN_PCI_CMD		0x04
#define RAVEN_PCI_STAT		0x06
#define RAVEN_PCI_REVID		0x08
#define RAVEN_PCI_IO		0x10
#define RAVEN_PCI_MEM		0x14
#define RAVEN_PCI_PSADD0	0x80
#define RAVEN_PCI_PSADD0_VAL	0x8000FBFF
#define RAVEN_PCI_PSOFF0	0x84
#define RAVEN_PCI_PSOFF0_VAL	0x800000F0
#define RAVEN_PCI_PSADD1	0x88
#define RAVEN_PCI_PSADD1_VAL	0xC000FCFF
#define RAVEN_PCI_PSOFF1	0x8C
#define RAVEN_PCI_PSOFF1_VAL	0x400000F0
#define RAVEN_PCI_PSADD2	0x90
#define RAVEN_PCI_PSADD2_VAL	0x00000000
#define RAVEN_PCI_PSOFF2	0x94
#define RAVEN_PCI_PSOFF2_VAL	0x00000000
#define RAVEN_PCI_PSADD3	0x98
#define RAVEN_PCI_PSADD3_VAL	0x00000000
#define RAVEN_PCI_PSOFF3	0x9C
#define RAVEN_PCI_PSOFF3_VAL	0x00000000

#define RAVEN_CMD_IOSP		0x0001
#define RAVEN_CMD_MEMSP		0x0002
#define RAVEN_CMD_MASTR		0x0004

#endif /* _MACHINE_RAVENREG_H_ */


text:
package httputil

import (
	"bufio"
	"bytes"
	"io"
	"io/ioutil"
	"log"
	"net/url"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/isucon/isucon6-final/bench/http"
	"github.com/isucon/isucon6-final/bench/http/httptest"
)

const fakeHopHeader = "X-Fake-Hop-Header-For-Test"

func init() {
	hopHeaders = append(hopHeaders, fakeHopHeader)
}

func TestReverseProxy(t *testing.T) {
	const backendResponse = "I am the backend"
	const backendStatus = 404
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" && r.FormValue("mode") == "hangup" {
			c, _, _ := w.(http.Hijacker).Hijack()
			c.Close()
			return
		}
		if len(r.TransferEncoding) > 0 {
			t.Errorf("backend got unexpected TransferEncoding: %v", r.TransferEncoding)
		}
		if r.Header.Get("X-Forwarded-For") == "" {
			t.Errorf("didn't get X-Forwarded-For header")
		}
		if c := r.Header.Get("Connection"); c != "" {
			t.Errorf("handler got Connection header value %q", c)
		}
		if c := r.Header.Get("Upgrade"); c != "" {
			t.Errorf("handler got Upgrade header value %q", c)
		}
		if c := r.Header.Get("Proxy-Connection"); c != "" {
			t.Errorf("handler got Proxy-Connection header value %q", c)
		}
		if g, e := r.Host, "some-name"; g != e {
			t.Errorf("backend got Host header %q, want %q", g, e)
		}
		w.Header().Set("Trailers", "not a special header field name")
		w.Header().Set("Trailer", "X-Trailer")
		w.Header().Set("X-Foo", "bar")
		w.Header().Set("Upgrade", "foo")
		w.Header().Set(fakeHopHeader, "foo")
		w.Header().Add("X-Multi-Value", "foo")
		w.Header().Add("X-Multi-Value", "bar")
		http.SetCookie(w, &http.Cookie{Name: "flavor", Value: "chocolateChip"})
		w.WriteHeader(backendStatus)
		w.Write([]byte(backendResponse))
		w.Header().Set("X-Trailer", "trailer_value")
	}))
	defer backend.Close()
	backendURL, err := url.Parse(backend.URL)
	if err != nil {
		t.Fatal(err)
	}
	proxyHandler := NewSingleHostReverseProxy(backendURL)
	proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
	frontend := httptest.NewServer(proxyHandler)
	defer frontend.Close()

	getReq, _ := http.NewRequest("GET", frontend.URL, nil)
	getReq.Host = "some-name"
	getReq.Header.Set("Connection", "close")
	getReq.Header.Set("Proxy-Connection", "should be deleted")
	getReq.Header.Set("Upgrade", "foo")
	getReq.Close = true
	res, err := http.DefaultClient.Do(getReq)
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	if g, e := res.StatusCode, backendStatus; g != e {
		t.Errorf("got res.StatusCode %d; expected %d", g, e)
	}
	if g, e := res.Header.Get("X-Foo"), "bar"; g != e {
		t.Errorf("got X-Foo %q; expected %q", g, e)
	}
	if c := res.Header.Get(fakeHopHeader); c != "" {
		t.Errorf("got %s header value %q", fakeHopHeader, c)
	}
	if g, e := res.Header.Get("Trailers"), "not a special header field name"; g != e {
		t.Errorf("header Trailers = %q; want %q", g, e)
	}
	if g, e := len(res.Header["X-Multi-Value"]), 2; g != e {
		t.Errorf("got %d X-Multi-Value header values; expected %d", g, e)
	}
	if g, e := len(res.Header["Set-Cookie"]), 1; g != e {
		t.Fatalf("got %d SetCookies, want %d", g, e)
	}
	if g, e := res.Trailer, (http.Header{"X-Trailer": nil}); !reflect.DeepEqual(g, e) {
		t.Errorf("before reading body, Trailer = %#v; want %#v", g, e)
	}
	if cookie := res.Cookies()[0]; cookie.Name != "flavor" {
		t.Errorf("unexpected cookie %q", cookie.Name)
	}
	bodyBytes, _ := ioutil.ReadAll(res.Body)
	if g, e := string(bodyBytes), backendResponse; g != e {
		t.Errorf("got body %q; expected %q", g, e)
	}
	if g, e := res.Trailer.Get("X-Trailer"), "trailer_value"; g != e {
		t.Errorf("Trailer(X-Trailer) = %q ; want %q", g, e)
	}

	// Test that a backend failing to be reached or one which doesn't return
	// a response results in a StatusBadGateway.
	getReq, _ = http.NewRequest("GET", frontend.URL+"/?mode=hangup", nil)
	getReq.Close = true
	res, err = http.DefaultClient.Do(getReq)
	if err != nil {
		t.Fatal(err)
	}
	res.Body.Close()
	if res.StatusCode != http.StatusBadGateway {
		t.Errorf("request to bad proxy = %v; want 502 StatusBadGateway", res.Status)
	}

}

func TestXForwardedFor(t *testing.T) {
	const prevForwardedFor = "client ip"
	const backendResponse = "I am the backend"
	const backendStatus = 404
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("X-Forwarded-For") == "" {
			t.Errorf("didn't get X-Forwarded-For header")
		}
		if !strings.Contains(r.Header.Get("X-Forwarded-For"), prevForwardedFor) {
			t.Errorf("X-Forwarded-For didn't contain prior data")
		}
		w.WriteHeader(backendStatus)
		w.Write([]byte(backendResponse))
	}))
	defer backend.Close()
	backendURL, err := url.Parse(backend.URL)
	if err != nil {
		t.Fatal(err)
	}
	proxyHandler := NewSingleHostReverseProxy(backendURL)
	frontend := httptest.NewServer(proxyHandler)
	defer frontend.Close()

	getReq, _ := http.NewRequest("GET", frontend.URL, nil)
	getReq.Host = "some-name"
	getReq.Header.Set("Connection", "close")
	getReq.Header.Set("X-Forwarded-For", prevForwardedFor)
	getReq.Close = true
	res, err := http.DefaultClient.Do(getReq)
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	if g, e := res.StatusCode, backendStatus; g != e {
		t.Errorf("got res.StatusCode %d; expected %d", g, e)
	}
	bodyBytes, _ := ioutil.ReadAll(res.Body)
	if g, e := string(bodyBytes), backendResponse; g != e {
		t.Errorf("got body %q; expected %q", g, e)
	}
}

var proxyQueryTests = []struct {
	baseSuffix string // suffix to add to backend URL
	reqSuffix  string // suffix to add to frontend's request URL
	want       string // what backend should see for final request URL (without ?)
}{
	{"", "", ""},
	{"?sta=tic", "?us=er", "sta=tic&us=er"},
	{"", "?us=er", "us=er"},
	{"?sta=tic", "", "sta=tic"},
}

func TestReverseProxyQuery(t *testing.T) {
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Got-Query", r.URL.RawQuery)
		w.Write([]byte("hi"))
	}))
	defer backend.Close()

	for i, tt := range proxyQueryTests {
		backendURL, err := url.Parse(backend.URL + tt.baseSuffix)
		if err != nil {
			t.Fatal(err)
		}
		frontend := httptest.NewServer(NewSingleHostReverseProxy(backendURL))
		req, _ := http.NewRequest("GET", frontend.URL+tt.reqSuffix, nil)
		req.Close = true
		res, err := http.DefaultClient.Do(req)
		if err != nil {
			t.Fatalf("%d. Get: %v", i, err)
		}
		if g, e := res.Header.Get("X-Got-Query"), tt.want; g != e {
			t.Errorf("%d. got query %q; expected %q", i, g, e)
		}
		res.Body.Close()
		frontend.Close()
	}
}

func TestReverseProxyFlushInterval(t *testing.T) {
	const expected = "hi"
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(expected))
	}))
	defer backend.Close()

	backendURL, err := url.Parse(backend.URL)
	if err != nil {
		t.Fatal(err)
	}

	proxyHandler := NewSingleHostReverseProxy(backendURL)
	proxyHandler.FlushInterval = time.Microsecond

	done := make(chan bool)
	onExitFlushLoop = func() { done <- true }
	defer func() { onExitFlushLoop = nil }()

	frontend := httptest.NewServer(proxyHandler)
	defer frontend.Close()

	req, _ := http.NewRequest("GET", frontend.URL, nil)
	req.Close = true
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	defer res.Body.Close()
	if bodyBytes, _ := ioutil.ReadAll(res.Body); string(bodyBytes) != expected {
		t.Errorf("got body %q; expected %q", bodyBytes, expected)
	}

	select {
	case <-done:
		// OK
	case <-time.After(5 * time.Second):
		t.Error("maxLatencyWriter flushLoop() never exited")
	}
}

func TestReverseProxyCancelation(t *testing.T) {
	const backendResponse = "I am the backend"

	reqInFlight := make(chan struct{})
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		close(reqInFlight)

		select {
		case <-time.After(10 * time.Second):
			// Note: this should only happen in broken implementations, and the
			// closenotify case should be instantaneous.
			t.Log("Failed to close backend connection")
			t.Fail()
		case <-w.(http.CloseNotifier).CloseNotify():
		}

		w.WriteHeader(http.StatusOK)
		w.Write([]byte(backendResponse))
	}))

	defer backend.Close()

	backend.Config.ErrorLog = log.New(ioutil.Discard, "", 0)

	backendURL, err := url.Parse(backend.URL)
	if err != nil {
		t.Fatal(err)
	}

	proxyHandler := NewSingleHostReverseProxy(backendURL)

	// Discards errors of the form:
	// http: proxy error: read tcp 127.0.0.1:44643: use of closed network connection
	proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0)

	frontend := httptest.NewServer(proxyHandler)
	defer frontend.Close()

	getReq, _ := http.NewRequest("GET", frontend.URL, nil)
	go func() {
		<-reqInFlight
		http.DefaultTransport.(*http.Transport).CancelRequest(getReq)
	}()
	res, err := http.DefaultClient.Do(getReq)
	if res != nil {
		t.Fatal("Non-nil response")
	}
	if err == nil {
		// This should be an error like:
		// Get http://127.0.0.1:58079: read tcp 127.0.0.1:58079:
		//    use of closed network connection
		t.Fatal("DefaultClient.Do() returned nil error")
	}
}

func req(t *testing.T, v string) *http.Request {
	req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(v)))
	if err != nil {
		t.Fatal(err)
	}
	return req
}

// Issue 12344
func TestNilBody(t *testing.T) {
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hi"))
	}))
	defer backend.Close()

	frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		backURL, _ := url.Parse(backend.URL)
		rp := NewSingleHostReverseProxy(backURL)
		r := req(t, "GET / HTTP/1.0\r\n\r\n")
		r.Body = nil // this accidentally worked in Go 1.4 and below, so keep it working
		rp.ServeHTTP(w, r)
	}))
	defer frontend.Close()

	res, err := http.Get(frontend.URL)
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	slurp, err := ioutil.ReadAll(res.Body)
	if err != nil {
		t.Fatal(err)
	}
	if string(slurp) != "hi" {
		t.Errorf("Got %q; want %q", slurp, "hi")
	}
}

// Issue 15524
func TestUserAgentHeader(t *testing.T) {
	const explicitUA = "explicit UA"
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/noua" {
			if c := r.Header.Get("User-Agent"); c != "" {
				t.Errorf("handler got non-empty User-Agent header %q", c)
			}
			return
		}
		if c := r.Header.Get("User-Agent"); c != explicitUA {
			t.Errorf("handler got unexpected User-Agent header %q", c)
		}
	}))
	defer backend.Close()
	backendURL, err := url.Parse(backend.URL)
	if err != nil {
		t.Fatal(err)
	}
	proxyHandler := NewSingleHostReverseProxy(backendURL)
	proxyHandler.ErrorLog = log.New(ioutil.Discard, "", 0) // quiet for tests
	frontend := httptest.NewServer(proxyHandler)
	defer frontend.Close()

	getReq, _ := http.NewRequest("GET", frontend.URL, nil)
	getReq.Header.Set("User-Agent", explicitUA)
	getReq.Close = true
	res, err := http.DefaultClient.Do(getReq)
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	res.Body.Close()

	getReq, _ = http.NewRequest("GET", frontend.URL+"/noua", nil)
	getReq.Header.Set("User-Agent", "")
	getReq.Close = true
	res, err = http.DefaultClient.Do(getReq)
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	res.Body.Close()
}

type bufferPool struct {
	get func() []byte
	put func([]byte)
}

func (bp bufferPool) Get() []byte  { return bp.get() }
func (bp bufferPool) Put(v []byte) { bp.put(v) }

func TestReverseProxyGetPutBuffer(t *testing.T) {
	const msg = "hi"
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, msg)
	}))
	defer backend.Close()

	backendURL, err := url.Parse(backend.URL)
	if err != nil {
		t.Fatal(err)
	}

	var (
		mu  sync.Mutex
		log []string
	)
	addLog := func(event string) {
		mu.Lock()
		defer mu.Unlock()
		log = append(log, event)
	}
	rp := NewSingleHostReverseProxy(backendURL)
	const size = 1234
	rp.BufferPool = bufferPool{
		get: func() []byte {
			addLog("getBuf")
			return make([]byte, size)
		},
		put: func(p []byte) {
			addLog("putBuf-" + strconv.Itoa(len(p)))
		},
	}
	frontend := httptest.NewServer(rp)
	defer frontend.Close()

	req, _ := http.NewRequest("GET", frontend.URL, nil)
	req.Close = true
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatalf("Get: %v", err)
	}
	slurp, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		t.Fatalf("reading body: %v", err)
	}
	if string(slurp) != msg {
		t.Errorf("msg = %q; want %q", slurp, msg)
	}
	wantLog := []string{"getBuf", "putBuf-" + strconv.Itoa(size)}
	mu.Lock()
	defer mu.Unlock()
	if !reflect.DeepEqual(log, wantLog) {
		t.Errorf("Log events = %q; want %q", log, wantLog)
	}
}

func TestReverseProxy_Post(t *testing.T) {
	const backendResponse = "I am the backend"
	const backendStatus = 200
	var requestBody = bytes.Repeat([]byte("a"), 1<<20)
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		slurp, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Errorf("Backend body read = %v", err)
		}
		if len(slurp) != len(requestBody) {
			t.Errorf("Backend read %d request body bytes; want %d", len(slurp), len(requestBody))
		}
		if !bytes.Equal(slurp, requestBody) {
			t.Error("Backend read wrong request body.") // 1MB; omitting details
		}
		w.Write([]byte(backendResponse))
	}))
	defer backend.Close()
	backendURL, err := url.Parse(backend.URL)
	if err != nil {
		t.Fatal(err)
	}
	proxyHandler := NewSingleHostReverseProxy(backendURL)
	frontend := httptest.NewServer(proxyHandler)
	defer frontend.Close()

	postReq, _ := http.NewRequest("POST", frontend.URL, bytes.NewReader(requestBody))
	res, err := http.DefaultClient.Do(postReq)
	if err != nil {
		t.Fatalf("Do: %v", err)
	}
	if g, e := res.StatusCode, backendStatus; g != e {
		t.Errorf("got res.StatusCode %d; expected %d", g, e)
	}
	bodyBytes, _ := ioutil.ReadAll(res.Body)
	if g, e := string(bodyBytes), backendResponse; g != e {
		t.Errorf("got body %q; expected %q", g, e)
	}
}