text:
<title>OGRE: Ogre::CreateCompositorScriptCompilerEvent Class Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre

Ogre::CreateCompositorScriptCompilerEvent

Public Member Functions |
Public Attributes |
Static Public Attributes

Ogre::CreateCompositorScriptCompilerEvent Class Reference

[General]

#include <OgreScriptCompiler.h>

Inheritance diagram for Ogre::CreateCompositorScriptCompilerEvent:

<map name="Ogre_1_1CreateCompositorScriptCompilerEvent_inherit__map" id="Ogre_1_1CreateCompositorScriptCompilerEvent_inherit__map">
<area shape="rect" id="node2" href="classOgre_1_1ScriptCompilerEvent.html" title="This struct is a base class for events which can be thrown by the compilers and caught by subscribers..." alt="" coords="64,5,253,35"/></map>
[legend]

List of all members.

Public Member Functions

 	CreateCompositorScriptCompilerEvent (const String &file, const String &name, const String &resourceGroup)

Public Attributes

String 	mFile

String 	mName

String 	mResourceGroup

String 	mType

Static Public Attributes

static String 	eventType

Detailed Description

Definition at line 561 of file OgreScriptCompiler.h.

Constructor & Destructor Documentation

          Ogre::CreateCompositorScriptCompilerEvent::CreateCompositorScriptCompilerEvent
          (
          const String &
           file,

          const String &
           name,

          const String &
           resourceGroup

          )

Definition at line 567 of file OgreScriptCompiler.h.

Member Data Documentation

          String Ogre::CreateCompositorScriptCompilerEvent::eventType [static]

Definition at line 565 of file OgreScriptCompiler.h.

          String Ogre::CreateCompositorScriptCompilerEvent::mFile

Definition at line 564 of file OgreScriptCompiler.h.

          String Ogre::CreateCompositorScriptCompilerEvent::mName

Definition at line 564 of file OgreScriptCompiler.h.

          String Ogre::CreateCompositorScriptCompilerEvent::mResourceGroup

Definition at line 564 of file OgreScriptCompiler.h.

          String Ogre::ScriptCompilerEvent::mType [inherited]

Definition at line 330 of file OgreScriptCompiler.h.

The documentation for this class was generated from the following file:

OgreScriptCompiler.h

Copyright © 2008 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Wed Nov 3 2010 19:25:01


text:
import yaml
import json

yaml_list = range(5)
yaml_list.append('string1')
yaml_list.append('string2')
yaml_list.append({})
yaml_list[-1]
{}
yaml_list[-1]['critter1'] = 'hedgehog'
yaml_list[-1]['critter2'] = 'bunny'
yaml_list[-1]['dungeon_levels'] = range(5)
yaml_list.append('list_end')

with open("class1_list.yml", "w") as f:
  f.write(yaml.dump(yaml_list, default_flow_style=False))

with open("class1_list.json", "w") as f:
  json.dump(yaml_list, f)

redpajama_set_name: RedPajamaGithub


text:
#include <LoggerCpp/LoggerCpp.h>

#include <iostream> // used for cerr messages

/**
 * @brief Simple test class
 */
class Tester {
public:
    Tester() :
        mLogger("main.Tester")
    {
    }

    void constTest (void) const {
        mLogger.debug() << "log within a const method";
    }

private:
    Log::Logger mLogger; ///< A named logger to produce log
};

/**
 * @brief Simple example program
 */
int main ()
{
    // Configure the default severity Level of new Channel objects
#ifndef NDEBUG
    Log::Manager::setDefaultLevel(Log::Log::eDebug);
#else
    Log::Manager::setDefaultLevel(Log::Log::eNotice);
#endif

    // Configure the Output objects
    Log::Config::Vector configList;
    Log::Config::addOutput(configList, "OutputConsole");
    Log::Config::addOutput(configList, "OutputFile");
    Log::Config::setOption(configList, "filename",          "log.txt");
    Log::Config::setOption(configList, "filename_old",      "log.old.txt");
    Log::Config::setOption(configList, "max_startup_size",  "0");
    Log::Config::setOption(configList, "max_size",          "10000");
#ifdef WIN32
    Log::Config::addOutput(configList, "OutputDebug");
#endif

    // Create a Logger object, using a "Main.Example" Channel
    Log::Logger logger("Main.Example");
    logger.warning() << "NO logs before configure()";

    try
    {
        // Configure the Log Manager (create the Output objects)
        Log::Manager::configure(configList);
    }
    catch (std::exception& e)
    {
        std::cerr << e.what();
    }

    // Test outputs of various kind of variables, and some common stream manipulations.
    std::string     str("string");
    unsigned int    ui  = 123;
    double          dbl = -0.023f;
    logger.debug() << "Variables ; '" << str << "', '" << ui << "', '" << dbl << "'";
    logger.debug() << "Hexa = " << std::hex << 0x75af0 << " test";
    logger.debug() << "Deci = " << std::right << std::setfill('0') << std::setw(8) << 76035 << " test";
    logger.debug() << "sizeof(logger)=" << sizeof(logger);

    // Test outputs of various severity Level
    logger.debug()  << "Debug.";
    logger.info()   << "Info.";
    logger.notice() << "Notice.";
    logger.warning()<< "Warning.";
    logger.error()  << "Error.";
    logger.critic() << "Critic.";

    // Modify the output Level of the underlying Channel, and test various severity Level again
    logger.setLevel(Log::Log::eWarning);
    logger.debug()  << "NO Debug.";     // NO more debug logs
    logger.info()   << "NO Info.";      // NO more info logs
    logger.notice() << "NO Notice.";    // NO more notice logs
    logger.warning()<< "Warning.";
    logger.error()  << "Error.";
    logger.critic() << "Critic.";

    // Reset Level of the "Main.example" channel by its name
    Log::Manager::get("Main.Example")->setLevel(Log::Log::eDebug);

    // Create other loggers, sharing the "Main.Example" Channel, and creating a new one
    Log::Logger logger2("Main.Example");
    Log::Logger logger3("Main.Other");
    logger.debug() << "First logger to the Channel";
    logger2.debug() << "Second logger to the Channel";
    logger3.debug() << "Third logger, other Channel";
    // Modify the Level of the "Main.example" channel by its name
    Log::Manager::get("Main.Example")->setLevel(Log::Log::eInfo);
    logger.debug() << "first logger inhibited";         // NO more debug logs for this logger
    logger2.debug() << "second logger also disabled";   // NO more debug logs (sharing the same underlying channel)
    logger3.debug() << "third logger still active";
    // Reset the Level of the "Main.example" channel by its name
    Log::Manager::get("Main.Example")->setLevel(Log::Log::eDebug);
    logger.debug() << "first logger re-activated";
    logger2.debug() << "second logger also re-activated";
    logger3.debug() << "third logger always active";

    // Create an object using a Logger as member variable
    Tester tester;
    tester.constTest();

    // Show how to get the current Channel configuration (to save it to a file, for instance)
    Log::Manager::get("Main.OtherChannel")->setLevel(Log::Log::eNotice);
    Log::Config::Ptr ChannelConfigPtr = Log::Manager::getChannelConfig();
    // Show how to set the current Channel configuration (restored from a file, for instance)
    Log::Manager::setChannelConfig(ChannelConfigPtr);

    // Terminate the Log Manager (destroy the Output objects)
    Log::Manager::terminate();
    logger.warning() << "NO more logs after terminate()";

    return 0;
}


text:
from director_protected import *

class FooBar(Bar):

    def ping(self):
        return "FooBar::ping();"

class FooBar2(Bar):

    def ping(self):
        return "FooBar2::ping();"

    def pang(self):
        return "FooBar2::pang();"

class FooBar3(Bar):

    def cheer(self):
        return "FooBar3::cheer();"

b = Bar()
f = b.create()
fb = FooBar()
fb2 = FooBar2()
fb3 = FooBar3()

try:
    s = fb.used()
    if s != "Foo::pang();Bar::pong();Foo::pong();FooBar::ping();":
        raise RuntimeError
    pass
except:
    raise RuntimeError, "bad FooBar::used"

try:
    s = fb2.used()
    if s != "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();":
        raise RuntimeError
    pass
except:
    raise RuntimeError, "bad FooBar2::used"

try:
    s = b.pong()
    if s != "Bar::pong();Foo::pong();Bar::ping();":
        raise RuntimeError
    pass
except:
    raise RuntimeError, "bad Bar::pong"

try:
    s = f.pong()
    if s != "Bar::pong();Foo::pong();Bar::ping();":
        raise RuntimeError
    pass
except:
    raise RuntimeError, " bad Foo::pong"

try:
    s = fb.pong()
    if s != "Bar::pong();Foo::pong();FooBar::ping();":
        raise RuntimeError
    pass
except:
    raise RuntimeError, " bad FooBar::pong"

protected = 1
try:
    b.ping()
    protected = 0
except:
    pass
if not protected:
    raise RuntimeError, "Foo::ping is protected"

protected = 1
try:
    f.ping()
    protected = 0
except:
    pass
if not protected:
    raise RuntimeError, "Foo::ping is protected"

protected = 1
try:
    f.pang()
    protected = 0
except:
    pass
if not protected:
    raise RuntimeError, "FooBar::pang is protected"

protected = 1
try:
    b.cheer()
    protected = 0
except:
    pass
if not protected:
    raise RuntimeError, "Bar::cheer is protected"

protected = 1
try:
    f.cheer()
    protected = 0
except:
    pass
if not protected:
    raise RuntimeError, "Foo::cheer is protected"

if fb3.cheer() != "FooBar3::cheer();":
    raise RuntimeError, "bad fb3::cheer"

if fb2.callping() != "FooBar2::ping();":
    raise RuntimeError, "bad fb2.callping"

if fb2.callcheer() != "FooBar2::pang();Bar::pong();Foo::pong();FooBar2::ping();":
    raise RuntimeError, "bad fb2.callcheer"

if fb3.callping() != "Bar::ping();":
    raise RuntimeError, "bad fb3.callping"

if fb3.callcheer() != "FooBar3::cheer();":
    raise RuntimeError, "bad fb3.callcheer"


text:
@implementation UIBarButtonItem (Category)

+ (instancetype)itemWithImage:(NSString *)imageName hightlightImage:(NSString *)hightlightImage target:(id)target action:(SEL)action {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:hightlightImage] forState:UIControlStateHighlighted];
    button.jt_size = button.currentBackgroundImage.size;
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[self alloc] initWithCustomView:button];
    return item;
}

@end


text:
package test161

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/ericaro/frontmatter"
	"github.com/imdario/mergo"
	"github.com/kevinburke/go.uuid"
	"io/ioutil"
	"math/rand"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"text/template"
)

// Many of the values below that come in from YAML are string types. This
// allows us to work around Go not having a nil type for things like ints, and
// also allows us to accept values like "10M" as numbers. Non-string types are
// only used when the default doesn't make sense. Given that the ultimate
// destination of these values is strings (sys161.conf configuration or JSON
// output) it doesn't matter.

type Sys161Conf struct {
	Path   string   `yaml:"path" json:"path"`
	CPUs   uint     `yaml:"cpus" json:"cpus"`
	RAM    string   `yaml:"ram" json:"ram"`
	Disk1  DiskConf `yaml:"disk1" json:"disk1"`
	Disk2  DiskConf `yaml:"disk2" json:"disk2"`
	Random uint32   `yaml:"-" json:"randomseed" bson:"randomseed"`
}

type DiskConf struct {
	Enabled string `yaml:"enabled" json:"enabled"`
	RPM     uint   `yaml:"rpm" json:"rpm"`
	Bytes   string `yaml:"bytes" json:"bytes"`
	NoDoom  string `yaml:"nodoom" json:"nodoom"`
}

type StatConf struct {
	Resolution float32 `yaml:"resolution" json:"resolution"`
	Window     uint    `yaml:"window" json:"window"`
}

type MonitorConf struct {
	Enabled         string  `yaml:"enabled" json:"enabled"`
	Window          uint    `yaml:"window" json:"window"`
	Kernel          Limits  `yaml:"kernel" json:"kernel"`
	User            Limits  `yaml:"user" json:"user"`
	ProgressTimeout float32 `yaml:"progresstimeout" json:"progresstimeout"`
	CommandTimeout  float32 `yaml:"commandtimeout" json:"commandtimeout"`
}

type Limits struct {
	EnableMin string  `yaml:"enablemin" json:"enablemin"`
	Min       float64 `yaml:"min" json:"min"`
	Max       float64 `yaml:"max" json:"max"`
}

type MiscConf struct {
	CommandRetries   uint    `yaml:"commandretries" json:"commandretries"`
	PromptTimeout    float32 `yaml:"prompttimeout" json:"prompttimeout"`
	CharacterTimeout uint    `yaml:"charactertimeout" json:"charactertimeout"`
	TempDir          string  `yaml:"tempdir" json:"-" bson:"-"`
	RetryCharacters  string  `yaml:"retrycharacters" json:"retrycharacters"`
	KillOnExit       string  `yaml:"killonexit" json:"killonexit"`
}

