text:
require 'rubygems'
require 'mme_tools/config'
require 'logger'

# per guardar i recuperar totes les configuracions es pot modificar l'arxiu
# 'config.yml'. Si s'esborra es regenera.
# la configuracio queda en l'objecte @setup de tipus MMETools::Config que es pot
# usar des d'on es 'requereixi' aquest arxiu.
if File.exist?("config.yml")
  @setup = MMETools::Config.load("config.yml")
else
  @setup = MMETools::Config.new do |c|

    _dir = File.expand_path(File.dirname(__FILE__))
    _nam = "gencat"

    # DEMO'S OWN CONFIGURACTION
    c.online = true   # if true -> application accesses internet
    # if false -> application uses Fakeweb to access pages

    # saving pages
    c.pdump = false    # if true -> accessed pages will be saved
    # if false -> accessed pages won't be saved
    # dir where dumped files will be stored
    #c.pdump_dir = File.expand_path("tmp/web_dumps","~")
    c.pdump_dir = "~/tmp/web_dumps"
    # extension of dumped files. If "gz" is used they will be compressed and
    # cannot be used by Fakeweb because it needs plain files
    c.pdump_ext = ".html"

    # saving data
    c.ddump = true    # if true -> parsed data will be saved
    # if true -> parsed data won't be saved
    # directory where parsed data will be saved
    c.ddump_dir = "tmp/data_dumps"
    # format of saved files
    c.ddump_format = :json

    # logging
    c.log = true      # if true -> log info will be saved
    # if false -> log info won't be saved
    #c.log_file = File.join(_dir,"tmp", _nam + ".log")
    c.log_file = File.join("tmp", _nam + ".log")
    c.log_level = Logger::DEBUG

    # parsed data
    c.saveparsed = true
    #c.saveparsed_file = File.join(_dir,"tmp", _nam + "_exp.yml")
    c.saveparsed_file = File.join("tmp", _nam + "_exp.yml")

    # simple map
    c.lookup = true
    #c.lookup_file = File.join(_dir,"tmp", _nam + "_lookup.yml")
    c.lookup_file = File.join("tmp", _nam + "_lookup.yml")

    # Threaded Agent
    c.num_threads = 8

    # Pagines inicials per scrutinitzar
    c.seeds = {
      # Futures licitacions que ja estan una mica passades ... Em sembla que ja no esta mantinguda aquesta seccio
      :ALERTES_FUTURES=> "https://contractaciopublica.gencat.cat/ecofin_pscp/AppJava/search.pscp?reqCode=searchCtn&set-locale=ca_ES",
      # Anuncis Previs: Futures licitacions que sembla que estan una mica mes actualitzades, tot i que algunes son molt velles
      :ANUNC_PREV => "https://contractaciopublica.gencat.cat/ecofin_pscp/AppJava/search.pscp?reqCode=searchPin&advancedSearch=false",
      # Anuncis de Licitacions en curs: Licitacions que es poden concursar i encara no ha arribat la data de presentacio
      :ANUNC_LICIT => "https://contractaciopublica.gencat.cat/ecofin_pscp/AppJava/search.pscp?reqCode=searchCn&advancedSearch=false",
      # Adjudciacions provisionals
      :ADJUD_PROV =>"https://contractaciopublica.gencat.cat/ecofin_pscp/AppJava/search.pscp?reqCode=searchPcan&advancedSearch=false&lawType=1",
      # Adjudciacions definitives
      :ADJUD_DEFI =>"https://contractaciopublica.gencat.cat/ecofin_pscp/AppJava/search.pscp?reqCode=searchDcan&advancedSearch=false&lawType=1",
    }
  end
  @setup.dump "config.yml"
end

# Rest of required files and setups

# minim suport de utf-8 a Ruby 1.8, pero millor anar a Ruby 1.9
require 'jcode' if RUBY_VERSION < '1.9'
#$KCODE = "u"
# includes generics
require 'yaml'
require 'fakeweb'
require 'uri_pathname'
# includes particulars
require '../../lib/webscrutinizer'  # use flag -I ../../lib to require the development .rb
# in other case, gem lib will be required


text:
package statistics_test

import (
	"time"

	. "github.com/pingcap/check"
	"github.com/pingcap/tidb/domain"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/model"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/testkit"
	"github.com/pingcap/tidb/util/testleak"
)

var _ = Suite(&testStatsUpdateSuite{})

type testStatsUpdateSuite struct {
	store kv.Storage
	do    *domain.Domain
}

func (s *testStatsUpdateSuite) SetUpSuite(c *C) {
	testleak.BeforeTest()
	var err error
	s.store, s.do, err = newStoreWithBootstrap(0)
	c.Assert(err, IsNil)
}

func (s *testStatsUpdateSuite) TearDownSuite(c *C) {
	s.do.Close()
	s.store.Close()
	testleak.AfterTest(c)()
}

func (s *testStatsUpdateSuite) TestSingleSessionInsert(c *C) {
	defer cleanEnv(c, s.store, s.do)
	testKit := testkit.NewTestKit(c, s.store)
	testKit.MustExec("use test")
	testKit.MustExec("create table t1 (c1 int, c2 int)")
	testKit.MustExec("create table t2 (c1 int, c2 int)")

	rowCount1 := 10
	rowCount2 := 20
	for i := 0; i < rowCount1; i++ {
		testKit.MustExec("insert into t1 values(1, 2)")
	}
	for i := 0; i < rowCount2; i++ {
		testKit.MustExec("insert into t2 values(1, 2)")
	}

	is := s.do.InfoSchema()
	tbl1, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
	c.Assert(err, IsNil)
	tableInfo1 := tbl1.Meta()
	h := s.do.StatsHandle()

	h.HandleDDLEvent(<-h.DDLEventCh())
	h.HandleDDLEvent(<-h.DDLEventCh())

	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 := h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(rowCount1))

	tbl2, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t2"))
	c.Assert(err, IsNil)
	tableInfo2 := tbl2.Meta()
	stats2 := h.GetTableStats(tableInfo2.ID)
	c.Assert(stats2.Count, Equals, int64(rowCount2))

	testKit.MustExec("analyze table t1")
	// Test update in a txn.
	for i := 0; i < rowCount1; i++ {
		testKit.MustExec("insert into t1 values(1, 2)")
	}
	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 = h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(rowCount1*2))

	// Test IncreaseFactor.
	count, err := stats1.ColumnEqualRowCount(testKit.Se.GetSessionVars().StmtCtx, types.NewIntDatum(1), tableInfo1.Columns[0].ID)
	c.Assert(err, IsNil)
	c.Assert(count, Equals, float64(rowCount1*2))

	testKit.MustExec("begin")
	for i := 0; i < rowCount1; i++ {
		testKit.MustExec("insert into t1 values(1, 2)")
	}
	testKit.MustExec("commit")
	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 = h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(rowCount1*3))

	testKit.MustExec("begin")
	for i := 0; i < rowCount1; i++ {
		testKit.MustExec("insert into t1 values(1, 2)")
	}
	for i := 0; i < rowCount1; i++ {
		testKit.MustExec("delete from t1 limit 1")
	}
	for i := 0; i < rowCount2; i++ {
		testKit.MustExec("update t2 set c2 = c1")
	}
	testKit.MustExec("commit")
	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 = h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(rowCount1*3))
	stats2 = h.GetTableStats(tableInfo2.ID)
	c.Assert(stats2.Count, Equals, int64(rowCount2))

	testKit.MustExec("begin")
	testKit.MustExec("delete from t1")
	testKit.MustExec("commit")
	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 = h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(0))

	rs := testKit.MustQuery("select modify_count from mysql.stats_meta")
	rs.Check(testkit.Rows("40", "70"))
}

func (s *testStatsUpdateSuite) TestRollback(c *C) {
	defer cleanEnv(c, s.store, s.do)
	testKit := testkit.NewTestKit(c, s.store)
	testKit.MustExec("use test")
	testKit.MustExec("create table t (a int, b int)")
	testKit.MustExec("begin")
	testKit.MustExec("insert into t values (1,2)")
	testKit.MustExec("rollback")

	is := s.do.InfoSchema()
	tbl, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
	c.Assert(err, IsNil)
	tableInfo := tbl.Meta()
	h := s.do.StatsHandle()
	h.HandleDDLEvent(<-h.DDLEventCh())
	h.DumpStatsDeltaToKV()
	h.Update(is)

	stats := h.GetTableStats(tableInfo.ID)
	c.Assert(stats.Count, Equals, int64(0))
	c.Assert(stats.ModifyCount, Equals, int64(0))
}

func (s *testStatsUpdateSuite) TestMultiSession(c *C) {
	defer cleanEnv(c, s.store, s.do)
	testKit := testkit.NewTestKit(c, s.store)
	testKit.MustExec("use test")
	testKit.MustExec("create table t1 (c1 int, c2 int)")

	rowCount1 := 10
	for i := 0; i < rowCount1; i++ {
		testKit.MustExec("insert into t1 values(1, 2)")
	}

	testKit1 := testkit.NewTestKit(c, s.store)
	for i := 0; i < rowCount1; i++ {
		testKit1.MustExec("insert into test.t1 values(1, 2)")
	}
	testKit2 := testkit.NewTestKit(c, s.store)
	for i := 0; i < rowCount1; i++ {
		testKit2.MustExec("delete from test.t1 limit 1")
	}
	is := s.do.InfoSchema()
	tbl1, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
	c.Assert(err, IsNil)
	tableInfo1 := tbl1.Meta()
	h := s.do.StatsHandle()

	h.HandleDDLEvent(<-h.DDLEventCh())

	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 := h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(rowCount1))

	for i := 0; i < rowCount1; i++ {
		testKit.MustExec("insert into t1 values(1, 2)")
	}

	for i := 0; i < rowCount1; i++ {
		testKit1.MustExec("insert into test.t1 values(1, 2)")
	}

	for i := 0; i < rowCount1; i++ {
		testKit2.MustExec("delete from test.t1 limit 1")
	}

	testKit.Se.Close()
	testKit2.Se.Close()

	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 = h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(rowCount1*2))
	// The session in testKit is already Closed, set it to nil will create a new session.
	testKit.Se = nil
	rs := testKit.MustQuery("select modify_count from mysql.stats_meta")
	rs.Check(testkit.Rows("60"))
}

func (s *testStatsUpdateSuite) TestTxnWithFailure(c *C) {
	defer cleanEnv(c, s.store, s.do)
	testKit := testkit.NewTestKit(c, s.store)
	testKit.MustExec("use test")
	testKit.MustExec("create table t1 (c1 int primary key, c2 int)")

	is := s.do.InfoSchema()
	tbl1, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
	c.Assert(err, IsNil)
	tableInfo1 := tbl1.Meta()
	h := s.do.StatsHandle()

	h.HandleDDLEvent(<-h.DDLEventCh())

	rowCount1 := 10
	testKit.MustExec("begin")
	for i := 0; i < rowCount1; i++ {
		testKit.MustExec("insert into t1 values(?, 2)", i)
	}
	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 := h.GetTableStats(tableInfo1.ID)
	// have not commit
	c.Assert(stats1.Count, Equals, int64(0))
	testKit.MustExec("commit")

	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 = h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(rowCount1))

	_, err = testKit.Exec("insert into t1 values(0, 2)")
	c.Assert(err, NotNil)

	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 = h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(rowCount1))

	testKit.MustExec("insert into t1 values(-1, 2)")
	h.DumpStatsDeltaToKV()
	h.Update(is)
	stats1 = h.GetTableStats(tableInfo1.ID)
	c.Assert(stats1.Count, Equals, int64(rowCount1+1))
}

