text:
// Copyright 2019 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

package tables_test

import (
	"context"

	. "github.com/pingcap/check"
	"github.com/pingcap/parser/model"
	"github.com/pingcap/tidb/ddl"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/sessionctx/binloginfo"
	"github.com/pingcap/tidb/table"
	"github.com/pingcap/tidb/table/tables"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/testkit"
)

func (ts *testSuite) TestPartitionBasic(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	ctx := tk.Se
	ctx.GetSessionVars().BinlogClient = binloginfo.MockPumpsClient(mockPumpClient{})
	tk.MustExec("set @@session.tidb_enable_table_partition = '1'")
	tk.MustExec(`CREATE TABLE partition_basic (id int(11), unique index(id))
PARTITION BY RANGE COLUMNS ( id ) (
		PARTITION p0 VALUES LESS THAN (6),
		PARTITION p1 VALUES LESS THAN (11),
		PARTITION p2 VALUES LESS THAN (16),
		PARTITION p3 VALUES LESS THAN (21)
)`)
	tk.MustExec("insert into partition_basic values(0)")
	tk.MustExec("insert into partition_basic values(2) on duplicate key update id = 1")
	tk.MustExec("update partition_basic set id = 7 where id = 0")

	tk.MustQuery("select * from partition_basic where id = 7").Check(testkit.Rows("7"))
	tk.MustQuery("select * from partition_basic partition (p1)").Check(testkit.Rows("7"))
	_, err := tk.Exec("select * from partition_basic partition (p5)")
	c.Assert(err, NotNil)

	_, err = tk.Exec("update partition_basic set id = 666 where id = 7")
	c.Assert(err, NotNil)
	tk.MustExec("update partition_basic set id = 9 where id = 7")
	tk.MustExec("delete from partition_basic where id = 7")
	tk.MustExec("delete from partition_basic where id = 9")
	tk.MustExec("drop table partition_basic")
}

func (ts *testSuite) TestPartitionAddRecord(c *C) {
	createTable1 := `CREATE TABLE test.t1 (id int(11), index(id))
PARTITION BY RANGE ( id ) (
		PARTITION p0 VALUES LESS THAN (6),
		PARTITION p1 VALUES LESS THAN (11),
		PARTITION p2 VALUES LESS THAN (16),
		PARTITION p3 VALUES LESS THAN (21)
)`
	ctx := context.Background()
	_, err := ts.se.Execute(ctx, "use test")
	c.Assert(err, IsNil)
	_, err = ts.se.Execute(ctx, "drop table if exists t1, t2;")
	c.Assert(err, IsNil)
	_, err = ts.se.Execute(ctx, createTable1)
	c.Assert(err, IsNil)
	tb, err := ts.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
	c.Assert(err, IsNil)
	tbInfo := tb.Meta()
	p0 := tbInfo.Partition.Definitions[0]
	c.Assert(p0.Name, Equals, model.NewCIStr("p0"))
	c.Assert(ts.se.NewTxn(ctx), IsNil)
	rid, err := tb.AddRecord(ts.se, types.MakeDatums(1))
	c.Assert(err, IsNil)

	// Check that add record writes to the partition, rather than the table.
	txn, err := ts.se.Txn(true)
	c.Assert(err, IsNil)
	val, err := txn.Get(context.TODO(), tables.PartitionRecordKey(p0.ID, rid.IntValue()))
	c.Assert(err, IsNil)
	c.Assert(len(val), Greater, 0)
	_, err = txn.Get(context.TODO(), tables.PartitionRecordKey(tbInfo.ID, rid.IntValue()))
	c.Assert(kv.ErrNotExist.Equal(err), IsTrue)

	// Cover more code.
	_, err = tb.AddRecord(ts.se, types.MakeDatums(7))
	c.Assert(err, IsNil)
	_, err = tb.AddRecord(ts.se, types.MakeDatums(12))
	c.Assert(err, IsNil)
	_, err = tb.AddRecord(ts.se, types.MakeDatums(16))
	c.Assert(err, IsNil)

	// Make the changes visible.
	_, err = ts.se.Execute(context.Background(), "commit")
	c.Assert(err, IsNil)

	// Check index count equals to data count.
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustQuery("select count(*) from t1").Check(testkit.Rows("4"))
	tk.MustQuery("select count(*) from t1 use index(id)").Check(testkit.Rows("4"))
	tk.MustQuery("select count(*) from t1 use index(id) where id > 6").Check(testkit.Rows("3"))

	// Value must locates in one partition.
	_, err = tb.AddRecord(ts.se, types.MakeDatums(22))
	c.Assert(table.ErrNoPartitionForGivenValue.Equal(err), IsTrue)
	ts.se.Execute(context.Background(), "rollback")

	createTable2 := `CREATE TABLE test.t2 (id int(11))
PARTITION BY RANGE ( id ) (
		PARTITION p0 VALUES LESS THAN (6),
		PARTITION p3 VALUES LESS THAN MAXVALUE
)`
	_, err = ts.se.Execute(context.Background(), createTable2)
	c.Assert(err, IsNil)
	c.Assert(ts.se.NewTxn(ctx), IsNil)
	tb, err = ts.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t2"))
	c.Assert(err, IsNil)
	_, err = tb.AddRecord(ts.se, types.MakeDatums(22))
	c.Assert(err, IsNil) // Insert into maxvalue partition.

	createTable3 := `create table test.t3 (id int) partition by range (id)
	(
       partition p0 values less than (10)
	)`
	_, err = ts.se.Execute(context.Background(), createTable3)
	c.Assert(err, IsNil)
	c.Assert(ts.se.NewTxn(ctx), IsNil)
	tb, err = ts.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t3"))
	c.Assert(err, IsNil)
	_, err = tb.AddRecord(ts.se, types.MakeDatums(11))
	c.Assert(table.ErrNoPartitionForGivenValue.Equal(err), IsTrue)
	_, err = tb.AddRecord(ts.se, types.MakeDatums(10))
	c.Assert(table.ErrNoPartitionForGivenValue.Equal(err), IsTrue)
	_, err = tb.AddRecord(ts.se, types.MakeDatums(0))
	c.Assert(err, IsNil)

	createTable4 := `create table test.t4 (a int,b int) partition by range (a+b)
	(
	partition p0 values less than (10)
	);`
	_, err = ts.se.Execute(context.Background(), createTable4)
	c.Assert(err, IsNil)
	c.Assert(ts.se.NewTxn(ctx), IsNil)
	tb, err = ts.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t4"))
	c.Assert(err, IsNil)
	_, err = tb.AddRecord(ts.se, types.MakeDatums(1, 11))
	c.Assert(table.ErrNoPartitionForGivenValue.Equal(err), IsTrue)
}

func (ts *testSuite) TestHashPartitionAddRecord(c *C) {
	_, err := ts.se.Execute(context.Background(), "use test")
	c.Assert(err, IsNil)
	_, err = ts.se.Execute(context.Background(), "drop table if exists t1;")
	c.Assert(err, IsNil)
	_, err = ts.se.Execute(context.Background(), "set @@session.tidb_enable_table_partition = '1';")
	c.Assert(err, IsNil)
	_, err = ts.se.Execute(context.Background(), `CREATE TABLE test.t1 (id int(11), index(id)) PARTITION BY HASH (id) partitions 4;`)
	c.Assert(err, IsNil)
	tb, err := ts.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
	c.Assert(err, IsNil)
	tbInfo := tb.Meta()
	p0 := tbInfo.Partition.Definitions[0]
	c.Assert(ts.se.NewTxn(context.Background()), IsNil)
	rid, err := tb.AddRecord(ts.se, types.MakeDatums(8))
	c.Assert(err, IsNil)

	// Check that add record writes to the partition, rather than the table.
	txn, err := ts.se.Txn(true)
	c.Assert(err, IsNil)
	val, err := txn.Get(context.TODO(), tables.PartitionRecordKey(p0.ID, rid.IntValue()))
	c.Assert(err, IsNil)
	c.Assert(len(val), Greater, 0)
	_, err = txn.Get(context.TODO(), tables.PartitionRecordKey(tbInfo.ID, rid.IntValue()))
	c.Assert(kv.ErrNotExist.Equal(err), IsTrue)

	// Cover more code.
	_, err = tb.AddRecord(ts.se, types.MakeDatums(-1))
	c.Assert(err, IsNil)
	_, err = tb.AddRecord(ts.se, types.MakeDatums(3))
	c.Assert(err, IsNil)
	_, err = tb.AddRecord(ts.se, types.MakeDatums(6))
	c.Assert(err, IsNil)

	// Make the changes visible.
	_, err = ts.se.Execute(context.Background(), "commit")
	c.Assert(err, IsNil)

	// Check index count equals to data count.
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustQuery("select count(*) from t1").Check(testkit.Rows("4"))
	tk.MustQuery("select count(*) from t1 use index(id)").Check(testkit.Rows("4"))
	tk.MustQuery("select count(*) from t1 use index(id) where id > 2").Check(testkit.Rows("3"))

	// Test for partition expression is negative number.
	_, err = ts.se.Execute(context.Background(), `CREATE TABLE test.t2 (id int(11), index(id)) PARTITION BY HASH (id) partitions 11;`)
	c.Assert(err, IsNil)
	tb, err = ts.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t2"))
	c.Assert(err, IsNil)
	tbInfo = tb.Meta()
	for i := 0; i < 11; i++ {
		c.Assert(ts.se.NewTxn(context.Background()), IsNil)
		rid, err = tb.AddRecord(ts.se, types.MakeDatums(-i))
		c.Assert(err, IsNil)
		txn, err = ts.se.Txn(true)
		c.Assert(err, IsNil)
		val, err = txn.Get(context.TODO(), tables.PartitionRecordKey(tbInfo.Partition.Definitions[i].ID, rid.IntValue()))
		c.Assert(err, IsNil)
		c.Assert(len(val), Greater, 0)
		_, err = txn.Get(context.TODO(), tables.PartitionRecordKey(tbInfo.ID, rid.IntValue()))
		c.Assert(kv.ErrNotExist.Equal(err), IsTrue)
	}
	_, err = ts.se.Execute(context.Background(), "drop table if exists t1, t2;")
	c.Assert(err, IsNil)
}

// TestPartitionGetPhysicalID tests partition.GetPhysicalID().
func (ts *testSuite) TestPartitionGetPhysicalID(c *C) {
	createTable1 := `CREATE TABLE test.t1 (id int(11), index(id))
PARTITION BY RANGE ( id ) (
		PARTITION p0 VALUES LESS THAN (6),
		PARTITION p1 VALUES LESS THAN (11),
		PARTITION p2 VALUES LESS THAN (16),
		PARTITION p3 VALUES LESS THAN (21)
)`

	_, err := ts.se.Execute(context.Background(), "Drop table if exists test.t1;")
	c.Assert(err, IsNil)
	_, err = ts.se.Execute(context.Background(), createTable1)
	c.Assert(err, IsNil)
	tb, err := ts.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
	c.Assert(err, IsNil)
	tbInfo := tb.Meta()
	ps := tbInfo.GetPartitionInfo()
	c.Assert(ps, NotNil)
	for _, pd := range ps.Definitions {
		p := tb.(table.PartitionedTable).GetPartition(pd.ID)
		c.Assert(p, NotNil)
		c.Assert(pd.ID, Equals, p.GetPhysicalID())
	}
}

