text:
package device

import (
	"bytes"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"net"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"

	deviceConfig "github.com/lxc/lxd/lxd/device/config"
	"github.com/lxc/lxd/lxd/device/nictype"
	"github.com/lxc/lxd/lxd/instance"
	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/network"
	"github.com/lxc/lxd/lxd/revert"
	"github.com/lxc/lxd/lxd/state"
	"github.com/lxc/lxd/lxd/util"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/logger"
	"github.com/lxc/lxd/shared/units"
	"github.com/lxc/lxd/shared/validate"
)

// Instances can be started in parallel, so lock the creation of VLANs.
var networkCreateSharedDeviceLock sync.Mutex

// NetworkSetDevMTU sets the MTU setting for a named network device if different from current.
func NetworkSetDevMTU(devName string, mtu uint64) error {
	curMTU, err := network.GetDevMTU(devName)
	if err != nil {
		return err
	}

	// Only try and change the MTU if the requested mac is different to current one.
	if curMTU != mtu {
		_, err := shared.RunCommand("ip", "link", "set", "dev", devName, "mtu", fmt.Sprintf("%d", mtu))
		if err != nil {
			return err
		}
	}

	return nil
}

// NetworkGetDevMAC retrieves the current MAC setting for a named network device.
func NetworkGetDevMAC(devName string) (string, error) {
	content, err := ioutil.ReadFile(fmt.Sprintf("/sys/class/net/%s/address", devName))
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(fmt.Sprintf("%s", content)), nil
}

// NetworkSetDevMAC sets the MAC setting for a named network device if different from current.
func NetworkSetDevMAC(devName string, mac string) error {
	curMac, err := NetworkGetDevMAC(devName)
	if err != nil {
		return err
	}

	// Only try and change the MAC if the requested mac is different to current one.
	if curMac != mac {
		_, err := shared.RunCommand("ip", "link", "set", "dev", devName, "address", mac)
		if err != nil {
			return err
		}
	}

	return nil
}

// NetworkRemoveInterface removes a network interface by name.
func NetworkRemoveInterface(nic string) error {
	_, err := shared.RunCommand("ip", "link", "del", "dev", nic)
	return err
}

// networkRemoveInterfaceIfNeeded removes a network interface by name but only if no other instance is using it.
func networkRemoveInterfaceIfNeeded(state *state.State, nic string, current instance.Instance, parent string, vlanID string) error {
	// Check if it's used by another instance.
	instances, err := instance.LoadNodeAll(state, instancetype.Any)
	if err != nil {
		return err
	}

	for _, inst := range instances {
		if inst.Name() == current.Name() && inst.Project() == current.Project() {
			continue
		}

		for devName, dev := range inst.ExpandedDevices() {
			if dev["type"] != "nic" || dev["vlan"] != vlanID || dev["parent"] != parent {
				continue
			}

			// Check if another running instance created the device, if so, don't touch it.
			if shared.IsTrue(inst.ExpandedConfig()[fmt.Sprintf("volatile.%s.last_state.created", devName)]) {
				return nil
			}
		}
	}

	return NetworkRemoveInterface(nic)
}

// networkCreateVlanDeviceIfNeeded creates a VLAN device if doesn't already exist.
func networkCreateVlanDeviceIfNeeded(state *state.State, parent string, vlanDevice string, vlanID string) (string, error) {
	if vlanID != "" {
		if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", vlanDevice)) {
			// Bring the parent interface up so we can add a vlan to it.
			_, err := shared.RunCommand("ip", "link", "set", "dev", parent, "up")
			if err != nil {
				return "", fmt.Errorf("Failed to bring up parent %s: %v", parent, err)
			}

			// Add VLAN interface on top of parent.
			_, err = shared.RunCommand("ip", "link", "add", "link", parent, "name", vlanDevice, "up", "type", "vlan", "id", vlanID)
			if err != nil {
				return "", err
			}

			// Attempt to disable IPv6 router advertisement acceptance.
			util.SysctlSet(fmt.Sprintf("net/ipv6/conf/%s/accept_ra", vlanDevice), "0")

			// We created a new vlan interface, return true.
			return "created", nil
		}

		// Check if it was created for another running instance.
		instances, err := instance.LoadNodeAll(state, instancetype.Any)
		if err != nil {
			return "", err
		}

		for _, inst := range instances {
			for devName, dev := range inst.ExpandedDevices() {
				if dev["type"] != "nic" || dev["vlan"] != vlanID || dev["parent"] != parent {
					continue
				}

				// Check if another running instance created the device, if so, mark it as created.
				if shared.IsTrue(inst.ExpandedConfig()[fmt.Sprintf("volatile.%s.last_state.created", devName)]) {
					return "reused", nil
				}
			}
		}
	}

	return "existing", nil
}

// networkSnapshotPhysicalNic records properties of the NIC to volatile so they can be restored later.
func networkSnapshotPhysicalNic(hostName string, volatile map[string]string) error {
	// Store current MTU for restoration on detach.
	mtu, err := network.GetDevMTU(hostName)
	if err != nil {
		return err
	}
	volatile["last_state.mtu"] = fmt.Sprintf("%d", mtu)

	// Store current MAC for restoration on detach
	mac, err := NetworkGetDevMAC(hostName)
	if err != nil {
		return err
	}
	volatile["last_state.hwaddr"] = mac
	return nil
}

// networkRestorePhysicalNic restores NIC properties from volatile to what they were before it was attached.
func networkRestorePhysicalNic(hostName string, volatile map[string]string) error {
	// If we created the "physical" device and then it should be removed.
	if shared.IsTrue(volatile["last_state.created"]) {
		return NetworkRemoveInterface(hostName)
	}

	// Bring the interface down, as this is sometimes needed to change settings on the nic.
	_, err := shared.RunCommand("ip", "link", "set", "dev", hostName, "down")
	if err != nil {
		return fmt.Errorf("Failed to bring down \"%s\": %v", hostName, err)
	}

	// If MTU value is specified then there is an original MTU that needs restoring.
	if volatile["last_state.mtu"] != "" {
		mtuInt, err := strconv.ParseUint(volatile["last_state.mtu"], 10, 32)
		if err != nil {
			return fmt.Errorf("Failed to convert mtu for \"%s\" mtu \"%s\": %v", hostName, volatile["last_state.mtu"], err)
		}

		err = NetworkSetDevMTU(hostName, mtuInt)
		if err != nil {
			return fmt.Errorf("Failed to restore physical dev \"%s\" mtu to \"%d\": %v", hostName, mtuInt, err)
		}
	}

	// If MAC value is specified then there is an original MAC that needs restoring.
	if volatile["last_state.hwaddr"] != "" {
		err := NetworkSetDevMAC(hostName, volatile["last_state.hwaddr"])
		if err != nil {
			return fmt.Errorf("Failed to restore physical dev \"%s\" mac to \"%s\": %v", hostName, volatile["last_state.hwaddr"], err)
		}
	}

	return nil
}

// networkRandomDevName returns a random device name with prefix.
// If the random string combined with the prefix exceeds 13 characters then empty string is returned.
// This is to ensure we support buggy dhclient applications: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=858580
func networkRandomDevName(prefix string) string {
	// Return a new random veth device name
	randBytes := make([]byte, 4)
	rand.Read(randBytes)
	iface := prefix + hex.EncodeToString(randBytes)
	if len(iface) > 13 {
		return ""
	}

	return iface
}

// networkCreateVethPair creates and configures a veth pair. It will set the hwaddr and mtu settings
// in the supplied config to the newly created peer interface. If mtu is not specified, but parent
// is supplied in config, then the MTU of the new peer interface will inherit the parent MTU.
// Accepts the name of the host side interface as a parameter and returns the peer interface name.
func networkCreateVethPair(hostName string, m deviceConfig.Device) (string, error) {
	peerName := networkRandomDevName("veth")

	_, err := shared.RunCommand("ip", "link", "add", "dev", hostName, "type", "veth", "peer", "name", peerName)
	if err != nil {
		return "", fmt.Errorf("Failed to create the veth interfaces %s and %s: %v", hostName, peerName, err)
	}

	_, err = shared.RunCommand("ip", "link", "set", "dev", hostName, "up")
	if err != nil {
		NetworkRemoveInterface(hostName)
		return "", fmt.Errorf("Failed to bring up the veth interface %s: %v", hostName, err)
	}

	// Set the MAC address on peer.
	if m["hwaddr"] != "" {
		_, err := shared.RunCommand("ip", "link", "set", "dev", peerName, "address", m["hwaddr"])
		if err != nil {
			NetworkRemoveInterface(peerName)
			return "", fmt.Errorf("Failed to set the MAC address: %v", err)
		}
	}

	// Set the MTU on peer. If not specified and has parent, will inherit MTU from parent.
	if m["mtu"] != "" {
		MTU, err := strconv.ParseUint(m["mtu"], 10, 32)
		if err != nil {
			return "", fmt.Errorf("Invalid MTU specified: %v", err)
		}

		err = NetworkSetDevMTU(peerName, MTU)
		if err != nil {
			NetworkRemoveInterface(peerName)
			return "", fmt.Errorf("Failed to set the MTU: %v", err)
		}

		err = NetworkSetDevMTU(hostName, MTU)
		if err != nil {
			NetworkRemoveInterface(peerName)
			return "", fmt.Errorf("Failed to set the MTU: %v", err)
		}
	} else if m["parent"] != "" {
		parentMTU, err := network.GetDevMTU(m["parent"])
		if err != nil {
			return "", fmt.Errorf("Failed to get the parent MTU: %v", err)
		}

		err = NetworkSetDevMTU(peerName, parentMTU)
		if err != nil {
			NetworkRemoveInterface(peerName)
			return "", fmt.Errorf("Failed to set the MTU: %v", err)
		}

		err = NetworkSetDevMTU(hostName, parentMTU)
		if err != nil {
			NetworkRemoveInterface(peerName)
			return "", fmt.Errorf("Failed to set the MTU: %v", err)
		}
	}

	return peerName, nil
}

// networkCreateTap creates and configures a TAP device.
func networkCreateTap(hostName string, m deviceConfig.Device) error {
	_, err := shared.RunCommand("ip", "tuntap", "add", "name", hostName, "mode", "tap")
	if err != nil {
		return errors.Wrapf(err, "Failed to create the tap interfaces %s", hostName)
	}

	revert := revert.New()
	defer revert.Fail()

	_, err = shared.RunCommand("ip", "link", "set", "dev", hostName, "up")
	if err != nil {
		return errors.Wrapf(err, "Failed to bring up the tap interface %s", hostName)
	}
	revert.Add(func() { NetworkRemoveInterface(hostName) })

	// Set the MTU on peer. If not specified and has parent, will inherit MTU from parent.
	if m["mtu"] != "" {
		MTU, err := strconv.ParseUint(m["mtu"], 10, 32)
		if err != nil {
			return errors.Wrap(err, "Invalid MTU specified")
		}

		err = NetworkSetDevMTU(hostName, MTU)
		if err != nil {
			return errors.Wrap(err, "Failed to set the MTU")
		}
	} else if m["parent"] != "" {
		parentMTU, err := network.GetDevMTU(m["parent"])
		if err != nil {
			return errors.Wrap(err, "Failed to get the parent MTU")
		}

		err = NetworkSetDevMTU(hostName, parentMTU)
		if err != nil {
			return errors.Wrap(err, "Failed to set the MTU")
		}
	}

	revert.Success()
	return nil
}

