text:
package main

import (
	"encoding/binary"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"sync"

	"github.com/gorilla/mux"
	log "github.com/lxc/lxd/shared/log15"

	lxd "github.com/lxc/lxd/client"
	"github.com/lxc/lxd/lxd/cluster"
	"github.com/lxc/lxd/lxd/db"
	"github.com/lxc/lxd/lxd/state"
	"github.com/lxc/lxd/lxd/util"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/logger"
	"github.com/lxc/lxd/shared/version"
)

// Lock to prevent concurent networks creation
var networkCreateLock sync.Mutex

// API endpoints
func networksGet(d *Daemon, r *http.Request) Response {
	recursion := util.IsRecursionRequest(r)

	ifs, err := networkGetInterfaces(d.cluster)
	if err != nil {
		return InternalError(err)
	}

	resultString := []string{}
	resultMap := []api.Network{}
	for _, iface := range ifs {
		if !recursion {
			resultString = append(resultString, fmt.Sprintf("/%s/networks/%s", version.APIVersion, iface))
		} else {
			net, err := doNetworkGet(d, iface)
			if err != nil {
				continue
			}
			resultMap = append(resultMap, net)
		}
	}

	if !recursion {
		return SyncResponse(true, resultString)
	}

	return SyncResponse(true, resultMap)
}

func networksPost(d *Daemon, r *http.Request) Response {
	networkCreateLock.Lock()
	defer networkCreateLock.Unlock()

	req := api.NetworksPost{}

	// Parse the request
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		return BadRequest(err)
	}

	// Sanity checks
	if req.Name == "" {
		return BadRequest(fmt.Errorf("No name provided"))
	}

	err = networkValidName(req.Name)
	if err != nil {
		return BadRequest(err)
	}

	if req.Type != "" && req.Type != "bridge" {
		return BadRequest(fmt.Errorf("Only 'bridge' type networks can be created"))
	}

	if req.Config == nil {
		req.Config = map[string]string{}
	}

	err = networkValidateConfig(req.Name, req.Config)
	if err != nil {
		return BadRequest(err)
	}

	url := fmt.Sprintf("/%s/networks/%s", version.APIVersion, req.Name)
	response := SyncResponseLocation(true, nil, url)

	if isClusterNotification(r) {
		// This is an internal request which triggers the actual
		// creation of the network across all nodes, after they have
		// been previously defined.
		err = doNetworksCreate(d, req, true)
		if err != nil {
			return SmartError(err)
		}
		return response
	}

	targetNode := r.FormValue("target")
	if targetNode != "" {
		// A targetNode was specified, let's just define the node's
		// network without actually creating it. The only legal key
		// value for the storage config is 'bridge.external_interfaces'.
		for key := range req.Config {
			if !shared.StringInSlice(key, db.NetworkNodeConfigKeys) {
				return SmartError(fmt.Errorf("Invalid config key '%s'", key))
			}
		}
		err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
			return tx.NetworkCreatePending(targetNode, req.Name, req.Config)
		})
		if err != nil {
			if err == db.DbErrAlreadyDefined {
				return BadRequest(
					fmt.Errorf("The network already defined on node %s", targetNode))
			}
			return SmartError(err)
		}
		return response
	}

	err = networkFillConfig(&req)
	if err != nil {
		return SmartError(err)
	}

	// Check if we're clustered
	count, err := cluster.Count(d.State())
	if err != nil {
		return SmartError(err)
	}

	if count > 1 {
		err = networksPostCluster(d, req)
		if err != nil {
			return SmartError(err)
		}
		return response
	}

	// No targetNode was specified and we're either a single-node
	// cluster or not clustered at all, so create the storage
	// pool immediately.
	networks, err := networkGetInterfaces(d.cluster)
	if err != nil {
		return InternalError(err)
	}

	if shared.StringInSlice(req.Name, networks) {
		return BadRequest(fmt.Errorf("The network already exists"))
	}

	// Create the database entry
	_, err = d.cluster.NetworkCreate(req.Name, req.Description, req.Config)
	if err != nil {
		return SmartError(fmt.Errorf("Error inserting %s into database: %s", req.Name, err))
	}

	err = doNetworksCreate(d, req, true)
	if err != nil {
		return SmartError(err)
	}

	return response
}

func networksPostCluster(d *Daemon, req api.NetworksPost) error {
	// Check that no node-specific config key has been defined.
	for key := range req.Config {
		if shared.StringInSlice(key, db.NetworkNodeConfigKeys) {
			return fmt.Errorf("Config key '%s' is node-specific", key)
		}
	}

	// Check that the network is properly defined, fetch the node-specific
	// configs and insert the global config.
	var configs map[string]map[string]string
	var nodeName string
	err := d.cluster.Transaction(func(tx *db.ClusterTx) error {
		// Check that the network was defined at all.
		networkID, err := tx.NetworkID(req.Name)
		if err != nil {
			return err
		}

		// Fetch the node-specific configs.
		configs, err = tx.NetworkNodeConfigs(networkID)
		if err != nil {
			return err
		}

		// Take note of the name of this node
		nodeName, err = tx.NodeName()
		if err != nil {
			return err
		}

		// Insert the global config keys.
		return tx.NetworkConfigAdd(networkID, 0, req.Config)
	})
	if err != nil {
		if err == db.NoSuchObjectError {
			return fmt.Errorf("Network not pending on any node (use --target <node> first)")
		}
		return err
	}

	// Create the network on this node.
	nodeReq := req
	for key, value := range configs[nodeName] {
		nodeReq.Config[key] = value
	}
	err = doNetworksCreate(d, nodeReq, false)
	if err != nil {
		return err
	}

	// Notify all other nodes to create the network.
	notifier, err := cluster.NewNotifier(d.State(), d.endpoints.NetworkCert(), cluster.NotifyAll)
	if err != nil {
		return err
	}
	notifyErr := notifier(func(client lxd.ContainerServer) error {
		server, _, err := client.GetServer()
		if err != nil {
			return err
		}

		nodeReq := req
		for key, value := range configs[server.Environment.ServerName] {
			nodeReq.Config[key] = value
		}

		return client.CreateNetwork(nodeReq)
	})

	errored := notifyErr != nil

	// Finally update the storage network state.
	err = d.cluster.Transaction(func(tx *db.ClusterTx) error {
		if errored {
			return tx.NetworkErrored(req.Name)
		}
		return tx.NetworkCreated(req.Name)
	})
	if err != nil {
		return err
	}

	return notifyErr
}

func networkFillConfig(req *api.NetworksPost) error {
	// Set some default values where needed
	if req.Config["bridge.mode"] == "fan" {
		if req.Config["fan.underlay_subnet"] == "" {
			req.Config["fan.underlay_subnet"] = "auto"
		}
	} else {
		if req.Config["ipv4.address"] == "" {
			req.Config["ipv4.address"] = "auto"
		}
		if req.Config["ipv4.address"] == "auto" && req.Config["ipv4.nat"] == "" {
			req.Config["ipv4.nat"] = "true"
		}

		if req.Config["ipv6.address"] == "" {
			content, err := ioutil.ReadFile("/proc/sys/net/ipv6/conf/default/disable_ipv6")
			if err == nil && string(content) == "0\n" {
				req.Config["ipv6.address"] = "auto"
			}
		}
		if req.Config["ipv6.address"] == "auto" && req.Config["ipv6.nat"] == "" {
			req.Config["ipv6.nat"] = "true"
		}
	}

	// Replace "auto" by actual values
	err := networkFillAuto(req.Config)
	if err != nil {
		return err
	}
	return nil
}

// Create the network on the system. The withDatabase flag is used to decide
// whether to cleanup the database if an error occurs.
func doNetworksCreate(d *Daemon, req api.NetworksPost, withDatabase bool) error {
	// Start the network
	n, err := networkLoadByName(d.State(), req.Name)
	if err != nil {
		return err
	}

	err = n.Start()
	if err != nil {
		n.Delete(withDatabase)
		return err
	}

	return nil
}

var networksCmd = Command{name: "networks", get: networksGet, post: networksPost}

func networkGet(d *Daemon, r *http.Request) Response {
	// If a target was specified, forward the request to the relevant node.
	response := ForwardedResponseIfTargetIsRemote(d, r)
	if response != nil {
		return response
	}

	name := mux.Vars(r)["name"]

	n, err := doNetworkGet(d, name)
	if err != nil {
		return SmartError(err)
	}

	targetNode := r.FormValue("target")
	clustered, err := cluster.Enabled(d.db)
	if err != nil {
		return SmartError(err)
	}

	// If no target node is specified and the daemon is clustered, we omit
	// the node-specific fields.
	if targetNode == "" && clustered {
		for _, key := range db.NetworkNodeConfigKeys {
			delete(n.Config, key)
		}
	}

	etag := []interface{}{n.Name, n.Managed, n.Type, n.Description, n.Config}

	return SyncResponseETag(true, &n, etag)
}

func doNetworkGet(d *Daemon, name string) (api.Network, error) {
	// Get some information
	osInfo, _ := net.InterfaceByName(name)
	_, dbInfo, _ := d.cluster.NetworkGet(name)

	// Sanity check
	if osInfo == nil && dbInfo == nil {
		return api.Network{}, os.ErrNotExist
	}

	// Prepare the response
	n := api.Network{}
	n.Name = name
	n.UsedBy = []string{}
	n.Config = map[string]string{}

	// Look for containers using the interface
	cts, err := d.cluster.ContainersList(db.CTypeRegular)
	if err != nil {
		return api.Network{}, err
	}

	for _, ct := range cts {
		c, err := containerLoadByName(d.State(), ct)
		if err != nil {
			return api.Network{}, err
		}

		if networkIsInUse(c, n.Name) {
			n.UsedBy = append(n.UsedBy, fmt.Sprintf("/%s/containers/%s", version.APIVersion, ct))
		}
	}

	// Set the device type as needed
	if osInfo != nil && shared.IsLoopback(osInfo) {
		n.Type = "loopback"
	} else if dbInfo != nil || shared.PathExists(fmt.Sprintf("/sys/class/net/%s/bridge", n.Name)) {
		if dbInfo != nil {
			n.Managed = true
			n.Description = dbInfo.Description
			n.Config = dbInfo.Config
		}

		n.Type = "bridge"
	} else if shared.PathExists(fmt.Sprintf("/proc/net/vlan/%s", n.Name)) {
		n.Type = "vlan"
	} else if shared.PathExists(fmt.Sprintf("/sys/class/net/%s/device", n.Name)) {
		n.Type = "physical"
	} else if shared.PathExists(fmt.Sprintf("/sys/class/net/%s/bonding", n.Name)) {
		n.Type = "bond"
	} else {
		_, err := shared.RunCommand("ovs-vsctl", "br-exists", n.Name)
		if err == nil {
			n.Type = "bridge"
		} else {
			n.Type = "unknown"
		}
	}

	if dbInfo != nil {
		n.Status = dbInfo.Status
		n.Locations = dbInfo.Locations
	}

	return n, nil
}

func networkDelete(d *Daemon, r *http.Request) Response {
	name := mux.Vars(r)["name"]
	state := d.State()

	// Check if the network is pending, if so we just need to delete it from
	// the database.
	_, network, err := d.cluster.NetworkGet(name)
	if err != nil {
		return SmartError(err)
	}
	if network.Status == "Pending" {
		err := d.cluster.NetworkDelete(name)
		if err != nil {
			return SmartError(err)
		}
		return EmptySyncResponse
	}

	// Get the existing network
	n, err := networkLoadByName(state, name)
	if err != nil {
		return NotFound
	}

	withDatabase := true
	if isClusterNotification(r) {
		withDatabase = false // We just want to delete the network from the system
	} else {
		// Sanity checks
		if n.IsUsed() {
			return BadRequest(fmt.Errorf("The network is currently in use"))
		}

		// Notify all other nodes. If any node is down, an error will be returned.
		notifier, err := cluster.NewNotifier(d.State(), d.endpoints.NetworkCert(), cluster.NotifyAll)
		if err != nil {
			return SmartError(err)
		}
		err = notifier(func(client lxd.ContainerServer) error {
			return client.DeleteNetwork(name)
		})
		if err != nil {
			return SmartError(err)
		}
	}

	// Delete the network
	err = n.Delete(withDatabase)
	if err != nil {
		return SmartError(err)
	}

	// Cleanup storage
	if shared.PathExists(shared.VarPath("networks", n.name)) {
		os.RemoveAll(shared.VarPath("networks", n.name))
	}

	return EmptySyncResponse
}