type CommandConf struct {
	Prefix string `yaml:"prefix" json:"prefix"`
	Prompt string `yaml:"prompt" json:"prompt"`
	Start  string `yaml:"start" json:"start"`
	End    string `yaml:"end" json:"end"`
}

var CONF_DEFAULTS = Test{
	Sys161: Sys161Conf{
		Path: "sys161",
		CPUs: 8,
		RAM:  "1M",
		Disk1: DiskConf{
			Enabled: "false",
			Bytes:   "32M",
			RPM:     7200,
			NoDoom:  "true",
		},
		Disk2: DiskConf{
			Enabled: "false",
			Bytes:   "32M",
			RPM:     7200,
			NoDoom:  "false",
		},
	},
	Stat: StatConf{
		Resolution: 0.01,
		Window:     1,
	},
	Monitor: MonitorConf{
		Enabled: "true",
		Window:  400,
		Kernel: Limits{
			EnableMin: "false",
			Min:       0.001,
			Max:       1.0,
		},
		User: Limits{
			EnableMin: "false",
			Min:       0.0001,
			Max:       1.0,
		},
		ProgressTimeout: 10.0,
		CommandTimeout:  60.0,
	},
	Misc: MiscConf{
		CommandRetries:   5,
		PromptTimeout:    1800.0,
		CharacterTimeout: 1000,
		RetryCharacters:  "true",
		KillOnExit:       "false",
	},
}

func confFromString(data string) (*Test, error) {
	t := &Test{}

	err := frontmatter.Unmarshal([]byte(data), t)
	if err != nil {
		return nil, err
	}
	t.Sys161.Random = rand.Uint32() >> 16

	t.requiredBy = make(map[string]bool)

	// TODO: Error checking here

	return t, nil
}

// TestFromFile parses the test file and sets configuration defaults.
func TestFromFile(filename string) (*Test, error) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("Error reading file %v: %v", filename, err)
	}
	test, err := TestFromString(string(data))
	if err != nil {
		err = fmt.Errorf("Error loading test file %v: %v", filename, err)
	}
	return test, err
}

// TestFromFile parses the test string and sets configuration defaults.
func TestFromString(data string) (*Test, error) {

	t, err := confFromString(data)
	if err != nil {
		return nil, err
	}

	// Check for empty commands and expand syntatic sugar before getting
	// started. Doing this first makes the main loop and retry logic simpler.

	t.ID = uuid.NewV4().String()
	err = t.initCommands()
	if err != nil {
		return nil, err
	}

	t.Result = TEST_RESULT_NONE

	return t, nil
}

func (t *Test) MergeConf(defaults Test) error {
	return mergo.Map(t, defaults)
}

const SYS161_TEMPLATE = `0 serial
1	emufs
{{if eq .Disk1.Enabled "true"}}
2	disk rpm={{.Disk1.RPM}} file=LHD0.img {{if eq .Disk1.NoDoom "true"}}nodoom{{end}} # bytes={{.Disk1.Bytes }}
{{end}}
{{if eq .Disk2.Enabled "true"}}
3	disk rpm={{.Disk2.RPM}} file=LHD1.img {{if eq .Disk2.NoDoom "true"}}nodoom{{end}} # bytes={{.Disk2.Bytes }}
{{end}}
28	random seed={{.Random}}
29	timer
30	trace
31	mainboard ramsize={{.RAM}} cpus={{.CPUs}}`

var confTemplate *template.Template
var confOnce sync.Once

// PrintConf formats the test configuration for use by sys161 via the sys161.conf file.
func (t *Test) PrintConf() (string, error) {

	confOnce.Do(func() { confTemplate, _ = template.New("conf").Parse(SYS161_TEMPLATE) })

	buffer := new(bytes.Buffer)

	// Can't fail, even if the test isn't properly initialized, because
	// t.Sys161 matches the template
	confTemplate.Execute(buffer, t.Sys161)

	var confString string
	for _, line := range strings.Split(strings.TrimSpace(buffer.String()), "\n") {
		if strings.TrimSpace(line) != "" {
			confString += line + "\n"
		}
	}
	return confString, nil
}

func (t *Test) confEqual(t2 *Test) bool {
	return t.Sys161 == t2.Sys161 &&
		t.Stat == t2.Stat &&
		t.Monitor == t2.Monitor &&
		t.Misc == t2.Misc &&
		reflect.DeepEqual(t.CommandConf, t2.CommandConf)
}

var prefixRegexp *regexp.Regexp
var prefixOnce sync.Once

func splitPrefix(commandLine string) (string, string) {
	prefixOnce.Do(func() { prefixRegexp = regexp.MustCompile(`^([!@#$%^&*]) `) })
	matches := prefixRegexp.FindStringSubmatch(strings.TrimSpace(commandLine))
	if len(matches) == 0 {
		return "", strings.TrimSpace(commandLine)
	} else {
		return matches[1], strings.TrimSpace(commandLine[1:])
	}
}

func (t *Test) checkCommandConf() error {
	prefixes := "$"
	errorMsg := ""
	var commandConf CommandConf
	for _, commandConf = range t.CommandConf {
		if commandConf.Prefix == "" || commandConf.Prompt == "" ||
			commandConf.Start == "" || commandConf.End == "" {
			errorMsg = "need to specific command prefix, prompt, start, and end"
			break
		}
		if len(commandConf.Prefix) > 1 {
			errorMsg = "illegal multicharacter prefix"
			break
		}
		prefix, _ := splitPrefix(commandConf.Prefix + " t")
		if prefix == "" {
			errorMsg = "invalid prefix"
			break
		} else if prefix == "$" {
			errorMsg = "the $ prefix is reserved for the shell"
			break
		} else if strings.ContainsAny(prefixes, prefix) {
			errorMsg = "duplicate prefix"
			break
		}
		prefixes += prefix
		startPrefix, _ := splitPrefix(commandConf.Start)
		if startPrefix != "" && startPrefix == prefix {
			errorMsg = "command start cannot start with own prefix"
			break
		}
		endPrefix, _ := splitPrefix(commandConf.End)
		if endPrefix != "" {
			errorMsg = "command exits should not contain a prefix"
			break
		}
	}
	if errorMsg == "" {
		for _, commandConf = range t.CommandConf {
			startPrefix, _ := splitPrefix(commandConf.Start)
			if startPrefix != "" && !strings.ContainsAny(prefixes, startPrefix) {
				errorMsg = "command start contains an unknown prefix"
				break
			}
		}
	}
	if errorMsg != "" {
		return errors.New(fmt.Sprintf("test161: %s (%v)", errorMsg, commandConf))
	} else {
		return nil
	}
}

var KERNEL_COMMAND_CONF = &CommandConf{
	Prompt: `OS/161 kernel [? for menu]: `,
	End:    "q",
}
var SHELL_COMMAND_CONF = &CommandConf{
	Prefix: "$",
	Prompt: `OS/161$ `,
	Start:  "s",
	End:    "exit",
}

func (t *Test) commandConfFromLine(commandLine string) (string, *CommandConf) {
	prefix, commandLine := splitPrefix(commandLine)
	if prefix == "" {
		return commandLine, KERNEL_COMMAND_CONF
	} else if prefix == "$" {
		return commandLine, SHELL_COMMAND_CONF
	} else {
		for _, commandConf := range t.CommandConf {
			if commandConf.Prefix == prefix {
				return commandLine, &commandConf
			}
		}
	}
	return commandLine, nil
}

// simplePrefixes handle prefixes that don't change the environment or require
// special prompts.

var khuPrefixRegexp *regexp.Regexp
var multiplierPrefixRegexp *regexp.Regexp
var simplePrefixOnce sync.Once

func simplePrefixes(inputCommands []string) ([]string, error) {
	outputCommands, err := doSimplePrefixes(inputCommands)
	if err != nil {
		return nil, err
	}
	outputCommands, err = doSimplePrefixes(outputCommands)
	if err != nil {
		return nil, err
	}
	return outputCommands, nil
}

func doSimplePrefixes(inputCommands []string) ([]string, error) {
	simplePrefixOnce.Do(func() {
		khuPrefixRegexp = regexp.MustCompile(`^\|(.*)`)
		multiplierPrefixRegexp = regexp.MustCompile(`^(\d+)x(.*)`)
	})
	outputCommands := make([]string, 0, len(inputCommands))
	for _, command := range inputCommands {
		command = strings.TrimSpace(command)
		matches := khuPrefixRegexp.FindStringSubmatch(command)
		if len(matches) != 0 {
			outputCommands = append(outputCommands, "khu", matches[1], "khu")
			continue
		}
		matches = multiplierPrefixRegexp.FindStringSubmatch(command)
		if len(matches) != 0 {
			multiplier, err := strconv.Atoi(matches[1])
			if err != nil {
				return nil, err
			}
			for i := 0; i < multiplier; i++ {
				outputCommands = append(outputCommands, matches[2])
			}
			continue
		}
		outputCommands = append(outputCommands, command)
	}
	return outputCommands, nil
}

// Don't get stuck in an infinite loop

const MAX_EXPANSION_LOOPS = 1024

func (c *Command) setCommandConfig(test *Test) {
	myname := c.Id()
	for _, tmpl := range test.CommandOverrides {
		if tmpl.Name == myname {
			c.Config = *(tmpl)
			return
		}
	}
}

func (t *Test) initCommands() (err error) {

	// Check defined command prefixes
	err = t.checkCommandConf()
	if err != nil {
		return err
	}

	// Set up the command configuration stack
	var commandConfStack []*CommandConf
	commandConfStack = append(commandConfStack, KERNEL_COMMAND_CONF)

	// Set the boot command
	t.Commands = append(t.Commands, &Command{
		Type:          "kernel",
		ID:            uuid.NewV4().String(),
		Test:          t,
		PromptPattern: regexp.MustCompile(regexp.QuoteMeta(KERNEL_COMMAND_CONF.Prompt)),
		Input: InputLine{
			Line: "boot",
		},
		Status:   COMMAND_STATUS_NONE,
		Panic:    CMD_OPT_NO,
		TimesOut: CMD_OPT_NO,
		Timeout:  0.0,
	})

	// Set all confs including kernel and shell
	allConfs := append(t.CommandConf, *SHELL_COMMAND_CONF, *KERNEL_COMMAND_CONF)

	commandLines := strings.Split(strings.TrimSpace(t.Content), "\n")
	commandLines, err = simplePrefixes(commandLines)
	if err != nil {
		return err
	}

	for i := 0; i <= MAX_EXPANSION_LOOPS; i++ {
		if i == MAX_EXPANSION_LOOPS {
			return errors.New("test161: infinite loop expanding command list")
		}
		if len(commandConfStack) == 0 {
			if len(commandLines) != 0 {
				return errors.New("test161: premature exit in command list")
			}
			// This is normal exit
			break
		}
		currentConf := commandConfStack[0]

		// May need to clean up previous configurations
		if len(commandLines) == 0 {
			commandLines = []string{strings.TrimSpace(currentConf.Prefix + " " + currentConf.End)}
			continue
		}

		// Peek at the first command
		commandLine := strings.TrimSpace(commandLines[0])
		if commandLine == "" {
			return errors.New("test161: found empty command")
		}

		commandLine, commandConf := t.commandConfFromLine(commandLine)
		if commandConf == nil {
			return errors.New(fmt.Sprintf("test161: command with invalid prefix %v", commandLine))
		}

		if !reflect.DeepEqual(currentConf, commandConf) {
			found := false
			for _, search := range commandConfStack {
				if commandConf == search {
					found = true
					break
				}
			}
			if found {
				commandLines = append([]string{strings.TrimSpace(currentConf.Prefix + " " + currentConf.End)}, commandLines...)
			} else {
				commandLines = append([]string{commandConf.Start}, commandLines...)
			}
			continue
		} else {
			typeConf := currentConf
			nextConf := currentConf
			if commandLine == currentConf.End {
				// The command exits the current configuration
				commandConfStack = commandConfStack[1:]
				if len(commandConfStack) > 0 {
					nextConf = commandConfStack[0]
				} else {
					nextConf = nil
				}
			} else {
				for _, search := range allConfs {
					if search.Start == strings.TrimSpace(currentConf.Prefix+" "+commandLine) {
						// The command starts a new configuration
						commandConfStack = append([]*CommandConf{&search}, commandConfStack...)
						typeConf = commandConfStack[0]
						nextConf = commandConfStack[0]
						break
					}
				}
			}
			var commandType string
			if typeConf.Prefix != "" || strings.HasPrefix(commandLine, "p ") {
				commandType = "user"
			} else {
				commandType = "kernel"
			}
			var promptPattern *regexp.Regexp
			if nextConf != nil {
				promptPattern = regexp.MustCompile(regexp.QuoteMeta(nextConf.Prompt))
			}
			newCmd := &Command{
				Type:          commandType,
				ID:            uuid.NewV4().String(),
				Test:          t,
				PromptPattern: promptPattern,
				Input: InputLine{
					Line: commandLine,
				},
				Status:   COMMAND_STATUS_NONE,
				Panic:    CMD_OPT_NO,
				TimesOut: CMD_OPT_NO,
				Timeout:  0.0,
			}
			newCmd.setCommandConfig(t)
			t.Commands = append(t.Commands, newCmd)
			commandLines = commandLines[1:]
		}
	}

	return nil
}