func (s *testStatsUpdateSuite) TestAutoUpdate(c *C) {
	defer cleanEnv(c, s.store, s.do)
	testKit := testkit.NewTestKit(c, s.store)
	testKit.MustExec("use test")
	testKit.MustExec("create table t (a int)")

	do := s.do
	is := do.InfoSchema()
	tbl, err := is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
	c.Assert(err, IsNil)
	tableInfo := tbl.Meta()
	h := do.StatsHandle()

	h.HandleDDLEvent(<-h.DDLEventCh())
	h.Update(is)
	stats := h.GetTableStats(tableInfo.ID)
	c.Assert(stats.Count, Equals, int64(0))

	_, err = testKit.Exec("insert into t values (1)")
	c.Assert(err, IsNil)
	h.DumpStatsDeltaToKV()
	h.Update(is)
	err = h.HandleAutoAnalyze(is)
	c.Assert(err, IsNil)
	h.Update(is)
	stats = h.GetTableStats(tableInfo.ID)
	c.Assert(stats.Count, Equals, int64(1))
	c.Assert(stats.ModifyCount, Equals, int64(0))

	_, err = testKit.Exec("insert into t values (1)")
	c.Assert(err, IsNil)
	h.DumpStatsDeltaToKV()
	h.Clear()
	// We set `Lease` here so that `Update` will use load by need strategy.
	h.Lease = time.Second
	h.Update(is)
	h.Lease = 0
	err = h.HandleAutoAnalyze(is)
	c.Assert(err, IsNil)
	h.Update(is)
	stats = h.GetTableStats(tableInfo.ID)
	c.Assert(stats.Count, Equals, int64(2))
	// Modify count is non-zero means that we do not analyze the table.
	c.Assert(stats.ModifyCount, Equals, int64(1))

	_, err = testKit.Exec("create index idx on t(a)")
	c.Assert(err, IsNil)
	is = do.InfoSchema()
	tbl, err = is.TableByName(model.NewCIStr("test"), model.NewCIStr("t"))
	c.Assert(err, IsNil)
	tableInfo = tbl.Meta()
	h.HandleAutoAnalyze(is)
	h.Update(is)
	stats = h.GetTableStats(tableInfo.ID)
	c.Assert(stats.Count, Equals, int64(2))
	c.Assert(stats.ModifyCount, Equals, int64(0))
	hg, ok := stats.Indices[tableInfo.Indices[0].ID]
	c.Assert(ok, IsTrue)
	c.Assert(hg.NDV, Equals, int64(1))
	c.Assert(hg.Len(), Equals, 1)
}

func (s *testStatsUpdateSuite) TestQueryFeedback(c *C) {
	defer cleanEnv(c, s.store, s.do)
	testKit := testkit.NewTestKit(c, s.store)
	testKit.MustExec("use test")
	testKit.MustExec("create table t (a int, b int, primary key(a), index idx(b))")
	testKit.MustExec("insert into t values (1,2),(2,2),(4,5)")
	testKit.MustExec("analyze table t")

	h := s.do.StatsHandle()
	tests := []struct {
		sql    string
		actual int64
	}{
		{
			sql:    "select * from t where t.a <= 1",
			actual: 1,
		},
		{
			sql:    "select * from t use index(idx) where t.b <= 2",
			actual: 2,
		},
		{
			sql:    "select b from t use index(idx) where t.b <= 5",
			actual: 3,
		},
	}
	for _, t := range tests {
		testKit.MustQuery(t.sql)
		h.DumpStatsDeltaToKV()
		feedback := h.GetQueryFeedback()
		c.Assert(len(feedback), Equals, 1)
		c.Assert(feedback[0].Actual(), Equals, t.actual)
	}

	// Feedback from limit executor may not be accurate.
	testKit.MustQuery("select * from t where t.a <= 2 limit 1")
	h.DumpStatsDeltaToKV()
	feedback := h.GetQueryFeedback()
	c.Assert(len(feedback), Equals, 0)
}

redpajama_set_name: RedPajamaGithub


text:
import _        from "underscore";
import $        from "jquery";
import BaseView from "./BaseView";

const CLASS_NAME_EMPTY = 'empty';
const CLASS_NAME_HALF  = 'half';
const CLASS_NAME_FULL  = 'full';

export default class RateView extends BaseView {

	className() { return  'ui-rate'; }

	constructor(options){
		super(options);

		this.setDefaultsOptions({
			min: 1,
			max: 5,
			rate: 0,
			edit: false,
			chars: {
				empty: "",
				half: "",
				full: ""
			}
		});

		this.cache.chars   = {};
		this.options.min   = parseInt( this.options.min );
		this.options.max   = parseInt( this.options.max );
		this.options.rate  = parseFloat( this.options.rate );

		if ( this.options.edit ){
			this.addEvents({
				'click span': 'onClick'
			});
		}
	}

	onRender(rendered){
		const min     = this.options.min;
		const max     = this.options.max;
		const rate    = this.options.rate;
		const prefix  = '$star-';
		let _char     = this.options.chars.empty;
		let cache     = this.cache;
		let chars     = cache.chars;
		let className;

		for (var i = min; i <= max; i++) {
			_char = this.options.chars.empty;
			if ( rate >= i )
				_char = this.options.chars.full;
			else if ( rate < i && rate > (i-1)  ) {
				_char = this.options.chars.half;
			}

			switch (_char) {
				case this.options.chars.empty:
					className = CLASS_NAME_EMPTY;
					break;
				case this.options.chars.half:
					className = CLASS_NAME_HALF;
					break;
				case this.options.chars.full:
					className = CLASS_NAME_FULL;
					break;
			}

			if ( rendered ){
				if ( chars[i] !== _char ){
					cache[prefix+i].attr('class', className).text( _char );
					chars[i] = _char;
				}
			}else{
				cache[prefix+i]   = $('<span />').data("value", i).attr('class', className).text( _char );
				chars[i] = _char;
				this.$el.append( cache[prefix+i] );
			}

		};

		return this;
	}

	update(rate){
		if ( _.isUndefined(rate) || _.isNull(rate) )
			return this;
		this.options.rate = parseFloat(rate);
		this.render();
		return this;
	}

	value() {
		return this.options.rate;
	}

	onClick(ev) {
		let $el = $(ev.currentTarget);
		this.update( $el.data('value') );
	}

};


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.plugin.base.security;

import com.facebook.presto.common.Subfield;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.connector.ConnectorAccessControl;
import com.facebook.presto.spi.connector.ConnectorTransactionHandle;
import com.facebook.presto.spi.security.AccessControlContext;
import com.facebook.presto.spi.security.ConnectorIdentity;
import com.facebook.presto.spi.security.PrestoPrincipal;
import com.facebook.presto.spi.security.Privilege;

import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;

import static java.util.Objects.requireNonNull;

public abstract class ForwardingConnectorAccessControl
        implements ConnectorAccessControl
{
    public static ConnectorAccessControl of(Supplier<ConnectorAccessControl> connectorAccessControlSupplier)
    {
        requireNonNull(connectorAccessControlSupplier, "connectorAccessControlSupplier is null");
        return new ForwardingConnectorAccessControl()
        {
            @Override
            protected ConnectorAccessControl delegate()
            {
                return connectorAccessControlSupplier.get();
            }
        };
    }

    protected abstract ConnectorAccessControl delegate();

    @Override
    public void checkCanCreateSchema(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String schemaName)
    {
        delegate().checkCanCreateSchema(transactionHandle, identity, context, schemaName);
    }

    @Override
    public void checkCanDropSchema(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String schemaName)
    {
        delegate().checkCanDropSchema(transactionHandle, identity, context, schemaName);
    }

    @Override
    public void checkCanRenameSchema(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String schemaName, String newSchemaName)
    {
        delegate().checkCanRenameSchema(transactionHandle, identity, context, schemaName, newSchemaName);
    }

    @Override
    public void checkCanShowSchemas(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context)
    {
        delegate().checkCanShowSchemas(transactionHandle, identity, context);
    }

    @Override
    public Set<String> filterSchemas(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, Set<String> schemaNames)
    {
        return delegate().filterSchemas(transactionHandle, identity, context, schemaNames);
    }

    @Override
    public void checkCanCreateTable(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName)
    {
        delegate().checkCanCreateTable(transactionHandle, identity, context, tableName);
    }

    @Override
    public void checkCanDropTable(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName)
    {
        delegate().checkCanDropTable(transactionHandle, identity, context, tableName);
    }

    @Override
    public void checkCanRenameTable(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName, SchemaTableName newTableName)
    {
        delegate().checkCanRenameTable(transactionHandle, identity, context, tableName, newTableName);
    }

    @Override
    public void checkCanShowTablesMetadata(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String schemaName)
    {
        delegate().checkCanShowTablesMetadata(transactionHandle, identity, context, schemaName);
    }

    @Override
    public Set<SchemaTableName> filterTables(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, Set<SchemaTableName> tableNames)
    {
        return delegate().filterTables(transactionHandle, identity, context, tableNames);
    }

    @Override
    public void checkCanAddColumn(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName)
    {
        delegate().checkCanAddColumn(transactionHandle, identity, context, tableName);
    }

    @Override
    public void checkCanDropColumn(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName)
    {
        delegate().checkCanDropColumn(transactionHandle, identity, context, tableName);
    }

    @Override
    public void checkCanRenameColumn(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName)
    {
        delegate().checkCanRenameColumn(transactionHandle, identity, context, tableName);
    }

    @Override
    public void checkCanSelectFromColumns(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName, Set<Subfield> columnOrSubfieldNames)
    {
        delegate().checkCanSelectFromColumns(transactionHandle, identity, context, tableName, columnOrSubfieldNames);
    }

    @Override
    public void checkCanInsertIntoTable(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName)
    {
        delegate().checkCanInsertIntoTable(transactionHandle, identity, context, tableName);
    }

    @Override
    public void checkCanDeleteFromTable(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName)
    {
        delegate().checkCanDeleteFromTable(transactionHandle, identity, context, tableName);
    }

    @Override
    public void checkCanTruncateTable(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName)
    {
        delegate().checkCanTruncateTable(transactionHandle, identity, context, tableName);
    }

    @Override
    public void checkCanCreateView(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName viewName)
    {
        delegate().checkCanCreateView(transactionHandle, identity, context, viewName);
    }

    @Override
    public void checkCanDropView(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName viewName)
    {
        delegate().checkCanDropView(transactionHandle, identity, context, viewName);
    }

    @Override
    public void checkCanCreateViewWithSelectFromColumns(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, SchemaTableName tableName, Set<String> columnNames)
    {
        delegate().checkCanCreateViewWithSelectFromColumns(transactionHandle, identity, context, tableName, columnNames);
    }

    @Override
    public void checkCanSetCatalogSessionProperty(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String propertyName)
    {
        delegate().checkCanSetCatalogSessionProperty(transactionHandle, identity, context, propertyName);
    }

    @Override
    public void checkCanGrantTablePrivilege(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, Privilege privilege, SchemaTableName tableName, PrestoPrincipal grantee, boolean withGrantOption)
    {
        delegate().checkCanGrantTablePrivilege(transactionHandle, identity, context, privilege, tableName, grantee, withGrantOption);
    }

    @Override
    public void checkCanRevokeTablePrivilege(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, Privilege privilege, SchemaTableName tableName, PrestoPrincipal revokee, boolean grantOptionFor)
    {
        delegate().checkCanGrantTablePrivilege(transactionHandle, identity, context, privilege, tableName, revokee, grantOptionFor);
    }

    @Override
    public void checkCanCreateRole(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String role, Optional<PrestoPrincipal> grantor)
    {
        delegate().checkCanCreateRole(transactionHandle, identity, context, role, grantor);
    }

    @Override
    public void checkCanDropRole(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String role)
    {
        delegate().checkCanDropRole(transactionHandle, identity, context, role);
    }

    @Override
    public void checkCanGrantRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, Set<String> roles, Set<PrestoPrincipal> grantees, boolean withAdminOption, Optional<PrestoPrincipal> grantor, String catalogName)
    {
        delegate().checkCanGrantRoles(transactionHandle, identity, context, roles, grantees, withAdminOption, grantor, catalogName);
    }

    @Override
    public void checkCanRevokeRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, Set<String> roles, Set<PrestoPrincipal> grantees, boolean adminOptionFor, Optional<PrestoPrincipal> grantor, String catalogName)
    {
        delegate().checkCanRevokeRoles(transactionHandle, identity, context, roles, grantees, adminOptionFor, grantor, catalogName);
    }

    @Override
    public void checkCanSetRole(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String role, String catalogName)
    {
        delegate().checkCanSetRole(transactionHandle, identity, context, role, catalogName);
    }

    @Override
    public void checkCanShowRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String catalogName)
    {
        delegate().checkCanShowRoles(transactionHandle, identity, context, catalogName);
    }

    @Override
    public void checkCanShowCurrentRoles(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String catalogName)
    {
        delegate().checkCanShowCurrentRoles(transactionHandle, identity, context, catalogName);
    }

    @Override
    public void checkCanShowRoleGrants(ConnectorTransactionHandle transactionHandle, ConnectorIdentity identity, AccessControlContext context, String catalogName)
    {
        delegate().checkCanShowRoleGrants(transactionHandle, identity, context, catalogName);
    }
}