func (ts *testSuite) TestGeneratePartitionExpr(c *C) {
	_, err := ts.se.Execute(context.Background(), "use test")
	c.Assert(err, IsNil)
	c.Assert(err, IsNil)
	_, err = ts.se.Execute(context.Background(), "drop table if exists t1;")
	c.Assert(err, IsNil)
	_, err = ts.se.Execute(context.Background(), `create table t1 (id int)
							partition by range (id) (
							partition p0 values less than (4),
							partition p1 values less than (7),
							partition p3 values less than maxvalue)`)
	c.Assert(err, IsNil)

	tbl, err := ts.dom.InfoSchema().TableByName(model.NewCIStr("test"), model.NewCIStr("t1"))
	c.Assert(err, IsNil)
	type partitionExpr interface {
		PartitionExpr() (*tables.PartitionExpr, error)
	}
	pe, err := tbl.(partitionExpr).PartitionExpr()
	c.Assert(err, IsNil)

	upperBounds := []string{
		"lt(t1.id, 4)",
		"lt(t1.id, 7)",
		"1",
	}
	for i, expr := range pe.UpperBounds {
		c.Assert(expr.String(), Equals, upperBounds[i])
	}
}

func (ts *testSuite) TestLocateRangeColumnPartitionErr(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	tk.MustExec(`CREATE TABLE t_month_data_monitor (
		id int(20) NOT NULL AUTO_INCREMENT,
		data_date date NOT NULL,
		PRIMARY KEY (id, data_date)
	) PARTITION BY RANGE COLUMNS(data_date) (
		PARTITION p20190401 VALUES LESS THAN ('2019-04-02'),
		PARTITION p20190402 VALUES LESS THAN ('2019-04-03')
	)`)

	_, err := tk.Exec("INSERT INTO t_month_data_monitor VALUES (4, '2019-04-04')")
	c.Assert(table.ErrNoPartitionForGivenValue.Equal(err), IsTrue)
}

func (ts *testSuite) TestLocateRangePartitionErr(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	tk.MustExec(`CREATE TABLE t_range_locate (
		id int(20) NOT NULL AUTO_INCREMENT,
		data_date date NOT NULL,
		PRIMARY KEY (id, data_date)
	) PARTITION BY RANGE(id) (
		PARTITION p0 VALUES LESS THAN (1024),
		PARTITION p1 VALUES LESS THAN (4096)
	)`)

	_, err := tk.Exec("INSERT INTO t_range_locate VALUES (5000, '2019-04-04')")
	c.Assert(table.ErrNoPartitionForGivenValue.Equal(err), IsTrue)
}

func (ts *testSuite) TestLocatePartitionWithExtraHandle(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	tk.MustExec(`CREATE TABLE t_extra (
		id int(20) NOT NULL AUTO_INCREMENT,
		x int(10) not null,
		PRIMARY KEY (id, x)
	) PARTITION BY RANGE(id) (
		PARTITION p0 VALUES LESS THAN (1024),
		PARTITION p1 VALUES LESS THAN (4096)
	)`)
	tk.MustExec("INSERT INTO t_extra VALUES (1000, 1000), (2000, 2000)")
	tk.MustExec("set autocommit=0;")
	tk.MustQuery("select * from t_extra where id = 1000 for update").Check(testkit.Rows("1000 1000"))
	tk.MustExec("commit")
}

func (ts *testSuite) TestMultiTableUpdate(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	tk.MustExec(`CREATE TABLE t_a (
		id int(20),
		data_date date
	) partition by hash(id) partitions 10`)
	tk.MustExec(`CREATE TABLE t_b (
		id int(20),
		data_date date
	) PARTITION BY RANGE(id) (
		PARTITION p0 VALUES LESS THAN (2),
		PARTITION p1 VALUES LESS THAN (4),
		PARTITION p2 VALUES LESS THAN (6)
	)`)
	tk.MustExec("INSERT INTO t_a VALUES (1, '2020-08-25'), (2, '2020-08-25'), (3, '2020-08-25'), (4, '2020-08-25'), (5, '2020-08-25')")
	tk.MustExec("INSERT INTO t_b VALUES (1, '2020-08-25'), (2, '2020-08-25'), (3, '2020-08-25'), (4, '2020-08-25'), (5, '2020-08-25')")
	tk.MustExec("update t_a, t_b set t_a.data_date = '2020-08-24',  t_a.data_date = '2020-08-23', t_a.id = t_a.id + t_b.id where t_a.id = t_b.id")
	tk.MustQuery("select id from t_a order by id").Check(testkit.Rows("2", "4", "6", "8", "10"))
}

func (ts *testSuite) TestLocatePartitionSingleColumn(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	tk.MustExec(`CREATE TABLE t_hash_locate (
		id int(20),
		data_date date
	) partition by hash(id) partitions 10`)

	tk.MustExec(`CREATE TABLE t_range (
		id int(10) NOT NULL,
		data_date date,
		PRIMARY KEY (id)
	) PARTITION BY RANGE(id) (
		PARTITION p0 VALUES LESS THAN (1),
		PARTITION p1 VALUES LESS THAN (2),
		PARTITION p2 VALUES LESS THAN (4)
	)`)

	tk.MustExec("INSERT INTO t_hash_locate VALUES (), (), (), ()")
	tk.MustQuery("SELECT count(*) FROM t_hash_locate PARTITION (p0)").Check(testkit.Rows("4"))
	tk.MustExec("INSERT INTO t_range VALUES (-1, NULL), (1, NULL), (2, NULL), (3, NULL)")
	tk.MustQuery("SELECT count(*) FROM t_range PARTITION (p0)").Check(testkit.Rows("1"))
	tk.MustQuery("SELECT count(*) FROM t_range PARTITION (p1)").Check(testkit.Rows("1"))
	tk.MustQuery("SELECT count(*) FROM t_range PARTITION (p2)").Check(testkit.Rows("2"))
	_, err := tk.Exec("INSERT INTO t_range VALUES (4, NULL)")
	c.Assert(table.ErrNoPartitionForGivenValue.Equal(err), IsTrue)
}

func (ts *testSuite) TestTimeZoneChange(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	createTable := `CREATE TABLE timezone_test (
	id int(11) NOT NULL,
	creation_dt timestamp DEFAULT CURRENT_TIMESTAMP ) PARTITION BY RANGE ( ` + "UNIX_TIMESTAMP(`creation_dt`)" + ` )
( PARTITION p5 VALUES LESS THAN ( UNIX_TIMESTAMP('2020-01-03 15:10:00') ),
	PARTITION p6 VALUES LESS THAN ( UNIX_TIMESTAMP('2020-01-03 15:15:00') ),
	PARTITION p7 VALUES LESS THAN ( UNIX_TIMESTAMP('2020-01-03 15:20:00') ),
	PARTITION p8 VALUES LESS THAN ( UNIX_TIMESTAMP('2020-01-03 15:25:00') ),
	PARTITION p9 VALUES LESS THAN (MAXVALUE) )`
	tk.MustExec("SET @@time_zone = 'Asia/Shanghai'")
	tk.MustExec(createTable)
	tk.MustQuery("SHOW CREATE TABLE timezone_test").Check(testkit.Rows("timezone_test CREATE TABLE `timezone_test` (\n" +
		"  `id` int(11) NOT NULL,\n" +
		"  `creation_dt` timestamp DEFAULT CURRENT_TIMESTAMP\n" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin\n" +
		"PARTITION BY RANGE ( UNIX_TIMESTAMP(`creation_dt`) ) (\n" +
		"  PARTITION `p5` VALUES LESS THAN (1578035400),\n" +
		"  PARTITION `p6` VALUES LESS THAN (1578035700),\n" +
		"  PARTITION `p7` VALUES LESS THAN (1578036000),\n" +
		"  PARTITION `p8` VALUES LESS THAN (1578036300),\n" +
		"  PARTITION `p9` VALUES LESS THAN (MAXVALUE)\n)"))
	tk.MustExec("DROP TABLE timezone_test")

	// Note that the result of "show create table" varies with time_zone.
	tk.MustExec("SET @@time_zone = 'UTC'")
	tk.MustExec(createTable)
	tk.MustQuery("SHOW CREATE TABLE timezone_test").Check(testkit.Rows("timezone_test CREATE TABLE `timezone_test` (\n" +
		"  `id` int(11) NOT NULL,\n" +
		"  `creation_dt` timestamp DEFAULT CURRENT_TIMESTAMP\n" +
		") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin\n" +
		"PARTITION BY RANGE ( UNIX_TIMESTAMP(`creation_dt`) ) (\n" +
		"  PARTITION `p5` VALUES LESS THAN (1578064200),\n" +
		"  PARTITION `p6` VALUES LESS THAN (1578064500),\n" +
		"  PARTITION `p7` VALUES LESS THAN (1578064800),\n" +
		"  PARTITION `p8` VALUES LESS THAN (1578065100),\n" +
		"  PARTITION `p9` VALUES LESS THAN (MAXVALUE)\n)"))

	// Change time zone and insert data, check the data locates in the correct partition.
	tk.MustExec("SET @@time_zone = 'Asia/Shanghai'")
	tk.MustExec("INSERT INTO timezone_test VALUES (1,'2020-01-03 15:16:59')")
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p5)").Check(testkit.Rows("1 2020-01-03 15:16:59"))
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p6)").Check(testkit.Rows())
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p7)").Check(testkit.Rows())
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p8)").Check(testkit.Rows())
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p9)").Check(testkit.Rows())

	tk.MustExec("SET @@time_zone = 'UTC'")
	tk.MustExec("INSERT INTO timezone_test VALUES (1,'2020-01-03 15:16:59')")
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p5)").Check(testkit.Rows("1 2020-01-03 07:16:59"))
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p6)").Check(testkit.Rows())
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p7)").Check(testkit.Rows("1 2020-01-03 15:16:59"))
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p8)").Check(testkit.Rows())
	tk.MustQuery("SELECT * FROM timezone_test PARTITION (p9)").Check(testkit.Rows())
}

func (ts *testSuite) TestCreatePartitionTableNotSupport(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	_, err := tk.Exec(`create table t7 (a int) partition by range (mod((select * from t), 5)) (partition p1 values less than (1));`)
	c.Assert(ddl.ErrPartitionFunctionIsNotAllowed.Equal(err), IsTrue)
	_, err = tk.Exec(`create table t7 (a int) partition by range (1 + (select * from t)) (partition p1 values less than (1));`)
	c.Assert(ddl.ErrPartitionFunctionIsNotAllowed.Equal(err), IsTrue)
	_, err = tk.Exec(`create table t7 (a int) partition by range (a + row(1, 2, 3)) (partition p1 values less than (1));`)
	c.Assert(ddl.ErrPartitionFunctionIsNotAllowed.Equal(err), IsTrue)
	_, err = tk.Exec(`create table t7 (a int) partition by range (-(select * from t)) (partition p1 values less than (1));`)
	c.Assert(ddl.ErrPartitionFunctionIsNotAllowed.Equal(err), IsTrue)
}