text:
Contributing to django-machina
##############################

Here are some simple rules to help you contribute to *django-machina*. You can contribute in many
ways!

Contributing code
=================

The preferred way to contribute to *django-machina* is to submit pull requests to the
`project's Github repository <https://github.com/ellmetha/django-machina>`_. Here are some general
tips regarding pull requests.

.. warning::

    Keep in mind that you should propose new features on the
    `project's issue tracker <https://github.com/ellmetha/django-machina/issues>`_ before starting
    working on your ideas! Remember that the central aim of *django-machina* is to provide a solid
    core of a forum project - without much of extra functionality included!

Development environment
-----------------------

.. note::

    The following steps assumes you have `Poetry <https://python-poetry.org/>`_ and
    `npm <https://www.npmjs.com/>`_ installed on your system.

You should first fork the
`django-machina's repository <https://github.com/ellmetha/django-machina>`_. Then you can get a
working copy of the project using the following commands:

.. code-block:: bash

    $ git clone git@github.com:<username>/django-machina.git
    $ cd django-machina
    $ make && npm install

Coding style
------------

Please make sure that your code is compliant with the
`PEP8 style guide <https://www.python.org/dev/peps/pep-0008/>`_. You can ignore the "Maximum Line
Length" requirement but the length of your lines should not exceed 100 characters. Remember that
your code will be checked using `flake8 <https://pypi.python.org/pypi/flake8>`_ and
`isort <https://github.com/timothycrosley/isort>`_. You can use the following command to trigger
such quality assurance checks:

.. code-block:: bash

    $ make qa

Tests
-----

You should not submit pull requests without providing tests. *Django-machina* uses
`pytest <http://pytest.org/latest/>`_ as a test runner but also as a syntax for tests instead of
unittest. So you should write your tests using `pytest <http://pytest.org/latest/>`_ instead of
unittest and you should not use the built-in ``django.test.TestCase``.

You can run the whole test suite using the following command:

.. code-block:: bash

    $ make tests

Code coverage should not decrease with pull requests! You can easily get the code coverage of the
project using the following command:

.. code-block:: bash

    $ make coverage

Contributing translations
=========================

The translation work on *django-machina* is done using
`Transifex <https://www.transifex.com/django-machina-team/django-machina/>`_. Don't hesitate to
apply for a language if you want to improve the internationalization of the project.

Using the issue tracker
=======================

You should use the `project's issue tracker <https://github.com/ellmetha/django-machina/issues>`_ if
you've found a bug or if you want to propose a new feature. Don't forget to include as many details
as possible in your tickets (eg. tracebacks if this is appropriate).

Security
========

If you've found a security issue please **do not open a Github issue**. Instead, send an email at
``security@ellmetha.dev``. We'll then investigate together to resolve the problem so we can make
an announcement about a solution along with the vulnerability.


text:
app.directive("commentView", function() {
	return {
		restrict: "E",
		templateUrl: "../templates/comment-view.php",
		controller: "../controllers/comments-controller.js"
	};
});


text:
namespace inet {

namespace ospf {

class NeighborStateTwoWay : public NeighborState
{
  public:
    virtual void processEvent(Neighbor *neighbor, Neighbor::NeighborEventType event);
    virtual Neighbor::NeighborStateType getState() const { return Neighbor::TWOWAY_STATE; }
};

} // namespace ospf

} // namespace inet

#endif // ifndef __INET_OSPFNEIGHBORSTATETWOWAY_H


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Build.Tasks
{
    using System;
    using System.Linq;

    using Cake.Common.Tools.NUnit;
    using Cake.Frosting;

    /// <summary>A cake task to run NUnit 3 tests.</summary>
    /// <remarks>This task is not used (NUnit 3 is not used by DNN), you probably want <see cref="UnitTests"/>.</remarks>
    [Dependency(typeof(Build))]
    public sealed class RunUnitTests : FrostingTask<Context>
    {
        /// <inheritdoc/>
        public override void Run(Context context)
        {
            context.NUnit3(
                "./src/**/bin/" + context.BuildConfiguration + "/*.Test*.dll",
                new NUnit3Settings { NoResults = false });
        }
    }
}


text:
package lu.william.feed;

import lu.william.comm.Feedback;
import lu.william.comm.SyntaxCommon;

public class GuestExit extends AbstractSimpleGuest {
	@Override
	public Feedback have(IDish dish) {
		myTable.setStatus(ITable.Status.Dead);
		return Feedback.yaki();
	}

	public String[] getFlavors() {
		return new String[] { SyntaxCommon.KEYWORD_EXIT };
	}
}


text:
/* @file MeshInterface.h Mesh network interface */
/** \addtogroup netinterface */
/** @{*/

#ifndef MESH_INTERFACE_H
#define MESH_INTERFACE_H

#include "netsocket/NetworkInterface.h"

/** Common interface that is shared between mesh hardware
 */
class MeshInterface : public virtual NetworkInterface {
public:
    /** @copydoc NetworkInterface::meshInterface
     */
    virtual MeshInterface *meshInterface()
    {
        return this;
    }

    /** Get the default Mesh interface.
     *
     * This is provided as a weak method so applications can override.
     * Default behavior is to get the target's default interface, if
     * any.
     *
     * @return pointer to interface, if any.
     */
    static MeshInterface *get_default_instance();

#if !defined(DOXYGEN_ONLY)
protected:

    /** Get the target's default Mesh interface.
     *
     * This is provided as a weak method so targets can override. The
     * default implementation will invoke LoWPANNDInterface or ThreadInterface
     * with the default NanostackRfPhy.
     *
     * @return pointer to interface, if any.
     */
    static MeshInterface *get_target_default_instance();
#endif //!defined(DOXYGEN_ONLY)
};

#endif

/** @}*/


text:
@implementation ServerController

#pragma mark Initializers and setup

- (NSString*) protocolIdentifier
{
    NSString* pairing = [[NSUserDefaults standardUserDefaults] objectForKey:@"pairing"];

    if (pairing)
    {
        return [NSString stringWithFormat:@"CocosP-%@",pairing];
    }
    else
    {
        return @"CocosPlayer";
    }
}

- (id) init
{
    self = [super init];
    if (!self) return NULL;

    connectedClients = [[NSMutableSet alloc] init];

    server = [[ThoMoServerStub alloc] initWithProtocolIdentifier:[self protocolIdentifier]];
    [server setDelegate:self];

    return self;
}

- (void) start
{
    if (server)
    {
        [server start];
        NSLog(@"Server started");
    }
}

- (void) updatePairing
{
    // Stop old server
    [server stop];
    [server release];
    server = NULL;
    [connectedClients removeAllObjects];

    // Start new server
    server = [[ThoMoServerStub alloc] initWithProtocolIdentifier:[self protocolIdentifier]];
    [server setDelegate:self];
    [server start];

    [[PlayerStatusLayer sharedInstance] setStatus:kCCBStatusStringWaiting];
}

#pragma mark Helper methods

- (void) executeJavaScript:(NSString*)script
{
    NSThread *cocos2dThread = [[CCDirector sharedDirector] runningThread];

	[cocos2dThread performBlock:^(void) {
		NSString * string = @"None\n";
		jsval out;
		BOOL success = [[ScriptingCore sharedInstance] evalString:script outVal:&out];

		if(success)
		{
			if(JSVAL_IS_BOOLEAN(out))
			{
				string = [NSString stringWithFormat:@"Result(bool): %@.\n", (JSVAL_TO_BOOLEAN(out)) ? @"true" : @"false"];
			}
			else if(JSVAL_IS_INT(out))
			{
				string = [NSString stringWithFormat:@"Result(int): %i.\n", JSVAL_TO_INT(out)];
			}
			else if(JSVAL_IS_DOUBLE(out))
			{
				string = [NSString stringWithFormat:@"Result(double): %d.\n", JSVAL_TO_DOUBLE(out)];
			}
			else if(JSVAL_IS_STRING(out)) {
				NSString *tmp;
				jsval_to_nsstring( [[ScriptingCore sharedInstance] globalContext], out, &tmp );
				string = [NSString stringWithFormat:@"Result(string): %d.\n", tmp];
			}
			else if (JSVAL_IS_VOID(out) )
				string = @"Result(void):\n";
			else if (JSVAL_IS_OBJECT(out) )
				string = @"Result(object):\n";
		}
		else
		{
			string = [NSString stringWithFormat:@"Error evaluating script:\n#############################\n%@\n#############################\n", script];
		}

		[self sendResultString:string];
	}
				  waitUntilDone:NO];
}

- (void) extractZipData:(NSData*)data
{
    NSString* dirPath = [CCBReader ccbDirectoryPath] ;
    NSString* zipPath = [dirPath stringByAppendingPathComponent:@"ccb.zip"];

    BOOL isDirectory = NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:dirPath isDirectory:&isDirectory])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:NULL error:NULL];
    }

    if(![data writeToFile:zipPath atomically:YES])
    {
        NSLog(@"Failed to write zip file");
        return;
    }

    if (![CCBReader unzipResources:zipPath])
    {
        NSLog(@"Failed to unzip resources");
    }

    NSLog(@"Resources unzipped!");
}

- (void) stopMain
{
    [[AppController appController] stopJSApp];
}

- (void) runMain
{
    [[AppController appController] runJSApp];
}

#pragma mark Server callbacks

- (void) server:(ThoMoServerStub *)theServer acceptedConnectionFromClient:(NSString *)aClientIdString
{
    NSLog(@"New Client: %@", aClientIdString);
    [connectedClients addObject:aClientIdString];

    NSLog(@"Num connected clients: %d", connectedClients.count);

    if (connectedClients.count == 1)
    {
        [[AppController appController] setStatus:kCCBStatusStringConnected forceStop:NO];
        [self sendDeviceName];
    }
    else
    {
        [[AppController appController] setStatus: kCCBStatusStringTooMany forceStop:YES];
    }
}

- (void)server:(ThoMoServerStub *)theServer lostConnectionToClient:(NSString *)aClientIdString errorMessage:(NSString *)errorMessage
{
    NSLog(@"Lost Client: %@", aClientIdString);
    [connectedClients removeObject:aClientIdString];

    if (connectedClients.count == 0)
    {
        [[AppController appController] setStatus:kCCBStatusStringWaiting forceStop:YES];
    }
    else if (connectedClients.count == 1)
    {
        [[AppController appController] setStatus:kCCBStatusStringConnected forceStop:NO];
    }
    else
    {
        [[AppController appController] setStatus: kCCBStatusStringTooMany forceStop:YES];
    }
}

- (void)serverDidShutDown:(ThoMoServerStub *)theServer
{
}

- (void)netServiceProblemEncountered:(NSString *)errorMessage onServer:(ThoMoServerStub *)theServer
{
}

- (void) server:(ThoMoServerStub *)theServer didReceiveData:(id)theData fromClient:(NSString *)aClientIdString
{
    if (connectedClients.count != 1) return;

    NSDictionary* msg = theData;

    NSString* cmd = [msg objectForKey:@"cmd"];

    NSLog(@"cmd: %@", cmd);

    if ([cmd isEqualToString:@"script"])
    {
        NSString* script = [msg objectForKey:@"script"];
        [self executeJavaScript:script];
    }
    else if ([cmd isEqualToString:@"run"])
    {
        [self runMain];
    }
    else if ([cmd isEqualToString:@"stop"])
    {
        [self stopMain];
    }
    else if ([cmd isEqualToString:@"zip"])
    {
        NSData* zipData = [msg objectForKey:@"data"];
        [self extractZipData:zipData];
    }
}

#pragma mark Sending messages

- (void) sendMessage:(NSDictionary*) msg
{
    if (connectedClients.count == 1)
    {
        [server sendToAllClients:msg];
    }
}

- (void) sendDeviceName
{
    NSMutableDictionary* msg = [NSMutableDictionary dictionary];
    [msg setObject:@"devicename" forKey:@"cmd"];
    [msg setObject:[[UIDevice currentDevice] name] forKey:@"devicename"];

    [self sendMessage:msg];
}

- (void) sendResultString:(NSString*) str
{
    NSMutableDictionary* msg = [NSMutableDictionary dictionary];
    [msg setObject:@"result" forKey:@"cmd"];
    [msg setObject:str forKey:@"result"];

    [self sendMessage:msg];
}

#pragma mark Common

- (void) dealloc
{
    [server release];
    [connectedClients release];

    [super dealloc];
}

@end


