text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>CIMApplication</artifactId>
        <groupId>ch.ninecode.cim</groupId>
        <relativePath>../pom.xml</relativePath>
        <version>2.12-3.0.1-3.0.14</version>
    </parent>
    <artifactId>ShortCircuit</artifactId>
    <groupId>ch.ninecode.sc</groupId>
    <name>ShortCircuit</name>
    <description>Compute short circuit values using Spark and Scala</description>
    <inceptionYear>2016</inceptionYear>
    <url>https://github.com/derrickoswald/CIMApplication/tree/master/ShortCircuit</url>
    <scm>
        <url>git@github.com:derrickoswald/CIMApplication.git</url>
        <connection>scm:git:git@github.com:derrickoswald/CIMApplication.git</connection>
        <developerConnection>scm:git:git@github.com:derrickoswald/CIMApplication.git</developerConnection>
    </scm>

    <properties>
        <version.dependency.log4j>2.16.0</version.dependency.log4j>
    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.ninecode.cim</groupId>
            <artifactId>CIMReader</artifactId>
            <version>${version.dependency.cimreader}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>ch.ninecode.gl</groupId>
            <artifactId>GridLAB-D</artifactId>
            <version>${project.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>ch.ninecode.net</groupId>
            <artifactId>Net</artifactId>
            <version>${project.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.ojalgo</groupId>
            <artifactId>ojalgo</artifactId>
            <version>48.4.2</version>
        </dependency>

        <dependency>
            <groupId>ch.ninecode.util</groupId>
            <artifactId>Util</artifactId>
            <version>${project.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>${version.dependency.sqlite}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.github.scopt</groupId>
            <artifactId>scopt_${version.dependency.scala}</artifactId>
            <version>${version.dependency.scopt}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>${version.dependency.scalalibrary}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-compiler</artifactId>
            <version>${version.dependency.scalalibrary}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_${version.dependency.scala}</artifactId>
            <version>${version.dependency.spark}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_${version.dependency.scala}</artifactId>
            <version>${version.dependency.spark}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-graphx_${version.dependency.scala}</artifactId>
            <version>${version.dependency.spark}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.json</artifactId>
            <version>${version.dependency.json}</version>
        </dependency>

        <dependency>
            <groupId>ch.ninecode.testutil</groupId>
            <artifactId>TestUtil</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.scalatest</groupId>
            <artifactId>scalatest_${version.dependency.scala}</artifactId>
            <version>${version.dependency.scalatest}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${version.dependency.junit}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <sourceDirectory>src/main/scala</sourceDirectory>
        <testSourceDirectory>src/test/scala</testSourceDirectory>
        <resources>
            <resource>
                <directory>${basedir}/src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${basedir}/src/test/resources</directory>
                <filtering>true</filtering>
            </testResource>
        </testResources>
        <plugins>
            <!-- enable scalatest -->
            <plugin>
                <groupId>org.scalatest</groupId>
                <artifactId>scalatest-maven-plugin</artifactId>
                <version>${version.dependency.scalatest-maven-plugin}</version>
                <configuration>
                    <reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory>
                    <junitxml>.</junitxml>
                    <filereports>ShortCircuitSuite.txt</filereports>
                    <suites>ch.ninecode.sc.TestSuite</suites>
                </configuration>
                <executions>
                    <execution>
                        <id>test</id>
                        <goals>
                            <goal>test</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>${version.dependency.maven-failsafe-plugin}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <skipAfterFailureCount>1</skipAfterFailureCount>
                    <jvm>/usr/lib/jvm/java-11-openjdk-amd64/bin/java</jvm>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>${version.dependency.build-helper-maven-plugin}</version>
                <executions>
                    <execution>
                        <id>check-for-local-cassandra</id>
                        <goals>
                            <goal>bsh-property</goal>
                        </goals>
                        <phase>initialize</phase>
                        <configuration>
                            <source>skipCassandra = ${localCassandra} || ${skipITs};</source>
                            <properties>
                                <property>skipCassandra</property>
                            </properties>
                        </configuration>
                    </execution>
                    <execution>
                        <id>reserve-network-port</id>
                        <goals>
                            <goal>reserve-network-port</goal>
                        </goals>
                        <!-- reserve the ports in the phase before process-test-resources
                             (where the resources are filtered and copied) -->
                        <phase>generate-test-resources</phase>
                        <configuration>
                            <portNames>
                                <portName>cassandra.jmxPort</portName>
                                <portName>cassandra.rpcPort</portName>
                                <portName>cassandra.stopPort</portName>
                                <portName>cassandra.storagePort</portName>
                                <portName>cassandra.nativeTransportPort</portName>
                            </portNames>
                        </configuration>
                    </execution>
                    <execution>
                        <id>set-cassandra-ports</id>
                        <goals>
                            <goal>bsh-property</goal>
                        </goals>
                        <phase>generate-test-resources</phase>
                        <configuration>
                            <source>
                                jmxPort = ${localCassandra} ? 7199 : ${cassandra.jmxPort};
                                rpcPort = ${localCassandra} ? 9160 : ${cassandra.rpcPort};
                                storagePort = ${localCassandra} ? 7000 : ${cassandra.storagePort};
                                nativeTransportPort = ${localCassandra} ? 9042 : ${cassandra.nativeTransportPort};
                            </source>
                            <properties>
                                <property>jmxPort</property>
                                <property>rpcPort</property>
                                <property>storagePort</property>
                                <property>nativeTransportPort</property>
                            </properties>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-toolchains-plugin</artifactId>
                <version>${version.dependency.maven-toolchains-plugin}</version>
                <executions>
                    <execution>
                        <id>default-pre-integration-test</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>toolchain</goal>
                        </goals>
                        <configuration>
                            <toolchains>
                                <jdk>
                                    <version>8</version>
                                    <vendor>OpenJDK</vendor>
                                </jdk>
                            </toolchains>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cassandra-maven-plugin</artifactId>
                <version>${version.dependency.cassandra-maven-plugin}</version>
                <configuration>
                    <clusterSize>1</clusterSize>
                    <startNativeTransport>true</startNativeTransport>
                    <cqlVersion>${version.dependency.cql}</cqlVersion>
                    <yaml>
rpc_port: ${rpcPort}
storage_port: ${storagePort}
native_transport_port: ${nativeTransportPort}
enable_user_defined_functions: true
enable_scripted_user_defined_functions: true
                    </yaml>
                    <script>${basedir}/src/test/resources/test_shortcircuit_schema.sql</script>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.cassandra</groupId>
                        <artifactId>cassandra-all</artifactId>
                        <version>${version.dependency.cassandra_all}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.logging.log4j</groupId>
                        <artifactId>log4j-cassandra</artifactId>
                        <version>${version.dependency.log4j}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.apache.logging.log4j</groupId>
                        <artifactId>log4j-slf4j-impl</artifactId>
                        <version>${version.dependency.log4j}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>Start Cassandra</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>start</goal>
                        </goals>
                        <configuration>
                            <skip>${skipCassandra}</skip>
                        </configuration>
                    </execution>
                    <execution>
                        <id>Stop Cassandra</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                        <configuration>
                            <skip>${skipCassandra}</skip>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!-- assembly for stand-alone program -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>${version.dependency.maven-assembly-plugin}</version>
                <executions>
                    <execution>
                        <id>make-short-circuit-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <finalName>ShortCircuit-${project.parent.version}</finalName>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                            <archive>
                                <manifest>
                                    <mainClass>ch.ninecode.sc.ShortCircuit</mainClass>
                                </manifest>
                                <addMavenDescriptor>false</addMavenDescriptor>
                            </archive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                        <configuration>
                            <includes>**/SCTestBase.*</includes>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
import sbt._

object ModelBuild extends Build {
    lazy val root = Project(id = "root", base = file(".")) aggregate(
      plannerJDBC,
      plannerJPA,
      plannerUsecases,
      plannerSignature,
      plannerRestAPI,
      plannerRestAPIHarness,
      plannerBalancer,
      plannerExecutor
    )

    lazy val plannerUsecases = Project(id="usecases", base = file("planner-usecases"))

    lazy val plannerJDBC = Project(id="jdbc", base = file("planner-jdbc"))dependsOn(plannerUsecases)

    lazy val plannerJPA = Project(id="jpa", base = file("planner-jpa"))dependsOn(plannerUsecases)

    lazy val plannerSignature = Project(id="signature", base = file("planner-signature"))

    lazy val plannerRestAPI = Project(id="restAPI", base = file("planner-restapi"))dependsOn(plannerSignature, plannerJDBC, plannerJPA)

    lazy val plannerRestAPIHarness = Project(id="restAPIHarness", base = file("planner-restapi-harness"))dependsOn(plannerSignature)

    lazy val plannerBalancer = Project(id="balancer", base = file("planner-balancer"))

    lazy val plannerExecutor = Project(id="executor", base = file("planner-executor"))dependsOn(plannerSignature, plannerJDBC, plannerJPA)
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe 'Command monitoring' do

  let(:subscriber) { EventSubscriber.new }

  let(:client) do
    authorized_client.with(app_name: 'command monitoring spec').tap do |client|
      client.subscribe(Mongo::Monitoring::COMMAND, subscriber)
    end
  end

  it 'notifies on successful commands' do
    result = client.database.command(:ismaster => 1)
    expect(result.documents.first['ismaster']).to be true

    started_events = subscriber.started_events.select do |event|
      event.command_name == 'ismaster'
    end
    expect(started_events.length).to eql(1)
    started_event = started_events.first
    expect(started_event.command_name).to eql('ismaster')
    expect(started_event.address).to be_a(Mongo::Address)

    succeeded_events = subscriber.succeeded_events.select do |event|
      event.command_name == 'ismaster'
    end
    expect(succeeded_events.length).to eql(1)
    succeeded_event = succeeded_events.first
    expect(succeeded_event.command_name).to eql('ismaster')
    expect(succeeded_event.reply).to be_a(BSON::Document)
    expect(succeeded_event.reply['ismaster']).to eql(true)
    expect(succeeded_event.reply['ok']).to eq(1)
    expect(succeeded_event.address).to be_a(Mongo::Address)
    expect(succeeded_event.duration).to be_a(Float)

    expect(subscriber.failed_events.length).to eql(0)
  end

  it 'notifies on failed commands' do
    expect do
      result = client.database.command(:bogus => 1)
    end.to raise_error(Mongo::Error::OperationFailure, /no such c(om)?m(an)?d/)

    started_events = subscriber.started_events.select do |event|
      event.command_name == 'bogus'
    end
    expect(started_events.length).to eql(1)
    started_event = started_events.first
    expect(started_event.command_name).to eql('bogus')
    expect(started_event.address).to be_a(Mongo::Address)

    succeeded_events = subscriber.succeeded_events.select do |event|
      event.command_name == 'ismaster'
    end
    expect(succeeded_events.length).to eql(0)

    failed_events = subscriber.failed_events.select do |event|
      event.command_name == 'bogus'
    end
    expect(failed_events.length).to eql(1)
    failed_event = failed_events.first
    expect(failed_event.command_name).to eql('bogus')
    expect(failed_event.message).to match(/no such c(om)?m(an)?d/)
    expect(failed_event.address).to be_a(Mongo::Address)
    expect(failed_event.duration).to be_a(Float)
  end

  context 'client with no established connections' do
    # For simplicity use 3.6+ servers only, then we can assert
    # scram auth commands
    min_server_fcv '3.6'

    # X.509 auth uses authenticate instead of sasl* commands
    require_no_x509_auth

    it 'does not nest auth and find' do
      expect(subscriber.started_events.length).to eq 0
      client['test-collection'].find(a: 1).first
      command_names = subscriber.started_events.map(&:command_name)
      expect(command_names).to eq %w(saslStart saslContinue saslContinue find)
    end
  end

  context 'when write concern is specified outside of command document' do
    require_wired_tiger
    require_topology :replica_set
    min_server_fcv '4.0'

    let(:collection) do
      client['command-monitoring-test']
    end
    let(:write_concern) { Mongo::WriteConcern.get({w: 42}) }
    let(:session) { client.start_session }
    let(:command) do
      Mongo::Operation::Command.new(
        selector: { commitTransaction: 1 },
        db_name: 'admin',
        session: session,
        txn_num: 123,
        write_concern: write_concern,
      )
    end

    it 'includes write concern in notified command document' do
      server = client.cluster.next_primary
      collection.insert_one(a: 1)
      session.start_transaction
      collection.insert_one({a: 1}, session: session)

      subscriber.clear_events!
      expect do
        command.execute(server)
      end.to raise_error(Mongo::Error::OperationFailure, /Not enough data-bearing nodes \(100\)/)

      expect(subscriber.started_events.length).to eq(1)
      event = subscriber.started_events.first
      expect(event.command['writeConcern']['w']).to eq(42)
    end
  end
end


text:
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'usp_SearchStudent')
	BEGIN
		DROP  Procedure  usp_SearchStudent
	END

GO

CREATE Procedure usp_SearchStudent
	(
		@studentid varchar(9)
	)

AS

	IF object_id('tempdb..#Students') IS NOT NULL
	BEGIN
		DROP TABLE #Students
	END

	CREATE TABLE #Students
	(
		pidm varchar(8),
		studentid varchar(9),
		firstName varchar(50),
		MI varchar(50),
		LastName varchar(50),
		Email varchar(100),
		EarnedUnits decimal(6,3),
		CurrentUnits decimal(6,3),
		major varchar(4),
		lastTerm varchar(6),
		astd varchar(2),
		LoginId varchar(50)
	)

	declare @tsql varchar(max)

	set @tsql = '
		insert into #Students
		select pidm, studentid
			 , firstname, mi, lastname
			 , email, earnedunits, currentunits
			 , major, lastterm, astd, loginid
			from openquery (sis, ''
			select spriden_pidm as pidm, spriden_id as studentId
			, spriden_first_name  as firstName, spriden_mi as mi, spriden_last_name as lastName
			, email.goremal_email_address as email
			, shrlgpa_hours_earned earnedUnits, 0 as currentUnits
			, zgvlcfs_majr_code as major
			, zgvlcfs_term_code_eff as lastTerm
			, shrttrm_astd_code_end_of_term as astd
			, lower(wormoth_login_id) as loginid
		from spriden
			inner join zgvlcfs on spriden_pidm = zgvlcfs_pidm
			inner join wormoth on spriden_pidm = wormoth_pidm
			inner join shrlgpa on spriden_pidm = shrlgpa_pidm
			left outer join shrttrm on spriden_pidm = shrttrm_pidm
			left outer join (
				select goremal_pidm, goremal_email_address
				from goremal
				where goremal_emal_code = ''''UCD''''
				  and goremal_status_ind = ''''A''''
			) email on email.goremal_pidm = spriden_pidm
		where spriden_id = ''''' + @studentid + '''''
		  and zgvlcfs_term_code_eff in (select max(zgvlcfs_term_code_eff) from zgvlcfs izgvlcfs where izgvlcfs.zgvlcfs_pidm = zgvlcfs.zgvlcfs_pidm)
		  and spriden_change_ind is null
		  and shrlgpa_gpa_type_ind = ''''O'''' and shrlgpa_levl_code = ''''UG''''
		  and shrttrm_term_code in ( select max(shrttrm_term_code) from shrttrm ishrttrm where ishrttrm.shrttrm_pidm = shrttrm.shrttrm_pidm and shrttrm_astd_code_end_of_term is not null )
		'')
	'
	exec(@tsql)

	if not exists (select * from #Students)
	begin

		set @tsql = '
			insert into #Students
			select pidm, studentid
				 , firstname, mi, lastname
				 , email, earnedunits, currentunits
				 , major, lastterm, astd, loginid
				from openquery (sis, ''
				select spriden_pidm as pidm, spriden_id as studentId
				, spriden_first_name  as firstName, spriden_mi as mi, spriden_last_name as lastName
				, email.goremal_email_address as email
				, shrlgpa_hours_earned earnedUnits, 0 as currentUnits
				, zgvlcfs_majr_code as major
				, zgvlcfs_term_code_eff as lastTerm
				, shrttrm_astd_code_end_of_term as astd
				, lower(wormoth_login_id) as loginid
			from spriden
				inner join zgvlcfs on spriden_pidm = zgvlcfs_pidm
				inner join wormoth on spriden_pidm = wormoth_pidm
				inner join shrlgpa on spriden_pidm = shrlgpa_pidm
				left outer join shrttrm on spriden_pidm = shrttrm_pidm
				left outer join (
					select goremal_pidm, goremal_email_address
					from goremal
					where goremal_emal_code = ''''UCD''''
					  and goremal_status_ind = ''''A''''
				) email on email.goremal_pidm = spriden_pidm
			where spriden_id = ''''' + @studentid + '''''
			  and zgvlcfs_term_code_eff in (select max(zgvlcfs_term_code_eff) from zgvlcfs izgvlcfs where izgvlcfs.zgvlcfs_pidm = zgvlcfs.zgvlcfs_pidm)
			  and spriden_change_ind is null
			  and shrlgpa_gpa_type_ind = ''''O'''' and shrlgpa_levl_code = ''''U2''''
			  and shrttrm_term_code in ( select max(shrttrm_term_code) from shrttrm ishrttrm where ishrttrm.shrttrm_pidm = shrttrm.shrttrm_pidm and shrttrm_astd_code_end_of_term is not null )
			'')
		'
		exec(@tsql)

	end

	select * from #students

	drop table #students

GO

GRANT EXEC ON usp_SearchStudent TO PUBLIC

GO


text:
#ifndef MONGOC_SET_PRIVATE_H
#define MONGOC_SET_PRIVATE_H

#if !defined (MONGOC_I_AM_A_DRIVER) && !defined (MONGOC_COMPILATION)
#error "Only <mongoc.h> can be included directly."
#endif

#include <bson.h>

BSON_BEGIN_DECLS

typedef void (*mongoc_set_item_dtor)(void *item,
                                     void *ctx);

/* return true to continue iteration, false to stop */
typedef bool (*mongoc_set_for_each_cb_t)(void *item,
                                         void *ctx);

typedef struct
{
   uint32_t id;
   void    *item;
} mongoc_set_item_t;

typedef struct
{
   mongoc_set_item_t   *items;
   size_t               items_len;
   size_t               items_allocated;
   mongoc_set_item_dtor dtor;
   void                *dtor_ctx;
} mongoc_set_t;

mongoc_set_t *
mongoc_set_new (size_t               nitems,
                mongoc_set_item_dtor dtor,
                void                *dtor_ctx);

void
mongoc_set_add (mongoc_set_t *set,
                uint32_t      id,
                void         *item);

void
mongoc_set_rm (mongoc_set_t *set,
               uint32_t      id);

void *
mongoc_set_get (mongoc_set_t *set,
                uint32_t      id);

void *
mongoc_set_get_item (mongoc_set_t *set,
                     int           index);

void
mongoc_set_destroy (mongoc_set_t *set);

/* loops over the set safe-ish.
 *
 * Caveats:
 *   - you can add items at any iteration
 *   - if you remove elements other than the one you're currently looking at,
 *     you may see it later in the iteration
 */
void
mongoc_set_for_each (mongoc_set_t            *set,
                     mongoc_set_for_each_cb_t cb,
                     void                    *ctx);

/* first item in set for which "cb" returns true */
void *
mongoc_set_find_item (mongoc_set_t            *set,
                      mongoc_set_for_each_cb_t cb,
                      void                    *ctx);

/* id of first item in set for which "cb" returns true, or 0. */
uint32_t
mongoc_set_find_id (mongoc_set_t            *set,
                    mongoc_set_for_each_cb_t cb,
                    void                    *ctx);

BSON_END_DECLS

#endif /* MONGOC_SET_PRIVATE_H */


text:
class Db::ItemsController < Db::ApplicationController
  permits :name, :url, :tombo_image

  before_action :authenticate_user!
  before_action :load_work, only: [:show, :new, :create, :edit, :update, :destroy]
  before_action :load_item, only: [:edit, :update, :destroy]

  def show
    @item = @work.item
  end

  def new
    @item = @work.build_item
    authorize @item, :new?
  end

  def create(item)
    @item = @work.build_item(item)
    authorize @item, :create?

    if @item.save_and_create_db_activity(current_user, "items.create")
      redirect_to db_work_item_path(@work), notice: "作品画像を登録しました"
    else
      render :new
    end
  end

  def edit
    authorize @item, :edit?
  end

  def update(item)
    authorize @item, :update?

    @item.attributes = item
    if @item.save_and_create_db_activity(current_user, "items.update")
      redirect_to db_work_item_path(@work), notice: "作品画像を更新しました"
    else
      render :edit
    end
  end

  def destroy
    authorize @item, :destroy?

    @item.destroy

    redirect_to db_work_item_path(@work), notice: "作品画像を削除しました"
  end

  private

  def load_work
    @work = Work.find(params[:work_id])
  end

  def load_item
    @item = @work.item
    raise ActiveRecord::RecordNotFound if @item.blank?
  end
end


text:
using System;

namespace Google.Apis.Auth.OAuth2
{
    ///
    /// Google OAuth2 constants.
    /// Canonical source for these URLs is: https://accounts.google.com/.well-known/openid-configuration
    ///
    public static class GoogleAuthConsts
    {
        /// The authorization code server URL.
        public const string AuthorizationUrl = "https://accounts.google.com/o/oauth2/auth";

        /// The OpenID Connect authorization code server URL.
        /// <remarks>
        /// Use of this <see cref="OidcAuthorizationUrl"/> is not 100% compatible with using
        /// <see cref="AuthorizationUrl"/>, so they are two distinct URLs.
        /// Internally within this library only this more up-to-date <see cref="OidcAuthorizationUrl"/> is used.
        /// </remarks>
        public const string OidcAuthorizationUrl = "https://accounts.google.com/o/oauth2/v2/auth";

        /// The approval URL (used in the Windows solution as a callback).
        public const string ApprovalUrl = "https://accounts.google.com/o/oauth2/approval";

        /// The authorization token server URL.
        public const string TokenUrl = "https://accounts.google.com/o/oauth2/token";

        /// The OpenID Connect authorization token server URL.
        /// <remarks>
        /// Use of this <see cref="OidcTokenUrl"/> is not 100% compatible with using
        /// <see cref="TokenUrl"/>, so they are two distinct URLs.
        /// Internally within this library only this more up-to-date <see cref="OidcTokenUrl"/> is used.
        /// </remarks>
        public const string OidcTokenUrl = "https://oauth2.googleapis.com/token";

        // Constant strings to avoid duplication below.
        // IP address instead of name to avoid DNS resolution
        private const string DefaultMetadataAddress = "169.254.169.254";
        internal const string DefaultMetadataServerUrl = "http://" + DefaultMetadataAddress;
        private const string ComputeTokenUrlSuffix = "/computeMetadata/v1/instance/service-accounts/default/token";
        private const string ComputeOidcTokenUrlSuffix = "/computeMetadata/v1/instance/service-accounts/default/identity";

        /// The Compute Engine authorization token server URL
        /// <remarks>IP address instead of name to avoid DNS resolution</remarks>
        public const string ComputeTokenUrl = DefaultMetadataServerUrl + ComputeTokenUrlSuffix;

        /// The path to the Google revocation endpoint.
        public const string RevokeTokenUrl = "https://oauth2.googleapis.com/revoke";

        /// The OpenID Connect Json Web Key Set (jwks) URL.
        public const string JsonWebKeySetUrl = "https://www.googleapis.com/oauth2/v3/certs";

        /// The IAP Json Web Key Set (jwks) URL.
        public const string IapKeySetUrl = "https://www.gstatic.com/iap/verify/public_key-jwk";

        /// Installed application redirect URI.
        [Obsolete(@"The OAuth out-of-band flow will be deprecated and this constant will be removed on October 3rd 2022. You can read more about deprecation here: https://developers.googleblog.com/2022/02/making-oauth-flows-safer.html#disallowed-oob.")]
        public const string InstalledAppRedirectUri = "urn:ietf:wg:oauth:2.0:oob";

        /// Installed application localhost redirect URI.
        public const string LocalhostRedirectUri = "http://localhost";

        /// IAM access token endpoint for service account.
        internal const string IamServiceAccountEndpointCommonPrefix = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/";

        /// IAM access token endpoint format string. To use it insert the service account email.
        internal const string IamAccessTokenEndpointFormatString = IamServiceAccountEndpointCommonPrefix + "{0}:generateAccessToken";

        /// IAM signBlob endpoint format string. To use it insert the service account email.
        internal const string IamSignEndpointFormatString = IamServiceAccountEndpointCommonPrefix + "{0}:signBlob";

        /// IAM ID token endpoint format string. To use it insert the service account email.
        internal const string IamIdTokenEndpointFormatString = IamServiceAccountEndpointCommonPrefix + "{0}:generateIdToken";

        /// Scope needed for source credential in impersonated credential.
        internal const string IamScope = "https://www.googleapis.com/auth/iam";

        ///
        /// The effective Compute Engine authorization token server URL.
        /// This takes account of the GCE_METADATA_HOST environment variable.
        ///
        internal static string EffectiveComputeTokenUrl => GetEffectiveMetadataUrl(ComputeTokenUrlSuffix, ComputeTokenUrl);

        ///
        /// The effective Compute Engine authorization token server URL for OIDC. This requires an audience parameter to be added.
        /// This takes account of the GCE_METADATA_HOST environment variable.
        ///
        internal static string EffectiveComputeOidcTokenUrl => GetEffectiveMetadataUrl(ComputeOidcTokenUrlSuffix, DefaultMetadataServerUrl + ComputeOidcTokenUrlSuffix);

        ///
        /// The effective Compute Engine metadata token server URL (with no path).
        /// This takes account of the GCE_METADATA_HOST environment variable.
        ///
        internal static string EffectiveMetadataServerUrl => GetEffectiveMetadataUrl(null, DefaultMetadataServerUrl);

        private static string GetEffectiveMetadataUrl(string suffix, string defaultValue)
        {
            string env = Environment.GetEnvironmentVariable("GCE_METADATA_HOST");
            return string.IsNullOrEmpty(env) ? defaultValue : "http://" + env + suffix;
        }
    }
}


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model as Eloquent;

/**
 * Description of Pelanggan
 *
 * @author nunenuh
 */
class Pelanggan extends Eloquent{
    protected $table = 'pelanggan';
}


text:
import sys, os
sys.path.append(os.path.abspath(os.path.join('..')))
# Import all stations
from stations.blacklists.station import *
from stations.cymon.station import *
from stations.fortiguard.station import *
from stations.hostsfile.station import *
from stations.ibmxforceex.station import *
from stations.malwr.station import *
from stations.metascan.station import *
from stations.threatcrowd.station import *
from stations.threatexpert.station import *
from stations.totalhash.station import *
from stations.virustotal.station import *
import helpers

##### DOMAIN SECTION ######
class From_domain(object):
    def __init__(self, verbose=False):
        self.verbose = verbose
        self.ip_dict = {}
        self.hash_dict = {}
        self.score_dict = {}
        self.url_dict = {}
        self.blacklist_dict = {}

    ########################################
    # Searches to IP
    def to_ipv4(self, search_value):
        if search_value:
            self.ip_dict.update({'Cymon': Cymon().domain_to_ipv4(search_value)})
            self.ip_dict.update({'FortiGuard': Fortiguard().domain_to_ipv4(search_value)})
            self.ip_dict.update({'Hostsfile': Hostsfile().domain_to_ipv4(search_value)})
            self.ip_dict.update({'IBM': Ibmxforce().domain_to_ipv4(search_value)})
            self.ip_dict.update({'Threatcrowd': Threatcrowd().domain_to_ipv4(search_value)})
            self.ip_dict.update({'Virustotal': Virustotal().domain_to_ipv4(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_domain.__name__, self.to_ipv4.__name__,
                                                       self.ip_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_domain.__name__, self.to_ipv4.__name__,
                                                          self.ip_dict)

    ########################################
    # Searches to HASH
    def to_hash(self, search_value):
        if search_value:
            self.hash_dict.update({'Malwr': Malwr().domain_to_hash(search_value)})
            self.hash_dict.update({'IBM': Ibmxforce().domain_to_hash(search_value)})
            self.hash_dict.update({'Threatexpert': Threatexpert().domain_to_hash(search_value)})
            self.hash_dict.update({'Totalhash': Totalhash().domain_to_hash(search_value)})
            self.hash_dict.update({'Threatcrowd': Threatcrowd().domain_to_hash(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_domain.__name__, self.to_hash.__name__,
                                                       self.hash_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_domain.__name__, self.to_hash.__name__,
                                                          self.hash_dict)

    ########################################
    # Searches to SCORE
    def to_score(self, search_value):
        if search_value:
            self.score_dict.update({'Malwr': Malwr().domain_to_score(search_value)})
            self.score_dict.update({'IBM': Ibmxforce().domain_to_score(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_domain.__name__, self.to_score.__name__,
                                                       self.score_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_domain.__name__, self.to_score.__name__,
                                                          self.score_dict)

    ########################################
    # Searches to URL
    def to_url(self, search_value):
        if search_value:
            self.url_dict.update({'Malwr': Malwr().domain_to_url(search_value)})
            self.url_dict.update({'Totalhash': Totalhash().domain_to_url(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_domain.__name__, self.to_url.__name__,
                                                       self.url_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_domain.__name__, self.to_url.__name__,
                                                          self.url_dict)

    ########################################
    # Searches to BLACKLISTS
    def to_blacklist(self, search_value):
        if search_value:
            if self.verbose:
                self.blacklist_dict.update({'McAfee': Mcafee().domain_to_blacklist(search_value)})

                return helpers.Common().verbose_output(search_value, From_domain.__name__, self.to_blacklist.__name__,
                                                       self.blacklist_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_domain.__name__, self.to_blacklist.__name__,
                                                          str(Blacklist().domain_blacklist_check(search_value)))

##### IP SECTION ######
class From_ipv4(object):
    def __init__(self, verbose=False):
        self.verbose = verbose
        self.domain_dict = {}
        self.hash_dict = {}
        self.score_dict = {}
        self.url_dict = {}
        self.blacklist_dict = {}

    ########################################
    # Searches to DOMAIN
    def to_domain(self, search_value):
        if search_value:
            self.domain_dict.update({'Cymon': Cymon().ipv4_to_domain(search_value)})
            self.domain_dict.update({'Hostsfile': Hostsfile().ipv4_to_domain(search_value)})
            self.domain_dict.update({'IBM': Ibmxforce().ipv4_to_domain(search_value)})
            self.domain_dict.update({'Threatcrowd': Threatcrowd().ipv4_to_domain(search_value)})
            self.domain_dict.update({'Virustotal': Virustotal().ipv4_to_domain(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_ipv4.__name__, self.to_domain.__name__,
                                                       self.domain_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_ipv4.__name__, self.to_domain.__name__,
                                                          self.domain_dict)

    ########################################
    # Searches to HASH
    def to_hash(self, search_value):
        if search_value:
            self.hash_dict.update({'Cymon': Cymon().ipv4_to_hash(search_value)})
            self.hash_dict.update({'Malwr': Malwr().ipv4_to_hash(search_value)})
            self.hash_dict.update({'IBM': Ibmxforce().ipv4_to_hash(search_value)})
            self.hash_dict.update({'Threatcrowd': Threatcrowd().ipv4_to_hash(search_value)})
            self.hash_dict.update({'Threatexpert': Threatexpert().ipv4_to_hash(search_value)})
            self.hash_dict.update({'Totalhash': Totalhash().ipv4_to_hash(search_value)})
            self.hash_dict.update({'Virustotal': Virustotal().ipv4_to_hash(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_ipv4.__name__, self.to_hash.__name__,
                                                       self.hash_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_ipv4.__name__, self.to_hash.__name__,
                                                          self.hash_dict)

    ########################################
    # Searches to SCORE
    def to_score(self, search_value):
        if search_value:
            self.score_dict.update({'Malwr': Malwr().ipv4_to_score(search_value)})
            self.score_dict.update({'Metascan': Metascan().ipv4_to_score(search_value)})
            self.score_dict.update({'IBM': Ibmxforce().ipv4_to_score(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_ipv4.__name__, self.to_score.__name__,
                                                       self.score_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_ipv4.__name__, self.to_score.__name__,
                                                          self.score_dict)

    ########################################
    # Searches to URL
    def to_url(self, search_value):
        if search_value:
            self.url_dict.update({'Cymon': Cymon().ipv4_to_url(search_value)})
            self.url_dict.update({'Malwr': Malwr().ipv4_to_url(search_value)})
            self.url_dict.update({'Totalhash': Totalhash().ipv4_to_url(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_ipv4.__name__, self.to_url.__name__,
                                                       self.url_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_ipv4.__name__, self.to_url.__name__,
                                                          self.url_dict)

    ########################################
    # Searches to BLACKLISTS
    def to_blacklist(self, search_value):
        if search_value:
            if self.verbose:
                self.blacklist_dict.update({'Asprox': Asprox().ipv4_to_blacklist(search_value)})
                self.blacklist_dict.update({'Feodo': Feodo().ipv4_to_blacklist(search_value)})
                self.blacklist_dict.update({'Malc0de': Malc0de().ipv4_to_blacklist(search_value)})
                self.blacklist_dict.update({'Zeustracker': Zeustracker().ipv4_to_blacklist(search_value)})
                self.blacklist_dict.update({'McAfee': Mcafee().ipv4_to_blacklist(search_value)})

                return helpers.Common().verbose_output(search_value, From_ipv4.__name__, self.to_blacklist.__name__,
                                                       self.blacklist_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_ipv4.__name__, self.to_blacklist.__name__,
                                                          str(Blacklist().ipv4_blacklist_check(search_value)))

##### HASH SECTION ######
class From_hash(object):
    def __init__(self, verbose=False):
        self.verbose = verbose
        self.ip_dict = {}
        self.score_dict = {}
        self.imphash_dict = {}
        self.url_dict = {}
        self.domain_dict = {}

    ########################################
    # Searches to IP
    def to_ipv4(self, search_value):
        if search_value:
            self.ip_dict.update({'IBM': Ibmxforce().hash_to_ipv4(search_value)})
            self.ip_dict.update({'Malwr': Malwr().hash_to_ipv4(search_value)})
            self.ip_dict.update({'Threatexpert': Threatexpert().hash_to_ipv4(search_value)})
            self.ip_dict.update({'Totalhash': Totalhash().hash_to_ipv4(search_value)})
            self.ip_dict.update({'Threatcrowd': Threatcrowd().hash_to_ipv4(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_hash.__name__, self.to_ipv4.__name__,
                                                       self.ip_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_hash.__name__, self.to_ipv4.__name__,
                                                          self.ip_dict)

    ########################################
    # Searches to DOMAIN
    def to_domain(self, search_value):
        if search_value:
            self.domain_dict.update({'Threatexpert': Threatexpert().hash_to_domain(search_value)})
            self.domain_dict.update({'Totalhash': Totalhash().hash_to_domain(search_value)})
            self.domain_dict.update({'Threatcrowd': Threatcrowd().hash_to_domain(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_hash.__name__, self.to_domain.__name__,
                                                       self.domain_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_hash.__name__, self.to_domain.__name__,
                                                          self.domain_dict)

    ########################################
    # Searches to SCORE
    def to_score(self, search_value):
        if search_value:
            self.score_dict.update({'Malwr': Malwr().hash_to_score(search_value)})
            self.score_dict.update({'Metascan': Metascan().hash_to_score(search_value)})
            self.score_dict.update({'IBM': Ibmxforce().hash_to_score(search_value)})
            self.score_dict.update({'Virustotal': Virustotal().hash_to_score(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_hash.__name__, self.to_score.__name__,
                                                       self.score_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_hash.__name__, self.to_score.__name__,
                                                          self.score_dict)

    ########################################
    # Searches to URL
    def to_url(self, search_value):
        if search_value:
            self.url_dict.update({'Cymon': Cymon().hash_to_url(search_value)})
            self.url_dict.update({'Malwr': Malwr().hash_to_url(search_value)})
            self.url_dict.update({'Threatexpert': Threatexpert().hash_to_url(search_value)})
            self.url_dict.update({'Totalhash': Totalhash().hash_to_url(search_value)})
            self.url_dict.update({'Virustotal': Virustotal().hash_to_url(search_value)})
            self.url_dict.update({'Threatcrowd': Threatcrowd().hash_to_url(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_hash.__name__, self.to_url.__name__,
                                                       self.url_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_hash.__name__, self.to_url.__name__,
                                                          self.url_dict)

    ########################################
    # Searches to IMPHASH
    def to_imphash(self, search_value):
        if search_value:
            self.imphash_dict.update({'Malwr': Malwr().hash_to_imphash(search_value)})
            self.imphash_dict.update({'Metascan': Metascan().hash_to_imphash(search_value)})
            self.imphash_dict.update({'Totalhash': Totalhash().hash_to_imphash(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_hash.__name__, self.to_imphash.__name__,
                                                       self.imphash_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_hash.__name__, self.to_imphash.__name__,
                                                          self.imphash_dict)

##### IMPHASH SECTION ######
class From_imphash(object):
    def __init__(self, verbose=False):
        self.verbose = verbose
        self.hash_dict = {}

    ########################################
    # Searches to HASH
    def to_hash(self, search_value):
        if search_value:
            self.hash_dict.update({'Threatexpert': Threatexpert().imphash_to_hash(search_value)})
            self.hash_dict.update({'Totalhash': Totalhash().imphash_to_hash(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_imphash.__name__, self.to_hash.__name__,
                                                       self.hash_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_imphash.__name__, self.to_hash.__name__,
                                                          self.hash_dict)
##### MUTEX SECTION ######
class From_mutex(object):
    def __init__(self, verbose=False):
        self.verbose = verbose
        self.hash_dict = {}

    ########################################
    # Searches to HASH
    def to_hash(self, search_value):
        if search_value:
            self.hash_dict.update({'Threatexpert': Threatexpert().mutex_to_hash(search_value)})
            self.hash_dict.update({'Totalhash': Totalhash().mutex_to_hash(search_value)})

            if self.verbose:
                return helpers.Common().verbose_output(search_value, From_mutex.__name__, self.to_hash.__name__,
                                                       self.hash_dict)
            else:
                return helpers.Common().nonverbose_output(search_value, From_mutex.__name__, self.to_hash.__name__,
                                                          self.hash_dict)


text:
package org.apache.lucene.document;

/**
 *  Provides information about what should be done with this Field
 *
 **/
public enum FieldSelectorResult {

    /**
     * Load this {@link Field} every time the {@link Document} is loaded, reading in the data as it is encountered.
     *  {@link Document#getField(String)} and {@link Document#getFieldable(String)} should not return null.
     *

     * {@link Document#add(Fieldable)} should be called by the Reader.
     */
  LOAD,

    /**
     * Lazily load this {@link Field}.  This means the {@link Field} is valid, but it may not actually contain its data until
     * invoked.  {@link Document#getField(String)} SHOULD NOT BE USED.  {@link Document#getFieldable(String)} is safe to use and should
     * return a valid instance of a {@link Fieldable}.
     *

     * {@link Document#add(Fieldable)} should be called by the Reader.
     */
  LAZY_LOAD,

    /**
     * Do not load the {@link Field}.  {@link Document#getField(String)} and {@link Document#getFieldable(String)} should return null.
     * {@link Document#add(Fieldable)} is not called.
     *

     * {@link Document#add(Fieldable)} should not be called by the Reader.
     */
  NO_LOAD,

    /**
     * Load this field as in the {@link #LOAD} case, but immediately return from {@link Field} loading for the {@link Document}.  Thus, the
     * Document may not have its complete set of Fields.  {@link Document#getField(String)} and {@link Document#getFieldable(String)} should
     * both be valid for this {@link Field}
     *

     * {@link Document#add(Fieldable)} should be called by the Reader.
     */
  LOAD_AND_BREAK,

    /** Expert:  Load the size of this {@link Field} rather than its value.
     * Size is measured as number of bytes required to store the field == bytes for a binary or any compressed value, and 2*chars for a String value.
     * The size is stored as a binary value, represented as an int in a byte[], with the higher order byte first in [0]
     */
  SIZE,

    /** Expert: Like {@link #SIZE} but immediately break from the field loading loop, i.e., stop loading further fields, after the size is loaded */
  SIZE_AND_BREAK
}


text:
require "ammars_mega_lotto/version"
require "ammars_mega_lotto/drawing"

module AmmarsMegaLotto
  # Your code goes here...
end


text:
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map';

import { AppUser } from '../model/app-user';

@Injectable()
export class UserService {

    url = "http://localhost:54042/api/AppUsers/";

    constructor(private http: Http) { }

    getAll() {

        /*
        var ret: AppUser[] = [];

        this.http.get('http://localhost:54042/api/AppUsers').
            map(res => res.json())
            .subscribe(res => {
                console.log("res: " + res[0].Username);
                ret = res;
            });
        return ret;
         */
        return this.http.get(this.url, this.jwt()).map((response: Response) => response.json());
}

    getByUsername(username: string) {
        return this.http.get("http://localhost:54042/roles/" + username, this.jwt()).map((response: Response) => response.json());
    }

    create(user: AppUser) {
        return this.http.post(this.url, user).map((response: Response) => response.json());
    }

    update(user: AppUser) {
        return this.http.put(this.url + user.Id, user, this.jwt()).map((response: Response) => response.json());
    }

    delete(id: number) {
        return this.http.delete(this.url + id, this.jwt()).map((response: Response) => response.json());
    }

    // private helper methods

    private jwt() {
        // create authorization header with jwt token
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
         let token = JSON.parse(localStorage.getItem('id_token'));
        if (currentUser && token) {
            let headers = new Headers({ 'Authorization': 'Bearer ' + token });
            return new RequestOptions({ headers: headers });
        }
    }
}


text:
class RemoveOrdersTotals < ActiveRecord::Migration[4.2]

  def self.up
    remove_column :orders, :total_cost
    remove_column :orders, :total_subsidy
    remove_column :orders, :total
  end

  def self.down
    add_column :orders, :total_cost,    :decimal, precision: 8, scale: 2, null: true
    add_column :orders, :total_subsidy, :decimal, precision: 8, scale: 2, null: true
    add_column :orders, :total,         :decimal, precision: 8, scale: 2, null: true

    execute "UPDATE orders SET total_cost = 0"
    execute "UPDATE orders SET total_subsidy = 0"
    execute "UPDATE orders SET total = 0"

    change_column :orders, :total_cost,    :decimal, precision: 8, scale: 2, null: false
    change_column :orders, :total_subsidy, :decimal, precision: 8, scale: 2, null: false
    change_column :orders, :total,         :decimal, precision: 8, scale: 2, null: false
  end

end


text:
function Bot(nick) {
    this.nick = nick;
    this.FACTOID_STORE_RE = /^(\w+) is (.+)$/;
    this.FACTOID_REMOVE_RE = /^forget (\w+)$/;
    this.FACTOID_RETRIEVAL_RE = /^\?(\w+)$/;
    this.FACTOID_RETRIEVAL_MENTION_RE = /^\?(\w+)(\s)@(\s)(.+)$/;
    this.KARMA_RE = /(\w+)([+]{2}|[-]{2})/;
    this.KARMA_BEST_RE = /^karma best$/;
    this.KARMA_WORST_RE = /^karma worst$/;
    this.MESSAGE_STORE_RE = /^tell (\w+)\s(.+)$/;
    this.addressedToMe = function (message) {
        return message.indexOf(nick) === 0;
    };
    this.normalizeMessage = function (message) {
        return message.substring(message.indexOf(nick) + nick.length + 1).trim();
    };
    this.isStatusMessage = function (message) {
        return this.addressedToMe(message) && message.indexOf('#status') > 0;
    };
    this.normalizeStatusMessage = function (message) {
        return message.substring(message.indexOf('#status') + '#status'.length + 1).trim();
    };
    this.isFactoidStoreRequest = function (message) {
        return this.addressedToMe(message) && !!this.FACTOID_STORE_RE.exec(this.normalizeMessage(message));
    };
    this.parseFactoidStoreRequest = function (message) {
        var matchData = this.FACTOID_STORE_RE.exec(this.normalizeMessage(message));
        if (matchData) {
            return {key: matchData[1], value: matchData[2]};
        }
        return false;
    };
    this.isFactoidRemovalRequest = function (message) {
        return this.addressedToMe(message) && !!this.FACTOID_REMOVE_RE.exec(this.normalizeMessage(message));
    };
    this.parseFactoidRemovalRequest = function (message) {
        var matchData = this.FACTOID_REMOVE_RE.exec(this.normalizeMessage(message));
        if (matchData) {
            return matchData[1];
        }
        return false;
    };
    this.isFactoidRetrievalRequest = function (message) {
        return !!this.FACTOID_RETRIEVAL_RE.exec(message);
    };
    this.parseFactoidRetrievalRequest = function (message) {
        var matchData = this.FACTOID_RETRIEVAL_RE.exec(message);
        if (matchData) {
            return matchData[1];
        }
        return false;
    };
    this.isKarmaRequest = function (message) {
        return !!this.KARMA_RE.exec(message);
    };

    this.isKarmaBestRequest = function (message) {
        return !!this.KARMA_BEST_RE.exec(message);
    };

    this.isKarmaWorstRequest = function (message) {
        return !!this.KARMA_WORST_RE.exec(message);
    };
    this.parseKarmaRequest = function (message) {
        var re = this.KARMA_RE;
        var found = message.match(new RegExp(re.source, 'g'));
        var result = [];
        if (found) {
            for(var i = 0; i < found.length; i++) {
                var karmaReqStr = found[i];
                var match = karmaReqStr.match(re);
                var user = match[1].toLowerCase();
                var dir = match[2] === '++' ? 1 : -1;
                result.push({ user:user, direction:dir });
            }
            return result;
        }
    };
    this.isValidKarmaRequest = function(from, karmaRequest) {
        for (var i = 0; i < karmaRequest.length; i++) {
            var request = karmaRequest[i];
            if (request) {
                if (request.user === from) {
                    if (request.direction > 0) {
                        return false;
                    }
                }
            }
        }
        return true;
    };
    this.isFactoidRetrievalMentionRequest = function(message) {
        return !!this.FACTOID_RETRIEVAL_MENTION_RE.exec(message);
    };
    this.parseFactoidMentionRequests = function (message) {
        if( this.isFactoidRetrievalMentionRequest(message) ) {
            var matchData = message.split("@");
            return {
                factoid:matchData[0].trim(),
                target:matchData[1].trim()
            };
        } else {
            return false;
        }
    };
    this.isMessageStoreRequest = function (message) {
        return this.addressedToMe(message) && !!this.MESSAGE_STORE_RE.exec(this.normalizeMessage(message));
    };
    this.parseMessageStoreRequest = function (message) {
        var matchData = this.MESSAGE_STORE_RE.exec(this.normalizeMessage(message));
        if (matchData) {
            return {
                recipient: matchData[1].trim(),
                message: matchData[2].trim()
            };
        } else {
            return false;
        }
    };
}
exports.Bot = Bot;


text:
namespace ReflexAPI.Util
{
    using System;
    using System.Reflection;
    using log4net;

    /// <summary>
    /// Utility class for logging operations.
    /// </summary>
    public static class LoggerUtil
    {
        public static readonly Type LogClassType = MethodBase.GetCurrentMethod().DeclaringType;
        public static readonly ILog Logger = LogManager.GetLogger(LogClassType);

        /// <summary>
        /// Logs the current message to both the loggers specified for handling information and
        /// debug messages.
        /// </summary>
        /// <param name="msg">The message to log.</param>
        /// <param name="type">The type of class that initiated the log request.</param>
        public static void LogInfoAndDebug(string msg, Type type)
        {
            var logger = LogManager.GetLogger(type);
            logger.Debug(msg);
            logger.Info(msg);
        }
    }
}


text:
package com.amazonaws.services.rekognition.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetFaceDetectionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * Unique identifier for the face detection job. The JobId is returned from
     * StartFaceDetection.
     *

     */
    private String jobId;
    /**
     *

     * Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you specify
     * a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     *

     */
    private Integer maxResults;
    /**
     *

     * If the previous response was incomplete (because there are more faces to retrieve), Amazon Rekognition Video
     * returns a pagination token in the response. You can use this pagination token to retrieve the next set of faces.
     *

     */
    private String nextToken;

    /**
     *

     * Unique identifier for the face detection job. The JobId is returned from
     * StartFaceDetection.
     *

     *
     * @param jobId
     *        Unique identifier for the face detection job. The JobId is returned from
     *        StartFaceDetection.
     */

    public void setJobId(String jobId) {
        this.jobId = jobId;
    }

    /**
     *

     * Unique identifier for the face detection job. The JobId is returned from
     * StartFaceDetection.
     *

     *
     * @return Unique identifier for the face detection job. The JobId is returned from
     *         StartFaceDetection.
     */

    public String getJobId() {
        return this.jobId;
    }

    /**
     *

     * Unique identifier for the face detection job. The JobId is returned from
     * StartFaceDetection.
     *

     *
     * @param jobId
     *        Unique identifier for the face detection job. The JobId is returned from
     *        StartFaceDetection.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetFaceDetectionRequest withJobId(String jobId) {
        setJobId(jobId);
        return this;
    }

    /**
     *

     * Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you specify
     * a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     *

     *
     * @param maxResults
     *        Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you
     *        specify a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you specify
     * a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     *

     *
     * @return Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you
     *         specify a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you specify
     * a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     *

     *
     * @param maxResults
     *        Maximum number of results to return per paginated call. The largest value you can specify is 1000. If you
     *        specify a value greater than 1000, a maximum of 1000 results is returned. The default value is 1000.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetFaceDetectionRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     *

     * If the previous response was incomplete (because there are more faces to retrieve), Amazon Rekognition Video
     * returns a pagination token in the response. You can use this pagination token to retrieve the next set of faces.
     *

     *
     * @param nextToken
     *        If the previous response was incomplete (because there are more faces to retrieve), Amazon Rekognition
     *        Video returns a pagination token in the response. You can use this pagination token to retrieve the next
     *        set of faces.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * If the previous response was incomplete (because there are more faces to retrieve), Amazon Rekognition Video
     * returns a pagination token in the response. You can use this pagination token to retrieve the next set of faces.
     *

     *
     * @return If the previous response was incomplete (because there are more faces to retrieve), Amazon Rekognition
     *         Video returns a pagination token in the response. You can use this pagination token to retrieve the next
     *         set of faces.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * If the previous response was incomplete (because there are more faces to retrieve), Amazon Rekognition Video
     * returns a pagination token in the response. You can use this pagination token to retrieve the next set of faces.
     *

     *
     * @param nextToken
     *        If the previous response was incomplete (because there are more faces to retrieve), Amazon Rekognition
     *        Video returns a pagination token in the response. You can use this pagination token to retrieve the next
     *        set of faces.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetFaceDetectionRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getJobId() != null)
            sb.append("JobId: ").append(getJobId()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetFaceDetectionRequest == false)
            return false;
        GetFaceDetectionRequest other = (GetFaceDetectionRequest) obj;
        if (other.getJobId() == null ^ this.getJobId() == null)
            return false;
        if (other.getJobId() != null && other.getJobId().equals(this.getJobId()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getJobId() == null) ? 0 : getJobId().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public GetFaceDetectionRequest clone() {
        return (GetFaceDetectionRequest) super.clone();
    }

}


text:
NHotkey
=======

Easily handle shortcut keys even when your WPF or WinForms app doesn't have focus. Declare hotkeys in XAML with the familiar `KeyBinding` syntax.

Nuget packages:
- for WPF: [NHotkey.Wpf](http://www.nuget.org/packages/NHotkey.Wpf/)
- for Windows Forms: [NHotkey.WindowsForms](http://www.nuget.org/packages/NHotkey.WindowsForms/)

### Windows Forms usage

Add a reference to `NHotkey.dll` and `NHotkey.WindowsForms.dll`. In the file where you want to
handle hotkeys, import the `NHotkey.WindowsForms` namespace:

```csharp
    using NHotkey.WindowsForms;
```

During initialization, add some hotkeys:

```csharp
    HotkeyManager.Current.AddOrReplace("Increment", Keys.Control | Keys.Alt | Keys.Add, OnIncrement);
    HotkeyManager.Current.AddOrReplace("Decrement", Keys.Control | Keys.Alt | Keys.Subtract, OnDecrement);
```

- the first parameter is an application-defined name for the hotkey; it can be anything you like,
as long as it's unique;
- the second parameter is the combination of keys for which you want to register a hotkey;
- the last parameter is a delegate of type `EventHandler<HotkeyEventArgs>` that will be called
when this hotkey is pressed. For instance:

```csharp
    private void OnIncrement(object sender, HotkeyEventArgs e)
    {
        Value++;
        e.Handled = true;
    }

    private void OnDecrement(object sender, HotkeyEventArgs e)
    {
        Value--;
        e.Handled = true;
    }
```

If you want to handle several hotkeys with the same handler, you can check the `Name`
property of the `HotkeyEventArgs`:

```csharp
    private void OnIncrementOrDecrement(object sender, HotkeyEventArgs e)
    {
        switch (e.Name)
        {
            case "Increment":
                Value++;
                break;
            case "DEcrement":
                Value--;
                break;
        }
        e.Handled = true;
    }
```

### WPF usage

The approach for WPF is very similar to the one for Windows Forms; the exposed API is slightly
different to account for the differences between WinForms and WPF. The WPF version also
supports `KeyBindings`.

Add a reference to `NHotkey.dll` and `NHotkey.Wpf.dll`. In the file where you want to
handle hotkeys, import the `NHotkey.Wpf` namespace:

```csharp
    using NHotkey.Wpf;
```

During initialization, add some hotkeys:

```csharp
    HotkeyManager.Current.AddOrReplace("Increment", Key.Add, ModifierKeys.Control | ModifierKeys.Alt, OnIncrement);
    HotkeyManager.Current.AddOrReplace("Decrement", Key.Subtract, ModifierKeys.Control | ModifierKeys.Alt, OnDecrement);
```

- the first parameter is an application-defined name for the hotkey; it can be anything you like,
as long as it's unique;
- the second and third parameters are the key and modifiers for which you want to register a hotkey;
- the last parameter is a delegate of type `EventHandler<HotkeyEventArgs>` that will be called
when this hotkey is pressed.

To support applications that use the MVVM pattern, you can also specify hotkeys in XAML using
`InputBindings`. Just declare `KeyBindings` as usual, and set the `HotkeyManager.RegisterGlobalHotkey`
attached property to `true`:

```xml
    ...
    <Window.InputBindings>
        <KeyBinding Gesture="Ctrl+Alt+Add" Command="{Binding IncrementCommand}"
                    HotkeyManager.RegisterGlobalHotkey="True" />
        <KeyBinding Gesture="Ctrl+Alt+Subtract" Command="{Binding DecrementCommand}"
                    HotkeyManager.RegisterGlobalHotkey="True" />
    </Window.InputBindings>
    ...
```

**Known limitations of this feature**

- the `HotkeyManager` can't detect if you remove a `KeyBinding`; it only relies on the
attached property being set to true or false. If you want to remove a KeyBinding at runtime,
make sure you set `HotkeyManager.RegisterGlobalHotkey` to false, otherwise it will
still be registered
- changing the keys or modifiers of a `KeyBinding` at runtime is currently not supported. If
you need to modify a `KeyBinding` at runtime, you need to set `HotkeyManager.RegisterGlobalHotkey`
to false, change the key, and set `HotkeyManager.RegisterGlobalHotkey` to true again.


text:
echo debconf shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true | /usr/bin/debconf-set-selections

DEBIAN_FRONTEND=noninteractive apt-get -y -qq update
DEBIAN_FRONTEND=noninteractive apt-get -y -qq install unzip wget software-properties-common

apt-add-repository -y ppa:webupd8team/java

DEBIAN_FRONTEND=noninteractive apt-get -y -qq update
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq oracle-java7-installer
DEBIAN_FRONTEND=noninteractive apt-get -y --force-yes -qq install ant && rm -Rf /var/cache/apt/*

mkdir /openrefine

# Download OpenRefine from gitub repository and compile
wget --no-check-certificate https://github.com/OpenRefine/OpenRefine/archive/2.6-beta.1.tar.gz -O ./2.6-beta.1.tar.gz; \
    tar xzvf 2.6-beta.1.tar.gz; rm 2.6-beta.1.tar.gz

mv OpenRefine-2.6-beta.1/* /openrefine; rm -rf OpenRefine-2.6-beta.1

cd /openrefine; ant clean build

# Download and compile rdf-extension
cd extensions; wget https://github.com/fadmaa/grefine-rdf-extension/archive/v0.9.0.tar.gz -O v0.9.0.tar.gz; \
    tar xzvf v0.9.0.tar.gz && rm v0.9.0.tar.gz; \
    mv grefine-rdf-extension-0.9.0 rdf-extension; \
    cd rdf-extension; \
    JAVA_TOOL_OPTIONS='-Dfile.encoding=UTF-8' ant build

# OpenRefine start script, adjusts the JVM memory according to the machines available memory

echo "#!/bin/bash

if [ -z "\$REFINE_MEMORY" ] ; then
    TOTAL_MEMORY=\`free -b | grep Mem | awk '{print \$2}'\`
    MIN_REFINE_MEMORY=\$(( $TOTAL_MEMORY - 3 * 1024 * 1024 * 1024 ))
    REFINE_MEMORY=\$(( \$TOTAL_MEMORY * 6 / 10 ))

    if [ "\$REFINE_MEMORY" -lt "\$MIN_REFINE_MEMORY" ]; then
        REFINE_MEMORY=\"$MIN_REFINE_MEMORY\"
    fi
fi
exec /openrefine/refine -i 0.0.0.0 -m \$REFINE_MEMORY" > /start.sh

chmod +x /start.sh

# Add OpenRefine to upstart

echo 'exec /start.sh
start on (local-filesystems and net-device-up IFACE!=lo)
stop on runlevel [!2345]
limit nofile 524288 1048576
limit nproc 524288 1048576
respawn' > /etc/init/openrefine.conf


text:
<?php

namespace Kunstmaan\NodeSearchBundle\Search;

use Kunstmaan\AdminBundle\Entity\BaseUser;
use Kunstmaan\AdminBundle\Helper\DomainConfigurationInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

/**
 * Default node searcher implementation
 *
 * @package Kunstmaan\NodeSearchBundle\Search
 */
class NodeSearcher extends AbstractElasticaSearcher
{
    /**
     * @var TokenStorageInterface
     */
    private $tokenStorage = null;

    /**
     * @var DomainConfigurationInterface
     */
    private $domainConfiguration;

    /**
     * @param TokenStorageInterface $tokenStorage
     */
    public function setTokenStorage(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    /**
     * @param DomainConfigurationInterface $domainConfiguration
     */
    public function setDomainConfiguration(DomainConfigurationInterface $domainConfiguration)
    {
        $this->domainConfiguration = $domainConfiguration;
    }

    /**
     * @param mixed  $query
     * @param string $lang
     * @param string $type
     *
     * @return mixed|void
     */
    public function defineSearch($query, $lang, $type)
    {
        $query = \Elastica\Util::escapeTerm($query);

        $elasticaQueryLang = new \Elastica\Query\Term();
        $elasticaQueryLang->setTerm('lang', $lang);

        $elasticaQueryString = new \Elastica\Query\Match();
        $elasticaQueryString
            ->setFieldQuery('content', $query)
            ->setFieldMinimumShouldMatch('content', '80%');

        $elasticaQueryTitle = new \Elastica\Query\QueryString();
        $elasticaQueryTitle
            ->setDefaultField('title')
            ->setBoost(2.0)
            ->setQuery($query);

        $elasticaQueryBool = new \Elastica\Query\BoolQuery();
        $elasticaQueryBool
            ->addMust($elasticaQueryLang)
            ->addShould($elasticaQueryTitle)
            ->addShould($elasticaQueryString)
            ->setMinimumNumberShouldMatch(1);

        $this->applySecurityFilter($elasticaQueryBool);

        if (!is_null($type)) {
            $elasticaQueryType = new \Elastica\Query\Term();
            $elasticaQueryType->setTerm('type', $type);
            $elasticaQueryBool->addMust($elasticaQueryType);
        }

        $rootNode = $this->domainConfiguration->getRootNode();
        if (!is_null($rootNode)) {
            $elasticaQueryRoot = new \Elastica\Query\Term();
            $elasticaQueryRoot->setTerm('root_id', $rootNode->getId());
            $elasticaQueryBool->addMust($elasticaQueryRoot);
        }

        $this->query->setQuery($elasticaQueryBool);
        $this->query->setHighlight(
            array(
                'pre_tags'  => array('<strong>'),
                'post_tags' => array('</strong>'),
                'fields'    => array(
                    'content' => array(
                        'fragment_size'       => 150,
                        'number_of_fragments' => 3
                    )
                )
            )
        );

    }

    /**
     * Filter search results so only documents that are viewable by the current
     * user will be returned...
     *
     * @param \Elastica\Query\BoolQuery $elasticaQueryBool
     */
    protected function applySecurityFilter($elasticaQueryBool)
    {
        $roles = $this->getCurrentUserRoles();

        $elasticaQueryRoles = new \Elastica\Query\Terms();
        $elasticaQueryRoles
            ->setTerms('view_roles', $roles)
            ->setMinimumMatch(1);
        $elasticaQueryBool->addMust($elasticaQueryRoles);
    }

    /**
     * @return array
     */
    protected function getCurrentUserRoles()
    {
        $roles = array();
        if (!is_null($this->tokenStorage)) {
            $user = $this->tokenStorage->getToken()->getUser();
            if ($user instanceof BaseUser) {
                $roles = $user->getRoles();
            }
        }

        // Anonymous access should always be available for both anonymous & logged in users
        if (!in_array('IS_AUTHENTICATED_ANONYMOUSLY', $roles)) {
            $roles[] = 'IS_AUTHENTICATED_ANONYMOUSLY';
        }

        return $roles;
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Kangyi
 * Date: 2015/1/14
 * Time: 11:23
 */

namespace Admin\Controller;
use Think\Controller;
use Think\Model;

class DeviceController extends AdminController{

    public function  _initialize(){
        parent::_initialize();
    }

    public function index(){
        $this->assign('uniqid',uniqid());
        $this->display();
    }

    public function getList(){
        //分页
        $page = I('page');
        $rows = I('rows');
        if(!$page){
            $page = NULL;
            $rows = NULL;
        }
        $Model = D('device');
        $where = NULL;

        $uid = I('uid');
        if($uid){
            $where['uid'] = $uid;
        }

        $list = $Model->getList($where,$page,$rows);
        $count = $Model->getCount($where);
        $result['total'] = $count;
        if(!$list){ $list = ''; }
        $result["rows"] = $list;
        $this->ajaxReturn($result,'JSON');
    }
}


text:
package functional

import play.api.test._
import play.api.test.Helpers._
import play.api.i18n.MessagesApi
import play.api.i18n.{Lang, Messages, MessagesImpl, MessagesProvider}
import java.time.Instant
import play.api.{Application => PlayApp}
import play.api.inject.guice.GuiceApplicationBuilder
import helpers.InjectorSupport
import play.api.db.Database
import org.joda.time.format.DateTimeFormat
import helpers.ViewHelpers
import java.util.concurrent.TimeUnit
import play.api.test._
import play.api.test.Helpers._
import java.sql.Connection

import helpers.Helper._
import org.specs2.mutable.Specification
import play.api.test.{Helpers, TestServer}
import play.api.i18n.{Lang, Messages}
import models._
import play.api.test.TestServer
import com.ruimo.scoins.Scoping._

class CouponSalesSpec extends Specification with InjectorSupport {
  "Coupon sale" should {
    "If the all of items are coupon, shipping address should be skipped." in new WithBrowser(
      WebDriverFactory(CHROME), appl(inMemoryDatabase(options = Map("MVCC" -> "true")))
    ) {
      inject[Database].withConnection { implicit conn =>
        val currencyInfo = inject[CurrencyRegistry]
        val localeInfo = inject[LocaleInfoRepo]
        import localeInfo.{En, Ja}
        implicit val lang = Lang("ja")
        implicit val storeUserRepo = inject[StoreUserRepo]
        val Messages = inject[MessagesApi]
        implicit val mp: MessagesProvider = new MessagesImpl(lang, Messages)

        val user = loginWithTestUser(browser)
        val tax = inject[TaxRepo].createNew
        val his = inject[TaxHistoryRepo].createNew(tax, TaxType.OUTER_TAX, BigDecimal("8"), date("9999-12-31"))
        val site1 = inject[SiteRepo].createNew(Ja, "商店1")
        val site2 = inject[SiteRepo].createNew(Ja, "商店2")
        val cat1 = inject[CategoryRepo].createNew(Map(Ja -> "植木", En -> "Plant"))

        val item1 = inject[ItemRepo].createNew(cat1)
        val item2 = inject[ItemRepo].createNew(cat1)
        val item3 = inject[ItemRepo].createNew(cat1)

        Coupon.updateAsCoupon(item1.id.get)
        Coupon.updateAsCoupon(item2.id.get)
        Coupon.updateAsCoupon(item3.id.get)

        val name1 = inject[ItemNameRepo].createNew(item1, Map(Ja -> "クーポン1", En -> "Coupon1"))
        val name2 = inject[ItemNameRepo].createNew(item2, Map(Ja -> "クーポン2", En -> "Coupon2"))
        val name3 = inject[ItemNameRepo].createNew(item3, Map(Ja -> "クーポン3", En -> "Coupon3"))

        val desc1 = inject[ItemDescriptionRepo].createNew(item1, site1, "クーポン1説明")
        val desc2 = inject[ItemDescriptionRepo].createNew(item2, site2, "クーポン2説明")
        val desc3 = inject[ItemDescriptionRepo].createNew(item3, site2, "クーポン3説明")

        inject[SiteItemRepo].createNew(site1, item1)
        inject[SiteItemRepo].createNew(site2, item2)
        inject[SiteItemRepo].createNew(site2, item3)

        val price1 = inject[ItemPriceRepo].createNew(item1, site1)
        val price2 = inject[ItemPriceRepo].createNew(item2, site2)
        val price3 = inject[ItemPriceRepo].createNew(item3, site2)

        val ph1 = inject[ItemPriceHistoryRepo].createNew(
          price1, tax, currencyInfo.Jpy, BigDecimal(101), None, BigDecimal(90), date("9999-12-31")
        )
        val ph2 = inject[ItemPriceHistoryRepo].createNew(
          price2, tax, currencyInfo.Jpy, BigDecimal(301), None, BigDecimal(200), date("9999-12-31")
        )
        val ph3 = inject[ItemPriceHistoryRepo].createNew(
          price3, tax, currencyInfo.Jpy, BigDecimal(401), None, BigDecimal(390), date("9999-12-31")
        )

        val cart1 = inject[ShoppingCartItemRepo].addItem(user.id.get, site1.id.get, item1.id.get.id, 15)
        val cart2 = inject[ShoppingCartItemRepo].addItem(user.id.get, site2.id.get, item2.id.get.id, 28)
        val cart3 = inject[ShoppingCartItemRepo].addItem(user.id.get, site2.id.get, item3.id.get.id, 40)

        browser.goTo(
          controllers.routes.Shipping.startEnterShippingAddress().url + "?lang=" + lang.code
        )

        browser.await().atMost(5, TimeUnit.SECONDS).untilPage().isLoaded()
        browser.webDriver.getTitle === Messages("commonTitle", Messages("confirm.shipping.address"))

        doWith(browser.find(".itemTableBody").index(0)) { b =>
          b.find(".itemName").text === "クーポン1"
          b.find(".siteName").text === "商店1"
          b.find(".itemQuantity").text === "15"
          b.find(".itemPrice").text === ViewHelpers.toAmount(BigDecimal(101 * 15))
        }

        doWith(browser.find(".itemTableBody").index(1)) { b =>
          b.find(".itemName").text === "クーポン2"
          b.find(".siteName").text === "商店2"
          b.find(".itemQuantity").text === "28"
          b.find(".itemPrice").text === ViewHelpers.toAmount(BigDecimal(301 * 28))
        }

        doWith(browser.find(".itemTableBody").index(2)) { b =>
          b.find(".itemName").text === "クーポン3"
          b.find(".siteName").text === "商店2"
          b.find(".itemQuantity").text === "40"
          b.find(".itemPrice").text === ViewHelpers.toAmount(BigDecimal(401 * 40))
        }

        browser.find(".subtotal").text === ViewHelpers.toAmount(
          BigDecimal(101 * 15 + 301 * 28 + 401 * 40)
        )

        val now = System.currentTimeMillis
        browser.find("#paypalimg").size === 0
        browser.find(".payByAccountingBill").click()
        browser.await().atMost(5, TimeUnit.SECONDS).untilPage().isLoaded()

        doWith(browser.find(".itemTableBody").index(0)) { b =>
          b.find(".itemName .itemNameBody").text === "クーポン1"
          b.find(".siteName").text === "商店1"
          b.find(".quantity").text === "15"
          b.find(".itemPrice").text === ViewHelpers.toAmount(BigDecimal(1515))
        }

        doWith(browser.find(".itemTableBody").index(1)) { b =>
          b.find(".itemName .itemNameBody").text === "クーポン2"
          b.find(".siteName").text === "商店2"
          b.find(".quantity").text === "28"
          b.find(".itemPrice").text === ViewHelpers.toAmount(BigDecimal(8428))
        }

        doWith(browser.find(".itemTableBody").index(2)) { b =>
          b.find(".itemName .itemNameBody").text === "クーポン3"
          b.find(".siteName").text === "商店2"
          b.find(".quantity").text === "40"
          b.find(".itemPrice").text === ViewHelpers.toAmount(BigDecimal(16040))
        }

        browser.find(".itemTableBody").index(2).find(".itemName input").click()

        val currentWindow = browser.webDriver.getWindowHandle
        val allWindows = browser.webDriver.getWindowHandles
        allWindows.remove(currentWindow)
        browser.webDriver.switchTo().window(allWindows.iterator.next)

        browser.await().atMost(5, TimeUnit.SECONDS).untilPage().isLoaded()

        browser.find(".date").find("span").index(1).text() ===
          DateTimeFormat.forPattern(Messages("published.date.format")).print(now)
        browser.find(".siteName").text() === Messages("coupon.user.company.name", "Company1")
        browser.find(".name").text() === justOneSpace(
          Messages("coupon.user.name", "Admin", "", "Manager")
        )
      }
    }
  }
}


text:
'use strict';

// Declare imports
const _ = require('lodash');
const querystring = require('querystring');
const PostmenError = require('./error/error');
const ErrorEnum = require('./error/error_enum');
// Global variable
const methods = ['GET', 'POST', 'DELETE', 'PUT'];
const version = '1.0.0';
const supported_headers = ['platform'];
// Payload class
class Payload {
	/**
	 * Function to create the request_object and other information
	 *
	 * @param postmen {Postmen} - the postmen object
	 * @param method {string} - get, post, put or delete
	 * @param resource {string} - pathname for URL
	 * @param input
	 *    body {object} - POST body
	 *    headers {object} - Customized headers
	 *    query {object} - query object or string
	 * @param config {object}
	 *     api_key {string} - Your Postmen API key
	 *     retry {boolean} - Retry if fail override this.retry if set
	 *     raw {boolean} - if true, return string, else return object, default false
	 * @return the payload object with properities below
	 * {
	 *    request_object {object} - object to create request
	 *    retry {boolean} - retry flag
	 *    raw {boolean} - response with string or not
	 * }
	 */
	constructor(postmen, method, resource, input, config) {
		// console.log(input);
		// (postmen, method, resource, input, config)
		this._errorHandling(method, resource, input, config);

		config = config || {};
		input = input || {};
		let qs = input.query;
		// parse qs if string
		if (_.isString(qs)) {
			qs = querystring.parse(qs);
		}
		// Request object
		let request_object = {
			headers: Object.assign({
				'postmen-api-key': config.api_key || postmen.tmp_api_key || postmen.api_key,
				'Content-Type': 'application/json',
				'Connection': 'keep-alive',
				'x-postmen-agent': version
			}, _.pick(input.headers, supported_headers)),
			url: this._urlBuilder(postmen.endpoint, resource),
			method: method,
			body: input.body,
			qs: qs,
			proxy: config.proxy || postmen.proxy,
			json: true
		};

		// Remove all null or undefined
		for (let key in request_object) {
			if (request_object[key] === null || request_object[key] === undefined) {
				delete request_object[key];
			}
		}

		// reset the tmp_api_key, if set the api_key by chainable function
		if (postmen.tmp_api_key) {
			postmen.tmp_api_key = null;
		}

		// Payload
		let payload = {
			request_object: request_object,
			retry: _.isBoolean(config.retry) ? config.retry : postmen.retry,
			raw: _.isBoolean(config.raw) ? config.raw : postmen.raw,
			delay: 1000
		};

		// Add retry count if needed
		if (payload.retry) {
			payload.retry_count = 1;
		}

		// console.log(payload);
		return payload; // Q: weird to return here
	}
	/**
	 * format the URL
	 *
	 * @param path {string}
	 * @param resource {string}
	 */
	_urlBuilder(path, resource) {
		let url;
		url = [path, resource].join('/');
		return url.replace(/([^:]\/)\/+/g, '$1');
	}
	/**
	 * Error Handling function
	 * Throw error if the input param contain incorrect type
	 *
	 * @param method {string}
	 * @param resource {resource}
	 * @param config {object}
	 */
	_errorHandling(method, resource, input, config) {
		// body, query, retry, raw
		if (!_.isString(method)) {
			// Verify method
			throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidMethod, method);
		} else if (methods.indexOf(method.toUpperCase()) === -1) {
			// Verify method
			throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidMethod, method);
		} else if (!_.isString(resource)) {
			// Verify resource
			throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidResource, resource);
		} else if (!_.isNull(input) && !_.isUndefined(input) && !_.isPlainObject(input)) {
			// Verify input
			throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidInputs, input);
		} else if (!_.isNull(config) && !_.isUndefined(config) && !_.isPlainObject(config)) {
			// Verify config
			throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidConfig, config);
		}

		// Verify input value
		if (input) {
			if (!_.isNull(input.body) && !_.isUndefined(input.body) && !_.isPlainObject(input.body)) {
				// Verify body
				throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidBody, input.body);
			} else if (!_.isNull(input.query) && !_.isUndefined(input.query) && !_.isPlainObject(input.query) && !_.isString(input.query)) {
				// Verify query
				throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidQuery, input.query);
			}
		}

		// Verify config value
		if (config) {
			if (!_.isNull(config.retry) && !_.isUndefined(config.retry) && !_.isBoolean(config.retry)) {
				// Verify retry
				throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidRetry, config.retry);
			} else if (!_.isNull(config.raw) && !_.isUndefined(config.raw) && !_.isBoolean(config.raw)) {
				// Verify raw
				throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidRaw, config.raw);
			} else if (!_.isNull(config.api_key) && !_.isUndefined(config.api_key) && !_.isString(config.api_key)) {
				// Verify api_key
				throw PostmenError.getSdkError(ErrorEnum.HandlerInvalidApiKey, config.api_key);
			}
		}
	}
}

// Exports the constructor
module.exports = function (postmen, method, resource, input, config) {
	return new Payload(postmen, method, resource, input, config);
};


text:
<?php
use yii\helpers\Url;
?>

<?= Yii::t('forms','to_order_test_drive') ?>

                        <form class="f-smr xhr-form" id="smr_form" method="POST" action="<?= Url::to(['/api/forms/add']) ?>" data-modal-success="thanks" data-modal-err="server-error">

                                <?= Yii::t('forms','your_name') ?>
                                <input type="text" class="g-input g-input--simple" name="name" id="smr_name" placeholder="<?= Yii::t('forms','your_name') ?>">

                                <?= Yii::t('forms','phone_number') ?> *
                                <input type="phone" class="g-input g-input--simple" name="phone" id="smr_phone" placeholder="<?= Yii::t('forms','phone_number') ?> *" required="required" aria-required="true">

                                <?= Yii::t('forms','your_email') ?>
                                <input type="email" class="g-input g-input--simple" name="email" id="smr_email" placeholder="<?= Yii::t('forms','your_email') ?>">

                            <input type="hidden" hidden name="form_type" value="test-drive">
                            <input name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" type="hidden">

                                    <button type="submit" class="btn btn--colored btn--normal"><?= Yii::t('forms','send') ?></button>

                        </form>