func (ts *testSuite) TestIntUint(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	tk.MustExec(`create table t_uint (id bigint unsigned) partition by range (id) (
partition p0 values less than (4294967293),
partition p1 values less than (4294967296),
partition p2 values less than (484467440737095),
partition p3 values less than (18446744073709551614))`)
	tk.MustExec("insert into t_uint values (1)")
	tk.MustExec("insert into t_uint values (4294967294)")
	tk.MustExec("insert into t_uint values (4294967295)")
	tk.MustExec("insert into t_uint values (18446744073709551613)")
	tk.MustQuery("select * from t_uint where id > 484467440737095").Check(testkit.Rows("18446744073709551613"))
	tk.MustQuery("select * from t_uint where id = 4294967295").Check(testkit.Rows("4294967295"))
	tk.MustQuery("select * from t_uint where id < 4294967294").Check(testkit.Rows("1"))
	tk.MustQuery("select * from t_uint where id >= 4294967293 order by id").Check(testkit.Rows("4294967294", "4294967295", "18446744073709551613"))

	tk.MustExec(`create table t_int (id bigint signed) partition by range (id) (
partition p0 values less than (-4294967293),
partition p1 values less than (-12345),
partition p2 values less than (0),
partition p3 values less than (484467440737095),
partition p4 values less than (9223372036854775806))`)
	tk.MustExec("insert into t_int values (-9223372036854775803)")
	tk.MustExec("insert into t_int values (-429496729312)")
	tk.MustExec("insert into t_int values (-1)")
	tk.MustExec("insert into t_int values (4294967295)")
	tk.MustExec("insert into t_int values (9223372036854775805)")
	tk.MustQuery("select * from t_int where id > 484467440737095").Check(testkit.Rows("9223372036854775805"))
	tk.MustQuery("select * from t_int where id = 4294967295").Check(testkit.Rows("4294967295"))
	tk.MustQuery("select * from t_int where id = -4294967294").Check(testkit.Rows())
	tk.MustQuery("select * from t_int where id < -12345 order by id desc").Check(testkit.Rows("-429496729312", "-9223372036854775803"))
}