text:
from sqlalchemy.exc import IntegrityError

from project import db
from project.api.models import User
from project.tests.base import BaseTestCase
from project.tests.utils import add_user

class TestUserModel(BaseTestCase):

    def test_add_user(self):
        user = add_user('justatest', 'test@test.com', 'test')
        self.assertTrue(user.id)
        self.assertEqual(user.username, 'justatest')
        self.assertEqual(user.email, 'test@test.com')
        self.assertTrue(user.password)
        self.assertTrue(user.active)
        self.assertTrue(user.created_at)
        self.assertTrue(user.admin == False)

    def test_encode_auth_token(self):
        user = add_user('justatest', 'test@test.com', 'test')
        auth_token = user.encode_auth_token(user.id)
        self.assertTrue(isinstance(auth_token, bytes))

    def test_decode_auth_token(self):
        user = add_user('justatest', 'test@test.com', 'test')
        auth_token = user.encode_auth_token(user.id)
        self.assertTrue(isinstance(auth_token, bytes))
        self.assertTrue(User.decode_auth_token(auth_token), user.id)

    def test_add_user_duplicate_username(self):
        add_user('justatest', 'test@test.com', 'test')
        duplicate_user = User(
            username='justatest',
            email='test@test2.com',
            password='test'
        )
        db.session.add(duplicate_user)
        self.assertRaises(IntegrityError, db.session.commit)

    def test_add_user_duplicate_email(self):
        add_user('justatest', 'test@test.com', 'test')
        duplicate_user = User(
            username='justatest2',
            email='test@test.com',
            password='test'
        )
        db.session.add(duplicate_user)
        self.assertRaises(IntegrityError, db.session.commit)

    def test_passwords_are_random(self):
        user_one = add_user('justatest', 'test@test.com', 'test')
        user_two = add_user('justatest2', 'test@test2.com', 'test')
        self.assertNotEqual(user_one.password, user_two.password)


text:
package com.jugoterapia.josdem.context;

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

import javax.inject.Qualifier;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ApplicationContext {}


text:
package edu.usu.sdl.spoon.importer;

/**
 *
 * @author dshurtleff
 */
public class AttributeAttachment
{
	private String filename;
	private String fileData;
	private String attributeType;
	private String attributeCode;

	public AttributeAttachment()
	{
	}

	public String getFilename()
	{
		return filename;
	}

	public void setFilename(String filename)
	{
		this.filename = filename;
	}

	public String getFileData()
	{
		return fileData;
	}

	public void setFileData(String fileData)
	{
		this.fileData = fileData;
	}

	public String getAttributeType()
	{
		return attributeType;
	}

	public void setAttributeType(String attributeType)
	{
		this.attributeType = attributeType;
	}

	public String getAttributeCode()
	{
		return attributeCode;
	}

	public void setAttributeCode(String attributeCode)
	{
		this.attributeCode = attributeCode;
	}

}


text:
namespace base {

extern const char kDontUseJobObjectFlag[];

// Callback that runs a test suite and returns exit code.
using RunTestSuiteCallback = OnceCallback<int(void)>;

// Launches unit tests in given test suite. Returns exit code.
int LaunchUnitTests(int argc,
                    char** argv,
                    RunTestSuiteCallback run_test_suite,
                    size_t retry_limit = 1U);

// Same as above, but always runs tests serially.
int LaunchUnitTestsSerially(int argc,
                            char** argv,
                            RunTestSuiteCallback run_test_suite);

// Launches unit tests in given test suite. Returns exit code.
// |parallel_jobs| is the number of parallel test jobs.
// |default_batch_limit| is the default size of test batch
// (use 0 to disable batching).
// |use_job_objects| determines whether to use job objects.
int LaunchUnitTestsWithOptions(int argc,
                               char** argv,
                               size_t parallel_jobs,
                               int default_batch_limit,
                               bool use_job_objects,
                               RunTestSuiteCallback run_test_suite);

#if defined(OS_WIN)
// Launches unit tests in given test suite. Returns exit code.
// |use_job_objects| determines whether to use job objects.
int LaunchUnitTests(int argc,
                    wchar_t** argv,
                    bool use_job_objects,
                    RunTestSuiteCallback run_test_suite);
#endif  // defined(OS_WIN)

// Delegate to abstract away platform differences for unit tests.
class UnitTestPlatformDelegate {
 public:
  // Called to get names of tests available for running. The delegate
  // must put the result in |output| and return true on success.
  virtual bool GetTests(std::vector<TestIdentifier>* output) = 0;

  // Called to create a temporary for storing test results. The delegate
  // must put the resulting path in |path| and return true on success.
  virtual bool CreateResultsFile(const base::FilePath& temp_dir,
                                 base::FilePath* path) = 0;

  // Called to create a new temporary file. The delegate must put the resulting
  // path in |path| and return true on success.
  virtual bool CreateTemporaryFile(const base::FilePath& temp_dir,
                                   base::FilePath* path) = 0;

  // Returns command line for child GTest process based on the command line
  // of current process. |test_names| is a vector of test full names
  // (e.g. "A.B"), |output_file| is path to the GTest XML output file.
  virtual CommandLine GetCommandLineForChildGTestProcess(
      const std::vector<std::string>& test_names,
      const base::FilePath& output_file,
      const base::FilePath& flag_file) = 0;

  // Returns wrapper to use for child GTest process. Empty string means
  // no wrapper.
  virtual std::string GetWrapperForChildGTestProcess() = 0;

 protected:
  ~UnitTestPlatformDelegate() = default;
};

// This default implementation uses gtest_util to get all
// compiled gtests into the binary.
// The delegate will relaunch test in parallel,
// but only use single test per launch.
class DefaultUnitTestPlatformDelegate : public UnitTestPlatformDelegate {
 public:
  DefaultUnitTestPlatformDelegate();

 private:
  // UnitTestPlatformDelegate:

  bool GetTests(std::vector<TestIdentifier>* output) override;

  bool CreateResultsFile(const base::FilePath& temp_dir,
                         base::FilePath* path) override;

  bool CreateTemporaryFile(const base::FilePath& temp_dir,
                           base::FilePath* path) override;

  CommandLine GetCommandLineForChildGTestProcess(
      const std::vector<std::string>& test_names,
      const base::FilePath& output_file,
      const base::FilePath& flag_file) override;

  std::string GetWrapperForChildGTestProcess() override;

  ScopedTempDir temp_dir_;

  DISALLOW_COPY_AND_ASSIGN(DefaultUnitTestPlatformDelegate);
};

// Test launcher delegate for unit tests (mostly to support batching).
class UnitTestLauncherDelegate : public TestLauncherDelegate {
 public:
  UnitTestLauncherDelegate(UnitTestPlatformDelegate* delegate,
                           size_t batch_limit,
                           bool use_job_objects);
  ~UnitTestLauncherDelegate() override;

 private:
  // TestLauncherDelegate:
  bool GetTests(std::vector<TestIdentifier>* output) override;

  CommandLine GetCommandLine(const std::vector<std::string>& test_names,
                             const FilePath& temp_dir,
                             FilePath* output_file) override;

  std::string GetWrapper() override;

  int GetLaunchOptions() override;

  TimeDelta GetTimeout() override;

  size_t GetBatchSize() override;

  ThreadChecker thread_checker_;

  UnitTestPlatformDelegate* platform_delegate_;

  // Maximum number of tests to run in a single batch.
  size_t batch_limit_;

  // Determines whether we use job objects on Windows.
  bool use_job_objects_;

  DISALLOW_COPY_AND_ASSIGN(UnitTestLauncherDelegate);
};

}   // namespace base

#endif  // BASE_TEST_LAUNCHER_UNIT_TEST_LAUNCHER_H_


text:
using System;
using System.Linq.Expressions;
using TITcs.SharePoint.Query.LinqProvider.Clauses.Expressions;
using TITcs.SharePoint.Query.LinqProvider.Parsing.Structure;
using TITcs.SharePoint.Query.LinqProvider.Parsing.Structure.ExpressionTreeProcessors;
using TITcs.SharePoint.Query.SharedSource.Utilities;

namespace TITcs.SharePoint.Query.LinqProvider.Parsing.ExpressionTreeVisitors
{
  /// <summary>
  /// Preprocesses an expression tree for parsing. The preprocessing involves detection of sub-queries and VB-specific expressions.
  /// </summary>
  public class SubQueryFindingExpressionTreeVisitor : ExpressionTreeVisitor
  {
    public static Expression Process (Expression expressionTree, INodeTypeProvider nodeTypeProvider)
    {
      ArgumentUtility.CheckNotNull ("expressionTree", expressionTree);
      ArgumentUtility.CheckNotNull ("nodeTypeProvider", nodeTypeProvider);

      var visitor = new SubQueryFindingExpressionTreeVisitor (nodeTypeProvider);
      return visitor.VisitExpression (expressionTree);
    }

    private readonly INodeTypeProvider _nodeTypeProvider;
    private readonly ExpressionTreeParser _expressionTreeParser;
    private readonly QueryParser _queryParser;

    private SubQueryFindingExpressionTreeVisitor (INodeTypeProvider nodeTypeProvider)
    {
      ArgumentUtility.CheckNotNull ("nodeTypeProvider", nodeTypeProvider);

      _nodeTypeProvider = nodeTypeProvider;
      _expressionTreeParser = new ExpressionTreeParser (_nodeTypeProvider, new NullExpressionTreeProcessor());
      _queryParser = new QueryParser (_expressionTreeParser);
    }

    public override Expression VisitExpression (Expression expression)
    {
      var potentialQueryOperatorExpression = _expressionTreeParser.GetQueryOperatorExpression (expression);
      if (potentialQueryOperatorExpression != null && _nodeTypeProvider.IsRegistered (potentialQueryOperatorExpression.Method))
        return CreateSubQueryNode (potentialQueryOperatorExpression);
      else
        return base.VisitExpression (expression);
    }

    protected internal override Expression VisitUnknownNonExtensionExpression (Expression expression)
    {
      //ignore
      return expression;
    }