// networkSetupHostVethRoutes configures a nic device's host side veth routes.
// Accepts an optional oldDevice that will have its old host routes removed before adding the new device routes.
// This allows live update of a veth device.
func networkSetupHostVethRoutes(s *state.State, device deviceConfig.Device, oldDevice deviceConfig.Device, v map[string]string) error {
	// Check whether host device resolution succeeded.
	if device["host_name"] == "" {
		return fmt.Errorf("Failed to find host side veth name for device %q", device["name"])
	}

	// If oldDevice provided, remove old routes if any remain.
	if oldDevice != nil {
		networkVethFillFromVolatile(oldDevice, v)
		networkRemoveVethRoutes(s, oldDevice)
	}

	// Setup static routes to container.
	err := networkSetVethRoutes(s, device)
	if err != nil {
		return err
	}

	return nil
}

// networkVethFillFromVolatile fills veth host_name and hwaddr fields from volatile if not set in device config.
func networkVethFillFromVolatile(device deviceConfig.Device, volatile map[string]string) {
	// If not configured, check if volatile data contains the most recently added host_name.
	if device["host_name"] == "" {
		device["host_name"] = volatile["host_name"]
	}

	// If not configured, check if volatile data contains the most recently added hwaddr.
	if device["hwaddr"] == "" {
		device["hwaddr"] = volatile["hwaddr"]
	}
}

// networkSetVethRoutes applies any static routes configured from the host to the container nic.
func networkSetVethRoutes(s *state.State, m deviceConfig.Device) error {
	// Decide whether the route should point to the veth parent or the bridge parent.
	routeDev := m["host_name"]

	nicType, err := nictype.NICType(s, m)
	if err != nil {
		return err
	}

	if nicType == "bridged" {
		routeDev = m["parent"]
	}

	if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", routeDev)) {
		return fmt.Errorf("Unknown or missing host side route interface: %s", routeDev)
	}

	// Add additional IPv4 routes (using boot proto to avoid conflicts with network static routes)
	if m["ipv4.routes"] != "" {
		for _, route := range strings.Split(m["ipv4.routes"], ",") {
			route = strings.TrimSpace(route)
			_, err := shared.RunCommand("ip", "-4", "route", "add", route, "dev", routeDev, "proto", "boot")
			if err != nil {
				return err
			}
		}
	}

	// Add additional IPv6 routes (using boot proto to avoid conflicts with network static routes)
	if m["ipv6.routes"] != "" {
		for _, route := range strings.Split(m["ipv6.routes"], ",") {
			route = strings.TrimSpace(route)
			_, err := shared.RunCommand("ip", "-6", "route", "add", route, "dev", routeDev, "proto", "boot")
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// networkRemoveVethRoutes removes any routes created for this device on the host that were first added
// with networkSetVethRoutes(). Expects to be passed the device config from the oldExpandedDevices.
func networkRemoveVethRoutes(s *state.State, m deviceConfig.Device) {
	// Decide whether the route should point to the veth parent or the bridge parent
	routeDev := m["host_name"]
	nicType, err := nictype.NICType(s, m)
	if err != nil {
		logger.Errorf("Failed to get NIC type for %q", m["name"])
		return
	}

	if nicType == "bridged" {
		routeDev = m["parent"]
	}

	if m["ipv4.routes"] != "" || m["ipv6.routes"] != "" {
		if routeDev == "" {
			logger.Errorf("Failed to remove static routes as route dev isn't set for %q", m["name"])
			return
		}

		if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", routeDev)) {
			return //Routes will already be gone if device doesn't exist.
		}
	}

	// Remove IPv4 routes
	if m["ipv4.routes"] != "" {
		for _, route := range strings.Split(m["ipv4.routes"], ",") {
			route = strings.TrimSpace(route)
			_, err := shared.RunCommand("ip", "-4", "route", "flush", route, "dev", routeDev, "proto", "boot")
			if err != nil {
				logger.Errorf("Failed to remove static route: %s to %s: %s", route, routeDev, err)
			}
		}
	}

	// Remove IPv6 routes
	if m["ipv6.routes"] != "" {
		for _, route := range strings.Split(m["ipv6.routes"], ",") {
			route = strings.TrimSpace(route)
			_, err := shared.RunCommand("ip", "-6", "route", "flush", route, "dev", routeDev, "proto", "boot")
			if err != nil {
				logger.Errorf("Failed to remove static route: %s to %s: %s", route, routeDev, err)
			}
		}
	}
}

// networkSetupHostVethLimits applies any network rate limits to the veth device specified in the config.
func networkSetupHostVethLimits(m deviceConfig.Device) error {
	var err error

	veth := m["host_name"]

	if veth == "" || !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", veth)) {
		return fmt.Errorf("Unknown or missing host side veth device %q", veth)
	}

	// Apply max limit
	if m["limits.max"] != "" {
		m["limits.ingress"] = m["limits.max"]
		m["limits.egress"] = m["limits.max"]
	}

	// Parse the values
	var ingressInt int64
	if m["limits.ingress"] != "" {
		ingressInt, err = units.ParseBitSizeString(m["limits.ingress"])
		if err != nil {
			return err
		}
	}

	var egressInt int64
	if m["limits.egress"] != "" {
		egressInt, err = units.ParseBitSizeString(m["limits.egress"])
		if err != nil {
			return err
		}
	}

	// Clean any existing entry
	shared.RunCommand("tc", "qdisc", "del", "dev", veth, "root")
	shared.RunCommand("tc", "qdisc", "del", "dev", veth, "ingress")

	// Apply new limits
	if m["limits.ingress"] != "" {
		_, err := shared.RunCommand("tc", "qdisc", "add", "dev", veth, "root", "handle", "1:0", "htb", "default", "10")
		if err != nil {
			return fmt.Errorf("Failed to create root tc qdisc: %s", err)
		}

		_, err = shared.RunCommand("tc", "class", "add", "dev", veth, "parent", "1:0", "classid", "1:10", "htb", "rate", fmt.Sprintf("%dbit", ingressInt))
		if err != nil {
			return fmt.Errorf("Failed to create limit tc class: %s", err)
		}

		_, err = shared.RunCommand("tc", "filter", "add", "dev", veth, "parent", "1:0", "protocol", "all", "u32", "match", "u32", "0", "0", "flowid", "1:1")
		if err != nil {
			return fmt.Errorf("Failed to create tc filter: %s", err)
		}
	}

	if m["limits.egress"] != "" {
		_, err := shared.RunCommand("tc", "qdisc", "add", "dev", veth, "handle", "ffff:0", "ingress")
		if err != nil {
			return fmt.Errorf("Failed to create ingress tc qdisc: %s", err)
		}

		_, err = shared.RunCommand("tc", "filter", "add", "dev", veth, "parent", "ffff:0", "protocol", "all", "u32", "match", "u32", "0", "0", "police", "rate", fmt.Sprintf("%dbit", egressInt), "burst", "1024k", "mtu", "64kb", "drop")
		if err != nil {
			return fmt.Errorf("Failed to create ingress tc qdisc: %s", err)
		}
	}

	return nil
}

// networkValidGateway validates the gateway value.
func networkValidGateway(value string) error {
	if shared.StringInSlice(value, []string{"none", "auto"}) {
		return nil
	}

	return fmt.Errorf("Invalid gateway: %s", value)
}

// networkValidVLANList validates a comma delimited list of VLAN IDs.
func networkValidVLANList(value string) error {
	for _, vlanID := range strings.Split(value, ",") {
		vlanID = strings.TrimSpace(vlanID)
		err := validate.IsNetworkVLAN(vlanID)
		if err != nil {
			return err
		}
	}

	return nil
}

// networkParsePortRange validates a port range in the form n-n.
func networkParsePortRange(r string) (int64, int64, error) {
	entries := strings.Split(r, "-")
	if len(entries) > 2 {
		return -1, -1, fmt.Errorf("Invalid port range %s", r)
	}

	base, err := strconv.ParseInt(entries[0], 10, 64)
	if err != nil {
		return -1, -1, err
	}

	size := int64(1)
	if len(entries) > 1 {
		size, err = strconv.ParseInt(entries[1], 10, 64)
		if err != nil {
			return -1, -1, err
		}

		size -= base
		size++
	}

	return base, size, nil
}

// networkInterfaceBindWait waits for network interface to appear after being binded to a driver.
func networkInterfaceBindWait(ifName string) error {
	for i := 0; i < 10; i++ {
		if shared.PathExists(fmt.Sprintf("/sys/class/net/%s", ifName)) {
			return nil
		}

		time.Sleep(50 * time.Millisecond)
	}

	return fmt.Errorf("Bind of interface %q took too long", ifName)
}