func (ts *testSuite) TestHashPartitionAndConditionConflict(c *C) {
	tk := testkit.NewTestKitWithInit(c, ts.store)
	tk.MustExec("use test")
	tk.MustExec("drop table if exists t1, t2, t3;")
	tk.MustExec("create table t1 (a int, b tinyint)  partition by range (a) (" +
		"    partition p0 values less than (10)," +
		"    partition p1 values less than (20)," +
		"    partition p2 values less than (30)," +
		"    partition p3 values less than (40)," +
		"    partition p4 values less than MAXVALUE" +
		");")

	tk.MustExec("insert into t1 values(NULL, NULL), (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (20, 20), (21, 21), (22, 22), (23, 23), (24, 24), (25, 25), (30, 30), (31, 31), (32, 32), (33, 33), (34, 34), (35, 35), (36, 36), (40, 40), (50, 50), (80, 80), (90, 90), (100, 100);")
	tk.MustExec("create table t2 (a int, b bigint) partition by hash(a) partitions 10;")
	tk.MustExec("insert into t2 values (NULL, NULL), (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16), (17, 17), (18, 18), (19, 19), (20, 20), (21, 21), (22, 22), (23, 23);")
	tk.MustQuery("select /*+ HASH_JOIN(t1, t2) */ * from t1 partition (p0) left join t2 partition (p1) on t1.a = t2.a where t1.a = 6 order by t1.a, t1.b, t2.a, t2.b;").
		Check(testkit.Rows("6 6 <nil> <nil>"))
	tk.MustQuery("select /*+ HASH_JOIN(t1, t2) */ * from t2 partition (p1) left join t1 partition (p0) on t2.a = t1.a where t2.a = 6 order by t1.a, t1.b, t2.a, t2.b;").
		Check(testkit.Rows())

	tk.MustQuery("select * from t2 partition (p1) where t2.a = 6;").Check(testkit.Rows())
}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PackageImports   #-}
{-# LANGUAGE TemplateHaskell  #-}
module PureScript.Ide.Internal.Sandbox where

import           Control.Concurrent.STM
import           Control.Lens                (over, _1, _2)
import           Control.Monad.Except
import           "monad-logger" Control.Monad.Logger
import           Control.Monad.Reader
import qualified Data.Map                    as M
import qualified Data.Text                   as T
import           Language.PureScript.Externs
import           Language.PureScript.Names
import           Language.PureScript.Pretty
import           PureScript.Ide.CaseSplit
import           PureScript.Ide.Error
import           PureScript.Ide.Externs
import           PureScript.Ide.State
import           PureScript.Ide.Types
import           PureScript.Ide.Filter
---- Testing stuff

env ss = PscEnvironment
        {
          envStateVar = ss
        , envConfiguration = Configuration "" True
        }

type PscM = ReaderT PscEnvironment (ExceptT PscIdeError (LoggingT IO))

runWithExternsFile
  :: FilePath -> PscM b -> IO (Either PscIdeError b)
runWithExternsFile fp = runWithExternsFiles [fp]

runWithExternsFiles
  :: [FilePath] -> PscM b -> IO (Either PscIdeError b)
runWithExternsFiles fps f = do
  serverState <- newTVarIO emptyPscState
  runStdoutLoggingT $ runExceptT $ flip runReaderT (env serverState) $ do
    efs <- liftIO $ runExceptT $ traverse readExternFile fps
    _ <- either
      (const (error "parsing the externs failed"))
      (traverse insertModule)
      efs
    f

runConway = runWithExternsFile   "../conway-purescript/output/MyModule/externs.json"
runDataList = runWithExternsFile "../conway-purescript/output/Data.List/externs.json"
runPrelude = runWithExternsFile  "../conway-purescript/output/Prelude/externs.json"
runEither = runWithExternsFile   "../conway-purescript/output/Data.Either/externs.json"
runHalogen = runWithExternsFile  "../conway-purescript/output/Halogen.Query.StateF/externs.json"

run = runWithExternsFiles [
 "../conway-purescript/output/MyModule/externs.json"
 , "../conway-purescript/output/Data.List/externs.json"
 , "../conway-purescript/output/Prelude/externs.json"
 , "../conway-purescript/output/Data.Either/externs.json"
 , "../conway-purescript/output/Halogen.Query.StateF/externs.json"
 ]

-- testing :: (PscIde m) => m ()
-- testing = do
--   (Just ef) <- M.lookup (moduleNameFromString "Data.Either") <$> getExternFiles
--   liftIO $ print $ getCtorArgs ef (ProperName "Either")

unsafeRight :: (Either a b) -> b
unsafeRight (Right b) = b

testModuleFilter = moduleFilter ["Halogen.HTML.Indexed"]
testDependencyFilter = dependencyFilter ["Halogen.HTML.Indexed"]
runTest externsFile =
   convertExterns . unsafeRight <$> (runExceptT $ readExternFile externsFile)

runTestFilter filter pscmod =
  applyFilters [filter] [pscmod]

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.dynamodbv2.online.index;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 *
 * Generator random data.
 *
 */
public class RandomDataGenerator {
    private static char[] symbols;
    private final Random random = new Random();

    static {
        StringBuilder tmp = new StringBuilder();
        for (char ch = '0'; ch < '9'; ++ch)
            tmp.append(ch);
        for (char ch = 'a'; ch <= 'z'; ++ch)
            tmp.append(ch);
        symbols = tmp.toString().toCharArray();
    }

    /**
     *
     * Generate next random string
     *
     */
    public String nextRadomString(int length) {
        char[] buf = new char[length];
        for (int index = 0; index < buf.length; ++index)
            buf[index] = symbols[random.nextInt(symbols.length)];
        return new String(buf);
    }

    /**
     *
     * Generate next random string array
     *
     */
    public List<String> nextRandomStringArray(int stringLength) {
        int arrayLength = random.nextInt(10) + 1;
        return this.nextRandomStringArray(stringLength, arrayLength);
    }

    public List<String> nextRandomStringArray(int stringLength, int arrayLength) {
        List<String> array = new ArrayList<String>();
        for (int i = 0; i < arrayLength; i++) {
            array.add(this.nextRadomString(stringLength));
        }
        return array;
    }

    /**
     *
     * Return random array of integer
     *
     */
    public List<String> nextRandomIntArray() {
        List<String> array = new ArrayList<String>();
        int arrayLength = random.nextInt(10) + 1;
        for (int i = 0; i < arrayLength; i++) {
            array.add(Integer.toString(this.nextRandomInt()));
        }
        return array;
    }

    /**
     *
     * Return next random binary array
     *
     */
    public List<ByteBuffer> nextRandomBinaryArray(int binaryLength) {
        List<ByteBuffer> array = new ArrayList<ByteBuffer>();
        int arrayLength = random.nextInt(10) + 1;
        for (int i = 0; i < arrayLength; i++) {
            array.add(this.nextRandomBinary(binaryLength));
        }
        return array;
    }

    /**
     *
     * Generate next binary buffer
     *
     */
    public ByteBuffer nextRandomBinary(int length) {
        char[] buf = new char[length];
        ByteBuffer byteBuffer = ByteBuffer.allocate(length);
        for (int index = 0; index < buf.length; ++index) {
            byte tmp = (byte) symbols[random.nextInt(symbols.length)];
            byteBuffer.put(tmp);
        }
        /** Should reset the position */
        byteBuffer.position(0);
        return byteBuffer;
    }

    /**
     *
     * Generate next random integer
     *
     */
    public int nextRandomInt() {
        return random.nextInt();
    }

    /**
     *
     * Generate next random integer within limit
     *
     */
    public int nextRandomInt(int limit) {
        return random.nextInt(limit);
    }
}


text:
package org.wuxinshui.boosters.designPatterns.abstractFactory;

/**
 * Created with IntelliJ IDEA.
 * User: FujiRen
 * Date: 2016/11/11
 * Time: 10:35
 * To change this template use File | Settings | File Templates.
 */
public class ClamPizza extends Pizza {
    PizzaIngredientFactory ingredientFactory;

    public ClamPizza(PizzaIngredientFactory ingredientFactory) {
        this.ingredientFactory = ingredientFactory;
        prepare();
    }

    @Override
    void prepare() {
        System.out.println("Preparing"+name);
        dough=ingredientFactory.createDough();
        sauce=ingredientFactory.createSauce();
        cheese=ingredientFactory.createCheese();
        clams= ingredientFactory.createClams();
    }
}


text:
import React from 'react'
import { View } from 'react-native'
import PropTypes from 'prop-types'

import SearchList from './SearchListContainer'

const SearchScreen = () => <View />

SearchScreen.navigationOptions = ( { navigation } ) => ( {
  header: <SearchList navigation={navigation} />,
} )

SearchScreen.propTypes = {
  navigation: PropTypes.object.isRequired,
}

export default SearchScreen


text:
package com.feilong.spring.web.servlet.interceptor.browsinghistory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import com.feilong.json.jsonlib.JsonUtil;
import com.feilong.servlet.http.RequestUtil;
import com.feilong.servlet.http.entity.RequestLogSwitch;
import com.feilong.spring.web.servlet.interceptor.AbstractHandlerMethodInterceptorAdapter;
import com.feilong.spring.web.servlet.interceptor.browsinghistory.command.BrowsingHistoryCommand;

/**
 * 商品浏览历史记录.
 *
 *
cookie里面放什么?

 *
 *

 *

 * itemid join--->aes hex 加密格式字符串
 *

 *

 *
 *
why 不放以 name price image等组成的对象?

 *
 *

 *
 *

 *
太大了,cookie的length 也大, 影响性能

 *
如果要做下架的商品不显示等业务控制,还需要再次解析

 *

 *

 *
 *
 *
如果只放itemId 一个值,渲染页面不是还要构造对象吗?

 *
 *

 *

 * 渲染可以通过 cache 提高性能
 *

 *

 *
 * @author feilong
 * @since 1.2.2
 */
public abstract class BrowsingHistoryInterceptor extends AbstractHandlerMethodInterceptorAdapter{

    /** The Constant log. */
    private static final Logger     LOGGER = LoggerFactory.getLogger(BrowsingHistoryInterceptor.class);

    /** The browsing history resolver. */
    private BrowsingHistoryResolver browsingHistoryResolver;

    //---------------------------------------------------------------

    /*
     * (non-Javadoc)
     *
     * @see com.feilong.spring.web.servlet.interceptor.AbstractHandlerMethodInterceptorAdapter#doPostHandle(javax.servlet.http.
     * HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.web.method.HandlerMethod,
     * org.springframework.web.servlet.ModelAndView)
     */
    @Override
    public void doPostHandle(HttpServletRequest request,HttpServletResponse response,HandlerMethod handlerMethod,ModelAndView modelAndView){
        //是否支持解析,有可能在xml里面配置的一些不相关的路径透过到了这个拦截器
        //比如 配置的 mapping path 是 item/* 但是有一些url地址是 item/wishlist 诸如此类的也到了该拦截器
        boolean isSupport = isSupport(request, handlerMethod, modelAndView);
        if (!isSupport){
            if (LOGGER.isInfoEnabled()){
                LOGGER.info(
                                "current request:[{}] not support this BrowsingHistoryInterceptor,maybe you can config path in spring config 'mvc:exclude-mapping' node!",
                                JsonUtil.format(RequestUtil.getRequestInfoMapForLog(request)));
            }
            return;
        }

        //---------------------------------------------------------------
        BrowsingHistoryCommand browsingHistoryCommand = constructBrowsingHistoryCommand(request, response, handlerMethod, modelAndView);
        if (null != browsingHistoryCommand){
            browsingHistoryResolver.add(browsingHistoryCommand, request, response);
            return;
        }

        //---------------------------------------------------------------
        if (LOGGER.isDebugEnabled()){
            LOGGER.debug(
                            "browsingHistoryCommand is null,don't add browsingHistory,request info:{}",
                            JsonUtil.format(RequestUtil.getRequestInfoMapForLog(request, RequestLogSwitch.NORMAL)));
        }
        return;
    }

    //---------------------------------------------------------------

    /**
     * 当前请求,是否支持解析.
     *
     * @param request
     *            the request
     * @param handlerMethod
     *            the handler method
     * @param modelAndView
     *            the model and view
     * @return true, if checks if is support
     * @since 1.5.3
     */
    protected abstract boolean isSupport(HttpServletRequest request,HandlerMethod handlerMethod,ModelAndView modelAndView);

    //---------------------------------------------------------------
    /**
     * Construct browsing history command.
     *

     * 如果返回 null或者empty 那么不会操作cookie
     *

     *
     * @param request
     *            the request
     * @param response
     *            the response
     * @param handlerMethod
     *            the handler method
     * @param modelAndView
     *            the model and view
     * @return the browsing history command
     */
    protected abstract BrowsingHistoryCommand constructBrowsingHistoryCommand(
                    HttpServletRequest request,
                    HttpServletResponse response,
                    HandlerMethod handlerMethod,
                    ModelAndView modelAndView);

    //---------------------------------------------------------------

    /**
     * 设置 the browsing history resolver.
     *
     * @param browsingHistoryResolver
     *            the browsingHistoryResolver to set
     */
    public void setBrowsingHistoryResolver(BrowsingHistoryResolver browsingHistoryResolver){
        this.browsingHistoryResolver = browsingHistoryResolver;
    }

}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//
// This template generates PublicResXFileCodeGenerator compatible code plus some
// useful extensions.
//
// The original version provided by ResXResourceManager is restricted to resource key names
// that are valid c# identifiers to keep this template simple (KISS!).
//
// Us it as it is or as a scaffold to generate the code you need.
//
// As long as you have ResXResourceManager running in the background, the generated code
// will be kept up to date.
//
//------------------------------------------------------------------------------

namespace ResXManager.Translators.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by a text template.
    // To add or remove a member, edit your .ResX file.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("ResXResourceManager", "1.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ResXManager.Translators.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to "Automatically detect HTML"
        /// </summary>
        public static string AutoDetectHtml {
            get {
                return ResourceManager.GetString("AutoDetectHtml", resourceCulture) ?? string.Empty;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to "Max characters per minute"
        /// </summary>
        public static string MaxCharactersPerMinute {
            get {
                return ResourceManager.GetString("MaxCharactersPerMinute", resourceCulture) ?? string.Empty;
            }
        }
    }

    /// <summary>
    /// Keys of all available strings in the applications resx-resources.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGenerated]
    public enum StringResourceKey
    {
        /// <summary>
        ///   Looks up a localized string similar to Automatically detect HTML.
        /// </summary>
        AutoDetectHtml,
        /// <summary>
        ///   Looks up a localized string similar to Max characters per minute.
        /// </summary>
        MaxCharactersPerMinute,
    }

    /// <summary>
    /// Specifies a localized description for an object.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [AttributeUsage(AttributeTargets.All, AllowMultiple=false)]
    public sealed class LocalizedDescriptionAttribute : System.ComponentModel.DescriptionAttribute
    {
        private readonly string _resourceKey;

        /// <summary>
        /// Initializes a new instance of the <see cref="LocalizedDescriptionAttribute"/> class.
        /// </summary>
        /// <param name="resourceKey">The resource key of the associated resource.</param>
        public LocalizedDescriptionAttribute(StringResourceKey resourceKey)
        {
            _resourceKey = resourceKey.ToString();
        }

        /// <summary>
        /// Gets the localized description from the resource id stored in this attribute.
        /// </summary>
        public override string Description
        {
            get
            {
                return Resources.ResourceManager.GetString(_resourceKey);
            }
        }
    }

    /// <summary>
    /// Specifies a localized display name for an object.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [AttributeUsage(AttributeTargets.All, AllowMultiple=false)]
    public sealed class LocalizedDisplayNameAttribute : System.ComponentModel.DisplayNameAttribute
    {
        private readonly string _resourceKey;

        /// <summary>
        /// Initializes a new instance of the <see cref="LocalizedDisplayNameAttribute"/> class.
        /// </summary>
        /// <param name="resourceKey">The resource key of the associated resource.</param>
        public LocalizedDisplayNameAttribute(StringResourceKey resourceKey)
        {
            _resourceKey = resourceKey.ToString();
        }

        /// <summary>
        /// Gets the localized display name from the resource id stored in this attribute.
        /// </summary>
        public override string DisplayName
        {
            get
            {
                return Resources.ResourceManager.GetString(_resourceKey);
            }
        }
    }

    /// <summary>
    /// Specifies a localized category for an object.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [AttributeUsage(AttributeTargets.All, AllowMultiple=false)]
    public sealed class LocalizedCategoryAttribute : System.ComponentModel.CategoryAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="LocalizedCategoryAttribute"/> class.
        /// </summary>
        /// <param name="resourceKey">The resource key of the associated resource.</param>
        public LocalizedCategoryAttribute(StringResourceKey resourceKey)
            : base(resourceKey.ToString())
        {
        }

        /// <summary>
        /// Gets the localized category name from the resource id stored in this attribute.
        /// </summary>
        protected override string GetLocalizedString(string value)
        {
            return Resources.ResourceManager.GetString(value);
        }
    }

    /// <summary>
    /// Specifies a localized display name for an object.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public sealed class LocalizedTextAttribute : global::TomsToolbox.Essentials.TextAttribute
    {
        // This code is generated by Resources.Designer.t4
        // If you get compile errors because you don't use the TomsToolbox.Essentials NuGet package,
        // either remove this part in the Resources.Designer.t4 file, or add a reference to the TomsToolbox.Essentials NuGet package.
        // Just search for this text and follow the instructions above.

        private readonly string _resourceKey;

        /// <summary>
        /// Initializes a new instance of the <see cref="LocalizedTextAttribute"/> class.
        /// </summary>
        /// <param name="key">Any user defined key to specify the usage of this text.</param>
        /// <param name="resourceKey">The resource key of the associated resource.</param>
        public LocalizedTextAttribute(object key, StringResourceKey resourceKey)
            : base(key)
        {
            _resourceKey = resourceKey.ToString();
        }

        /// <summary>
        /// Gets the localized text from the resource id stored in this attribute.
        /// </summary>
        public override string Text
        {
            get
            {
                return Resources.ResourceManager.GetString(_resourceKey);
            }
        }
    }

    /// <summary>
    /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.DataTypeAttribute"/> class.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
    public class DataTypeAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
    {
        private StringResourceKey _resourceKey;

        /// <summary>
        /// Initializes a new instance of the <see cref="DataTypeAttribute"/> class.
        /// </summary>
        public DataTypeAttribute(StringResourceKey resourceKey, System.ComponentModel.DataAnnotations.DataType dataType)
            : base(dataType)
        {
            ResourceKey = resourceKey;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DataTypeAttribute"/> class.
        /// </summary>
        public DataTypeAttribute(StringResourceKey resourceKey, string customDataType)
            : base(customDataType)
        {
            ResourceKey = resourceKey;
        }

        /// <summary>
        /// Gets or sets the resource key.
        /// </summary>
        public StringResourceKey ResourceKey
        {
            get
            {
                return _resourceKey;
            }
            set
            {
                _resourceKey = value;
                ErrorMessageResourceType = typeof(Resources);
                ErrorMessageResourceName = value.ToString();
            }
        }
    }

    /// <summary>
    /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.RangeAttribute"/> class.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
    public class RangeAttribute : System.ComponentModel.DataAnnotations.RangeAttribute
    {
        private StringResourceKey _resourceKey;

        /// <summary>
        /// Initializes a new instance of the <see cref="RangeAttribute"/> class.
        /// </summary>
        public RangeAttribute(StringResourceKey resourceKey, int minimum, int maximum)
            : base(minimum, maximum)
        {
            ResourceKey = resourceKey;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RangeAttribute"/> class.
        /// </summary>
        public RangeAttribute(StringResourceKey resourceKey, double minimum, double maximum)
            : base(minimum, maximum)
        {
            ResourceKey = resourceKey;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RangeAttribute"/> class.
        /// </summary>
        public RangeAttribute(StringResourceKey resourceKey, Type type, string minimum, string maximum)
            : base(type, minimum, maximum)
        {
            ResourceKey = resourceKey;
        }

        /// <summary>
        /// Gets or sets the resource key.
        /// </summary>
        public StringResourceKey ResourceKey
        {
            get
            {
                return _resourceKey;
            }
            set
            {
                _resourceKey = value;
                ErrorMessageResourceType = typeof(Resources);
                ErrorMessageResourceName = value.ToString();
            }
        }
    }

    /// <summary>
    /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.RegularExpressionAttribute"/> class.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
    public class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.RegularExpressionAttribute
    {
        private StringResourceKey _resourceKey;

        /// <summary>
        /// Initializes a new instance of the <see cref="RegularExpressionAttribute"/> class.
        /// </summary>
        public RegularExpressionAttribute(StringResourceKey resourceKey, string pattern)
            : base(pattern)
        {
            ResourceKey = resourceKey;
        }

        /// <summary>
        /// Gets or sets the resource key.
        /// </summary>
        public StringResourceKey ResourceKey
        {
            get
            {
                return _resourceKey;
            }
            set
            {
                _resourceKey = value;
                ErrorMessageResourceType = typeof(Resources);
                ErrorMessageResourceName = value.ToString();
            }
        }
    }

    /// <summary>
    /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.RequiredAttribute"/> class.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
    public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
    {
        private StringResourceKey _resourceKey;

        /// <summary>
        /// Initializes a new instance of the <see cref="RequiredAttribute"/> class.
        /// </summary>
        public RequiredAttribute(StringResourceKey resourceKey)
            : base()
        {
            ResourceKey = resourceKey;
        }

        /// <summary>
        /// Gets or sets the resource key.
        /// </summary>
        public StringResourceKey ResourceKey
        {
            get
            {
                return _resourceKey;
            }
            set
            {
                _resourceKey = value;
                ErrorMessageResourceType = typeof(Resources);
                ErrorMessageResourceName = value.ToString();
            }
        }
    }

    /// <summary>
    /// A localizable version of the <see cref="System.ComponentModel.DataAnnotations.StringLengthAttribute"/> class.
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCode("ResXResourceManager", "1.0.0.0")]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false)]
    public class StringLengthAttribute : System.ComponentModel.DataAnnotations.StringLengthAttribute
    {
        private StringResourceKey _resourceKey;

        /// <summary>
        /// Initializes a new instance of the <see cref="StringLengthAttribute"/> class.
        /// </summary>
        public StringLengthAttribute(StringResourceKey resourceKey, int maximumLength)
            : base(maximumLength)
        {
            ResourceKey = resourceKey;
        }

        /// <summary>
        /// Gets or sets the resource key.
        /// </summary>
        public StringResourceKey ResourceKey
        {
            get
            {
                return _resourceKey;
            }
            set
            {
                _resourceKey = value;
                ErrorMessageResourceType = typeof(Resources);
                ErrorMessageResourceName = value.ToString();
            }
        }
    }

}