    private SubQueryExpression CreateSubQueryNode (MethodCallExpression methodCallExpression)
    {
      QueryModel queryModel = _queryParser.GetParsedQuery (methodCallExpression);
      return new SubQueryExpression (queryModel);
    }
  }
}


text:
<?php

namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Zend\Validator\File\Size;
use Zend\Session\Storage\SessionStorage;
use Zend\Session\SessionManager;

use Admin\Model\OtherServicesModel;
use Admin\Model\OtherServicesTable;

class OtherServicesController extends AbstractActionController
{
    protected $otherServicesTable;

    public function getOtherServicesTable()
    {
        if(!$this->otherServicesTable)
        {
            $sm= $this->getServiceLocator();
            $this->otherServicesTable = $sm->get('Admin\Model\otherServicesTable');
        }
        return $this->otherServicesTable;
    }
    //Actions
    public function indexAction()
    {
        $this->layout('layout/adminDashboardLayout');
        return new ViewModel(array(

                ));
    }

    public function ajaxListAction(){

        $viewModel = new ViewModel(array(
            'listAllMenuData' => $this->getOtherServicesTable()->listAllOtherServices(),
            'flashMessages' => $this->flashMessenger()->getMessages()

        ));

        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function addAction()
    {
        $config=$this->getServiceLocator()->get('config');
        $this->layout('layout/adminDashboardLayout');
        $request=$this->getRequest();
	$upload = $this->UploadFilesLib();
          $this->flashMessenger()->addMessage('');
        if($request->isPost())
        {
            //exit('ok');
            $otherServicesData = new OtherServicesModel();
            $path=$config['defaultValues']['upload_path'];
            if(isset($_FILES['field']['name'][0]) && !empty($_FILES['field']['name'][0])){
                        $file= $_FILES['field']['name'];
                        $serviceImg = $upload->getRandFileNa($file);
                        $upload->copyFile('field',$path.'/images/products/other_service', 1, $serviceImg);
            }
            //Current User Id from Session
	    $title=stripslashes($request->getPost("service_title"));
            $desc=stripslashes($request->getPost("service_description"));
            $otherServicesData->setServiceTitle($title);
            $otherServicesData->setServiceLink($request->getPost("service_link"));
            $otherServicesData->setServiceDescription($desc);
            $otherServicesData->setServicePrice($request->getPost("service_price"));
            $otherServicesData->setServiceImage($serviceImg);
            $lastId = $this->getOtherServicesTable()->saveOtherServices($otherServicesData);
            $this->flashMessenger()->addMessage('Data Inserted Successfully');
            return $this->redirect()->toRoute('admin/otherservices/add');
        }

        return new ViewModel(array(
            'flashMessages' => $this->flashMessenger()->getMessages(),
        ));

    }

    public function editAction()
    {
        $id=(int) $this->params()->fromRoute('id');
        $this->layout('layout/adminDashboardLayout');
        $request=$this->getRequest();
        $config=$this->getServiceLocator()->get('config');
	$upload = $this->UploadFilesLib();
          $this->flashMessenger()->addMessage('');
          $service=$this->getOtherServicesTable()->singleOtherServicesrow($id);

        if($request->isPost())
        {
            //exit('ok');
            $otherServicesData = new OtherServicesModel();
            $otherServicesData->setId($id);
            $path=$config['defaultValues']['upload_path'];
            if(isset($_FILES['field']['name'][0]) && !empty($_FILES['field']['name'][0])){

                foreach($service as $ser){
                    unlink($path.'/images/products/other_service/'.$ser['service_image']);
                }
                $file= $_FILES['field']['name'];
                $serviceImg = $upload->getRandFileNa($file);
                $upload->copyFile('field',$path.'/images/products/other_service', 1, $serviceImg);
                $otherServicesData->setServiceImage($serviceImg);
            }
            //Current User Id from Session
          	$title=stripslashes($request->getPost("service_title"));
                $desc=stripslashes($request->getPost("service_description"));
            $otherServicesData->setServiceTitle($title);
            $otherServicesData->setServiceLink($request->getPost("service_link"));
            $otherServicesData->setServiceDescription($desc);
            $otherServicesData->setServicePrice($request->getPost("service_price"));

            $lastId = $this->getOtherServicesTable()->updateOtherServices($otherServicesData);
            $this->flashMessenger()->addMessage('Data Inserted Successfully');
            return $this->redirect()->toRoute('admin/otherservices');
        }

        return new ViewModel(array(
            'otherService'  =>$service,
            'flashMessages' => $this->flashMessenger()->getMessages(),
        ));

    }

    public function editTitleAction()
    {
        //$id=(int) $this->params()->fromRoute('id');
        $this->layout('layout/adminDashboardLayout');
        $request=$this->getRequest();
	          $this->flashMessenger()->addMessage('');
        $otherServiceTitle=$this->getOtherServicesTable()->listOtherServicesTitle();

        if($request->isPost())
        {
            //exit('ok');
             foreach($otherServiceTitle as $title){
                  $id = $title['id'];}
            $otherServicesTitle = new OtherServicesModel();
            $otherServicesTitle->setId($id);
            $otherServicesTitle->setServiceTitle($request->getPost("service_title"));
            $otherServicesTitle->setServiceDescription($request->getPost("service_description"));
            $lastId = $this->getOtherServicesTable()->updateOtherServices($otherServicesTitle);
            $this->flashMessenger()->addMessage('Title Updated Successfully');
            return $this->redirect()->toRoute('admin/otherservices/edittitle');
        }

        return new ViewModel(array(
            'otherService'  => $otherServiceTitle,
            'flashMessages' => $this->flashMessenger()->getMessages(),
        ));

    }

    public function deleteAction(){
        //$delId = (int) $this->params()->fromRoute('id');
        $config=$this->getServiceLocator()->get('config');
        $delId = $this->getRequest()->getPost('delId');
        $res=$this->getOtherServicesTable()->singleOtherServicesrow($delId);
        $path=$config['defaultValues']['upload_path'];
        foreach($res as $rs){
            unlink($path.'/images/products/other_service/'.$rs['service_image']);
        }

          $this->getOtherServicesTable()->deleteOtherServices($delId);
        exit;

    }

}


text:
<?php

return [
    'This category was added' => 'Категория была добавлена',
    'Add category' => 'Добавить категорию',
    'Categories' => 'Категории',
    'Edit category' => 'Редактировать категорию',
    'Category was updated' => 'Категория была обновлена',
    'This category was removed' => 'Категория была удалена',
];


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.percolate.coffee.activity.CoffeeTypeDetailedViewAcitivity">

    <item
        android:id="@+id/action_share"
        android:showAsAction="ifRoom"
        android:title="@string/action_share"/>

</menu>


text:
import os
import sys
from django.utils.translation import ugettext_lazy as _

PROJECT_ROOT = os.path.abspath(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))

if 'test' in sys.argv:
    DATABASES['default'] = {  # noqa
        'ENGINE': 'django.db.backends.sqlite3'
    }
    SOUTH_TESTS_MIGRATE = False

SOUTH_MIGRATION_MODULES = {
    'taggit': 'taggit.south_migrations',
    'djangocms_text_ckeditor': 'djangocms_text_ckeditor.migrations',
}

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Europe/Berlin'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-US'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.abspath(os.path.join(PROJECT_ROOT, 'media'))

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/media/'

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = os.path.abspath(os.path.join(PROJECT_ROOT, 'static-collected'))

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    #os.path.join(PROJECT_ROOT, 'static'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.doc.XViewMiddleware',
    'django.middleware.common.CommonMiddleware',
    'cms.middleware.page.CurrentPageMiddleware',
    'cms.middleware.user.CurrentUserMiddleware',
    'cms.middleware.toolbar.ToolbarMiddleware',
    'cms.middleware.language.LanguageCookieMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = [
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.i18n',
    'django.core.context_processors.request',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'cosinnus.utils.context_processors.settings',
    'cosinnus.utils.context_processors.cosinnus',
    'cms.context_processors.media',
    'sekizai.context_processors.sekizai',
    'postman.context_processors.inbox',
    'django_settings_export.settings_export',
]

THUMBNAIL_PROCESSORS = (
    'easy_thumbnails.processors.colorspace',
    #'easy_thumbnails.processors.autocrop',
    #'easy_thumbnails.processors.scale_and_crop',
    'filer.thumbnail_processors.scale_and_crop_with_subject_location',
    'easy_thumbnails.processors.filters',
)
THUMBNAIL_ALIASES = {
    '': {
        'avatar_large': {'size': (200, 200), 'crop': True, 'upscale': True },
        'avatar_medium': {'size': (64, 64), 'crop': True, 'upscale': True },
        'avatar_small': {'size': (32, 32), 'crop': True, 'upscale': True },
        'bus_medium': {'size': (265, 200), 'crop': True, 'upscale': True },
        'bus_large': {'size': (600, 300), 'crop': True, 'upscale': True },
        'event': {'size': (70, 70), 'crop': True, 'upscale': True },
        'note_large': {'size': (1140, 400), 'crop': True, 'upscale': True },
        'note_medium': {'size': (350, 232), 'crop': True, 'upscale': True },
        'note_small': {'size': (175, 125), 'crop': True, 'upscale': True },
        'slideshow': {'size': (1920, 700), 'crop': True, 'upscale': True },
        'blogpost': {'size': (1920, 1080), 'crop': True, 'upscale': True },
        'community_map': {'size': (300, 120), 'crop': True, 'upscale': True },
        'community_list': {'size': (220, 120), 'crop': True, 'upscale': True },
    },
}

ROOT_URLCONF = 'ecobasa.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'ecobasa.wsgi.application'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'django.template.loaders.eggs.Loader',
)

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates"
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_ROOT, "templates"),
)

CMS_TEMPLATES = (
    ('start.html', 'Startpage'),
    ('ecobasa/about.html', 'About'),
    ('ecobasa/blog.html', 'Blog'),
    ('ecobasa/tour_blog.html', 'Tour Blog'),
    ('ecobasa/support.html', 'Support'),
)

LANGUAGES = (
    ('en', _('English')),
    ('de', _('German')),
    ('es', _('Spanish')),
    #('fr', _('French')),
    #('hu', _('Hungarian')),
)

INSTALLED_APPS = (
    # Django Apps
    'suit',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.humanize',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.webdesign',

    # 'django_extensions',
    'django_select2',
    'widget_tweaks',

    # custom apps
    'ecobasa',
    'cosinnus',
    'cosinnus_message',
    'cosinnus_todo',
    'cosinnus_etherpad',
    'cosinnus_event',
    'cosinnus_note',
    # 'skillshare',
    # 'references',

    # third-party
    'osm_field',
    'appconf',
    'bootstrap3',
    'bootstrap3_datetime',
    'easy_thumbnails',
    'geoposition',
    'south',
    'taggit',
    'filer',
    'haystack',
    'honeypot',
    'postman',
    'embed_video',
    'contact_form',
    'django_extensions',

    # CMS
    'cms',
    'djangocms_text_ckeditor',
    'mptt',
    'menus',
    'cms.plugins.link',
    'sekizai',
    'cmsplugin_filer_folder',
    'cmsplugin_filer_file',
    'cmsplugin_filer_image',
    'cmsplugin_filer_teaser',
    'cmsplugin_filer_video',

    # userprofiles
    'userprofiles',
    'userprofiles.contrib.accountverification',
    #'userprofiles.contrib.emailverification',
    #'userprofiles.contrib.profiles',

)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

AUTHENTICATION_BACKENDS = {

   'django.contrib.auth.backends.ModelBackend',

}