func networkPost(d *Daemon, r *http.Request) Response {
	// FIXME: renaming a network is currently not supported in clustering
	//        mode. The difficulty is that network.Start() depends on the
	//        network having already been renamed in the database, which is
	//        a chicken-and-egg problem for cluster notifications (the
	//        serving node should typically do the database job, so the
	//        network is not yet renamed inthe db when the notified node
	//        runs network.Start).
	clustered, err := cluster.Enabled(d.db)
	if err != nil {
		return SmartError(err)
	}
	if clustered {
		return BadRequest(fmt.Errorf("Renaming a network not supported in LXD clusters"))
	}

	name := mux.Vars(r)["name"]
	req := api.NetworkPost{}
	state := d.State()

	// Parse the request
	err = json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		return BadRequest(err)
	}

	// Get the existing network
	n, err := networkLoadByName(state, name)
	if err != nil {
		return NotFound
	}

	// Sanity checks
	if req.Name == "" {
		return BadRequest(fmt.Errorf("No name provided"))
	}

	err = networkValidName(req.Name)
	if err != nil {
		return BadRequest(err)
	}

	// Check that the name isn't already in use
	networks, err := networkGetInterfaces(d.cluster)
	if err != nil {
		return InternalError(err)
	}

	if shared.StringInSlice(req.Name, networks) {
		return Conflict
	}

	// Rename it
	err = n.Rename(req.Name)
	if err != nil {
		return SmartError(err)
	}

	return SyncResponseLocation(true, nil, fmt.Sprintf("/%s/networks/%s", version.APIVersion, req.Name))
}

func networkPut(d *Daemon, r *http.Request) Response {
	name := mux.Vars(r)["name"]

	// Get the existing network
	_, dbInfo, err := d.cluster.NetworkGet(name)
	if err != nil {
		return SmartError(err)
	}

	// Validate the ETag
	etag := []interface{}{dbInfo.Name, dbInfo.Managed, dbInfo.Type, dbInfo.Description, dbInfo.Config}

	err = util.EtagCheck(r, etag)
	if err != nil {
		return PreconditionFailed(err)
	}

	req := api.NetworkPut{}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return BadRequest(err)
	}

	return doNetworkUpdate(d, name, dbInfo.Config, req)
}

func networkPatch(d *Daemon, r *http.Request) Response {
	name := mux.Vars(r)["name"]

	// Get the existing network
	_, dbInfo, err := d.cluster.NetworkGet(name)
	if dbInfo != nil {
		return SmartError(err)
	}

	// Validate the ETag
	etag := []interface{}{dbInfo.Name, dbInfo.Managed, dbInfo.Type, dbInfo.Description, dbInfo.Config}

	err = util.EtagCheck(r, etag)
	if err != nil {
		return PreconditionFailed(err)
	}

	req := api.NetworkPut{}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return BadRequest(err)
	}

	// Config stacking
	if req.Config == nil {
		req.Config = map[string]string{}
	}

	for k, v := range dbInfo.Config {
		_, ok := req.Config[k]
		if !ok {
			req.Config[k] = v
		}
	}

	return doNetworkUpdate(d, name, dbInfo.Config, req)
}

func doNetworkUpdate(d *Daemon, name string, oldConfig map[string]string, req api.NetworkPut) Response {
	// Validate the configuration
	err := networkValidateConfig(name, req.Config)
	if err != nil {
		return BadRequest(err)
	}

	// When switching to a fan bridge, auto-detect the underlay
	if req.Config["bridge.mode"] == "fan" {
		if req.Config["fan.underlay_subnet"] == "" {
			req.Config["fan.underlay_subnet"] = "auto"
		}
	}

	// Load the network
	n, err := networkLoadByName(d.State(), name)
	if err != nil {
		return NotFound
	}

	err = n.Update(req)
	if err != nil {
		return SmartError(err)
	}

	return EmptySyncResponse
}

var networkCmd = Command{name: "networks/{name}", get: networkGet, delete: networkDelete, post: networkPost, put: networkPut, patch: networkPatch}

func networkLeasesGet(d *Daemon, r *http.Request) Response {
	name := mux.Vars(r)["name"]
	leaseFile := shared.VarPath("networks", name, "dnsmasq.leases")

	// Try to get the network
	n, err := doNetworkGet(d, name)
	if err != nil {
		return SmartError(err)
	}

	// Validate that we do have leases for it
	if !n.Managed || n.Type != "bridge" {
		return NotFound
	}

	if !shared.PathExists(leaseFile) {
		return BadRequest(fmt.Errorf("No lease file for network"))
	}

	// Read all the leases
	content, err := ioutil.ReadFile(leaseFile)
	if err != nil {
		return SmartError(err)
	}

	leases := []api.NetworkLease{}

	// Get all the containers
	containers, err := d.cluster.ContainersList(db.CTypeRegular)
	if err != nil {
		return SmartError(err)
	}

	// Get static leases
	for _, cName := range containers {
		// Load the container
		c, err := containerLoadByName(d.State(), cName)
		if err != nil {
			continue
		}

		// Go through all its devices (including profiles
		for k, d := range c.ExpandedDevices() {
			// Skip uninteresting entries
			if d["type"] != "nic" || d["nictype"] != "bridged" || d["parent"] != name {
				continue
			}

			// Fill in the hwaddr from volatile
			d, err = c.(*containerLXC).fillNetworkDevice(k, d)
			if err != nil {
				continue
			}

			// Add the lease
			if d["ipv4.address"] != "" {
				leases = append(leases, api.NetworkLease{
					Hostname: cName,
					Address:  d["ipv4.address"],
					Hwaddr:   d["hwaddr"],
					Type:     "static",
				})
			}

			if d["ipv6.address"] != "" {
				leases = append(leases, api.NetworkLease{
					Hostname: cName,
					Address:  d["ipv6.address"],
					Hwaddr:   d["hwaddr"],
					Type:     "static",
				})
			}
		}
	}

	// Get dynamic leases
	for _, lease := range strings.Split(string(content), "\n") {
		fields := strings.Fields(lease)
		if len(fields) >= 5 {
			// Parse the MAC
			mac := networkGetMacSlice(fields[1])
			macStr := strings.Join(mac, ":")

			if len(macStr) < 17 && fields[4] != "" {
				macStr = fields[4][len(fields[4])-17:]
			}

			// Look for an existing static entry
			found := false
			for _, entry := range leases {
				if entry.Hwaddr == macStr && entry.Address == fields[2] {
					found = true
					break
				}
			}

			if found {
				continue
			}

			// Add the lease to the list
			leases = append(leases, api.NetworkLease{
				Hostname: fields[3],
				Address:  fields[2],
				Hwaddr:   macStr,
				Type:     "dynamic",
			})
		}
	}

	return SyncResponse(true, leases)
}

var networkLeasesCmd = Command{name: "networks/{name}/leases", get: networkLeasesGet}

// The network structs and functions
func networkLoadByName(s *state.State, name string) (*network, error) {
	id, dbInfo, err := s.Cluster.NetworkGet(name)
	if err != nil {
		return nil, err
	}

	n := network{state: s, id: id, name: name, description: dbInfo.Description, config: dbInfo.Config}

	return &n, nil
}

func networkStartup(s *state.State) error {
	// Get a list of managed networks
	networks, err := s.Cluster.NetworksNotPending()
	if err != nil {
		return err
	}

	// Bring them all up
	for _, name := range networks {
		n, err := networkLoadByName(s, name)
		if err != nil {
			return err
		}

		err = n.Start()
		if err != nil {
			// Don't cause LXD to fail to start entirely on network bring up failure
			logger.Error("Failed to bring up network", log.Ctx{"err": err, "name": name})
		}
	}

	return nil
}

func networkShutdown(s *state.State) error {
	// Get a list of managed networks
	networks, err := s.Cluster.Networks()
	if err != nil {
		return err
	}

	// Bring them all up
	for _, name := range networks {
		n, err := networkLoadByName(s, name)
		if err != nil {
			return err
		}

		if !n.IsRunning() {
			continue
		}

		err = n.Stop()
		if err != nil {
			logger.Error("Failed to bring down network", log.Ctx{"err": err, "name": name})
		}
	}

	return nil
}

type network struct {
	// Properties
	db          *db.Node
	state       *state.State
	id          int64
	name        string
	description string

	// config
	config map[string]string
}

func (n *network) Config() map[string]string {
	return n.config
}

func (n *network) IsRunning() bool {
	return shared.PathExists(fmt.Sprintf("/sys/class/net/%s", n.name))
}

func (n *network) IsUsed() bool {
	// Look for containers using the interface
	cts, err := n.state.Cluster.ContainersList(db.CTypeRegular)
	if err != nil {
		return true
	}

	for _, ct := range cts {
		c, err := containerLoadByName(n.state, ct)
		if err != nil {
			return true
		}

		if networkIsInUse(c, n.name) {
			return true
		}
	}

	return false
}

func (n *network) Delete(withDatabase bool) error {
	// Bring the network down
	if n.IsRunning() {
		err := n.Stop()
		if err != nil {
			return err
		}
	}

	// If withDatabase is false, this is a cluster notification, and we
	// don't want to perform any database work.
	if !withDatabase {
		return nil
	}

	// Remove the network from the database
	err := n.state.Cluster.NetworkDelete(n.name)
	if err != nil {
		return err
	}

	return nil
}

func (n *network) Rename(name string) error {
	// Sanity checks
	if n.IsUsed() {
		return fmt.Errorf("The network is currently in use")
	}

	// Bring the network down
	if n.IsRunning() {
		err := n.Stop()
		if err != nil {
			return err
		}
	}

	// Rename directory
	if shared.PathExists(shared.VarPath("networks", name)) {
		os.RemoveAll(shared.VarPath("networks", name))
	}

	if shared.PathExists(shared.VarPath("networks", n.name)) {
		err := os.Rename(shared.VarPath("networks", n.name), shared.VarPath("networks", name))
		if err != nil {
			return err
		}
	}

	// Rename the database entry
	err := n.state.Cluster.NetworkRename(n.name, name)
	if err != nil {
		return err
	}
	n.name = name

	// Bring the network up
	err = n.Start()
	if err != nil {
		return err
	}

	return nil
}