text:
!function(a,b){
// AMD
"function"==typeof define&&define.amd?define(["jquery"],function(c){return b(a,c)}):"object"==typeof exports?b(a,require("jquery")):b(a,a.jQuery)}("undefined"!=typeof window?window:this,function(a,b){"use strict";/**
	 * Utility for determing transform matrix equality
	 * Checks backwards to test translation first
	 * @param {Array} first
	 * @param {Array} second
	 */
function c(a,b){for(var c=a.length;--c;)if(+a[c]!==+b[c])return!1;return!0}/**
	 * Creates the options object for reset functions
	 * @param {Boolean|Object} opts See reset methods
	 * @returns {Object} Returns the newly-created options object
	 */
function d(a){var c={range:!0,animate:!0};return"boolean"==typeof a?c.animate=a:b.extend(c,a),c}/**
	 * Represent a transformation matrix with a 3x3 matrix for calculations
	 * Matrix functions adapted from Louis Remi's jQuery.transform (https://github.com/louisremi/jquery.transform.js)
	 * @param {Array|Number} a An array of six values representing a 2d transformation matrix
	 */
function e(a,c,d,e,f,g,h,i,j){"array"===b.type(a)?this.elements=[+a[0],+a[2],+a[4],+a[1],+a[3],+a[5],0,0,1]:this.elements=[a,c,d,e,f,g,h||0,i||0,j||1]}/**
	 * Create a vector containing three values
	 */
function f(a,b,c){this.elements=[a,b,c]}/**
	 * Create a Panzoom object for a given element
	 * @constructor
	 * @param {Element} elem - Element to use pan and zoom
	 * @param {Object} [options] - An object literal containing options to override default options
	 *  (See Panzoom.defaults for ones not listed below)
	 * @param {jQuery} [options.$zoomIn] - zoom in buttons/links collection (you can also bind these yourself
	 *  e.g. $button.on('click', function(e) { e.preventDefault(); $elem.panzoom('zoomIn'); });)
	 * @param {jQuery} [options.$zoomOut] - zoom out buttons/links collection on which to bind zoomOut
	 * @param {jQuery} [options.$zoomRange] - zoom in/out with this range control
	 * @param {jQuery} [options.$reset] - Reset buttons/links collection on which to bind the reset method
	 * @param {Function} [options.on[Start|Change|Zoom|Pan|End|Reset] - Optional callbacks for panzoom events
	 */
function g(a,c){
// Allow instantiation without `new` keyword
if(!(this instanceof g))return new g(a,c);
// Sanity checks
1!==a.nodeType&&b.error("Panzoom called on non-Element node"),b.contains(l,a)||b.error("Panzoom element must be attached to the document");
// Don't remake
var d=b.data(a,m);if(d)return d;
// Extend default with given object literal
// Each instance gets its own options
this.options=c=b.extend({},g.defaults,c),this.elem=a;var e=this.$elem=b(a);this.$set=c.$set&&c.$set.length?c.$set:e,this.$doc=b(a.ownerDocument||l),this.$parent=e.parent(),
// This is SVG if the namespace is SVG
// However, while <svg> elements are SVG, we want to treat those like other elements
this.isSVG=r.test(a.namespaceURI)&&"svg"!==a.nodeName.toLowerCase(),this.panning=!1,
// Save the original transform value
// Save the prefixed transform style key
// Set the starting transform
this._buildTransform(),
// Build the appropriately-prefixed transform style property name
// De-camelcase
this._transform=!this.isSVG&&b.cssProps.transform.replace(q,"-$1").toLowerCase(),
// Build the transition value
this._buildTransition(),
// Build containment dimensions
this.resetDimensions();
// Add zoom and reset buttons to `this`
var f=b(),h=this;b.each(["$zoomIn","$zoomOut","$zoomRange","$reset"],function(a,b){h[b]=c[b]||f}),this.enable(),
// Save the instance
b.data(a,m,this)}
// Common properties to lift for touch or pointer events
var h="over out down up move enter leave cancel".split(" "),i=b.extend({},b.event.mouseHooks),j={};
// Support pointer events in IE11+ if available
if(a.PointerEvent)b.each(h,function(a,c){
// Add event name to events property and add fixHook
b.event.fixHooks[j[c]="pointer"+c]=i});else{var k=i.props;
// Add touch properties for the touch hook
i.props=k.concat(["touches","changedTouches","targetTouches","altKey","ctrlKey","metaKey","shiftKey"]),/**
		 * Support: Android
		 * Android sets pageX/Y to 0 for any touch event
		 * Attach first touch's pageX/pageY and clientX/clientY if not set correctly
		 */
i.filter=function(a,b){var c,d=k.length;if(!b.pageX&&b.touches&&(c=b.touches[0]))
// Copy over all mouse properties
for(;d--;)a[k[d]]=c[k[d]];return a},b.each(h,function(a,c){
// No equivalent touch events for over and out
if(2>a)j[c]="mouse"+c;else{var d="touch"+("down"===c?"start":"up"===c?"end":c);
// Add fixHook
b.event.fixHooks[d]=i,
// Add event names to events property
j[c]=d+" mouse"+c}})}b.pointertouch=j;var l=a.document,m="__pz__",n=Array.prototype.slice,o=!!a.PointerEvent,p=function(){var a=l.createElement("input");return a.setAttribute("oninput","return"),"function"==typeof a.oninput}(),q=/([A-Z])/g,r=/^http:[\w\.\/]+svg$/,s=/^inline/,t="(\\-?[\\d\\.e]+)",u="\\,?\\s*",v=new RegExp("^matrix\\("+t+u+t+u+t+u+t+u+t+u+t+"\\)$");/**
	 * Get the element at zero-indexed index i
	 * @param {Number} i
	 */
// Attach regex for possible use (immutable)
// Container for event names
// Add Panzoom as a static property
/**
	 * Extend jQuery
	 * @param {Object|String} options - The name of a method to call on the prototype
	 *  or an object literal of options
	 * @returns {jQuery|Mixed} jQuery instance for regular chaining or the return value(s) of a panzoom method call
	 */
return e.prototype={/**
		 * Multiply a 3x3 matrix by a similar matrix or a vector
		 * @param {Matrix|Vector} matrix
		 * @return {Matrix|Vector} Returns a vector if multiplying by a vector
		 */
x:function(a){var b=a instanceof f,c=this.elements,d=a.elements;return b&&3===d.length?new f(c[0]*d[0]+c[1]*d[1]+c[2]*d[2],c[3]*d[0]+c[4]*d[1]+c[5]*d[2],c[6]*d[0]+c[7]*d[1]+c[8]*d[2]):d.length===c.length?new e(c[0]*d[0]+c[1]*d[3]+c[2]*d[6],c[0]*d[1]+c[1]*d[4]+c[2]*d[7],c[0]*d[2]+c[1]*d[5]+c[2]*d[8],c[3]*d[0]+c[4]*d[3]+c[5]*d[6],c[3]*d[1]+c[4]*d[4]+c[5]*d[7],c[3]*d[2]+c[4]*d[5]+c[5]*d[8],c[6]*d[0]+c[7]*d[3]+c[8]*d[6],c[6]*d[1]+c[7]*d[4]+c[8]*d[7],c[6]*d[2]+c[7]*d[5]+c[8]*d[8]):!1},/**
		 * Generates an inverse of the current matrix
		 * @returns {Matrix}
		 */
inverse:function(){var a=1/this.determinant(),b=this.elements;return new e(a*(b[8]*b[4]-b[7]*b[5]),a*-(b[8]*b[1]-b[7]*b[2]),a*(b[5]*b[1]-b[4]*b[2]),a*-(b[8]*b[3]-b[6]*b[5]),a*(b[8]*b[0]-b[6]*b[2]),a*-(b[5]*b[0]-b[3]*b[2]),a*(b[7]*b[3]-b[6]*b[4]),a*-(b[7]*b[0]-b[6]*b[1]),a*(b[4]*b[0]-b[3]*b[1]))},/**
		 * Calculates the determinant of the current matrix
		 * @returns {Number}
		 */
determinant:function(){var a=this.elements;return a[0]*(a[8]*a[4]-a[7]*a[5])-a[3]*(a[8]*a[1]-a[7]*a[2])+a[6]*(a[5]*a[1]-a[4]*a[2])}},f.prototype.e=e.prototype.e=function(a){return this.elements[a]},g.rmatrix=v,g.events=b.pointertouch,g.defaults={
// Should always be non-empty
// Used to bind jQuery events without collisions
// A guid is not added here as different instantiations/versions of panzoom
// on the same element is not supported, so don't do it.
eventNamespace:".panzoom",
// Whether or not to transition the scale
transition:!0,
// Default cursor style for the element
cursor:"move",
// There may be some use cases for zooming without panning or vice versa
disablePan:!1,disableZoom:!1,
// The increment at which to zoom
// adds/subtracts to the scale each time zoomIn/Out is called
increment:.3,minScale:.4,maxScale:5,
// The default step for the range input
// Precendence: default < HTML attribute < option setting
rangeStep:.05,
// Animation duration (ms)
duration:200,
// CSS easing used for scale transition
easing:"ease-in-out",
// Indicate that the element should be contained within it's parent when panning
// Note: this does not affect zooming outside of the parent
// Set this value to 'invert' to only allow panning outside of the parent element (basically the opposite of the normal use of contain)
// 'invert' is useful for a large panzoom element where you don't want to show anything behind it
contain:!1},g.prototype={constructor:g,/**
		 * @returns {Panzoom} Returns the instance
		 */
instance:function(){return this},/**
		 * Enable or re-enable the panzoom instance
		 */
enable:function(){
// Unbind first
this._initStyle(),this._bind(),this.disabled=!1},/**
		 * Disable panzoom
		 */
disable:function(){this.disabled=!0,this._resetStyle(),this._unbind()},/**
		 * @returns {Boolean} Returns whether the current panzoom instance is disabled
		 */
isDisabled:function(){return this.disabled},/**
		 * Destroy the panzoom instance
		 */
destroy:function(){this.disable(),b.removeData(this.elem,m)},/**
		 * Builds the restricing dimensions from the containment element
		 * Also used with focal points
		 * Call this method whenever the dimensions of the element or parent are changed
		 */
resetDimensions:function(){
// Reset container properties
var a=this.$parent;this.container={width:a.innerWidth(),height:a.innerHeight()};var c,d=a.offset(),e=this.elem,f=this.$elem;this.isSVG?(c=e.getBoundingClientRect(),c={left:c.left-d.left,top:c.top-d.top,width:c.width,height:c.height,margin:{left:0,top:0}}):c={left:b.css(e,"left",!0)||0,top:b.css(e,"top",!0)||0,width:f.innerWidth(),height:f.innerHeight(),margin:{top:b.css(e,"marginTop",!0)||0,left:b.css(e,"marginLeft",!0)||0}},c.widthBorder=b.css(e,"borderLeftWidth",!0)+b.css(e,"borderRightWidth",!0)||0,c.heightBorder=b.css(e,"borderTopWidth",!0)+b.css(e,"borderBottomWidth",!0)||0,this.dimensions=c},/**
		 * Return the element to it's original transform matrix
		 * @param {Boolean} [options] If a boolean is passed, animate the reset (default: true). If an options object is passed, simply pass that along to setMatrix.
		 * @param {Boolean} [options.silent] Silence the reset event
		 */
reset:function(a){a=d(a);
// Reset the transform to its original value
var b=this.setMatrix(this._origTransform,a);a.silent||this._trigger("reset",b)},/**
		 * Only resets zoom level
		 * @param {Boolean|Object} [options] Whether to animate the reset (default: true) or an object of options to pass to zoom()
		 */
resetZoom:function(a){a=d(a);var b=this.getMatrix(this._origTransform);a.dValue=b[3],this.zoom(b[0],a)},/**
		 * Only reset panning
		 * @param {Boolean|Object} [options] Whether to animate the reset (default: true) or an object of options to pass to pan()
		 */
resetPan:function(a){var b=this.getMatrix(this._origTransform);this.pan(b[4],b[5],d(a))},/**
		 * Sets a transform on the $set
		 * @param {String} transform
		 */
setTransform:function(a){for(var c=this.isSVG?"attr":"style",d=this.$set,e=d.length;e--;)b[c](d[e],"transform",a)},/**
		 * Retrieving the transform is different for SVG
		 *  (unless a style transform is already present)
		 * Uses the $set collection for retrieving the transform
		 * @param {String} [transform] Pass in an transform value (like 'scale(1.1)')
		 *  to have it formatted into matrix format for use by Panzoom
		 * @returns {String} Returns the current transform value of the element
		 */
getTransform:function(a){var c=this.$set,d=c[0];
// Retrieve the transform
// Convert any transforms set by the user to matrix format
// by setting to computed
// Get computed and set for next time
return a?this.setTransform(a):a=b[this.isSVG?"attr":"style"](d,"transform"),"none"===a||v.test(a)||this.setTransform(a=b.css(d,"transform")),a||"none"},/**
		 * Retrieve the current transform matrix for $elem (or turn a transform into it's array values)
		 * @param {String} [transform] matrix-formatted transform value
		 * @returns {Array} Returns the current transform matrix split up into it's parts, or a default matrix
		 */
getMatrix:function(a){var b=v.exec(a||this.getTransform());return b&&b.shift(),b||[1,0,0,1,0,0]},/**
		 * Given a matrix object, quickly set the current matrix of the element
		 * @param {Array|String} matrix
		 * @param {Boolean} [animate] Whether to animate the transform change
		 * @param {Object} [options]
		 * @param {Boolean|String} [options.animate] Whether to animate the transform change, or 'skip' indicating that it is unnecessary to set
		 * @param {Boolean} [options.contain] Override the global contain option
		 * @param {Boolean} [options.range] If true, $zoomRange's value will be updated.
		 * @param {Boolean} [options.silent] If true, the change event will not be triggered
		 * @returns {Array} Returns the newly-set matrix
		 */
setMatrix:function(a,c){if(!this.disabled){c||(c={}),
// Convert to array
"string"==typeof a&&(a=this.getMatrix(a));var d,e,f,g,h,i,j,k,l,m,n=+a[0],o=this.$parent,p="undefined"!=typeof c.contain?c.contain:this.options.contain;
// Apply containment
// Use absolute value of scale here as negative scale doesn't mean even smaller
// marginW += dims.widthBorder / 2;
// If the element is not naturally centered, assume full margin right
// Set transition
// Update range
// Set the matrix on this.$set
return p&&(d=this._checkDims(),e=this.container,l=d.width+d.widthBorder,m=d.height+d.heightBorder,f=l*Math.abs(n)>e.width?(l*Math.abs(n)-e.width)/2:0,g=m*Math.abs(n)>e.height?(m*Math.abs(n)-e.height)/2:0,j=d.left+d.margin.left,k=d.top+d.margin.top,"invert"===p?(h=l>e.width?l-e.width:0,i=m>e.height?m-e.height:0,f+=(e.width-l)/2,g+=(e.height-m)/2,a[4]=Math.max(Math.min(a[4],f-j),-f-j-h),a[5]=Math.max(Math.min(a[5],g-k),-g-k-i+d.heightBorder)):(g+=d.heightBorder/2,h=e.width>l?e.width-l:0,i=e.height>m?e.height-m:0,"center"===o.css("textAlign")&&s.test(b.css(this.elem,"display"))?h=0:f=g=0,a[4]=Math.min(Math.max(a[4],f-j),-f-j+h),a[5]=Math.min(Math.max(a[5],g-k),-g-k+i))),"skip"!==c.animate&&this.transition(!c.animate),c.range&&this.$zoomRange.val(n),this.setTransform("matrix("+a.join(",")+")"),c.silent||this._trigger("change",a),a}},/**
		 * @returns {Boolean} Returns whether the panzoom element is currently being dragged
		 */
isPanning:function(){return this.panning},/**
		 * Apply the current transition to the element, if allowed
		 * @param {Boolean} [off] Indicates that the transition should be turned off
		 */
transition:function(a){if(this._transition)for(var c=a||!this.options.transition?"none":this._transition,d=this.$set,e=d.length;e--;)
// Avoid reflows when zooming
b.style(d[e],"transition")!==c&&b.style(d[e],"transition",c)},/**
		 * Pan the element to the specified translation X and Y
		 * Note: this is not the same as setting jQuery#offset() or jQuery#position()
		 * @param {Number} x
		 * @param {Number} y
		 * @param {Object} [options] These options are passed along to setMatrix
		 * @param {Array} [options.matrix] The matrix being manipulated (if already known so it doesn't have to be retrieved again)
		 * @param {Boolean} [options.silent] Silence the pan event. Note that this will also silence the setMatrix change event.
		 * @param {Boolean} [options.relative] Make the x and y values relative to the existing matrix
		 */
pan:function(a,b,c){if(!this.options.disablePan){c||(c={});var d=c.matrix;d||(d=this.getMatrix()),
// Cast existing matrix values to numbers
c.relative&&(a+=+d[4],b+=+d[5]),d[4]=a,d[5]=b,this.setMatrix(d,c),c.silent||this._trigger("pan",d[4],d[5])}},/**
		 * Zoom in/out the element using the scale properties of a transform matrix
		 * @param {Number|Boolean} [scale] The scale to which to zoom or a boolean indicating to transition a zoom out
		 * @param {Object} [opts] All global options can be overwritten by this options object. For example, override the default increment.
		 * @param {Boolean} [opts.noSetRange] Specify that the method should not set the $zoomRange value (as is the case when $zoomRange is calling zoom on change)
		 * @param {jQuery.Event|Object} [opts.focal] A focal point on the panzoom element on which to zoom.
		 *  If an object, set the clientX and clientY properties to the position relative to the parent
		 * @param {Boolean} [opts.animate] Whether to animate the zoom (defaults to true if scale is not a number, false otherwise)
		 * @param {Boolean} [opts.silent] Silence the zoom event
		 * @param {Array} [opts.matrix] Optionally pass the current matrix so it doesn't need to be retrieved
		 * @param {Number} [opts.dValue] Think of a transform matrix as four values a, b, c, d
		 *  where a/d are the horizontal/vertical scale values and b/c are the skew values
		 *  (5 and 6 of matrix array are the tx/ty transform values).
		 *  Normally, the scale is set to both the a and d values of the matrix.
		 *  This option allows you to specify a different d value for the zoom.
		 *  For instance, to flip vertically, you could set -1 as the dValue.
		 */
zoom:function(a,c){
// Shuffle arguments
"object"==typeof a?(c=a,a=null):c||(c={});var d=b.extend({},this.options,c);
// Check if disabled
if(!d.disableZoom){var g=!1,h=d.matrix||this.getMatrix();"number"!=typeof a&&(a=+h[0]+d.increment*(a?-1:1),g=!0),
// Constrain scale
a>d.maxScale?a=d.maxScale:a<d.minScale&&(a=d.minScale);
// Calculate focal point based on scale
var i=d.focal;if(i&&!d.disablePan){
// Adapted from code by Florian Günther
// https://github.com/florianguenther/zui53
var j=this._checkDims(),k=i.clientX,l=i.clientY;
// Adjust the focal point for default transform-origin => 50% 50%
this.isSVG||(k-=(j.width+j.widthBorder)/2,l-=(j.height+j.heightBorder)/2);var m=new f(k,l,1),n=new e(h),o=this.parentOffset||this.$parent.offset(),p=new e(1,0,o.left-this.$doc.scrollLeft(),0,1,o.top-this.$doc.scrollTop()),q=n.inverse().x(p.inverse().x(m)),r=a/h[0];n=n.x(new e([r,0,0,r,0,0])),m=p.x(n.x(q)),h[4]=+h[4]+(k-m.e(0)),h[5]=+h[5]+(l-m.e(1))}
// Set the scale
h[0]=a,h[3]="number"==typeof d.dValue?d.dValue:a,
// Calling zoom may still pan the element
this.setMatrix(h,{animate:"boolean"==typeof d.animate?d.animate:g,
// Set the zoomRange value
range:!d.noSetRange}),
// Trigger zoom event
d.silent||this._trigger("zoom",h[0],d)}},/**
		 * Get/set option on an existing instance
		 * @returns {Array|undefined} If getting, returns an array of all values
		 *   on each instance for a given key. If setting, continue chaining by returning undefined.
		 */
option:function(a,c){var d;if(!a)
// Avoids returning direct reference
return b.extend({},this.options);if("string"==typeof a){if(1===arguments.length)return void 0!==this.options[a]?this.options[a]:null;d={},d[a]=c}else d=a;this._setOptions(d)},/**
		 * Internally sets options
		 * @param {Object} options - An object literal of options to set
		 */
_setOptions:function(a){b.each(a,b.proxy(function(a,c){switch(a){case"disablePan":this._resetStyle();/* falls through */
case"$zoomIn":case"$zoomOut":case"$zoomRange":case"$reset":case"disableZoom":case"onStart":case"onChange":case"onZoom":case"onPan":case"onEnd":case"onReset":case"eventNamespace":this._unbind()}switch(this.options[a]=c,a){case"disablePan":this._initStyle();/* falls through */
case"$zoomIn":case"$zoomOut":case"$zoomRange":case"$reset":
// Set these on the instance
this[a]=c;/* falls through */
case"disableZoom":case"onStart":case"onChange":case"onZoom":case"onPan":case"onEnd":case"onReset":case"eventNamespace":this._bind();break;case"cursor":b.style(this.elem,"cursor",c);break;case"minScale":this.$zoomRange.attr("min",c);break;case"maxScale":this.$zoomRange.attr("max",c);break;case"rangeStep":this.$zoomRange.attr("step",c);break;case"startTransform":this._buildTransform();break;case"duration":case"easing":this._buildTransition();/* falls through */
case"transition":this.transition();break;case"$set":c instanceof b&&c.length&&(this.$set=c,
// Reset styles
this._initStyle(),this._buildTransform())}},this))},/**
		 * Initialize base styles for the element and its parent
		 */
_initStyle:function(){var a={
// Promote the element to it's own compositor layer
"backface-visibility":"hidden",
// Set to defaults for the namespace
"transform-origin":this.isSVG?"0 0":"50% 50%"};
// Set elem styles
this.options.disablePan||(a.cursor=this.options.cursor),this.$set.css(a);
// Set parent to relative if set to static
var c=this.$parent;
// No need to add styles to the body
c.length&&!b.nodeName(c[0],"body")&&(a={overflow:"hidden"},"static"===c.css("position")&&(a.position="relative"),c.css(a))},/**
		 * Undo any styles attached in this plugin
		 */
_resetStyle:function(){this.$elem.css({cursor:"",transition:""}),this.$parent.css({overflow:"",position:""})},/**
		 * Binds all necessary events
		 */
_bind:function(){var a=this,c=this.options,d=c.eventNamespace,e=o?"pointerdown"+d:"touchstart"+d+" mousedown"+d,f=o?"pointerup"+d:"touchend"+d+" click"+d,h={},i=this.$reset,j=this.$zoomRange;
// No bindings if zooming is disabled
if(
// Bind panzoom events from options
b.each(["Start","Change","Zoom","Pan","End","Reset"],function(){var a=c["on"+this];b.isFunction(a)&&(h["panzoom"+this.toLowerCase()+d]=a)}),
// Bind $elem drag and click/touchdown events
// Bind touchstart if either panning or zooming is enabled
c.disablePan&&c.disableZoom||(h[e]=function(b){var d;("touchstart"===b.type?!(d=b.touches)||(1!==d.length||c.disablePan)&&2!==d.length:c.disablePan||1!==b.which)||(b.preventDefault(),b.stopPropagation(),a._startMove(b,d))}),this.$elem.on(h),
// Bind reset
i.length&&i.on(f,function(b){b.preventDefault(),a.reset()}),
// Set default attributes for the range input
j.length&&j.attr({
// Only set the range step if explicit or
// set the default if there is no attribute present
step:c.rangeStep===g.defaults.rangeStep&&j.attr("step")||c.rangeStep,min:c.minScale,max:c.maxScale}).prop({value:this.getMatrix()[0]}),!c.disableZoom){var k=this.$zoomIn,l=this.$zoomOut;
// Bind zoom in/out
// Don't bind one without the other
k.length&&l.length&&(
// preventDefault cancels future mouse events on touch events
k.on(f,function(b){b.preventDefault(),a.zoom()}),l.on(f,function(b){b.preventDefault(),a.zoom(!0)})),j.length&&(h={},h[(o?"pointerdown":"mousedown")+d]=function(){a.transition(!0)},h[(p?"input":"change")+d]=function(){a.zoom(+this.value,{noSetRange:!0})},j.on(h))}},/**
		 * Unbind all events
		 */
_unbind:function(){this.$elem.add(this.$zoomIn).add(this.$zoomOut).add(this.$reset).off(this.options.eventNamespace)},/**
		 * Builds the original transform value
		 */
_buildTransform:function(){
// Save the original transform
// Retrieving this also adds the correct prefixed style name
// to jQuery's internal $.cssProps
return this._origTransform=this.getTransform(this.options.startTransform)},/**
		 * Set transition property for later use when zooming
		 * If SVG, create necessary animations elements for translations and scaling
		 */
_buildTransition:function(){if(this._transform){var a=this.options;this._transition=this._transform+" "+a.duration+"ms "+a.easing}},/**
		 * Checks dimensions to make sure they don't need to be re-calculated
		 */
_checkDims:function(){var a=this.dimensions;
// Rebuild if width or height is still 0
return a.width&&a.height||this.resetDimensions(),this.dimensions},/**
		 * Calculates the distance between two touch points
		 * Remember pythagorean?
		 * @param {Array} touches
		 * @returns {Number} Returns the distance
		 */
_getDistance:function(a){var b=a[0],c=a[1];return Math.sqrt(Math.pow(Math.abs(c.clientX-b.clientX),2)+Math.pow(Math.abs(c.clientY-b.clientY),2))},/**
		 * Constructs an approximated point in the middle of two touch points
		 * @returns {Object} Returns an object containing pageX and pageY
		 */
_getMiddle:function(a){var b=a[0],c=a[1];return{clientX:(c.clientX-b.clientX)/2+b.clientX,clientY:(c.clientY-b.clientY)/2+b.clientY}},/**
		 * Trigger a panzoom event on our element
		 * The event is passed the Panzoom instance
		 * @param {String|jQuery.Event} event
		 * @param {Mixed} arg1[, arg2, arg3, ...] Arguments to append to the trigger
		 */
_trigger:function(a){"string"==typeof a&&(a="panzoom"+a),this.$elem.triggerHandler(a,[this].concat(n.call(arguments,1)))},/**
		 * Starts the pan
		 * This is bound to mouse/touchmove on the element
		 * @param {jQuery.Event} event An event with pageX, pageY, and possibly the touches list
		 * @param {TouchList} [touches] The touches list if present
		 */
_startMove:function(a,d){var e,f,g,h,i,j,k,m,n=this,p=this.options,q=p.eventNamespace,r=this.getMatrix(),s=r.slice(0),t=+s[4],u=+s[5],v={matrix:r,animate:"skip"};
// Use proper events
o?(f="pointermove",g="pointerup"):"touchstart"===a.type?(f="touchmove",g="touchend"):(f="mousemove",g="mouseup"),f+=q,g+=q,this.transition(!0),this.panning=!0,this._trigger("start",a,d),d&&2===d.length?(h=this._getDistance(d),i=+r[0],j=this._getMiddle(d),e=function(a){a.preventDefault();var b=n._getMiddle(d=a.touches),c=n._getDistance(d)-h;n.zoom(c*(p.increment/100)+i,{focal:b,matrix:r,animate:!1}),n.pan(+r[4]+b.clientX-j.clientX,+r[5]+b.clientY-j.clientY,v),j=b}):(k=a.pageX,m=a.pageY,e=function(a){a.preventDefault(),n.pan(t+a.pageX-k,u+a.pageY-m,v)}),b(l).off(q).on(f,e).on(g,function(a){a.preventDefault(),b(this).off(q),n.panning=!1,a.type="panzoomend",n._trigger(a,r,!c(r,s))})}},b.Panzoom=g,b.fn.panzoom=function(a){var c,d,e,f;
// Call methods widget-style
// Call methods widget-style
return"string"==typeof a?(f=[],d=n.call(arguments,1),this.each(function(){c=b.data(this,m),c?"_"!==a.charAt(0)&&"function"==typeof(e=c[a])&&void 0!==(e=e.apply(c,d))&&f.push(e):f.push(void 0)}),f.length?1===f.length?f[0]:f:this):this.each(function(){new g(this,a)})},g});