# userprofile settings
USERPROFILES_CHECK_UNIQUE_EMAIL = True
USERPROFILES_DOUBLE_CHECK_EMAIL = False
USERPROFILES_DOUBLE_CHECK_PASSWORD = True
USERPROFILES_REGISTRATION_FULLNAME = True
# irrelevant settings, since we override the view
USERPROFILES_REGISTRATION_FORM = 'ecobasa.forms.RegistrationMemberForm'

USERPROFILES_USE_ACCOUNT_VERIFICATION = False
USERPROFILES_ACCOUNT_VERIFICATION_DAYS = 7

USERPROFILES_USE_PROFILE = False
USERPROFILES_INLINE_PROFILE_ADMIN = False
#USERPROFILES_PROFILE_FORM = 'ecobasa.forms.EcobasaProfileForm'

USERPROFILES_USE_EMAIL_VERIFICATION = False
#USERPROFILES_EMAIL_VERIFICATION_DAYS = 2
#USERPROFILES_EMAIL_VERIFICATION_DONE_URL = 'userprofiles_profile_change'
USERPROFILES_AUTO_LOGIN = True

# from django.core.urlresolvers import reverse
# LOGIN_URL = reverse('home')
LOGIN_REDIRECT_URL = '/profile/dashboard/'

# COSINNUS settings
FORMAT_MODULE_PATH = 'cosinnus.formats'

COSINNUS_ATTACHABLE_OBJECTS = {
#    'cosinnus_event.Event' : [
#        'cosinnus_todo.TodoEntry',
#    ],
}

COSINNUS_USER_PROFILE_MODEL = 'ecobasa.EcobasaUserProfile'
COSINNUS_USER_PROFILE_SERIALIZER = 'ecobasa.models.serializers.EcobasaUserProfileSerializer'

# etherpad
COSINNUS_ETHERPAD_BASE_URL = 'https://pad.ecobasa.org/api'
COSINNUS_ETHERPAD_API_KEY = '30e6027d19afd4bbdbea69b1370c55552505e8f8d2edf4eb60f7e49fc1e48f04'

# hide apps from automatic listing
COSINNUS_HIDE_APPS = ('cosinnus_message',)

#INTERNAL_IPS = ('127.0.0.1', '::1', 'localhost',)

CKEDITOR_UPLOAD_PATH = "uploads/"

CKEDITOR_SETTINGS = {
    'language': '{{ language }}',
    'width': '100%',
    'toolbar_HTMLField': [
        ['Undo', 'Redo'],
        ['ShowBlocks'],
        ['Format', 'Styles'],
    ],
    'skin': 'moono',
}

# Search
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': os.path.join(PROJECT_ROOT, 'whoosh_index'),
    }
}
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 20
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

# honeypot
HONEYPOT_FIELD_NAME = 'Username'

# select2
AUTO_RENDER_SELECT2_STATICS = True

# postman configuration for cosinnus-message
POSTMAN_DISALLOW_ANONYMOUS = True  # No anonymous messaging
POSTMAN_AUTO_MODERATE_AS = True  # Auto accept all messages
POSTMAN_SHOW_USER_AS = 'username'

# Override django-bootstrap's default jquery version
BOOTSTRAP3 = {
    'jquery_url': '//code.jquery.com/jquery-2.1.0.min.js',
}

# special group for the platform itself (For the teammembers and Internal Blog)
# override in your local settings.py
ECOBASA_GROUP = 1

# special group all pioneers are member of and whose posts are exposed
# override in your local settings.py
ECOBASA_SPECIAL_COSINNUS_GROUP = 8

# special group all community ambassadors are member of
# override in your local settings.py
ECOBASA_COMMUNITY_GROUP = 90

# used on about page for the tour progress bar
# can't create timezone-aware datetimes here, hence the tuple
ECOBASA_TOUR_START = (2014, 7, 7)
ECOBASA_TOUR_END = (2014, 8, 26)

#SSL
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600
SECURE_HSTS_INCLUDE_SUBDOMAINS = True

GEOPOSITION_GOOGLE_MAPS_API_KEY = 'AIzaSyB2_6y4Jr7VPT3U4nUz3bf6YA7ef3YijHM'

SETTINGS_EXPORT = [
    'ECOBASA_SPECIAL_COSINNUS_GROUP',
    'ECOBASA_COMMUNITY_GROUP',
]


text:
<?php
/**
 * Stripe Payment Request API
 *
 * @package WooCommerce_Stripe/Classes/Payment_Request
 * @since   4.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * WC_Stripe_Payment_Request class.
 */
class WC_Stripe_Payment_Request {
	/**
	 * Enabled.
	 *
	 * @var
	 */
	public $stripe_settings;

	/**
	 * Stripe Checkout enabled.
	 *
	 * @var
	 */
	public $stripe_checkout_enabled;

	/**
	 * Total label
	 *
	 * @var
	 */
	public $total_label;

	/**
	 * Key
	 *
	 * @var
	 */
	public $publishable_key;

	/**
	 * Key
	 *
	 * @var
	 */
	public $secret_key;

	/**
	 * Is test mode active?
	 *
	 * @var bool
	 */
	public $testmode;

	/**
	 * This Instance.
	 *
	 * @var
	 */
	private static $_this;

	/**
	 * Initialize class actions.
	 *
	 * @since 3.0.0
	 * @version 4.0.0
	 */
	public function __construct() {
		self::$_this                   = $this;
		$this->stripe_settings         = get_option( 'woocommerce_stripe_settings', array() );
		$this->testmode                = ( ! empty( $this->stripe_settings['testmode'] ) && 'yes' === $this->stripe_settings['testmode'] ) ? true : false;
		$this->publishable_key         = ! empty( $this->stripe_settings['publishable_key'] ) ? $this->stripe_settings['publishable_key'] : '';
		$this->secret_key              = ! empty( $this->stripe_settings['secret_key'] ) ? $this->stripe_settings['secret_key'] : '';
		$this->stripe_checkout_enabled = isset( $this->stripe_settings['stripe_checkout'] ) && 'yes' === $this->stripe_settings['stripe_checkout'];
		$this->total_label             = ! empty( $this->stripe_settings['statement_descriptor'] ) ? WC_Stripe_Helper::clean_statement_descriptor( $this->stripe_settings['statement_descriptor'] ) : '';

		if ( $this->testmode ) {
			$this->publishable_key = ! empty( $this->stripe_settings['test_publishable_key'] ) ? $this->stripe_settings['test_publishable_key'] : '';
			$this->secret_key      = ! empty( $this->stripe_settings['test_secret_key'] ) ? $this->stripe_settings['test_secret_key'] : '';
		}

		$this->total_label = str_replace( "'", '', $this->total_label ) . apply_filters( 'wc_stripe_payment_request_total_label_suffix', ' (via WooCommerce)' );

		// Checks if Stripe Gateway is enabled.
		if ( empty( $this->stripe_settings ) || ( isset( $this->stripe_settings['enabled'] ) && 'yes' !== $this->stripe_settings['enabled'] ) ) {
			return;
		}

		// Checks if Payment Request is enabled.
		if ( ! isset( $this->stripe_settings['payment_request'] ) || 'yes' !== $this->stripe_settings['payment_request'] ) {
			return;
		}

		// Don't load for change payment method page.
		if ( isset( $_GET['change_payment_method'] ) ) {
			return;
		}

		$wc_default_country = substr( get_option( 'woocommerce_default_country' ), 0, 2 );

		if ( ! in_array( $wc_default_country, $this->get_stripe_supported_countries() ) ) {
			return;
		}

		add_action( 'template_redirect', array( $this, 'set_session' ) );
		$this->init();
	}