func (n *network) Start() error {
	// If we are in mock mode, just no-op.
	if n.state.OS.MockMode {
		return nil
	}

	// Create directory
	if !shared.PathExists(shared.VarPath("networks", n.name)) {
		err := os.MkdirAll(shared.VarPath("networks", n.name), 0711)
		if err != nil {
			return err
		}
	}

	// Create the bridge interface
	if !n.IsRunning() {
		if n.config["bridge.driver"] == "openvswitch" {
			_, err := shared.RunCommand("ovs-vsctl", "add-br", n.name)
			if err != nil {
				return err
			}
		} else {
			_, err := shared.RunCommand("ip", "link", "add", "dev", n.name, "type", "bridge")
			if err != nil {
				return err
			}
		}
	}

	// Get a list of tunnels
	tunnels := networkGetTunnels(n.config)

	// IPv6 bridge configuration
	if !shared.StringInSlice(n.config["ipv6.address"], []string{"", "none"}) {
		err := networkSysctl(fmt.Sprintf("ipv6/conf/%s/autoconf", n.name), "0")
		if err != nil {
			return err
		}

		err = networkSysctl(fmt.Sprintf("ipv6/conf/%s/accept_dad", n.name), "0")
		if err != nil {
			return err
		}
	}

	// Get a list of interfaces
	ifaces, err := net.Interfaces()
	if err != nil {
		return err
	}

	// Cleanup any existing tunnel device
	for _, iface := range ifaces {
		if strings.HasPrefix(iface.Name, fmt.Sprintf("%s-", n.name)) {
			_, err = shared.RunCommand("ip", "link", "del", "dev", iface.Name)
			if err != nil {
				return err
			}
		}
	}

	// Set the MTU
	mtu := ""
	if n.config["bridge.mtu"] != "" {
		mtu = n.config["bridge.mtu"]
	} else if len(tunnels) > 0 {
		mtu = "1400"
	} else if n.config["bridge.mode"] == "fan" {
		if n.config["fan.type"] == "ipip" {
			mtu = "1480"
		} else {
			mtu = "1450"
		}
	}

	// Attempt to add a dummy device to the bridge to force the MTU
	if mtu != "" && n.config["bridge.driver"] != "openvswitch" {
		_, err = shared.RunCommand("ip", "link", "add", "dev", fmt.Sprintf("%s-mtu", n.name), "mtu", mtu, "type", "dummy")
		if err == nil {
			networkAttachInterface(n.name, fmt.Sprintf("%s-mtu", n.name))
		}
	}

	// Now, set a default MTU
	if mtu == "" {
		mtu = "1500"
	}

	_, err = shared.RunCommand("ip", "link", "set", "dev", n.name, "mtu", mtu)
	if err != nil {
		return err
	}

	// Bring it up
	_, err = shared.RunCommand("ip", "link", "set", "dev", n.name, "up")
	if err != nil {
		return err
	}

	// Add any listed existing external interface
	if n.config["bridge.external_interfaces"] != "" {
		for _, entry := range strings.Split(n.config["bridge.external_interfaces"], ",") {
			entry = strings.TrimSpace(entry)
			iface, err := net.InterfaceByName(entry)
			if err != nil {
				continue
			}

			unused := true
			addrs, err := iface.Addrs()
			if err == nil {
				for _, addr := range addrs {
					ip, _, err := net.ParseCIDR(addr.String())
					if ip != nil && err == nil && ip.IsGlobalUnicast() {
						unused = false
						break
					}
				}
			}

			if !unused {
				return fmt.Errorf("Only unconfigured network interfaces can be bridged")
			}

			err = networkAttachInterface(n.name, entry)
			if err != nil {
				return err
			}
		}
	}

	// Remove any existing IPv4 iptables rules
	err = networkIptablesClear("ipv4", n.name, "")
	if err != nil {
		return err
	}

	err = networkIptablesClear("ipv4", n.name, "mangle")
	if err != nil {
		return err
	}

	err = networkIptablesClear("ipv4", n.name, "nat")
	if err != nil {
		return err
	}

	// Flush all IPv4 addresses and routes
	_, err = shared.RunCommand("ip", "-4", "addr", "flush", "dev", n.name, "scope", "global")
	if err != nil {
		return err
	}

	_, err = shared.RunCommand("ip", "-4", "route", "flush", "dev", n.name, "proto", "static")
	if err != nil {
		return err
	}

	// Configure IPv4 firewall (includes fan)
	if n.config["bridge.mode"] == "fan" || !shared.StringInSlice(n.config["ipv4.address"], []string{"", "none"}) {
		if (n.config["ipv4.dhcp"] == "" || shared.IsTrue(n.config["ipv4.dhcp"])) && (n.config["ipv4.firewall"] == "" || shared.IsTrue(n.config["ipv4.firewall"])) {
			// Setup basic iptables overrides for DHCP/DNS
			rules := [][]string{
				{"ipv4", n.name, "", "INPUT", "-i", n.name, "-p", "udp", "--dport", "67", "-j", "ACCEPT"},
				{"ipv4", n.name, "", "INPUT", "-i", n.name, "-p", "udp", "--dport", "53", "-j", "ACCEPT"},
				{"ipv4", n.name, "", "INPUT", "-i", n.name, "-p", "tcp", "--dport", "53", "-j", "ACCEPT"},
				{"ipv4", n.name, "", "OUTPUT", "-o", n.name, "-p", "udp", "--sport", "67", "-j", "ACCEPT"},
				{"ipv4", n.name, "", "OUTPUT", "-o", n.name, "-p", "udp", "--sport", "53", "-j", "ACCEPT"},
				{"ipv4", n.name, "", "OUTPUT", "-o", n.name, "-p", "tcp", "--sport", "53", "-j", "ACCEPT"}}

			for _, rule := range rules {
				err = networkIptablesPrepend(rule[0], rule[1], rule[2], rule[3], rule[4:]...)
				if err != nil {
					return err
				}
			}
		}

		// Attempt a workaround for broken DHCP clients
		networkIptablesPrepend("ipv4", n.name, "mangle", "POSTROUTING", "-o", n.name, "-p", "udp", "--dport", "68", "-j", "CHECKSUM", "--checksum-fill")

		// Allow forwarding
		if n.config["bridge.mode"] == "fan" || n.config["ipv4.routing"] == "" || shared.IsTrue(n.config["ipv4.routing"]) {
			err = networkSysctl("ipv4/ip_forward", "1")
			if err != nil {
				return err
			}

			if n.config["ipv4.firewall"] == "" || shared.IsTrue(n.config["ipv4.firewall"]) {
				err = networkIptablesPrepend("ipv4", n.name, "", "FORWARD", "-i", n.name, "-j", "ACCEPT")
				if err != nil {
					return err
				}

				err = networkIptablesPrepend("ipv4", n.name, "", "FORWARD", "-o", n.name, "-j", "ACCEPT")
				if err != nil {
					return err
				}
			}
		} else {
			if n.config["ipv4.firewall"] == "" || shared.IsTrue(n.config["ipv4.firewall"]) {
				err = networkIptablesPrepend("ipv4", n.name, "", "FORWARD", "-i", n.name, "-j", "REJECT")
				if err != nil {
					return err
				}

				err = networkIptablesPrepend("ipv4", n.name, "", "FORWARD", "-o", n.name, "-j", "REJECT")
				if err != nil {
					return err
				}
			}
		}
	}

	// Start building the dnsmasq command line
	dnsmasqCmd := []string{"dnsmasq", "--strict-order", "--bind-interfaces",
		fmt.Sprintf("--pid-file=%s", shared.VarPath("networks", n.name, "dnsmasq.pid")),
		"--except-interface=lo",
		fmt.Sprintf("--interface=%s", n.name)}

	if !debug {
		// --quiet options are only supported on >2.67
		minVer, _ := version.NewDottedVersion("2.67")

		v, err := networkGetDnsmasqVersion()
		if err == nil && v.Compare(minVer) > 0 {
			dnsmasqCmd = append(dnsmasqCmd, []string{"--quiet-dhcp", "--quiet-dhcp6", "--quiet-ra"}...)
		}
	}

	// Configure IPv4
	if !shared.StringInSlice(n.config["ipv4.address"], []string{"", "none"}) {
		// Parse the subnet
		ip, subnet, err := net.ParseCIDR(n.config["ipv4.address"])
		if err != nil {
			return err
		}

		// Update the dnsmasq config
		dnsmasqCmd = append(dnsmasqCmd, fmt.Sprintf("--listen-address=%s", ip.String()))
		if n.config["ipv4.dhcp"] == "" || shared.IsTrue(n.config["ipv4.dhcp"]) {
			if !shared.StringInSlice("--dhcp-no-override", dnsmasqCmd) {
				dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-no-override", "--dhcp-authoritative", fmt.Sprintf("--dhcp-leasefile=%s", shared.VarPath("networks", n.name, "dnsmasq.leases")), fmt.Sprintf("--dhcp-hostsfile=%s", shared.VarPath("networks", n.name, "dnsmasq.hosts"))}...)
			}

			if n.config["ipv4.dhcp.gateway"] != "" {
				dnsmasqCmd = append(dnsmasqCmd, fmt.Sprintf("--dhcp-option=3,%s", n.config["ipv4.dhcp.gateway"]))
			}

			expiry := "1h"
			if n.config["ipv4.dhcp.expiry"] != "" {
				expiry = n.config["ipv4.dhcp.expiry"]
			}

			if n.config["ipv4.dhcp.ranges"] != "" {
				for _, dhcpRange := range strings.Split(n.config["ipv4.dhcp.ranges"], ",") {
					dhcpRange = strings.TrimSpace(dhcpRange)
					dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-range", fmt.Sprintf("%s,%s", strings.Replace(dhcpRange, "-", ",", -1), expiry)}...)
				}
			} else {
				dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-range", fmt.Sprintf("%s,%s,%s", networkGetIP(subnet, 2).String(), networkGetIP(subnet, -2).String(), expiry)}...)
			}
		}

		// Add the address
		_, err = shared.RunCommand("ip", "-4", "addr", "add", "dev", n.name, n.config["ipv4.address"])
		if err != nil {
			return err
		}

		// Configure NAT
		if shared.IsTrue(n.config["ipv4.nat"]) {
			err = networkIptablesPrepend("ipv4", n.name, "nat", "POSTROUTING", "-s", subnet.String(), "!", "-d", subnet.String(), "-j", "MASQUERADE")
			if err != nil {
				return err
			}
		}

		// Add additional routes
		if n.config["ipv4.routes"] != "" {
			for _, route := range strings.Split(n.config["ipv4.routes"], ",") {
				route = strings.TrimSpace(route)
				_, err = shared.RunCommand("ip", "-4", "route", "add", "dev", n.name, route, "proto", "static")
				if err != nil {
					return err
				}
			}
		}
	}

	// Remove any existing IPv6 iptables rules
	err = networkIptablesClear("ipv6", n.name, "")
	if err != nil {
		return err
	}

	err = networkIptablesClear("ipv6", n.name, "nat")
	if err != nil {
		return err
	}

	// Flush all IPv6 addresses and routes
	_, err = shared.RunCommand("ip", "-6", "addr", "flush", "dev", n.name, "scope", "global")
	if err != nil {
		return err
	}

	_, err = shared.RunCommand("ip", "-6", "route", "flush", "dev", n.name, "proto", "static")
	if err != nil {
		return err
	}

	// Configure IPv6
	if !shared.StringInSlice(n.config["ipv6.address"], []string{"", "none"}) {
		// Enable IPv6 for the subnet
		err := networkSysctl(fmt.Sprintf("ipv6/conf/%s/disable_ipv6", n.name), "0")
		if err != nil {
			return err
		}

		// Parse the subnet
		ip, subnet, err := net.ParseCIDR(n.config["ipv6.address"])
		if err != nil {
			return err
		}

		// Update the dnsmasq config
		dnsmasqCmd = append(dnsmasqCmd, []string{fmt.Sprintf("--listen-address=%s", ip.String()), "--enable-ra"}...)
		if (n.config["ipv6.dhcp"] == "" || shared.IsTrue(n.config["ipv6.dhcp"])) && (n.config["ipv6.firewall"] == "" || shared.IsTrue(n.config["ipv6.firewall"])) {
			// Setup basic iptables overrides for DHCP/DNS
			rules := [][]string{
				{"ipv6", n.name, "", "INPUT", "-i", n.name, "-p", "udp", "--dport", "546", "-j", "ACCEPT"},
				{"ipv6", n.name, "", "INPUT", "-i", n.name, "-p", "udp", "--dport", "53", "-j", "ACCEPT"},
				{"ipv6", n.name, "", "INPUT", "-i", n.name, "-p", "tcp", "--dport", "53", "-j", "ACCEPT"},
				{"ipv6", n.name, "", "OUTPUT", "-o", n.name, "-p", "udp", "--sport", "546", "-j", "ACCEPT"},
				{"ipv6", n.name, "", "OUTPUT", "-o", n.name, "-p", "udp", "--sport", "53", "-j", "ACCEPT"},
				{"ipv6", n.name, "", "OUTPUT", "-o", n.name, "-p", "tcp", "--sport", "53", "-j", "ACCEPT"}}

			for _, rule := range rules {
				err = networkIptablesPrepend(rule[0], rule[1], rule[2], rule[3], rule[4:]...)
				if err != nil {
					return err
				}
			}

			// Build DHCP configuration
			if !shared.StringInSlice("--dhcp-no-override", dnsmasqCmd) {
				dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-no-override", "--dhcp-authoritative", fmt.Sprintf("--dhcp-leasefile=%s", shared.VarPath("networks", n.name, "dnsmasq.leases")), fmt.Sprintf("--dhcp-hostsfile=%s", shared.VarPath("networks", n.name, "dnsmasq.hosts"))}...)
			}

			expiry := "1h"
			if n.config["ipv6.dhcp.expiry"] != "" {
				expiry = n.config["ipv6.dhcp.expiry"]
			}

			if shared.IsTrue(n.config["ipv6.dhcp.stateful"]) {
				if n.config["ipv6.dhcp.ranges"] != "" {
					for _, dhcpRange := range strings.Split(n.config["ipv6.dhcp.ranges"], ",") {
						dhcpRange = strings.TrimSpace(dhcpRange)
						dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-range", fmt.Sprintf("%s,%s", strings.Replace(dhcpRange, "-", ",", -1), expiry)}...)
					}
				} else {
					dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-range", fmt.Sprintf("%s,%s,%s", networkGetIP(subnet, 2), networkGetIP(subnet, -1), expiry)}...)
				}
			} else {
				dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-range", fmt.Sprintf("::,constructor:%s,ra-stateless,ra-names", n.name)}...)
			}
		} else {
			dnsmasqCmd = append(dnsmasqCmd, []string{"--dhcp-range", fmt.Sprintf("::,constructor:%s,ra-only", n.name)}...)
		}

		// Allow forwarding
		if n.config["ipv6.routing"] == "" || shared.IsTrue(n.config["ipv6.routing"]) {
			// Get a list of proc entries
			entries, err := ioutil.ReadDir("/proc/sys/net/ipv6/conf/")
			if err != nil {
				return err
			}

			// First set accept_ra to 2 for everything
			for _, entry := range entries {
				content, err := ioutil.ReadFile(fmt.Sprintf("/proc/sys/net/ipv6/conf/%s/accept_ra", entry.Name()))
				if err == nil && string(content) != "1\n" {
					continue
				}

				err = networkSysctl(fmt.Sprintf("ipv6/conf/%s/accept_ra", entry.Name()), "2")
				if err != nil && !os.IsNotExist(err) {
					return err
				}
			}

			// Then set forwarding for all of them
			for _, entry := range entries {
				err = networkSysctl(fmt.Sprintf("ipv6/conf/%s/forwarding", entry.Name()), "1")
				if err != nil && !os.IsNotExist(err) {
					return err
				}
			}

			if n.config["ipv6.firewall"] == "" || shared.IsTrue(n.config["ipv6.firewall"]) {
				err = networkIptablesPrepend("ipv6", n.name, "", "FORWARD", "-i", n.name, "-j", "ACCEPT")
				if err != nil {
					return err
				}

				err = networkIptablesPrepend("ipv6", n.name, "", "FORWARD", "-o", n.name, "-j", "ACCEPT")
				if err != nil {
					return err
				}
			}
		} else {
			if n.config["ipv6.firewall"] == "" || shared.IsTrue(n.config["ipv6.firewall"]) {
				err = networkIptablesPrepend("ipv6", n.name, "", "FORWARD", "-i", n.name, "-j", "REJECT")
				if err != nil {
					return err
				}

				err = networkIptablesPrepend("ipv6", n.name, "", "FORWARD", "-o", n.name, "-j", "REJECT")
				if err != nil {
					return err
				}
			}
		}

		// Add the address
		_, err = shared.RunCommand("ip", "-6", "addr", "add", "dev", n.name, n.config["ipv6.address"])
		if err != nil {
			return err
		}

		// Configure NAT
		if shared.IsTrue(n.config["ipv6.nat"]) {
			err = networkIptablesPrepend("ipv6", n.name, "nat", "POSTROUTING", "-s", subnet.String(), "!", "-d", subnet.String(), "-j", "MASQUERADE")
			if err != nil {
				return err
			}
		}

		// Add additional routes
		if n.config["ipv6.routes"] != "" {
			for _, route := range strings.Split(n.config["ipv6.routes"], ",") {
				route = strings.TrimSpace(route)
				_, err = shared.RunCommand("ip", "-6", "route", "add", "dev", n.name, route, "proto", "static")
				if err != nil {
					return err
				}
			}
		}
	}

	// Configure the fan
	if n.config["bridge.mode"] == "fan" {
		tunName := fmt.Sprintf("%s-fan", n.name)

		// Parse the underlay
		underlay := n.config["fan.underlay_subnet"]
		_, underlaySubnet, err := net.ParseCIDR(underlay)
		if err != nil {
			return nil
		}

		// Parse the overlay
		overlay := n.config["fan.overlay_subnet"]
		if overlay == "" {
			overlay = "240.0.0.0/8"
		}

		_, overlaySubnet, err := net.ParseCIDR(overlay)
		if err != nil {
			return err
		}

		// Get the address
		fanAddress, devName, devAddr, err := networkFanAddress(underlaySubnet, overlaySubnet)
		if err != nil {
			return err
		}

		addr := strings.Split(fanAddress, "/")
		if n.config["fan.type"] == "ipip" {
			fanAddress = fmt.Sprintf("%s/24", addr[0])
		}

		// Parse the host subnet
		_, hostSubnet, err := net.ParseCIDR(fmt.Sprintf("%s/24", addr[0]))
		if err != nil {
			return err
		}

		// Add the address
		_, err = shared.RunCommand("ip", "-4", "addr", "add", "dev", n.name, fanAddress)
		if err != nil {
			return err
		}

		// Update the dnsmasq config
		dnsmasqCmd = append(dnsmasqCmd, []string{
			fmt.Sprintf("--listen-address=%s", addr[0]),
			"--dhcp-no-override", "--dhcp-authoritative",
			fmt.Sprintf("--dhcp-leasefile=%s", shared.VarPath("networks", n.name, "dnsmasq.leases")),
			fmt.Sprintf("--dhcp-hostsfile=%s", shared.VarPath("networks", n.name, "dnsmasq.hosts")),
			"--dhcp-range", fmt.Sprintf("%s,%s", networkGetIP(hostSubnet, 2).String(), networkGetIP(hostSubnet, -2).String())}...)

		// Setup the tunnel
		if n.config["fan.type"] == "ipip" {
			_, err = shared.RunCommand("ip", "-4", "route", "flush", "dev", "tunl0")
			if err != nil {
				return err
			}

			_, err = shared.RunCommand("ip", "link", "set", "dev", "tunl0", "up")
			if err != nil {
				return err
			}

			// Fails if the map is already set
			shared.RunCommand("ip", "link", "change", "dev", "tunl0", "type", "ipip", "fan-map", fmt.Sprintf("%s:%s", overlay, underlay))

			_, err = shared.RunCommand("ip", "route", "add", overlay, "dev", "tunl0", "src", addr[0])
			if err != nil {
				return err
			}
		} else {
			vxlanID := fmt.Sprintf("%d", binary.BigEndian.Uint32(overlaySubnet.IP.To4())>>8)

			_, err = shared.RunCommand("ip", "link", "add", tunName, "type", "vxlan", "id", vxlanID, "dev", devName, "dstport", "0", "local", devAddr, "fan-map", fmt.Sprintf("%s:%s", overlay, underlay))
			if err != nil {
				return err
			}

			err = networkAttachInterface(n.name, tunName)
			if err != nil {
				return err
			}

			_, err = shared.RunCommand("ip", "link", "set", "dev", tunName, "mtu", mtu, "up")
			if err != nil {
				return err
			}

			_, err = shared.RunCommand("ip", "link", "set", "dev", n.name, "up")
			if err != nil {
				return err
			}
		}

		// Configure NAT
		err = networkIptablesPrepend("ipv4", n.name, "nat", "POSTROUTING", "-s", underlaySubnet.String(), "!", "-d", underlaySubnet.String(), "-j", "MASQUERADE")
		if err != nil {
			return err
		}
	}

	// Configure tunnels
	for _, tunnel := range tunnels {
		getConfig := func(key string) string {
			return n.config[fmt.Sprintf("tunnel.%s.%s", tunnel, key)]
		}

		tunProtocol := getConfig("protocol")
		tunLocal := getConfig("local")
		tunRemote := getConfig("remote")
		tunName := fmt.Sprintf("%s-%s", n.name, tunnel)

		// Configure the tunnel
		cmd := []string{"ip", "link", "add", "dev", tunName}
		if tunProtocol == "gre" {
			// Skip partial configs
			if tunProtocol == "" || tunLocal == "" || tunRemote == "" {
				continue
			}

			cmd = append(cmd, []string{"type", "gretap", "local", tunLocal, "remote", tunRemote}...)
		} else if tunProtocol == "vxlan" {
			tunGroup := getConfig("group")
			tunInterface := getConfig("interface")

			// Skip partial configs
			if tunProtocol == "" {
				continue
			}

			cmd = append(cmd, []string{"type", "vxlan"}...)

			if tunLocal != "" && tunRemote != "" {
				cmd = append(cmd, []string{"local", tunLocal, "remote", tunRemote}...)
			} else {
				if tunGroup == "" {
					tunGroup = "239.0.0.1"
				}

				devName := tunInterface
				if devName == "" {
					_, devName, err = networkDefaultGatewaySubnetV4()
					if err != nil {
						return err
					}
				}

				cmd = append(cmd, []string{"group", tunGroup, "dev", devName}...)
			}

			tunPort := getConfig("port")
			if tunPort == "" {
				tunPort = "0"
			}
			cmd = append(cmd, []string{"dstport", tunPort}...)

			tunId := getConfig("id")
			if tunId == "" {
				tunId = "1"
			}
			cmd = append(cmd, []string{"id", tunId}...)
		}

		// Create the interface
		_, err = shared.RunCommand(cmd[0], cmd[1:]...)
		if err != nil {
			return err
		}

		// Bridge it and bring up
		err = networkAttachInterface(n.name, tunName)
		if err != nil {
			return err
		}

		_, err = shared.RunCommand("ip", "link", "set", "dev", tunName, "mtu", mtu, "up")
		if err != nil {
			return err
		}

		_, err = shared.RunCommand("ip", "link", "set", "dev", n.name, "up")
		if err != nil {
			return err
		}
	}

	// Kill any existing dnsmasq daemon for this network
	err = networkKillDnsmasq(n.name, false)
	if err != nil {
		return err
	}

	// Configure dnsmasq
	if n.config["bridge.mode"] == "fan" || !shared.StringInSlice(n.config["ipv4.address"], []string{"", "none"}) || !shared.StringInSlice(n.config["ipv6.address"], []string{"", "none"}) {
		// Setup the dnsmasq domain
		dnsDomain := n.config["dns.domain"]
		if dnsDomain == "" {
			dnsDomain = "lxd"
		}

		if n.config["dns.mode"] != "none" {
			dnsmasqCmd = append(dnsmasqCmd, []string{"-s", dnsDomain, "-S", fmt.Sprintf("/%s/", dnsDomain)}...)
		}

		// Create a config file to contain additional config (and to prevent dnsmasq from reading /etc/dnsmasq.conf)
		err = ioutil.WriteFile(shared.VarPath("networks", n.name, "dnsmasq.raw"), []byte(fmt.Sprintf("%s\n", n.config["raw.dnsmasq"])), 0644)
		if err != nil {
			return err
		}
		dnsmasqCmd = append(dnsmasqCmd, fmt.Sprintf("--conf-file=%s", shared.VarPath("networks", n.name, "dnsmasq.raw")))

		// Attempt to drop privileges
		for _, user := range []string{"lxd", "nobody"} {
			_, err := shared.UserId(user)
			if err != nil {
				continue
			}

			dnsmasqCmd = append(dnsmasqCmd, []string{"-u", user}...)
			break
		}

		// Create DHCP hosts directory
		if !shared.PathExists(shared.VarPath("networks", n.name, "dnsmasq.hosts")) {
			err = os.MkdirAll(shared.VarPath("networks", n.name, "dnsmasq.hosts"), 0755)
			if err != nil {
				return err
			}
		}

		// Check for dnsmasq
		_, err := exec.LookPath("dnsmasq")
		if err != nil {
			return fmt.Errorf("dnsmasq is required for LXD managed bridges.")
		}

		// Start dnsmasq (occasionally races, try a few times)
		output, err := shared.TryRunCommand(dnsmasqCmd[0], dnsmasqCmd[1:]...)
		if err != nil {
			return fmt.Errorf("Failed to run: %s: %s", strings.Join(dnsmasqCmd, " "), strings.TrimSpace(output))
		}

		// Update the static leases
		err = networkUpdateStatic(n.state, n.name)
		if err != nil {
			return err
		}
	}

	return nil
}