// networkDHCPValidIP returns whether an IP fits inside one of the supplied DHCP ranges and subnet.
func networkDHCPValidIP(subnet *net.IPNet, ranges []network.DHCPRange, IP net.IP) bool {
	inSubnet := subnet.Contains(IP)
	if !inSubnet {
		return false
	}

	if len(ranges) > 0 {
		for _, IPRange := range ranges {
			if bytes.Compare(IP, IPRange.Start) >= 0 && bytes.Compare(IP, IPRange.End) <= 0 {
				return true
			}
		}
	} else if inSubnet {
		return true
	}

	return false
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~    Copyright (c) Arturas Molcanovas <a.molcanovas@gmail.com> 2016.
  ~    https://github.com/aloframework/log
  ~
  ~    Licensed under the Apache License, Version 2.0 (the "License");
  ~    you may not use this file except in compliance with the License.
  ~    You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~    Unless required by applicable law or agreed to in writing, software
  ~    distributed under the License is distributed on an "AS IS" BASIS,
  ~    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~    See the License for the specific language governing permissions and
  ~    limitations under the License.
  -->

<phpunit backupGlobals="true"
         backupStaticAttributes="true"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="true"
         stopOnFailure="false"
         syntaxCheck="true"
         verbose="true"
        >
    <testsuites>
        <testsuite name="Default">
            <directory>./tests</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory suffix=".php">src</directory>

            <exclude>
                <directory suffix=".php">vendor</directory>
            </exclude>
        </whitelist>
    </filter>

    <logging>
        <log type="coverage-html" target="coverage"/>
        <log type="coverage-text" target="php://stdout"/>
    </logging>
</phpunit>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/church-events/modern-church-events/general-relief-society-meeting-2011" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-events/modern-church-events/general-relief-society-meeting-2011</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">General Relief Society Meeting (2011)</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-events/modern-church-events/general-relief-society-meeting-2011</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/church-events/modern-church-events/general-relief-society-meeting-2011</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Event</sem:object>
  </sem:triple>
</sem:triples>


text:
<resources>
  <item type="layout" name="other_layout">@layout/layout3</string>
</resources>


text:
using System.ComponentModel.Composition;
using Castle.MicroKernel.Registration;
using Topics.Radical.ComponentModel.Messaging;

namespace Topics.Radical.Windows.Presentation.Boot.Installers
{
    /// <summary>
    /// A Windsor installer.
    /// </summary>
    [Export( typeof( IWindsorInstaller ) )]
    public class MessageBrokerInstaller : IWindsorInstaller
    {
        /// <summary>
        /// Performs the installation in the <see cref="T:Castle.Windsor.IWindsorContainer"/>.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="store">The configuration store.</param>
        public void Install( Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store )
        {
            var conventions = container.Resolve<BootstrapConventions>();
            var currentDirectory = Helpers.EnvironmentHelper.GetCurrentDirectory();

            // Registriamo gli handler
            container.Register
            (
                AllTypes.FromAssemblyInDirectory( new AssemblyFilter( currentDirectory ).FilterByAssembly( conventions.IncludeAssemblyInContainerScan ) )
                    .IncludeNonPublicTypes()
                    .Where( t => conventions.IsMessageHandler( t ) && !conventions.IsExcluded( t ) )
                    .WithService.Select( ( type, baseTypes ) => conventions.SelectMessageHandlerContracts( type ) )
                    .Configure( c => c.PropertiesIgnore( conventions.IgnorePropertyInjection ) )
            );
        }
    }
}


text:
package org.commonwl.view.workflow;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.commonwl.view.cwl.CWLService;
import org.commonwl.view.cwl.CWLToolRunner;
import org.commonwl.view.cwl.CWLToolStatus;
import org.commonwl.view.git.GitDetails;
import org.commonwl.view.git.GitSemaphore;
import org.commonwl.view.git.GitService;
import org.commonwl.view.graphviz.GraphVizService;
import org.commonwl.view.researchobject.ROBundleFactory;
import org.commonwl.view.researchobject.ROBundleNotFoundException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.RefNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.PathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class WorkflowService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final GitService gitService;
    private final CWLService cwlService;
    private final WorkflowRepository workflowRepository;
    private final QueuedWorkflowRepository queuedWorkflowRepository;
    private final ROBundleFactory ROBundleFactory;
    private final GraphVizService graphVizService;
    private final CWLToolRunner cwlToolRunner;
    private final GitSemaphore gitSemaphore;
    private final int cacheDays;

    @Autowired
    public WorkflowService(GitService gitService,
                           CWLService cwlService,
                           WorkflowRepository workflowRepository,
                           QueuedWorkflowRepository queuedWorkflowRepository,
                           ROBundleFactory ROBundleFactory,
                           GraphVizService graphVizService,
                           CWLToolRunner cwlToolRunner,
                           GitSemaphore gitSemaphore,
                           @Value("${cacheDays}") int cacheDays) {
        this.gitService = gitService;
        this.cwlService = cwlService;
        this.workflowRepository = workflowRepository;
        this.queuedWorkflowRepository = queuedWorkflowRepository;
        this.ROBundleFactory = ROBundleFactory;
        this.graphVizService = graphVizService;
        this.cwlToolRunner = cwlToolRunner;
        this.cacheDays = cacheDays;
        this.gitSemaphore = gitSemaphore;
    }

    /**
     * Gets a page of all workflows from the database
     * @param pageable The details of the page to be requested
     * @return The resulting page of the workflow entries
     */
    public Page<Workflow> getPageOfWorkflows(Pageable pageable) {
        return workflowRepository.findAllByOrderByRetrievedOnDesc(pageable);
    }

    /**
     * Gets a page of all workflows from the database
     * @param searchString The string to search for
     * @param pageable The details of the page to be requested
     * @return The resulting page of the workflow entries
     */
    public Page<Workflow> searchPageOfWorkflows(String searchString, Pageable pageable) {
        return workflowRepository.findByLabelContainingOrDocContainingIgnoreCase(searchString, searchString, pageable);
    }

    /**
     * Get a workflow from the database by its ID
     * @param id The ID of the workflow
     * @return The model for the workflow
     */
    public Workflow getWorkflow(String id) {
        return workflowRepository.findById(id).orElse(null);
    }

    /**
     * Get a queued workflow from the database by its ID
     * @param id The ID of the queued workflow
     * @return The model for the queued workflow
     */
    public QueuedWorkflow getQueuedWorkflow(String id) {
        return queuedWorkflowRepository.findById(id).orElse(null);
    }

    /**
     * Get a queued workflow from the database
     * @param githubInfo Github information for the workflow
     * @return The queued workflow model
     */
    public QueuedWorkflow getQueuedWorkflow(GitDetails githubInfo) {
        QueuedWorkflow queued = queuedWorkflowRepository.findByRetrievedFrom(githubInfo);

        // Slash in branch fix
        boolean slashesInPath = true;
        while (queued == null && slashesInPath) {
            GitDetails correctedForSlash = gitService.transferPathToBranch(githubInfo);
            if (correctedForSlash != null) {
                githubInfo = correctedForSlash;
                queued = queuedWorkflowRepository.findByRetrievedFrom(githubInfo);
            } else {
                slashesInPath = false;
            }
        }

        return queued;
    }

    /**
     * Get a workflow from the database, refreshing it if cache has expired
     * @param gitInfo Git information for the workflow
     * @return The workflow model associated with gitInfo
     */
    public Workflow getWorkflow(GitDetails gitInfo) {
        // Check database for existing workflows from this repository
        Workflow workflow = workflowRepository.findByRetrievedFrom(gitInfo);

        // Slash in branch fix
        boolean slashesInPath = true;
        while (workflow == null && slashesInPath) {
            GitDetails correctedForSlash = gitService.transferPathToBranch(gitInfo);
            if (correctedForSlash != null) {
                gitInfo = correctedForSlash;
                workflow = workflowRepository.findByRetrievedFrom(gitInfo);
            } else {
                slashesInPath = false;
            }
        }

        // Cache update
        if (workflow != null) {
            // Delete the existing workflow if the cache has expired
            if (cacheExpired(workflow)) {
                removeWorkflow(workflow);

                // Add the new workflow if it exists
                try {
                    createQueuedWorkflow(workflow.getRetrievedFrom());

                    // Add the old commit for the purposes of permalinks
                    // TODO: Separate concept of commit from branch ref, see #164
                    GitDetails byOldCommitId = workflow.getRetrievedFrom();
                    byOldCommitId.setBranch(workflow.getLastCommit());
                    if (getQueuedWorkflow(byOldCommitId) == null
                            && getWorkflow(byOldCommitId) == null) {
                        createQueuedWorkflow(byOldCommitId);
                    }

                    workflow = null;
                } catch (Exception e) {
                    // Add back the old workflow if it is broken now
                    logger.error("Could not parse updated workflow " + workflow.getID());
                    workflowRepository.save(workflow);
                }
            }
        }

        return workflow;
    }

    /**
     * Get a list of workflows from a directory
     * @param gitInfo The Git directory information
     * @return The list of workflow overviews
     */
    public List<WorkflowOverview> getWorkflowsFromDirectory(GitDetails gitInfo) throws IOException, GitAPIException {
        List<WorkflowOverview> workflowsInDir = new ArrayList<>();
        try {
            boolean safeToAccess = gitSemaphore.acquire(gitInfo.getRepoUrl());
            Git repo = null;
            while (repo == null) {
                try {
                    repo = gitService.getRepository(gitInfo, safeToAccess);
                } catch (RefNotFoundException ex) {
                    // Attempt slashes in branch fix
                    GitDetails correctedForSlash = gitService.transferPathToBranch(gitInfo);
                    if (correctedForSlash != null) {
                        gitInfo = correctedForSlash;
                    } else {
                        throw ex;
                    }
                }
            }

            Path localPath = repo.getRepository().getWorkTree().toPath();
            Path pathToDirectory = localPath.resolve(gitInfo.getPath()).normalize().toAbsolutePath();
            Path root = Paths.get("/").toAbsolutePath();
            if (pathToDirectory.equals(root)) {
                pathToDirectory = localPath;
            } else if (!pathToDirectory.startsWith(localPath.normalize().toAbsolutePath())) {
                // Prevent path traversal attacks
                throw new WorkflowNotFoundException();
            }

            File directory = new File(pathToDirectory.toString());
            if (directory.exists() && directory.isDirectory()) {
                for (final File file : directory.listFiles()) {
                    int eIndex = file.getName().lastIndexOf('.') + 1;
                    if (eIndex > 0) {
                        String extension = file.getName().substring(eIndex);
                        if (extension.equals("cwl")) {
                            WorkflowOverview overview = cwlService.getWorkflowOverview(file);
                            if (overview != null) {
                                workflowsInDir.add(overview);
                            }
                        }
                    }
                }
            }
        } finally {
            gitSemaphore.release(gitInfo.getRepoUrl());
        }
        return workflowsInDir;
    }

    /**
     * Get the RO bundle for a Workflow, triggering re-download if it does not exist
     * @param gitDetails The origin details of the workflow
     * @return The file containing the RO bundle
     * @throws ROBundleNotFoundException If the RO bundle was not found
     */
    public File getROBundle(GitDetails gitDetails) throws ROBundleNotFoundException {
        // Get workflow from database
        Workflow workflow = getWorkflow(gitDetails);

        // If workflow does not exist or the bundle doesn't yet
        if (workflow == null || workflow.getRoBundlePath() == null) {
            throw new ROBundleNotFoundException();
        }

        // 404 error with retry if the file on disk does not exist
        File bundleDownload = new File(workflow.getRoBundlePath());
        if (!bundleDownload.exists()) {
            // Clear current RO bundle link and create a new one (async)
            workflow.setRoBundlePath(null);
            workflowRepository.save(workflow);
            generateROBundle(workflow);
            throw new ROBundleNotFoundException();
        }

        return bundleDownload;
    }

    /**
     * Builds a new queued workflow from Git
     * @param gitInfo Git information for the workflow
     * @return A queued workflow model
     * @throws GitAPIException Git errors
     * @throws WorkflowNotFoundException Workflow was not found within the repository
     * @throws IOException Other file handling exceptions
     */
    public QueuedWorkflow createQueuedWorkflow(GitDetails gitInfo)
            throws GitAPIException, WorkflowNotFoundException, IOException {
        QueuedWorkflow queuedWorkflow;

        try {
            boolean safeToAccess = gitSemaphore.acquire(gitInfo.getRepoUrl());
            Git repo = null;
            while (repo == null) {
                try {
                    repo = gitService.getRepository(gitInfo, safeToAccess);
                } catch (RefNotFoundException ex) {
                    // Attempt slashes in branch fix
                    GitDetails correctedForSlash = gitService.transferPathToBranch(gitInfo);
                    if (correctedForSlash != null) {
                        gitInfo = correctedForSlash;
                    } else {
                        throw ex;
                    }
                }
            }
            Path localPath = repo.getRepository().getWorkTree().toPath();
            String latestCommit = gitService.getCurrentCommitID(repo);

            Path workflowFile = localPath.resolve(gitInfo.getPath()).normalize().toAbsolutePath();
            // Prevent path traversal attacks
            if (!workflowFile.startsWith(localPath.normalize().toAbsolutePath())) {
                throw new WorkflowNotFoundException();
            }

            // Check workflow is readable
            if (!Files.isReadable(workflowFile)) {
                throw new WorkflowNotFoundException();
            }

            // Handling of packed workflows
            String packedWorkflowId = gitInfo.getPackedId();
            if (packedWorkflowId == null) {
                if (cwlService.isPacked(workflowFile.toFile())) {
                    List<WorkflowOverview> overviews = cwlService.getWorkflowOverviewsFromPacked(workflowFile.toFile());
                    if (overviews.size() == 0) {
                        throw new IOException("No workflow was found within the packed CWL file");
                    } else {
                        // Dummy queued workflow object to return the list
                        QueuedWorkflow overviewList = new QueuedWorkflow();
                        overviewList.setWorkflowList(overviews);
                        return overviewList;
                    }
                }
            } else {
                // Packed ID specified but was not found
                if (!cwlService.isPacked(workflowFile.toFile())) {
                    throw new WorkflowNotFoundException();
                }
            }

            Workflow basicModel = cwlService.parseWorkflowNative(workflowFile, packedWorkflowId);

            // Set origin details
            basicModel.setRetrievedOn(new Date());
            basicModel.setRetrievedFrom(gitInfo);
            basicModel.setLastCommit(latestCommit);

            // Save the queued workflow to database
            queuedWorkflow = new QueuedWorkflow();
            queuedWorkflow.setTempRepresentation(basicModel);
            queuedWorkflowRepository.save(queuedWorkflow);

            // ASYNC OPERATIONS
            // Parse with cwltool and update model
            try {
                cwlToolRunner.createWorkflowFromQueued(queuedWorkflow);
            } catch (Exception e) {
                logger.error("Could not update workflow with cwltool", e);
            }

        } finally {
            gitSemaphore.release(gitInfo.getRepoUrl());
        }

        // Return this model to be displayed
        return queuedWorkflow;
    }

    /**
     * Retry the running of cwltool to create a new workflow
     * @param queuedWorkflow The workflow to use to update
     */
    public void retryCwltool(QueuedWorkflow queuedWorkflow) {
        queuedWorkflow.setMessage(null);
        queuedWorkflow.setCwltoolStatus(CWLToolStatus.RUNNING);
        queuedWorkflowRepository.save(queuedWorkflow);
        try {
            cwlToolRunner.createWorkflowFromQueued(queuedWorkflow);
        } catch (Exception e) {
            logger.error("Could not update workflow with cwltool", e);
        }
    }

    /**
     * Find a workflow by commit ID and path
     * @param commitID The commit ID of the workflow
     * @param path The path to the workflow within the repository
     * @return A workflow model with the above two parameters
     */
    public Workflow findByCommitAndPath(String commitID, String path) throws WorkflowNotFoundException {
        return findByCommitAndPath(commitID, path, Optional.empty());
    }

    /**
     * Find a workflow by commit ID and path
     *
     * @param commitID
     *            The commit ID of the workflow
     * @param path
     *            The path to the workflow within the repository
     * @param part
     *            The #part within the workflow, or Optional.empty() for no part, or
     *            null for any part
     * @return A workflow model with the above two parameters
     */
    public Workflow findByCommitAndPath(String commitID, String path, Optional<String> part)
            throws WorkflowNotFoundException, MultipleWorkflowsException {
        List<Workflow> matches = workflowRepository.findByCommitAndPath(commitID, path);
        if (matches == null || matches.isEmpty()) {
            throw new WorkflowNotFoundException();
        } else if (part == null) {
            // any part will do - so we'll pick the first one
            return matches.get(0);
        } else {
            // Multiple matches means either added by both branch and ID
            // Or packed workflow
            for (Workflow workflow : matches) {
                if (Objects.equals(part.orElse(null), workflow.getRetrievedFrom().getPackedId())) {
                    // either both are null; or both are non-null and equal
                    return workflow;
                }
            }
            if (part.isPresent()) {
                // Sorry, don't know about your part!
                throw new WorkflowNotFoundException();
            } else {
                // No part requested, let's show some alternate permalinks,
                // in addition to the raw redirect
                throw new MultipleWorkflowsException(matches);
            }
        }
    }

    /**
     * Get a graph in a particular format and return it
     * @param format The format for the graph file
     * @param gitDetails The Git details of the workflow
     * @return A FileSystemResource representing the graph
     * @throws WorkflowNotFoundException Error getting the workflow or format
     * @throws IOException Error reading the workflow files
     */
    public PathResource getWorkflowGraph(String format, GitDetails gitDetails)
            throws WorkflowNotFoundException, IOException {
        // Determine file extension from format
        String extension;
        switch (format) {
            case "svg":
            case "png":
                extension = format;
                break;
            case "xdot":
                extension = "dot";
                break;
            default:
                throw new WorkflowNotFoundException();
        }

        // Get workflow
        Workflow workflow = getWorkflow(gitDetails);
        if (workflow == null) {
            throw new WorkflowNotFoundException();
        }

        // Generate graph and serve the file
        Path out = graphVizService.getGraphPath(workflow.getID() + "." + extension, workflow.getVisualisationDot(), format);
        return new PathResource(out);
    }

    /**
     * Generates the RO bundle for a Workflow and adds it to the model
     * @param workflow The workflow model to create a Research Object for
     */
    private void generateROBundle(Workflow workflow) {
        try {
            ROBundleFactory.createWorkflowRO(workflow);
        } catch (Exception ex) {
            logger.error("Error creating RO Bundle", ex);
        }
    }

    /**
     * Removes a workflow and its research object bundle
     * @param workflow The workflow to be deleted
     */
    private void removeWorkflow(Workflow workflow) {
        // Delete the Research Object Bundle from disk
        if (workflow.getRoBundlePath() != null) {
            File roBundle = new File(workflow.getRoBundlePath());
            if (roBundle.delete()) {
                logger.debug("Deleted Research Object Bundle");
            } else {
                logger.debug("Failed to delete Research Object Bundle");
            }
        }

        // Delete cached graphviz images if they exist
        graphVizService.deleteCache(workflow.getID());

        // Remove the workflow from the database
        workflowRepository.delete(workflow);

        // Remove any queued repositories pointing to the workflow
        queuedWorkflowRepository.deleteByTempRepresentation_RetrievedFrom(workflow.getRetrievedFrom());
    }

    /**
     * Check for cache expiration based on time and commit sha
     * @param workflow The cached workflow model
     * @return Whether or not there are new commits
     */
    private boolean cacheExpired(Workflow workflow) {
        // If this is a branch and not added by commit ID
        if (!workflow.getRetrievedFrom().getBranch().equals(workflow.getLastCommit())) {
            try {
                // Calculate expiration
                Calendar expireCal = Calendar.getInstance();
                expireCal.setTime(workflow.getRetrievedOn());
                expireCal.add(Calendar.DATE, cacheDays);
                Date expirationDate = expireCal.getTime();

                // Check cached retrievedOn date
                if (expirationDate.before(new Date())) {
                    // Cache expiry time has elapsed
                    // Check current head of the branch with the cached head
                    logger.info("Time has expired for caching, checking commits...");
                    String currentHead;
                    boolean safeToAccess = gitSemaphore.acquire(workflow.getRetrievedFrom().getRepoUrl());
                    try {
                        Git repo = gitService.getRepository(workflow.getRetrievedFrom(), safeToAccess);
                        currentHead = gitService.getCurrentCommitID(repo);
                    } finally {
                        gitSemaphore.release(workflow.getRetrievedFrom().getRepoUrl());
                    }
                    logger.info("Current: " + workflow.getLastCommit() + ", HEAD: " + currentHead);

                    // Reset date in database if there are still no changes
                    boolean expired = !workflow.getLastCommit().equals(currentHead);
                    if (!expired) {
                        workflow.setRetrievedOn(new Date());
                        workflowRepository.save(workflow);
                    }

                    // Return whether the cache has expired
                    return expired;
                }
            } catch(Exception ex){
                // Default to no expiry if there was an API error
                logger.error("API Error when checking for latest commit ID for caching", ex);
            }
        }
        return false;
    }

    public Optional<String> findRawBaseForCommit(String commitId) {
        for (Workflow w : workflowRepository.findByCommit(commitId)) {
            String potentialRaw = w.getRetrievedFrom().getRawUrl(commitId);
            String path = w.getRetrievedFrom().getPath();
            if (potentialRaw.endsWith(path)) {
                return Optional.of(potentialRaw.replace(path, ""));
            }
        }
        // Not found, or not at github.com/gitlab.com
        return Optional.empty();

    }

}