	/**
	 * List of supported countries by Stripe.
	 *
	 * @since 4.1.3
	 * @return array The list of countries.
	 */
	public function get_stripe_supported_countries() {
		return apply_filters( 'wc_stripe_supported_countries', array( 'AT', 'AU', 'BE', 'BR', 'CA', 'CH', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GB', 'HK', 'IE', 'IN', 'IT', 'JP', 'LT', 'LU', 'LV', 'MX', 'NL', 'NZ', 'NO', 'PH', 'PL', 'PT', 'RO', 'SE', 'SG', 'SK', 'US' ) );
	}

	/**
	 * Checks if keys are set.
	 *
	 * @since 4.0.6
	 * @return bool
	 */
	public function are_keys_set() {
		if ( empty( $this->secret_key ) || empty( $this->publishable_key ) ) {
			return false;
		}

		return true;
	}

	/**
	 * Get this instance.
	 *
	 * @since 4.0.6
	 * @return class
	 */
	public static function instance() {
		return self::$_this;
	}

	/**
	 * Sets the WC customer session if one is not set.
	 * This is needed so nonces can be verified by AJAX Request.
	 *
	 * @since 4.0.0
	 */
	public function set_session() {
		if ( ! is_product() || ( isset( WC()->session ) && WC()->session->has_session() ) ) {
			return;
		}

		$session_class = apply_filters( 'woocommerce_session_handler', 'WC_Session_Handler' );
		$wc_session    = new $session_class();

		if ( version_compare( WC_VERSION, '3.3', '>=' ) ) {
			$wc_session->init();
		}

		$wc_session->set_customer_session_cookie( true );
	}

	/**
	 * Initialize hooks.
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 */
	public function init() {
		add_action( 'wp_enqueue_scripts', array( $this, 'scripts' ) );

		/*
		 * In order to display the Payment Request button in the correct position,
		 * a new hook was added to WooCommerce 3.0. In older versions of WooCommerce,
		 * CSS is used to position the button.
		 */
		if ( WC_Stripe_Helper::is_pre_30() ) {
			add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'display_payment_request_button_html' ), 1 );
			add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'display_payment_request_button_separator_html' ), 2 );
		} else {
			add_action( 'woocommerce_after_add_to_cart_quantity', array( $this, 'display_payment_request_button_html' ), 1 );
			add_action( 'woocommerce_after_add_to_cart_quantity', array( $this, 'display_payment_request_button_separator_html' ), 2 );
		}

		add_action( 'woocommerce_proceed_to_checkout', array( $this, 'display_payment_request_button_html' ), 1 );
		add_action( 'woocommerce_proceed_to_checkout', array( $this, 'display_payment_request_button_separator_html' ), 2 );

		add_action( 'woocommerce_checkout_before_customer_details', array( $this, 'display_payment_request_button_html' ), 1 );
		add_action( 'woocommerce_checkout_before_customer_details', array( $this, 'display_payment_request_button_separator_html' ), 2 );

		add_action( 'wc_ajax_wc_stripe_get_cart_details', array( $this, 'ajax_get_cart_details' ) );
		add_action( 'wc_ajax_wc_stripe_get_shipping_options', array( $this, 'ajax_get_shipping_options' ) );
		add_action( 'wc_ajax_wc_stripe_update_shipping_method', array( $this, 'ajax_update_shipping_method' ) );
		add_action( 'wc_ajax_wc_stripe_create_order', array( $this, 'ajax_create_order' ) );
		add_action( 'wc_ajax_wc_stripe_add_to_cart', array( $this, 'ajax_add_to_cart' ) );
		add_action( 'wc_ajax_wc_stripe_get_selected_product_data', array( $this, 'ajax_get_selected_product_data' ) );
		add_action( 'wc_ajax_wc_stripe_clear_cart', array( $this, 'ajax_clear_cart' ) );
		add_action( 'wc_ajax_wc_stripe_log_errors', array( $this, 'ajax_log_errors' ) );

		add_filter( 'woocommerce_gateway_title', array( $this, 'filter_gateway_title' ), 10, 2 );
		add_filter( 'woocommerce_validate_postcode', array( $this, 'postal_code_validation' ), 10, 3 );

		add_action( 'woocommerce_checkout_order_processed', array( $this, 'add_order_meta' ), 10, 2 );
	}

	/**
	 * Gets the button type.
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 * @return string
	 */
	public function get_button_type() {
		return isset( $this->stripe_settings['payment_request_button_type'] ) ? $this->stripe_settings['payment_request_button_type'] : 'default';
	}

	/**
	 * Gets the button theme.
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 * @return string
	 */
	public function get_button_theme() {
		return isset( $this->stripe_settings['payment_request_button_theme'] ) ? $this->stripe_settings['payment_request_button_theme'] : 'dark';
	}

	/**
	 * Gets the button height.
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 * @return string
	 */
	public function get_button_height() {
		return isset( $this->stripe_settings['payment_request_button_height'] ) ? str_replace( 'px', '', $this->stripe_settings['payment_request_button_height'] ) : '64';
	}

	/**
	 * Gets the product data for the currently viewed page
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 */
	public function get_product_data() {
		if ( ! is_product() ) {
			return false;
		}

		global $post;

		$product = wc_get_product( $post->ID );

		$data  = array();
		$items = array();

		$items[] = array(
			'label'  => WC_Stripe_Helper::is_pre_30() ? $product->name : $product->get_name(),
			'amount' => WC_Stripe_Helper::get_stripe_amount( WC_Stripe_Helper::is_pre_30() ? $product->price : $product->get_price() ),
		);

		if ( wc_tax_enabled() ) {
			$items[] = array(
				'label'   => __( 'Tax', 'woocommerce-gateway-stripe' ),
				'amount'  => 0,
				'pending' => true,
			);
		}

		if ( wc_shipping_enabled() && $product->needs_shipping() ) {
			$items[] = array(
				'label'   => __( 'Shipping', 'woocommerce-gateway-stripe' ),
				'amount'  => 0,
				'pending' => true,
			);

			$data['shippingOptions']  = array(
				'id'     => 'pending',
				'label'  => __( 'Pending', 'woocommerce-gateway-stripe' ),
				'detail' => '',
				'amount' => 0,
			);
		}

		$data['displayItems'] = $items;
		$data['total'] = array(
			'label'   => apply_filters( 'wc_stripe_payment_request_total_label', $this->total_label ),
			'amount'  => WC_Stripe_Helper::get_stripe_amount( WC_Stripe_Helper::is_pre_30() ? $product->price : $product->get_price() ),
			'pending' => true,
		);

		$data['requestShipping'] = ( wc_shipping_enabled() && $product->needs_shipping() );
		$data['currency']        = strtolower( get_woocommerce_currency() );
		$data['country_code']    = substr( get_option( 'woocommerce_default_country' ), 0, 2 );

		return apply_filters( 'wc_stripe_payment_request_product_data', $data, $product );
	}

	/**
	 * Filters the gateway title to reflect Payment Request type
	 *
	 */
	public function filter_gateway_title( $title, $id ) {
		global $post;

		if ( ! is_object( $post ) ) {
			return $title;
		}

		if ( WC_Stripe_Helper::is_pre_30() ) {
			$method_title = get_post_meta( $post->ID, '_payment_method_title', true );
		} else {
			$order        = wc_get_order( $post->ID );
			$method_title = is_object( $order ) ? $order->get_payment_method_title() : '';
		}

		if ( 'stripe' === $id && ! empty( $method_title ) && 'Apple Pay (Stripe)' === $method_title ) {
			return $method_title;
		}

		if ( 'stripe' === $id && ! empty( $method_title ) && 'Chrome Payment Request (Stripe)' === $method_title ) {
			return $method_title;
		}

		return $title;
	}

	/**
	 * Removes postal code validation from WC.
	 *
	 * @since 3.1.4
	 * @version 4.0.0
	 */
	public function postal_code_validation( $valid, $postcode, $country ) {
		$gateways = WC()->payment_gateways->get_available_payment_gateways();

		if ( ! isset( $gateways['stripe'] ) ) {
			return $valid;
		}

		$payment_request_type = isset( $_POST['payment_request_type'] ) ? wc_clean( $_POST['payment_request_type'] ) : '';

		if ( 'apple_pay' !== $payment_request_type ) {
			return $valid;
		}

		/**
		 * Currently Apple Pay truncates postal codes from UK and Canada to first 3 characters
		 * when passing it back from the shippingcontactselected object. This causes WC to invalidate
		 * the order and not let it go through. The remedy for now is just to remove this validation.
		 * Note that this only works with shipping providers that don't validate full postal codes.
		 */
		if ( 'GB' === $country || 'CA' === $country ) {
			return true;
		}

		return $valid;
	}

	/**
	 * Add needed order meta
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 * @param int $order_id
	 * @param array $posted_data The posted data from checkout form.
	 */
	public function add_order_meta( $order_id, $posted_data ) {
		if ( empty( $_POST['payment_request_type'] ) ) {
			return;
		}

		$order = wc_get_order( $order_id );

		$payment_request_type = wc_clean( $_POST['payment_request_type'] );

		if ( 'apple_pay' === $payment_request_type ) {
			if ( WC_Stripe_Helper::is_pre_30() ) {
				update_post_meta( $order_id, '_payment_method_title', 'Apple Pay (Stripe)' );
			} else {
				$order->set_payment_method_title( 'Apple Pay (Stripe)' );
				$order->save();
			}
		}

		if ( 'payment_request_api' === $payment_request_type ) {
			if ( WC_Stripe_Helper::is_pre_30() ) {
				update_post_meta( $order_id, '_payment_method_title', 'Chrome Payment Request (Stripe)' );
			} else {
				$order->set_payment_method_title( 'Chrome Payment Request (Stripe)' );
				$order->save();
			}
		}
	}

	/**
	 * Checks to make sure product type is supported.
	 *
	 * @since 3.1.0
	 * @version 4.0.0
	 * @return array
	 */
	public function supported_product_types() {
		return apply_filters( 'wc_stripe_payment_request_supported_types', array(
			'simple',
			'variable',
			'variation',
			'subscription',
			'booking',
			'bundle',
			'composite',
			'mix-and-match',
		) );
	}

	/**
	 * Checks the cart to see if all items are allowed to used.
	 *
	 * @since 3.1.4
	 * @version 4.0.0
	 * @return bool
	 */
	public function allowed_items_in_cart() {
		foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
			$_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );

			if ( ! in_array( ( WC_Stripe_Helper::is_pre_30() ? $_product->product_type : $_product->get_type() ), $this->supported_product_types() ) ) {
				return false;
			}

			// Pre Orders compatbility where we don't support charge upon release.
			if ( class_exists( 'WC_Pre_Orders_Order' ) && WC_Pre_Orders_Cart::cart_contains_pre_order() && WC_Pre_Orders_Product::product_is_charged_upon_release( WC_Pre_Orders_Cart::get_pre_order_product() ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Load public scripts and styles.
	 *
	 * @since 3.1.0
	 * @version 4.0.0
	 */
	public function scripts() {
		// If keys are not set bail.
		if ( ! $this->are_keys_set() ) {
			WC_Stripe_Logger::log( 'Keys are not set correctly.' );
			return;
		}

		// If no SSL bail.
		if ( ! $this->testmode && ! is_ssl() ) {
			WC_Stripe_Logger::log( 'Stripe Payment Request live mode requires SSL.' );
			return;
		}

		if ( ! is_product() && ! is_cart() && ! is_checkout() && ! isset( $_GET['pay_for_order'] ) ) {
			return;
		}

		if ( is_product() ) {
			global $post;

			$product = wc_get_product( $post->ID );

			if ( ! is_object( $product ) || ! in_array( ( WC_Stripe_Helper::is_pre_30() ? $product->product_type : $product->get_type() ), $this->supported_product_types() ) ) {
				return;
			}

			if ( apply_filters( 'wc_stripe_hide_payment_request_on_product_page', false, $post ) ) {
				return;
			}
		}

		$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';

		wp_register_script( 'stripe', 'https://js.stripe.com/v3/', '', '3.0', true );
		wp_register_script( 'wc_stripe_payment_request', plugins_url( 'assets/js/stripe-payment-request' . $suffix . '.js', WC_STRIPE_MAIN_FILE ), array( 'jquery', 'stripe' ), WC_STRIPE_VERSION, true );

		wp_localize_script(
			'wc_stripe_payment_request',
			'wc_stripe_payment_request_params',
			array(
				'ajax_url' => WC_AJAX::get_endpoint( '%%endpoint%%' ),
				'stripe'   => array(
					'key'                => $this->publishable_key,
					'allow_prepaid_card' => apply_filters( 'wc_stripe_allow_prepaid_card', true ) ? 'yes' : 'no',
				),
				'nonce'    => array(
					'payment'                        => wp_create_nonce( 'wc-stripe-payment-request' ),
					'shipping'                       => wp_create_nonce( 'wc-stripe-payment-request-shipping' ),
					'update_shipping'                => wp_create_nonce( 'wc-stripe-update-shipping-method' ),
					'checkout'                       => wp_create_nonce( 'woocommerce-process_checkout' ),
					'add_to_cart'                    => wp_create_nonce( 'wc-stripe-add-to-cart' ),
					'get_selected_product_data'      => wp_create_nonce( 'wc-stripe-get-selected-product-data' ),
					'log_errors'                     => wp_create_nonce( 'wc-stripe-log-errors' ),
					'clear_cart'                     => wp_create_nonce( 'wc-stripe-clear-cart' ),
				),
				'i18n'     => array(
					'no_prepaid_card'  => __( 'Sorry, we\'re not accepting prepaid cards at this time.', 'woocommerce-gateway-stripe' ),
					/* translators: Do not translate the [option] placeholder */
					'unknown_shipping' => __( 'Unknown shipping option "[option]".', 'woocommerce-gateway-stripe' ),
				),
				'checkout' => array(
					'url'            => wc_get_checkout_url(),
					'currency_code'  => strtolower( get_woocommerce_currency() ),
					'country_code'   => substr( get_option( 'woocommerce_default_country' ), 0, 2 ),
					'needs_shipping' => WC()->cart->needs_shipping() ? 'yes' : 'no',
				),
				'button' => array(
					'type'   => $this->get_button_type(),
					'theme'  => $this->get_button_theme(),
					'height' => $this->get_button_height(),
					'locale' => substr( get_locale(), 0, 2 ), // Default format is en_US.
				),
				'is_product_page' => is_product(),
				'product'         => $this->get_product_data(),
			)
		);

		wp_enqueue_script( 'wc_stripe_payment_request' );
	}

	/**
	 * Display the payment request button.
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 */
	public function display_payment_request_button_html() {
		global $post;

		$gateways = WC()->payment_gateways->get_available_payment_gateways();

		if ( ! isset( $gateways['stripe'] ) ) {
			return;
		}

		if ( ! is_cart() && ! is_checkout() && ! is_product() && ! isset( $_GET['pay_for_order'] ) ) {
			return;
		}

		if ( is_product() && apply_filters( 'wc_stripe_hide_payment_request_on_product_page', false, $post ) ) {
			return;
		}

		if ( is_checkout() && ! apply_filters( 'wc_stripe_show_payment_request_on_checkout', false, $post ) ) {
			return;
		}

		if ( is_product() ) {
			$product = wc_get_product( $post->ID );

			if ( ! is_object( $product ) || ! in_array( ( WC_Stripe_Helper::is_pre_30() ? $product->product_type : $product->get_type() ), $this->supported_product_types() ) ) {
				return;
			}

			// Pre Orders charge upon release not supported.
			if ( class_exists( 'WC_Pre_Orders_Order' ) && WC_Pre_Orders_Product::product_is_charged_upon_release( $product ) ) {
				WC_Stripe_Logger::log( 'Pre Order charge upon release is not supported. ( Payment Request button disabled )' );
				return;
			}
		} else {
			if ( ! $this->allowed_items_in_cart() ) {
				WC_Stripe_Logger::log( 'Items in the cart has unsupported product type ( Payment Request button disabled )' );
				return;
			}
		}
		?>

		<?php
	}

	/**
	 * Display payment request button separator.
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 */
	public function display_payment_request_button_separator_html() {
		global $post;

		$gateways = WC()->payment_gateways->get_available_payment_gateways();

		if ( ! isset( $gateways['stripe'] ) ) {
			return;
		}

		if ( ! is_cart() && ! is_checkout() && ! is_product() && ! isset( $_GET['pay_for_order'] ) ) {
			return;
		}

		if ( is_product() && apply_filters( 'wc_stripe_hide_payment_request_on_product_page', false, $post ) ) {
			return;
		}

		if ( is_checkout() && ! apply_filters( 'wc_stripe_show_payment_request_on_checkout', false, $post ) ) {
			return;
		}

		if ( is_product() ) {
			$product = wc_get_product( $post->ID );

			if ( ! is_object( $product ) || ! in_array( ( WC_Stripe_Helper::is_pre_30() ? $product->product_type : $product->get_type() ), $this->supported_product_types() ) ) {
				return;
			}

			// Pre Orders charge upon release not supported.
			if ( class_exists( 'WC_Pre_Orders_Order' ) && WC_Pre_Orders_Product::product_is_charged_upon_release( $product ) ) {
				WC_Stripe_Logger::log( 'Pre Order charge upon release is not supported. ( Payment Request button disabled )' );
				return;
			}
		} else {
			if ( ! $this->allowed_items_in_cart() ) {
				WC_Stripe_Logger::log( 'Items in the cart has unsupported product type ( Payment Request button disabled )' );
				return;
			}
		}
		?>

— <?php esc_html_e( 'OR', 'woocommerce-gateway-stripe' ); ?> —

		<?php
	}

	/**
	 * Log errors coming from Payment Request
	 *
	 * @since 3.1.4
	 * @version 4.0.0
	 */
	public function ajax_log_errors() {
		check_ajax_referer( 'wc-stripe-log-errors', 'security' );

		$errors = wc_clean( stripslashes( $_POST['errors'] ) );

		WC_Stripe_Logger::log( $errors );

		exit;
	}

	/**
	 * Clears cart.
	 *
	 * @since 3.1.4
	 * @version 4.0.0
	 */
	public function ajax_clear_cart() {
		check_ajax_referer( 'wc-stripe-clear-cart', 'security' );

		WC()->cart->empty_cart();
		exit;
	}

	/**
	 * Get cart details.
	 */
	public function ajax_get_cart_details() {
		check_ajax_referer( 'wc-stripe-payment-request', 'security' );

		if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
			define( 'WOOCOMMERCE_CART', true );
		}

		WC()->cart->calculate_totals();

		$currency = get_woocommerce_currency();

		// Set mandatory payment details.
		$data = array(
			'shipping_required' => WC()->cart->needs_shipping(),
			'order_data'        => array(
				'currency'        => strtolower( $currency ),
				'country_code'    => substr( get_option( 'woocommerce_default_country' ), 0, 2 ),
			),
		);

		$data['order_data'] += $this->build_display_items();

		wp_send_json( $data );
	}

	/**
	 * Get shipping options.
	 *
	 * @see WC_Cart::get_shipping_packages().
	 * @see WC_Shipping::calculate_shipping().
	 * @see WC_Shipping::get_packages().
	 */
	public function ajax_get_shipping_options() {
		check_ajax_referer( 'wc-stripe-payment-request-shipping', 'security' );

		try {
			// Set the shipping package.
			$posted = filter_input_array( INPUT_POST, array(
				'country'   => FILTER_SANITIZE_STRING,
				'state'     => FILTER_SANITIZE_STRING,
				'postcode'  => FILTER_SANITIZE_STRING,
				'city'      => FILTER_SANITIZE_STRING,
				'address'   => FILTER_SANITIZE_STRING,
				'address_2' => FILTER_SANITIZE_STRING,
			) );

			$this->calculate_shipping( apply_filters( 'wc_stripe_payment_request_shipping_posted_values', $posted ) );

			// Set the shipping options.
			$data     = array();
			$packages = WC()->shipping->get_packages();

			if ( ! empty( $packages ) && WC()->customer->has_calculated_shipping() ) {
				foreach ( $packages as $package_key => $package ) {
					if ( empty( $package['rates'] ) ) {
						throw new Exception( __( 'Unable to find shipping method for address.', 'woocommerce-gateway-stripe' ) );
					}

					foreach ( $package['rates'] as $key => $rate ) {
						$data['shipping_options'][] = array(
							'id'       => $rate->id,
							'label'    => $rate->label,
							'detail'   => '',
							'amount'   => WC_Stripe_Helper::get_stripe_amount( $rate->cost ),
						);
					}
				}
			} else {
				throw new Exception( __( 'Unable to find shipping method for address.', 'woocommerce-gateway-stripe' ) );
			}

			if ( isset( $data[0] ) ) {
				// Auto select the first shipping method.
				WC()->session->set( 'chosen_shipping_methods', array( $data[0]['id'] ) );
			}

			WC()->cart->calculate_totals();

			$data += $this->build_display_items();
			$data['result'] = 'success';

			wp_send_json( $data );
		} catch ( Exception $e ) {
			$data += $this->build_display_items();
			$data['result'] = 'invalid_shipping_address';

			wp_send_json( $data );
		}
	}

	/**
	 * Update shipping method.
	 */
	public function ajax_update_shipping_method() {
		check_ajax_referer( 'wc-stripe-update-shipping-method', 'security' );

		if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
			define( 'WOOCOMMERCE_CART', true );
		}

		$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
		$shipping_method         = filter_input( INPUT_POST, 'shipping_method', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY );

		if ( is_array( $shipping_method ) ) {
			foreach ( $shipping_method as $i => $value ) {
				$chosen_shipping_methods[ $i ] = wc_clean( $value );
			}
		}

		WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );

		WC()->cart->calculate_totals();

		$data = array();
		$data += $this->build_display_items();
		$data['result'] = 'success';

		wp_send_json( $data );
	}

	/**
	 * Gets the selected product data.
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 * @return array $data
	 */
	public function ajax_get_selected_product_data() {
		check_ajax_referer( 'wc-stripe-get-selected-product-data', 'security' );

		$product_id = absint( $_POST['product_id'] );
		$qty = ! isset( $_POST['qty'] ) ? 1 : absint( $_POST['qty'] );

		$product = wc_get_product( $product_id );

		if ( 'variable' === ( WC_Stripe_Helper::is_pre_30() ? $product->product_type : $product->get_type() ) && isset( $_POST['attributes'] ) ) {
			$attributes = array_map( 'wc_clean', $_POST['attributes'] );

			if ( WC_Stripe_Helper::is_pre_30() ) {
				$variation_id = $product->get_matching_variation( $attributes );
			} else {
				$data_store = WC_Data_Store::load( 'product' );
				$variation_id = $data_store->find_matching_product_variation( $product, $attributes );
			}

			if ( ! empty( $variation_id ) ) {
				$product = wc_get_product( $variation_id );
			}
		} elseif ( 'simple' === ( WC_Stripe_Helper::is_pre_30() ? $product->product_type : $product->get_type() ) ) {
			$product = wc_get_product( $product_id );
		}

		$total = $qty * ( WC_Stripe_Helper::is_pre_30() ? $product->price : $product->get_price() );

		$quantity_label = 1 < $qty ? ' (x' . $qty . ')' : '';

		$data  = array();
		$items = array();

		$items[] = array(
			'label'  => ( WC_Stripe_Helper::is_pre_30() ? $product->name : $product->get_name() ) . $quantity_label,
			'amount' => WC_Stripe_Helper::get_stripe_amount( $total ),
		);

		if ( wc_tax_enabled() ) {
			$items[] = array(
				'label'   => __( 'Tax', 'woocommerce-gateway-stripe' ),
				'amount'  => 0,
				'pending' => true,
			);
		}

		if ( wc_shipping_enabled() && $product->needs_shipping() ) {
			$items[] = array(
				'label'   => __( 'Shipping', 'woocommerce-gateway-stripe' ),
				'amount'  => 0,
				'pending' => true,
			);

			$data['shippingOptions']  = array(
				'id'     => 'pending',
				'label'  => __( 'Pending', 'woocommerce-gateway-stripe' ),
				'detail' => '',
				'amount' => 0,
			);
		}

		$data['displayItems'] = $items;
		$data['total'] = array(
			'label'   => $this->total_label,
			'amount'  => WC_Stripe_Helper::get_stripe_amount( $total ),
			'pending' => true,
		);

		$data['requestShipping'] = ( wc_shipping_enabled() && $product->needs_shipping() );
		$data['currency']        = strtolower( get_woocommerce_currency() );
		$data['country_code']    = substr( get_option( 'woocommerce_default_country' ), 0, 2 );

		wp_send_json( $data );
	}

	/**
	 * Adds the current product to the cart. Used on product detail page.
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 * @return array $data
	 */
	public function ajax_add_to_cart() {
		check_ajax_referer( 'wc-stripe-add-to-cart', 'security' );

		if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
			define( 'WOOCOMMERCE_CART', true );
		}

		WC()->shipping->reset_shipping();

		$product_id = absint( $_POST['product_id'] );
		$qty = ! isset( $_POST['qty'] ) ? 1 : absint( $_POST['qty'] );

		$product = wc_get_product( $product_id );

		// First empty the cart to prevent wrong calculation.
		WC()->cart->empty_cart();

		if ( 'variable' === ( WC_Stripe_Helper::is_pre_30() ? $product->product_type : $product->get_type() ) && isset( $_POST['attributes'] ) ) {
			$attributes = array_map( 'wc_clean', $_POST['attributes'] );

			if ( WC_Stripe_Helper::is_pre_30() ) {
				$variation_id = $product->get_matching_variation( $attributes );
			} else {
				$data_store = WC_Data_Store::load( 'product' );
				$variation_id = $data_store->find_matching_product_variation( $product, $attributes );
			}

			WC()->cart->add_to_cart( $product->get_id(), $qty, $variation_id, $attributes );
		}

		if ( 'simple' === ( WC_Stripe_Helper::is_pre_30() ? $product->product_type : $product->get_type() ) ) {
			WC()->cart->add_to_cart( $product->get_id(), $qty );
		}

		WC()->cart->calculate_totals();

		$data = array();
		$data += $this->build_display_items();
		$data['result'] = 'success';

		wp_send_json( $data );
	}

	/**
	 * Normalizes the state/county field because in some
	 * cases, the state/county field is formatted differently from
	 * what WC is expecting and throws an error. An example
	 * for Ireland the county dropdown in Chrome shows "Co. Clare" format
	 *
	 * @since 4.0.0
	 * @version 4.0.0
	 */
	public function normalize_state() {
		$billing_country  = ! empty( $_POST['billing_country'] ) ? wc_clean( $_POST['billing_country'] ) : '';
		$shipping_country = ! empty( $_POST['shipping_country'] ) ? wc_clean( $_POST['shipping_country'] ) : '';
		$billing_state    = ! empty( $_POST['billing_state'] ) ? wc_clean( $_POST['billing_state'] ) : '';
		$shipping_state   = ! empty( $_POST['shipping_state'] ) ? wc_clean( $_POST['shipping_state'] ) : '';

		if ( $billing_state && $billing_country ) {
			$valid_states = WC()->countries->get_states( $billing_country );

			// Valid states found for country.
			if ( ! empty( $valid_states ) && is_array( $valid_states ) && sizeof( $valid_states ) > 0 ) {
				foreach ( $valid_states as $state_abbr => $state ) {
					if ( preg_match( '/' . preg_quote( $state ) . '/i', $billing_state ) ) {
						$_POST['billing_state'] = $state_abbr;
					}
				}
			}
		}

		if ( $shipping_state && $shipping_country ) {
			$valid_states = WC()->countries->get_states( $shipping_country );

			// Valid states found for country.
			if ( ! empty( $valid_states ) && is_array( $valid_states ) && sizeof( $valid_states ) > 0 ) {
				foreach ( $valid_states as $state_abbr => $state ) {
					if ( preg_match( '/' . preg_quote( $state ) . '/i', $shipping_state ) ) {
						$_POST['shipping_state'] = $state_abbr;
					}
				}
			}
		}
	}

	/**
	 * Create order. Security is handled by WC.
	 *
	 * @since 3.1.0
	 * @version 4.0.0
	 */
	public function ajax_create_order() {
		if ( WC()->cart->is_empty() ) {
			wp_send_json_error( __( 'Empty cart', 'woocommerce-gateway-stripe' ) );
		}

		if ( ! defined( 'WOOCOMMERCE_CHECKOUT' ) ) {
			define( 'WOOCOMMERCE_CHECKOUT', true );
		}

		$this->normalize_state();

		WC()->checkout()->process_checkout();

		die( 0 );
	}

	/**
	 * Calculate and set shipping method.
	 *
	 * @since 3.1.0
	 * @version 4.0.0
	 * @param array $address
	 */
	protected function calculate_shipping( $address = array() ) {
		global $states;

		$country   = $address['country'];
		$state     = $address['state'];
		$postcode  = $address['postcode'];
		$city      = $address['city'];
		$address_1 = $address['address'];
		$address_2 = $address['address_2'];

		$country_class = new WC_Countries();
		$country_class->load_country_states();

		/**
		 * In some versions of Chrome, state can be a full name. So we need
		 * to convert that to abbreviation as WC is expecting that.
		 */
		if ( 2 < strlen( $state ) ) {
			$state = array_search( ucfirst( strtolower( $state ) ), $states[ $country ] );
		}

		WC()->shipping->reset_shipping();

		if ( $postcode && WC_Validation::is_postcode( $postcode, $country ) ) {
			$postcode = wc_format_postcode( $postcode, $country );
		}

		if ( $country ) {
			WC()->customer->set_location( $country, $state, $postcode, $city );
			WC()->customer->set_shipping_location( $country, $state, $postcode, $city );
		} else {
			WC_Stripe_Helper::is_pre_30() ? WC()->customer->set_to_base() : WC()->customer->set_billing_address_to_base();
			WC_Stripe_Helper::is_pre_30() ? WC()->customer->set_shipping_to_base() : WC()->customer->set_shipping_address_to_base();
		}

		if ( WC_Stripe_Helper::is_pre_30() ) {
			WC()->customer->calculated_shipping( true );
		} else {
			WC()->customer->set_calculated_shipping( true );
			WC()->customer->save();
		}

		$packages = array();

		$packages[0]['contents']                 = WC()->cart->get_cart();
		$packages[0]['contents_cost']            = 0;
		$packages[0]['applied_coupons']          = WC()->cart->applied_coupons;
		$packages[0]['user']['ID']               = get_current_user_id();
		$packages[0]['destination']['country']   = $country;
		$packages[0]['destination']['state']     = $state;
		$packages[0]['destination']['postcode']  = $postcode;
		$packages[0]['destination']['city']      = $city;
		$packages[0]['destination']['address']   = $address_1;
		$packages[0]['destination']['address_2'] = $address_2;

		foreach ( WC()->cart->get_cart() as $item ) {
			if ( $item['data']->needs_shipping() ) {
				if ( isset( $item['line_total'] ) ) {
					$packages[0]['contents_cost'] += $item['line_total'];
				}
			}
		}

		$packages = apply_filters( 'woocommerce_cart_shipping_packages', $packages );

		WC()->shipping->calculate_shipping( $packages );
	}

	/**
	 * Builds the shippings methods to pass to Payment Request
	 *
	 * @since 3.1.0
	 * @version 4.0.0
	 */
	protected function build_shipping_methods( $shipping_methods ) {
		if ( empty( $shipping_methods ) ) {
			return array();
		}

		$shipping = array();

		foreach ( $shipping_methods as $method ) {
			$shipping[] = array(
				'id'         => $method['id'],
				'label'      => $method['label'],
				'detail'     => '',
				'amount'     => WC_Stripe_Helper::get_stripe_amount( $method['amount']['value'] ),
			);
		}

		return $shipping;
	}

	/**
	 * Builds the line items to pass to Payment Request
	 *
	 * @since 3.1.0
	 * @version 4.0.0
	 */
	protected function build_display_items() {
		if ( ! defined( 'WOOCOMMERCE_CART' ) ) {
			define( 'WOOCOMMERCE_CART', true );
		}

		$items     = array();
		$subtotal  = 0;
		$discounts = 0;

		// Default show only subtotal instead of itemization.
		if ( ! apply_filters( 'wc_stripe_payment_request_hide_itemization', true ) ) {
			foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
				$amount         = $cart_item['line_subtotal'];
				$subtotal       += $cart_item['line_subtotal'];
				$quantity_label = 1 < $cart_item['quantity'] ? ' (x' . $cart_item['quantity'] . ')' : '';

				$product_name = WC_Stripe_Helper::is_pre_30() ? $cart_item['data']->post->post_title : $cart_item['data']->get_name();

				$item = array(
					'label'  => $product_name . $quantity_label,
					'amount' => WC_Stripe_Helper::get_stripe_amount( $amount ),
				);

				$items[] = $item;
			}
		}

		if ( version_compare( WC_VERSION, '3.2', '<' ) ) {
			$discounts = wc_format_decimal( WC()->cart->get_cart_discount_total(), WC()->cart->dp );
		} else {
			$applied_coupons = array_values( WC()->cart->get_coupon_discount_totals() );

			foreach ( $applied_coupons as $amount ) {
				$discounts += (float) $amount;
			}
		}

		$discounts   = wc_format_decimal( $discounts, WC()->cart->dp );
		$tax         = wc_format_decimal( WC()->cart->tax_total + WC()->cart->shipping_tax_total, WC()->cart->dp );
		$shipping    = wc_format_decimal( WC()->cart->shipping_total, WC()->cart->dp );
		$items_total = wc_format_decimal( WC()->cart->cart_contents_total, WC()->cart->dp ) + $discounts;
		$order_total = version_compare( WC_VERSION, '3.2', '<' ) ? wc_format_decimal( $items_total + $tax + $shipping - $discounts, WC()->cart->dp ) : WC()->cart->get_total( false );

		if ( wc_tax_enabled() ) {
			$items[] = array(
				'label'  => esc_html( __( 'Tax', 'woocommerce-gateway-stripe' ) ),
				'amount' => WC_Stripe_Helper::get_stripe_amount( $tax ),
			);
		}

		if ( WC()->cart->needs_shipping() ) {
			$items[] = array(
				'label'  => esc_html( __( 'Shipping', 'woocommerce-gateway-stripe' ) ),
				'amount' => WC_Stripe_Helper::get_stripe_amount( $shipping ),
			);
		}

		if ( WC()->cart->has_discount() ) {
			$items[] = array(
				'label'  => esc_html( __( 'Discount', 'woocommerce-gateway-stripe' ) ),
				'amount' => WC_Stripe_Helper::get_stripe_amount( $discounts ),
			);
		}

		if ( version_compare( WC_VERSION, '3.2', '<' ) ) {
			$cart_fees = WC()->cart->fees;
		} else {
			$cart_fees = WC()->cart->get_fees();
		}

		// Include fees and taxes as display items.
		foreach ( $cart_fees as $key => $fee ) {
			$items[] = array(
				'label'  => $fee->name,
				'amount' => WC_Stripe_Helper::get_stripe_amount( $fee->amount ),
			);
		}

		return array(
			'displayItems' => $items,
			'total'      => array(
				'label'   => $this->total_label,
				'amount'  => max( 0, apply_filters( 'woocommerce_stripe_calculated_total', WC_Stripe_Helper::get_stripe_amount( $order_total ), $order_total, WC()->cart ) ),
				'pending' => false,
			),
		);
	}
}

