text:
package node

import (
	"database/sql"
	"encoding/hex"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/pkg/errors"

	"github.com/lxc/lxd/lxd/db/query"
	"github.com/lxc/lxd/lxd/db/schema"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/logger"
	"github.com/lxc/lxd/shared/units"
)

// Schema for the local database.
func Schema() *schema.Schema {
	schema := schema.NewFromMap(updates)
	schema.Fresh(freshSchema)
	return schema
}

// FreshSchema returns the fresh schema definition of the local database.
func FreshSchema() string {
	return freshSchema
}

// SchemaDotGo refreshes the schema.go file in this package, using the updates
// defined here.
func SchemaDotGo() error {
	return schema.DotGo(updates, "schema")
}

/* Database updates are one-time actions that are needed to move an
   existing database from one version of the schema to the next.

   Those updates are applied at startup time before anything else in LXD
   is initialized. This means that they should be entirely
   self-contained and not touch anything but the database.

   Calling LXD functions isn't allowed as such functions may themselves
   depend on a newer DB schema and so would fail when upgrading a very old
   version of LXD.

   DO NOT USE this mechanism for one-time actions which do not involve
   changes to the database schema. Use patches instead (see lxd/patches.go).

   REMEMBER to run "make update-schema" after you add a new update function to
   this slice. That will refresh the schema declaration in lxd/db/schema.go and
   include the effect of applying your patch as well.

   Only append to the updates list, never remove entries and never re-order them.
*/

var updates = map[int]schema.Update{
	1:  updateFromV0,
	2:  updateFromV1,
	3:  updateFromV2,
	4:  updateFromV3,
	5:  updateFromV4,
	6:  updateFromV5,
	7:  updateFromV6,
	8:  updateFromV7,
	9:  updateFromV8,
	10: updateFromV9,
	11: updateFromV10,
	12: updateFromV11,
	13: updateFromV12,
	14: updateFromV13,
	15: updateFromV14,
	16: updateFromV15,
	17: updateFromV16,
	18: updateFromV17,
	19: updateFromV18,
	20: updateFromV19,
	21: updateFromV20,
	22: updateFromV21,
	23: updateFromV22,
	24: updateFromV23,
	25: updateFromV24,
	26: updateFromV25,
	27: updateFromV26,
	28: updateFromV27,
	29: updateFromV28,
	30: updateFromV29,
	31: updateFromV30,
	32: updateFromV31,
	33: updateFromV32,
	34: updateFromV33,
	35: updateFromV34,
	36: updateFromV35,
	37: updateFromV36,
	38: updateFromV37,
	39: updateFromV38,
	40: updateFromV39,
}

// UpdateFromPreClustering is the last schema version where clustering support
// was not available, and hence no cluster dqlite database is used.
const UpdateFromPreClustering = 36

// Schema updates begin here

// Fix the address of the bootstrap node being set to "0" in the raft_nodes
// table.
func updateFromV39(tx *sql.Tx) error {
	nodes := []struct {
		ID      uint64
		Address string
	}{}
	dest := func(i int) []interface{} {
		nodes = append(nodes, struct {
			ID      uint64
			Address string
		}{})
		return []interface{}{&nodes[i].ID, &nodes[i].Address}
	}
	stmt, err := tx.Prepare("SELECT id, address FROM raft_nodes")
	if err != nil {
		return err
	}

	defer stmt.Close()

	err = query.SelectObjects(stmt, dest)
	if err != nil {
		return errors.Wrap(err, "Failed to fetch raft nodes")
	}

	if len(nodes) != 1 {
		return nil
	}

	info := nodes[0]
	if info.ID != 1 || info.Address != "0" {
		return nil
	}

	config, err := query.SelectConfig(tx, "config", "")
	if err != nil {
		return err
	}
	address := config["cluster.https_address"]
	if address != "" {
		_, err := tx.Exec("UPDATE raft_nodes SET address=? WHERE id=1", address)
		if err != nil {
			return err
		}
	}

	return nil
}

// Add role column to raft_nodes table. All existing entries will have role "0"
// which means voter.
func updateFromV38(tx *sql.Tx) error {
	stmt := `
ALTER TABLE raft_nodes ADD COLUMN role INTEGER NOT NULL DEFAULT 0;
`
	_, err := tx.Exec(stmt)
	return err
}

// Copy core.https_address to cluster.https_address in case this node is
// clustered.
func updateFromV37(tx *sql.Tx) error {
	count, err := query.Count(tx, "raft_nodes", "")
	if err != nil {
		return errors.Wrap(err, "Fetch count of Raft nodes")
	}

	if count == 0 {
		// This node is not clustered, nothing to do.
		return nil
	}

	// Copy the core.https_address config.
	_, err = tx.Exec(`
INSERT INTO config (key, value)
  SELECT 'cluster.https_address', value FROM config WHERE key = 'core.https_address'
`)
	if err != nil {
		return errors.Wrap(err, "Insert cluster.https_address config")
	}

	return nil
}

// Add a raft_nodes table to be used when running in clustered mode. It lists
// the current nodes in the LXD cluster that are participating to the dqlite
// database Raft cluster.
//
// The 'id' column contains the raft server ID of the database node, and the
// 'address' column its network address. Both are used internally by the raft
// Go package to manage the cluster.
//
// Typical setups will have 3 LXD cluster nodes that participate to the dqlite
// database Raft cluster, and an arbitrary number of additional LXD cluster
// nodes that don't. Non-database nodes are not tracked in this table, but rather
// in the nodes table of the cluster database itself.
//
// The data in this table must be replicated by LXD on all nodes of the
// cluster, regardless of whether they are part of the raft cluster or not, and
// all nodes will consult this table when they need to find out a leader to
// send SQL queries to.
func updateFromV36(tx *sql.Tx) error {
	stmts := `
CREATE TABLE raft_nodes (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    address TEXT NOT NULL,
    UNIQUE (address)
);
DELETE FROM config WHERE NOT key='core.https_address';
DROP TABLE certificates;
DROP TABLE containers_devices_config;
DROP TABLE containers_devices;
DROP TABLE containers_config;
DROP TABLE containers_profiles;
DROP TABLE containers;
DROP TABLE images_aliases;
DROP TABLE images_properties;
DROP TABLE images_source;
DROP TABLE images;
DROP TABLE networks_config;
DROP TABLE networks;
DROP TABLE profiles_devices_config;
DROP TABLE profiles_devices;
DROP TABLE profiles_config;
DROP TABLE profiles;
DROP TABLE storage_volumes_config;
DROP TABLE storage_volumes;
DROP TABLE storage_pools_config;
DROP TABLE storage_pools;
`
	_, err := tx.Exec(stmts)
	return err
}

func updateFromV35(tx *sql.Tx) error {
	stmts := `
CREATE TABLE tmp (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    image_id INTEGER NOT NULL,
    description TEXT,
    FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE,
    UNIQUE (name)
);
INSERT INTO tmp (id, name, image_id, description)
    SELECT id, name, image_id, description
    FROM images_aliases;
DROP TABLE images_aliases;
ALTER TABLE tmp RENAME TO images_aliases;

ALTER TABLE networks ADD COLUMN description TEXT;
ALTER TABLE storage_pools ADD COLUMN description TEXT;
ALTER TABLE storage_volumes ADD COLUMN description TEXT;
ALTER TABLE containers ADD COLUMN description TEXT;
`
	_, err := tx.Exec(stmts)
	return err
}