func (n *network) Stop() error {
	if !n.IsRunning() {
		return fmt.Errorf("The network is already stopped")
	}

	// Destroy the bridge interface
	if n.config["bridge.driver"] == "openvswitch" {
		_, err := shared.RunCommand("ovs-vsctl", "del-br", n.name)
		if err != nil {
			return err
		}
	} else {
		_, err := shared.RunCommand("ip", "link", "del", "dev", n.name)
		if err != nil {
			return err
		}
	}

	// Cleanup iptables
	err := networkIptablesClear("ipv4", n.name, "")
	if err != nil {
		return err
	}

	err = networkIptablesClear("ipv4", n.name, "mangle")
	if err != nil {
		return err
	}

	err = networkIptablesClear("ipv4", n.name, "nat")
	if err != nil {
		return err
	}

	err = networkIptablesClear("ipv6", n.name, "")
	if err != nil {
		return err
	}

	err = networkIptablesClear("ipv6", n.name, "nat")
	if err != nil {
		return err
	}

	// Kill any existing dnsmasq daemon for this network
	err = networkKillDnsmasq(n.name, false)
	if err != nil {
		return err
	}

	// Get a list of interfaces
	ifaces, err := net.Interfaces()
	if err != nil {
		return err
	}

	// Cleanup any existing tunnel device
	for _, iface := range ifaces {
		if strings.HasPrefix(iface.Name, fmt.Sprintf("%s-", n.name)) {
			_, err = shared.RunCommand("ip", "link", "del", "dev", iface.Name)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func (n *network) Update(newNetwork api.NetworkPut) error {
	err := networkFillAuto(newNetwork.Config)
	if err != nil {
		return err
	}
	newConfig := newNetwork.Config

	// Backup the current state
	oldConfig := map[string]string{}
	oldDescription := n.description
	err = shared.DeepCopy(&n.config, &oldConfig)
	if err != nil {
		return err
	}

	// Define a function which reverts everything.  Defer this function
	// so that it doesn't need to be explicitly called in every failing
	// return path.  Track whether or not we want to undo the changes
	// using a closure.
	undoChanges := true
	defer func() {
		if undoChanges {
			n.config = oldConfig
			n.description = oldDescription
		}
	}()

	// Diff the configurations
	changedConfig := []string{}
	userOnly := true
	for key := range oldConfig {
		if oldConfig[key] != newConfig[key] {
			if !strings.HasPrefix(key, "user.") {
				userOnly = false
			}

			if !shared.StringInSlice(key, changedConfig) {
				changedConfig = append(changedConfig, key)
			}
		}
	}

	for key := range newConfig {
		if oldConfig[key] != newConfig[key] {
			if !strings.HasPrefix(key, "user.") {
				userOnly = false
			}

			if !shared.StringInSlice(key, changedConfig) {
				changedConfig = append(changedConfig, key)
			}
		}
	}

	// Skip on no change
	if len(changedConfig) == 0 && newNetwork.Description == n.description {
		return nil
	}

	// Update the network
	if !userOnly {
		if shared.StringInSlice("bridge.driver", changedConfig) && n.IsRunning() {
			err = n.Stop()
			if err != nil {
				return err
			}
		}

		if shared.StringInSlice("bridge.external_interfaces", changedConfig) && n.IsRunning() {
			devices := []string{}
			for _, dev := range strings.Split(newConfig["bridge.external_interfaces"], ",") {
				dev = strings.TrimSpace(dev)
				devices = append(devices, dev)
			}

			for _, dev := range strings.Split(oldConfig["bridge.external_interfaces"], ",") {
				dev = strings.TrimSpace(dev)
				if dev == "" {
					continue
				}

				if !shared.StringInSlice(dev, devices) && shared.PathExists(fmt.Sprintf("/sys/class/net/%s", dev)) {
					err = networkDetachInterface(n.name, dev)
					if err != nil {
						return err
					}
				}
			}
		}
	}

	// Apply changes
	n.config = newConfig
	n.description = newNetwork.Description

	// Update the database
	err = n.state.Cluster.NetworkUpdate(n.name, n.description, n.config)
	if err != nil {
		return err
	}

	// Restart the network
	if !userOnly {
		err = n.Start()
		if err != nil {
			return err
		}
	}

	// Success, update the closure to mark that the changes should be kept.
	undoChanges = false

	return nil
}


text:
from custom.opm.constants import InvalidRow
from custom.opm.tests import OPMCaseReportTestBase, OPMCase, MockCaseRow

class TestInvalidDates(OPMCaseReportTestBase):

    def testBadEdd(self):
        case = OPMCase(
            forms=[],
            edd='this is not a date',
        )
        self.assertRaises(InvalidRow, MockCaseRow, case, self.report)

    def testBadDod(self):
        case = OPMCase(
            forms=[],
            dod='this is not a date',
        )
        self.assertRaises(InvalidRow, MockCaseRow, case, self.report)

redpajama_set_name: RedPajamaGithub


text:
require 'pathname'
require 'envyable'
require 'yaml'

namespace :envyable do
  desc 'Export the .env file to the remote servers'
  task :export do
    on roles fetch(:envyable_roles) do
      env = {}.tap do |env|
        Envyable::Loader.new(fetch(:envyable_path), env).load(fetch(:stage).to_s)
      end

      upload! StringIO.new(YAML.dump(env)), "#{release_path}/#{fetch(:envyable_path)}"
      if fetch(:envyable_env_path)
        execute(:mkdir, "-p", Pathname.new(fetch(:envyable_env_path)).dirname)
        upload! StringIO.new(env.map { |k, v| "#{k}=#{v}" }.join("\n")), fetch(:envyable_env_path)
      end
    end
  end

  after 'deploy:updated', 'envyable:export'
end

namespace :load do
  task :defaults do
    set :envyable_roles, fetch(:envyable_roles, :all)
    set :envyable_path, fetch(:envyable_path, "config/env.yml")
  end
end


text:
%--- help for store_probabilities ---
%
%  INTERNAL FUNCTION
%
%
%    Other functions named store_probabilities
%
%       dsge/store_probabilities
%


text:
FROM python:3.7-slim

# Copy local code to the container image.
ENV APP_HOME /app
ENV PYTHONUNBUFFERED TRUE

WORKDIR $APP_HOME
COPY . .

# Install production dependencies.
RUN pip install gunicorn cloudevents functions-framework
RUN pip install -r requirements.txt
RUN chmod +x send_cloudevent.py

# Run the web service on container startup.
CMD ["functions-framework", "--target=hello", "--signature-type=cloudevent"]


text:
<?php
Header("Location: /me-demo/model-engine/designer.php");
exit();
?>


text:
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
  inject,
  async,
  TestBed,
  ComponentFixture
} from '@angular/core/testing';
import { Component } from '@angular/core';
import {
  BaseRequestOptions,
  ConnectionBackend,
  Http
} from '@angular/http';
import { MockBackend } from '@angular/http/testing';

// Load the implementations that should be tested
import { StateService } from '../../services';
import { HomeComponent } from './home.component';

describe(`Home`, () => {
  let comp: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;

  // async beforeEach
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [HomeComponent],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        BaseRequestOptions,
        MockBackend,
        {
          provide: Http,
          useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
            return new Http(backend, defaultOptions);
          },
          deps: [MockBackend, BaseRequestOptions]
        },
        StateService,
      ]
    })
      .compileComponents(); // compile template and css
  }));

  // synchronous beforeEach
  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    comp = fixture.componentInstance;

    fixture.detectChanges(); // trigger initial data binding
  });

  it('should have default data', () => {
    expect(comp.localState).toEqual({ value: '' });
  });

  it('should have an appState', () => {
    expect(!!comp.appState).toEqual(true);
  });

  it('should not have an user in appState', () => {
    expect(!comp.appState.getValue<any>('User')).toEqual(true);
  });

  it('should log ngOnInit', () => {
    spyOn(console, 'log');
    expect(console.log).not.toHaveBeenCalled();

    comp.ngOnInit();
    expect(console.log).toHaveBeenCalled();
  });

});