text:
package dbtarzan.gui.config.connections

import scalafx.scene.layout. { HBox, Region, Priority }
import scalafx.scene.control.Button
import scalafx.event.ActionEvent
import scalafx.Includes._
import scalafx.scene.Parent
import scalafx.geometry.{ Insets, Pos }
import dbtarzan.gui.TControlBuilder
import dbtarzan.localization.Localization

class ConnectionButtons(localization: Localization) extends TControlBuilder {
  private val buttonNew = new Button {
    text = localization.new_
  }

  private val buttonRemove = new Button {
    text = localization.remove
  }

  private val buttonDuplicate = new Button {
    text = localization.duplicate
  }

  private val buttonTest = new Button {
    text = localization.test
  }

  private val buttonCancel = new Button {
    text = localization.cancel
    alignmentInParent = Pos.CENTER_RIGHT
  }

  private val buttonSave = new Button {
    text = localization.save
    alignmentInParent = Pos.CENTER_RIGHT
  }

	private val layout = new HBox {
    children = List(
      buttonNew,
      buttonRemove,
      buttonDuplicate,
      new Region() { hgrow = Priority.Always },
      buttonTest,
      new Region() { hgrow = Priority.Always },
      buttonSave,
      buttonCancel
    )
  	padding = Insets(10)
  	spacing = 10
  }