func updateFromV34(tx *sql.Tx) error {
	stmt := `
CREATE TABLE IF NOT EXISTS storage_pools (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    driver VARCHAR(255) NOT NULL,
    UNIQUE (name)
);
CREATE TABLE IF NOT EXISTS storage_pools_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    storage_pool_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    UNIQUE (storage_pool_id, key),
    FOREIGN KEY (storage_pool_id) REFERENCES storage_pools (id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS storage_volumes (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    storage_pool_id INTEGER NOT NULL,
    type INTEGER NOT NULL,
    UNIQUE (storage_pool_id, name, type),
    FOREIGN KEY (storage_pool_id) REFERENCES storage_pools (id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS storage_volumes_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    storage_volume_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    UNIQUE (storage_volume_id, key),
    FOREIGN KEY (storage_volume_id) REFERENCES storage_volumes (id) ON DELETE CASCADE
);`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV33(tx *sql.Tx) error {
	stmt := `
CREATE TABLE IF NOT EXISTS networks (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    UNIQUE (name)
);
CREATE TABLE IF NOT EXISTS networks_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    network_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    UNIQUE (network_id, key),
    FOREIGN KEY (network_id) REFERENCES networks (id) ON DELETE CASCADE
);`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV32(tx *sql.Tx) error {
	_, err := tx.Exec("ALTER TABLE containers ADD COLUMN last_use_date DATETIME;")
	return err
}

func updateFromV31(tx *sql.Tx) error {
	stmt := `
CREATE TABLE IF NOT EXISTS patches (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    applied_at DATETIME NOT NULL,
    UNIQUE (name)
);`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV30(tx *sql.Tx) error {
	// NOTE: this database update contained daemon-level logic which
	//       was been moved to patchUpdateFromV15 in patches.go.
	return nil
}

func updateFromV29(tx *sql.Tx) error {
	if shared.PathExists(shared.VarPath("zfs.img")) {
		err := os.Chmod(shared.VarPath("zfs.img"), 0600)
		if err != nil {
			return err
		}
	}

	return nil
}

func updateFromV28(tx *sql.Tx) error {
	stmt := `
INSERT INTO profiles_devices (profile_id, name, type) SELECT id, "aadisable", 2 FROM profiles WHERE name="docker";
INSERT INTO profiles_devices_config (profile_device_id, key, value) SELECT profiles_devices.id, "source", "/dev/null" FROM profiles_devices LEFT JOIN profiles WHERE profiles_devices.profile_id = profiles.id AND profiles.name = "docker" AND profiles_devices.name = "aadisable";
INSERT INTO profiles_devices_config (profile_device_id, key, value) SELECT profiles_devices.id, "path", "/sys/module/apparmor/parameters/enabled" FROM profiles_devices LEFT JOIN profiles WHERE profiles_devices.profile_id = profiles.id AND profiles.name = "docker" AND profiles_devices.name = "aadisable";`
	tx.Exec(stmt)

	return nil
}

func updateFromV27(tx *sql.Tx) error {
	_, err := tx.Exec("UPDATE profiles_devices SET type=3 WHERE type='unix-char';")
	return err
}

func updateFromV26(tx *sql.Tx) error {
	stmt := `
ALTER TABLE images ADD COLUMN auto_update INTEGER NOT NULL DEFAULT 0;
CREATE TABLE IF NOT EXISTS images_source (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    image_id INTEGER NOT NULL,
    server TEXT NOT NULL,
    protocol INTEGER NOT NULL,
    certificate TEXT NOT NULL,
    alias VARCHAR(255) NOT NULL,
    FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE
);`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV25(tx *sql.Tx) error {
	stmt := `
INSERT INTO profiles (name, description) VALUES ("docker", "Profile supporting docker in containers");
INSERT INTO profiles_config (profile_id, key, value) SELECT id, "security.nesting", "true" FROM profiles WHERE name="docker";
INSERT INTO profiles_config (profile_id, key, value) SELECT id, "linux.kernel_modules", "overlay, nf_nat" FROM profiles WHERE name="docker";
INSERT INTO profiles_devices (profile_id, name, type) SELECT id, "fuse", "unix-char" FROM profiles WHERE name="docker";
INSERT INTO profiles_devices_config (profile_device_id, key, value) SELECT profiles_devices.id, "path", "/dev/fuse" FROM profiles_devices LEFT JOIN profiles WHERE profiles_devices.profile_id = profiles.id AND profiles.name = "docker";`
	tx.Exec(stmt)

	return nil
}

func updateFromV24(tx *sql.Tx) error {
	_, err := tx.Exec("ALTER TABLE containers ADD COLUMN stateful INTEGER NOT NULL DEFAULT 0;")
	return err
}

func updateFromV23(tx *sql.Tx) error {
	_, err := tx.Exec("ALTER TABLE profiles ADD COLUMN description TEXT;")
	return err
}

func updateFromV22(tx *sql.Tx) error {
	stmt := `
DELETE FROM containers_devices_config WHERE key='type';
DELETE FROM profiles_devices_config WHERE key='type';`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV21(tx *sql.Tx) error {
	_, err := tx.Exec("ALTER TABLE containers ADD COLUMN creation_date DATETIME NOT NULL DEFAULT 0;")
	return err
}

func updateFromV20(tx *sql.Tx) error {
	stmt := `
UPDATE containers_devices SET name='__lxd_upgrade_root' WHERE name='root';
UPDATE profiles_devices SET name='__lxd_upgrade_root' WHERE name='root';

INSERT INTO containers_devices (container_id, name, type) SELECT id, "root", 2 FROM containers;
INSERT INTO containers_devices_config (container_device_id, key, value) SELECT id, "path", "/" FROM containers_devices WHERE name='root';`
	_, err := tx.Exec(stmt)

	return err
}

func updateFromV19(tx *sql.Tx) error {
	stmt := `
DELETE FROM containers_config WHERE container_id NOT IN (SELECT id FROM containers);
DELETE FROM containers_devices_config WHERE container_device_id NOT IN (SELECT id FROM containers_devices WHERE container_id IN (SELECT id FROM containers));
DELETE FROM containers_devices WHERE container_id NOT IN (SELECT id FROM containers);
DELETE FROM containers_profiles WHERE container_id NOT IN (SELECT id FROM containers);
DELETE FROM images_aliases WHERE image_id NOT IN (SELECT id FROM images);
DELETE FROM images_properties WHERE image_id NOT IN (SELECT id FROM images);`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV18(tx *sql.Tx) error {
	var id int
	var value string

	// Update container config
	rows, err := tx.Query("SELECT id, value FROM containers_config WHERE key='limits.memory'")
	if err != nil {
		return err
	}
	defer rows.Close()

	for rows.Next() {
		err := rows.Scan(&id, &value)
		if err != nil {
			return err
		}

		// If already an integer, don't touch
		_, err = strconv.Atoi(value)
		if err == nil {
			continue
		}

		// Generate the new value
		value = strings.ToUpper(value)
		value += "B"

		// Deal with completely broken values
		_, err = units.ParseByteSizeString(value)
		if err != nil {
			logger.Debugf("Invalid container memory limit, id=%d value=%s, removing", id, value)
			_, err = tx.Exec("DELETE FROM containers_config WHERE id=?;", id)
			if err != nil {
				return err
			}
		}

		// Set the new value
		_, err = tx.Exec("UPDATE containers_config SET value=? WHERE id=?", value, id)
		if err != nil {
			return err
		}
	}

	err = rows.Err()
	if err != nil {
		return err
	}

	// Update profiles config
	rows, err = tx.Query("SELECT id, value FROM profiles_config WHERE key='limits.memory'")
	if err != nil {
		return err
	}
	defer rows.Close()

	for rows.Next() {
		err := rows.Scan(&id, &value)
		if err != nil {
			return err
		}

		// If already an integer, don't touch
		_, err = strconv.Atoi(value)
		if err == nil {
			continue
		}

		// Generate the new value
		value = strings.ToUpper(value)
		value += "B"

		// Deal with completely broken values
		_, err = units.ParseByteSizeString(value)
		if err != nil {
			logger.Debugf("Invalid profile memory limit, id=%d value=%s, removing", id, value)
			_, err = tx.Exec("DELETE FROM profiles_config WHERE id=?;", id)
			if err != nil {
				return err
			}
		}

		// Set the new value
		_, err = tx.Exec("UPDATE profiles_config SET value=? WHERE id=?", value, id)
		if err != nil {
			return err
		}
	}

	err = rows.Err()
	if err != nil {
		return err
	}

	return nil
}

func updateFromV17(tx *sql.Tx) error {
	stmt := `
DELETE FROM profiles_config WHERE key LIKE 'volatile.%';
UPDATE containers_config SET key='limits.cpu' WHERE key='limits.cpus';
UPDATE profiles_config SET key='limits.cpu' WHERE key='limits.cpus';`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV16(tx *sql.Tx) error {
	stmt := `
UPDATE config SET key='storage.lvm_vg_name' WHERE key = 'core.lvm_vg_name';
UPDATE config SET key='storage.lvm_thinpool_name' WHERE key = 'core.lvm_thinpool_name';`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV15(tx *sql.Tx) error {
	// NOTE: this database update contained daemon-level logic which
	//       was been moved to patchUpdateFromV15 in patches.go.
	return nil
}

func updateFromV14(tx *sql.Tx) error {
	stmt := `
PRAGMA foreign_keys=OFF; -- So that integrity doesn't get in the way for now

DELETE FROM containers_config WHERE key="volatile.last_state.power";

INSERT INTO containers_config (container_id, key, value)
    SELECT id, "volatile.last_state.power", "RUNNING"
    FROM containers WHERE power_state=1;

INSERT INTO containers_config (container_id, key, value)
    SELECT id, "volatile.last_state.power", "STOPPED"
    FROM containers WHERE power_state != 1;

CREATE TABLE tmp (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    architecture INTEGER NOT NULL,
    type INTEGER NOT NULL,
    ephemeral INTEGER NOT NULL DEFAULT 0,
    UNIQUE (name)
);

INSERT INTO tmp SELECT id, name, architecture, type, ephemeral FROM containers;

DROP TABLE containers;
ALTER TABLE tmp RENAME TO containers;

PRAGMA foreign_keys=ON; -- Make sure we turn integrity checks back on.`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV13(tx *sql.Tx) error {
	stmt := `
UPDATE containers_config SET key='volatile.base_image' WHERE key = 'volatile.baseImage';`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV12(tx *sql.Tx) error {
	stmt := `
ALTER TABLE images ADD COLUMN cached INTEGER NOT NULL DEFAULT 0;
ALTER TABLE images ADD COLUMN last_use_date DATETIME;`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV11(tx *sql.Tx) error {
	// NOTE: this database update contained daemon-level logic which
	//       was been moved to patchUpdateFromV15 in patches.go.
	return nil
}

func updateFromV10(tx *sql.Tx) error {
	// NOTE: this database update contained daemon-level logic which
	//       was been moved to patchUpdateFromV10 in patches.go.
	return nil
}

func updateFromV9(tx *sql.Tx) error {
	stmt := `
CREATE TABLE tmp (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    container_id INTEGER NOT NULL,
    name VARCHAR(255) NOT NULL,
    type VARCHAR(255) NOT NULL default "none",
    FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE,
    UNIQUE (container_id, name)
);

INSERT INTO tmp SELECT * FROM containers_devices;

UPDATE containers_devices SET type=0 WHERE id IN (SELECT id FROM tmp WHERE type="none");
UPDATE containers_devices SET type=1 WHERE id IN (SELECT id FROM tmp WHERE type="nic");
UPDATE containers_devices SET type=2 WHERE id IN (SELECT id FROM tmp WHERE type="disk");
UPDATE containers_devices SET type=3 WHERE id IN (SELECT id FROM tmp WHERE type="unix-char");
UPDATE containers_devices SET type=4 WHERE id IN (SELECT id FROM tmp WHERE type="unix-block");

DROP TABLE tmp;

CREATE TABLE tmp (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    profile_id INTEGER NOT NULL,
    name VARCHAR(255) NOT NULL,
    type VARCHAR(255) NOT NULL default "none",
    FOREIGN KEY (profile_id) REFERENCES profiles (id) ON DELETE CASCADE,
    UNIQUE (profile_id, name)
);

INSERT INTO tmp SELECT * FROM profiles_devices;

UPDATE profiles_devices SET type=0 WHERE id IN (SELECT id FROM tmp WHERE type="none");
UPDATE profiles_devices SET type=1 WHERE id IN (SELECT id FROM tmp WHERE type="nic");
UPDATE profiles_devices SET type=2 WHERE id IN (SELECT id FROM tmp WHERE type="disk");
UPDATE profiles_devices SET type=3 WHERE id IN (SELECT id FROM tmp WHERE type="unix-char");
UPDATE profiles_devices SET type=4 WHERE id IN (SELECT id FROM tmp WHERE type="unix-block");

DROP TABLE tmp;`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV8(tx *sql.Tx) error {
	stmt := `
UPDATE certificates SET fingerprint = replace(fingerprint, " ", "");`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV7(tx *sql.Tx) error {
	stmt := `
UPDATE config SET key='core.trust_password' WHERE key IN ('password', 'trust_password', 'trust-password', 'core.trust-password');
DELETE FROM config WHERE key != 'core.trust_password';`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV6(tx *sql.Tx) error {
	// This update recreates the schemas that need an ON DELETE CASCADE foreign
	// key.
	stmt := `
PRAGMA foreign_keys=OFF; -- So that integrity doesn't get in the way for now

CREATE TEMP TABLE tmp AS SELECT * FROM containers_config;
DROP TABLE containers_config;
CREATE TABLE IF NOT EXISTS containers_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    container_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE,
    UNIQUE (container_id, key)
);
INSERT INTO containers_config SELECT * FROM tmp;
DROP TABLE tmp;

CREATE TEMP TABLE tmp AS SELECT * FROM containers_devices;
DROP TABLE containers_devices;
CREATE TABLE IF NOT EXISTS containers_devices (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    container_id INTEGER NOT NULL,
    name VARCHAR(255) NOT NULL,
    type INTEGER NOT NULL default 0,
    FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE,
    UNIQUE (container_id, name)
);
INSERT INTO containers_devices SELECT * FROM tmp;
DROP TABLE tmp;

CREATE TEMP TABLE tmp AS SELECT * FROM containers_devices_config;
DROP TABLE containers_devices_config;
CREATE TABLE IF NOT EXISTS containers_devices_config (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    container_device_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    FOREIGN KEY (container_device_id) REFERENCES containers_devices (id) ON DELETE CASCADE,
    UNIQUE (container_device_id, key)
);
INSERT INTO containers_devices_config SELECT * FROM tmp;
DROP TABLE tmp;

CREATE TEMP TABLE tmp AS SELECT * FROM containers_profiles;
DROP TABLE containers_profiles;
CREATE TABLE IF NOT EXISTS containers_profiles (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    container_id INTEGER NOT NULL,
    profile_id INTEGER NOT NULL,
    apply_order INTEGER NOT NULL default 0,
    UNIQUE (container_id, profile_id),
    FOREIGN KEY (container_id) REFERENCES containers(id) ON DELETE CASCADE,
    FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
);
INSERT INTO containers_profiles SELECT * FROM tmp;
DROP TABLE tmp;

CREATE TEMP TABLE tmp AS SELECT * FROM images_aliases;
DROP TABLE images_aliases;
CREATE TABLE IF NOT EXISTS images_aliases (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    image_id INTEGER NOT NULL,
    description VARCHAR(255),
    FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE,
    UNIQUE (name)
);
INSERT INTO images_aliases SELECT * FROM tmp;
DROP TABLE tmp;

CREATE TEMP TABLE tmp AS SELECT * FROM images_properties;
DROP TABLE images_properties;
CREATE TABLE IF NOT EXISTS images_properties (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    image_id INTEGER NOT NULL,
    type INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE
);
INSERT INTO images_properties SELECT * FROM tmp;
DROP TABLE tmp;

CREATE TEMP TABLE tmp AS SELECT * FROM profiles_config;
DROP TABLE profiles_config;
CREATE TABLE IF NOT EXISTS profiles_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    profile_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value VARCHAR(255),
    UNIQUE (profile_id, key),
    FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
);
INSERT INTO profiles_config SELECT * FROM tmp;
DROP TABLE tmp;

CREATE TEMP TABLE tmp AS SELECT * FROM profiles_devices;
DROP TABLE profiles_devices;
CREATE TABLE IF NOT EXISTS profiles_devices (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    profile_id INTEGER NOT NULL,
    name VARCHAR(255) NOT NULL,
    type INTEGER NOT NULL default 0,
    UNIQUE (profile_id, name),
    FOREIGN KEY (profile_id) REFERENCES profiles (id) ON DELETE CASCADE
);
INSERT INTO profiles_devices SELECT * FROM tmp;
DROP TABLE tmp;

CREATE TEMP TABLE tmp AS SELECT * FROM profiles_devices_config;
DROP TABLE profiles_devices_config;
CREATE TABLE IF NOT EXISTS profiles_devices_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    profile_device_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    UNIQUE (profile_device_id, key),
    FOREIGN KEY (profile_device_id) REFERENCES profiles_devices (id) ON DELETE CASCADE
);
INSERT INTO profiles_devices_config SELECT * FROM tmp;
DROP TABLE tmp;

PRAGMA foreign_keys=ON; -- Make sure we turn integrity checks back on.`
	_, err := tx.Exec(stmt)
	if err != nil {
		return err
	}

	// Get the rows with broken foreign keys an nuke them
	rows, err := tx.Query("PRAGMA foreign_key_check;")
	if err != nil {
		return err
	}
	defer rows.Close()

	var tablestodelete []string
	var rowidtodelete []int

	for rows.Next() {
		var tablename string
		var rowid int
		var targetname string
		var keynumber int

		rows.Scan(&tablename, &rowid, &targetname, &keynumber)
		tablestodelete = append(tablestodelete, tablename)
		rowidtodelete = append(rowidtodelete, rowid)
	}
	rows.Close()

	for i := range tablestodelete {
		_, err = tx.Exec(fmt.Sprintf("DELETE FROM %s WHERE rowid = %d;", tablestodelete[i], rowidtodelete[i]))
		if err != nil {
			return err
		}
	}

	return err
}

func updateFromV5(tx *sql.Tx) error {
	stmt := `
ALTER TABLE containers ADD COLUMN power_state INTEGER NOT NULL DEFAULT 0;
ALTER TABLE containers ADD COLUMN ephemeral INTEGER NOT NULL DEFAULT 0;`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV4(tx *sql.Tx) error {
	stmt := `
CREATE TABLE IF NOT EXISTS config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    UNIQUE (key)
);`

	_, err := tx.Exec(stmt)
	if err != nil {
		return err
	}

	passfname := shared.VarPath("adminpwd")
	passOut, err := os.Open(passfname)
	oldPassword := ""
	if err == nil {
		defer passOut.Close()
		buff := make([]byte, 96)
		_, err = passOut.Read(buff)
		if err != nil {
			return err
		}

		oldPassword = hex.EncodeToString(buff)
		stmt := `INSERT INTO config (key, value) VALUES ("core.trust_password", ?);`

		_, err := tx.Exec(stmt, oldPassword)
		if err != nil {
			return err
		}

		return os.Remove(passfname)
	}

	return nil
}

func updateFromV3(tx *sql.Tx) error {
	// Attempt to create a default profile (but don't fail if already there)
	tx.Exec("INSERT INTO profiles (name) VALUES (\"default\");")

	return nil
}

func updateFromV2(tx *sql.Tx) error {
	stmt := `
CREATE TABLE IF NOT EXISTS containers_devices (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    container_id INTEGER NOT NULL,
    name VARCHAR(255) NOT NULL,
    type INTEGER NOT NULL default 0,
    FOREIGN KEY (container_id) REFERENCES containers (id) ON DELETE CASCADE,
    UNIQUE (container_id, name)
);
CREATE TABLE IF NOT EXISTS containers_devices_config (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    container_device_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    FOREIGN KEY (container_device_id) REFERENCES containers_devices (id),
    UNIQUE (container_device_id, key)
);
CREATE TABLE IF NOT EXISTS containers_profiles (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    container_id INTEGER NOT NULL,
    profile_id INTEGER NOT NULL,
    apply_order INTEGER NOT NULL default 0,
    UNIQUE (container_id, profile_id),
    FOREIGN KEY (container_id) REFERENCES containers(id) ON DELETE CASCADE,
    FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS profiles (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    UNIQUE (name)
);
CREATE TABLE IF NOT EXISTS profiles_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    profile_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value VARCHAR(255),
    UNIQUE (profile_id, key),
    FOREIGN KEY (profile_id) REFERENCES profiles(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS profiles_devices (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    profile_id INTEGER NOT NULL,
    name VARCHAR(255) NOT NULL,
    type INTEGER NOT NULL default 0,
    UNIQUE (profile_id, name),
    FOREIGN KEY (profile_id) REFERENCES profiles (id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS profiles_devices_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    profile_device_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    UNIQUE (profile_device_id, key),
    FOREIGN KEY (profile_device_id) REFERENCES profiles_devices (id)
);`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV1(tx *sql.Tx) error {
	// v1..v2 adds images aliases
	stmt := `
CREATE TABLE IF NOT EXISTS images_aliases (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    image_id INTEGER NOT NULL,
    description VARCHAR(255),
    FOREIGN KEY (image_id) REFERENCES images (id) ON DELETE CASCADE,
    UNIQUE (name)
);`
	_, err := tx.Exec(stmt)
	return err
}

func updateFromV0(tx *sql.Tx) error {
	// v0..v1 the dawn of containers
	stmt := `
CREATE TABLE certificates (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    fingerprint VARCHAR(255) NOT NULL,
    type INTEGER NOT NULL,
    name VARCHAR(255) NOT NULL,
    certificate TEXT NOT NULL,
    UNIQUE (fingerprint)
);
CREATE TABLE containers (
    id INTEGER primary key AUTOINCREMENT NOT NULL,
    name VARCHAR(255) NOT NULL,
    architecture INTEGER NOT NULL,
    type INTEGER NOT NULL,
    UNIQUE (name)
);
CREATE TABLE containers_config (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    container_id INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    FOREIGN KEY (container_id) REFERENCES containers (id),
    UNIQUE (container_id, key)
);
CREATE TABLE images (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    fingerprint VARCHAR(255) NOT NULL,
    filename VARCHAR(255) NOT NULL,
    size INTEGER NOT NULL,
    public INTEGER NOT NULL DEFAULT 0,
    architecture INTEGER NOT NULL,
    creation_date DATETIME,
    expiry_date DATETIME,
    upload_date DATETIME NOT NULL,
    UNIQUE (fingerprint)
);
CREATE TABLE images_properties (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    image_id INTEGER NOT NULL,
    type INTEGER NOT NULL,
    key VARCHAR(255) NOT NULL,
    value TEXT,
    FOREIGN KEY (image_id) REFERENCES images (id)
);`
	_, err := tx.Exec(stmt)
	return err
}

// UpdateFromV16 is used by a legacy test in the parent package.
var UpdateFromV16 = updateFromV16


text:
namespace DoctrineShips.Data
{
    using System.Data.Entity;
    using DoctrineShips.Data.Mapping;
    using GenericRepository.Providers.EntityFramework;

    public class DoctrineShipsContext : DbContextBase
    {
        public DoctrineShipsContext() :
            base("name=DoctrineShipsDb")
        {
            //Database.SetInitializer<DoctrineShipsContext>(new DropCreateDatabaseAlways<DoctrineShipsContext>());
            Database.SetInitializer<DoctrineShipsContext>(null);
            Configuration.ProxyCreationEnabled = false;
        }

        public new IDbSet<T> Set<T>() where T : class
        {
            return base.Set<T>();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Configurations.Add(new AccessCodeMap());
            modelBuilder.Configurations.Add(new AccountMap());
            modelBuilder.Configurations.Add(new ArticleMap());
            modelBuilder.Configurations.Add(new ComponentMap());
            modelBuilder.Configurations.Add(new ContractMap());
            modelBuilder.Configurations.Add(new CustomerMap());
            modelBuilder.Configurations.Add(new DoctrineMap());
            modelBuilder.Configurations.Add(new DoctrineShipFitMap());
            modelBuilder.Configurations.Add(new LogMessageMap());
            modelBuilder.Configurations.Add(new NotificationRecipientMap());
            modelBuilder.Configurations.Add(new SalesAgentMap());
            modelBuilder.Configurations.Add(new SettingProfileMap());
            modelBuilder.Configurations.Add(new ShipFitComponentMap());
            modelBuilder.Configurations.Add(new ShipFitMap());
            modelBuilder.Configurations.Add(new SubscriptionPlanMap());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.jgroups.tests;

import org.jgroups.Global;
import org.jgroups.raft.util.RequestTable;
import org.jgroups.util.Util;
import org.testng.annotations.Test;

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.IntStream;

/**
 * @author Bela Ban
 * @since  0.1
 */
@Test(groups=Global.FUNCTIONAL,singleThreaded=true) // single-threaded because of the single CompletableFuture
public class RequestTableTest {
    protected static final CompletableFuture<byte[]> future=new CompletableFuture<>();

    public void testSimple() {
        Supplier<Integer> majority=() -> 3;
        RequestTable<String> table=new RequestTable<>();
        table.create(1, "A", future, majority);
        table.add(1, "A", majority);
        assert !table.isCommitted(1);
        boolean done=table.add(1, "B", majority);
        assert !done;
        done=table.add(1, "C", majority);
        assert done;
        assert table.isCommitted(1);
    }

    public void testSingleNode() {
        RequestTable<String> table=new RequestTable<>();
        table.create(1, "A", future, () -> 1);
        assert table.isCommitted(1);
        boolean added=table.add(1, "A", () -> 1);
        assert !added : "should only mark as committed once";
    }

    public void testAdd() {
        RequestTable<String> table=new RequestTable<>();
        table.create(3, "A", future, () -> 2);
        assert table.isCommitted(1);
        assert !table.isCommitted(3);
        table.add(3, "A", () -> 2);
        assert !table.isCommitted(3);
        boolean commited=table.add(3, "B", () -> 2);
        assert commited && table.isCommitted(3);
        for(int i=4; i <= 10; i++)
            table.create(i, "A", future, () -> 2);
        commited=table.add(10, "B", () -> 2);
        assert commited;
        for(int i=4; i <= 10; i++)
            assert table.isCommitted(10);
        assert table.size() == 8;
    }

    public void testNotifyAndRemove() {
        RequestTable<String> table=new RequestTable<>();
        for(int i=1; i <= 5; i++)
            table.create(i, "A", future, () -> 1);
        IntStream.rangeClosed(1,5).parallel().forEach(i -> table.notifyAndRemove(i, "bb".getBytes()));
        Util.waitUntilTrue(5000, 200, () -> table.size() == 0);
        assert table.size() == 0 : String.format("table size should be %d but is %d", 0, table.size());
    }
}


text:
var internet = {};
module['exports'] = internet;
internet.domain_suffix = require("./domain_suffix");


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Messaging\V1\Service;

use Twilio\Http\Response;
use Twilio\Page;
use Twilio\Version;

/**
 * PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
 */
class UsAppToPersonUsecasePage extends Page {
    /**
     * @param Version $version Version that contains the resource
     * @param Response $response Response from the API
     * @param array $solution The context solution
     */
    public function __construct(Version $version, Response $response, array $solution) {
        parent::__construct($version, $response);

        // Path Solution
        $this->solution = $solution;
    }

    /**
     * @param array $payload Payload response from the API
     * @return UsAppToPersonUsecaseInstance \Twilio\Rest\Messaging\V1\Service\UsAppToPersonUsecaseInstance
     */
    public function buildInstance(array $payload): UsAppToPersonUsecaseInstance {
        return new UsAppToPersonUsecaseInstance(
            $this->version,
            $payload,
            $this->solution['messagingServiceSid']
        );
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString(): string {
        return '[Twilio.Messaging.V1.UsAppToPersonUsecasePage]';
    }
}


text:
#include <served/methods_handler.hpp>

namespace served {

//  -----  constructors  -----

methods_handler::methods_handler(const std::string path, const std::string info /* = "" */)
	: _path(path)
	, _info(info)
{
}

//  -----  method registering  -----

methods_handler &
methods_handler::get (served_req_handler handler)
{
	_handlers[served::method::GET] = handler;
	return *this;
}

methods_handler &
methods_handler::post(served_req_handler handler)
{
	_handlers[served::method::POST] = handler;
	return *this;
}

methods_handler &
methods_handler::head(served_req_handler handler)
{
	_handlers[served::method::HEAD] = handler;
	return *this;
}

methods_handler &
methods_handler::put (served_req_handler handler)
{
	_handlers[served::method::PUT] = handler;
	return *this;
}

methods_handler &
methods_handler::del (served_req_handler handler)
{
	_handlers[served::method::DELETE] = handler;
	return *this;
}

methods_handler &
methods_handler::method(const served::method method, served_req_handler handler)
{
	_handlers[method] = handler;
	return *this;
}

//  -----  endpoint propagation  -----

void
methods_handler::propagate_endpoint(served_endpoint_list & endpoints) const
{
	std::vector<std::string> methods;
	for ( const auto & m_handler : _handlers )
	{
		methods.push_back(served::method_to_string(m_handler.first));
	}
	endpoints[_path] = served_method_list(_info, methods);
}

} // served


text:
module Engines
  class Plugin
    module Configurable
      class Config < ActiveRecord::Base
        set_table_name 'plugin_configs'
        serialize :options, Hash

        def after_initialize
          write_attribute(:options, {}) if read_attribute(:options).nil?
        end
      end

      def option(property, default, field_type = :text_field)
        instance_eval <<-END, __FILE__, __LINE__
          def #{property}
            config.options[#{property.inspect}] || #{default.inspect}
          end
          def #{property}=(value)
            config.options[#{property.inspect}] = value
          end
        END
        default_options[property] = field_type
      end

      def options=(options)
        config.options = options
      end

      def default_options
        @default_options ||= {}
      end

      def save!
        config.save!
      end

      def destroy
        config.destroy
        @config = nil
      end

      private

      def config
        @config ||= Config.find_or_initialize_by_name(conf_name)
      end

      # allow subclasses to hook in here
      def conf_name
        name
      end
    end
  end
end

Engines::Plugin.send :include, Engines::Plugin::Configurable


text:
var inherits = require('util').inherits;
var childProcess = require('child_process');
var fs = require('fs');

var ResourceLoader = require('./ResourceLoader');
var ImageResource = require('../resource/Image');
var MessageList = require('../MessageList');
var getImageSize = require('../parse/getImageSize');

/**
 * @class Loads and parses __mocks__ / *.js files
 *
 * @extends {ResourceLoader}
 */
function ImageLoader(options) {
  ResourceLoader.call(this, options);
}
inherits(ImageLoader, ResourceLoader);
ImageLoader.prototype.path = __filename;

ImageLoader.prototype.getResourceTypes = function() {
  return [ImageResource];
};

ImageLoader.prototype.getExtensions = function() {
  return ['.jpg', '.png', '.gif'];
};

/**
 * Creates a new resource for a given path.
 *
 * @protected
 * @param {String}               path      resource being built
 * @param {ProjectConfiguration} configuration configuration for the path
 * @param {Function}             callback
 */
ImageLoader.prototype.loadFromPath =
  function(path, configuration, callback) {

  var image = new ImageResource(path);
  var messages = MessageList.create();
  image.id = path;
  fs.readFile(path, function(err, buffer) {
    image.networkSize = buffer.length;
    var size = getImageSize(buffer);
    if (size) {
      image.width = size.width;
      image.height = size.height;
    }
    callback(messages, image);
  });
};

var re = /\.(jpg|gif|png)$/;
/**
 * Only match __mocks__ / *.js files
 * @static
 * @param  {String} filePath
 * @return {Boolean}
 */
ImageLoader.prototype.matchPath = function(filePath) {
  return re.test(filePath);
};

module.exports = ImageLoader;


text:
package com.intellij.openapi.actionSystem.impl;

import com.intellij.openapi.actionSystem.DataContext;
import org.jetbrains.annotations.ApiStatus;

@ApiStatus.Internal
public interface AsyncDataContext extends DataContext {
}


text:
/*
 * Serializer.h
 * Declares the Serializer class, which writes objects to files
 * Created by: Andrew Davis
 * Created on: 10/10/2015
 * Open source
 */

//disallow reinclusion
#ifndef SERIAL_S_H
#define SERIAL_S_H

//includes
#include "../util/Enums.h"
#include "../interface/ISerializable.h"

//class definition

class Serializer {
	public:
		//constructors and destructor
		Serializer(const char* fileName, SaveType typeToProcess);
		Serializer(const Serializer& s); //copy constructor
		virtual ~Serializer(); //destructor
		//getters
		SaveType getProcessingType(); //gets the type currently being processed
		ISerializable getSavingObject(); //gets the object being saved
		//setter
		void setSavingObject(ISerializeable obj); //sets the object to be saved
		//method
		void process(); //saves the current object
	protected:
		std::ofstream file; //stream to write data to
		ISerializable currentObj //current object being saved
};

#endif


text:
using System;
using System.Collections.Generic;

class QuickSortStrings
{
    static void Main()
    {
        Console.WriteLine("Sort an array of integers using the quick sort algorithm");

        // Create an unsortArr array of integers intArray
        int[] unsortArr = { 200, 38, 15, 2048, 0, 159, 15963, 2, 88, 41 };

        Console.WriteLine("Unsorted array:");
        for (int i = 0; i < unsortArr.Length; i++)
        {
            Console.Write(unsortArr[i] + " ");
        }
        Console.WriteLine();

        // Sort the array

        QuickSortInt(unsortArr, 0, unsortArr.Length - 1);

        Console.WriteLine("Sorted array:");
        for (int i = 0; i < unsortArr.Length; i++)
        {
            Console.Write(unsortArr[i] + " ");
        }
        Console.WriteLine();
    }

    // A method to sort the array of integers using the QuickSort approach

    public static void QuickSortInt(int[] intArray, int leftSide, int rightSide)
    {
        int i = leftSide;
        int j = rightSide;
        int pivot = intArray[(leftSide + rightSide) / 2];

        while (i <= j)
        {
            while (intArray[i].CompareTo(pivot) < 0)
            {
                i++;
            }

            while (intArray[j].CompareTo(pivot) > 0)
            {
                j--;
            }

            if (i <= j)
            {
                // Swap the elements
                int temp = intArray[i];
                intArray[i] = intArray[j];
                intArray[j] = temp;
                i++;
                j--;
            }
        }

        // Recursive calls of QuickSort method
        if (leftSide < j)
        {
            QuickSortInt(intArray, leftSide, j);
        }

        if (i < rightSide)
        {
            QuickSortInt(intArray, i, rightSide);
        }

    }
}


text:
from pin.lib import p

import unittest
from tests import fixtures

class TestBanner(unittest.TestCase):

    def setUp(self):
        fixtures.reset()
        self.banner = p.modes["banner"]

    def test_enable(self):
        self.banner.enable()
        self.assertTrue(self.banner.enabled)

    def test_bypass(self):
        self.banner.enable()
        self.banner.bypass()
        self.assertFalse(self.banner.enabled)


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/sv_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:ignore="UselessLeaf,UselessParent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="200dp"
                tools:ignore="UselessLeaf,UselessParent" >

                <com.android.volley.toolbox.NetworkImageView
                    android:id="@+id/img_content"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scaleType="centerCrop"
                    tools:ignore="ContentDescription" />

                <TextView
                    android:id="@+id/tx_desc"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_marginTop="10dp"
                    android:padding="10dp"
                    android:textColor="#FFFFFF"
                    android:textSize="18sp" />
            </RelativeLayout>

            <com.qf.teach.project.zhihudaily.custom.CustomListViewForScrollView
                android:id="@+id/lv_theme"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:divider="#EEEEEE"
                android:dividerHeight="5dp"
                android:padding="10dp" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>


text:
<?php

namespace Magento\Customer\CustomerData;

/**
 * Js layout data provider pool
 */
class JsLayoutDataProviderPool implements JsLayoutDataProviderPoolInterface
{
    /**
     * Js layout data providers
     *
     * @var JsLayoutDataProviderInterface[]
     */
    protected $jsLayoutDataProviders;

    /**
     * Construct
     *
     * @param JsLayoutDataProviderInterface[] $jsLayoutDataProviders
     */
    public function __construct(
        array $jsLayoutDataProviders = []
    ) {
        $this->jsLayoutDataProviders = $jsLayoutDataProviders;
    }

    /**
     * {@inheritdoc}
     */
    public function getData()
    {
        $data = [];
        if ($this->jsLayoutDataProviders) {
            foreach ($this->jsLayoutDataProviders as $dataProvider) {
                $data = array_merge_recursive($data, $dataProvider->getData());
            }
        }
        return $data;
    }
}


text:
#if defined(XALAN_BUILD_DEPRECATED_DOM_BRIDGE)

#include "XercesNodeListBridge.hpp"

#include <cassert>

#include "XercesBridgeNavigator.hpp"

XALAN_CPP_NAMESPACE_BEGIN

XercesNodeListBridge::XercesNodeListBridge(
			const DOM_NodeListType&			theXercesNodeList,
			const XercesBridgeNavigator&	theNavigator) :
	XalanNodeList(),
	m_xercesNodeList(theXercesNodeList),
	m_navigator(theNavigator)
{
}

XercesNodeListBridge::~XercesNodeListBridge()
{
}

XercesNodeListBridge::XercesNodeListBridge(const XercesNodeListBridge&	theSource) :
	XalanNodeList(theSource),
	m_xercesNodeList(theSource.m_xercesNodeList),
	m_navigator(theSource.m_navigator)
{
}

XalanNode*
XercesNodeListBridge::item(unsigned int	index) const
{
	return m_navigator.mapNode(m_xercesNodeList.item(index));
}

unsigned int
XercesNodeListBridge::getLength() const
{
	return m_xercesNodeList.getLength();
}

XALAN_CPP_NAMESPACE_END

#endif //XALAN_BUILD_DEPRECATED_DOM_BRIDGE


text:
import { Skill } from "models/status";

export enum SkillActionType {
	Set = '[skill]::set',
	Delete = '[skill]::delete',
}

export interface SkillSetAction {
	readonly type: SkillActionType.Set;
	readonly skill: Skill | Skill[];
}

export interface SkillDeleteAction {
	readonly type: SkillActionType.Delete;
	readonly uuid: string | string[];
}

export type SkillAction =
	| SkillSetAction
	| SkillDeleteAction

export const SkillAction = {
	set(skill: Skill | Skill[]): SkillSetAction {
		return { type: SkillActionType.Set, skill };
	},
	delete(uuid: string | string[]): SkillDeleteAction {
		return { type: SkillActionType.Delete, uuid };
	},
}


text:
        <title>Designing Services That Deliver</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

            Designing Services That Deliver

Authors

G. Lynn Shostack

Year

Notes

Suggested as the seminal work in service blueprinting, which builds on a critique of services from a user point of view.

Tags

Relevance

Quotations

"The development of a new service is usually characterized by trial and error. Developers translate a subjective description of a need into an operational concept that may bear only a remote resemblance to the original idea. No one systematically quantifies the process or devises tests to ensure that the service is complete, rational, and fulfills the original need objectively."

"There are several reasons for the lack of analytical service systems designs. Services are unusual in that they have impact, but no form. Like light, they can't be physically stored or possessed and their consumption is often simultaneous with their production."

"It is important to watch out for parts of the service that the consumer does not see, like purchasing of supplies. Though invisible, these processes are important because changing them may alter the way consumers perceive the service."

"Isolating fail points. Having diagrammed the processes involved, the designer can now see where the system might go awry."

"A blueprint facilitates the analysis of cost-benefit trade-offs and can be used to test the appeal of different designs to prospective customers."

"Very little of this service is visible to customers. In fact, customers have virtually no conception of the processes that underlie most services."

Boundary Objects

Concepts

Field of Study

Methodology

References


text:
vagrant-webdev-nfs is a [Vagrant](http://www.vagrantup.com) based development box that can be used to quickly set-up a web development box. It is a fork of the [vagrant-webdev](https://github.com/hemenkapadia/vagrant-webdev) project, but modified to use `nfs` to sync folders between `GUEST` and `HOST` systems rather than the default VirtualBox mechanism. `nfs` is said to provide approx 10 to 100 times better performance than the default VirtualBox one.

Use vagrant-webdev-nfs if your `HOST` operating system is a Linux\Unix based system. If your `HOST` operating system is Windows then use [vagrant-webdev](https://github.com/hemenkapadia/vagrant-webdev) instead.

## What constitutes the development stack ?

The following forms the development stack

1. Ubuntu 14.04 (Trusty Thar) 32 bit base box.  (Referred to as `GUEST` throughout the document)
2. Oracle JDK 7
3. Apache Maven
4. Nodejs and NPM
5. yeoman stack
6. mongodb

## How do I start using vagrant-webdev-nfs?

I recommend  you use vagrant-webdev-nfs on Mac or any Linux\Unix environment. For Windows `HOST` systems I recommend using [vagrant-webdev](https://bitbucket.org/hemenkapadiapublic/vagrant-webdev).

### Step 1. System Set-up

Go ahead and get the following tools installed on your system (Referred to as `HOST` throughout the document)

1. [Git](http://git-scm.com/downloads)
2. [Virtualbox](https://www.virtualbox.org/wiki/Downloads)
3. [Vagrant](https://www.vagrantup.com/downloads.html)
4. [nfs-kernel-server](https://coderwall.com/p/uaohzg), [nfs-common and portmap](https://coderwall.com/p/uaohzg)

To know more about NFS performance read

1. [Use NFS to speed up your Vagrant ](https://coderwall.com/p/uaohzg)
2. [NFS shared folders](http://friendsofvagrant.github.io/v1/docs/nfs.html)

I also assume a directory structure as follows. So go ahead and create one as mentioned below

	| Your home directory
	|--- projects
	|------ vagrant-webdev-workspace
	|------ vagrant-webdev-m2

> vagrant-webdev-workspace and vagrant-webdev-m2 are important shared folders between your `GUEST` and `HOST`.

> Workspace folder will contain your development code, such that you can use tools that you are comfortable with (IDE, Browser etc.) on your `HOST` for development and testing. The code that you develop will then be built and deployed on the `GUEST` environment.

> M2 folder is your maven repository, needed for dependency resolution in your IDE on `HOST` as well as for building on `GUEST`.

### Step 2. Clone the GitHub repository

Follow these commands to clone the vagrant-webdev repository on the `HOST`

	cd ~
	cd projects
	git clone https://github.com/hemenkapadia/vagrant-webdev-nfs.git

This will clone the vagrant-webdev-nfs code from git on your machine and your directory structure would look like

	| Your home directory
	|--- projects
	|------ vagrant-webdev-workspace
	|------ vagrant-webdev-m2
	|------ vagrant-webdev-nfs

### Step 3. Start the `GUEST` machine

Follow these commands to start the `GUEST` machine as a virtual machine running in your `HOST` environment

	cd ~
	cd projects
	cd vagrant-webdev-nfs
	vagrant up

This step will take a long time to complete for the first time, so have some patience.

> For the first time, vagrant will download the Ubuntu base box (approx 300 MB) and provision it. During provisioning, it also downloads the Oracle JDK 7 installer (approx 150 MB) which also takes time depending on your internet connection. Be patient, as long as you do not see any error you should be good.

If the above step completed successfully you have a fully operational web development system ready at your disposal, with all the tools mentioned in the development stack above pre-installed for you.

### Step 4. Connect to the `GUEST` and verify

To connect to your vagrant-webdev development environment issue the command in the vagrant-webdev directory

	vagrant ssh

This will open up a SSH session with the `GUEST` and issue you a prompt as shown below

	hemen@hemen-MXC061:~/projects/vagrant-webdev-nfs$ vagrant ssh
	Welcome to Ubuntu 14.04 LTS (GNU/Linux 3.13.0-30-generic i686)

    Documentation:  https://help.ubuntu.com/

    System information disabled due to load higher than 1.0

    Get cloud support with Ubuntu Advantage Cloud Guest:
      http://www.ubuntu.com/business/services/cloud

    0 packages can be updated.
    0 updates are security updates.

    vagrant@vagrant-ubuntu-trusty-32:~$

Notice the change in the prompt. It indicates that you are now on the `GUEST` box.

I use the following commands to ensure vagrant-webdev-nfs has been provisioned correctly. Verify once your machine is up too.

	vagrant@vagrant-ubuntu-trusty-32:~$ java -version
	java version "1.7.0_60"
    Java(TM) SE Runtime Environment (build 1.7.0_60-b19)
    Java HotSpot(TM) Client VM (build 24.60-b09, mixed mode)
    vagrant@vagrant-ubuntu-trusty-32:~$ mvn -version
    Apache Maven 3.0.5
    Maven home: /usr/share/maven
    Java version: 1.7.0_60, vendor: Oracle Corporation
    Java home: /usr/lib/jvm/java-7-oracle/jre
    Default locale: en_US, platform encoding: UTF-8
    OS name: "linux", version: "3.13.0-30-generic", arch: "i386", family: "unix"
    vagrant@vagrant-ubuntu-trusty-32:~$ mongod -version
    db version v2.4.10
    Wed Jul  2 17:10:54.326 git version: e3d78955d181e475345ebd60053a4738a4c5268a
    vagrant@vagrant-ubuntu-trusty-32:~$ mongo -version
    MongoDB shell version: 2.4.10
    vagrant@vagrant-ubuntu-trusty-32:~$ node -v
    v0.10.29
    vagrant@vagrant-ubuntu-trusty-32:~$ npm -v
    1.4.14
    vagrant@vagrant-ubuntu-trusty-32:~$ yo -v
    [?] ==========================================================================
    We're constantly looking for ways to make yo better!
    May we anonymously report usage statistics to improve the tool over time?
    More info: https://github.com/yeoman/insight & http://yeoman.io
    ==========================================================================: No
    1.2.0
    vagrant@vagrant-ubuntu-trusty-32:~$ env | grep java
	vagrant@vagrant-ubuntu-trusty-32:~$ npm -v
	1.4.14
	vagrant@vagrant-ubuntu-trusty-32:~$ yo -v
	[?] ==========================================================================
	We're constantly looking for ways to make yo better!
	May we anonymously report usage statistics to improve the tool over time?
	More info: https://github.com/yeoman/insight & http://yeoman.io
	==========================================================================: No
	1.2.0
	vagrant@vagrant-ubuntu-trusty-32:~$ env | grep java
    DERBY_HOME=/usr/lib/jvm/java-7-oracle/db
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/java-7-oracle/bin:/usr/
    lib/jvm/java-7-oracle/db/bin:/usr/lib/jvm/java-7-oracle/jre/bin
    JAVA_HOME=/usr/lib/jvm/java-7-oracle
    NODE_PATH=/usr/lib/nodejs:/usr/lib/node_modules:/usr/share/javascript
    J2SDKDIR=/usr/lib/jvm/java-7-oracle
    J2REDIR=/usr/lib/jvm/java-7-oracle/jre
    vagrant@vagrant-ubuntu-trusty-32:~$ env | grep maven
    vagrant@vagrant-ubuntu-trusty-32:~$

## How can I contribute ?

### Branch or Fork ?

The first and foremost requirement to contribute is to have a GitHub account, so as a first step please [register with GitHub](https://github.com/).

> Currently, I do not plan to add other additional features to vagrant-webdev-nfs unless it is really value adding.

As a result of the above guideline, there are two options available for you to contribute.

* __Branch__: If you are planning to fix a bug in the current code or in general improving the way things are implemented, without adding new features, you need to create a Branch. In case you are planning to add new features or packages please do __NOT__ create a Branch, but create a Fork. I discuss branching in more detail below.
* __Fork__: If you intend to use vagrant-webdev as a base and then want to modify it (e.g. remove mongodb and add MySQL) or want to add additional packages, then you need to create a Fork. That way none of the changes you make in your fork move to my repository, but there is a linkage maintained. You can continue working independently on your Fork which is identical to it's parent repository when you forked it.

### Git Flow.

If you are new to Git, then I strongly recommend reading the following in order before you proceed to contribute to the repository.

* [Git Branching chapter](https://www.atlassian.com/git/tutorial/git-branches)
* [Git Workflows chapter](https://www.atlassian.com/git/tutorials/comparing-workflows/)
* [Vincent Driessen's - A successful Git branching model](http://nvie.com/posts/a-successful-git-branching-model/)
* [A cheatsheet for Vincent's branching model](http://www.marvinlabs.com/wp-content/uploads/2013/06/git-flow-cheatsheet.pdf)
* [Gitflow

The branching model suggested by Vincent is excellent and strongly recommended in any Enterprise development scenario. If you are interested in implementing the same I suggest you also read about [git-flow - a plugin that makes it much easier to follow Vincent's approach](http://danielkummer.github.io/git-flow-cheatsheet/)

### GitHub Flow

However for this project (and possibly all my other repositories) I would use only a subset of the workflow suggested by Vincent.

Read the below two articles completely

* [GitHub flow](https://guides.github.com/introduction/flow/)
* [Comparision of Git flow and GitHub flow](http://nicoespeon.com/en/2013/08/which-git-workflow-for-my-project/)

Our repository will have a single long running branch

* __master__: This is the main branch, and is expected to be extremely stable. This branch will be cloned by most people who would want to start using vagrant-webdev, hence the stability requirement. It is recommended not to push directly to master unless the change is extremely small and you are sure it will not impact anything and have thoroughly tested it. I would still recommend not to push directly to master.

If there is a new feature we would agree to add, then we would create a new feature branch to track that development

* __feature branches__: A single feature branch is created to logically track an individual feature being developed, on which multiple developers could be working. The naming convention to follow for a feature branch is __feature_name__. A single developer can work on more than one feature.

#### GitHub Flow steps

I suggest each developer follow the below process to contribute new features

1. Create a new feature branch locally as well as on the remote (if it does not exists). Creating on remote is very important because you would want to collaborate with others who would want to work on the same feature. Additionally it would also avoid work duplication. Feature branch is created from master.
2. Develop on your local feature branch, and push frequently to the remote feature branch.
3. Periodically monitor any changes made to master after you created the feature branch from master in step 1 above. If there are any changes, merge them to your feature branch.
4. Once feature is complete and tested to be working fine, open a pull request for merging back to master.
5. A code review process will follow.
6. Post successful code review the new feature branch will be merged into master.
7. The feature branch will be deleted on remote, and ideally should be deleted locally too.

That's it. Feel free to participate.


text:
'use strict';

import gulp from 'gulp';
import browserSync from 'browser-sync';

gulp.task('browserSync', () => {

	return browserSync.init({
		server: {
			baseDir: global.config.const_settings.distLocation,
			index: 'index.html',
		},
		ui: false,
		open: false,
	});

});


text:
package main

import (
	"errors"
	"flag"
	"fmt"
	"net/http"
	gourl "net/url"
	"os"
	"regexp"
	"runtime"
	"strings"

	"github.com/rakyll/boom/boomer"
)

const (
	headerRegexp = "^([\\w-]+):\\s*(.+)"
	authRegexp   = "^([\\w-\\.]+):(.+)"
)

var (
	m           = flag.String("m", "GET", "")
	headers     = flag.String("h", "", "")
	body        = flag.String("d", "", "")
	accept      = flag.String("A", "", "")
	contentType = flag.String("T", "text/html", "")
	authHeader  = flag.String("a", "", "")

	output = flag.String("o", "", "")

	c    = flag.Int("c", 50, "")
	n    = flag.Int("n", 200, "")
	q    = flag.Int("q", 0, "")
	t    = flag.Int("t", 0, "")
	cpus = flag.Int("cpus", runtime.GOMAXPROCS(-1), "")

	insecure           = flag.Bool("allow-insecure", false, "")
	disableCompression = flag.Bool("disable-compression", false, "")
	disableKeepAlives  = flag.Bool("disable-keepalive", false, "")
	proxyAddr          = flag.String("x", "", "")
)

var usage = `Usage: boom [options...] <url>

Options:
  -n  Number of requests to run.
  -c  Number of requests to run concurrently. Total number of requests cannot
      be smaller than the concurency level.
  -q  Rate limit, in seconds (QPS).
  -o  Output type. If none provided, a summary is printed.
      "csv" is the only supported alternative. Dumps the response
      metrics in comma-seperated values format.

  -m  HTTP method, one of GET, POST, PUT, DELETE, HEAD, OPTIONS.
  -h  Custom HTTP headers, name1:value1;name2:value2.
  -t  Timeout in ms.
  -A  HTTP Accept header.
  -d  HTTP request body.
  -T  Content-type, defaults to "text/html".
  -a  Basic authentication, username:password.
  -x  HTTP Proxy address as host:port.

  -allow-insecure       Allow bad/expired TLS/SSL certificates.
  -disable-compression  Disable compression.
  -disable-keepalive    Disable keep-alive, prevents re-use of TCP
                        connections between different HTTP requests.
  -cpus                 Number of used cpu cores.
                        (default for current machine is %d cores)
`

func main() {
	flag.Usage = func() {
		fmt.Fprint(os.Stderr, fmt.Sprintf(usage, runtime.NumCPU()))
	}

	flag.Parse()
	if flag.NArg() < 1 {
		usageAndExit("")
	}

	runtime.GOMAXPROCS(*cpus)
	num := *n
	conc := *c
	q := *q

	if num <= 0 || conc <= 0 {
		usageAndExit("n and c cannot be smaller than 1.")
	}

	var (
		url, method string
		// Username and password for basic auth
		username, password string
		// request headers
		header http.Header = make(http.Header)
	)

	url = flag.Args()[0]
	method = strings.ToUpper(*m)

	// set content-type
	header.Set("Content-Type", *contentType)
	// set any other additional headers
	if *headers != "" {
		headers := strings.Split(*headers, ";")
		for _, h := range headers {
			match, err := parseInputWithRegexp(h, headerRegexp)
			if err != nil {
				usageAndExit(err.Error())
			}
			header.Set(match[1], match[2])
		}
	}

	if *accept != "" {
		header.Set("Accept", *accept)
	}

	// set basic auth if set
	if *authHeader != "" {
		match, err := parseInputWithRegexp(*authHeader, authRegexp)
		if err != nil {
			usageAndExit(err.Error())
		}
		username, password = match[1], match[2]
	}

	if *output != "csv" && *output != "" {
		usageAndExit("Invalid output type; only csv is supported.")
	}

	var proxyURL *gourl.URL
	if *proxyAddr != "" {
		var err error
		proxyURL, err = gourl.Parse(*proxyAddr)
		if err != nil {
			usageAndExit(err.Error())
		}
	}

	(&boomer.Boomer{
		Req: &boomer.ReqOpts{
			Method:   method,
			URL:      url,
			Body:     *body,
			Header:   header,
			Username: username,
			Password: password,
		},
		N:                  num,
		C:                  conc,
		Qps:                q,
		Timeout:            *t,
		AllowInsecure:      *insecure,
		DisableCompression: *disableCompression,
		DisableKeepAlives:  *disableKeepAlives,
		ProxyAddr:          proxyURL,
		Output:             *output,
	}).Run()
}

func usageAndExit(message string) {
	if message != "" {
		fmt.Fprintf(os.Stderr, message)
		fmt.Fprintf(os.Stderr, "\n\n")
	}
	flag.Usage()
	fmt.Fprintf(os.Stderr, "\n")
	os.Exit(1)
}

func parseInputWithRegexp(input, regx string) ([]string, error) {
	re := regexp.MustCompile(regx)
	matches := re.FindStringSubmatch(input)
	if len(matches) < 1 {
		return nil, errors.New("Could not parse provided input")
	}
	return matches, nil
}


text:
#include "AbstractParam.h"

namespace RAML
{
    std::string AbstractParam::getDefaultValue() const
    {
        return m_defaultValue;
    }
    void AbstractParam::setDefaultValue(const std::string &defaultValue)
    {
        m_defaultValue = defaultValue;
    }

    std::string AbstractParam::getDescription() const
    {
        return m_description;
    }

    void AbstractParam::setDescription(const std::string &description)
    {
        m_description = description;
    }

    std::string AbstractParam::getDisplayName() const
    {
        return m_displayName;
    }

    void AbstractParam::setDisplayName(const std::string &displayName)
    {
        m_displayName = displayName;
    }

    std::list<std::string> AbstractParam::getEnumeration() const
    {
        return m_enumeration;
    }

    void AbstractParam::setEnumeration(const std::string &enumeration)
    {
        m_enumeration.push_back(enumeration);
    }

    std::string AbstractParam::getExample() const
    {
        return m_example;
    }

    void AbstractParam::setExample(const std::string &example)
    {
        m_example = example;
    }

    int AbstractParam::getMaxLength() const
    {
        return m_maxLength;
    }

    void AbstractParam::setMaxLength(int maxLength)
    {
        m_maxLength = maxLength;
    }

    int AbstractParam::getMaximum() const
    {
        return m_maximum;
    }

    void AbstractParam::setMaximum(int maximum)
    {
        m_maximum = maximum;
    }

    int AbstractParam::getMinLength() const
    {
        return m_minLength;
    }

    void AbstractParam::setMinLength(int minLength)
    {
        m_minLength = minLength;
    }

    int AbstractParam::getMinimum() const
    {
        return m_minimum;
    }

    void AbstractParam::setMinimum(int minimum)
    {
        m_minimum = minimum;
    }

    std::string AbstractParam::getPattern() const
    {
        return m_pattern;
    }

    void AbstractParam::setPattern(const std::string &pattern)
    {
        m_pattern = pattern;
    }

    std::string AbstractParam::getType() const
    {
        return m_type;
    }

    void AbstractParam::setType(const std::string &type)
    {
        m_type = type;
    }

    bool AbstractParam::isRepeat() const
    {
        return m_repeat;
    }

    void AbstractParam::setRepeat(bool repeat)
    {
        m_repeat = repeat;
    }

    bool AbstractParam::isRequired() const
    {
        return m_required;
    }

    void AbstractParam::setRequired(bool required)
    {
        m_required = required;
    }

    void AbstractParam::readParameters(const YAML::Node &yamlNode)
    {
        for ( YAML::const_iterator it = yamlNode.begin(); it != yamlNode.end(); ++it )
        {
            std::string key = READ_NODE_AS_STRING(it->first);

            if (key == Keys::Description)
            {
                setDescription(READ_NODE_AS_STRING(it->second));
            }
            else if (key == Keys::Default)
            {
                setDefaultValue(READ_NODE_AS_STRING(it->second));
            }
            else if (key == Keys::DisplayName)
            {
                setDisplayName(READ_NODE_AS_STRING(it->second));
            }
            else if (key == Keys::Example)
            {
                setExample(READ_NODE_AS_STRING(it->second));
            }
            else if (key == Keys::Maximum)
            {
                setMaximum(READ_NODE_AS_LONG(it->second));
            }
            else if (key == Keys::Minimum)
            {
                setMinimum(READ_NODE_AS_LONG(it->second));
            }
            else if (key == Keys::MaxLength)
            {
                setMaxLength(READ_NODE_AS_INT(it->second));
            }
            else if (key == Keys::MinLength)
            {
                setMinLength(READ_NODE_AS_INT(it->second));
            }
            else if (key == Keys::Pattern)
            {
                setPattern(READ_NODE_AS_STRING(it->second));
            }
            else if (key == Keys::Repeat)
            {
                setRepeat(READ_NODE_AS_BOOL(it->second));
            }
            else if (key == Keys::Required)
            {
                setRequired(READ_NODE_AS_BOOL(it->second));
            }
            else if (key == Keys::Type)
            {
                setType(READ_NODE_AS_STRING(it->second));
            }
            else if (key == Keys::Enum)
            {
                YAML::Node enumNode = it->second;
                for ( YAML::const_iterator tt = enumNode.begin(); tt != enumNode.end(); ++tt )
                {
                    setEnumeration(READ_NODE_AS_STRING(*tt));
                }
            }
        }
    }
}


text:
 {{'APPLICATIONS.TOPOLOGY.TASK.ERRORS_LABEL' | translate}}

      <node-filters-errors-display
        tasks = "deploymentContext.deploymentTopologyDTO.validation.taskList['NODE_FILTER_INVALID']"
        input-column=true>
      </node-filters-errors-display>

      <scalability-errors-display
        tasks="deploymentContext.deploymentTopologyDTO.validation.taskList['SCALABLE_CAPABILITY_INVALID']">
      </scalability-errors-display>

      <properties-errors-display
        tasks = "deploymentContext.deploymentTopologyDTO.validation.taskList['PROPERTIES']">
      </properties-errors-display>

      <input-artifacts-errors-display
              tasks = "deploymentContext.deploymentTopologyDTO.validation.taskList['INPUT_ARTIFACT_INVALID']">
      </input-artifacts-errors-display>

    <fieldset class="detail-bloc">
      <legend>

            {{'APPLICATIONS.TOPOLOGY.PROPERTIES_INPUTS' | translate}}

      </legend>

              <property-display definition="inputDefinition"
                                property-type="deploymentContext.deploymentTopologyDTO.dataTypes[inputDefinition.type]"
                                dependencies="deploymentContext.deploymentTopologyDTO.topology.dependencies"
                                property-name="inputId"
                                property-value="deploymentContext.deploymentTopologyDTO.topology.inputProperties[inputId]"
                                on-save="updateInputValue(propertyDefinition, propertyValue, inputId)"
                                editable="deploymentContext.selectedEnvironment.status === 'UNDEPLOYED'"
                                condensed="true">
              </property-display>

    </fieldset>

    <fieldset class="detail-bloc">
      <legend>

           {{'APPLICATIONS.TOPOLOGY.ARTIFACTS.INPUTS' | translate}}

      </legend>

            {{artifactKey}}

{{'COMMON.TYPE' | translate}}

{{artifactValue.artifactType}}

{{'APPLICATIONS.TOPOLOGY.REFERENCE' | translate}}

                   20]}}">{{artifactValue.artifactName | truncate:20}}

                      <input type="file" class="upload" ng-file-select="onArtifactSelected($files, artifactKey, inputArtifactValue)">

                  <progressbar ng-if="uploads[artifactKey].isUploading" class="progress-striped active" value="uploads[artifactKey].uploadProgress"
                               type="{{uploads[artifactKey].type}}" />

    </fieldset>

    <fieldset class="detail-bloc">
      <legend>

           {{'APPLICATIONS.TOPOLOGY.ORCHESTRATOR_PROPERTIES' | translate}}

      </legend>

              <property-display ng-init="condensed = true"
                                definition="propertyDefinition"
                                property-name="propertyKey"
                                property-value="deploymentContext.deploymentTopologyDTO.topology.providerDeploymentProperties[propertyKey]"
                                on-save="updateDeploymentProperty(propertyDefinition, propertyKey, propertyValue)"
                                editable="deploymentContext.selectedEnvironment.status === 'UNDEPLOYED'"
                                condensed="condensed">
              </property-display>

    </fieldset>


text:
__docformat__ = 'restructuredtext'

# Let users know if they're missing any of our hard dependencies
hard_dependencies = ("numpy", "pytz", "dateutil")
missing_dependencies = []

for dependency in hard_dependencies:
    try:
        __import__(dependency)
    except ImportError as e:
        missing_dependencies.append(dependency)

if missing_dependencies:
    raise ImportError("Missing required dependencies {0}".format(missing_dependencies))

# numpy compat
from pandas.compat.numpy import *

try:
    from pandas import hashtable, tslib, lib
except ImportError as e:  # pragma: no cover
    module = str(e).lstrip('cannot import name ')  # hack but overkill to use re
    raise ImportError("C extension: {0} not built. If you want to import "
                      "pandas from the source directory, you may need to run "
                      "'python setup.py build_ext --inplace' to build the C "
                      "extensions first.".format(module))

from datetime import datetime
from pandas.info import __doc__

# let init-time option registration happen
import pandas.core.config_init

from pandas.core.api import *
from pandas.sparse.api import *
from pandas.stats.api import *
from pandas.tseries.api import *
from pandas.io.api import *
from pandas.computation.api import *

from pandas.tools.merge import merge, concat, ordered_merge
from pandas.tools.pivot import pivot_table, crosstab
from pandas.tools.plotting import scatter_matrix, plot_params
from pandas.tools.tile import cut, qcut
from pandas.tools.util import to_numeric
from pandas.core.reshape import melt
from pandas.util.print_versions import show_versions

# define the testing framework
import pandas.util.testing
from pandas.util.nosetester import NoseTester
test = NoseTester().test
del NoseTester

# use the closest tagged version if possible
from ._version import get_versions
v = get_versions()
__version__ = v.get('closest-tag',v['version'])
del get_versions, v


text:
#include "CollectProto.h"
#include "RegUtil.h"

class SoftwareCollector:
	public AutoCreateDataCollector<SoftwareCollector>,
	public RegUtilLocal<SoftwareCollector>
{
public:
	long Collect(NVDataItem ** ReturnItem);
	virtual ~SoftwareCollector() {};

private:
	long CollectSingleProgram (HKEY SubKey, char * SubKeyName, NVDataItem * TargetData, bool * KeepItem);

};

#endif


text:
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System;
using System.DirectoryServices;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;

namespace TfsOnlineSDK {

    class Program {

        static void Main(string[] args) {

            var tfsUrl = "https://epeinnovations.visualstudio.com";
            var userName = "marco.baccaro@epeinnovations.com";
            var password = "Elroy1981";

            //CreateLabel(tfsUrl, userName, password);
            RemoveXAMLBuildController(new Uri("https://epeinnovations.visualstudio.com"), "jeuxq5v546nq5feddzpxfnzcz57sweambeg45gr2nuwz5f3oj2yq", "marco.baccaro@epeinnovations.com");

        }

        private static void RemoveXAMLBuildController(Uri uri, string pat, string name) {

            NetworkCredential networkCredential = new NetworkCredential("marco.baccaro@epeinnovations.com", pat);
            BasicAuthCredential basicCredential = new BasicAuthCredential(networkCredential);

            TfsClientCredentials tfsCredentials = new TfsClientCredentials(basicCredential);
            tfsCredentials.AllowInteractive = false;
            var server = new TfsTeamProjectCollection(uri, tfsCredentials);

            server.Authenticate();
            var buildServer = (IBuildServer)server.GetService(typeof(IBuildServer));
            var controller = buildServer.QueryBuildControllers().FirstOrDefault();

            if (controller == null) {
                Console.WriteLine($"No XAML controllers found with name '{name}'");
            } else {

                if (controller.Agents.Count > 0) {
                    Console.WriteLine("Deleting build agents in controller");
                    buildServer.DeleteBuildAgents(controller.Agents.ToArray());
                }

                Console.WriteLine($"Deleting build controller '{name}'");
                buildServer.DeleteBuildControllers(new IBuildController[] { controller });

            }

        }

        public static void CreateLabel(string tfsUrl, string userName, string password) {

            BasicAuthCredential basicCred = new BasicAuthCredential(new NetworkCredential("mbaccaro", "Elroy1981"));
            TfsClientCredentials credential = new TfsClientCredentials(basicCred);
            //credential.AllowInteractive = false;

            var tfs = new TfsTeamProjectCollection(new Uri(tfsUrl), credential);
            var versioncontrols = tfs.GetService<VersionControlServer>();

            Microsoft.TeamFoundation.Framework.Client.TeamFoundationIdentity identity;
            tfs.GetAuthenticatedIdentity(out identity);

            string labelScope = "$/QlikviewExtension";
            string labelComment = "Example label showing API usage";
            VersionControlLabel labelToCreate = new VersionControlLabel(versioncontrols, "TestMarco", identity.DisplayName, labelScope, labelComment);
            LabelItemSpec[] labelItemSpecs = new LabelItemSpec[1];
            ItemSpec itemSpec = new ItemSpec("$/QlikviewExtension/Main/QlikviewExtensions/EPE.QlikviewExtensions/EpeInnovations/Donut/", RecursionType.Full);
            labelItemSpecs[0] = new LabelItemSpec(itemSpec, VersionSpec.Latest, false);

            versioncontrols.DeleteLabel("TestMarco 20160817 115444", labelScope);
            LabelResult[] result = versioncontrols.CreateLabel(labelToCreate, labelItemSpecs, LabelChildOption.Replace);

        }

    }

}


text:
{-# LANGUAGE MagicHash, NoImplicitPrelude, BangPatterns, UnliftedFFITypes #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  GHC.CString
-- Copyright   :  (c) The University of Glasgow 2011
-- License     :  see libraries/ghc-prim/LICENSE
--
-- Maintainer  :  cvs-ghc@haskell.org
-- Stability   :  internal
-- Portability :  non-portable (GHC Extensions)
--
-- GHC C strings definitions (previously in GHC.Base).
-- Use GHC.Exts from the base package instead of importing this
-- module directly.
--
-----------------------------------------------------------------------------

module GHC.CString (
        JString(..), JString#, JByteArray(..), JByteArray#,
        getBytesUtf8#, indexStrChar#, byteArrayLength,
        unpackCString#, unpackAppendCString#, unpackFoldrCString#,
        unpackCStringUtf8#, unpackNBytes#
    ) where

import GHC.Types
import GHC.Prim

type JString# = Object# JString -- convenience

data {-# CLASS "byte[]" #-} JByteArray = JByteArray (Object# JByteArray)
type JByteArray# = Object# JByteArray

foreign import java unsafe "@static eta.ghc_prim.Utils.byteBufferToBytes"
  getBytes :: Addr# -> Int# -> JByteArray#

getBytesUtf8# :: Addr# -> Int# -> JByteArray#
getBytesUtf8# a len = getBytes a len

byteArrayLength :: JByteArray# -> Int#
byteArrayLength x = alength# x

indexStrChar# :: JByteArray# -> Int# -> Char#
indexStrChar# bytes n = jbyte2char# (indexJByteArray# bytes n)

-----------------------------------------------------------------------------
-- Unpacking C strings}
-----------------------------------------------------------------------------

-- This code is needed for virtually all programs, since it's used for
-- unpacking the strings of error messages.

-- Used to be in GHC.Base, but was moved to ghc-prim because the new generics
-- stuff uses Strings in the representation, so to give representations for
-- ghc-prim types we need unpackCString#

{- Note [Inlining unpackCString#]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There's really no point in ever inlining things like unpackCString# as the loop
doesn't specialise in an interesting way and we can't deforest the list
constructors (we'd want to use unpackFoldrCString# for this). Moreover, it's
pretty small, so there's a danger that it'll be inlined at every literal, which
is a waste.

Moreover, inlining early may interfere with a variety of rules that are supposed
to match unpackCString#,

 * BuiltInRules in PrelRules.hs; e.g.
       eqString (unpackCString# (Lit s1)) (unpackCString# (Lit s2)
          = s1 == s2

 * unpacking rules; e.g. in GHC.Base,
       unpackCString# a
          = build (unpackFoldrCString# a)

 * stream fusion rules; e.g. in the `text` library,
       unstream (S.map safe (S.streamList (GHC.unpackCString# a)))
          = unpackCString# a

Moreover, we want to make it CONLIKE, so that:

* the rules in PrelRules will fire when the string is let-bound.
  E.g. the eqString rule in PrelRules
   eqString (unpackCString# (Lit s1)) (unpackCString# (Lit s2) = s1==s2

* exprIsConApp_maybe will see the string when we have
     let x = unpackCString# "foo"#
     ...(case x of algs)...

All of this goes for unpackCStringUtf8# too.
-}

unpackCString# :: Addr# -> [Char]
{-# NOINLINE CONLIKE unpackCString# #-}
    -- There's really no point in inlining this, ever, as the loop doesn't
    -- specialise in an interesting But it's pretty small, so there's a danger
    -- that it'll be inlined at every literal, which is a waste
unpackCString# addr
  = unpack 0#
  where
    unpack nh
      | isTrue# (ch `eqChar#` '\0'#) = []
      | True                         = C# ch : unpack (nh +# 1#)
      where
        !ch = indexCharOffAddr# addr nh

unpackAppendCString# :: Addr# -> [Char] -> [Char]
{-# NOINLINE unpackAppendCString# #-}
     -- See the NOINLINE note on unpackCString#
unpackAppendCString# addr rest
  = unpack 0#
  where
    unpack nh
      | isTrue# (ch `eqChar#` '\0'#) = rest
      | True                         = C# ch : unpack (nh +# 1#)
      where
        !ch = indexCharOffAddr# addr nh

unpackFoldrCString# :: Addr# -> (Char -> a -> a) -> a -> a

-- Usually the unpack-list rule turns unpackFoldrCString# into unpackCString#

-- It also has a BuiltInRule in PrelRules.lhs:
--      unpackFoldrCString# "foo" c (unpackFoldrCString# "baz" c n)
--        =  unpackFoldrCString# "foobaz" c n

{-# NOINLINE unpackFoldrCString# #-}
-- At one stage I had NOINLINE [0] on the grounds that, unlike
-- unpackCString#, there *is* some point in inlining
-- unpackFoldrCString#, because we get better code for the
-- higher-order function call.  BUT there may be a lot of
-- literal strings, and making a separate 'unpack' loop for
-- each is highly gratuitous.  See nofib/real/anna/PrettyPrint.

unpackFoldrCString# addr f z
  = unpack 0#
  where
    unpack nh
      | isTrue# (ch `eqChar#` '\0'#) = z
      | True                         = C# ch `f` unpack (nh +# 1#)
      where
        !ch = indexCharOffAddr# addr nh

-- There's really no point in inlining this for the same reasons as
-- unpackCString. See Note [Inlining unpackCString#] above for details.
unpackCStringUtf8# :: Addr# -> [Char]
{-# NOINLINE CONLIKE unpackCStringUtf8# #-}
unpackCStringUtf8# addr
  = unpack 0#
  where
    -- We take care to strictly evaluate the character decoding as
    -- indexCharOffAddr# is marked with the can_fail flag and
    -- consequently GHC won't evaluate the expression unless it is absolutely
    -- needed.
    unpack nh
      | isTrue# (ch `eqChar#` '\0'#  ) = []
      | isTrue# (ch `leChar#` '\x7F'#) = C# ch : unpack (nh +# 1#)
      | isTrue# (ch `leChar#` '\xDF'#) =
          let !c = C# (chr# (((ord# ch                                  -# 0xC0#) `uncheckedIShiftL#`  6#) +#
                              (ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#)))
          in c : unpack (nh +# 2#)
      | isTrue# (ch `leChar#` '\xEF'#) =
          let !c = C# (chr# (((ord# ch                                  -# 0xE0#) `uncheckedIShiftL#` 12#) +#
                             ((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#`  6#) +#
                              (ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#)))
          in c : unpack (nh +# 3#)
      | True                           =
          let !c = C# (chr# (((ord# ch                                  -# 0xF0#) `uncheckedIShiftL#` 18#) +#
                             ((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#` 12#) +#
                             ((ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#) `uncheckedIShiftL#`  6#) +#
                              (ord# (indexCharOffAddr# addr (nh +# 3#)) -# 0x80#)))
          in c : unpack (nh +# 4#)
      where
        !ch = indexCharOffAddr# addr nh

-- There's really no point in inlining this for the same reasons as
-- unpackCString. See Note [Inlining unpackCString#] above for details.
unpackNBytes# :: Addr# -> Int# -> [Char]
{-# NOINLINE unpackNBytes# #-}
unpackNBytes# _addr 0#   = []
unpackNBytes#  addr len# = unpack [] (len# -# 1#)
    where
     unpack acc i#
      | isTrue# (i# <# 0#)  = acc
      | True                =
         case indexCharOffAddr# addr i# of
            ch -> unpack (C# ch : acc) (i# -# 1#)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>The nova.tests.test_powervm Module — nova 2012.2.1 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/tweaks.css" type="text/css" />

    <link rel="top" title="nova 2012.2.1 documentation" href="../index.html" />
    <link rel="up" title="<no title>" href="autoindex.html" />
    <link rel="next" title="The nova.tests.test_quota Module" href="nova.tests.test_quota.html" />
    <link rel="prev" title="The nova.tests.test_policy Module" href="nova.tests.test_policy.html" />

OpenStack

Home

Projects

User Stories

Community

Blog

Wiki

Documentation

The <tt class="xref py py-mod docutils literal">nova.tests.test_powervm</tt> Module¶

Test suite for PowerVMDriver.

class <tt class="descname">FakeIVMOperator</tt>¶

Bases: <tt class="xref py py-class docutils literal">object</tt>

<tt class="descname">attach_disk_to_vhost</tt><big>(</big>disk, vhost<big>)</big>¶

<tt class="descname">copy_file_to_device</tt><big>(</big>sourcePath, device<big>)</big>¶

<tt class="descname">copy_image_file</tt><big>(</big>sourcePath, remotePath<big>)</big>¶

<tt class="descname">create_logical_volume</tt><big>(</big>size<big>)</big>¶

<tt class="descname">create_lpar</tt><big>(</big>lpar<big>)</big>¶

<tt class="descname">get_cpu_info</tt><big>(</big><big>)</big>¶

<tt class="descname">get_disk_info</tt><big>(</big><big>)</big>¶

<tt class="descname">get_disk_name_by_vhost</tt><big>(</big>vhost<big>)</big>¶

<tt class="descname">get_lpar</tt><big>(</big>instance_name, resource_type='lpar'<big>)</big>¶

<tt class="descname">get_memory_info</tt><big>(</big><big>)</big>¶

<tt class="descname">get_vhost_by_instance_id</tt><big>(</big>instance_id<big>)</big>¶

<tt class="descname">get_virtual_eth_adapter_id</tt><big>(</big><big>)</big>¶

<tt class="descname">list_lpar_instances</tt><big>(</big><big>)</big>¶

<tt class="descname">remove_disk</tt><big>(</big>disk_name<big>)</big>¶

<tt class="descname">remove_logical_volume</tt><big>(</big>lv_name<big>)</big>¶

<tt class="descname">remove_lpar</tt><big>(</big>instance_name<big>)</big>¶

<tt class="descname">run_cfg_dev</tt><big>(</big>device_name<big>)</big>¶

<tt class="descname">start_lpar</tt><big>(</big>instance_name<big>)</big>¶

<tt class="descname">stop_lpar</tt><big>(</big>instance_name<big>)</big>¶

class <tt class="descname">PowerVMDriverTestCase</tt><big>(</big>methodName='runTest'<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">nova.test.TestCase</tt>

Unit tests for PowerVM connection calls.

<tt class="descname">setUp</tt><big>(</big><big>)</big>¶

<tt class="descname">test_destroy</tt><big>(</big><big>)</big>¶

<tt class="descname">test_get_info</tt><big>(</big><big>)</big>¶

<tt class="descname">test_instance_exists</tt><big>(</big><big>)</big>¶

<tt class="descname">test_list_instances</tt><big>(</big><big>)</big>¶

<tt class="descname">test_spawn</tt><big>(</big><big>)</big>¶

<tt class="descname">fake_get_powervm_operator</tt><big>(</big><big>)</big>¶

<tt class="descname">fake_lpar</tt><big>(</big>instance_name<big>)</big>¶

Previous topic

The <tt class="docutils literal docutils literal docutils literal">nova.tests.test_policy</tt> Module

Next topic

The <tt class="docutils literal">nova.tests.test_quota</tt> Module

This Page

Show Source

Quick search

              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>

              Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

nova 2012.2.1 documentation »

Developer Guide »

<no title> »

        © Copyright 2010-present, OpenStack, LLC.
      Last updated on Thu Nov 1 16:11:51 2012, commit 4ed8d3e.
      Created using Sphinx 1.1.3.


text:
import hyperadmin

from dockitcms.models import Collection, PublicResource as ConfiguredPublicResource, DocumentDesign, Subsite, Application, Index
from dockitcms.resources.common import ReloadCMSSiteMixin, CMSDocumentResource, ReloadCMSDotpathResource

app_name = 'dockitcms'

class ApplicationResource(CMSDocumentResource):
    list_display = ['name', 'slug']

hyperadmin.site.register(Application, ApplicationResource, app_name=app_name)

class DocumentDesignResource(CMSDocumentResource):
    dotpath_resource_class = ReloadCMSDotpathResource

hyperadmin.site.register(DocumentDesign, DocumentDesignResource, app_name=app_name)

class CollectionResource(ReloadCMSSiteMixin, CMSDocumentResource):
    list_display = ['title', 'application', 'key']
    dotpath_resource_class = ReloadCMSDotpathResource

    def get_manage_collection_resource_kwargs(self, item, **kwargs):
        document_class = item.instance.get_document()
        params = {'resource_adaptor':document_class,
                  'site':self.site,
                  'parent_resource':self,
                  'collection':item,}
        params.update(kwargs)
        return params

    def get_manage_collection_resource(self, item, **kwargs):
        kwargs = self.get_manage_collection_resource_kwargs(item, **kwargs)
        klass = item.get_resource_class()
        return klass(**kwargs)

hyperadmin.site.register(Collection, CollectionResource, app_name=app_name)

class IndexResource(ReloadCMSSiteMixin, CMSDocumentResource):
    dotpath_resource_class = ReloadCMSDotpathResource

hyperadmin.site.register(Index, IndexResource, app_name=app_name)

class SubsiteResource(ReloadCMSSiteMixin, CMSDocumentResource):
    list_display = ['name', 'url', 'slug']
    dotpath_resource_class = ReloadCMSDotpathResource

hyperadmin.site.register(Subsite, SubsiteResource, app_name=app_name)

class PublicResource(ReloadCMSSiteMixin, CMSDocumentResource):
    list_display = ['name', 'subsite', 'collection', 'url']
    dotpath_resource_class = ReloadCMSDotpathResource

    def get_prompt(self):
        return 'Public Resource'

hyperadmin.site.register(ConfiguredPublicResource, PublicResource, app_name=app_name)


text:
package org.magcruise.gaming.model.def.sys;

import java.nio.file.Path;
import java.nio.file.Paths;

import org.magcruise.gaming.lang.SConstructor;

public class DefGameLogDb implements DefGameSystemProperty {

	private Path parentPath;
	private String name;

	public DefGameLogDb(Path parentPath, String name) {
		this.parentPath = parentPath;
		this.name = name;
	}

	public Path getJdbcUrlPath() {
		return Paths.get(parentPath.toString(), name);
	}

	@Override
	public SConstructor<? extends DefGameLogDb> toConstructor(ToExpressionStyle style) {
		return SConstructor.toConstructor(style, getClass(), parentPath, name);
	}

}