text:
#ifndef _TXN_CLIENT_MPI_H
#define _TXN_CLIENT_MPI_H

#include <mpi.h>
#include "txn_transaction.h"
#include "txn_globals.h"
#include <stdlib.h>

// ROOT_COMM1 = 'world' comm (unused)
// ROOT_COMM2 = unused
// SUB_COMM1 = coordinator & sub_coordinators only
// SUB_COMM2 = subordinates and the local sub_coordinator
#define ROOT_COMM1 0
#define ROOT_COMM2 1
#define SUB_COMM1 2
#define SUB_COMM2 3

#define VOTE 0
#define INIT 1

/*
 * MPI Tags that the asynchronous collectives use.
 */
enum MSG_TAG
{
    TAG_BEGIN_TX = 6500,
    TAG_BCAST_SUB_TX_SIZE,
    TAG_BCAST_SUB_TX,
    TAG_NEW_SUB_TX,
    TAG_BEGIN_SUB_TX,
    TAG_BEGIN_WRITE,
    TAG_REQ_VOTE_VAR,
    TAG_VOTE_VAR,
    TAG_PRE_COMMIT,
    TAG_PRE_COMMIT_RESP,
    TAG_FINALIZE_TX,
    TAG_COMMIT,
    TAG_ABORT,
    TAG_REQ_VOTE_TX,
    TAG_VOTE_TX,
    TAG_VOTE_TX_RESP,
    TAG_FAILED_RANK,

    TAG_PROCESS_FAILURE,
    TAG_NEW_SUB_COORDINATOR,
    TAG_NEW_COORDINATOR
};
typedef enum MSG_TAG MSG_TAG;

/*
 * MPI library uses this to broadcast state updates to transactions.
 */
struct _mpi_tx
{
    int tx_id;
    txn_state state;
    txn_status status;
    txn_vote vote;
    // no other purpose other than testing.
    // might use for reporting purposes later.
    int from_app_rank;
};
typedef struct _mpi_tx mpi_tx;

/*
 * Used to respond to your parent coordinator with your sub_transaction
 * information.  Used only once, when the sub-coordinators gather their
 * begin transaction responses from their subordinates.
 */
struct _mpi_tx_response
{
    mpi_tx tx;
    sub_transaction sub_tx[MAX_SUB_TRANSACTIONS];
    int num_sub_transactions;
};
typedef struct _mpi_tx_response mpi_tx_response;
//=============================================================================
/*
 * This function initializes MPI for the transaction layer.
 * This is completely separate from the application's MPI.
 * Sets up the various groups, colors, and communicators.
 */
struct transaction_comm * txn_mpi_init(MPI_Comm, int);

/* cleanup what we allocated */
void txn_mpi_finalize (struct transaction_comm * comm);

/*
 * Begins a transaction.  Goes up and down the tree and returns a
 * success or failure code.
 */
int mpi_begin_transaction(struct transaction * txn, mpi_tx * tx);

/*
 * Votes on a specific transaction.  Will determine if all
 * of the sub_transactions have completed their required
 * operations or not.  Requires two complete trips up
 * and down the tree.  One two init and gather the responses
 * and the 2nd will disperse the coordinators decision.
 */
int mpi_vote_transaction(struct transaction_comm * comms, mpi_tx*, txn_vote);

/*
 * Commits a transaction.  If there's an error here,
 * you can still abort the transaction.
 */
int mpi_commit_transaction(struct transaction_comm * comms, mpi_tx * tx);

/*
 * Aborts the transaction.
 */
int mpi_abort_transaction(struct transaction_comm * comms, mpi_tx * tx);

/*
 * Used to commit or abort a transaction based on the result
 * of the voting phase.  If all agree to commit, and no errors occurred,
 * then STATUS will be COMMIT, else, it will be ABORT.
 */
int mpi_finalize_transaction(struct transaction_comm * comms, mpi_tx * tx, txn_vote THE_VOTE);

/*
 * Broadcasts a transaction from the root to via the
 * communicator specified at the comm_index.
 */
int mpi_bcast_transaction(struct transaction_comm * comms, mpi_tx*, MSG_TAG);

/*
 * Broadcasts a transaction from the root to via the
 * communicator specified at the comm_index.
 */
int mpi_bcast_sub_transactions (struct transaction * txn);

/*
 * TODO: have to generalize this, and gather_transactions so that
 * both mpi_tx and mpi_tx_response; will require generalizing of
 * the associated reducer functions also.
 * I could also use function pointers to reducer operations, based on
 * the type, but we risk compile time type-safety.
 */
int mpi_gather_response(struct transaction_comm * comms, mpi_tx_response*, MSG_TAG);

/*
 * Aggregates the transactions responses from a node's children.
 * Basically gathers the "OK" or abort after the init.
 */
int mpi_gather_transaction(struct transaction_comm * comms, mpi_tx*, MSG_TAG);

/*
 * Gets all messages from the MPI unexpected messages buffer
 * of a given tag. Makes one iteration through.
 */
int mpi_get_all_tag(struct transaction_comm * comms, char*, int, int, int, MSG_TAG, int);

/*
 * Helper function that calls mpi_get_all_tag, but repeatedly
 * tries to get all messages
 * until all expected are recieved, or until a timeout period.
 */
int mpi_get_all_tag_timed(struct transaction_comm * comms, char*, int, int, int,
				 MSG_TAG, double, int*, int);

void txn_mpi_print_failed_ranks (struct transaction_comm * comm);
#endif


text:
package com.kk.inject.integration.singleton.factory;

import com.kk.inject.Factory;
import com.kk.inject.Inject;
import com.kk.inject.Module;
import com.kk.inject.Named;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * Tests the multiple injection.
 */
public class MultipleInjectionsTest {