  def onNew(action : () => Unit ): Unit =
    buttonNew.onAction = (event: ActionEvent)  => action()

  def onRemove(action : () => Unit ): Unit =
    buttonRemove.onAction = (event: ActionEvent)  => action()

  def onDuplicate(action : () => Unit ): Unit =
    buttonDuplicate.onAction = (event: ActionEvent)  => action()

  def onTest(action : () => Unit ): Unit =
    buttonTest.onAction = (event: ActionEvent)  => action()

  def onSave(action : () => Unit ): Unit =
    buttonSave.onAction = (event: ActionEvent)  => action()

  def onCancel(action : () => Unit ): Unit =
    buttonCancel.onAction = (event: ActionEvent)  => action()

  def control : Parent = layout
}


text:
package org.jgroups.protocols.relay;

import org.jgroups.util.AsciiString;
import org.jgroups.util.ExtendedUUID;
import org.jgroups.util.UUID;
import org.jgroups.util.Util;

import java.util.Arrays;

/**
 * Implementation of SiteAddress
 * @author Bela Ban
 * @since 3.2
 */
public class SiteUUID extends ExtendedUUID implements SiteAddress {
    protected static final byte[] NAME      = Util.stringToBytes("name"); // logical name, can be null
    protected static final byte[] SITE_NAME = Util.stringToBytes("site");
    private static final long     serialVersionUID=7128439052905502361L;

    public SiteUUID() {
    }

    public SiteUUID(long mostSigBits, long leastSigBits, String name, String site) {
        super(mostSigBits,leastSigBits);
        if(name != null)
            put(NAME, Util.stringToBytes(name));
        put(SITE_NAME, Util.stringToBytes(site));
    }

    public SiteUUID(long mostSigBits, long leastSigBits, byte[] name, byte[] site) {
        super(mostSigBits,leastSigBits);
        if(name != null)
            put(NAME, name);
        put(SITE_NAME, site);
    }

    public SiteUUID(UUID uuid, String name, String site) {
        super(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits());
        if(name != null)
            put(NAME, Util.stringToBytes(name));
        put(SITE_NAME, Util.stringToBytes(site));
    }

    public String getName() {
        return Util.bytesToString(get(NAME));
    }

    public String getSite() {
        return Util.bytesToString(get(SITE_NAME));
    }

    public UUID copy() {
        return new SiteUUID(mostSigBits, leastSigBits, get(NAME), get(SITE_NAME));
    }

    @Override
    public String toString() {
        return print(false);
    }

    public String print(boolean detailed) {
        String name=getName();
        String retval=name != null? name : get(this);
        return retval + ":" + getSite() + (detailed? printOthers() : "");
    }

    protected String printOthers() {
        StringBuilder sb=new StringBuilder();
        if(flags != 0)
            sb.append(" flags=" + flags + " (" + flagsToString() + ")");
        if(keys == null)
            return sb.toString();
        for(int i=0; i < keys.length; i++) {
            byte[] key=keys[i];
            if(key == null || Arrays.equals(key,SITE_NAME) || Arrays.equals(key, NAME))
                continue;
            byte[] val=values[i];
            Object obj=null;
            try {
                obj=Util.objectFromByteBuffer(val);
            }
            catch(Throwable t) {
            }
            if(obj == null) {
                try {
                    obj=Util.bytesToString(val);
                }
                catch(Throwable t) {
                    obj=val != null? val.length + " bytes" : null;
                }
            }

            sb.append(", ").append(new AsciiString(key)).append("=").append(obj);
        }
        return sb.toString();
    }
}


text:
namespace base {
class DictionaryValue;
class ListValue;
}  // namespace base

namespace content {

// This class takes the arugment of json format from
// GpuBenchmarking::PointerActionSequence, parses it and warps
// it into a SyntheticPointerActionListParams object.
class ActionsParser {
 public:
  explicit ActionsParser(base::Value* value);
  ~ActionsParser();
  bool ParsePointerActionSequence();
  std::string error_message() { return error_message_; }
  std::unique_ptr<SyntheticPointerActionListParams> gesture_params() {
    return std::move(gesture_params_);
  }

 private:
  bool ParsePointerActions(const base::DictionaryValue& pointer_actions);
  bool ParseActions(const base::ListValue& actions);
  bool ParseAction(const base::DictionaryValue& action,
                   SyntheticPointerActionListParams::ParamList& param_list);

  std::unique_ptr<SyntheticPointerActionListParams> gesture_params_;
  std::vector<SyntheticPointerActionListParams::ParamList>
      pointer_actions_list_;
  size_t longest_action_sequence_;
  std::string source_type_;
  std::string error_message_;

  base::Value* pointer_actions_value_;
  int action_index_;

  DISALLOW_COPY_AND_ASSIGN(ActionsParser);
};

}  // namespace content

#endif  // CONTENT_RENDERER_GPU_ACTION_PARSER_H_


text:
YiiBooster v1.0.7
==========