text:
// autotest.c
//
// This file is used in conjunction with autotest_include.h (generated with
// autotest_gen.py) to produce an executable for automatically testing the
// various signal processing algorithms in liquid.

// default include headers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "autotest/autotest.h"

void usage()
{
    // help
    printf("Usage: xautotest [OPTION]\n");
    printf("Execute autotest scripts for liquid-dsp library.\n");
    printf("  -h            display this help and exit\n");
    printf("  -t <id>       run specific test\n");
    printf("  -p <id>       run specific package\n");
    printf("  -r            run all tests, random order\n");
    printf("  -L            lists all scripts\n");
    printf("  -l            lists all packages\n");
    printf("  -x            stop on fail\n");
    printf("  -s <string>   run all tests matching search string\n");
    printf("  -v            verbose\n");
    printf("  -q            quiet\n");
    printf("  -o <filename> output file (json)\n");
}

// define autotest function pointer
typedef void(autotest_function_t) (void);

// define autotest_t
typedef struct {
    unsigned int id;                // test identification
    autotest_function_t * api;      // test function, e.g. autotest_modem()
    const char* name;               // test name
    long unsigned int num_checks;   // number of checks that were run for this test
    long unsigned int num_passed;   // number of checks that passed
    long unsigned int num_failed;   // number of checks that failed
    long unsigned int num_warnings; // number of warnings
    float percent_passed;           // percent of checks that passed
    int executed;                   // was the test executed?
    int pass;                       // did the test pass? (i.e. no failures)
} autotest_t;

// define package_t
typedef struct {
    unsigned int id;            // package identification
    unsigned int index;         // index of first autotest
    unsigned int num_scripts;   // number of tests in package
    const char* name;           // package name
    int executed;               // were any tests executed?
} package_t;