    @Before
    public void resetSingletonFactory() {
        Factory.resetFactoryDefinition();
        Factory.resetSingletonFactory();
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Constructor injection
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    private interface IUserCI {

        String getUserName();
    }

    private interface IGreeterCI {

        void greet();
    }

    private static class UserCI implements IUserCI {

        private final String mUserName;

        @Inject
        public UserCI(final String userName) {
            mUserName = userName;
        }

        @Override
        public String getUserName() {
            return mUserName;
        }
    }

    private static class GreeterCI implements IGreeterCI {

        private       String  mGreeting;
        private final IUserCI mUser;

        @Inject
        public GreeterCI(final IUserCI user) {
            mUser = user;
            mGreeting = "";
        }

        @Override
        public void greet() {
            mGreeting = "Hello " + mUser.getUserName() + "!";
        }
    }

    public static class ModuleCI extends Module {

        @Override
        protected void defineBindings() {
            whenRequestedInstanceOf(String.class).thenReturn("World");
            whenRequestedInstanceOf(IUserCI.class).thenInstantiate(UserCI.class);
            whenRequestedInstanceOf(IGreeterCI.class).thenInstantiate(GreeterCI.class);
        }
    }

    @Test
    public void injectCI() {
        Factory.addModuleClass(ModuleCI.class);
        final IGreeterCI greeter = Factory.getInstance(IGreeterCI.class);
        Assert.assertEquals("", ((GreeterCI) greeter).mGreeting);
        greeter.greet();
        Assert.assertEquals("Hello World!", ((GreeterCI) greeter).mGreeting);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Field injection
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    private interface IUserFI {

        String getUserName();
    }

    private interface IGreeterFI {

        void greet();
    }

    private static class UserFI implements IUserFI {

        @Inject private String mUserName;

        @Override
        public String getUserName() {
            return mUserName;
        }
    }

    private static class GreeterFI implements IGreeterFI {

        @Inject private IUserFI mUser;
        private         String  mGreeting;

        public GreeterFI() {
            mGreeting = "";
        }

        @Override
        public void greet() {
            mGreeting = "Hello " + mUser.getUserName() + "!";
        }
    }

    public static class ModuleFI extends Module {

        @Override
        protected void defineBindings() {
            whenRequestedInstanceOf(String.class).thenReturn("World");
            whenRequestedInstanceOf(IUserFI.class).thenInstantiate(UserFI.class);
            whenRequestedInstanceOf(IGreeterFI.class).thenInstantiate(GreeterFI.class);
        }
    }

    @Test
    public void injectFI() {
        Factory.addModuleClass(ModuleFI.class);
        final IGreeterFI greeter = Factory.getInstance(IGreeterFI.class);
        Assert.assertEquals("", ((GreeterFI) greeter).mGreeting);
        greeter.greet();
        Assert.assertEquals("Hello World!", ((GreeterFI) greeter).mGreeting);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // Method injection
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    private interface IUserMI {

        String getUserName();
    }

    private interface IGreeterMI {

        void greet();
    }

    private static class UserMI implements IUserMI {

        private String mUserName;

        @Inject
        public void setUserName(@Named("userName") final String userName) {
            mUserName = userName;
        }

        @Override
        public String getUserName() {
            return mUserName;
        }
    }

    private static class GreeterMI implements IGreeterMI {

        private String  mSaidGreeting;
        private IUserMI mUser;
        private String  mGreeting;

        public GreeterMI() {
            mSaidGreeting = "";
        }

        @Inject
        public void setup(@Named("greeting") final String greeting, final IUserMI user) {
            mGreeting = greeting;
            mUser = user;
        }

        @Override
        public void greet() {
            mSaidGreeting = mGreeting + " " + mUser.getUserName() + "!";
        }
    }

    public static class ModuleMI extends Module {

        @Override
        protected void defineBindings() {
            whenRequestedInstanceOf(String.class).ifNamed("userName").thenReturn("World");
            whenRequestedInstanceOf(String.class).ifNamed("greeting").thenReturn("Hello");
            whenRequestedInstanceOf(IUserMI.class).thenInstantiate(UserMI.class);
            whenRequestedInstanceOf(IGreeterMI.class).thenInstantiate(GreeterMI.class);
        }
    }

    @Test
    public void injectMI() {
        Factory.addModuleClass(ModuleMI.class);
        final IGreeterMI greeter = Factory.getInstance(IGreeterMI.class);
        Assert.assertEquals("", ((GreeterMI) greeter).mSaidGreeting);
        greeter.greet();
        Assert.assertEquals("Hello World!", ((GreeterMI) greeter).mSaidGreeting);
    }
}


text:
require 'json'
require 'spec_helper'

describe Switchcoder do
  it "should do GET and return Net::HTTPResponse" do

    client = Switchcoder::Client.new('1231232123', 'api.switchcoder.com', method: :get);
    phone_number = client.phone_number('19195551212');
    code = client.code(123);
    request_parameters = {parameter1:'parameter1Value', parameter2:'parameter2Value'};
    request_body = {bodyValue1:'my text'};

    response = code.invoke(request_parameters, request_body.to_json)

    response.should be_a Net::HTTPResponse

  end

  it "should do GET and return Net::HTTPResponse" do

    client = Switchcoder::Client.new('1231232123', 'api.switchcoder.com');
    phone_number = client.phone_number('19195551212');
    code = client.code(123);
    request_parameters = {parameter1:'parameter1Value', parameter2:'parameter2Value'};
    request_body = {bodyValue1:'my text'};

    response = code.invoke(request_parameters, request_body.to_json)

    response.should be_a Net::HTTPResponse

  end
end


text:
/*
 * GET URL
 */

var tokens = [];

exports.index = function (req, res) {

	res.json({ url: "https://www.flickr.com/" });

};

exports.exchange = function(req, res)
{
	var flickr = req.flickr;
	var storage = req.storage;

	var msg = req.body;

	var requestToken = msg.oauth_token;
	var requestTokenVerifier = msg.oauth_verifier;
	var requestTokenSecret = null;

	for (var i=0; i<tokens.length; i++) {

		var t = tokens[i];

		if (t.requestToken === requestToken)
		{
			requestTokenSecret = t.requestTokenSecret;

			// Remove the token from array.
			tokens.splice(i, 1);

			break;
		}
	}

	if (requestTokenSecret === null)
	{
		throw new Error('Cannot find existing request token. Cannot continue. Please try again.');
	}

	flickr.getAccessToken(requestToken, requestTokenSecret, requestTokenVerifier, function (err, message) {

		if (err) {
			throw err;
		}

		console.log('Get Access Token: ', message);

		// Return the access token to the user for local permanent storage.
		res.json(message);

		// Insert access token if not already exists.
		storage.openCollection('tokens').then(function (collection) {

			var document = storage.readByToken(message.oauthToken, collection).then(function (document) {

				if (document === undefined) {
					var doc = {
						modified: new Date(),
						token: message.oauthToken,
						secret: message.oauthTokenSecret,
						userNsId: message.userNsId,
						userName: message.userName,
						ip: req.ip
					};

					storage.insert(doc, collection).then(function (document) {
						console.log('Saved document: ' + document);
					});
				} else {
					console.log('Found document: ' + document);
					//document.modified = new Date();
					//storage.update(document, collection);

				}
			}).fail(function (err) {

				console.log('Failed to read document!! Error: ' + err);

			});
		});

		/*
		var doc = {
						modified: new Date(),
						requestToken: oauthToken,
						requestTokenSecret: oauthTokenSecret,
						ip: req.ip
					};

		doc.authToken = message.oauthToken;
		doc.authTokenSecret = message.oauthTokenSecret;
		doc.userName = message.userName;
		doc.userNsId = message.userNsId;
		doc.ip = req.ip;

		storage.update(doc, collection);*/
		//storage.delete(doc);

	});

	/*
	storage.openCollection('tokens').then(function (collection) {
		console.log('Opening collection... reading document by token..');

		var document = storage.readByRequestToken(token, collection).then(function (document) {
			if (document === undefined) {
				console.log('This should not happen. When the user have received verified, this document should exist in the database.');
				throw new Error('Cannot find existing session. Cannot continue.');
			} else {
				var doc = document;

			}
		}).fail(function (err) {

			console.log('Failed to read document!! Error: ' + err);

		});
	});*/
};

exports.url = function (req, res) {

	var flickr = req.flickr;
	var storage = req.storage;

	var cleanUpTokens = function()
	{
		console.log('cleaning up tokens...', tokens.length);

		for (var i=0; i<tokens.length; i++) {

			var token = tokens[i];

			var diffSeconds = (new Date() - token.date) / 1000;
			console.log('diff: ', diffSeconds);

			// Let's keep the tokens in-memory for 30 minutes. If user have not authorized
			// within that timeframe, we'l delete it from memory.
			if (diffSeconds > 1800)
			{
				console.log('Removing Request Token from memory due to inactivity');
				console.log('Request Token: ', token);
				tokens.splice(i, 1);
			}
		}
	};

	flickr.getAuthUrl(function (err, data) {

		if (err) {
			console.log('Error with getAuthUrl: ', err);
			return;
		}

		var oauthToken = data.oauthToken;
		var oauthTokenSecret = data.oauthTokenSecret;

		console.log('oauthRequestToken: ', oauthToken);
		console.log('oauthRequestTokenSecret: ', oauthTokenSecret);

		// We'll store the requestToken and requestTokenSecret in-memory temporarely.

		var requestToken = { 	requestToken: oauthToken,
								requestTokenSecret: oauthTokenSecret,
						   		date: new Date()
							};

		// Add the new request token.
		tokens.push(requestToken);
		console.log('Token added to array. Length: ', tokens.length);

		// Clean up old request tokens.
		cleanUpTokens();

		// Return the login URL to the user.
		res.json({ url: data.url });

		/*
		storage.openCollection('tokens').then(function (collection) {

			console.log('COLLECTION OPENED!! Searching for: ' + oauthToken);

			var document = storage.readByRequestToken(oauthToken, collection).then(function (document) {
				if (document === undefined) {
					var doc = {
						modified: new Date(),
						requestToken: oauthToken,
						requestTokenSecret: oauthTokenSecret,
						ip: req.ip
					};

					storage.insert(doc, collection).then(function (document) {
						console.log('Saved document: ' + document);
					});
				} else {
					console.log('Found document: ' + document);
					document.modified = new Date();
					storage.update(document, collection);

				}
			}).fail(function (err) {

				console.log('Failed to read document!! Error: ' + err);

			});
		});*/
	});
};


text:
Like a product it should follow these rules:

- Easy to learn
- Hard to misuse
- Easy to read and maintain it
- Audience oriented

### Design your API with a customer, or at least with a customer in mind and actively seek feedback.

Every API should be designed as if it were an external API for paying customers. Design your API with the API consumer in mind!

Each resource MUST make sense from the perspective of the API consumer. Beware of simply copy your internal model. Do not leak irrelevant implementation details out to your API.

**We believe that APIs are products**. We will provide these APIs to other business units and partners. The future is unpredictable. The conviction that an API is only internally or in one Business unit of use, can rapidly change. Therefore APIs should be designed like external APIs. Last but not least we learn to design better APIs.

### Do not invent or implement API Management

We have a list of appropriate API management solutions we like to standardize on. If our existing solutions and blueprints do not fit, we work with you to find one which does. Refer to [API Management](../api-management/api-management.md) for details.

### Every API MUST be described using a formal API description language

While we recognize the existence of various languages ([RAML](https://raml.org/), [API Blueprint](https://apiblueprint.org/)) we standardize on [Swagger](https://swagger.io) as the most commonly used language. API documentation has to be generated from its Swagger definition to ensure inherent consistency. Swagger is used to provide access to the API via API management tooling.

Reserve time to create documentation. Use [Swagger](http://swagger.io/) to document. Refer to [Documentation](../documentation/documentation.md) for details.

### API clients MUST use an API Key

Different SLA's CAN be offered by the API provider. API clients are identified by API keys obtained from the API Portal. **No API access without a corresponding and valid API key** (Exception for pubsub notification APIs which only contain the link to the resource but not the resource itself).


text:
<?php
/**
 * @phpVersion >= 8.0.0
 */

use Nette\Application\Request;
use Nette\Application\Routers\SimpleRouter;
use Nette\Application\UI\Control;
use Nette\Application\UI\Presenter;
use Nette\Http\Request as HttpRequest;
use Nette\Http\Response;
use Nette\Http\UrlScript;
use Nextras\Application\UI\Secured;
use Nextras\Application\UI\SecuredLinksControlTrait;
use Nextras\Application\UI\SecuredLinksPresenterTrait;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';

class TestControl extends Control
{
	use SecuredLinksControlTrait;
	#[Secured]
	public function handlePay($amount = 0)
	{
	}
}

class TestPresenter extends Presenter
{
	use SecuredLinksPresenterTrait;
	protected function startup()
	{
		parent::startup();
		$this['mycontrol'] = new TestControl;
	}
	public function renderDefault()
	{
		$this->terminate();
	}
	#[Secured]
	public function handlePay($amount = 0)
	{
	}
	#[Secured]
	public function handlePay2($amount)
	{
	}
	#[Secured]
	public function handleList(array $sections)
	{
	}
}

$url = new UrlScript('http://localhost/index.php', '/index.php');

$httpRequest = new HttpRequest($url);
$httpResponse = new Response();

$router = new SimpleRouter();
$request = new Request('Test', HttpRequest::GET, array());

$sessionSection = Mockery::mock('alias:Nette\Http\SessionSection');
$sessionSection->token = 'abcd';

$session = Mockery::mock('Nette\Http\Session');
$session->shouldReceive('getSection')->with('Nextras.Application.UI.SecuredLinksPresenterTrait')->andReturn($sessionSection);
$session->shouldReceive('getId')->times(8)->andReturn('session_id_1');

$presenter = new TestPresenter();
$presenter->autoCanonicalize = FALSE;
$presenter->injectPrimary(NULL, NULL, $router, $httpRequest, $httpResponse, $session, NULL);
$presenter->run($request);

Assert::same( '/index.php?action=default&do=pay&presenter=Test&_sec=7VNmMotk', $presenter->link('pay!') );
Assert::same( '/index.php?amount=200&action=default&do=pay&presenter=Test&_sec=7VNmMotk', $presenter->link('pay!', [200]) );
Assert::same( '/index.php?amount=100&action=default&do=pay2&presenter=Test&_sec=JtQFHCP3', $presenter->link('pay2!', [100]) );
Assert::same( '/index.php?amount=200&action=default&do=pay2&presenter=Test&_sec=S2PM9nnh', $presenter->link('pay2!', [200]) );
Assert::same( '/index.php?sections[0]=a&sections[1]=b&action=default&do=list&presenter=Test&_sec=btNfK0zF', urldecode($presenter->link('list!', [['a', 'b']])) );
Assert::same( '/index.php?sections[0]=a&sections[1]=c&action=default&do=list&presenter=Test&_sec=2oGtxq6E', urldecode($presenter->link('list!', [['a', 'c']])) );

Assert::same( '/index.php?action=default&do=mycontrol-pay&presenter=Test&mycontrol-_sec=_eyaqc4b', $presenter['mycontrol']->link('pay') );
Assert::same( '/index.php?mycontrol-amount=200&action=default&do=mycontrol-pay&presenter=Test&mycontrol-_sec=_eyaqc4b', $presenter['mycontrol']->link('pay', [200]) );

$session->shouldReceive('getId')->times(2)->andReturn('session_id_2');

Assert::same( '/index.php?sections[0]=a&sections[1]=b&action=default&do=list&presenter=Test&_sec=Y3v1C1cr', urldecode($presenter->link('list!', [['a', 'b']])) );
Assert::same( '/index.php?sections[0]=a&sections[1]=c&action=default&do=list&presenter=Test&_sec=kfY-zsLy', urldecode($presenter->link('list!', [['a', 'c']])) );

Mockery::close();


text:
define(['jquery', 'calculateSelectedNum','createInnerBoxFragment'], function($, calculateSelectedNum,createInnerBoxFragment) {

    //查找所有
    function findAll(table) {
        $.ajax({
            type: "post",
            //同步请求
            async: false,
            //用表名当url参数
            url: "/baidunewsThinkPHP/BgManager/Index/selectAll",
            data: {
                "table": table
            },
            success: function(data) {
                // console.log(data);
                createInnerBoxFragment(data, table);
                calculateSelectedNum();
            }
        });
        //动态添加的类,需要同步ajax,之后抛出它的选择器事件
        //这里将选中的ID外面蓝色圈添加去掉操作
        var contentitemid = $(".content-item-id").click(function() {
            var _this = $(this);
            // _this.toggleClass("selected");
            var itemid = _this.children(".itemid");
            if(_this.hasClass("selected")){
                _this.removeClass("selected");
                itemid.css("border","4px solid #fff");
            }else{
                _this.addClass("selected");
                itemid.css("border","4px solid rgb(26, 188, 157)");
            }

        });
        return contentitemid;
    }

    return findAll;
});


text:
import React, { Component, PropTypes } from 'react'
import { Link } from 'react-router'
import styles from './PostListItem.css'

export default class PostListItem extends Component {
  static propTypes = {
    post: PropTypes.shape({
      title: PropTypes.string.isRequired,
      content: PropTypes.string.isRequired,
      slug: PropTypes.string.isRequired
    }).isRequired
  }

  render () {
    const { post } = this.props

    return (
      <Link to={'/' + post.slug} className={styles.item}>

{post.title}

      </Link>
    )
  }
}


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.DesktopVirtualization.Models
{
    public partial class HostPoolRegistrationInfo : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(ExpireOn))
            {
                writer.WritePropertyName("expirationTime");
                writer.WriteStringValue(ExpireOn.Value, "O");
            }
            if (Optional.IsDefined(Token))
            {
                writer.WritePropertyName("token");
                writer.WriteStringValue(Token);
            }
            if (Optional.IsDefined(RegistrationTokenOperation))
            {
                writer.WritePropertyName("registrationTokenOperation");
                writer.WriteStringValue(RegistrationTokenOperation.Value.ToString());
            }
            writer.WriteEndObject();
        }

        internal static HostPoolRegistrationInfo DeserializeHostPoolRegistrationInfo(JsonElement element)
        {
            Optional<DateTimeOffset> expirationTime = default;
            Optional<string> token = default;
            Optional<HostPoolRegistrationTokenOperation> registrationTokenOperation = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("expirationTime"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    expirationTime = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("token"))
                {
                    token = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("registrationTokenOperation"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    registrationTokenOperation = new HostPoolRegistrationTokenOperation(property.Value.GetString());
                    continue;
                }
            }
            return new HostPoolRegistrationInfo(Optional.ToNullable(expirationTime), token.Value, Optional.ToNullable(registrationTokenOperation));
        }
    }
}


text:
#ifndef FLENS_MATRIXTYPES_HERMITIAN_IMPL_HBMATRIX_H
#define FLENS_MATRIXTYPES_HERMITIAN_IMPL_HBMATRIX_H 1

#include <cxxblas/typedefs.h>
#include <flens/auxiliary/auxiliary.h>
#include <flens/typedefs.h>
#include <flens/matrixtypes/hermitian/hermitianmatrix.h>
#include <flens/typedefs.h>

namespace flens {

// forward declarations
template <typename A>
    class DenseVector;

template <typename FS>
    class GbMatrix;

template <typename FS>
    class HbMatrix;

template <typename FS>
    class SbMatrix;

template <typename FS>
    class TbMatrix;

template <typename FS>
class HbMatrix
    : public HermitianMatrix<HbMatrix<FS> >
{
    public:
        typedef FS                                  Engine;
        typedef typename Engine::ElementType        ElementType;
        typedef typename Engine::IndexType          IndexType;

        // std:: typedefs
        typedef typename Engine::size_type        size_type;
        typedef ElementType                       value_type;
        typedef typename Engine::pointer          pointer;
        typedef typename Engine::const_pointer    const_pointer;
        typedef typename Engine::reference        reference;
        typedef typename Engine::const_reference  const_reference;

        // view types from Engine
        typedef typename Engine::ConstView          EngineConstView;
        typedef typename Engine::View               EngineView;
        typedef typename Engine::NoView             EngineNoView;

        typedef typename Engine::ConstArrayView     ConstArrayView;
        typedef typename Engine::ArrayView          ArrayView;
        typedef typename Engine::Array              Array;

        // view types
        typedef DenseVector<ConstArrayView>         ConstVectorView;
        typedef DenseVector<ArrayView>              VectorView;
        typedef DenseVector<Array>                  Vector;

        typedef GbMatrix<EngineConstView>           ConstGeneralView;
        typedef GbMatrix<EngineView>                GeneralView;
        typedef GbMatrix<EngineNoView>              GeneralNoView;

        typedef HbMatrix<EngineConstView>           ConstView;
        typedef HbMatrix<EngineView>                View;
        typedef HbMatrix<EngineNoView>              NoView;

        typedef SbMatrix<EngineConstView>           ConstSymmetricView;
        typedef SbMatrix<EngineView>                SymmetricView;
        typedef SbMatrix<EngineNoView>              SymmetricNoView;

        typedef TbMatrix<EngineConstView>           ConstTriangularView;
        typedef TbMatrix<EngineView>                TriangularView;
        typedef TbMatrix<EngineNoView>              TriangularNoView;

        HbMatrix();

        explicit
        HbMatrix(IndexType dim, StorageUpLo upLo, IndexType numOffDiags,
                 IndexType firstIndex = Engine::defaultIndexBase);

        HbMatrix(const Engine &engine, StorageUpLo upLo);

        HbMatrix(const HbMatrix &rhs);

        template <typename RHS>
            HbMatrix(const HbMatrix<RHS> &rhs);

        template <typename RHS>
            HbMatrix(HbMatrix<RHS> &rhs);

        template <typename RHS,
                  class = typename RestrictTo<!IsSame<FS,RHS>::value, void>::Type>
            HbMatrix(HbMatrix<RHS> &&rhs);

        template <typename RHS>
            HbMatrix(const Matrix<RHS> &rhs);

        // -- operators --------------------------------------------------------

        HbMatrix &
        operator=(const HbMatrix &rhs);

        template <typename RHS>
            HbMatrix &
            operator=(const Matrix<RHS> &rhs);

        template <typename RHS>
            HbMatrix &
            operator+=(const Matrix<RHS> &rhs);

        template <typename RHS>
            HbMatrix &
            operator-=(const Matrix<RHS> &rhs);

        HbMatrix<FS> &
        operator=(const ElementType &alpha);

        HbMatrix<FS> &
        operator+=(const ElementType &alpha);

        HbMatrix<FS> &
        operator-=(const ElementType &alpha);

        HbMatrix &
        operator*=(const ElementType &alpha);

        HbMatrix &
        operator/=(const ElementType &alpha);

        const_reference
        operator()(IndexType row, IndexType col) const;

        reference
        operator()(IndexType row, IndexType col);

        // -- views ------------------------------------------------------------

        // general views
        ConstGeneralView
        general() const;

        GeneralView
        general();

        // symmetric view
        ConstSymmetricView
        symmetric() const;

        SymmetricView
        symmetric();

        // triangular view
        ConstTriangularView
        triangular() const;

        TriangularView
        triangular();

        VectorView
        diag(IndexType diag);

        const ConstVectorView
        diag(IndexType diag) const;

        // -- methods ----------------------------------------------------------

        IndexType
        dim() const;

        IndexType
        numCols() const;

        IndexType
        numRows() const;

        IndexType
        firstIndex() const;

        IndexType
        lastIndex() const;

        IndexType
        leadingDimension() const;

        StorageOrder
        order() const;

        IndexType
        numOffDiags() const;

        const_pointer
        data() const;

        pointer
        data();

        template <typename RHS>
            bool
            resize(const HbMatrix<RHS> &rhs,
                   const ElementType &value = ElementType());

        bool
        resize(IndexType dim, IndexType numOffDiags,
               IndexType firstIndex = Engine::defaultIndexBase,
               const ElementType &value = ElementType());

        template <typename RHS>
            bool
            reserve(const HbMatrix<RHS> &rhs);

        bool
        reserve(IndexType dim, IndexType numOffDiags,
                IndexType firstIndex = Engine::defaultIndexBase);

        bool
        fill(const ElementType &value = ElementType());

        bool
        fillRandom();

        // -- implementation ---------------------------------------------------

        const Engine &
        engine() const;

        Engine &
        engine();

        StorageUpLo
        upLo() const;

    private:
        Engine       engine_;
        StorageUpLo  upLo_;
};

//-- Traits --------------------------------------------------------------------
//
//  IsHbMatrix
//
struct HbMatrixChecker_
{

    struct Two {
        char x;
        char y;
    };

    static Two
    check(AnyConversion_);

    template <typename Any>
        static char
        check(HbMatrix<Any>);
};

template <typename T>
struct IsHbMatrix
{
    static T var;
    static const bool value = sizeof(HbMatrixChecker_::check(var))==1;
};

} // namespace flens

#endif // FLENS_MATRIXTYPES_HERMITIAN_IMPL_HBMATRIX_H


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ("blog", "0001_initial"),
    ]

    operations = [
        migrations.AddField(
            model_name="blogentry",
            name="icon",
            field=models.CharField(
                default=b"fa-align-right",
                help_text=b"The font awesome icon to be displayed",
                max_length=64,
            ),
            preserve_default=True,
        ),
    ]


text:
namespace google_breakpad {

// Opaque type for the serialized representation of a NonAllocatingMap. One is
// created in NonAllocatingMap::Serialize and can be deserialized using one of
// the constructors.
struct SerializedNonAllocatingMap;

// NonAllocatingMap is an implementation of a map/dictionary collection that
// uses a fixed amount of storage, so that it does not perform any dynamic
// allocations for its operations.
//
// The actual map storage (the Entry) is guaranteed to be POD, so that it can
// be transmitted over various IPC mechanisms.
//
// The template parameters control the amount of storage used for the key,
// value, and map. The KeySize and ValueSize are measured in bytes, not glyphs,
// and includes space for a \0 byte. This gives space for KeySize-1 and
// ValueSize-1 characters in an entry. NumEntries is the total number of
// entries that will fit in the map.
template <size_t KeySize, size_t ValueSize, size_t NumEntries>
class NonAllocatingMap {
 public:
  // Constant and publicly accessible versions of the template parameters.
  static const size_t key_size = KeySize;
  static const size_t value_size = ValueSize;
  static const size_t num_entries = NumEntries;

  // An Entry object is a single entry in the map. If the key is a 0-length
  // NUL-terminated string, the entry is empty.
  struct Entry {
    char key[KeySize];
    char value[ValueSize];

    bool is_active() const {
      return key[0] != '\0';
    }
  };

  // An Iterator can be used to iterate over all the active entries in a
  // NonAllocatingMap.
  class Iterator {
   public:
    explicit Iterator(const NonAllocatingMap& map)
        : map_(map),
          current_(0) {
    }

    // Returns the next entry in the map, or NULL if at the end of the
    // collection.
    const Entry* Next() {
      while (current_ < map_.num_entries) {
        const Entry* entry = &map_.entries_[current_++];
        if (entry->is_active()) {
          return entry;
        }
      }
      return NULL;
    }

   private:
    const NonAllocatingMap& map_;
    size_t current_;

    DISALLOW_COPY_AND_ASSIGN(Iterator);
  };

  NonAllocatingMap() : entries_() {
  }

  NonAllocatingMap(const NonAllocatingMap& other) {
    *this = other;
  }

  NonAllocatingMap& operator=(const NonAllocatingMap& other) {
    assert(other.key_size == key_size);
    assert(other.value_size == value_size);
    assert(other.num_entries == num_entries);
    if (other.key_size == key_size && other.value_size == value_size &&
        other.num_entries == num_entries) {
      memcpy(entries_, other.entries_, sizeof(entries_));
    }
    return *this;
  }

  // Constructs a map from its serialized form. |map| should be the out
  // parameter from Serialize() and |size| should be its return value.
  NonAllocatingMap(const SerializedNonAllocatingMap* map, size_t size) {
    assert(size == sizeof(entries_));
    if (size == sizeof(entries_)) {
      memcpy(entries_, map, size);
    }
  }

  // Returns the number of active key/value pairs. The upper limit for this
  // is NumEntries.
  size_t GetCount() const {
    size_t count = 0;
    for (size_t i = 0; i < num_entries; ++i) {
      if (entries_[i].is_active()) {
        ++count;
      }
    }
    return count;
  }

  // Given |key|, returns its corresponding |value|. |key| must not be NULL. If
  // the key is not found, NULL is returned.
  const char* GetValueForKey(const char* key) const {
    assert(key);
    if (!key)
      return NULL;

    const Entry* entry = GetConstEntryForKey(key);
    if (!entry)
      return NULL;

    return entry->value;
  }

  // Stores |value| into |key|, replacing the existing value if |key| is
  // already present. |key| must not be NULL. If |value| is NULL, the key is
  // removed from the map. If there is no more space in the map, then the
  // operation silently fails.
  void SetKeyValue(const char* key, const char* value) {
    if (!value) {
      RemoveKey(key);
      return;
    }

    assert(key);
    if (!key)
      return;

    // Key must not be an empty string.
    assert(key[0] != '\0');
    if (key[0] == '\0')
      return;

    Entry* entry = GetEntryForKey(key);

    // If it does not yet exist, attempt to insert it.
    if (!entry) {
      for (size_t i = 0; i < num_entries; ++i) {
        if (!entries_[i].is_active()) {
          entry = &entries_[i];

          strncpy(entry->key, key, key_size);
          entry->key[key_size - 1] = '\0';

          break;
        }
      }
    }

    // If the map is out of space, entry will be NULL.
    if (!entry)
      return;

#ifndef NDEBUG
    // Sanity check that the key only appears once.
    int count = 0;
    for (size_t i = 0; i < num_entries; ++i) {
      if (strncmp(entries_[i].key, key, key_size) == 0)
        ++count;
    }
    assert(count == 1);
#endif

    strncpy(entry->value, value, value_size);
    entry->value[value_size - 1] = '\0';
  }

  // Given |key|, removes any associated value. |key| must not be NULL. If
  // the key is not found, this is a noop.
  void RemoveKey(const char* key) {
    assert(key);
    if (!key)
      return;

    Entry* entry = GetEntryForKey(key);
    if (entry) {
      entry->key[0] = '\0';
      entry->value[0] = '\0';
    }

#ifndef NDEBUG
    assert(GetEntryForKey(key) == NULL);
#endif
  }

  // Places a serialized version of the map into |map| and returns the size.
  // Both of these should be passed to the deserializing constructor. Note that
  // the serialized |map| is scoped to the lifetime of the non-serialized
  // instance of this class. The |map| can be copied across IPC boundaries.
  size_t Serialize(const SerializedNonAllocatingMap** map) const {
    *map = reinterpret_cast<const SerializedNonAllocatingMap*>(entries_);
    return sizeof(entries_);
  }

 private:
  const Entry* GetConstEntryForKey(const char* key) const {
    for (size_t i = 0; i < num_entries; ++i) {
      if (strncmp(key, entries_[i].key, key_size) == 0) {
        return &entries_[i];
      }
    }
    return NULL;
  }

  Entry* GetEntryForKey(const char* key) {
    return const_cast<Entry*>(GetConstEntryForKey(key));
  }

  Entry entries_[NumEntries];
};

// For historical reasons this specialized version is available with the same
// size factors as a previous implementation.
typedef NonAllocatingMap<256, 256, 64> SimpleStringDictionary;

}  // namespace google_breakpad

#endif  // COMMON_SIMPLE_STRING_DICTIONARY_H_


text:
<!--
    Copyright (c) Microsoft Corporation. All rights reserved.
    Licensed under the MIT License. See License.txt in the project root for license information.
-->

<rules>
  <rule id="Entry.Core.1006" category="core" target="entry" specificationsection ="2.2.6.2.2" v4specificationsection="10.1" v4specification="odataatom" requirementlevel="should" format="atom" mle="true">
    <description>If the entity represents an AtomPub Media Link Entry, an <atom:link> element SHOULD be included, which contains an atom:rel="edit-media" attribute.</description>
    <action processor="rng">
      <grammar xmlns="http://relaxng.org/ns/structure/1.0" xmlns:atom="http://www.w3.org/2005/Atom">
        <start>
          <element>
            <anyName />
            <!-- Ignore the entry element. -->
            <ref name="anyAttributes" />
            <interleave>
              <element name="atom:link">
                <attribute name="rel">
                  <value>edit-media</value>
                </attribute>
                <oneOrMore>
                  <ref name="anyAttributes_other_than_atom_rel" />
                </oneOrMore>
              </element>
              <zeroOrMore>
                <!-- Elements here should not be atom:link with attribute rel with value edit-media. -->
                <choice>
                  <!-- Any element that is not atom:link. -->
                  <ref name="anyElement_other_than_atom_link" />
                  <!-- Any element that is atom:link yet with attribute rel not equal to edit-media. -->
                  <ref name="anyElement_of_atom_link_without_attribute_rel_with_value_edit_media" />
                </choice>
              </zeroOrMore>
            </interleave>
          </element>
        </start>
        <define name="anyContent">
          <zeroOrMore>
            <choice>
              <attribute>
                <anyName />
              </attribute>
              <text />
              <ref name="anyElement" />
            </choice>
          </zeroOrMore>
        </define>
        <define name="anyAttributes">
          <zeroOrMore>
            <choice>
              <attribute>
                <anyName />
              </attribute>
            </choice>
          </zeroOrMore>
        </define>
        <define name="anyAttributes_other_than_atom_rel">
          <zeroOrMore>
            <choice>
              <attribute>
                <anyName>
                  <except>
                    <name>rel</name>
                  </except>
                </anyName>
              </attribute>
            </choice>
          </zeroOrMore>
        </define>
        <define name="anyAttributes_other_than_atom_rel_with_value_edit_media">
          <zeroOrMore>
            <choice>
              <attribute>
                <anyName>
                  <except>
                    <name>rel</name>
                  </except>
                </anyName>
              </attribute>
              <attribute>
                <name>rel</name>
                <data type="token">
                  <except>
                    <value>edit-media</value>
                  </except>
                </data>
              </attribute>
            </choice>
          </zeroOrMore>
        </define>
        <define name="anyElement">
          <element>
            <anyName />
            <zeroOrMore>
              <choice>
                <attribute>
                  <anyName />
                </attribute>
                <text />
                <ref name="anyElement" />
              </choice>
            </zeroOrMore>
          </element>
        </define>
        <define name="anyElement_other_than_atom_link">
          <element>
            <choice>
              <anyName>
                <except>
                  <nsName ns="http://www.w3.org/2005/Atom" />
                </except>
              </anyName>
              <nsName ns="http://www.w3.org/2005/Atom">
                <except>
                  <name>atom:link</name>
                </except>
              </nsName>
            </choice>
            <ref name="anyAttributes" />
            <text />
            <zeroOrMore>
              <ref name="anyElement" />
            </zeroOrMore>
          </element>
        </define>
        <define name="anyElement_of_atom_link_without_attribute_rel_with_value_edit_media">
          <element name="atom:link">
            <ref name="anyAttributes_other_than_atom_rel_with_value_edit_media" />
            <text />
            <zeroOrMore>
              <ref name="anyElement" />
            </zeroOrMore>
          </element>
        </define>
      </grammar>
    </action>
    <errormessage>If the entity represents an AtomPub Media Link Entry, an <atom:link> element SHOULD be included, which contains an atom:rel="edit-media" attribute.</errormessage>
  </rule>
</rules>


text:
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
import { AppContainer } from 'react-hot-loader'
import configureStore from './store/configureStore'
import Root from './router/Root'

export const store = configureStore()
const history = syncHistoryWithStore(browserHistory, store)

render(
    <AppContainer>
        <Root store={store} history={history} />
    </AppContainer>,
    document.getElementById('root'),
)

if (module.hot) {
    module.hot.accept('./router/Root', () => {
        const NewRoot = require('./router/Root').default
        render(
            <AppContainer>
                <NewRoot store={store} history={history} />
            </AppContainer>,
            document.getElementById('root'),
        )
    })
}


text:
'''
 upload hexfile via STM8 bootloader or SWIM
'''

# required modules
import sys
import os
import platform
import misc

##################
# upload to STM8 via stm8gal and UART bootloader
##################
def stm8gal(tooldir='../../../Tools/', tool='stm8gal', port='/dev/ttyUSB0', outdir='output', target='main.ihx', reset=0):

  # on Windows attach .exe to tool
  if platform.system() == 'Windows':
    tool = tool + ".exe"

  # assemble shell command
  cmd = tooldir + tool + ' -p ' + port + ' -w ' + outdir + '/' + target + ' -v -R ' + str(reset)

  # on Windows replace path delimiter
  if platform.system() == 'Windows':
    cmd = cmd.replace('/','\\')
  #print cmd

  # upload hexfile
  exitcode = os.system(cmd)

  # check for success
  if (exitcode != 0):
    sys.stderr.write('error '+str(exitcode)+'\n\n')
    misc.Exit(exitcode)

# stm8gal
##################

##################
# upload to STM8 via stm8flash and SWIM interface
##################
def stm8flash(tooldir='../../../Tools/', tool='stm8flash', device='stm8s105c6', hardware='stlink', outdir='output', target='main.ihx'):

  # separate output a bit
  sys.stdout.write('\n')

  # on Windows attach .exe to tool
  if platform.system() == 'Windows':
    tool = tool + ".exe"

  # assemble shell command
  cmd = tooldir + tool + ' -c ' + hardware + ' -w ' + outdir + '/' + target + ' -p ' + device

  # on Windows replace path delimiter
  if platform.system() == 'Windows':
    cmd = cmd.replace('/','\\')
    cmd = cmd + ".exe"
  #print cmd

  # upload hexfile
  exitcode = os.system(cmd)

  # check for success
  if (exitcode != 0):
    sys.stderr.write('error '+str(exitcode)+'\n\n')
    misc.Exit(exitcode)

# stm8flash
##################

##################
# upload to STM8 via stm8flash and SWIM interface
##################
def STVP(tooldir='C:/Programme/STMicroelectronics/st_toolset/stvp/', tool='STVP_CmdLine.exe', device='STM8S105x6', hardware='ST-LINK', outdir='output', target='main.ihx'):

  # assemble shell command
  cmd = tooldir + tool + ' -BoardName=' + hardware + ' -Port=USB -ProgMode=SWIM -Device=' + device + \
    ' -readData -readOption -no_progData -no_progOption -no_loop -no_log -FileProg=' + outdir + '/' + target

  # on Windows replace path delimiter
  if platform.system() == 'Windows':
    cmd = cmd.replace('/','\\')
  #print cmd

  # upload hexfile
  exitcode = os.system(cmd)

  # check for success
  if (exitcode != 0):
    sys.stderr.write('error '+str(exitcode)+'\n\n')
    misc.Exit(exitcode)

# STVP
##################