new WC_Stripe_Payment_Request();


text:
@implementation AKParallelCombLowPassFilterReverb
{
    AKParameter * _input;
}

- (instancetype)initWithInput:(AKParameter *)input
                     duration:(AKParameter *)duration
     highFrequencyDiffusivity:(AKParameter *)highFrequencyDiffusivity
{
    self = [super initWithString:[self operationName]];
    if (self) {
        _input = input;
        _duration = duration;
        _highFrequencyDiffusivity = highFrequencyDiffusivity;
        [self setUpConnections];
}
    return self;
}

- (instancetype)initWithInput:(AKParameter *)input
{
    self = [super initWithString:[self operationName]];
    if (self) {
        _input = input;
        // Default Values
        _duration = akp(1);
        _highFrequencyDiffusivity = akp(0.5);
        [self setUpConnections];
    }
    return self;
}

+ (instancetype)reverbWithInput:(AKParameter *)input
{
    return [[AKParallelCombLowPassFilterReverb alloc] initWithInput:input];
}

- (void)setDuration:(AKParameter *)duration {
    _duration = duration;
    [self setUpConnections];
}

- (void)setOptionalDuration:(AKParameter *)duration {
    [self setDuration:duration];
}

- (void)setHighFrequencyDiffusivity:(AKParameter *)highFrequencyDiffusivity {
    _highFrequencyDiffusivity = highFrequencyDiffusivity;
    [self setUpConnections];
}