// include auto-generated autotest header
//
// defines the following symbols:
//   #define AUTOSCRIPT_VERSION
//   #define NUM_AUTOSCRIPTS
//   autotest_t scripts[NUM_AUTOSCRIPTS]
//   #define NUM_PACKAGES
//   struct package_t packages[NUM_PACKAGES]
#include "../autotest_include.h"

//
// helper functions:
//

// execute a specific test
void execute_autotest(autotest_t * _test, int _verbose);

// execute a specific package
void execute_package(package_t * _p, int _verbose);

// execute a specific package if string matches
void execute_package_search(package_t * _p, char * _str, int _verbose);

// print all autotest results
void print_autotest_results(autotest_t * _test);

// print the results of a particular package
void print_package_results(package_t * _p);

// print all unstable tests (those which failed or gave warnings)
void print_unstable_tests(void);

// print list of tests
void print_test_list(void);

// print list of packages
void print_package_list(void);

// print basic autotest results to stdout
int export_results(char * _filename);

// main function
int main(int argc, char *argv[])
{
    // options
    enum {RUN_ALL,              // run all tests
          RUN_ALL_RANDOM,       // run all tests (random order)
          RUN_SINGLE_TEST,      // run just a single test
          RUN_SINGLE_PACKAGE,   // run just a single package
          RUN_SEARCH
    } mode = RUN_ALL;

    // set defaults
    unsigned int autotest_id        = 0;
    unsigned int package_id         = 0;
    int          verbose            = 1;
    int          stop_on_fail       = 0;
    int          rseed              = 0;
    char         search_string[128] = "";
    char         filename[256]      = "";

    unsigned int i;

    // get input options
    int d;
    while((d = getopt(argc,argv,"ht:p:rLlxs:vqo:")) != EOF){
        switch (d) {
        case 'h':
            usage();
            return 0;
        case 't':
            autotest_id = atoi(optarg);
            mode = RUN_SINGLE_TEST;
            break;
        case 'p':
            package_id = atoi(optarg);
            mode = RUN_SINGLE_PACKAGE;
            break;
        case 'r':
            mode = RUN_ALL_RANDOM;
            break;
        case 'L':
            // list packages, scripts and exit
            print_test_list();
            return 0;
        case 'l':
            // list only packages and exit
            print_package_list();
            return 0;
        case 'x':
            stop_on_fail = 1;
            break;
        case 's':
            mode = RUN_SEARCH;
            strncpy(search_string, optarg, 128);
            search_string[127] = '\0';
            break;
        case 'v':
            verbose = 1;
            liquid_autotest_verbose = 1;
            break;
        case 'q':
            verbose = 0;
            liquid_autotest_verbose = 0;
            break;
        case 'o':
            strncpy(filename,optarg,255);
            filename[255] = '\0';
            break;
        default:
            return 1;
        }
    }

    // validate results
    if (autotest_id >= NUM_AUTOSCRIPTS) {
        printf("error, cannot run autotest %u; index exceeded\n", autotest_id);
        return -1;
    } else if (package_id >= NUM_PACKAGES) {
        printf("error, cannot run package %u; index exceeded\n", package_id);
        return -1;
    }

    unsigned int n=0;
    switch (mode) {
    case RUN_ALL:
        for (i=0; i<NUM_PACKAGES; i++) {
            execute_package( &packages[i], verbose );

            n++;
            if (stop_on_fail && liquid_autotest_num_failed > 0)
                break;
        }

        for (i=0; i<n; i++) {
            if (verbose)
                print_package_results( &packages[i] );
        }
        break;
    case RUN_ALL_RANDOM:
        // initialize with large random number
        i = (rseed + 8191) % NUM_AUTOSCRIPTS;

        while (n < NUM_AUTOSCRIPTS) {
            i = (i + 524287) % NUM_AUTOSCRIPTS;
            while (scripts[i].executed) {
                i++;
                if (i >= NUM_AUTOSCRIPTS)
                    i %= NUM_AUTOSCRIPTS;
            }

            printf("executing test %4u (%4u / %4u)\n", i, n+1, NUM_AUTOSCRIPTS);
            execute_autotest( &scripts[i], verbose );

            n++;
            if (stop_on_fail && liquid_autotest_num_failed > 0)
                break;
        }

        for (i=0; i<n; i++) {
            if (verbose)
                print_autotest_results( &scripts[i] );
        }
        break;
    case RUN_SINGLE_TEST:
        execute_autotest( &scripts[autotest_id], verbose );
        if (verbose)
            print_autotest_results( &scripts[autotest_id] );
        break;
    case RUN_SINGLE_PACKAGE:
        execute_package( &packages[package_id], verbose );
        if (verbose)
            print_package_results( &packages[package_id] );
        break;
    case RUN_SEARCH:
        printf("running all scripts matching '%s'...\n", search_string);

        // search all packages
        for (i=0; i<NUM_PACKAGES; i++)
            execute_package_search( &packages[i], search_string, verbose);

        // print results
        for (i=0; i<NUM_PACKAGES; i++) {
            if (verbose && packages[i].executed)
                print_package_results( &packages[i] );
        }
        break;
    }

    if (liquid_autotest_verbose)
        print_unstable_tests();

    autotest_print_results();

    // export results
    if (strcmp(filename,"")!=0)
        export_results(filename);

    return 0;
}

// execute a specific autotest
//  _test       :   pointer to autotest object
//  _verbose    :   verbose output flag
void execute_autotest(autotest_t * _test,
                      int _verbose)
{
    unsigned long int autotest_num_passed_init = liquid_autotest_num_passed;
    unsigned long int autotest_num_failed_init = liquid_autotest_num_failed;
    unsigned long int autotest_num_warnings_init = liquid_autotest_num_warnings;

    // execute test
    _test->api();

    _test->num_passed = liquid_autotest_num_passed - autotest_num_passed_init;
    _test->num_failed = liquid_autotest_num_failed - autotest_num_failed_init;
    _test->num_warnings = liquid_autotest_num_warnings - autotest_num_warnings_init;
    _test->num_checks = _test->num_passed + _test->num_failed;
    _test->pass = (_test->num_failed==0) ? 1 : 0;
    if (_test->num_checks > 0)
        _test->percent_passed = 100.0f * (float) (_test->num_passed) / (float) (_test->num_checks);
    else
        _test->percent_passed = 0.0f;

    _test->executed = 1;

    //if (_verbose)
    //    print_autotest_results(_test);
}

// execute a specific package
//  _p          :   pointer to package object
//  _verbose    :   verbose output flag
void execute_package(package_t * _p,
                     int _verbose)
{
    if (_verbose)
        printf("%u: %s\n", _p->id, _p->name);

    unsigned int i;
    for (i=0; i<_p->num_scripts; i++) {
        execute_autotest( &scripts[ i + _p->index ], _verbose );
    }

    _p->executed = 1;
}

// execute a specific package if string matches
void execute_package_search(package_t * _p, char * _str, int _verbose)
{
    // see if search string matches autotest name
    if (strstr(_p->name, _str) != NULL) {
        // run the package
        execute_package(_p, _verbose);
    } else {

        unsigned int i;
        unsigned int i0 = _p->index;
        unsigned int i1 = _p->num_scripts + i0;
        for (i=i0; i<i1; i++) {
            // see if search string matches autotest name
            if (strstr(scripts[i].name, _str) != NULL) {
                // run the autotest
                execute_autotest( &scripts[i], _verbose );
                _p->executed = 1;
            }
        }
    }
}

// print results of a particular test
void print_autotest_results(autotest_t * _test)
{
    if (!_test->executed)
        printf("    %3u :   IGNORED ", _test->id);
    else if (_test->pass)
        printf("    %3u :   PASS    ", _test->id);
    else
        printf("    %3u : <<FAIL>>  ", _test->id);

    printf("passed %4lu / %4lu checks (%5.1f%%) : %s\n",
            _test->num_passed,
            _test->num_checks,
            _test->percent_passed,
            _test->name);
}

// print results of a particular package
void print_package_results(package_t * _p)
{
    unsigned int i;
    printf("%u: %s:\n", _p->id, _p->name);
    for (i=_p->index; i<(_p->index+_p->num_scripts); i++) {
        //if ( scripts[i].executed ) // only print scripts that were executed
        print_autotest_results( &scripts[i] );
    }

    printf("\n");
}

// print all unstable tests (those which failed or gave warnings)
void print_unstable_tests(void)
{
    if (liquid_autotest_num_failed == 0 &&
        liquid_autotest_num_warnings == 0)
    {
        return;
    }

    printf("==================================\n");
    printf(" UNSTABLE TESTS:\n");
    unsigned int t;
    for (t=0; t<NUM_AUTOSCRIPTS; t++) {
        if (scripts[t].executed) {
            if (!scripts[t].pass) {
                printf("    %3u : <<FAIL>> %s\n", scripts[t].id,
                                                  scripts[t].name);
            }

            if (scripts[t].num_warnings > 0) {
                printf("    %3u : %4lu warnings %s\n", scripts[t].id,
                                                       scripts[t].num_warnings,
                                                       scripts[t].name);
            }
        }
    }
}

void print_test_list(void)
{
    unsigned int i;
    unsigned int j;
    for (i=0; i<NUM_PACKAGES; i++) {
        printf("%u: %s\n", packages[i].id, packages[i].name);
        for (j=packages[i].index; j<packages[i].num_scripts+packages[i].index; j++)
            printf("    %u: %s\n", scripts[j].id, scripts[j].name);
    }
}

void print_package_list(void)
{
    unsigned int i;
    for (i=0; i<NUM_PACKAGES; i++)
        printf("%u: %s\n", packages[i].id, packages[i].name);
}

// print basic autotest results to stdout
int export_results(char * _filename)
{
    // try to open file for writing
    FILE * fid = fopen(_filename,"w");
    if (!fid) {
        fprintf(stderr,"error: export_results(), could not open '%s' for writing\n", _filename);
        return -1;
    }

    // print header
    fprintf(fid,"{\n");
    fprintf(fid,"  \"build-info\" : {\n");
    fprintf(fid,"  },\n");
    fprintf(fid,"  \"tests\" : [\n");

    // print each individual test as opposed to package
    unsigned int i;
    for (i=0; i<NUM_AUTOSCRIPTS; i++) {
        fprintf(fid,"    {\"id\":%3u, \"pass\":%s, \"num_checks\":%4u, \"num_passed\":%4u, \"name\":\"%s\"}%s\n",
                scripts[i].id,
                scripts[i].num_failed == 0 ? "true" : "false",
                scripts[i].num_checks,
                scripts[i].num_passed,
                scripts[i].name,
                i==NUM_AUTOSCRIPTS-1 ? "" : ",");
    }

    fprintf(fid,"  ]\n");
    fprintf(fid,"}\n");
    fclose(fid);

    if (liquid_autotest_verbose)
        printf("output .json results written to %s\n", _filename);

    // everything is fine
    return 0;
}