text:
package api

import (
	"config"
	"fmt"
	"net/http"
	"mylog"
)

// Start 根据配置参数启动Api服务
func Start(config config.ApiConfig) {
	if !config.Enable {
		return
	}
	auth := config.BasicAuth
	var basicAuthMedia = func(ctx Context) error {
		if !auth.Enable {
			return nil
		}
		if name, pass, ok := ctx.r.BasicAuth(); ok && name == auth.Username && pass == auth.Password {
			return nil
		}
		ctx.w.Header().Add("WWW-Authenticate", `Basic realm="Login Required"`)
		ctx.w.WriteHeader(401)
		return fmt.Errorf("用户名密码错误")
	}
	handler := &RestHandler{}
	handler.Get("/api/config", createHandleFunc(getConfig, basicAuthMedia))
	handler.Get("/api/config/rules", createHandleFunc(getRulesConfig, basicAuthMedia))
	handler.Get("r:/api/config/rules/[\\S\\s]+", createHandleFunc(getOneRulesConfig, basicAuthMedia))
	handler.Get("/api/config/api-info", createHandleFunc(getApiConfig, basicAuthMedia))

	handler.Get("/api/context", createHandleFunc(getContext, basicAuthMedia))
	handler.Post("/api/context", createHandleFunc(postRule, basicAuthMedia))

	handler.Post("r:/api/context/[\\S\\s]+/stop", createHandleFunc(ruleStop, basicAuthMedia))
	handler.Post("r:/api/context/[\\S\\s]+/start", createHandleFunc(ruleStart, basicAuthMedia))
	handler.Post("r:/api/context/[\\S\\s]+/restart", createHandleFunc(ruleRestart, basicAuthMedia))
	// 静态文件处理
	handler.Get("r:/[\\s\\S]*", createHandle(http.FileServer(http.Dir("./static/")), basicAuthMedia))

	go func() {
		err := http.ListenAndServe(":"+config.Port, handler)
		if err != nil {
			mylog.Error("启动api服务失败", err)
		}
	}()
	mylog.Info("启动api服务中", config.Port)
}


text:
var cradle = require("cradle"),
	http = require("http"),
	urlParser = require("url"),
	parser = require("xml2json"),
	config = require("../configuration/config.js"),
	utils = require("../configuration/utils.js");

var harvested = new(cradle.Connection)(config.dbInfo.dbHost, config.dbInfo.dbPort, { cache: false }).database(config.dbInfo.databases.dbHarvestName);

function validateInputFormat(input, data) {
	try { inputJson = parser.toJson(data, { object: true, reversible: true }); }
	catch(err) { return [false, "URL returned an invalid XML document."]; }

	switch (input) {
	case "atom":
		if (inputJson.hasOwnProperty("feed")) {
			return [true, inputJson];
		} else { return [false, "URL did not return a valid Atom Feed."]; }
	case "iso":
		if (inputJson.hasOwnProperty("gmd:MD_Metadata")) {
			return [true, inputJson];
		} else { return [false, "URL did not return a valid ISO 19139 XML document."]; }
	}
}

/** MIDDLEWARE TO HARVEST AN EXTERNAL RESOURCE **/
exports.harvestResource = function(req, res, next) {
	if (!req.body.harvestFormat) {
		res.redirect("/new-harvest/");
	} else {
		urlBits = urlParser.parse(req.body.url, false, true);
		getOptions = { host: urlBits.hostname, port: (urlBits.port || 80), path: urlBits.pathname + ( urlBits.search || "" ) };
		http.get(getOptions, function(proxyResponse) {
			data = "";
			proxyResponse.on("data", function(chunk) { data += chunk; });
			proxyResponse.on("end", function() {
				formatted = validateInputFormat(req.body.harvestFormat, data);
				if (!formatted[0]) { utils.renderToResponse(req, res, "errorResponse", { message: formatted[1], status: 500 }); }
				else {
					req.harvestedJson = formatted[1];
					next();
				}
			});
		}).on("error", function(err) {
			utils.renderToResponse(req, res, "errorResponse", { message: "The URL you entered was invalid. Please try again." });
		});
	}
};

/** MIDDLEWARE FOR SAVING A HARVESTED RESOURCE **/
//req.harvestedJson must have already been set by prior middleware.
exports.saveHarvestedResource = function(req, res, next) {
	switch (req.body.harvestFormat) {
	case "atom":
		entryConString = req.harvestedJson.feed.entry.constructor.toString();
		if (entryConString.indexOf("Array") != -1) {
			entries = req.harvestedJson.feed.entry;
		} else if (entryConString.indexOf("Object") != -1) {
			entries = [ req.harvestedJson.feed.entry ];
		} else { entries = []; }

		function checkCompletion() {
			if (req.harvestIds.length == entries.length) { next(); }
		}

		req.harvestIds = [];
		for (var e in entries) {
			harvested.save(entries[e], function(err, dbRes) {
				if (err) { utils.renderToResponse(req, res, "errorResponse", { message: "Error saving your harvested resource.", status: 500 }); }
				else {
					req.harvestIds.push(dbRes.id);
					checkCompletion();
				}
			});
		}
		break;
	case "iso":
		harvested.save(req.harvestedJson, function(err, dbRes) {
			if (err) { utils.renderToResponse(req, res, "errorResponse", { message: "Error saving your harvested resource.", status: 500 }); }
			else {
				req.harvestId = dbRes.id;
				next();
			}
		});
	}
};

/** MIDDLEWARE FOR RETREIVING A SINGLE HARVESTED RESOURCE THROUGH A PARTICULAR INPUT VIEW **/
//req.harvestId or req.harvestIds must have already been set by prior middleware.
exports.viewHarvestedResource = function(req, res, next) {
	function completionCheck() {
		if (req.resources.length == ids.length) { next(); }
	}
	req.resources = [], ids = req.harvestIds || [ req.harvestId ];
	for (var i in ids) {
		harvested.view("inputs/" + req.body.harvestFormat, { key: ids[i] }, function(err, dbRes) {
			if (err) { utils.renderToResponse(req, res, "errorResponse", { message: "Error retrieving views from the harvest database", status: 500 }); }
			else {
				if (dbRes.length == 0) { req.resources.push(null); }
				else {
					theResource = dbRes[0].value;
					if (!theResource.hasOwnProperty("HarvestInformation")) { theResource.HarvestInformation = {}; }
					theResource.HarvestInformation.HarvestRecordId = req.harvestId;
					theResource.HarvestInformation.HarvestURL = req.body.url;
					theResource.HarvestInformation.HarvestDate = utils.getCurrentDate();

					if (req.body.collection && req.body.collection != "") {
						theResource.Collections = [ req.body.collection ];
					}

					req.resources.push(theResource);
				}
				completionCheck();
			}
		});
	}
};


text:
<!DOCTYPE html>
<html lang="en">

{% include head.html %}

<body>

    {% include nav.html %}

    {{ content }}

    {% include footer.html %}

    {% include ga.html %}

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_CHTML,Safe"></script>

</body>

</html>


text: module ChromeTools; end


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

title: FileSystem
---

FileSystem
==========

このオブジェクトはファイルシステムを表します。

プロパティー
----------

- __name:__ ファイルシステムの名前を表します _(DOMString)_
- __root:__ ファイルシステムのルートディレクトリを表します _(DirectoryEntry)_

詳細
-------

`FileSystem` オブジェクトはファイルシステムの情報を表します。ファイルシステムの名前は既にあるファイルシステムに対して一意になります。 root プロパティーはファイルシステムのルートディレクトリを表す `[DirectoryEntry](../directoryentry/directoryentry.html)` オブジェクトを保持します。

サポートされているプラットフォーム
-------------------

- Android
- BlackBerry WebWorks (OS 5.0 以上)
- iOS
- Windows Phone 7 (Mango)

[File](../fileobj/fileobj.html) System の使用例
-------------------------

    function onSuccess(fileSystem) {
        console.log(fileSystem.name);
        console.log(fileSystem.root.name);
    }

    // ファイルシステムをリクエスト
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, null);

詳細な使用例
------------

    <!DOCTYPE html>

        <title>File System の使用例</title>

Example

File System


