text:
package generate

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"strings"

	rspec "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/opencontainers/runtime-tools/generate/seccomp"
	"github.com/opencontainers/runtime-tools/validate"
	"github.com/syndtr/gocapability/capability"
)

var (
	// Namespaces include the names of supported namespaces.
	Namespaces = []string{"network", "pid", "mount", "ipc", "uts", "user", "cgroup"}

	// we don't care about order...and this is way faster...
	removeFunc = func(s []string, i int) []string {
		s[i] = s[len(s)-1]
		return s[:len(s)-1]
	}
)

// Generator represents a generator for a container config.
type Generator struct {
	Config       *rspec.Spec
	HostSpecific bool
}

// ExportOptions have toggles for exporting only certain parts of the specification
type ExportOptions struct {
	Seccomp bool // seccomp toggles if only seccomp should be exported
}

// New creates a configuration Generator with the default
// configuration for the target operating system.
func New(os string) (generator Generator, err error) {
	if os != "linux" && os != "solaris" && os != "windows" {
		return generator, fmt.Errorf("no defaults configured for %s", os)
	}

	config := rspec.Spec{
		Version:  rspec.Version,
		Hostname: "mrsdalloway",
	}

	if os == "windows" {
		config.Process = &rspec.Process{
			Args: []string{
				"cmd",
			},
			Cwd: `C:\`,
			ConsoleSize: &rspec.Box{
				Width:  80,
				Height: 20,
			},
		}
		config.Windows = &rspec.Windows{
			IgnoreFlushesDuringBoot: true,
			Network: &rspec.WindowsNetwork{
				AllowUnqualifiedDNSQuery: true,
			},
		}
	} else {
		config.Root = &rspec.Root{
			Path:     "rootfs",
			Readonly: false,
		}
		config.Process = &rspec.Process{
			Terminal: false,
			Args: []string{
				"sh",
			},
		}
	}

	if os == "linux" || os == "solaris" {
		config.Process.User = rspec.User{}
		config.Process.Env = []string{
			"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
			"TERM=xterm",
		}
		config.Process.Cwd = "/"
		config.Process.Rlimits = []rspec.POSIXRlimit{
			{
				Type: "RLIMIT_NOFILE",
				Hard: uint64(1024),
				Soft: uint64(1024),
			},
		}
	}

	if os == "linux" {
		config.Process.Capabilities = &rspec.LinuxCapabilities{
			Bounding: []string{
				"CAP_CHOWN",
				"CAP_DAC_OVERRIDE",
				"CAP_FSETID",
				"CAP_FOWNER",
				"CAP_MKNOD",
				"CAP_NET_RAW",
				"CAP_SETGID",
				"CAP_SETUID",
				"CAP_SETFCAP",
				"CAP_SETPCAP",
				"CAP_NET_BIND_SERVICE",
				"CAP_SYS_CHROOT",
				"CAP_KILL",
				"CAP_AUDIT_WRITE",
			},
			Permitted: []string{
				"CAP_CHOWN",
				"CAP_DAC_OVERRIDE",
				"CAP_FSETID",
				"CAP_FOWNER",
				"CAP_MKNOD",
				"CAP_NET_RAW",
				"CAP_SETGID",
				"CAP_SETUID",
				"CAP_SETFCAP",
				"CAP_SETPCAP",
				"CAP_NET_BIND_SERVICE",
				"CAP_SYS_CHROOT",
				"CAP_KILL",
				"CAP_AUDIT_WRITE",
			},
			Inheritable: []string{
				"CAP_CHOWN",
				"CAP_DAC_OVERRIDE",
				"CAP_FSETID",
				"CAP_FOWNER",
				"CAP_MKNOD",
				"CAP_NET_RAW",
				"CAP_SETGID",
				"CAP_SETUID",
				"CAP_SETFCAP",
				"CAP_SETPCAP",
				"CAP_NET_BIND_SERVICE",
				"CAP_SYS_CHROOT",
				"CAP_KILL",
				"CAP_AUDIT_WRITE",
			},
			Effective: []string{
				"CAP_CHOWN",
				"CAP_DAC_OVERRIDE",
				"CAP_FSETID",
				"CAP_FOWNER",
				"CAP_MKNOD",
				"CAP_NET_RAW",
				"CAP_SETGID",
				"CAP_SETUID",
				"CAP_SETFCAP",
				"CAP_SETPCAP",
				"CAP_NET_BIND_SERVICE",
				"CAP_SYS_CHROOT",
				"CAP_KILL",
				"CAP_AUDIT_WRITE",
			},
			Ambient: []string{
				"CAP_CHOWN",
				"CAP_DAC_OVERRIDE",
				"CAP_FSETID",
				"CAP_FOWNER",
				"CAP_MKNOD",
				"CAP_NET_RAW",
				"CAP_SETGID",
				"CAP_SETUID",
				"CAP_SETFCAP",
				"CAP_SETPCAP",
				"CAP_NET_BIND_SERVICE",
				"CAP_SYS_CHROOT",
				"CAP_KILL",
				"CAP_AUDIT_WRITE",
			},
		}
		config.Mounts = []rspec.Mount{
			{
				Destination: "/proc",
				Type:        "proc",
				Source:      "proc",
				Options:     []string{"nosuid", "noexec", "nodev"},
			},
			{
				Destination: "/dev",
				Type:        "tmpfs",
				Source:      "tmpfs",
				Options:     []string{"nosuid", "strictatime", "mode=755", "size=65536k"},
			},
			{
				Destination: "/dev/pts",
				Type:        "devpts",
				Source:      "devpts",
				Options:     []string{"nosuid", "noexec", "newinstance", "ptmxmode=0666", "mode=0620", "gid=5"},
			},
			{
				Destination: "/dev/shm",
				Type:        "tmpfs",
				Source:      "shm",
				Options:     []string{"nosuid", "noexec", "nodev", "mode=1777", "size=65536k"},
			},
			{
				Destination: "/dev/mqueue",
				Type:        "mqueue",
				Source:      "mqueue",
				Options:     []string{"nosuid", "noexec", "nodev"},
			},
			{
				Destination: "/sys",
				Type:        "sysfs",
				Source:      "sysfs",
				Options:     []string{"nosuid", "noexec", "nodev", "ro"},
			},
		}
		config.Linux = &rspec.Linux{
			Resources: &rspec.LinuxResources{
				Devices: []rspec.LinuxDeviceCgroup{
					{
						Allow:  false,
						Access: "rwm",
					},
				},
			},
			Namespaces: []rspec.LinuxNamespace{
				{
					Type: "pid",
				},
				{
					Type: "network",
				},
				{
					Type: "ipc",
				},
				{
					Type: "uts",
				},
				{
					Type: "mount",
				},
			},
			Seccomp: seccomp.DefaultProfile(&config),
		}
	}

	return Generator{Config: &config}, nil
}

// NewFromSpec creates a configuration Generator from a given
// configuration.
//
// Deprecated: Replace with:
//
//   generator := Generator{Config: config}
func NewFromSpec(config *rspec.Spec) Generator {
	return Generator{
		Config: config,
	}
}

// NewFromFile loads the template specified in a file into a
// configuration Generator.
func NewFromFile(path string) (Generator, error) {
	cf, err := os.Open(path)
	if err != nil {
		if os.IsNotExist(err) {
			return Generator{}, fmt.Errorf("template configuration at %s not found", path)
		}
		return Generator{}, err
	}
	defer cf.Close()

	return NewFromTemplate(cf)
}

// NewFromTemplate loads the template from io.Reader into a
// configuration Generator.
func NewFromTemplate(r io.Reader) (Generator, error) {
	var config rspec.Spec
	if err := json.NewDecoder(r).Decode(&config); err != nil {
		return Generator{}, err
	}
	return Generator{
		Config: &config,
	}, nil
}

// SetSpec sets the configuration in the Generator g.
//
// Deprecated: Replace with:
//
//   Use generator.Config = config
func (g *Generator) SetSpec(config *rspec.Spec) {
	g.Config = config
}

// Spec gets the configuration from the Generator g.
//
// Deprecated: Replace with generator.Config.
func (g *Generator) Spec() *rspec.Spec {
	return g.Config
}

// Save writes the configuration into w.
func (g *Generator) Save(w io.Writer, exportOpts ExportOptions) (err error) {
	var data []byte

	if g.Config.Linux != nil {
		buf, err := json.Marshal(g.Config.Linux)
		if err != nil {
			return err
		}
		if string(buf) == "{}" {
			g.Config.Linux = nil
		}
	}

	if exportOpts.Seccomp {
		data, err = json.MarshalIndent(g.Config.Linux.Seccomp, "", "\t")
	} else {
		data, err = json.MarshalIndent(g.Config, "", "\t")
	}
	if err != nil {
		return err
	}

	_, err = w.Write(data)
	if err != nil {
		return err
	}

	return nil
}

// SaveToFile writes the configuration into a file.
func (g *Generator) SaveToFile(path string, exportOpts ExportOptions) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()
	return g.Save(f, exportOpts)
}

// SetVersion sets g.Config.Version.
func (g *Generator) SetVersion(version string) {
	g.initConfig()
	g.Config.Version = version
}

// SetRootPath sets g.Config.Root.Path.
func (g *Generator) SetRootPath(path string) {
	g.initConfigRoot()
	g.Config.Root.Path = path
}

// SetRootReadonly sets g.Config.Root.Readonly.
func (g *Generator) SetRootReadonly(b bool) {
	g.initConfigRoot()
	g.Config.Root.Readonly = b
}

// SetHostname sets g.Config.Hostname.
func (g *Generator) SetHostname(s string) {
	g.initConfig()
	g.Config.Hostname = s
}

// ClearAnnotations clears g.Config.Annotations.
func (g *Generator) ClearAnnotations() {
	if g.Config == nil {
		return
	}
	g.Config.Annotations = make(map[string]string)
}

// AddAnnotation adds an annotation into g.Config.Annotations.
func (g *Generator) AddAnnotation(key, value string) {
	g.initConfigAnnotations()
	g.Config.Annotations[key] = value
}

// RemoveAnnotation remove an annotation from g.Config.Annotations.
func (g *Generator) RemoveAnnotation(key string) {
	if g.Config == nil || g.Config.Annotations == nil {
		return
	}
	delete(g.Config.Annotations, key)
}

// RemoveHostname removes g.Config.Hostname, setting it to an empty string.
func (g *Generator) RemoveHostname() {
	if g.Config == nil {
		return
	}
	g.Config.Hostname = ""
}

// SetProcessConsoleSize sets g.Config.Process.ConsoleSize.
func (g *Generator) SetProcessConsoleSize(width, height uint) {
	g.initConfigProcessConsoleSize()
	g.Config.Process.ConsoleSize.Width = width
	g.Config.Process.ConsoleSize.Height = height
}

// SetProcessUID sets g.Config.Process.User.UID.
func (g *Generator) SetProcessUID(uid uint32) {
	g.initConfigProcess()
	g.Config.Process.User.UID = uid
}

// SetProcessUsername sets g.Config.Process.User.Username.
func (g *Generator) SetProcessUsername(username string) {
	g.initConfigProcess()
	g.Config.Process.User.Username = username
}

// SetProcessGID sets g.Config.Process.User.GID.
func (g *Generator) SetProcessGID(gid uint32) {
	g.initConfigProcess()
	g.Config.Process.User.GID = gid
}

// SetProcessCwd sets g.Config.Process.Cwd.
func (g *Generator) SetProcessCwd(cwd string) {
	g.initConfigProcess()
	g.Config.Process.Cwd = cwd
}

// SetProcessNoNewPrivileges sets g.Config.Process.NoNewPrivileges.
func (g *Generator) SetProcessNoNewPrivileges(b bool) {
	g.initConfigProcess()
	g.Config.Process.NoNewPrivileges = b
}

// SetProcessTerminal sets g.Config.Process.Terminal.
func (g *Generator) SetProcessTerminal(b bool) {
	g.initConfigProcess()
	g.Config.Process.Terminal = b
}

// SetProcessApparmorProfile sets g.Config.Process.ApparmorProfile.
func (g *Generator) SetProcessApparmorProfile(prof string) {
	g.initConfigProcess()
	g.Config.Process.ApparmorProfile = prof
}

// SetProcessArgs sets g.Config.Process.Args.
func (g *Generator) SetProcessArgs(args []string) {
	g.initConfigProcess()
	g.Config.Process.Args = args
}

// ClearProcessEnv clears g.Config.Process.Env.
func (g *Generator) ClearProcessEnv() {
	if g.Config == nil || g.Config.Process == nil {
		return
	}
	g.Config.Process.Env = []string{}
}

// AddProcessEnv adds name=value into g.Config.Process.Env, or replaces an
// existing entry with the given name.
func (g *Generator) AddProcessEnv(name, value string) {
	g.initConfigProcess()

	env := fmt.Sprintf("%s=%s", name, value)
	for idx := range g.Config.Process.Env {
		if strings.HasPrefix(g.Config.Process.Env[idx], name+"=") {
			g.Config.Process.Env[idx] = env
			return
		}
	}
	g.Config.Process.Env = append(g.Config.Process.Env, env)
}

// AddProcessRlimits adds rlimit into g.Config.Process.Rlimits.
func (g *Generator) AddProcessRlimits(rType string, rHard uint64, rSoft uint64) {
	g.initConfigProcess()
	for i, rlimit := range g.Config.Process.Rlimits {
		if rlimit.Type == rType {
			g.Config.Process.Rlimits[i].Hard = rHard
			g.Config.Process.Rlimits[i].Soft = rSoft
			return
		}
	}

	newRlimit := rspec.POSIXRlimit{
		Type: rType,
		Hard: rHard,
		Soft: rSoft,
	}
	g.Config.Process.Rlimits = append(g.Config.Process.Rlimits, newRlimit)
}

// RemoveProcessRlimits removes a rlimit from g.Config.Process.Rlimits.
func (g *Generator) RemoveProcessRlimits(rType string) {
	if g.Config == nil || g.Config.Process == nil {
		return
	}
	for i, rlimit := range g.Config.Process.Rlimits {
		if rlimit.Type == rType {
			g.Config.Process.Rlimits = append(g.Config.Process.Rlimits[:i], g.Config.Process.Rlimits[i+1:]...)
			return
		}
	}
}

// ClearProcessRlimits clear g.Config.Process.Rlimits.
func (g *Generator) ClearProcessRlimits() {
	if g.Config == nil || g.Config.Process == nil {
		return
	}
	g.Config.Process.Rlimits = []rspec.POSIXRlimit{}
}

// ClearProcessAdditionalGids clear g.Config.Process.AdditionalGids.
func (g *Generator) ClearProcessAdditionalGids() {
	if g.Config == nil || g.Config.Process == nil {
		return
	}
	g.Config.Process.User.AdditionalGids = []uint32{}
}

// AddProcessAdditionalGid adds an additional gid into g.Config.Process.AdditionalGids.
func (g *Generator) AddProcessAdditionalGid(gid uint32) {
	g.initConfigProcess()
	for _, group := range g.Config.Process.User.AdditionalGids {
		if group == gid {
			return
		}
	}
	g.Config.Process.User.AdditionalGids = append(g.Config.Process.User.AdditionalGids, gid)
}

// SetProcessSelinuxLabel sets g.Config.Process.SelinuxLabel.
func (g *Generator) SetProcessSelinuxLabel(label string) {
	g.initConfigProcess()
	g.Config.Process.SelinuxLabel = label
}

// SetLinuxCgroupsPath sets g.Config.Linux.CgroupsPath.
func (g *Generator) SetLinuxCgroupsPath(path string) {
	g.initConfigLinux()
	g.Config.Linux.CgroupsPath = path
}

// SetLinuxIntelRdtL3CacheSchema sets g.Config.Linux.IntelRdt.L3CacheSchema
func (g *Generator) SetLinuxIntelRdtL3CacheSchema(schema string) {
	g.initConfigLinuxIntelRdt()
	g.Config.Linux.IntelRdt.L3CacheSchema = schema
}

// SetLinuxMountLabel sets g.Config.Linux.MountLabel.
func (g *Generator) SetLinuxMountLabel(label string) {
	g.initConfigLinux()
	g.Config.Linux.MountLabel = label
}

// SetProcessOOMScoreAdj sets g.Config.Process.OOMScoreAdj.
func (g *Generator) SetProcessOOMScoreAdj(adj int) {
	g.initConfigProcess()
	g.Config.Process.OOMScoreAdj = &adj
}

// SetLinuxResourcesBlockIOLeafWeight sets g.Config.Linux.Resources.BlockIO.LeafWeight.
func (g *Generator) SetLinuxResourcesBlockIOLeafWeight(weight uint16) {
	g.initConfigLinuxResourcesBlockIO()
	g.Config.Linux.Resources.BlockIO.LeafWeight = &weight
}

// AddLinuxResourcesBlockIOLeafWeightDevice adds or sets g.Config.Linux.Resources.BlockIO.WeightDevice.LeafWeight.
func (g *Generator) AddLinuxResourcesBlockIOLeafWeightDevice(major int64, minor int64, weight uint16) {
	g.initConfigLinuxResourcesBlockIO()
	for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice {
		if weightDevice.Major == major && weightDevice.Minor == minor {
			g.Config.Linux.Resources.BlockIO.WeightDevice[i].LeafWeight = &weight
			return
		}
	}
	weightDevice := new(rspec.LinuxWeightDevice)
	weightDevice.Major = major
	weightDevice.Minor = minor
	weightDevice.LeafWeight = &weight
	g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice, *weightDevice)
}

// DropLinuxResourcesBlockIOLeafWeightDevice drops a item form g.Config.Linux.Resources.BlockIO.WeightDevice.LeafWeight
func (g *Generator) DropLinuxResourcesBlockIOLeafWeightDevice(major int64, minor int64) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil {
		return
	}

	for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice {
		if weightDevice.Major == major && weightDevice.Minor == minor {
			if weightDevice.Weight != nil {
				newWeightDevice := new(rspec.LinuxWeightDevice)
				newWeightDevice.Major = major
				newWeightDevice.Minor = minor
				newWeightDevice.Weight = weightDevice.Weight
				g.Config.Linux.Resources.BlockIO.WeightDevice[i] = *newWeightDevice
			} else {
				g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice[:i], g.Config.Linux.Resources.BlockIO.WeightDevice[i+1:]...)
			}
			return
		}
	}
}

// SetLinuxResourcesBlockIOWeight sets g.Config.Linux.Resources.BlockIO.Weight.
func (g *Generator) SetLinuxResourcesBlockIOWeight(weight uint16) {
	g.initConfigLinuxResourcesBlockIO()
	g.Config.Linux.Resources.BlockIO.Weight = &weight
}

// AddLinuxResourcesBlockIOWeightDevice adds or sets g.Config.Linux.Resources.BlockIO.WeightDevice.Weight.
func (g *Generator) AddLinuxResourcesBlockIOWeightDevice(major int64, minor int64, weight uint16) {
	g.initConfigLinuxResourcesBlockIO()
	for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice {
		if weightDevice.Major == major && weightDevice.Minor == minor {
			g.Config.Linux.Resources.BlockIO.WeightDevice[i].Weight = &weight
			return
		}
	}
	weightDevice := new(rspec.LinuxWeightDevice)
	weightDevice.Major = major
	weightDevice.Minor = minor
	weightDevice.Weight = &weight
	g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice, *weightDevice)
}

// DropLinuxResourcesBlockIOWeightDevice drops a item form g.Config.Linux.Resources.BlockIO.WeightDevice.Weight
func (g *Generator) DropLinuxResourcesBlockIOWeightDevice(major int64, minor int64) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil {
		return
	}

	for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice {
		if weightDevice.Major == major && weightDevice.Minor == minor {
			if weightDevice.LeafWeight != nil {
				newWeightDevice := new(rspec.LinuxWeightDevice)
				newWeightDevice.Major = major
				newWeightDevice.Minor = minor
				newWeightDevice.LeafWeight = weightDevice.LeafWeight
				g.Config.Linux.Resources.BlockIO.WeightDevice[i] = *newWeightDevice
			} else {
				g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice[:i], g.Config.Linux.Resources.BlockIO.WeightDevice[i+1:]...)
			}
			return
		}
	}
}

// AddLinuxResourcesBlockIOThrottleReadBpsDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice.
func (g *Generator) AddLinuxResourcesBlockIOThrottleReadBpsDevice(major int64, minor int64, rate uint64) {
	g.initConfigLinuxResourcesBlockIO()
	throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice, major, minor, rate)
	g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice = throttleDevices
}

// DropLinuxResourcesBlockIOThrottleReadBpsDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice.
func (g *Generator) DropLinuxResourcesBlockIOThrottleReadBpsDevice(major int64, minor int64) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil {
		return
	}

	throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice, major, minor)
	g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice = throttleDevices
}

// AddLinuxResourcesBlockIOThrottleReadIOPSDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice.
func (g *Generator) AddLinuxResourcesBlockIOThrottleReadIOPSDevice(major int64, minor int64, rate uint64) {
	g.initConfigLinuxResourcesBlockIO()
	throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice, major, minor, rate)
	g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice = throttleDevices
}

// DropLinuxResourcesBlockIOThrottleReadIOPSDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice.
func (g *Generator) DropLinuxResourcesBlockIOThrottleReadIOPSDevice(major int64, minor int64) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil {
		return
	}

	throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice, major, minor)
	g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice = throttleDevices
}

// AddLinuxResourcesBlockIOThrottleWriteBpsDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice.
func (g *Generator) AddLinuxResourcesBlockIOThrottleWriteBpsDevice(major int64, minor int64, rate uint64) {
	g.initConfigLinuxResourcesBlockIO()
	throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice, major, minor, rate)
	g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice = throttleDevices
}

// DropLinuxResourcesBlockIOThrottleWriteBpsDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice.
func (g *Generator) DropLinuxResourcesBlockIOThrottleWriteBpsDevice(major int64, minor int64) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil {
		return
	}

	throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice, major, minor)
	g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice = throttleDevices
}

// AddLinuxResourcesBlockIOThrottleWriteIOPSDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice.
func (g *Generator) AddLinuxResourcesBlockIOThrottleWriteIOPSDevice(major int64, minor int64, rate uint64) {
	g.initConfigLinuxResourcesBlockIO()
	throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice, major, minor, rate)
	g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice = throttleDevices
}

// DropLinuxResourcesBlockIOThrottleWriteIOPSDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice.
func (g *Generator) DropLinuxResourcesBlockIOThrottleWriteIOPSDevice(major int64, minor int64) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil {
		return
	}

	throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice, major, minor)
	g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice = throttleDevices
}

// SetLinuxResourcesCPUShares sets g.Config.Linux.Resources.CPU.Shares.
func (g *Generator) SetLinuxResourcesCPUShares(shares uint64) {
	g.InitConfigLinuxResourcesCPU()
	g.Config.Linux.Resources.CPU.Shares = &shares
}

// SetLinuxResourcesCPUQuota sets g.Config.Linux.Resources.CPU.Quota.
func (g *Generator) SetLinuxResourcesCPUQuota(quota int64) {
	g.InitConfigLinuxResourcesCPU()
	g.Config.Linux.Resources.CPU.Quota = &quota
}

// SetLinuxResourcesCPUPeriod sets g.Config.Linux.Resources.CPU.Period.
func (g *Generator) SetLinuxResourcesCPUPeriod(period uint64) {
	g.InitConfigLinuxResourcesCPU()
	g.Config.Linux.Resources.CPU.Period = &period
}

// SetLinuxResourcesCPURealtimeRuntime sets g.Config.Linux.Resources.CPU.RealtimeRuntime.
func (g *Generator) SetLinuxResourcesCPURealtimeRuntime(time int64) {
	g.InitConfigLinuxResourcesCPU()
	g.Config.Linux.Resources.CPU.RealtimeRuntime = &time
}

// SetLinuxResourcesCPURealtimePeriod sets g.Config.Linux.Resources.CPU.RealtimePeriod.
func (g *Generator) SetLinuxResourcesCPURealtimePeriod(period uint64) {
	g.InitConfigLinuxResourcesCPU()
	g.Config.Linux.Resources.CPU.RealtimePeriod = &period
}

// SetLinuxResourcesCPUCpus sets g.Config.Linux.Resources.CPU.Cpus.
func (g *Generator) SetLinuxResourcesCPUCpus(cpus string) {
	g.InitConfigLinuxResourcesCPU()
	g.Config.Linux.Resources.CPU.Cpus = cpus
}

// SetLinuxResourcesCPUMems sets g.Config.Linux.Resources.CPU.Mems.
func (g *Generator) SetLinuxResourcesCPUMems(mems string) {
	g.InitConfigLinuxResourcesCPU()
	g.Config.Linux.Resources.CPU.Mems = mems
}

// AddLinuxResourcesHugepageLimit adds or sets g.Config.Linux.Resources.HugepageLimits.
func (g *Generator) AddLinuxResourcesHugepageLimit(pageSize string, limit uint64) {
	hugepageLimit := rspec.LinuxHugepageLimit{
		Pagesize: pageSize,
		Limit:    limit,
	}

	g.initConfigLinuxResources()
	for i, pageLimit := range g.Config.Linux.Resources.HugepageLimits {
		if pageLimit.Pagesize == pageSize {
			g.Config.Linux.Resources.HugepageLimits[i].Limit = limit
			return
		}
	}
	g.Config.Linux.Resources.HugepageLimits = append(g.Config.Linux.Resources.HugepageLimits, hugepageLimit)
}

// DropLinuxResourcesHugepageLimit drops a hugepage limit from g.Config.Linux.Resources.HugepageLimits.
func (g *Generator) DropLinuxResourcesHugepageLimit(pageSize string) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil {
		return
	}

	for i, pageLimit := range g.Config.Linux.Resources.HugepageLimits {
		if pageLimit.Pagesize == pageSize {
			g.Config.Linux.Resources.HugepageLimits = append(g.Config.Linux.Resources.HugepageLimits[:i], g.Config.Linux.Resources.HugepageLimits[i+1:]...)
			return
		}
	}
}

// SetLinuxResourcesMemoryLimit sets g.Config.Linux.Resources.Memory.Limit.
func (g *Generator) SetLinuxResourcesMemoryLimit(limit int64) {
	g.initConfigLinuxResourcesMemory()
	g.Config.Linux.Resources.Memory.Limit = &limit
}

// SetLinuxResourcesMemoryReservation sets g.Config.Linux.Resources.Memory.Reservation.
func (g *Generator) SetLinuxResourcesMemoryReservation(reservation int64) {
	g.initConfigLinuxResourcesMemory()
	g.Config.Linux.Resources.Memory.Reservation = &reservation
}

// SetLinuxResourcesMemorySwap sets g.Config.Linux.Resources.Memory.Swap.
func (g *Generator) SetLinuxResourcesMemorySwap(swap int64) {
	g.initConfigLinuxResourcesMemory()
	g.Config.Linux.Resources.Memory.Swap = &swap
}

// SetLinuxResourcesMemoryKernel sets g.Config.Linux.Resources.Memory.Kernel.
func (g *Generator) SetLinuxResourcesMemoryKernel(kernel int64) {
	g.initConfigLinuxResourcesMemory()
	g.Config.Linux.Resources.Memory.Kernel = &kernel
}

// SetLinuxResourcesMemoryKernelTCP sets g.Config.Linux.Resources.Memory.KernelTCP.
func (g *Generator) SetLinuxResourcesMemoryKernelTCP(kernelTCP int64) {
	g.initConfigLinuxResourcesMemory()
	g.Config.Linux.Resources.Memory.KernelTCP = &kernelTCP
}

// SetLinuxResourcesMemorySwappiness sets g.Config.Linux.Resources.Memory.Swappiness.
func (g *Generator) SetLinuxResourcesMemorySwappiness(swappiness uint64) {
	g.initConfigLinuxResourcesMemory()
	g.Config.Linux.Resources.Memory.Swappiness = &swappiness
}

// SetLinuxResourcesMemoryDisableOOMKiller sets g.Config.Linux.Resources.Memory.DisableOOMKiller.
func (g *Generator) SetLinuxResourcesMemoryDisableOOMKiller(disable bool) {
	g.initConfigLinuxResourcesMemory()
	g.Config.Linux.Resources.Memory.DisableOOMKiller = &disable
}

// SetLinuxResourcesNetworkClassID sets g.Config.Linux.Resources.Network.ClassID.
func (g *Generator) SetLinuxResourcesNetworkClassID(classid uint32) {
	g.initConfigLinuxResourcesNetwork()
	g.Config.Linux.Resources.Network.ClassID = &classid
}

// AddLinuxResourcesNetworkPriorities adds or sets g.Config.Linux.Resources.Network.Priorities.
func (g *Generator) AddLinuxResourcesNetworkPriorities(name string, prio uint32) {
	g.initConfigLinuxResourcesNetwork()
	for i, netPriority := range g.Config.Linux.Resources.Network.Priorities {
		if netPriority.Name == name {
			g.Config.Linux.Resources.Network.Priorities[i].Priority = prio
			return
		}
	}
	interfacePrio := new(rspec.LinuxInterfacePriority)
	interfacePrio.Name = name
	interfacePrio.Priority = prio
	g.Config.Linux.Resources.Network.Priorities = append(g.Config.Linux.Resources.Network.Priorities, *interfacePrio)
}

// DropLinuxResourcesNetworkPriorities drops one item from g.Config.Linux.Resources.Network.Priorities.
func (g *Generator) DropLinuxResourcesNetworkPriorities(name string) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.Network == nil {
		return
	}

	for i, netPriority := range g.Config.Linux.Resources.Network.Priorities {
		if netPriority.Name == name {
			g.Config.Linux.Resources.Network.Priorities = append(g.Config.Linux.Resources.Network.Priorities[:i], g.Config.Linux.Resources.Network.Priorities[i+1:]...)
			return
		}
	}
}

// SetLinuxResourcesPidsLimit sets g.Config.Linux.Resources.Pids.Limit.
func (g *Generator) SetLinuxResourcesPidsLimit(limit int64) {
	g.initConfigLinuxResourcesPids()
	g.Config.Linux.Resources.Pids.Limit = limit
}

// ClearLinuxSysctl clears g.Config.Linux.Sysctl.
func (g *Generator) ClearLinuxSysctl() {
	if g.Config == nil || g.Config.Linux == nil {
		return
	}
	g.Config.Linux.Sysctl = make(map[string]string)
}

// AddLinuxSysctl adds a new sysctl config into g.Config.Linux.Sysctl.
func (g *Generator) AddLinuxSysctl(key, value string) {
	g.initConfigLinuxSysctl()
	g.Config.Linux.Sysctl[key] = value
}

// RemoveLinuxSysctl removes a sysctl config from g.Config.Linux.Sysctl.
func (g *Generator) RemoveLinuxSysctl(key string) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Sysctl == nil {
		return
	}
	delete(g.Config.Linux.Sysctl, key)
}

// ClearLinuxUIDMappings clear g.Config.Linux.UIDMappings.
func (g *Generator) ClearLinuxUIDMappings() {
	if g.Config == nil || g.Config.Linux == nil {
		return
	}
	g.Config.Linux.UIDMappings = []rspec.LinuxIDMapping{}
}

// AddLinuxUIDMapping adds uidMap into g.Config.Linux.UIDMappings.
func (g *Generator) AddLinuxUIDMapping(hid, cid, size uint32) {
	idMapping := rspec.LinuxIDMapping{
		HostID:      hid,
		ContainerID: cid,
		Size:        size,
	}

	g.initConfigLinux()
	g.Config.Linux.UIDMappings = append(g.Config.Linux.UIDMappings, idMapping)
}

// ClearLinuxGIDMappings clear g.Config.Linux.GIDMappings.
func (g *Generator) ClearLinuxGIDMappings() {
	if g.Config == nil || g.Config.Linux == nil {
		return
	}
	g.Config.Linux.GIDMappings = []rspec.LinuxIDMapping{}
}

// AddLinuxGIDMapping adds gidMap into g.Config.Linux.GIDMappings.
func (g *Generator) AddLinuxGIDMapping(hid, cid, size uint32) {
	idMapping := rspec.LinuxIDMapping{
		HostID:      hid,
		ContainerID: cid,
		Size:        size,
	}

	g.initConfigLinux()
	g.Config.Linux.GIDMappings = append(g.Config.Linux.GIDMappings, idMapping)
}

// SetLinuxRootPropagation sets g.Config.Linux.RootfsPropagation.
func (g *Generator) SetLinuxRootPropagation(rp string) error {
	switch rp {
	case "":
	case "private":
	case "rprivate":
	case "slave":
	case "rslave":
	case "shared":
	case "rshared":
	case "unbindable":
	case "runbindable":
	default:
		return fmt.Errorf("rootfs-propagation %q must be empty or one of (r)private|(r)slave|(r)shared|(r)unbindable", rp)
	}
	g.initConfigLinux()
	g.Config.Linux.RootfsPropagation = rp
	return nil
}

// ClearPreStartHooks clear g.Config.Hooks.Prestart.
func (g *Generator) ClearPreStartHooks() {
	if g.Config == nil || g.Config.Hooks == nil {
		return
	}
	g.Config.Hooks.Prestart = []rspec.Hook{}
}

// AddPreStartHook add a prestart hook into g.Config.Hooks.Prestart.
func (g *Generator) AddPreStartHook(preStartHook rspec.Hook) error {
	g.initConfigHooks()
	g.Config.Hooks.Prestart = append(g.Config.Hooks.Prestart, preStartHook)
	return nil
}

// ClearPostStopHooks clear g.Config.Hooks.Poststop.
func (g *Generator) ClearPostStopHooks() {
	if g.Config == nil || g.Config.Hooks == nil {
		return
	}
	g.Config.Hooks.Poststop = []rspec.Hook{}
}

// AddPostStopHook adds a poststop hook into g.Config.Hooks.Poststop.
func (g *Generator) AddPostStopHook(postStopHook rspec.Hook) error {
	g.initConfigHooks()
	g.Config.Hooks.Poststop = append(g.Config.Hooks.Poststop, postStopHook)
	return nil
}

// ClearPostStartHooks clear g.Config.Hooks.Poststart.
func (g *Generator) ClearPostStartHooks() {
	if g.Config == nil || g.Config.Hooks == nil {
		return
	}
	g.Config.Hooks.Poststart = []rspec.Hook{}
}

// AddPostStartHook adds a poststart hook into g.Config.Hooks.Poststart.
func (g *Generator) AddPostStartHook(postStartHook rspec.Hook) error {
	g.initConfigHooks()
	g.Config.Hooks.Poststart = append(g.Config.Hooks.Poststart, postStartHook)
	return nil
}

// AddMount adds a mount into g.Config.Mounts.
func (g *Generator) AddMount(mnt rspec.Mount) {
	g.initConfig()

	g.Config.Mounts = append(g.Config.Mounts, mnt)
}

// RemoveMount removes a mount point on the dest directory
func (g *Generator) RemoveMount(dest string) {
	g.initConfig()

	for index, mount := range g.Config.Mounts {
		if mount.Destination == dest {
			g.Config.Mounts = append(g.Config.Mounts[:index], g.Config.Mounts[index+1:]...)
			return
		}
	}
}

// Mounts returns the list of mounts
func (g *Generator) Mounts() []rspec.Mount {
	g.initConfig()

	return g.Config.Mounts
}

// ClearMounts clear g.Config.Mounts
func (g *Generator) ClearMounts() {
	if g.Config == nil {
		return
	}
	g.Config.Mounts = []rspec.Mount{}
}

// SetupPrivileged sets up the privilege-related fields inside g.Config.
func (g *Generator) SetupPrivileged(privileged bool) {
	if privileged { // Add all capabilities in privileged mode.
		var finalCapList []string
		for _, cap := range capability.List() {
			if g.HostSpecific && cap > validate.LastCap() {
				continue
			}
			finalCapList = append(finalCapList, fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String())))
		}
		g.initConfigLinux()
		g.initConfigProcessCapabilities()
		g.ClearProcessCapabilities()
		g.Config.Process.Capabilities.Bounding = append(g.Config.Process.Capabilities.Bounding, finalCapList...)
		g.Config.Process.Capabilities.Effective = append(g.Config.Process.Capabilities.Effective, finalCapList...)
		g.Config.Process.Capabilities.Inheritable = append(g.Config.Process.Capabilities.Inheritable, finalCapList...)
		g.Config.Process.Capabilities.Permitted = append(g.Config.Process.Capabilities.Permitted, finalCapList...)
		g.Config.Process.Capabilities.Ambient = append(g.Config.Process.Capabilities.Ambient, finalCapList...)
		g.Config.Process.SelinuxLabel = ""
		g.Config.Process.ApparmorProfile = ""
		g.Config.Linux.Seccomp = nil
	}
}

// ClearProcessCapabilities clear g.Config.Process.Capabilities.
func (g *Generator) ClearProcessCapabilities() {
	if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil {
		return
	}
	g.Config.Process.Capabilities.Bounding = []string{}
	g.Config.Process.Capabilities.Effective = []string{}
	g.Config.Process.Capabilities.Inheritable = []string{}
	g.Config.Process.Capabilities.Permitted = []string{}
	g.Config.Process.Capabilities.Ambient = []string{}
}

// AddProcessCapabilityAmbient adds a process capability into g.Config.Process.Capabilities.Ambient.
func (g *Generator) AddProcessCapabilityAmbient(c string) error {
	cp := strings.ToUpper(c)
	if err := validate.CapValid(cp, g.HostSpecific); err != nil {
		return err
	}

	g.initConfigProcessCapabilities()

	var foundAmbient bool
	for _, cap := range g.Config.Process.Capabilities.Ambient {
		if strings.ToUpper(cap) == cp {
			foundAmbient = true
			break
		}
	}

	if !foundAmbient {
		g.Config.Process.Capabilities.Ambient = append(g.Config.Process.Capabilities.Ambient, cp)
	}

	return nil
}

// AddProcessCapabilityBounding adds a process capability into g.Config.Process.Capabilities.Bounding.
func (g *Generator) AddProcessCapabilityBounding(c string) error {
	cp := strings.ToUpper(c)
	if err := validate.CapValid(cp, g.HostSpecific); err != nil {
		return err
	}

	g.initConfigProcessCapabilities()

	var foundBounding bool
	for _, cap := range g.Config.Process.Capabilities.Bounding {
		if strings.ToUpper(cap) == cp {
			foundBounding = true
			break
		}
	}
	if !foundBounding {
		g.Config.Process.Capabilities.Bounding = append(g.Config.Process.Capabilities.Bounding, cp)
	}

	return nil
}

// AddProcessCapabilityEffective adds a process capability into g.Config.Process.Capabilities.Effective.
func (g *Generator) AddProcessCapabilityEffective(c string) error {
	cp := strings.ToUpper(c)
	if err := validate.CapValid(cp, g.HostSpecific); err != nil {
		return err
	}

	g.initConfigProcessCapabilities()

	var foundEffective bool
	for _, cap := range g.Config.Process.Capabilities.Effective {
		if strings.ToUpper(cap) == cp {
			foundEffective = true
			break
		}
	}
	if !foundEffective {
		g.Config.Process.Capabilities.Effective = append(g.Config.Process.Capabilities.Effective, cp)
	}

	return nil
}

// AddProcessCapabilityInheritable adds a process capability into g.Config.Process.Capabilities.Inheritable.
func (g *Generator) AddProcessCapabilityInheritable(c string) error {
	cp := strings.ToUpper(c)
	if err := validate.CapValid(cp, g.HostSpecific); err != nil {
		return err
	}

	g.initConfigProcessCapabilities()

	var foundInheritable bool
	for _, cap := range g.Config.Process.Capabilities.Inheritable {
		if strings.ToUpper(cap) == cp {
			foundInheritable = true
			break
		}
	}
	if !foundInheritable {
		g.Config.Process.Capabilities.Inheritable = append(g.Config.Process.Capabilities.Inheritable, cp)
	}

	return nil
}

// AddProcessCapabilityPermitted adds a process capability into g.Config.Process.Capabilities.Permitted.
func (g *Generator) AddProcessCapabilityPermitted(c string) error {
	cp := strings.ToUpper(c)
	if err := validate.CapValid(cp, g.HostSpecific); err != nil {
		return err
	}

	g.initConfigProcessCapabilities()

	var foundPermitted bool
	for _, cap := range g.Config.Process.Capabilities.Permitted {
		if strings.ToUpper(cap) == cp {
			foundPermitted = true
			break
		}
	}
	if !foundPermitted {
		g.Config.Process.Capabilities.Permitted = append(g.Config.Process.Capabilities.Permitted, cp)
	}

	return nil
}

// DropProcessCapabilityAmbient drops a process capability from g.Config.Process.Capabilities.Ambient.
func (g *Generator) DropProcessCapabilityAmbient(c string) error {
	if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil {
		return nil
	}

	cp := strings.ToUpper(c)
	for i, cap := range g.Config.Process.Capabilities.Ambient {
		if strings.ToUpper(cap) == cp {
			g.Config.Process.Capabilities.Ambient = removeFunc(g.Config.Process.Capabilities.Ambient, i)
		}
	}

	return validate.CapValid(cp, false)
}

// DropProcessCapabilityBounding drops a process capability from g.Config.Process.Capabilities.Bounding.
func (g *Generator) DropProcessCapabilityBounding(c string) error {
	if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil {
		return nil
	}

	cp := strings.ToUpper(c)
	for i, cap := range g.Config.Process.Capabilities.Bounding {
		if strings.ToUpper(cap) == cp {
			g.Config.Process.Capabilities.Bounding = removeFunc(g.Config.Process.Capabilities.Bounding, i)
		}
	}

	return validate.CapValid(cp, false)
}

// DropProcessCapabilityEffective drops a process capability from g.Config.Process.Capabilities.Effective.
func (g *Generator) DropProcessCapabilityEffective(c string) error {
	if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil {
		return nil
	}

	cp := strings.ToUpper(c)
	for i, cap := range g.Config.Process.Capabilities.Effective {
		if strings.ToUpper(cap) == cp {
			g.Config.Process.Capabilities.Effective = removeFunc(g.Config.Process.Capabilities.Effective, i)
		}
	}

	return validate.CapValid(cp, false)
}

// DropProcessCapabilityInheritable drops a process capability from g.Config.Process.Capabilities.Inheritable.
func (g *Generator) DropProcessCapabilityInheritable(c string) error {
	if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil {
		return nil
	}

	cp := strings.ToUpper(c)
	for i, cap := range g.Config.Process.Capabilities.Inheritable {
		if strings.ToUpper(cap) == cp {
			g.Config.Process.Capabilities.Inheritable = removeFunc(g.Config.Process.Capabilities.Inheritable, i)
		}
	}

	return validate.CapValid(cp, false)
}

// DropProcessCapabilityPermitted drops a process capability from g.Config.Process.Capabilities.Permitted.
func (g *Generator) DropProcessCapabilityPermitted(c string) error {
	if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil {
		return nil
	}

	cp := strings.ToUpper(c)
	for i, cap := range g.Config.Process.Capabilities.Permitted {
		if strings.ToUpper(cap) == cp {
			g.Config.Process.Capabilities.Permitted = removeFunc(g.Config.Process.Capabilities.Permitted, i)
		}
	}

	return validate.CapValid(cp, false)
}

func mapStrToNamespace(ns string, path string) (rspec.LinuxNamespace, error) {
	switch ns {
	case "network":
		return rspec.LinuxNamespace{Type: rspec.NetworkNamespace, Path: path}, nil
	case "pid":
		return rspec.LinuxNamespace{Type: rspec.PIDNamespace, Path: path}, nil
	case "mount":
		return rspec.LinuxNamespace{Type: rspec.MountNamespace, Path: path}, nil
	case "ipc":
		return rspec.LinuxNamespace{Type: rspec.IPCNamespace, Path: path}, nil
	case "uts":
		return rspec.LinuxNamespace{Type: rspec.UTSNamespace, Path: path}, nil
	case "user":
		return rspec.LinuxNamespace{Type: rspec.UserNamespace, Path: path}, nil
	case "cgroup":
		return rspec.LinuxNamespace{Type: rspec.CgroupNamespace, Path: path}, nil
	default:
		return rspec.LinuxNamespace{}, fmt.Errorf("unrecognized namespace %q", ns)
	}
}

// ClearLinuxNamespaces clear g.Config.Linux.Namespaces.
func (g *Generator) ClearLinuxNamespaces() {
	if g.Config == nil || g.Config.Linux == nil {
		return
	}
	g.Config.Linux.Namespaces = []rspec.LinuxNamespace{}
}

// AddOrReplaceLinuxNamespace adds or replaces a namespace inside
// g.Config.Linux.Namespaces.
func (g *Generator) AddOrReplaceLinuxNamespace(ns string, path string) error {
	namespace, err := mapStrToNamespace(ns, path)
	if err != nil {
		return err
	}

	g.initConfigLinux()
	for i, ns := range g.Config.Linux.Namespaces {
		if ns.Type == namespace.Type {
			g.Config.Linux.Namespaces[i] = namespace
			return nil
		}
	}
	g.Config.Linux.Namespaces = append(g.Config.Linux.Namespaces, namespace)
	return nil
}

// RemoveLinuxNamespace removes a namespace from g.Config.Linux.Namespaces.
func (g *Generator) RemoveLinuxNamespace(ns string) error {
	namespace, err := mapStrToNamespace(ns, "")
	if err != nil {
		return err
	}

	if g.Config == nil || g.Config.Linux == nil {
		return nil
	}
	for i, ns := range g.Config.Linux.Namespaces {
		if ns.Type == namespace.Type {
			g.Config.Linux.Namespaces = append(g.Config.Linux.Namespaces[:i], g.Config.Linux.Namespaces[i+1:]...)
			return nil
		}
	}
	return nil
}

// AddDevice - add a device into g.Config.Linux.Devices
func (g *Generator) AddDevice(device rspec.LinuxDevice) {
	g.initConfigLinux()

	for i, dev := range g.Config.Linux.Devices {
		if dev.Path == device.Path {
			g.Config.Linux.Devices[i] = device
			return
		}
		if dev.Type == device.Type && dev.Major == device.Major && dev.Minor == device.Minor {
			fmt.Fprintln(os.Stderr, "WARNING: The same type, major and minor should not be used for multiple devices.")
		}
	}

	g.Config.Linux.Devices = append(g.Config.Linux.Devices, device)
}

// RemoveDevice remove a device from g.Config.Linux.Devices
func (g *Generator) RemoveDevice(path string) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Devices == nil {
		return
	}

	for i, device := range g.Config.Linux.Devices {
		if device.Path == path {
			g.Config.Linux.Devices = append(g.Config.Linux.Devices[:i], g.Config.Linux.Devices[i+1:]...)
			return
		}
	}
}

// ClearLinuxDevices clears g.Config.Linux.Devices
func (g *Generator) ClearLinuxDevices() {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Devices == nil {
		return
	}

	g.Config.Linux.Devices = []rspec.LinuxDevice{}
}

// AddLinuxResourcesDevice - add a device into g.Config.Linux.Resources.Devices
func (g *Generator) AddLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) {
	g.initConfigLinuxResources()

	device := rspec.LinuxDeviceCgroup{
		Allow:  allow,
		Type:   devType,
		Access: access,
		Major:  major,
		Minor:  minor,
	}
	g.Config.Linux.Resources.Devices = append(g.Config.Linux.Resources.Devices, device)
}

// RemoveLinuxResourcesDevice - remove a device from g.Config.Linux.Resources.Devices
func (g *Generator) RemoveLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) {
	if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil {
		return
	}
	for i, device := range g.Config.Linux.Resources.Devices {
		if device.Allow == allow &&
			(devType == device.Type || (devType != "" && device.Type != "" && devType == device.Type)) &&
			(access == device.Access || (access != "" && device.Access != "" && access == device.Access)) &&
			(major == device.Major || (major != nil && device.Major != nil && *major == *device.Major)) &&
			(minor == device.Minor || (minor != nil && device.Minor != nil && *minor == *device.Minor)) {

			g.Config.Linux.Resources.Devices = append(g.Config.Linux.Resources.Devices[:i], g.Config.Linux.Resources.Devices[i+1:]...)
			return
		}
	}
	return
}

// strPtr returns the pointer pointing to the string s.
func strPtr(s string) *string { return &s }

// SetSyscallAction adds rules for syscalls with the specified action
func (g *Generator) SetSyscallAction(arguments seccomp.SyscallOpts) error {
	g.initConfigLinuxSeccomp()
	return seccomp.ParseSyscallFlag(arguments, g.Config.Linux.Seccomp)
}

// SetDefaultSeccompAction sets the default action for all syscalls not defined
// and then removes any syscall rules with this action already specified.
func (g *Generator) SetDefaultSeccompAction(action string) error {
	g.initConfigLinuxSeccomp()
	return seccomp.ParseDefaultAction(action, g.Config.Linux.Seccomp)
}

// SetDefaultSeccompActionForce only sets the default action for all syscalls not defined
func (g *Generator) SetDefaultSeccompActionForce(action string) error {
	g.initConfigLinuxSeccomp()
	return seccomp.ParseDefaultActionForce(action, g.Config.Linux.Seccomp)
}

// SetSeccompArchitecture sets the supported seccomp architectures
func (g *Generator) SetSeccompArchitecture(architecture string) error {
	g.initConfigLinuxSeccomp()
	return seccomp.ParseArchitectureFlag(architecture, g.Config.Linux.Seccomp)
}

// RemoveSeccompRule removes rules for any specified syscalls
func (g *Generator) RemoveSeccompRule(arguments string) error {
	g.initConfigLinuxSeccomp()
	return seccomp.RemoveAction(arguments, g.Config.Linux.Seccomp)
}

// RemoveAllSeccompRules removes all syscall rules
func (g *Generator) RemoveAllSeccompRules() error {
	g.initConfigLinuxSeccomp()
	return seccomp.RemoveAllSeccompRules(g.Config.Linux.Seccomp)
}

// AddLinuxMaskedPaths adds masked paths into g.Config.Linux.MaskedPaths.
func (g *Generator) AddLinuxMaskedPaths(path string) {
	g.initConfigLinux()
	g.Config.Linux.MaskedPaths = append(g.Config.Linux.MaskedPaths, path)
}

// AddLinuxReadonlyPaths adds readonly paths into g.Config.Linux.MaskedPaths.
func (g *Generator) AddLinuxReadonlyPaths(path string) {
	g.initConfigLinux()
	g.Config.Linux.ReadonlyPaths = append(g.Config.Linux.ReadonlyPaths, path)
}

func addOrReplaceBlockIOThrottleDevice(tmpList []rspec.LinuxThrottleDevice, major int64, minor int64, rate uint64) []rspec.LinuxThrottleDevice {
	throttleDevices := tmpList
	for i, throttleDevice := range throttleDevices {
		if throttleDevice.Major == major && throttleDevice.Minor == minor {
			throttleDevices[i].Rate = rate
			return throttleDevices
		}
	}
	throttleDevice := new(rspec.LinuxThrottleDevice)
	throttleDevice.Major = major
	throttleDevice.Minor = minor
	throttleDevice.Rate = rate
	throttleDevices = append(throttleDevices, *throttleDevice)

	return throttleDevices
}

func dropBlockIOThrottleDevice(tmpList []rspec.LinuxThrottleDevice, major int64, minor int64) []rspec.LinuxThrottleDevice {
	throttleDevices := tmpList
	for i, throttleDevice := range throttleDevices {
		if throttleDevice.Major == major && throttleDevice.Minor == minor {
			throttleDevices = append(throttleDevices[:i], throttleDevices[i+1:]...)
			return throttleDevices
		}
	}

	return throttleDevices
}

// AddSolarisAnet adds network into g.Config.Solaris.Anet
func (g *Generator) AddSolarisAnet(anet rspec.SolarisAnet) {
	g.initConfigSolaris()
	g.Config.Solaris.Anet = append(g.Config.Solaris.Anet, anet)
}

// SetSolarisCappedCPUNcpus sets g.Config.Solaris.CappedCPU.Ncpus
func (g *Generator) SetSolarisCappedCPUNcpus(ncpus string) {
	g.initConfigSolarisCappedCPU()
	g.Config.Solaris.CappedCPU.Ncpus = ncpus
}

// SetSolarisCappedMemoryPhysical sets g.Config.Solaris.CappedMemory.Physical
func (g *Generator) SetSolarisCappedMemoryPhysical(physical string) {
	g.initConfigSolarisCappedMemory()
	g.Config.Solaris.CappedMemory.Physical = physical
}

// SetSolarisCappedMemorySwap sets g.Config.Solaris.CappedMemory.Swap
func (g *Generator) SetSolarisCappedMemorySwap(swap string) {
	g.initConfigSolarisCappedMemory()
	g.Config.Solaris.CappedMemory.Swap = swap
}

// SetSolarisLimitPriv sets g.Config.Solaris.LimitPriv
func (g *Generator) SetSolarisLimitPriv(limitPriv string) {
	g.initConfigSolaris()
	g.Config.Solaris.LimitPriv = limitPriv
}

// SetSolarisMaxShmMemory sets g.Config.Solaris.MaxShmMemory
func (g *Generator) SetSolarisMaxShmMemory(memory string) {
	g.initConfigSolaris()
	g.Config.Solaris.MaxShmMemory = memory
}

// SetSolarisMilestone sets g.Config.Solaris.Milestone
func (g *Generator) SetSolarisMilestone(milestone string) {
	g.initConfigSolaris()
	g.Config.Solaris.Milestone = milestone
}

// SetWindowsHypervUntilityVMPath sets g.Config.Windows.HyperV.UtilityVMPath.
func (g *Generator) SetWindowsHypervUntilityVMPath(path string) {
	g.initConfigWindowsHyperV()
	g.Config.Windows.HyperV.UtilityVMPath = path
}

// SetWinodwsIgnoreFlushesDuringBoot sets g.Config.Winodws.IgnoreFlushesDuringBoot.
func (g *Generator) SetWinodwsIgnoreFlushesDuringBoot(ignore bool) {
	g.initConfigWindows()
	g.Config.Windows.IgnoreFlushesDuringBoot = ignore
}

// AddWindowsLayerFolders adds layer folders into  g.Config.Windows.LayerFolders.
func (g *Generator) AddWindowsLayerFolders(folder string) {
	g.initConfigWindows()
	g.Config.Windows.LayerFolders = append(g.Config.Windows.LayerFolders, folder)
}

// SetWindowsNetwork sets g.Config.Windows.Network.
func (g *Generator) SetWindowsNetwork(network rspec.WindowsNetwork) {
	g.initConfigWindows()
	g.Config.Windows.Network = &network
}

// SetWindowsResourcesCPU sets g.Config.Windows.Resources.CPU.
func (g *Generator) SetWindowsResourcesCPU(cpu rspec.WindowsCPUResources) {
	g.initConfigWindowsResources()
	g.Config.Windows.Resources.CPU = &cpu
}

// SetWindowsResourcesMemoryLimit sets g.Config.Windows.Resources.Memory.Limit.
func (g *Generator) SetWindowsResourcesMemoryLimit(limit uint64) {
	g.initConfigWindowsResourcesMemory()
	g.Config.Windows.Resources.Memory.Limit = &limit
}

// SetWindowsResourcesStorage sets g.Config.Windows.Resources.Storage.
func (g *Generator) SetWindowsResourcesStorage(storage rspec.WindowsStorageResources) {
	g.initConfigWindowsResources()
	g.Config.Windows.Resources.Storage = &storage
}

// SetWinodwsServicing sets g.Config.Winodws.Servicing.
func (g *Generator) SetWinodwsServicing(servicing bool) {
	g.initConfigWindows()
	g.Config.Windows.Servicing = servicing
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Linq;

namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement
{
    /// <summary>
    /// Obtains all the shard maps and shards from an LSM.
    /// </summary>
    internal class GetShardsLocalOperation : StoreOperationLocal
    {
        /// <summary>
        /// Constructs request for obtaining all the shard maps and shards from an LSM.
        /// </summary>
        /// <param name="shardMapManager">Shard map manager.</param>
        /// <param name="location">Location of the LSM.</param>
        /// <param name="operationName">Operatio name.</param>
        internal GetShardsLocalOperation(ShardMapManager shardMapManager, ShardLocation location, string operationName) :
            base(shardMapManager.Credentials, shardMapManager.RetryPolicy, location, operationName)
        {
        }

        /// <summary>
        /// Whether this is a read-only operation.
        /// </summary>
        public override bool ReadOnly
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Execute the operation against LSM in the current transaction scope.
        /// </summary>
        /// <param name="ts">Transaction scope.</param>
        /// <returns>
        /// Results of the operation.
        /// </returns>
        public override IStoreResults DoLocalExecute(IStoreTransactionScope ts)
        {
            IStoreResults result = ts.ExecuteCommandSingle(SqlUtils.CheckIfExistsLocalScript.Single());

            if (result.StoreVersion == null)
            {
                // Shard not deployed, which is an error condition.
                throw new ShardManagementException(
                    ShardManagementErrorCategory.Recovery,
                    ShardManagementErrorCode.ShardNotValid,
                    Errors._Recovery_ShardNotValid,
                    this.Location,
                    this.OperationName);
            }

            return ts.ExecuteOperation(
                StoreOperationRequestBuilder.SpGetAllShardsLocal,
                StoreOperationRequestBuilder.GetAllShardsLocal());
        }

        /// <summary>
        /// Handles errors from the LSM operation.
        /// </summary>
        /// <param name="result">Operation result.</param>
        public override void HandleDoLocalExecuteError(IStoreResults result)
        {
            // Possible errors are:
            // StoreResult.StoreVersionMismatch
            // StoreResult.MissingParametersForStoredProcedure
            throw StoreOperationErrorHandler.OnRecoveryErrorLocal(
                result,
                null,
                this.Location,
                ShardManagementErrorCategory.Recovery,
                this.OperationName,
                StoreOperationRequestBuilder.SpGetAllShardsLocal);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* Generic definitions */

/* Assertions (useful to generate conditional code) */
/* Current type and class (and size, if applicable) */
/* Value methods */
/* Interfaces (keys) */
/* Interfaces (values) */
/* Abstract implementations (keys) */
/* Abstract implementations (values) */
/* Static containers (keys) */
/* Static containers (values) */
/* Implementations */
/* Synchronized wrappers */
/* Unmodifiable wrappers */
/* Other wrappers */
/* Methods (keys) */
/* Methods (values) */
/* Methods (keys/values) */
/* Methods that have special names depending on keys (but the special names depend on values) */
/* Equality */
/* Object/Reference-only definitions (keys) */
/* Primitive-type-only definitions (keys) */
/* Object/Reference-only definitions (values) */
/* Primitive-type-only definitions (values) */
/*
 * Copyright (C) 2002-2013 Sebastiano Vigna
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package it.unimi.dsi.fastutil.shorts;
import it.unimi.dsi.fastutil.floats.FloatCollection;
import it.unimi.dsi.fastutil.floats.AbstractFloatCollection;
import it.unimi.dsi.fastutil.floats.FloatIterator;
import it.unimi.dsi.fastutil.floats.AbstractFloatIterator;
import it.unimi.dsi.fastutil.objects.ObjectSet;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import java.util.Iterator;
import java.util.Map;
/** An abstract class providing basic methods for maps implementing a type-specific interface.
 *
 *
Optional operations just throw an {@link
 * UnsupportedOperationException}. Generic versions of accessors delegate to
 * the corresponding type-specific counterparts following the interface rules
 * (they take care of returning null on a missing key).
 *
 *
As a further help, this class provides a {@link BasicEntry BasicEntry} inner class
 * that implements a type-specific version of {@link java.util.Map.Entry}; it
 * is particularly useful for those classes that do not implement their own
 * entries (e.g., most immutable maps).
 */
public abstract class AbstractShort2FloatMap extends AbstractShort2FloatFunction implements Short2FloatMap , java.io.Serializable {
 private static final long serialVersionUID = -4940583368468432370L;
 protected AbstractShort2FloatMap() {}
 public boolean containsValue( Object ov ) {
  return containsValue( ((((Float)(ov)).floatValue())) );
 }
 /** Checks whether the given value is contained in {@link #values()}. */
 public boolean containsValue( float v ) {
  return values().contains( v );
 }
 /** Checks whether the given value is contained in {@link #keySet()}. */
 public boolean containsKey( short k ) {
  return keySet().contains( k );
 }
 /** Puts all pairs in the given map.
	 * If the map implements the interface of this map,
	 * it uses the faster iterators.
	 *
	 * @param m a map.
	 */
 @SuppressWarnings("unchecked")
 public void putAll(Map<? extends Short,? extends Float> m) {
  int n = m.size();
  final Iterator<? extends Map.Entry<? extends Short,? extends Float>> i = m.entrySet().iterator();
  if (m instanceof Short2FloatMap) {
   Short2FloatMap.Entry e;
   while(n-- != 0) {
    e = (Short2FloatMap.Entry )i.next();
    put(e.getShortKey(), e.getFloatValue());
   }
  }
  else {
   Map.Entry<? extends Short,? extends Float> e;
   while(n-- != 0) {
    e = i.next();
    put(e.getKey(), e.getValue());
   }
  }
 }
 public boolean isEmpty() {
  return size() == 0;
 }
 /** This class provides a basic but complete type-specific entry class for all those maps implementations
	 * that do not have entries on their own (e.g., most immutable maps).
	 *
	 *
This class does not implement {@link java.util.Map.Entry#setValue(Object) setValue()}, as the modification
	 * would not be reflected in the base map.
	 */
 public static class BasicEntry implements Short2FloatMap.Entry {
  protected short key;
  protected float value;
  public BasicEntry( final Short key, final Float value ) {
   this.key = ((key).shortValue());
   this.value = ((value).floatValue());
  }
  public BasicEntry( final short key, final float value ) {
   this.key = key;
   this.value = value;
  }

  public Short getKey() {
   return (Short.valueOf(key));
  }

  public short getShortKey() {
   return key;
  }

  public Float getValue() {
   return (Float.valueOf(value));
  }

  public float getFloatValue() {
   return value;
  }

  public float setValue( final float value ) {
   throw new UnsupportedOperationException();
  }

  public Float setValue( final Float value ) {
   return Float.valueOf(setValue(value.floatValue()));
  }

  public boolean equals( final Object o ) {
   if (!(o instanceof Map.Entry)) return false;
   Map.Entry<?,?> e = (Map.Entry<?,?>)o;

   return ( (key) == (((((Short)(e.getKey())).shortValue()))) ) && ( (value) == (((((Float)(e.getValue())).floatValue()))) );
  }

  public int hashCode() {
   return (key) ^ it.unimi.dsi.fastutil.HashCommon.float2int(value);
  }

  public String toString() {
   return key + "->" + value;
  }
 }

 /** Returns a type-specific-set view of the keys of this map.
	 *
	 *
The view is backed by the set returned by {@link #entrySet()}. Note that
	 * no attempt is made at caching the result of this method, as this would
	 * require adding some attributes that lightweight implementations would
	 * not need. Subclasses may easily override this policy by calling
	 * this method and caching the result, but implementors are encouraged to
	 * write more efficient ad-hoc implementations.
	 *
	 * @return a set view of the keys of this map; it may be safely cast to a type-specific interface.
	 */

 public ShortSet keySet() {
  return new AbstractShortSet () {

    public boolean contains( final short k ) { return containsKey( k ); }

    public int size() { return AbstractShort2FloatMap.this.size(); }
    public void clear() { AbstractShort2FloatMap.this.clear(); }

    public ShortIterator iterator() {
     return new AbstractShortIterator () {
       final ObjectIterator<Map.Entry<Short,Float>> i = entrySet().iterator();

       public short nextShort() { return ((Short2FloatMap.Entry )i.next()).getShortKey(); };

       public boolean hasNext() { return i.hasNext(); }
      };
    }
   };
 }

 /** Returns a type-specific-set view of the values of this map.
	 *
	 *
The view is backed by the set returned by {@link #entrySet()}. Note that
	 * no attempt is made at caching the result of this method, as this would
	 * require adding some attributes that lightweight implementations would
	 * not need. Subclasses may easily override this policy by calling
	 * this method and caching the result, but implementors are encouraged to
	 * write more efficient ad-hoc implementations.
	 *
	 * @return a set view of the values of this map; it may be safely cast to a type-specific interface.
	 */

 public FloatCollection values() {
  return new AbstractFloatCollection () {

    public boolean contains( final float k ) { return containsValue( k ); }

    public int size() { return AbstractShort2FloatMap.this.size(); }
    public void clear() { AbstractShort2FloatMap.this.clear(); }

    public FloatIterator iterator() {
     return new AbstractFloatIterator () {
       final ObjectIterator<Map.Entry<Short,Float>> i = entrySet().iterator();

       public float nextFloat() { return ((Short2FloatMap.Entry )i.next()).getFloatValue(); };

       public boolean hasNext() { return i.hasNext(); }
      };
    }
   };
 }

 @SuppressWarnings({ "unchecked", "rawtypes" })
 public ObjectSet<Map.Entry<Short, Float>> entrySet() {
  return (ObjectSet)short2FloatEntrySet();
 }

 /** Returns a hash code for this map.
	 *
	 * The hash code of a map is computed by summing the hash codes of its entries.
	 *
	 * @return a hash code for this map.
	 */

 public int hashCode() {
  int h = 0, n = size();
  final ObjectIterator<? extends Map.Entry<Short,Float>> i = entrySet().iterator();

  while( n-- != 0 ) h += i.next().hashCode();
  return h;
 }

 public boolean equals(Object o) {
  if ( o == this ) return true;
  if ( ! ( o instanceof Map ) ) return false;

  Map<?,?> m = (Map<?,?>)o;
  if ( m.size() != size() ) return false;
  return entrySet().containsAll( m.entrySet() );
 }

 public String toString() {
  final StringBuilder s = new StringBuilder();
  final ObjectIterator<? extends Map.Entry<Short,Float>> i = entrySet().iterator();
  int n = size();
  Short2FloatMap.Entry e;
  boolean first = true;

  s.append("{");

  while(n-- != 0) {
   if (first) first = false;
   else s.append(", ");

   e = (Short2FloatMap.Entry )i.next();

    s.append(String.valueOf(e.getShortKey()));
   s.append("=>");

    s.append(String.valueOf(e.getFloatValue()));
  }

  s.append("}");
  return s.toString();
 }

}


text:
/* $This file is distributed under the terms of the license in LICENSE$ */

package edu.cornell.mannlib.vitro.webapp.utils.configuration;

import edu.cornell.mannlib.vitro.webapp.modelaccess.RequestModelAccess;

/**
 * When the ConfigurationBeanLoader creates an instance of this class, it will
 * call this method, supplying the RDF models for the current HTTP request.
 */
public interface RequestModelsUser {
	void setRequestModels(RequestModelAccess models);
}


text:
from __future__ import unicode_literals
from ..model import SegStats

def test_SegStats_inputs():
    input_map = dict(annot=dict(argstr='--annot %s %s %s',
    mandatory=True,
    xor=('segmentation_file', 'annot', 'surf_label'),
    ),
    args=dict(argstr='%s',
    ),
    avgwf_file=dict(argstr='--avgwfvol %s',
    ),
    avgwf_txt_file=dict(argstr='--avgwf %s',
    ),
    brain_vol=dict(argstr='--%s',
    ),
    brainmask_file=dict(argstr='--brainmask %s',
    ),
    calc_power=dict(argstr='--%s',
    ),
    calc_snr=dict(argstr='--snr',
    ),
    color_table_file=dict(argstr='--ctab %s',
    xor=('color_table_file', 'default_color_table', 'gca_color_table'),
    ),
    cortex_vol_from_surf=dict(argstr='--surf-ctx-vol',
    ),
    default_color_table=dict(argstr='--ctab-default',
    xor=('color_table_file', 'default_color_table', 'gca_color_table'),
    ),
    empty=dict(argstr='--empty',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    etiv=dict(argstr='--etiv',
    ),
    etiv_only=dict(),
    euler=dict(argstr='--euler',
    ),
    exclude_ctx_gm_wm=dict(argstr='--excl-ctxgmwm',
    ),
    exclude_id=dict(argstr='--excludeid %d',
    ),
    frame=dict(argstr='--frame %d',
    ),
    gca_color_table=dict(argstr='--ctab-gca %s',
    xor=('color_table_file', 'default_color_table', 'gca_color_table'),
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    in_file=dict(argstr='--i %s',
    ),
    in_intensity=dict(argstr='--in %s --in-intensity-name %s',
    ),
    intensity_units=dict(argstr='--in-intensity-units %s',
    requires=['in_intensity'],
    ),
    mask_erode=dict(argstr='--maskerode %d',
    ),
    mask_file=dict(argstr='--mask %s',
    ),
    mask_frame=dict(requires=['mask_file'],
    ),
    mask_invert=dict(argstr='--maskinvert',
    ),
    mask_sign=dict(),
    mask_thresh=dict(argstr='--maskthresh %f',
    ),
    multiply=dict(argstr='--mul %f',
    ),
    non_empty_only=dict(argstr='--nonempty',
    ),
    partial_volume_file=dict(argstr='--pv %s',
    ),
    segment_id=dict(argstr='--id %s...',
    ),
    segmentation_file=dict(argstr='--seg %s',
    mandatory=True,
    xor=('segmentation_file', 'annot', 'surf_label'),
    ),
    sf_avg_file=dict(argstr='--sfavg %s',
    ),
    subcort_gm=dict(argstr='--subcortgray',
    ),
    subjects_dir=dict(),
    summary_file=dict(argstr='--sum %s',
    genfile=True,
    position=-1,
    ),
    supratent=dict(argstr='--supratent',
    ),
    surf_label=dict(argstr='--slabel %s %s %s',
    mandatory=True,
    xor=('segmentation_file', 'annot', 'surf_label'),
    ),
    terminal_output=dict(deprecated='1.0.0',
    nohash=True,
    ),
    total_gray=dict(argstr='--totalgray',
    ),
    vox=dict(argstr='--vox %s',
    ),
    wm_vol_from_surf=dict(argstr='--surf-wm-vol',
    ),
    )
    inputs = SegStats.input_spec()

    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(inputs.traits()[key], metakey) == value

def test_SegStats_outputs():
    output_map = dict(avgwf_file=dict(),
    avgwf_txt_file=dict(),
    sf_avg_file=dict(),
    summary_file=dict(),
    )
    outputs = SegStats.output_spec()

    for key, metadata in list(output_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(outputs.traits()[key], metakey) == value


text:
<?php
/**
 * @file mod/thing.php
 * @brief
 */

require_once('include/items.php');
require_once('include/contact_selectors.php');

function thing_init(&$a) {

	if(! local_channel())
		return;

	$account_id = $a->get_account();
	$channel    = $a->get_channel();

	$term_hash = (($_REQUEST['term_hash']) ? $_REQUEST['term_hash'] : '');

	$name = escape_tags($_REQUEST['term']);
	$verb = escape_tags($_REQUEST['verb']);
	$activity = intval($_REQUEST['activity']);
	$profile_guid = escape_tags($_REQUEST['profile_assign']);
	$url = $_REQUEST['link'];
	$photo = $_REQUEST['img'];

	$hash = random_string();

	$verbs = obj_verbs();

	/**
	 * verbs: [0] = first person singular, e.g. "I want", [1] = 3rd person singular, e.g. "Bill wants"
	 * We use the first person form when creating an activity, but the third person for use in activities
	 * @FIXME There is no accounting for verb gender for languages where this is significant. We may eventually
	 * require obj_verbs() to provide full conjugations and specify which form to use in the $_REQUEST params to this module.
	 */

	$translated_verb = $verbs[$verb][1];

	/*
	 * The site administrator can do things that normals cannot.
	 * This is restricted because it will likely cause
	 * an activitystreams protocol violation and the activity might
	 * choke in some other network and result in unnecessary
	 * support requests. It isn't because we're trying to be heavy-handed
	 * about what you can and can't do.
	 */

	if(! $translated_verb) {
		if(is_site_admin())
			$translated_verb = $verb;
	}

	/*
	 * Things, objects: We do not provide definite (a, an) or indefinite (the) articles or singular/plural designators
	 * That needs to be specified in your thing. e.g. Mike has "a carrot", Greg wants "balls", Bob likes "the Boston Red Sox".
	 */

	/*
	 * Future work on this module might produce more complex activities with targets, e.g. Phillip likes Karen's moustache
	 * and to describe other non-thing objects like channels, such as Karl wants Susan - where Susan represents a channel profile.
	 */

	if((! $name) || (! $translated_verb))
		return;

	if($term_hash) {
		$t = q("select * from obj left join term on obj_obj = term_hash where term_hash != '' and obj_type = %d and term_hash = '%s' limit 1",
			intval(TERM_OBJ_THING),
			dbesc($term_hash)
		);
		if(! $t) {
			notice( t('Item not found.') . EOL);
			return;
		}
		$orig_record = $t[0];
		if($photo != $orig_record['imgurl']) {
			$arr = import_profile_photo($photo,get_observer_hash(),true);
			$local_photo = $arr[0];
			$local_photo_type = $arr[3];
		}
		else
			$local_photo = $orig_record['imgurl'];

		$r = q("update term  set term = '%s', url = '%s', imgurl = '%s' where term_hash = '%s' and uid = %d",
			dbesc($name),
			dbesc(($url) ? $url : z_root() . '/thing/' . $term_hash),
			dbesc($local_photo),
			dbesc($term_hash),
			intval(local_channel())
		);

		info( t('Thing updated') . EOL);
		return;
	}

	$sql = (($profile_guid) ? " and profile_guid = '" . dbesc($profile_guid) . "' " : " and is_default = 1 ");
	$p = q("select profile_guid, is_default from profile where uid = %d $sql limit 1",
		intval(local_channel())
	);

	if($p)
		$profile = $p[0];
	else
		return;

	$local_photo = null;

	if($photo) {
		$arr = import_profile_photo($photo,get_observer_hash(),true);
		$local_photo = $arr[0];
		$local_photo_type = $arr[3];
	}

	$r = q("select * from term where uid = %d and otype = %d and type = %d and term = '%s' limit 1",
		intval(local_channel()),
		intval(TERM_OBJ_THING),
		intval(TERM_THING),
		dbesc($name)
	);
	if(! $r) {
		$r = q("insert into term ( aid, uid, oid, otype, type, term, url, imgurl, term_hash )
			values( %d, %d, %d, %d, %d, '%s', '%s', '%s', '%s' ) ",
			intval($account_id),
			intval(local_channel()),
			0,
			intval(TERM_OBJ_THING),
			intval(TERM_THING),
			dbesc($name),
			dbesc(($url) ? $url : z_root() . '/thing/' . $hash),
			dbesc(($photo) ? $local_photo : ''),
			dbesc($hash)
		);
		$r = q("select * from term where uid = %d and otype = %d and type = %d and term = '%s' limit 1",
			intval(local_channel()),
			intval(TERM_OBJ_THING),
			intval(TERM_THING),
			dbesc($name)
		);
	}
	$term = $r[0];

	$r = q("insert into obj ( obj_page, obj_verb, obj_type, obj_channel, obj_obj) values ('%s','%s', %d, %d, '%s') ",
		dbesc($profile['profile_guid']),
		dbesc($verb),
		intval(TERM_OBJ_THING),
		intval(local_channel()),
		dbesc($term['term_hash'])
	);

	if(! $r) {
		notice( t('Object store: failed'));
		return;
	}

	info( t('Thing added'));

	if($activity) {
		$arr = array();
		$links = array(array('rel' => 'alternate','type' => 'text/html', 'href' => $term['url']));
		if($local_photo)
			$links[] = array('rel' => 'photo', 'type' => $local_photo_type, 'href' => $local_photo);

		$objtype = ACTIVITY_OBJ_THING;

		$obj = json_encode(array(
			'type'    => $objtype,
			'id'      => $term['url'],
			'link'    => $links,
			'title'   => $term['term'],
			'content' => $term['term']
		));

		$bodyverb = str_replace('OBJ: ', '',t('OBJ: %1$s %2$s %3$s'));

		$arr['owner_xchan']  = $channel['channel_hash'];
		$arr['author_xchan'] = $channel['channel_hash'];

		$arr['item_flags'] = ITEM_ORIGIN|ITEM_WALL|ITEM_THREAD_TOP;

		$ulink = '[zrl=' . $channel['xchan_url'] . ']' . $channel['channel_name'] . '[/zrl]';
		$plink = '[zrl=' . $term['url'] . ']' . $term['term'] . '[/zrl]';

		$arr['body'] =  sprintf( $bodyverb, $ulink, $translated_verb, $plink );

		if($local_photo)
			$arr['body'] .= "\n\n[zmg]" . $local_photo . "[/zmg]";

		$arr['verb'] = $verb;
		$arr['obj_type'] = $objtype;
		$arr['object'] = $obj;

		if(! $profile['is_default']) {
			$arr['item_private'] = true;
			$str = '';
			$r = q("select abook_xchan from abook where abook_channel = %d and abook_profile = '%s'",
				intval(local_channel()),
				dbesc($profile_guid)
			);
			if($r) {
				$arr['allow_cid'] = '';
				foreach($r as $rr)
					$arr['allow_cid'] .= '<' . $rr['abook_xchan'] . '>';
			}
			else
				$arr['allow_cid'] = '<' . get_observer_hash() . '>';
		}

		$ret = post_activity_item($arr);
	}
}

function thing_content(&$a) {

	if(argc() == 2) {

		$r = q("select * from obj left join term on obj_obj = term_hash where term_hash != '' and obj_type = %d and term_hash = '%s' limit 1",
			intval(TERM_OBJ_THING),
			dbesc(argv(1))
		);

		if($r) {
			return replace_macros(get_markup_template('show_thing.tpl'), array(
				'$header' => t('Show Thing'),
				'$edit' => t('Edit'),
				'$delete' => t('Delete'),
				'$canedit' => ((local_channel() && local_channel() == $r[0]['obj_channel']) ? true : false),
				'$thing' => $r[0] ));
		}
		else {
			notice( t('item not found.') . EOL);
			return;
		}
	}

	$channel = $a->get_channel();

	if(! (local_channel() && $channel)) {
		notice( t('Permission denied.') . EOL);
		return;
	}

	$thing_hash = '';

	if(argc() == 3 && argv(1) === 'edit') {
		$thing_hash = argv(2);

		$r = q("select * from obj left join term on obj_obj = term_hash where term_hash != '' and obj_type = %d and term_hash = '%s' limit 1",
			intval(TERM_OBJ_THING),
			dbesc($thing_hash)
		);

		if((! $r) || ($r[0]['obj_channel'] != local_channel())) {
			notice( t('Permission denied.') . EOL);
			return '';
		}

		$o .= replace_macros(get_markup_template('thing_edit.tpl'),array(
			'$thing_hdr' => t('Edit Thing'),
			'$multiprof' => feature_enabled(local_channel(),'multi_profiles'),
			'$profile_lbl' => t('Select a profile'),
			'$profile_select' => contact_profile_assign($r[0]['obj_page']),
			'$verb_lbl' => $channel['channel_name'],
			'$verb_select' => obj_verb_selector($r[0]['obj_verb']),
			'$activity' => array('activity',t('Post an activity'),true,t('Only sends to viewers of the applicable profile')),
			'$thing_hash' => $thing_hash,
			'$thing_lbl' => t('Name of thing e.g. something'),
			'$thething' => $r[0]['term'],
			'$url_lbl' => t('URL of thing (optional)'),
			'$theurl' => $r[0]['url'],
			'$img_lbl' => t('URL for photo of thing (optional)'),
			'$imgurl' => $r[0]['imgurl'],
			'$submit' => t('Submit')
		));

		return $o;
	}

	if(argc() == 3 && argv(1) === 'drop') {
		$thing_hash = argv(2);

		$r = q("select * from obj left join term on obj_obj = term_hash where term_hash != '' and obj_type = %d and term_hash = '%s' limit 1",
			intval(TERM_OBJ_THING),
			dbesc($thing_hash)
		);

		if((! $r) || ($r[0]['obj_channel'] != local_channel())) {
			notice( t('Permission denied.') . EOL);
			return '';
		}

		$x = q("delete from obj where obj_obj = '%s' and obj_type = %d and obj_channel = %d",
			dbesc($thing_hash),
			intval(TERM_OBJ_THING),
			intval(local_channel())
		);
		$x = q("delete from term where term_hash = '%s' and uid = %d",
			dbesc($thing_hash),
			intval(local_channel())
		);

		return $o;
	}

	$o .= replace_macros(get_markup_template('thing_input.tpl'),array(
		'$thing_hdr' => t('Add Thing to your Profile'),
		'$multiprof' => feature_enabled(local_channel(),'multi_profiles'),
		'$profile_lbl' => t('Select a profile'),
		'$profile_select' => contact_profile_assign(''),
		'$verb_lbl' => $channel['channel_name'],
		'$activity' => array('activity',t('Post an activity'),((array_key_exists('activity',$_REQUEST)) ? $_REQUEST['activity'] : true),t('Only sends to viewers of the applicable profile')),
		'$verb_select' => obj_verb_selector(),
		'$thing_lbl' => t('Name of thing e.g. something'),
		'$url_lbl' => t('URL of thing (optional)'),
		'$img_lbl' => t('URL for photo of thing (optional)'),
		'$submit' => t('Submit')
	));

	return $o;
}


text:
package org.apache.juddi.samples;

import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.ws.Holder;
import org.apache.juddi.v3.client.config.UDDIClient;
import org.apache.juddi.v3.client.transport.Transport;
import org.uddi.api_v3.*;
import org.uddi.custody_v3.KeyBag;
import org.uddi.custody_v3.TransferEntities;
import org.uddi.custody_v3.TransferToken;
import org.uddi.v3_service.UDDICustodyTransferPortType;
import org.uddi.v3_service.UDDIInquiryPortType;
import org.uddi.v3_service.UDDIPublicationPortType;
import org.uddi.v3_service.UDDISecurityPortType;

/**
 * This provides an example of how to transfer custody of a business from one
 * user to another on the same UDDI node. All child objects are also transfer
 *
 * @author Alex O'Ree
 */
public class UddiCustodyTransfer {

        private static UDDISecurityPortType security = null;
        private static UDDIPublicationPortType publish = null;
        private static UDDIInquiryPortType uddiInquiryService = null;
        private static UDDICustodyTransferPortType custodyTransferPortType = null;

        public UddiCustodyTransfer() {
                try {
                        // create a manager and read the config in the archive;
                        // you can use your config file name
                        UDDIClient clerkManager = new UDDIClient("META-INF/simple-publish-uddi.xml");
                        Transport transport = clerkManager.getTransport();
                        // Now you create a reference to the UDDI API
                        security = transport.getUDDISecurityService();

                        publish = transport.getUDDIPublishService();
                        uddiInquiryService = transport.getUDDIInquiryService();
                        custodyTransferPortType = transport.getUDDICustodyTransferService();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

        public static void main(String args[]) throws Exception {
                UddiCustodyTransfer sp = new UddiCustodyTransfer();

                GetAuthToken getAuthTokenRoot = new GetAuthToken();
                getAuthTokenRoot.setUserID("root");
                getAuthTokenRoot.setCred("root");

                // Making API call that retrieves the authentication token for the 'root' user.
                AuthToken rootAuthToken = security.getAuthToken(getAuthTokenRoot);
                System.out.println("root AUTHTOKEN = " + "don't log auth tokens!");

                getAuthTokenRoot = new GetAuthToken();
                getAuthTokenRoot.setUserID("uddi");
                getAuthTokenRoot.setCred("uddi");

                // Making API call that retrieves the authentication token for the 'root' user.
                AuthToken uddiAuthToken = security.getAuthToken(getAuthTokenRoot);
                System.out.println("uddi AUTHTOKEN = " + "don't log auth tokens!");
                BusinessEntity biz = sp.CreateBusiness("uddi");

                //save user uddi's business
                SaveBusiness sb = new SaveBusiness();
                sb.setAuthInfo(uddiAuthToken.getAuthInfo());
                sb.getBusinessEntity().add(biz);
                BusinessDetail saveBusiness = publish.saveBusiness(sb);

                sp.TransferBusiness(uddiAuthToken.getAuthInfo(), "uddi", rootAuthToken.getAuthInfo(), "root", saveBusiness.getBusinessEntity().get(0).getBusinessKey());
        }

        public void TransferBusiness(String fromUser, String fromUserAuthToken, String toUser, String toUserAuthToken,
                String BusinessKey) throws Exception {

                System.out.println("Transfering business key " + BusinessKey);
                DatatypeFactory df = DatatypeFactory.newInstance();
                GregorianCalendar gcal = new GregorianCalendar();
                gcal.setTimeInMillis(System.currentTimeMillis());
                XMLGregorianCalendar xcal = df.newXMLGregorianCalendar(gcal);

                //Create a transfer token from fromUser to toUser
                KeyBag kb = new KeyBag();
                kb.getKey().add(BusinessKey);
                Holder<String> nodeidOUT = new Holder<String>();
                Holder<XMLGregorianCalendar> expiresOUT = new Holder<XMLGregorianCalendar>();
                Holder<byte[]> tokenOUT = new Holder<byte[]>();
                custodyTransferPortType.getTransferToken(fromUserAuthToken, kb, nodeidOUT, expiresOUT, tokenOUT);

                System.out.println("Transfer token obtained. Give this to user " + toUser);
                System.out.println("Expires " + expiresOUT.value.toXMLFormat());
                System.out.println("Node " + nodeidOUT.value);
                System.out.println("Token " + org.apache.commons.codec.binary.Base64.encodeBase64String(tokenOUT.value));

                if (toUser == null || toUser.length() == 0 || toUserAuthToken == null || toUserAuthToken.length() == 0) {
                        System.out.println("The toUser parameters are either null or empty, I can't complete the transfer here");
                        return;
                }

                //The magic part happens here, the user ROOT needs to give the user UDDI the token information out of band
                //in practice, all values must match exactly
                //UDDI now accepts the transfer
                TransferEntities te = new TransferEntities();
                te.setAuthInfo(toUserAuthToken);
                te.setKeyBag(kb);
                TransferToken tt = new TransferToken();
                tt.setExpirationTime(expiresOUT.value);
                tt.setNodeID(nodeidOUT.value);
                tt.setOpaqueToken(tokenOUT.value);
                te.setTransferToken(tt);
                System.out.println("Excuting transfer...");
                custodyTransferPortType.transferEntities(te);
                System.out.println("Complete! verifing ownership change...");

                //confirm the transfer
                GetOperationalInfo go = new GetOperationalInfo();
                go.setAuthInfo(fromUserAuthToken);
                go.getEntityKey().add(BusinessKey);
                OperationalInfos operationalInfo = uddiInquiryService.getOperationalInfo(go);
                boolean ok = false;
                boolean found = false;
                for (int i = 0; i < operationalInfo.getOperationalInfo().size(); i++) {
                        if (operationalInfo.getOperationalInfo().get(i).getEntityKey().equalsIgnoreCase(BusinessKey)) {
                                found = true;
                                if (operationalInfo.getOperationalInfo().get(i).getAuthorizedName().equalsIgnoreCase(fromUser)) {
                                        System.out.println("Transfer unexpected failed");
                                }
                                if (operationalInfo.getOperationalInfo().get(i).getAuthorizedName().equalsIgnoreCase(toUser)) {
                                        ok = true;
                                }

                        }
                }
                if (!found) {
                        System.out.println("Could get the operational info the transfed business");
                }
                System.out.println("Transfer " + (ok ? "success" : " failed"));
        }

        private BusinessEntity CreateBusiness(String user) {
                BusinessEntity be = new BusinessEntity();
                be.getName().add(new Name(user + "'s business", null));
                return be;
        }

}


text:
package com.nexr.hive.excel;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.io.Writable;
import org.apache.poi.ss.usermodel.Cell;

public class ExcelRowWritable implements Writable {

	private final List<Cell> row = new ArrayList<Cell>();

	public void add(Cell cell) {
		row.add(cell);
	}

	public List<Cell> get() {
		return row;
	}

	public void clear() {
		row.clear();
	}

	@Override
	public void write(DataOutput out) throws IOException {
		throw new UnsupportedOperationException("write");
	}

	@Override
	public void readFields(DataInput in) throws IOException {
		throw new UnsupportedOperationException("readFields");
	}

	@Override
	public String toString() {
		return row.toString();
	}

}


text:
<?php

namespace Tebru\Retrofit\Test\Mock\Service;

use Tebru\Retrofit\Annotation as Rest;
use Tebru\Retrofit\Http\AsyncAware;
use Tebru\Retrofit\Http\Callback;

/**
 * Interface MockServiceAsync
 *
 * @author Edward Pfremmer <epfremme@nerdery.com>
 */
interface MockServiceAsync extends AsyncAware
{
    /**
     * @Rest\GET("/get")
     */
    public function asyncOptional(Callback $callback = null);

    /**
     * @Rest\GET("/get")
     */
    public function asyncNotOptional(Callback $callback);
}


text:
import {AntdWidgets} from "../../..";
declare const AntdWidgets: AntdWidgets;
export default AntdWidgets;


text:
``BARFcfg`` is a Python script built upon BARF that lets you recover the
control-flow graph of a binary program.

# Usage

```
usage: BARFcfg [-h] [-s SYMBOL_FILE] [-a] [-o RECOVER_ONE] [-f {graph,text}]
               [-t] [-d OUTPUT_DIR] [-b] [-r]
               filename

Tool for recovering CFG of a binary.

positional arguments:
  filename              Binary file name.

optional arguments:
  -h, --help            show this help message and exit
  -s SYMBOL_FILE, --symbol-file SYMBOL_FILE
                        Load symbols from file.
  -a, --recover-all     Recover all functions.
  -o RECOVER_ONE, --recover-one RECOVER_ONE
                        Recover specified function.
  -f {graph,text}, --format {graph,text}
                        Output format.
  -t, --time            Print process time.
  -d OUTPUT_DIR, --output-dir OUTPUT_DIR
                        Ouput directory.
  -b, --brief           Brief output.
  -r, --show-reil       Show REIL translation.

```