text:
package org.apache.flink.table.expressions

import org.apache.calcite.rex.RexNode
import org.apache.calcite.tools.RelBuilder
import org.apache.flink.api.common.typeinfo.{SqlTimeTypeInfo, TypeInformation}
import org.apache.flink.table.calcite.FlinkRelBuilder
import FlinkRelBuilder.NamedWindowProperty
import org.apache.flink.table.validate.{ValidationFailure, ValidationSuccess}

trait WindowProperty {

  def toNamedWindowProperty(name: String): NamedWindowProperty

  def resultType: TypeInformation[_]

}

abstract class AbstractWindowProperty(child: PlannerExpression)
  extends UnaryExpression
  with WindowProperty {

  override def toString = s"WindowProperty($child)"

  override private[flink] def toRexNode(implicit relBuilder: RelBuilder): RexNode =
    throw new UnsupportedOperationException("WindowProperty cannot be transformed to RexNode.")

  override private[flink] def validateInput() =
    if (child.isInstanceOf[WindowReference]) {
      ValidationSuccess
    } else {
      ValidationFailure("Child must be a window reference.")
    }

  def toNamedWindowProperty(name: String): NamedWindowProperty = NamedWindowProperty(name, this)
}

case class WindowStart(child: PlannerExpression) extends AbstractWindowProperty(child) {

  override def resultType = SqlTimeTypeInfo.TIMESTAMP

  override def toString: String = s"start($child)"
}

case class WindowEnd(child: PlannerExpression) extends AbstractWindowProperty(child) {

  override def resultType = SqlTimeTypeInfo.TIMESTAMP

  override def toString: String = s"end($child)"
}


text:
package factory

import (
	"errors"
	"strings"
	"testing"
	"time"

	kutil "github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	buildapi "github.com/openshift/origin/pkg/build/api"
	controller "github.com/openshift/origin/pkg/controller"
)

type buildUpdater struct {
	Build *buildapi.Build
}

func (b *buildUpdater) Update(namespace string, build *buildapi.Build) error {
	b.Build = build
	return nil
}

func TestLimitedLogAndRetryFinish(t *testing.T) {
	updater := &buildUpdater{}
	err := errors.New("funky error")

	now := kutil.Now()
	retry := controller.Retry{0, kutil.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute()-31, now.Second(), now.Nanosecond(), now.Location())}
	if limitedLogAndRetry(updater, 30*time.Minute)(&buildapi.Build{Status: buildapi.BuildStatus{Phase: buildapi.BuildPhaseNew}}, err, retry) {
		t.Error("Expected no more retries after reaching timeout!")
	}
	if updater.Build == nil {
		t.Fatal("BuildUpdater wasn't called!")
	}
	if updater.Build.Status.Phase != buildapi.BuildPhaseFailed {
		t.Errorf("Expected status %s, got %s!", buildapi.BuildPhaseFailed, updater.Build.Status.Phase)
	}
	if !strings.Contains(updater.Build.Status.Message, err.Error()) {
		t.Errorf("Expected message to contain %v, got %s!", err.Error(), updater.Build.Status.Message)
	}
	if updater.Build.Status.CompletionTimestamp == nil {
		t.Error("Expected CompletionTimestamp to be set!")
	}
}

func TestLimitedLogAndRetryProcessing(t *testing.T) {
	updater := &buildUpdater{}
	err := errors.New("funky error")

	now := kutil.Now()
	retry := controller.Retry{0, kutil.Date(now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute()-10, now.Second(), now.Nanosecond(), now.Location())}
	if !limitedLogAndRetry(updater, 30*time.Minute)(&buildapi.Build{Status: buildapi.BuildStatus{Phase: buildapi.BuildPhaseNew}}, err, retry) {
		t.Error("Expected more retries!")
	}
	if updater.Build != nil {
		t.Fatal("BuildUpdater shouldn't be called!")
	}
}


text:
package core

import (
	"fmt"
	"sort"
	"strings"

	"github.com/pingcap/parser/ast"
	"github.com/pingcap/parser/model"
	"github.com/pingcap/tidb/expression"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/util/ranger"
	"github.com/pingcap/tidb/util/set"
)

// AggregateFuncExtractor visits Expr tree.
// It converts ColunmNameExpr to AggregateFuncExpr and collects AggregateFuncExpr.
type AggregateFuncExtractor struct {
	inAggregateFuncExpr bool
	// AggFuncs is the collected AggregateFuncExprs.
	AggFuncs []*ast.AggregateFuncExpr
}

// Enter implements Visitor interface.
func (a *AggregateFuncExtractor) Enter(n ast.Node) (ast.Node, bool) {
	switch n.(type) {
	case *ast.AggregateFuncExpr:
		a.inAggregateFuncExpr = true
	case *ast.SelectStmt, *ast.SetOprStmt:
		return n, true
	}
	return n, false
}

// Leave implements Visitor interface.
func (a *AggregateFuncExtractor) Leave(n ast.Node) (ast.Node, bool) {
	switch v := n.(type) {
	case *ast.AggregateFuncExpr:
		a.inAggregateFuncExpr = false
		a.AggFuncs = append(a.AggFuncs, v)
	}
	return n, true
}

// WindowFuncExtractor visits Expr tree.
// It converts ColunmNameExpr to WindowFuncExpr and collects WindowFuncExpr.
type WindowFuncExtractor struct {
	// WindowFuncs is the collected WindowFuncExprs.
	windowFuncs []*ast.WindowFuncExpr
}

// Enter implements Visitor interface.
func (a *WindowFuncExtractor) Enter(n ast.Node) (ast.Node, bool) {
	switch n.(type) {
	case *ast.SelectStmt, *ast.SetOprStmt:
		return n, true
	}
	return n, false
}

// Leave implements Visitor interface.
func (a *WindowFuncExtractor) Leave(n ast.Node) (ast.Node, bool) {
	switch v := n.(type) {
	case *ast.WindowFuncExpr:
		a.windowFuncs = append(a.windowFuncs, v)
	}
	return n, true
}

// logicalSchemaProducer stores the schema for the logical plans who can produce schema directly.
type logicalSchemaProducer struct {
	schema *expression.Schema
	names  types.NameSlice
	baseLogicalPlan
}

// Schema implements the Plan.Schema interface.
func (s *logicalSchemaProducer) Schema() *expression.Schema {
	if s.schema == nil {
		if len(s.Children()) == 1 {
			// default implementation for plans has only one child: proprgate child schema.
			// multi-children plans are likely to have particular implementation.
			s.schema = s.Children()[0].Schema().Clone()
		} else {
			s.schema = expression.NewSchema()
		}
	}
	return s.schema
}

func (s *logicalSchemaProducer) OutputNames() types.NameSlice {
	if s.names == nil && len(s.Children()) == 1 {
		// default implementation for plans has only one child: proprgate child `OutputNames`.
		// multi-children plans are likely to have particular implementation.
		s.names = s.Children()[0].OutputNames()
	}
	return s.names
}

func (s *logicalSchemaProducer) SetOutputNames(names types.NameSlice) {
	s.names = names
}

// SetSchema implements the Plan.SetSchema interface.
func (s *logicalSchemaProducer) SetSchema(schema *expression.Schema) {
	s.schema = schema
}

func (s *logicalSchemaProducer) setSchemaAndNames(schema *expression.Schema, names types.NameSlice) {
	s.schema = schema
	s.names = names
}

// inlineProjection prunes unneeded columns inline a executor.
func (s *logicalSchemaProducer) inlineProjection(parentUsedCols []*expression.Column) {
	used := expression.GetUsedList(parentUsedCols, s.Schema())
	for i := len(used) - 1; i >= 0; i-- {
		if !used[i] {
			s.schema.Columns = append(s.Schema().Columns[:i], s.Schema().Columns[i+1:]...)
		}
	}
}

// physicalSchemaProducer stores the schema for the physical plans who can produce schema directly.
type physicalSchemaProducer struct {
	schema *expression.Schema
	basePhysicalPlan
}

func (s *physicalSchemaProducer) cloneWithSelf(newSelf PhysicalPlan) (*physicalSchemaProducer, error) {
	base, err := s.basePhysicalPlan.cloneWithSelf(newSelf)
	if err != nil {
		return nil, err
	}
	return &physicalSchemaProducer{
		basePhysicalPlan: *base,
		schema:           s.Schema().Clone(),
	}, nil
}

// Schema implements the Plan.Schema interface.
func (s *physicalSchemaProducer) Schema() *expression.Schema {
	if s.schema == nil {
		if len(s.Children()) == 1 {
			// default implementation for plans has only one child: proprgate child schema.
			// multi-children plans are likely to have particular implementation.
			s.schema = s.Children()[0].Schema().Clone()
		} else {
			s.schema = expression.NewSchema()
		}
	}
	return s.schema
}

// SetSchema implements the Plan.SetSchema interface.
func (s *physicalSchemaProducer) SetSchema(schema *expression.Schema) {
	s.schema = schema
}

// baseSchemaProducer stores the schema for the base plans who can produce schema directly.
type baseSchemaProducer struct {
	schema *expression.Schema
	names  types.NameSlice
	basePlan
}

// OutputNames returns the outputting names of each column.
func (s *baseSchemaProducer) OutputNames() types.NameSlice {
	return s.names
}

func (s *baseSchemaProducer) SetOutputNames(names types.NameSlice) {
	s.names = names
}

// Schema implements the Plan.Schema interface.
func (s *baseSchemaProducer) Schema() *expression.Schema {
	if s.schema == nil {
		s.schema = expression.NewSchema()
	}
	return s.schema
}

// SetSchema implements the Plan.SetSchema interface.
func (s *baseSchemaProducer) SetSchema(schema *expression.Schema) {
	s.schema = schema
}

func (s *baseSchemaProducer) setSchemaAndNames(schema *expression.Schema, names types.NameSlice) {
	s.schema = schema
	s.names = names
}

// Schema implements the Plan.Schema interface.
func (p *LogicalMaxOneRow) Schema() *expression.Schema {
	s := p.Children()[0].Schema().Clone()
	resetNotNullFlag(s, 0, s.Len())
	return s
}

func buildLogicalJoinSchema(joinType JoinType, join LogicalPlan) *expression.Schema {
	leftSchema := join.Children()[0].Schema()
	switch joinType {
	case SemiJoin, AntiSemiJoin:
		return leftSchema.Clone()
	case LeftOuterSemiJoin, AntiLeftOuterSemiJoin:
		newSchema := leftSchema.Clone()
		newSchema.Append(join.Schema().Columns[join.Schema().Len()-1])
		return newSchema
	}
	newSchema := expression.MergeSchema(leftSchema, join.Children()[1].Schema())
	if joinType == LeftOuterJoin {
		resetNotNullFlag(newSchema, leftSchema.Len(), newSchema.Len())
	} else if joinType == RightOuterJoin {
		resetNotNullFlag(newSchema, 0, leftSchema.Len())
	}
	return newSchema
}