- (void)setOptionalHighFrequencyDiffusivity:(AKParameter *)highFrequencyDiffusivity {
    [self setHighFrequencyDiffusivity:highFrequencyDiffusivity];
}

- (void)setUpConnections
{
    self.state = @"connectable";
    self.dependencies = @[_input, _duration, _highFrequencyDiffusivity];
}

- (NSString *)inlineStringForCSD
{
    NSMutableString *inlineCSDString = [[NSMutableString alloc] init];

    [inlineCSDString appendString:@"nreverb("];
    [inlineCSDString appendString:[self inputsString]];
    [inlineCSDString appendString:@")"];

    return inlineCSDString;
}

- (NSString *)stringForCSD
{
    NSMutableString *csdString = [[NSMutableString alloc] init];

    [csdString appendFormat:@"%@ nreverb ", self];
    [csdString appendString:[self inputsString]];
    return csdString;
}

- (NSString *)inputsString {
    NSMutableString *inputsString = [[NSMutableString alloc] init];

    if ([_input class] == [AKAudio class]) {
        [inputsString appendFormat:@"%@, ", _input];
    } else {
        [inputsString appendFormat:@"AKAudio(%@), ", _input];
    }

    if ([_duration class] == [AKControl class]) {
        [inputsString appendFormat:@"%@, ", _duration];
    } else {
        [inputsString appendFormat:@"AKControl(%@), ", _duration];
    }

    if ([_highFrequencyDiffusivity class] == [AKControl class]) {
        [inputsString appendFormat:@"%@", _highFrequencyDiffusivity];
    } else {
        [inputsString appendFormat:@"AKControl(%@)", _highFrequencyDiffusivity];
    }
return inputsString;
}

@end