text:
"""
    solace.badges
    ~~~~~~~~~~~~~

    This module implements the badge system.

    :copyright: (c) 2010 by the Solace Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from operator import attrgetter

from solace.i18n import lazy_gettext, _
from solace.utils.remoting import RemoteObject

def try_award(event, *args):
    """Tries to avard a badge for the given event.  The events correspond
    to the `on_X` callbacks on the badges, just without the `on_` prefix.
    """
    lookup = attrgetter('on_' + event)
    for badge in badge_list:
        cb = lookup(badge)
        if cb is None:
            continue
        user = cb(*args)
        if user is not None:
            if isinstance(user, tuple):
                user, payload = user
            else:
                payload = None
            if badge.single_awarded and badge in user.badges:
                continue
            user._badges.append(UserBadge(badge, payload))
            # inactive or banned users don't get messages.
            if user.is_active and not user.is_banned:
                UserMessage(user, _(u'You earned the "%s" badge') % badge.name)

_numeric_levels = dict(zip(('bronce', 'silver', 'gold', 'platin'),
                           range(4)))

class Badge(RemoteObject):
    """Represents a badge.

    It can react to the following events::

        on_vote = lambda user, post, delta
        on_accept = lambda user, post, answer
        on_reply = lambda user, post
        on_new_topic = lambda user, topic
        on_edit = lambda user, post
    """

    remote_object_type = 'solace.badge'
    public_fields = ('level', 'identifier', 'name', 'description')

    def __init__(self, level, identifier, name, description=None,
                 single_awarded=False,
                 on_vote=None, on_accept=None, on_reply=None,
                 on_new_topic=None, on_edit=None):
        assert level in ('bronce', 'silver', 'gold', 'platin')
        assert len(identifier) <= 30
        self.level = level
        self.identifier = identifier
        self.name = name
        self.single_awarded = single_awarded
        self.description = description
        self.on_vote = on_vote
        self.on_accept = on_accept
        self.on_reply = on_reply
        self.on_new_topic = on_new_topic
        self.on_edit = on_edit

    @property
    def numeric_level(self):
        return _numeric_levels[self.level]

    def get_url_values(self):
        return 'badges.show_badge', {'identifier': self.identifier}

    def __repr__(self):
        return '<%s \'%s\' (%s)>' % (
            type(self).__name__,
            self.name.encode('utf-8'),
            ('bronce', 'silver', 'gold', 'platin')[self.numeric_level]
        )

def _try_award_special_answer(post, badge, votes_required):
    """Helper for nice and good answer."""
    pid = str(post.id)
    user = post.author
    for user_badge in user._badges:
        if user_badge.badge == badge and \
           user_badge.payload == pid:
            return
    if post.is_answer and post.votes >= votes_required:
        return user, pid

def _try_award_self_learner(post):
    """Helper for the self learner badge."""
    pid = str(post.id)
    user = post.author
    for user_badge in user._badges:
        if user_badge.badge == SELF_LEARNER and \
           user_badge.payload == pid:
            return
    if post.is_answer and post.author == post.topic.author \
       and post.votes >= 3:
        return user, pid

def _try_award_reversal(post):
    """Helper for the reversal badge."""
    pid = str(post.id)
    user = post.author
    for user_badge in user._badges:
        if user_badge.badge == REVERSAL and \
           user_badge.payload == pid:
            return
    if post.is_answer and post.votes >= 20 and \
       post.topic.votes <= -5:
        return user, pid

CRITIC = Badge('bronce', 'critic', lazy_gettext(u'Critic'),
    lazy_gettext(u'First down vote'),
    single_awarded=True,
    on_vote=lambda user, post, delta:
        user if delta < 0 and user != post.author else None
)

SELF_CRITIC = Badge('silver', 'self-critic', lazy_gettext(u'Self-Critic'),
    lazy_gettext(u'First downvote on own reply or question'),
    single_awarded=True,
    on_vote=lambda user, post, delta:
        user if delta < 0 and user == post.author else None
)

EDITOR = Badge('bronce', 'editor', lazy_gettext(u'Editor'),
    lazy_gettext(u'First edited post'),
    single_awarded=True,
    on_edit=lambda user, post: user
)

INQUIRER = Badge('bronce', 'inquirer', lazy_gettext(u'Inquirer'),
    lazy_gettext(u'First asked question'),
    single_awarded=True,
    on_new_topic=lambda user, topic: user
)

TROUBLESHOOTER = Badge('silver', 'troubleshooter',
    lazy_gettext(u'Troubleshooter'),
    lazy_gettext(u'First answered question'),
    single_awarded=True,
    on_accept=lambda user, topic, post: post.author if post else None
)

NICE_ANSWER = Badge('bronce', 'nice-answer', lazy_gettext(u'Nice Answer'),
    lazy_gettext(u'Answer was upvoted 10 times'),
    on_accept=lambda user, topic, post: _try_award_special_answer(post,
        NICE_ANSWER, 10) if post else None,
    on_vote=lambda user, post, delta: _try_award_special_answer(post,
        NICE_ANSWER, 10)
)

GOOD_ANSWER = Badge('silver', 'good-answer', lazy_gettext(u'Good Answer'),
    lazy_gettext(u'Answer was upvoted 25 times'),
    on_accept=lambda user, topic, post: _try_award_special_answer(post,
        GOOD_ANSWER, 25) if post else None,
    on_vote=lambda user, post, delta: _try_award_special_answer(post,
        GOOD_ANSWER, 25)
)

GREAT_ANSWER = Badge('gold', 'great-answer', lazy_gettext(u'Great Answer'),
    lazy_gettext(u'Answer was upvoted 75 times'),
    on_accept=lambda user, topic, post: _try_award_special_answer(post,
        GOOD_ANSWER, 75) if post else None,
    on_vote=lambda user, post, delta: _try_award_special_answer(post,
        GOOD_ANSWER, 75)
)

UNIQUE_ANSWER = Badge('platin', 'unique-answer', lazy_gettext(u'Unique Answer'),
    lazy_gettext(u'Answer was upvoted 150 times'),
    on_accept=lambda user, topic, post: _try_award_special_answer(post,
        GOOD_ANSWER, 150) if post else None,
    on_vote=lambda user, post, delta: _try_award_special_answer(post,
        GOOD_ANSWER, 150)
)

REVERSAL = Badge('gold', 'reversal', lazy_gettext(u'Reversal'),
    lazy_gettext(u'Provided answer of +20 score to a question of -5 score'),
    on_accept=lambda user, topic, post: _try_award_reversal(post) if post else None,
    on_vote=lambda user, post, delta: _try_award_reversal(post)
)

SELF_LEARNER = Badge('silver', 'self-learner', lazy_gettext(u'Self-Learner'),
    lazy_gettext(u'Answered your own question with at least 4 upvotes'),
    on_accept=lambda user, topic, post: _try_award_self_learner(post) if post else None,
    on_vote=lambda user, post, delta: _try_award_self_learner(post)
)

#: list of all badges
badge_list = [CRITIC, EDITOR, INQUIRER, TROUBLESHOOTER, NICE_ANSWER,
              GOOD_ANSWER, SELF_LEARNER, SELF_CRITIC, GREAT_ANSWER,
              UNIQUE_ANSWER, REVERSAL]

#: all the badges by key
badges_by_id = dict((x.identifier, x) for x in badge_list)

# circular dependencies
from solace.models import UserBadge, UserMessage


text:
namespace drive {

class DriveSystemServiceBrowserTest : public InProcessBrowserTest {
};

// Verify DriveSystemService is created during login.
IN_PROC_BROWSER_TEST_F(DriveSystemServiceBrowserTest, CreatedDuringLogin) {
  EXPECT_TRUE(DriveSystemServiceFactory::FindForProfile(browser()->profile()));
}

}  // namespace drive


text:
using UnityEngine;
using System.Collections;

public class FireControl : MonoBehaviour {

    public ProjectileSpawner spawner;
    public TargetControl targeting;
    public AimControl aim;

    [SerializeField]
    bool fire = false;
    public float fireRate;

	// Use this for initialization
	void Start () {
        StartCoroutine(FireLoop());
	}

    private IEnumerator FireLoop() {
        while (true) {
            // case when target is destroyed or not found
            if (!aim.target) {
                aim.SetTarget(targeting.RequestNewTarget());
            }
            if (fire)
            {

                if (aim.target)
                {
                    Projectile projectile = spawner.Spawn();
                    projectile.OnInstantiated(aim.target.position);

                    yield return new WaitForSeconds(fireRate);
                }
            }

            yield return null;
        }
    }

    internal void SetNewTarget(Transform target) {
        if (target) {
            fire = true;
            aim.SetTarget( target);
        }
        else
        {
            fire = false;
            aim.SetTarget(null);
        }
    }

    internal void OnZeroTargets() {
        fire = false;
    }

    [System.Obsolete()]
    internal void OnTargetExit(Transform target)
    {
        if (aim.target == target && target != null)
        {
            aim.target=targeting.RequestNewTarget();
        }
    }
}


text:
package org.apache.beam.sdk.metrics;

/**
 * Marker interface for all user-facing metrics.
 */
public interface Metric { }


text:
from .es_query import HQESQuery
from . import filters

class UserES(HQESQuery):
    index = 'users'
    default_filters = {
        'not_deleted': {"term": {"base_doc": "couchuser"}},
        'active': {"term": {"is_active": True}},
    }
    @property
    def builtin_filters(self):
        return [
            domain,
            created,
            mobile_users,
            web_users,
            user_ids,
            location,
        ] + super(UserES, self).builtin_filters

    def show_inactive(self):
        return self.remove_default_filter('active')

def domain(domain):
    return filters.OR(
        filters.term("domain.exact", domain),
        filters.term("domain_memberships.domain.exact", domain)
    )

def username(username):
    return filters.term("username.exact", username)

def web_users():
    return filters.doc_type("WebUser")

def mobile_users():
    return filters.doc_type("CommCareUser")

def unknown_users():
    return filters.doc_type("UnknownUser")

def admin_users():
    return filters.doc_type("AdminUser")

def demo_users():
    return username("demo_user")

def created(gt=None, gte=None, lt=None, lte=None):
    return filters.date_range('created_on', gt, gte, lt, lte)

def user_ids(user_ids):
    return filters.term("_id", list(user_ids))

def location(location_id):
    return filters.term('location_id', location_id)


text:
module Fog
  module OracleCloud
    class SOA
      class Real

      	def get_instance(instance_id)
 					response = request(
            :expects  => 200,
            :method   => 'GET',
            :path     => "/paas/service/soa/api/v1.1/instances/#{@identity_domain}/#{instance_id}"
          )
          response
        end
      end

      class Mock
        def get_instance(name)
          response = Excon::Response.new
          if instance = self.data[:instances][name]
            case instance['status']
            when 'Terminating'
              if Time.now - self.data[:deleted_at][name] >= Fog::Mock.delay
                self.data[:deleted_at].delete(name)
                self.data[:instances].delete(name)
              end
            when 'In Progress'
              if Time.now - self.data[:created_at][name] >= Fog::Mock.delay
                self.data[:instances][name]['status'] = 'Running'
                instance = self.data[:instances][name]
                self.data[:created_at].delete(name)
              end
            end
            response.status = 200
            response.body = instance
            response
          else
            raise Fog::OracleCloud::SOA::NotFound.new("SOA #{name} does not exist");
          end
        end
      end
    end
  end
end


text:
const promisify = require('util').promisify;
const fs = require('fs');
const exec = promisify(require('child_process').exec);
const mkdir = promisify(fs.mkdir);
const writeFile = promisify(fs.writeFile);
const assert = require('assert');

const code = `
const update = require('immutability-helper');

const state1 = ['x'];
const state2 = update(state1, {$push: ['y']})
console.log(JSON.stringify(state2));
`

Promise.resolve()
  .then(() => mkdir('test-js-dir'))
  .then(() => process.chdir('test-js-dir'))
  .then(() => exec('npm init -y'))
  .then(() => exec('npm install ../'))
  .then(() => writeFile('foo.js', code))
  .then(() => exec('node foo'))
  .then(result => assert.strictEqual(result.stdout.trim(), '["x","y"]'))
  .catch(error => console.error('uncaught error:', error));


text:
module Feldspar.Core.Frontend.Logic
where

import Prelude hiding ((&&), (||))
import Feldspar.Core.Constructs
import Feldspar.Core.Constructs.Logic
import Feldspar.Core.Frontend.Literal
import Feldspar.Core.Frontend.Condition

import Language.Syntactic

infixr 3 &&
infixr 3 &&*
infixr 2 ||
infixr 2 ||*

not :: Data Bool -> Data Bool
not = sugarSymF Not

(&&) :: Data Bool -> Data Bool -> Data Bool
(&&) = sugarSymF And

(||) :: Data Bool -> Data Bool -> Data Bool
(||) = sugarSymF Or

-- | Lazy conjunction, second argument only evaluated if necessary
(&&*) :: Data Bool -> Data Bool -> Data Bool
a &&* b =  a ? b $ false

-- | Lazy disjunction, second argument only evaluated if necessary
(||*) :: Data Bool -> Data Bool -> Data Bool
a ||* b = a ? true $ b


text:
require 'test_helper'

module ActiveModel
  class Serializer
    module Adapter
      class JsonApi
        class IncludeParamTest < ActiveSupport::TestCase
          IncludeParamAuthor = Class.new(::Model) do
            associations :tags, :posts
          end

          class CustomCommentLoader
            def all
              [{ foo: 'bar' }]
            end
          end

          class TagSerializer < ActiveModel::Serializer
            attributes :id, :name
          end

          class IncludeParamAuthorSerializer < ActiveModel::Serializer
            class_attribute :comment_loader

            has_many :tags, serializer: TagSerializer do
              link :self, '//example.com/link_author/relationships/tags'
              include_data :if_sideloaded
            end

            has_many :unlinked_tags, serializer: TagSerializer do
              include_data :if_sideloaded
            end

            has_many :posts, serializer: PostWithTagsSerializer do
              include_data :if_sideloaded
            end
            has_many :locations do
              include_data :if_sideloaded
            end
            has_many :comments do
              include_data :if_sideloaded
              IncludeParamAuthorSerializer.comment_loader.all
            end
          end

          def setup
            IncludeParamAuthorSerializer.comment_loader = Class.new(CustomCommentLoader).new
            @tag = Tag.new(id: 1337, name: 'mytag')
            @author = IncludeParamAuthor.new(
              id: 1337,
              tags: [@tag]
            )
          end

          def test_relationship_not_loaded_when_not_included
            expected = {
              links: {
                self: '//example.com/link_author/relationships/tags'
              }
            }

            @author.define_singleton_method(:read_attribute_for_serialization) do |attr|
              fail 'should not be called' if attr == :tags
              super(attr)
            end

            assert_relationship(:tags, expected)
          end

          def test_relationship_included
            expected = {
              data: [
                {
                  id: '1337',
                  type: 'tags'
                }
              ],
              links: {
                self: '//example.com/link_author/relationships/tags'
              }
            }

            assert_relationship(:tags, expected, include: :tags)
          end

          def test_sideloads_included
            expected = [
              {
                id: '1337',
                type: 'tags',
                attributes: { name: 'mytag' }
              }
            ]
            hash = result(include: :tags)
            assert_equal(expected, hash[:included])
          end

          def test_nested_relationship
            expected = {
              data: [
                {
                  id: '1337',
                  type: 'tags'
                }
              ],
              links: {
                self: '//example.com/link_author/relationships/tags'
              }
            }

            expected_no_data = {
              links: {
                self: '//example.com/link_author/relationships/tags'
              }
            }

            assert_relationship(:tags, expected, include: [:tags, { posts: :tags }])

            @author.define_singleton_method(:read_attribute_for_serialization) do |attr|
              fail 'should not be called' if attr == :tags
              super(attr)
            end

            assert_relationship(:tags, expected_no_data, include: { posts: :tags })
          end

          def test_include_params_with_no_block
            @author.define_singleton_method(:read_attribute_for_serialization) do |attr|
              fail 'should not be called' if attr == :locations
              super(attr)
            end

            expected = { meta: {} }

            assert_relationship(:locations, expected)
          end

          def test_block_relationship
            expected = {
              data: [
                { 'foo' => 'bar' }
              ]
            }

            assert_relationship(:comments, expected, include: [:comments])
          end

          def test_node_not_included_when_no_link
            expected = nil
            assert_relationship(:unlinked_tags, expected)
          end

          private

          def result(opts)
            opts = { adapter: :json_api }.merge(opts)
            serializable(@author, opts).serializable_hash
          end

          def assert_relationship(relationship_name, expected, opts = {})
            hash = result(opts)
            assert_equal(expected, hash[:data][:relationships][relationship_name])
          end
        end
      end
    end
  end
end


text:
int PutRec( int filehandle, void *buffer, int sizeofrec, long fileptr )
{
	if ( -1 == lseek( filehandle, fileptr, 0 ) ) return( -1 );
	if ( sizeofrec != write( filehandle, buffer, sizeofrec ) ) return( -1 );
	return( 0 );
}


text:
//  Copyright 2018 Twitter. All rights reserved.
//
//  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.twitter.heron.streamlet.scala

import java.util.logging.{Level, Logger}

import com.twitter.heron.api.HeronSubmitter
import com.twitter.heron.api.exception.AlreadyAliveException
import com.twitter.heron.api.exception.InvalidTopologyException
import com.twitter.heron.streamlet.Config
import com.twitter.heron.streamlet.scala.impl.BuilderImpl

/**
  * Runner is used to run a topology that is built by the builder.
  * It exports a sole function called run that takes care of constructing the topology
  */
class Runner {

  private val LOG = Logger.getLogger(classOf[Runner].getName)

  /**
    * Runs the computation
    *
    * @param name    The name of the topology
    * @param config  Any config that is passed to the topology
    * @param builder The builder used to keep track of the sources.
    */
  def run(name: String, config: Config, builder: Builder): Unit = {
    val builderImpl = builder.asInstanceOf[BuilderImpl]
    val topologyBuilder = builderImpl.build
    try {
      HeronSubmitter.submitTopology(name,
                                    config.getHeronConfig,
                                    topologyBuilder.createTopology)
    } catch {
      case e @ (_: AlreadyAliveException | _: InvalidTopologyException) =>
        LOG.log(Level.SEVERE, "Topology could not be submitted", e)
    }
  }
}


text:
package net.vidageek.mirror.provider.java;

import static java.lang.String.format;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import net.vidageek.mirror.exception.MirrorException;
import net.vidageek.mirror.provider.GenericTypeAccessor;
import net.vidageek.mirror.provider.ParameterizedElementReflectionProvider;

/**
 * @author dnfeitosa
 */
public class PureJavaParameterizedElementReflectionProvider implements ParameterizedElementReflectionProvider {

	private final GenericTypeAccessor accessor;

	public PureJavaParameterizedElementReflectionProvider(GenericTypeAccessor accessor) {
		this.accessor = accessor;
	}

	public Class<?> getTypeAtPosition(int index) {
		ParameterizedType genericType;
		try {
			genericType = (ParameterizedType) accessor.getGenericTypes();
		} catch (ClassCastException e) {
			throw new MirrorException("Element is not parameterized with a generic type.", e);
		}
		Type[] typeArguments = genericType.getActualTypeArguments();
		try {
			return (Class<?>) typeArguments[index];
		} catch (ArrayIndexOutOfBoundsException e) {
			throw new MirrorException(format("No type declared at position %d.", index));
		}
	}
}


text:
export class Configuration {

    /*-------------------------------------------------------------------------
     * docomment
     *-----------------------------------------------------------------------*/
    public static KEY_DOCOMMENT = 'docomment';
    public static SYNTAX = 'syntax';
    public static ACTIVATE_ON_ENTER = 'activateOnEnter';
    public static ADVANCED = 'advanced';

    /*-------------------------------------------------------------------------
     * files
     *-----------------------------------------------------------------------*/
    public static KEY_FILES = 'files';
    public static EOL = 'eol';

    /*-------------------------------------------------------------------------
     * editor
     *-----------------------------------------------------------------------*/
    public static KEY_EDITOR = 'editor';
    public static INSERT_SPACES = 'insertSpaces';
    public static DETECT_IDENTATION = 'detectIndentation';

    public syntax: CommentSyntax;
    public activateOnEnter: boolean;
    public advanced: Object;
    public eol: string;
    public insertSpaces: boolean;
    public detectIdentation: boolean;

}

export enum CommentSyntax {
    single = 'single', // three slashes ///
    delimited = 'delimited', // start with a slash and two stars /**
}


text:
<?php

namespace Puli\Manager\Module;

use Exception;
use InvalidArgumentException;
use Puli\Manager\Api\Context\ProjectContext;
use Puli\Manager\Api\Module\RootModuleFile;
use Puli\Manager\Api\Module\RootModuleFileManager;
use Puli\Manager\Config\AbstractConfigManager;
use Puli\Manager\Json\JsonStorage;
use ReflectionClass;
use ReflectionException;
use Webmozart\Expression\Expr;
use Webmozart\Expression\Expression;

/**
 * Manages changes to the root module file.
 *
 * Use this class to make persistent changes to the puli.json of a project.
 * Whenever you call methods in this class, the changes will be written to disk.
 *
 * @since  1.0
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class RootModuleFileManagerImpl extends AbstractConfigManager implements RootModuleFileManager
{
    /**
     * @var ProjectContext
     */
    private $context;

    /**
     * @var RootModuleFile
     */
    private $rootModuleFile;

    /**
     * @var JsonStorage
     */
    private $jsonStorage;

    /**
     * Creates a new module file manager.
     *
     * @param ProjectContext $context     The project context
     * @param JsonStorage    $jsonStorage The module file storage.
     */
    public function __construct(ProjectContext $context, JsonStorage $jsonStorage)
    {
        $this->context = $context;
        $this->rootModuleFile = $context->getRootModuleFile();
        $this->jsonStorage = $jsonStorage;
    }

    /**
     * {@inheritdoc}
     */
    public function getConfig()
    {
        return $this->rootModuleFile->getConfig();
    }

    /**
     * {@inheritdoc}
     */
    public function getContext()
    {
        return $this->context;
    }

    /**
     * {@inheritdoc}
     */
    public function getModuleFile()
    {
        return $this->rootModuleFile;
    }

    /**
     * {@inheritdoc}
     */
    public function getModuleName()
    {
        return $this->rootModuleFile->getModuleName();
    }

    /**
     * {@inheritdoc}
     */
    public function setModuleName($moduleName)
    {
        if ($moduleName === $this->rootModuleFile->getModuleName()) {
            return;
        }

        $previousName = $this->rootModuleFile->getModuleName();

        $this->rootModuleFile->setModuleName($moduleName);

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            $this->rootModuleFile->setModuleName($previousName);

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function addPluginClass($pluginClass)
    {
        if ($this->rootModuleFile->hasPluginClass($pluginClass)) {
            // Already installed locally
            return;
        }

        $this->validatePluginClass($pluginClass);

        $previousClasses = $this->rootModuleFile->getPluginClasses();

        $this->rootModuleFile->addPluginClass($pluginClass);

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            $this->rootModuleFile->setPluginClasses($previousClasses);

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removePluginClass($pluginClass)
    {
        if (!$this->rootModuleFile->hasPluginClass($pluginClass)) {
            return;
        }

        $previousClasses = $this->rootModuleFile->getPluginClasses();

        $this->rootModuleFile->removePluginClass($pluginClass);

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            $this->rootModuleFile->setPluginClasses($previousClasses);

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removePluginClasses(Expression $expr)
    {
        $save = false;
        $previousClasses = $this->rootModuleFile->getPluginClasses();

        foreach ($previousClasses as $pluginClass) {
            if ($expr->evaluate($pluginClass)) {
                $this->rootModuleFile->removePluginClass($pluginClass);
                $save = true;
            }
        }

        if (!$save) {
            return;
        }

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            $this->rootModuleFile->setPluginClasses($previousClasses);

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function clearPluginClasses()
    {
        $this->removePluginClasses(Expr::true());
    }

    /**
     * {@inheritdoc}
     */
    public function hasPluginClass($pluginClass)
    {
        return $this->rootModuleFile->hasPluginClass($pluginClass);
    }

    /**
     * {@inheritdoc}
     */
    public function hasPluginClasses(Expression $expr = null)
    {
        if (!$expr) {
            return $this->rootModuleFile->hasPluginClasses();
        }

        foreach ($this->rootModuleFile->getPluginClasses() as $pluginClass) {
            if ($expr->evaluate($pluginClass)) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getPluginClasses()
    {
        return $this->rootModuleFile->getPluginClasses();
    }

    /**
     * {@inheritdoc}
     */
    public function findPluginClasses(Expression $expr)
    {
        $pluginClasses = array();

        foreach ($this->rootModuleFile->getPluginClasses() as $pluginClass) {
            if ($expr->evaluate($pluginClass)) {
                $pluginClasses[] = $pluginClass;
            }
        }

        return $pluginClasses;
    }

    /**
     * {@inheritdoc}
     */
    public function setExtraKey($key, $value)
    {
        $previouslySet = $this->rootModuleFile->hasExtraKey($key);
        $previousValue = $this->rootModuleFile->getExtraKey($key);

        if ($value === $previousValue) {
            return;
        }

        $this->rootModuleFile->setExtraKey($key, $value);

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            if ($previouslySet) {
                $this->rootModuleFile->setExtraKey($key, $previousValue);
            } else {
                $this->rootModuleFile->removeExtraKey($key);
            }

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function setExtraKeys(array $values)
    {
        $previousValues = array();
        $previouslyUnset = array();

        foreach ($values as $key => $value) {
            if ($this->rootModuleFile->hasExtraKey($key)) {
                if ($value !== $previous = $this->rootModuleFile->getExtraKey($key)) {
                    $previousValues[$key] = $previous;
                }
            } else {
                $previouslyUnset[$key] = true;
            }
        }

        if (!$previousValues && !$previouslyUnset) {
            return;
        }

        $this->rootModuleFile->setExtraKeys($values);

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            foreach ($values as $key => $value) {
                if (isset($previouslyUnset[$key])) {
                    $this->rootModuleFile->removeExtraKey($key);
                } else {
                    $this->rootModuleFile->setExtraKey($key, $previousValues[$key]);
                }
            }

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeExtraKey($key)
    {
        if (!$this->rootModuleFile->hasExtraKey($key)) {
            return;
        }

        $previousValue = $this->rootModuleFile->getExtraKey($key);

        $this->rootModuleFile->removeExtraKey($key);

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            $this->rootModuleFile->setExtraKey($key, $previousValue);

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function removeExtraKeys(Expression $expr)
    {
        $previousValues = $this->rootModuleFile->getExtraKeys();
        $save = false;

        foreach ($this->rootModuleFile->getExtraKeys() as $key => $value) {
            if ($expr->evaluate($key)) {
                $this->rootModuleFile->removeExtraKey($key);
                $save = true;
            }
        }

        if (!$save) {
            return;
        }

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            $this->rootModuleFile->setExtraKeys($previousValues);

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function clearExtraKeys()
    {
        $previousValues = $this->rootModuleFile->getExtraKeys();

        if (!$previousValues) {
            return;
        }

        $this->rootModuleFile->clearExtraKeys();

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            $this->rootModuleFile->setExtraKeys($previousValues);

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function hasExtraKey($key)
    {
        return $this->rootModuleFile->hasExtraKey($key);
    }

    /**
     * {@inheritdoc}
     */
    public function hasExtraKeys(Expression $expr = null)
    {
        if (!$expr) {
            return $this->rootModuleFile->hasExtraKeys();
        }

        foreach ($this->rootModuleFile->getExtraKeys() as $key => $value) {
            if ($expr->evaluate($key)) {
                return true;
            }
        }

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getExtraKey($key, $default = null)
    {
        return $this->rootModuleFile->getExtraKey($key, $default);
    }

    /**
     * {@inheritdoc}
     */
    public function getExtraKeys()
    {
        return $this->rootModuleFile->getExtraKeys();
    }

    /**
     * {@inheritdoc}
     */
    public function findExtraKeys(Expression $expr)
    {
        $values = array();

        foreach ($this->rootModuleFile->getExtraKeys() as $key => $value) {
            if ($expr->evaluate($key)) {
                $values[$key] = $value;
            }
        }

        return $values;
    }

    /**
     * {@inheritdoc}
     */
    public function migrate($targetVersion)
    {
        $previousVersion = $this->rootModuleFile->getVersion();

        if ($previousVersion === $targetVersion) {
            return;
        }

        $this->rootModuleFile->setVersion($targetVersion);

        try {
            $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
        } catch (Exception $e) {
            $this->rootModuleFile->setVersion($previousVersion);

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function saveConfigFile()
    {
        $this->jsonStorage->saveRootModuleFile($this->rootModuleFile);
    }

    private function validatePluginClass($pluginClass)
    {
        try {
            $reflClass = new ReflectionClass($pluginClass);
        } catch (ReflectionException $e) {
            throw new InvalidArgumentException(sprintf(
                'The plugin class %s does not exist.',
                $pluginClass
            ), 0, $e);
        }

        if ($reflClass->isInterface()) {
            throw new InvalidArgumentException(sprintf(
                'The plugin class %s should be a class, but is an interface.',
                $pluginClass
            ));
        }

        if (version_compare(PHP_VERSION, '5.4.0', '>=') && $reflClass->isTrait()) {
            throw new InvalidArgumentException(sprintf(
                'The plugin class %s should be a class, but is a trait.',
                $pluginClass
            ));
        }

        if (!$reflClass->implementsInterface('\Puli\Manager\Api\PuliPlugin')) {
            throw new InvalidArgumentException(sprintf(
                'The plugin class %s must implement PuliPlugin.',
                $pluginClass
            ));
        }

        $constructor = $reflClass->getConstructor();

        if (null !== $constructor && $constructor->getNumberOfRequiredParameters() > 0) {
            throw new InvalidArgumentException(sprintf(
                'The constructor of the plugin class %s must not have required '.
                'parameters.',
                $pluginClass
            ));
        }
    }
}


text:
/**
 */
package com.specmate.model.requirements.impl;

import com.specmate.model.base.impl.IModelNodeImpl;

import com.specmate.model.requirements.CEGNode;
import com.specmate.model.requirements.NodeType;
import com.specmate.model.requirements.RequirementsPackage;

import org.eclipse.emf.ecore.EClass;

/**
 *
 * An implementation of the model object 'CEG Node'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link com.specmate.model.requirements.impl.CEGNodeImpl#getType Type}

 *
{@link com.specmate.model.requirements.impl.CEGNodeImpl#getVariable Variable}

 *
{@link com.specmate.model.requirements.impl.CEGNodeImpl#getCondition Condition}

 *

 *
 * @generated
 */
public class CEGNodeImpl extends IModelNodeImpl implements CEGNode {
	/**
	 * The default value of the '{@link #getType() Type}' attribute.
	 *
	 *
	 * @see #getType()
	 * @generated
	 * @ordered
	 */
	protected static final NodeType TYPE_EDEFAULT = NodeType.AND;

	/**
	 * The default value of the '{@link #getVariable() Variable}' attribute.
	 *
	 *
	 * @see #getVariable()
	 * @generated
	 * @ordered
	 */
	protected static final String VARIABLE_EDEFAULT = null;

	/**
	 * The default value of the '{@link #getCondition() Condition}' attribute.
	 *
	 *
	 * @see #getCondition()
	 * @generated
	 * @ordered
	 */
	protected static final String CONDITION_EDEFAULT = null;

	/**
	 *
	 *
	 * @generated
	 */
	protected CEGNodeImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return RequirementsPackage.Literals.CEG_NODE;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NodeType getType() {
		return (NodeType)eDynamicGet(RequirementsPackage.CEG_NODE__TYPE, RequirementsPackage.Literals.CEG_NODE__TYPE, true, true);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setType(NodeType newType) {
		eDynamicSet(RequirementsPackage.CEG_NODE__TYPE, RequirementsPackage.Literals.CEG_NODE__TYPE, newType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getVariable() {
		return (String)eDynamicGet(RequirementsPackage.CEG_NODE__VARIABLE, RequirementsPackage.Literals.CEG_NODE__VARIABLE, true, true);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setVariable(String newVariable) {
		eDynamicSet(RequirementsPackage.CEG_NODE__VARIABLE, RequirementsPackage.Literals.CEG_NODE__VARIABLE, newVariable);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getCondition() {
		return (String)eDynamicGet(RequirementsPackage.CEG_NODE__CONDITION, RequirementsPackage.Literals.CEG_NODE__CONDITION, true, true);
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setCondition(String newCondition) {
		eDynamicSet(RequirementsPackage.CEG_NODE__CONDITION, RequirementsPackage.Literals.CEG_NODE__CONDITION, newCondition);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case RequirementsPackage.CEG_NODE__TYPE:
				return getType();
			case RequirementsPackage.CEG_NODE__VARIABLE:
				return getVariable();
			case RequirementsPackage.CEG_NODE__CONDITION:
				return getCondition();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case RequirementsPackage.CEG_NODE__TYPE:
				setType((NodeType)newValue);
				return;
			case RequirementsPackage.CEG_NODE__VARIABLE:
				setVariable((String)newValue);
				return;
			case RequirementsPackage.CEG_NODE__CONDITION:
				setCondition((String)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case RequirementsPackage.CEG_NODE__TYPE:
				setType(TYPE_EDEFAULT);
				return;
			case RequirementsPackage.CEG_NODE__VARIABLE:
				setVariable(VARIABLE_EDEFAULT);
				return;
			case RequirementsPackage.CEG_NODE__CONDITION:
				setCondition(CONDITION_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case RequirementsPackage.CEG_NODE__TYPE:
				return getType() != TYPE_EDEFAULT;
			case RequirementsPackage.CEG_NODE__VARIABLE:
				return VARIABLE_EDEFAULT == null ? getVariable() != null : !VARIABLE_EDEFAULT.equals(getVariable());
			case RequirementsPackage.CEG_NODE__CONDITION:
				return CONDITION_EDEFAULT == null ? getCondition() != null : !CONDITION_EDEFAULT.equals(getCondition());
		}
		return super.eIsSet(featureID);
	}

} //CEGNodeImpl