// BuildPhysicalJoinSchema builds the schema of PhysicalJoin from it's children's schema.
func BuildPhysicalJoinSchema(joinType JoinType, join PhysicalPlan) *expression.Schema {
	switch joinType {
	case SemiJoin, AntiSemiJoin:
		return join.Children()[0].Schema().Clone()
	case LeftOuterSemiJoin, AntiLeftOuterSemiJoin:
		newSchema := join.Children()[0].Schema().Clone()
		newSchema.Append(join.Schema().Columns[join.Schema().Len()-1])
		return newSchema
	}
	return expression.MergeSchema(join.Children()[0].Schema(), join.Children()[1].Schema())
}

// GetStatsInfo gets the statistics info from a physical plan tree.
func GetStatsInfo(i interface{}) map[string]uint64 {
	if i == nil {
		// it's a workaround for https://github.com/pingcap/tidb/issues/17419
		// To entirely fix this, uncomment the assertion in TestPreparedIssue17419
		return nil
	}
	p := i.(Plan)
	var physicalPlan PhysicalPlan
	switch x := p.(type) {
	case *Insert:
		physicalPlan = x.SelectPlan
	case *Update:
		physicalPlan = x.SelectPlan
	case *Delete:
		physicalPlan = x.SelectPlan
	case PhysicalPlan:
		physicalPlan = x
	}

	if physicalPlan == nil {
		return nil
	}

	statsInfos := make(map[string]uint64)
	statsInfos = CollectPlanStatsVersion(physicalPlan, statsInfos)
	return statsInfos
}

// extractStringFromStringSet helps extract string info from set.StringSet
func extractStringFromStringSet(set set.StringSet) string {
	if len(set) < 1 {
		return ""
	}
	l := make([]string, 0, len(set))
	for k := range set {
		l = append(l, fmt.Sprintf(`"%s"`, k))
	}
	sort.Strings(l)
	return fmt.Sprintf("%s", strings.Join(l, ","))
}

func tableHasDirtyContent(ctx sessionctx.Context, tableInfo *model.TableInfo) bool {
	pi := tableInfo.GetPartitionInfo()
	if pi == nil {
		return ctx.HasDirtyContent(tableInfo.ID)
	}
	// Currently, we add UnionScan on every partition even though only one partition's data is changed.
	// This is limited by current implementation of Partition Prune. It'll be updated once we modify that part.
	for _, partition := range pi.Definitions {
		if ctx.HasDirtyContent(partition.ID) {
			return true
		}
	}
	return false
}

func cloneExprs(exprs []expression.Expression) []expression.Expression {
	cloned := make([]expression.Expression, 0, len(exprs))
	for _, e := range exprs {
		cloned = append(cloned, e.Clone())
	}
	return cloned
}

func cloneCols(cols []*expression.Column) []*expression.Column {
	cloned := make([]*expression.Column, 0, len(cols))
	for _, c := range cols {
		cloned = append(cloned, c.Clone().(*expression.Column))
	}
	return cloned
}

func cloneColInfos(cols []*model.ColumnInfo) []*model.ColumnInfo {
	cloned := make([]*model.ColumnInfo, 0, len(cols))
	for _, c := range cols {
		cloned = append(cloned, c.Clone())
	}
	return cloned
}

func cloneRanges(ranges []*ranger.Range) []*ranger.Range {
	cloned := make([]*ranger.Range, 0, len(ranges))
	for _, r := range ranges {
		cloned = append(cloned, r.Clone())
	}
	return cloned
}

func clonePhysicalPlan(plans []PhysicalPlan) ([]PhysicalPlan, error) {
	cloned := make([]PhysicalPlan, 0, len(plans))
	for _, p := range plans {
		c, err := p.Clone()
		if err != nil {
			return nil, err
		}
		cloned = append(cloned, c)
	}
	return cloned, nil
}


text:
package com.pivotal.gemfirexd;

/**
 * List of GemFireXD constants that is used other than {@link Attribute} and
 * {@link Property}.
 *
 * @author soubhikc
 */
// if renamed, messages.xml should also be adjusted accordingly.
public interface Constants {

  /**
   * Possible values of GEMFIREXD-PROPERTIES property keys.
   *

   * Keys are case-sensitive and enumeration.name() method should be used for
   * appropriate key strings.
   *
   * @author soubhikc
   */
  // if renamed, messages.xml should also be adjusted accordingly.
  public static enum QueryHints {

    /**
     * To override default optimizer's choice of join strategy.
     *

     * Possible values NESTEDLOOP or HASH
     *
     *

     * This can be FROM clause as well as table optimizer hint, in other words, this can be
     * mentioned between FROM clause and the first table name or after each table name.
     *
     *

     * examples:

     *  SELECT a, b FROM -- GEMFIREXD-PROPERTIES joinStrategy=HASH \n userTable1
     * t1, userTable2 t2 WHERE t1.col1 = t2.col1
     *

     *  SELECT a, b FROM userTable1
     * t1 -- GEMFIREXD-PROPERTIES joinStrategy=HASH \n, userTable2 t2 WHERE t1.col1 = t2.col1
     *
     */
    joinStrategy,

    /**
     * Query Hint to override optimizer's choice of ordering tables. Typically
     * used in conjunction with {@link #joinStrategy}.
     *
     *

     * Possible values are FIXED or UNFIXED, where FIXED will ensure ordering of
     * the tables as appeared in the FROM list.
     *
     *

     * This can only be used with FROM clause, in other words, this can only be
     * mentioned between FROM clause and the first table name.
     *
     *

     * example:

     *  SELECT a, b FROM -- GEMFIREXD-PROPERTIES joinOrder=FIXED \n userTable1
     * t1, userTable2 t2 -- GEMFIREXD-PROPERTIES joinStrategy=HASH \n WHERE t1.col1 = t2.col1
     *
     */
    joinOrder,

    /**
     * Query Hint to force usage of any particular index.
     *
     *

     * Possible values are unqualified index name or NULL
     * indicating table scan.
     *
     *

     * This can only be used within TableExpression and only on base tables.
     * Cannot be specified for views or derived tables.
     */
    index,

    /**
     * Query Hint to force usage of index enforcing a particular constraint.
     * This is similar to {@link #index} property but index is used via
     * constraint name.
     *
     *

     * Possible values are unqualified constraint name of primary key, foreign
     * key or unique constraint.
     *
     *

     * This can only be used within TableExpression and only on base tables.
     */
    constraint,

    hashInitialCapacity,

    hashLoadFactor,

    hashMaxCapacity,

    bulkFetch,

    /**
     * Query Hint to indicate inclusion of secondary buckets of partitioned
     * tables while joining with virtual tables.
     *
     *

     * If true, partitioned table's secondary bucket will be
     * considered for routing and scanning while performing the join with
     * virtual table output.
     *
     *

     * This can only be used on base tables or virtual tables.
     *
     *

     * example:

     *  SELECT dsid(), count(1) from sys.members , userPartitionedTable t1
     * -- GEMFIREXD-PROPERTIES withSecondaries=true \n GROUP BY dsid()
     *
     *
     * Following query will return Entry Size/Value Size for primary buckets
     * only.
     * SELECT * FROM sys.memoryAnalytics -- GEMFIREXD-PROPERTIES withSecondaries=false \n
     *
     */
    withSecondaries,

    /**
     * Query Hint to alias an user query that will be shown in Visual Statistics
     * Display (VSD) instead of system generated statement alias.
     *
     *

     * This can only be used in FROM clause i.e. immediately after the FROM
     * clause and before the table name. WhiteSpace characters are not allowed
     * as word separator.
     *
     *

     * example:

     *
     * SELECT * FROM -- GEMFIREXD-PROPERTIES statementAlias=My_QUERY \n userTable t1
     * -- GEMFIREXD-PROPERTIES index=IDX_COL1 \n WHERE t1.col1 is not null
     *
     */
    statementAlias,

    /**
     * Query hint to specify whether to query HDFS data.
     *
     *

     * Possible values are 'true' or 'false'.
     *
     *

     * This can only be used as a table optimizer hint i.e. can only be specified
     * immediately after each table name.
     *
     *

     * example:

     * SELECT * FROM userTable t1 -- GEMFIREXD-PROPERTIES queryHDFS=true \n
     *  WHERE t1.col1 is not null
     */
    queryHDFS,

    /**
     * Query hint to specify the execution engine for the query.
     *
     *

     * Possible values are 'Spark' or 'Store'.
     *
     *

     * This can only be used with FROM clause, in other words, this can only be
     * mentioned between FROM clause and the first table name.
     *
     *

     * example:

     * SELECT * FROM userTable t1 -- GEMFIREXD-PROPERTIES executionEngine=Spark \n
     *  WHERE t1.col1 is not null
     */
    executionEngine,

    /**
     * Memory Analytics sizer query hints.
     *
     * @see SizerHints
     */
    sizerHints;

    /**
     * SizerHint constant values which can be passed comma separated.
     *

     * example:

     *
     *   SELECT * FROM sys.memoryAnalytics -- GEMFIREXD-PROPERTIES sizerHints=withMemoryFootPrint \n
     *
     *

     * jdbc example:

     *

     *
     *   java.sql.Statement st = conn.createStatement();
     *   StringBuilder sb = new StringBuilder("SELECT * FROM sys.memoryAnalytics -- GEMFIREXD-PROPERTIES sizerHints=");
     *   sb.append(com.pivotal.gemfirexd.Constants.QueryHints.SizerHints.withMemoryFootPrint.name());
     *   sb.append("\n");
     *   java.sql.ResultSet rs = st.executeQuery(sb.toString());
     *   while(rs.next()) {
     *     System.out.println(rs.getObject(1));
     *   }

     *
     *

     * @author soubhikc
     */
    // if renamed, messages.xml should also be adjusted accordingly.
    // TODO add other parameters , logObjectReferenceGraph, logTopConsumers, traceOutput, traceVerbose
    public static enum SizerHints {
      withMemoryFootPrint,
      logObjectReferenceGraph,
      logTopConsumers,
      traceOutput,
      traceVerbose
    }
  }

  public static final String LDAP_LOCAL_USER_DN = "gemfirexd.user";

  public static final String LDAP_SEARCH_FILTER_USERNAME = "%USERNAME%";

  /**
   * Prefix used for user names internally when granting privileges to those
   * coming from LDAP groups.
   */
  public static final String LDAP_GROUP_PREFIX = "LDAPGROUP:";

  /**
   * The token for the LDAP group name provided in custom LDAP group search
   * filter specification.
   */
  public static final String LDAP_SEARCH_FILTER_GROUP = "%GROUP%";

  /**
   * Property value to AUTH_PROVIDER or to SERVER_AUTH_PROVIDER for enabling
   * BUILTIN scheme.
   *
   */
  String AUTHENTICATION_PROVIDER_BUILTIN = "BUILTIN";