YiiBooster is a widget toolkit for [Yii web framework](http://www.yiiframework.com).
Its main purpose is to ease building UI in Yii-based web applications utilizing the beauty of [Twitter Bootstrap][twitter-bootstrap]
and several other great UI plugins developed over time by the community.

Twitter Bootstrap wrapping is based over the excellent job of [Christoffer Niska](https://twitter.com/Crisu83) called [Yii-Bootstrap](http://www.cniska.net/yii-bootstrap/).
We at [Clevertech](http://clevertech.biz) included his library into our own Yii project startup library, [YiiBoilerplate](http://github.com/clevertech/yiiboilerplate),
and started improving it in order to satisfy some of our customers' project requirements.
YiiBooster is an end result of this effort.

## Widgets at a glance
Overall, the following is included in YiiBooster:

* All of most current [Twitter Bootstrap][twitter-bootstrap] goodness we were able to integrate with.
* [FontAwesome icons pack](http://fortawesome.github.io/Font-Awesome/) for Twitter Bootstrap.
* [jQuery File Upload](https://github.com/blueimp/jQuery-File-Upload) widget for fancy file uploads.
* [jQueryUI/Bootstrap](http://addyosmani.github.io/jquery-ui-bootstrap/) integration.
* [Select2](http://ivaynberg.github.io/select2/) widget for fancy selectors.
* [X-Editable](http://vitalets.github.io/x-editable/) plugin for in-place editing of table cells values.
* [jQRangeSlider](http://ghusse.github.io/jQRangeSlider/) widget for additional awesomeness.
* Absolutely crazy custom grid views called [TbExtendedGridView](http://yii-booster.clevertech.biz/extended-grid.html)
and [TbJsonGridView](http://yii-booster.clevertech.biz/json-grid.html), packed with features to the brim.
* *Four* different WYSIWYG editors for you to choose: [wysihtml5](https://github.com/xing/wysihtml5) [with Bootstrap integration](https://github.com/jhollingworth/bootstrap-wysihtml5),
[jQuery Markdown](https://github.com/arhpreston/jquery-markdown), [CKEditor](http://ckeditor.com/) and [Redactor](http://imperavi.com/redactor/).
And don't be afraid to use Redactor, because Yii community bought an ORM license for it.
* And several other little and not-so-little widgets for you to use.

## Quick Start

If you want, you can clone the [github repo](https://github.com/clevertech/YiiBooster) and get the full codebase
to build the distributive or documentation or just to hack something.

If you just want to _use_ YiiBooster, you need to [download the latest distributive archive](https://github.com/clevertech/YiiBooster/zipball/master).
After that, consult the [YiiBooster documentation website][booster-docs] or the `INSTALL.md` file included in the package.

## Widgets end-user documentation
Check out [YiiBooster documentation website][booster-docs].

## Contributing
Please submit all pull requests against `*-wip` branches.
All details are explained in the [wiki page describing how to properly contribute to this repository](https://github.com/clevertech/YiiBooster/wiki/How-to-contribute-to-this-repository)

## Bug tracker
If you find any bugs, please create an issue at [issue tracker for project Github repository](https://github.com/clevertech/YiiBooster/issues).

## License
This work is licensed under a MIT license. Full text is included in the `LICENSE` file in the root of codebase.

[![Clevertech](http://clevertech.biz/images/slir/w54-h36-c54:36/images/site/index/home/clevertech-logo.png)](http://www.clevertech.biz)

Well-built beautifully designed web applications.

[www.clevertech.biz](http://www.clevertech.biz)

[twitter-bootstrap]: http://twitter.github.com/bootstrap/
[booster-docs]: http://yii-booster.clevertech.biz/


text:
namespace extensions {

AsyncExtensionFunction::ResponseAction
DataReductionProxyClearDataSavingsFunction::Run() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  data_reduction_proxy::DataReductionProxySettings* settings =
      DataReductionProxyChromeSettingsFactory::GetForBrowserContext(
          browser_context());
  settings->data_reduction_proxy_service()->compression_stats()->
      ClearDataSavingStatistics();
  return RespondNow(NoArguments());
}

}  // namespace extensions


text:
import copy
import uuid

import mock
import six
import yaml

from mistralclient.api.v2 import executions
from mistralclient.api.v2 import tasks
from mistralclient.api.v2 import workbooks
from mistralclient.api.v2 import workflows
from oslo_config import cfg

# XXX: actionsensor import depends on config being setup.
import st2tests.config as tests_config
tests_config.parse_args()

# Set defaults for retry options.
cfg.CONF.set_override('retry_exp_msec', 100, group='mistral')
cfg.CONF.set_override('retry_exp_max_msec', 200, group='mistral')
cfg.CONF.set_override('retry_stop_max_msec', 200, group='mistral')

import st2common.bootstrap.runnersregistrar as runners_registrar
from st2actions.runners.localrunner import LocalShellRunner
from st2actions.runners.mistral.v2 import MistralRunner
from st2common.constants import action as action_constants
from st2common.models.api.action import ActionAPI
from st2common.models.db.liveaction import LiveActionDB
from st2common.persistence.action import Action
from st2common.persistence.liveaction import LiveAction
from st2common.services import action as action_service
from st2common.transport.liveaction import LiveActionPublisher
from st2common.transport.publishers import CUDPublisher
from st2tests import DbTestCase
from st2tests.fixturesloader import FixturesLoader
from tests.unit.base import MockLiveActionPublisher

TEST_FIXTURES = {
    'workflows': [
        'workflow_v2.yaml',
        'workbook_v2_many_workflows.yaml'
    ],
    'actions': [
        'workflow_v2.yaml',
        'workbook_v2_many_workflows.yaml',
        'local.yaml'
    ]
}

PACK = 'generic'
LOADER = FixturesLoader()
FIXTURES = LOADER.load_fixtures(fixtures_pack=PACK, fixtures_dict=TEST_FIXTURES)

# Workbook with multiple workflows
WB1_YAML_FILE_NAME = TEST_FIXTURES['workflows'][1]
WB1_YAML_FILE_PATH = LOADER.get_fixture_file_path_abs(PACK, 'workflows', WB1_YAML_FILE_NAME)
WB1_SPEC = FIXTURES['workflows'][WB1_YAML_FILE_NAME]
WB1_YAML = yaml.safe_dump(WB1_SPEC, default_flow_style=False)
WB1_NAME = '%s.%s' % (PACK, WB1_YAML_FILE_NAME.replace('.yaml', ''))
WB1 = workbooks.Workbook(None, {'name': WB1_NAME, 'definition': WB1_YAML})
WB1_MAIN_EXEC = {'id': str(uuid.uuid4()), 'state': 'RUNNING'}
WB1_MAIN_EXEC['workflow_name'] = WB1_NAME + '.main'
WB1_MAIN_EXEC_ERRORED = copy.deepcopy(WB1_MAIN_EXEC)
WB1_MAIN_EXEC_ERRORED['state'] = 'ERROR'
WB1_MAIN_TASK1 = {'id': str(uuid.uuid4()), 'name': 'greet', 'state': 'ERROR'}
WB1_MAIN_TASKS = [tasks.Task(None, WB1_MAIN_TASK1)]
WB1_MAIN_TASK_ID = WB1_MAIN_TASK1['id']
WB1_SUB1_EXEC = {'id': str(uuid.uuid4()), 'state': 'RUNNING', 'task_execution_id': WB1_MAIN_TASK_ID}
WB1_SUB1_EXEC['workflow_name'] = WB1_NAME + '.subflow1'
WB1_SUB1_EXEC_ERRORED = copy.deepcopy(WB1_SUB1_EXEC)
WB1_SUB1_EXEC_ERRORED['state'] = 'ERROR'
WB1_SUB1_TASK1 = {'id': str(uuid.uuid4()), 'name': 'say-greeting', 'state': 'SUCCESS'}
WB1_SUB1_TASK2 = {'id': str(uuid.uuid4()), 'name': 'say-friend', 'state': 'ERROR'}
WB1_SUB1_TASKS = [tasks.Task(None, WB1_SUB1_TASK1), tasks.Task(None, WB1_SUB1_TASK2)]

# Non-workbook with a single workflow
WF1_YAML_FILE_NAME = TEST_FIXTURES['workflows'][0]
WF1_YAML_FILE_PATH = LOADER.get_fixture_file_path_abs(PACK, 'workflows', WF1_YAML_FILE_NAME)
WF1_SPEC = FIXTURES['workflows'][WF1_YAML_FILE_NAME]
WF1_YAML = yaml.safe_dump(WF1_SPEC, default_flow_style=False)
WF1_NAME = '%s.%s' % (PACK, WF1_YAML_FILE_NAME.replace('.yaml', ''))
WF1 = workflows.Workflow(None, {'name': WF1_NAME, 'definition': WF1_YAML})
WF1_EXEC = {'id': str(uuid.uuid4()), 'state': 'ERROR', 'workflow_name': WF1_NAME}
WF1_EXEC_NOT_RERUNABLE = copy.deepcopy(WF1_EXEC)
WF1_EXEC_NOT_RERUNABLE['state'] = 'PAUSED'
WF1_TASK1 = {'id': str(uuid.uuid4()), 'name': 'say-greeting', 'state': 'SUCCESS'}
WF1_TASK2 = {'id': str(uuid.uuid4()), 'name': 'say-friend', 'state': 'SUCCESS'}
WF1_TASKS = [tasks.Task(None, WF1_TASK1), tasks.Task(None, WF1_TASK2)]

# Action executions requirements
ACTION_PARAMS = {'friend': 'Rocky'}

NON_EMPTY_RESULT = 'non-empty'

@mock.patch.object(LocalShellRunner, 'run', mock.
                   MagicMock(return_value=(action_constants.LIVEACTION_STATUS_SUCCEEDED,
                                           NON_EMPTY_RESULT, None)))
@mock.patch.object(CUDPublisher, 'publish_update', mock.MagicMock(return_value=None))
@mock.patch.object(CUDPublisher, 'publish_create',
                   mock.MagicMock(side_effect=MockLiveActionPublisher.publish_create))
@mock.patch.object(LiveActionPublisher, 'publish_state',
                   mock.MagicMock(side_effect=MockLiveActionPublisher.publish_state))
class MistralRunnerTest(DbTestCase):

    @classmethod
    def setUpClass(cls):
        super(MistralRunnerTest, cls).setUpClass()
        runners_registrar.register_runner_types()

        for _, fixture in six.iteritems(FIXTURES['actions']):
            instance = ActionAPI(**fixture)
            Action.add_or_update(ActionAPI.to_model(instance))

    def setUp(self):
        super(MistralRunnerTest, self).setUp()
        cfg.CONF.set_override('api_url', 'http://0.0.0.0:9101', group='auth')

    @mock.patch.object(
        workflows.WorkflowManager, 'list',
        mock.MagicMock(return_value=[]))
    @mock.patch.object(
        workflows.WorkflowManager, 'get',
        mock.MagicMock(return_value=WF1))
    @mock.patch.object(
        workflows.WorkflowManager, 'create',
        mock.MagicMock(return_value=[WF1]))
    @mock.patch.object(
        executions.ExecutionManager, 'create',
        mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC)))
    @mock.patch.object(
        MistralRunner, 'resume',
        mock.MagicMock(
            return_value=(action_constants.LIVEACTION_STATUS_RUNNING,
                          {'tasks': []},
                          {'execution_id': str(uuid.uuid4())})
        )
    )
    def test_resume_option(self):
        MistralRunner.entry_point = mock.PropertyMock(return_value=WF1_YAML_FILE_PATH)
        liveaction1 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS)
        liveaction1, execution1 = action_service.request(liveaction1)
        self.assertFalse(MistralRunner.resume.called)

        # Rerun the execution.
        context = {
            're-run': {
                'ref': execution1.id,
                'tasks': ['x']
            }
        }

        liveaction2 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS, context=context)
        liveaction2, execution2 = action_service.request(liveaction2)
        liveaction2 = LiveAction.get_by_id(str(liveaction2.id))
        self.assertEqual(liveaction2.status, action_constants.LIVEACTION_STATUS_RUNNING)

        task_specs = {
            'x': {
                'reset': False
            }
        }

        MistralRunner.resume.assert_called_with(ex_ref=execution1, task_specs=task_specs)

    @mock.patch.object(
        workflows.WorkflowManager, 'list',
        mock.MagicMock(return_value=[]))
    @mock.patch.object(
        workflows.WorkflowManager, 'get',
        mock.MagicMock(return_value=WF1))
    @mock.patch.object(
        workflows.WorkflowManager, 'create',
        mock.MagicMock(return_value=[WF1]))
    @mock.patch.object(
        executions.ExecutionManager, 'create',
        mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC)))
    @mock.patch.object(
        MistralRunner, 'resume',
        mock.MagicMock(
            return_value=(action_constants.LIVEACTION_STATUS_RUNNING,
                          {'tasks': []},
                          {'execution_id': str(uuid.uuid4())})
        )
    )
    def test_resume_option_reset_tasks(self):
        MistralRunner.entry_point = mock.PropertyMock(return_value=WF1_YAML_FILE_PATH)
        liveaction1 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS)
        liveaction1, execution1 = action_service.request(liveaction1)
        self.assertFalse(MistralRunner.resume.called)

        # Rerun the execution.
        context = {
            're-run': {
                'ref': execution1.id,
                'tasks': ['x', 'y'],
                'reset': ['y']
            }
        }

        liveaction2 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS, context=context)
        liveaction2, execution2 = action_service.request(liveaction2)
        liveaction2 = LiveAction.get_by_id(str(liveaction2.id))
        self.assertEqual(liveaction2.status, action_constants.LIVEACTION_STATUS_RUNNING)

        task_specs = {
            'x': {
                'reset': False
            },
            'y': {
                'reset': True
            }
        }

        MistralRunner.resume.assert_called_with(ex_ref=execution1, task_specs=task_specs)

    @mock.patch.object(
        workflows.WorkflowManager, 'list',
        mock.MagicMock(return_value=[]))
    @mock.patch.object(
        workflows.WorkflowManager, 'get',
        mock.MagicMock(return_value=WF1))
    @mock.patch.object(
        workflows.WorkflowManager, 'create',
        mock.MagicMock(return_value=[WF1]))
    @mock.patch.object(
        executions.ExecutionManager, 'create',
        mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC_NOT_RERUNABLE)))
    @mock.patch.object(
        executions.ExecutionManager, 'get',
        mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC_NOT_RERUNABLE)))
    @mock.patch.object(
        tasks.TaskManager, 'list',
        mock.MagicMock(return_value=WF1_TASKS))
    def test_resume_workflow_not_in_rerunable_state(self):
        MistralRunner.entry_point = mock.PropertyMock(return_value=WF1_YAML_FILE_PATH)
        liveaction1 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS)
        liveaction1, execution1 = action_service.request(liveaction1)

        # Rerun the execution.
        context = {
            're-run': {
                'ref': execution1.id,
                'tasks': ['say-friend']
            }
        }

        liveaction2 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS, context=context)
        liveaction2, execution2 = action_service.request(liveaction2)
        liveaction2 = LiveAction.get_by_id(str(liveaction2.id))
        self.assertEqual(liveaction2.status, action_constants.LIVEACTION_STATUS_FAILED)
        self.assertIn('not in a rerunable state', liveaction2.result.get('error'))

    @mock.patch.object(
        workflows.WorkflowManager, 'list',
        mock.MagicMock(return_value=[]))
    @mock.patch.object(
        workflows.WorkflowManager, 'get',
        mock.MagicMock(return_value=WF1))
    @mock.patch.object(
        workflows.WorkflowManager, 'create',
        mock.MagicMock(return_value=[WF1]))
    @mock.patch.object(
        executions.ExecutionManager, 'list',
        mock.MagicMock(return_value=[executions.Execution(None, WF1_EXEC)]))
    @mock.patch.object(
        executions.ExecutionManager, 'create',
        mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC)))
    @mock.patch.object(
        executions.ExecutionManager, 'get',
        mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC)))
    @mock.patch.object(
        tasks.TaskManager, 'list',
        mock.MagicMock(return_value=WF1_TASKS))
    def test_resume_tasks_not_in_rerunable_state(self):
        MistralRunner.entry_point = mock.PropertyMock(return_value=WF1_YAML_FILE_PATH)
        liveaction1 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS)
        liveaction1, execution1 = action_service.request(liveaction1)

        # Rerun the execution.
        context = {
            're-run': {
                'ref': execution1.id,
                'tasks': ['say-friend']
            }
        }

        liveaction2 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS, context=context)
        liveaction2, execution2 = action_service.request(liveaction2)
        liveaction2 = LiveAction.get_by_id(str(liveaction2.id))
        self.assertEqual(liveaction2.status, action_constants.LIVEACTION_STATUS_FAILED)
        self.assertIn('Unable to identify rerunable', liveaction2.result.get('error'))

    @mock.patch.object(
        workflows.WorkflowManager, 'list',
        mock.MagicMock(return_value=[]))
    @mock.patch.object(
        workflows.WorkflowManager, 'get',
        mock.MagicMock(return_value=WF1))
    @mock.patch.object(
        workflows.WorkflowManager, 'create',
        mock.MagicMock(return_value=[WF1]))
    @mock.patch.object(
        executions.ExecutionManager, 'list',
        mock.MagicMock(return_value=[executions.Execution(None, WF1_EXEC)]))
    @mock.patch.object(
        executions.ExecutionManager, 'create',
        mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC)))
    @mock.patch.object(
        executions.ExecutionManager, 'get',
        mock.MagicMock(return_value=executions.Execution(None, WF1_EXEC)))
    @mock.patch.object(
        tasks.TaskManager, 'list',
        mock.MagicMock(return_value=WF1_TASKS))
    def test_resume_unidentified_tasks(self):
        MistralRunner.entry_point = mock.PropertyMock(return_value=WF1_YAML_FILE_PATH)
        liveaction1 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS)
        liveaction1, execution1 = action_service.request(liveaction1)

        # Rerun the execution.
        context = {
            're-run': {
                'ref': execution1.id,
                'tasks': ['x']
            }
        }

        liveaction2 = LiveActionDB(action=WF1_NAME, parameters=ACTION_PARAMS, context=context)
        liveaction2, execution2 = action_service.request(liveaction2)
        liveaction2 = LiveAction.get_by_id(str(liveaction2.id))
        self.assertEqual(liveaction2.status, action_constants.LIVEACTION_STATUS_FAILED)
        self.assertIn('Unable to identify', liveaction2.result.get('error'))

    @mock.patch.object(
        workflows.WorkflowManager, 'list',
        mock.MagicMock(return_value=[]))
    @mock.patch.object(
        workflows.WorkflowManager, 'get',
        mock.MagicMock(return_value=WF1))
    @mock.patch.object(
        workbooks.WorkbookManager, 'create',
        mock.MagicMock(return_value=WB1))
    @mock.patch.object(
        executions.ExecutionManager, 'create',
        mock.MagicMock(return_value=executions.Execution(None, WB1_MAIN_EXEC)))
    @mock.patch.object(
        executions.ExecutionManager, 'get',
        mock.MagicMock(return_value=executions.Execution(None, WB1_MAIN_EXEC_ERRORED)))
    @mock.patch.object(
        executions.ExecutionManager, 'list',
        mock.MagicMock(
            return_value=[
                executions.Execution(None, WB1_MAIN_EXEC_ERRORED),
                executions.Execution(None, WB1_SUB1_EXEC_ERRORED)]))
    @mock.patch.object(
        tasks.TaskManager, 'list',
        mock.MagicMock(side_effect=[WB1_MAIN_TASKS, WB1_SUB1_TASKS]))
    @mock.patch.object(
        tasks.TaskManager, 'rerun',
        mock.MagicMock(return_value=None))
    def test_resume_subworkflow_task(self):
        MistralRunner.entry_point = mock.PropertyMock(return_value=WB1_YAML_FILE_PATH)
        liveaction1 = LiveActionDB(action=WB1_NAME, parameters=ACTION_PARAMS)
        liveaction1, execution1 = action_service.request(liveaction1)

        # Rerun the execution.
        context = {
            're-run': {
                'ref': execution1.id,
                'tasks': ['greet.say-friend']
            }
        }

        liveaction2 = LiveActionDB(action=WB1_NAME, parameters=ACTION_PARAMS, context=context)
        liveaction2, execution2 = action_service.request(liveaction2)
        liveaction2 = LiveAction.get_by_id(str(liveaction2.id))

        self.assertEqual(liveaction2.status, action_constants.LIVEACTION_STATUS_RUNNING)

        expected_env = {
            'st2_liveaction_id': str(liveaction2.id),
            'st2_execution_id': str(execution2.id),
            '__actions': {
                'st2.action': {
                    'st2_context': {
                        'endpoint': 'http://0.0.0.0:9101/v1/actionexecutions',
                        'notify': {},
                        'parent': {
                            're-run': context['re-run'],
                            'execution_id': str(execution2.id)
                        },
                        'skip_notify_tasks': []
                    }
                }
            },
            'st2_action_api_url': 'http://0.0.0.0:9101/v1'
        }

        tasks.TaskManager.rerun.assert_called_with(
            WB1_SUB1_TASK2['id'],
            reset=False,
            env=expected_env
        )

    @mock.patch.object(
        workflows.WorkflowManager, 'list',
        mock.MagicMock(return_value=[]))
    @mock.patch.object(
        workflows.WorkflowManager, 'get',
        mock.MagicMock(return_value=WF1))
    @mock.patch.object(
        workbooks.WorkbookManager, 'create',
        mock.MagicMock(return_value=WB1))
    @mock.patch.object(
        executions.ExecutionManager, 'create',
        mock.MagicMock(return_value=executions.Execution(None, WB1_MAIN_EXEC)))
    @mock.patch.object(
        executions.ExecutionManager, 'get',
        mock.MagicMock(return_value=executions.Execution(None, WB1_MAIN_EXEC_ERRORED)))
    @mock.patch.object(
        executions.ExecutionManager, 'list',
        mock.MagicMock(
            return_value=[
                executions.Execution(None, WB1_MAIN_EXEC_ERRORED),
                executions.Execution(None, WB1_SUB1_EXEC_ERRORED)]))
    @mock.patch.object(
        tasks.TaskManager, 'list',
        mock.MagicMock(side_effect=[WB1_MAIN_TASKS, WB1_SUB1_TASKS]))
    def test_resume_unidentified_subworkflow_task(self):
        MistralRunner.entry_point = mock.PropertyMock(return_value=WB1_YAML_FILE_PATH)
        liveaction1 = LiveActionDB(action=WB1_NAME, parameters=ACTION_PARAMS)
        liveaction1, execution1 = action_service.request(liveaction1)

        # Rerun the execution.
        context = {
            're-run': {
                'ref': execution1.id,
                'tasks': ['greet.x']
            }
        }

        liveaction2 = LiveActionDB(action=WB1_NAME, parameters=ACTION_PARAMS, context=context)
        liveaction2, execution2 = action_service.request(liveaction2)
        liveaction2 = LiveAction.get_by_id(str(liveaction2.id))
        self.assertEqual(liveaction2.status, action_constants.LIVEACTION_STATUS_FAILED)
        self.assertIn('Unable to identify', liveaction2.result.get('error'))

    @mock.patch.object(
        workflows.WorkflowManager, 'list',
        mock.MagicMock(return_value=[]))
    @mock.patch.object(
        workflows.WorkflowManager, 'get',
        mock.MagicMock(return_value=WF1))
    @mock.patch.object(
        workbooks.WorkbookManager, 'create',
        mock.MagicMock(return_value=WB1))
    @mock.patch.object(
        executions.ExecutionManager, 'create',
        mock.MagicMock(return_value=executions.Execution(None, WB1_MAIN_EXEC)))
    @mock.patch.object(
        executions.ExecutionManager, 'get',
        mock.MagicMock(return_value=executions.Execution(None, WB1_MAIN_EXEC_ERRORED)))
    @mock.patch.object(
        executions.ExecutionManager, 'list',
        mock.MagicMock(
            return_value=[
                executions.Execution(None, WB1_MAIN_EXEC_ERRORED),
                executions.Execution(None, WB1_SUB1_EXEC_ERRORED)]))
    @mock.patch.object(
        tasks.TaskManager, 'list',
        mock.MagicMock(side_effect=[WB1_MAIN_TASKS, WB1_SUB1_TASKS]))
    @mock.patch.object(
        tasks.TaskManager, 'rerun',
        mock.MagicMock(return_value=None))
    def test_resume_and_reset_subworkflow_task(self):
        MistralRunner.entry_point = mock.PropertyMock(return_value=WB1_YAML_FILE_PATH)
        liveaction1 = LiveActionDB(action=WB1_NAME, parameters=ACTION_PARAMS)
        liveaction1, execution1 = action_service.request(liveaction1)

        # Rerun the execution.
        context = {
            're-run': {
                'ref': execution1.id,
                'tasks': ['greet.say-friend'],
                'reset': ['greet.say-friend']
            }
        }

        liveaction2 = LiveActionDB(action=WB1_NAME, parameters=ACTION_PARAMS, context=context)
        liveaction2, execution2 = action_service.request(liveaction2)
        liveaction2 = LiveAction.get_by_id(str(liveaction2.id))

        self.assertEqual(liveaction2.status, action_constants.LIVEACTION_STATUS_RUNNING)

        expected_env = {
            'st2_liveaction_id': str(liveaction2.id),
            'st2_execution_id': str(execution2.id),
            '__actions': {
                'st2.action': {
                    'st2_context': {
                        'endpoint': 'http://0.0.0.0:9101/v1/actionexecutions',
                        'notify': {},
                        'parent': {
                            're-run': context['re-run'],
                            'execution_id': str(execution2.id)
                        },
                        'skip_notify_tasks': []
                    }
                }
            },
            'st2_action_api_url': 'http://0.0.0.0:9101/v1'
        }

        tasks.TaskManager.rerun.assert_called_with(
            WB1_SUB1_TASK2['id'],
            reset=True,
            env=expected_env
        )