  /**
   * Property value to AUTH_PROVIDER or to SERVER_AUTH_PROVIDER for enabling
   * LDAP scheme.

   *

   *
   * Verifying LDAP server can be configured by setting
   * {@link com.pivotal.gemfirexd.Property#AUTH_LDAP_SERVER ldapserver} property.
   *
   */
  String AUTHENTICATION_PROVIDER_LDAP = "LDAP";

  /**
   * The security mechanism to use when starting network server to impose policy
   * for client connections.
   *

   * Security mechanism options are:
   *

   *
USER_ONLY_SECURITY
   *
CLEAR_TEXT_PASSWORD_SECURITY
   *
ENCRYPTED_PASSWORD_SECURITY
   *
ENCRYPTED_USER_AND_PASSWORD_SECURITY
   *
STRONG_PASSWORD_SUBSTITUTE_SECURITY
   *

   * The default security mechanism is USER_ONLY SECURITY
   *

   * If the application specifies a security mechanism then it will be the only
   * one attempted. If the specified security mechanism is not supported by the
   * conversation then an exception will be thrown and there will be no
   * additional retries.
   *

   * Both user and password need to be set for all security mechanism except
   * USER_ONLY_SECURITY
   */
  public static enum SecurityMechanism {
    /**
     * SECMEC_USRIDONL = 4
     *

     * Only user id is required.
     */
    USER_ONLY_SECURITY,
    /**
     * SECMEC_USRIDPWD = 3
     *

     * Both user id and password are required. password is in clear text.
     */
    CLEAR_TEXT_PASSWORD_SECURITY,
    /**
     * SECMEC_EUSRIDPWD = 9
     *

     * both password and user are encrypted
     */
    ENCRYPTED_USER_AND_PASSWORD_SECURITY,
    /**
     * SECMEC_USRSSBPWD = 8
     *

     * Password substitute is to be used.
     */
    STRONG_PASSWORD_SUBSTITUTE_SECURITY;
  };
}


text:
namespace FarmAutomation.Common
{
    public enum ItemQuality
    {
        Low = 0,
        Medium = 1,
        High = 2
    }
}


text:
package org.artifactory.storage.db.build.entity;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import org.apache.commons.lang.StringUtils;

import java.util.Collection;

/**
 * Date: 10/30/12
 * Time: 12:21 PM
 *
 * @author freds
 */
public class BuildEntity {
    private final long buildId;
    private final String buildName;
    private final String buildNumber;
    private final long buildDate;
    private final String ciUrl;
    private final long created;
    private final String createdBy;
    private final long modified;
    private final String modifiedBy;

    /**
     * Initialized as null, and can (and should) be set only once
     */
    private ImmutableSet<BuildProperty> properties = null;

    /**
     * Initialized as null, and can (and should) be set only once
     */
    private ImmutableSortedSet<BuildPromotionStatus> promotions = null;

    public BuildEntity(long buildId, String buildName, String buildNumber, long buildDate, String ciUrl, long created,
            String createdBy, long modified, String modifiedBy) {
        if (buildId <= 0L) {
            throw new IllegalArgumentException("Build id cannot be zero or negative!");
        }
        if (StringUtils.isBlank(buildName) || StringUtils.isBlank(buildNumber) || buildDate <= 0L) {
            throw new IllegalArgumentException("Build name, number and date cannot be empty or null!");
        }
        if (created <= 0L) {
            throw new IllegalArgumentException("Created date cannot be zero or negative!");
        }
        this.buildId = buildId;
        this.buildName = buildName;
        this.buildNumber = buildNumber;
        this.buildDate = buildDate;
        this.ciUrl = ciUrl;
        this.created = created;
        this.createdBy = createdBy;
        this.modified = modified;
        this.modifiedBy = modifiedBy;
    }

    public long getBuildId() {
        return buildId;
    }

    public String getBuildName() {
        return buildName;
    }

    public String getBuildNumber() {
        return buildNumber;
    }

    public long getBuildDate() {
        return buildDate;
    }

    public String getCiUrl() {
        return ciUrl;
    }

    public long getCreated() {
        return created;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public long getModified() {
        return modified;
    }

    public String getModifiedBy() {
        return modifiedBy;
    }

    public ImmutableSortedSet<BuildPromotionStatus> getPromotions() {
        if (promotions == null) {
            throw new IllegalStateException("Build object was not initialized correctly! Promotions missing.");
        }
        return promotions;
    }

    public void setPromotions(Collection<BuildPromotionStatus> promotions) {
        if (this.promotions != null) {
            throw new IllegalStateException("Cannot set Promotions already set!");
        }
        if (promotions == null) {
            throw new IllegalArgumentException("Cannot set promotions to null");
        }
        this.promotions = ImmutableSortedSet.copyOf(promotions);
    }

    public ImmutableSet<BuildProperty> getProperties() {
        if (properties == null) {
            throw new IllegalStateException("Build object was not initialized correctly! Properties missing.");
        }
        return properties;
    }

    public void setProperties(Collection<BuildProperty> properties) {
        if (this.properties != null) {
            throw new IllegalStateException("Cannot set Properties already set!");
        }
        if (properties == null) {
            throw new IllegalArgumentException("Cannot set properties to null");
        }
        this.properties = ImmutableSet.copyOf(properties);
    }

    public boolean isIdentical(BuildEntity b) {
        ImmutableSet<BuildProperty> oprops = b.getProperties();
        if (oprops.size() != getProperties().size()) {
            return false;
        }
        for (BuildProperty prop : properties) {
            boolean foundIdentical = false;
            for (BuildProperty oprop : oprops) {
                if (oprop.isIdentical(prop)) {
                    foundIdentical = true;
                }
            }
            if (!foundIdentical) {
                return false;
            }
        }
        return Objects.equal(promotions, b.promotions)
                && StringUtils.equals(buildName, b.buildName)
                && StringUtils.equals(buildNumber, b.buildNumber)
                && buildDate == b.buildDate
                && StringUtils.equals(ciUrl, b.ciUrl)
                && created == b.created
                && StringUtils.equals(createdBy, b.createdBy)
                && modified == b.modified
                && StringUtils.equals(modifiedBy, b.modifiedBy);
    }
}


text:
@font-face {
    font-family: 'meridan_custom';
    src:url('../fonts/meridan_custom.eot?nc34o9');
    src:url('../fonts/meridan_custom.eot?#iefixnc34o9') format('embedded-opentype'),
    url('../fonts/meridan_custom.woff?nc34o9') format('woff'),
    url('../fonts/meridan_custom.ttf?nc34o9') format('truetype'),
    url('../fonts/meridan_custom.svg?nc34o9#meridan_custom') format('svg');
    font-weight: normal;
    font-style: normal;
}

[class^="iconM-"], [class*=" iconM-"] {
    font-family: 'meridan_custom';
    speak: none;
    font-style: normal;
    font-weight: normal;
    font-variant: normal;
    text-transform: none;
    line-height: 1;

    /* Better Font Rendering =========== */
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.iconM-download:before {
    content: "\e600";
}

.iconM-upload:before {
    content: "\e601";
    font-size:17px;
}
.iconM-jump:before {
    content: "\e602";
    font-size:17px;
}


text:
{% if security.vote('IS_AUTHENTICATED_FULLY') %}
  Logged in as {{ security.user }} Log Out
{% else %}
  Log In
{% endif %}


text:
A CLI utility for posting to http://littlelogs.co

## Install

`npm install littlelogger-cli -g`

## Usage

```
  Update LittleLogs timeline.

  Usage:

  littlelogger <command | message> [ <options> ].

  Commands:

  init - use to configure littlelogger.

  'Options:

  -m, --message    The message you wish to send to LittleLogs.
                   Must be less than 250 characters!
  -h, --help       Show this help.
  -v, --version    Show littlelogger version.
```

## License

MIT


text:
function dummy() {
  console.log('hello world!');
}


text: angular.module('myModule', ['lib.mod1', 'lib.mod2']);


text:
package org.projectodd.wunderboss.messaging.jms;

import org.projectodd.wunderboss.Options;
import org.projectodd.wunderboss.codecs.Codecs;
import org.projectodd.wunderboss.messaging.Context;
import org.projectodd.wunderboss.messaging.Listener;
import org.projectodd.wunderboss.messaging.MessageHandler;
import org.projectodd.wunderboss.messaging.Messaging;
import org.projectodd.wunderboss.messaging.Topic;

import javax.jms.Destination;
import javax.jms.TopicSubscriber;
import java.util.HashMap;
import java.util.Map;

public class JMSTopic extends JMSDestination implements Topic {

    public JMSTopic(String name, Destination destination, JMSMessagingSkeleton broker) {
        super(name, destination, broker);
    }

    @Override
    public Listener subscribe(final String id, final MessageHandler handler,
                              final Codecs codecs,
                              final Map<SubscribeOption, Object> options) throws Exception {
        Options<SubscribeOption> opts = new Options<>(options);
        final JMSSpecificContext context = (JMSSpecificContext)context(id, opts.get(SubscribeOption.CONTEXT));
        final TopicSubscriber subscriber = context
                .jmsSession()
                .createDurableSubscriber((javax.jms.Topic) jmsDestination(),
                                         id,
                                         opts.getString(SubscribeOption.SELECTOR), false);

        final Listener listener = new JMSListener(handler,
                                                  codecs,
                                                  this,
                                                  context,
                                                  subscriber).start();

        Context parent = (Context)opts.get(SubscribeOption.CONTEXT);
        if (parent != null) {
            parent.addCloseable(listener);
        }

        broker().addCloseableForDestination(this, listener);

        return new Listener() {
            @Override
            public void close() throws Exception {
                listener.close();
                context.close();
            }
        };
    }

    @Override
    public void unsubscribe(String id, Map<UnsubscribeOption, Object> options) throws Exception {
        final Options<UnsubscribeOption> opts = new Options<>(options);
        try (JMSSpecificContext context = (JMSSpecificContext)context(id, opts.get(UnsubscribeOption.CONTEXT))) {
            context.jmsSession().unsubscribe(id);
        }
    }

    @Override
    public JMSDestination.Type type() {
        return JMSDestination.Type.TOPIC;
    }

    @Override
    public int defaultConcurrency() {
        return 1;
    }

    protected JMSSpecificContext context(final String id, final Object context) throws Exception {
        if (context != null) {
            return ((JMSSpecificContext)context).asNonCloseable();
        } else {
            return (JMSSpecificContext)broker()
                    .createContext(new HashMap<Messaging.CreateContextOption, Object>() {{
                        put(Messaging.CreateContextOption.CLIENT_ID, id);
                    }});
        }
    }

}


text:
http_path = ""
css_dir = "css"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "js"

# To enable relative paths to assets via compass helper functions. Uncomment:
relative_assets = true

# You can select your preferred output style here (can be overridden via the command line):
# :expanded or :nested or :compact or :compressed
if environment == :development
    output_style = :expanded
else
    output_style = :compressed
    line_comments = false
end

asset_cache_buster :none