text:
from unittest import TestCase

from allennlp.models.archival import load_archive
from allennlp.service.predictors import Predictor

class TestSrlPredictor(TestCase):
    def test_uses_named_inputs(self):
        inputs = {
                "sentence": "The squirrel wrote a unit test to make sure its nuts worked as designed."
        }

        archive = load_archive('tests/fixtures/srl/serialization/model.tar.gz')
        predictor = Predictor.from_archive(archive, 'semantic-role-labeling')

        result = predictor.predict_json(inputs)

        words = result.get("words")
        assert words == ["The", "squirrel", "wrote", "a", "unit", "test",
                         "to", "make", "sure", "its", "nuts", "worked", "as", "designed", "."]
        num_words = len(words)

        verbs = result.get("verbs")
        assert verbs is not None
        assert isinstance(verbs, list)

        assert any(v["verb"] == "wrote" for v in verbs)
        assert any(v["verb"] == "make" for v in verbs)
        assert any(v["verb"] == "worked" for v in verbs)

        for verb in verbs:
            tags = verb.get("tags")
            assert tags is not None
            assert isinstance(tags, list)
            assert all(isinstance(tag, str) for tag in tags)
            assert len(tags) == num_words


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>

    <predicate lemma="wharf">

        <roleset framnet="-" id="wharf.01" name="shore up a river bank" vncls="9.9">
            <roles>
                <role descr="agent, entity building or deciding to build a wharf" f="" n="0">
                    <vnrole vncls="butter-9.9" vntheta="agent"/>
                </role>

                <role descr="the shore/bank" f="" n="1">
                    <vnrole vncls="butter-9.9" vntheta="destination"/>
                </role>
                <role descr="wharf structure or materials" f="" n="2">
                    <vnrole vncls="butter-9.9" vntheta="theme"/>
                </role>
                <note/>
            </roles>

            <example name="All args" src="internet" type="-">
                <inflection aspect="ns" form="full" person="third" tense="past" voice="active"/>
                <text>They wharfed the narrow channel with a wall of a brick to keep the bank from falling in.</text>

                <arg f="" n="0">They</arg>
                <rel f="">wharfed</rel>
                <arg f="" n="1">the narrow channel</arg>
                <arg f="" n="2">with a wall of brick</arg>
                <arg f="prp" n="m">to keep the bank from falling in.</arg>
                <note/>
            </example>
            <note>Roleset based on internet search. Member of Vncls 9.9. Comparison to 'roof'. Roleset by Julia.</note>
        </roleset>
        <roleset framnet="-" id="wharf.02" name="leave at a wharf" vncls="9.10">
            <roles>
                <role descr="agent, entity dropping off the goods" f="" n="0">
                    <vnrole vncls="pocket-9.10" vntheta="agent"/>
                </role>

                <role descr="the goods" f="" n="1">
                    <vnrole vncls="pocket-9.10" vntheta="theme"/>
                </role>
                <role descr="the wharf itself" f="" n="2">
                    <vnrole vncls="pocket-9.10" vntheta="location"/>
                </role>
                <note>Arg 2 not observed, but predicted.</note>
            </roles>

            <example name="Standard example" src="internet" type="-">
                <inflection aspect="ns" form="full" person="third" tense="past" voice="active"/>
                <text>They wharfed the goods safely.</text>

                <arg f="" n="0">They</arg>
                <rel f="">wharfed</rel>
                <arg f="" n="1">the goods</arg>
                <arg f="mnr" n="m">safely</arg>
                <note/>
            </example>
            <note>Roleset based on internet search. Member of Vncls 9.10. Comparison to 'warehouse'. Roleset by Julia.</note>
        </roleset>
        <roleset framnet="-" id="wharf.03" name="dock at a wharf" vncls="9.1">
            <roles>
                <role descr="The crew" f="" n="0">
                    <vnrole vncls="put-9.1-1" vntheta="agent"/>
                </role>

                <role descr="the ship" f="" n="1">
                    <vnrole vncls="put-9.1-1" vntheta="theme"/>
                </role>
                <role descr="location" f="" n="2">
                    <vnrole vncls="put-9.1-1" vntheta="destination"/>
                </role>
                <note/>
            </roles>

            <example name="All args" src="internet" type="-">
                <inflection aspect="ns" form="full" person="third" tense="past" voice="active"/>
                <text>They wharfed the patrol boat out front.</text>

                <arg f="" n="0">They</arg>
                <rel f="">wharfed</rel>
                <arg f="" n="1">the patrol boat</arg>
                <arg f="" n="2">out front</arg>
                <note/>
            </example>
            <example name="Theme as subject" src="internet" type="-">
                <inflection aspect="ns" form="full" person="third" tense="past" voice="active"/>
                <text>The big ship wharfed in the evening.</text>

                <arg f="" n="1">The big ship</arg>
                <rel f="">wharfed</rel>
                <arg f="tmp" n="m">in the evening.</arg>
                <note/>
            </example>
            <note>Roleset based on internet search. Member of Vncls 9.1-1. Comparison to 'dock'. Roleset by Julia.</note>
        </roleset>
        <note/>
    </predicate>
    <note/>
</frameset>