text:
package beego

import (
	"crypto/tls"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"strings"

	"github.com/beego/beego/config"
	"github.com/beego/beego/context"
	"github.com/beego/beego/logs"
	"github.com/beego/beego/session"
	"github.com/beego/beego/utils"
)

// Config is the main struct for BConfig
type Config struct {
	AppName             string // Application name
	RunMode             string // Running Mode: dev | prod
	RouterCaseSensitive bool
	ServerName          string
	RecoverPanic        bool
	RecoverFunc         func(*context.Context)
	CopyRequestBody     bool
	EnableGzip          bool
	MaxMemory           int64
	EnableErrorsShow    bool
	EnableErrorsRender  bool
	Listen              Listen
	WebConfig           WebConfig
	Log                 LogConfig
}

// Listen holds for http and https related config
type Listen struct {
	Graceful          bool // Graceful means use graceful module to start the server
	ServerTimeOut     int64
	ListenTCP4        bool
	EnableHTTP        bool
	HTTPAddr          string
	HTTPPort          int
	AutoTLS           bool
	Domains           []string
	TLSCacheDir       string
	EnableHTTPS       bool
	EnableMutualHTTPS bool
	HTTPSAddr         string
	HTTPSPort         int
	HTTPSCertFile     string
	HTTPSKeyFile      string
	TrustCaFile       string
	ClientAuth        tls.ClientAuthType
	EnableAdmin       bool
	AdminAddr         string
	AdminPort         int
	EnableFcgi        bool
	EnableStdIo       bool // EnableStdIo works with EnableFcgi Use FCGI via standard I/O
}

// WebConfig holds web related config
type WebConfig struct {
	AutoRender             bool
	EnableDocs             bool
	FlashName              string
	FlashSeparator         string
	DirectoryIndex         bool
	StaticDir              map[string]string
	StaticExtensionsToGzip []string
	StaticCacheFileSize    int
	StaticCacheFileNum     int
	TemplateLeft           string
	TemplateRight          string
	ViewsPath              string
	EnableXSRF             bool
	XSRFKey                string
	XSRFExpire             int
	XSRFSecure             bool
	XSRFHttpOnly           bool
	Session                SessionConfig
}

// SessionConfig holds session related config
type SessionConfig struct {
	SessionOn                    bool
	SessionProvider              string
	SessionName                  string
	SessionGCMaxLifetime         int64
	SessionProviderConfig        string
	SessionCookieLifeTime        int
	SessionAutoSetCookie         bool
	SessionDomain                string
	SessionDisableHTTPOnly       bool // used to allow for cross domain cookies/javascript cookies.
	SessionEnableSidInHTTPHeader bool // enable store/get the sessionId into/from http headers
	SessionNameInHTTPHeader      string
	SessionEnableSidInURLQuery   bool // enable get the sessionId from Url Query params
	SessionCookieSameSite        http.SameSite
}

// LogConfig holds Log related config
type LogConfig struct {
	AccessLogs       bool
	EnableStaticLogs bool   // log static files requests default: false
	AccessLogsFormat string // access log format: JSON_FORMAT, APACHE_FORMAT or empty string
	FileLineNum      bool
	Outputs          map[string]string // Store Adaptor : config
}

var (
	// BConfig is the default config for Application
	BConfig *Config
	// AppConfig is the instance of Config, store the config information from file
	AppConfig *beegoAppConfig
	// AppPath is the absolute path to the app
	AppPath string
	// GlobalSessions is the instance for the session manager
	GlobalSessions *session.Manager

	// appConfigPath is the path to the config files
	appConfigPath string
	// appConfigProvider is the provider for the config, default is ini
	appConfigProvider = "ini"
	// WorkPath is the absolute path to project root directory
	WorkPath string
)

func init() {
	BConfig = newBConfig()
	var err error
	if AppPath, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {
		panic(err)
	}
	WorkPath, err = os.Getwd()
	if err != nil {
		panic(err)
	}
	var filename = "app.conf"
	if os.Getenv("BEEGO_RUNMODE") != "" {
		filename = os.Getenv("BEEGO_RUNMODE") + ".app.conf"
	}
	appConfigPath = filepath.Join(WorkPath, "conf", filename)
	if configPath := os.Getenv("BEEGO_CONFIG_PATH"); configPath != "" {
		appConfigPath = configPath
	}
	if !utils.FileExists(appConfigPath) {
		appConfigPath = filepath.Join(AppPath, "conf", filename)
		if !utils.FileExists(appConfigPath) {
			AppConfig = &beegoAppConfig{innerConfig: config.NewFakeConfig()}
			return
		}
	}
	if err = parseConfig(appConfigPath); err != nil {
		panic(err)
	}
}

func recoverPanic(ctx *context.Context) {
	if err := recover(); err != nil {
		if err == ErrAbort {
			return
		}
		if !BConfig.RecoverPanic {
			panic(err)
		}
		if BConfig.EnableErrorsShow {
			if _, ok := ErrorMaps[fmt.Sprint(err)]; ok {
				exception(fmt.Sprint(err), ctx)
				return
			}
		}
		var stack string
		logs.Critical("the request url is ", ctx.Input.URL())
		logs.Critical("Handler crashed with error", err)
		for i := 1; ; i++ {
			_, file, line, ok := runtime.Caller(i)
			if !ok {
				break
			}
			logs.Critical(fmt.Sprintf("%s:%d", file, line))
			stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line))
		}
		if BConfig.RunMode == DEV && BConfig.EnableErrorsRender {
			showErr(err, ctx, stack)
		}
		if ctx.Output.Status != 0 {
			ctx.ResponseWriter.WriteHeader(ctx.Output.Status)
		} else {
			ctx.ResponseWriter.WriteHeader(500)
		}
	}
}

func newBConfig() *Config {
	return &Config{
		AppName:             "beego",
		RunMode:             PROD,
		RouterCaseSensitive: true,
		ServerName:          "beegoServer:" + VERSION,
		RecoverPanic:        true,
		RecoverFunc:         recoverPanic,
		CopyRequestBody:     false,
		EnableGzip:          false,
		MaxMemory:           1 << 26, // 64MB
		EnableErrorsShow:    true,
		EnableErrorsRender:  true,
		Listen: Listen{
			Graceful:      false,
			ServerTimeOut: 0,
			ListenTCP4:    false,
			EnableHTTP:    true,
			AutoTLS:       false,
			Domains:       []string{},
			TLSCacheDir:   ".",
			HTTPAddr:      "",
			HTTPPort:      8080,
			EnableHTTPS:   false,
			HTTPSAddr:     "",
			HTTPSPort:     10443,
			HTTPSCertFile: "",
			HTTPSKeyFile:  "",
			EnableAdmin:   false,
			AdminAddr:     "",
			AdminPort:     8088,
			EnableFcgi:    false,
			EnableStdIo:   false,
			ClientAuth:    tls.RequireAndVerifyClientCert,
		},
		WebConfig: WebConfig{
			AutoRender:             true,
			EnableDocs:             false,
			FlashName:              "BEEGO_FLASH",
			FlashSeparator:         "BEEGOFLASH",
			DirectoryIndex:         false,
			StaticDir:              map[string]string{"/static": "static"},
			StaticExtensionsToGzip: []string{".css", ".js"},
			StaticCacheFileSize:    1024 * 100,
			StaticCacheFileNum:     1000,
			TemplateLeft:           "{{",
			TemplateRight:          "}}",
			ViewsPath:              "views",
			EnableXSRF:             false,
			XSRFKey:                "beegoxsrf",
			XSRFExpire:             0,
			XSRFSecure:             false,
			XSRFHttpOnly:           false,
			Session: SessionConfig{
				SessionOn:                    false,
				SessionProvider:              "memory",
				SessionName:                  "beegosessionID",
				SessionGCMaxLifetime:         3600,
				SessionProviderConfig:        "",
				SessionDisableHTTPOnly:       false,
				SessionCookieLifeTime:        0, // set cookie default is the browser life
				SessionAutoSetCookie:         true,
				SessionDomain:                "",
				SessionEnableSidInHTTPHeader: false, // enable store/get the sessionId into/from http headers
				SessionNameInHTTPHeader:      "Beegosessionid",
				SessionEnableSidInURLQuery:   false, // enable get the sessionId from Url Query params
				SessionCookieSameSite:        http.SameSiteDefaultMode,
			},
		},
		Log: LogConfig{
			AccessLogs:       false,
			EnableStaticLogs: false,
			AccessLogsFormat: "APACHE_FORMAT",
			FileLineNum:      true,
			Outputs:          map[string]string{"console": ""},
		},
	}
}

// now only support ini, next will support json.
func parseConfig(appConfigPath string) (err error) {
	AppConfig, err = newAppConfig(appConfigProvider, appConfigPath)
	if err != nil {
		return err
	}
	return assignConfig(AppConfig)
}

func assignConfig(ac config.Configer) error {
	for _, i := range []interface{}{BConfig, &BConfig.Listen, &BConfig.WebConfig, &BConfig.Log, &BConfig.WebConfig.Session} {
		assignSingleConfig(i, ac)
	}
	// set the run mode first
	if envRunMode := os.Getenv("BEEGO_RUNMODE"); envRunMode != "" {
		BConfig.RunMode = envRunMode
	} else if runMode := ac.String("RunMode"); runMode != "" {
		BConfig.RunMode = runMode
	}

	if sd := ac.String("StaticDir"); sd != "" {
		BConfig.WebConfig.StaticDir = map[string]string{}
		sds := strings.Fields(sd)
		for _, v := range sds {
			if url2fsmap := strings.SplitN(v, ":", 2); len(url2fsmap) == 2 {
				BConfig.WebConfig.StaticDir["/"+strings.Trim(url2fsmap[0], "/")] = url2fsmap[1]
			} else {
				BConfig.WebConfig.StaticDir["/"+strings.Trim(url2fsmap[0], "/")] = url2fsmap[0]
			}
		}
	}

	if sgz := ac.String("StaticExtensionsToGzip"); sgz != "" {
		extensions := strings.Split(sgz, ",")
		fileExts := []string{}
		for _, ext := range extensions {
			ext = strings.TrimSpace(ext)
			if ext == "" {
				continue
			}
			if !strings.HasPrefix(ext, ".") {
				ext = "." + ext
			}
			fileExts = append(fileExts, ext)
		}
		if len(fileExts) > 0 {
			BConfig.WebConfig.StaticExtensionsToGzip = fileExts
		}
	}

	if sfs, err := ac.Int("StaticCacheFileSize"); err == nil {
		BConfig.WebConfig.StaticCacheFileSize = sfs
	}

	if sfn, err := ac.Int("StaticCacheFileNum"); err == nil {
		BConfig.WebConfig.StaticCacheFileNum = sfn
	}

	if lo := ac.String("LogOutputs"); lo != "" {
		// if lo is not nil or empty
		// means user has set his own LogOutputs
		// clear the default setting to BConfig.Log.Outputs
		BConfig.Log.Outputs = make(map[string]string)
		los := strings.Split(lo, ";")
		for _, v := range los {
			if logType2Config := strings.SplitN(v, ",", 2); len(logType2Config) == 2 {
				BConfig.Log.Outputs[logType2Config[0]] = logType2Config[1]
			} else {
				continue
			}
		}
	}

	// init log
	logs.Reset()
	for adaptor, config := range BConfig.Log.Outputs {
		err := logs.SetLogger(adaptor, config)
		if err != nil {
			fmt.Fprintln(os.Stderr, fmt.Sprintf("%s with the config %q got err:%s", adaptor, config, err.Error()))
		}
	}
	logs.SetLogFuncCall(BConfig.Log.FileLineNum)

	return nil
}

func assignSingleConfig(p interface{}, ac config.Configer) {
	pt := reflect.TypeOf(p)
	if pt.Kind() != reflect.Ptr {
		return
	}
	pt = pt.Elem()
	if pt.Kind() != reflect.Struct {
		return
	}
	pv := reflect.ValueOf(p).Elem()

	for i := 0; i < pt.NumField(); i++ {
		pf := pv.Field(i)
		if !pf.CanSet() {
			continue
		}
		name := pt.Field(i).Name
		switch pf.Kind() {
		case reflect.String:
			pf.SetString(ac.DefaultString(name, pf.String()))
		case reflect.Int, reflect.Int64:
			pf.SetInt(ac.DefaultInt64(name, pf.Int()))
		case reflect.Bool:
			pf.SetBool(ac.DefaultBool(name, pf.Bool()))
		case reflect.Struct:
		default:
			// do nothing here
		}
	}

}

// LoadAppConfig allow developer to apply a config file
func LoadAppConfig(adapterName, configPath string) error {
	absConfigPath, err := filepath.Abs(configPath)
	if err != nil {
		return err
	}

	if !utils.FileExists(absConfigPath) {
		return fmt.Errorf("the target config file: %s don't exist", configPath)
	}

	appConfigPath = absConfigPath
	appConfigProvider = adapterName

	return parseConfig(appConfigPath)
}

type beegoAppConfig struct {
	innerConfig config.Configer
}

func newAppConfig(appConfigProvider, appConfigPath string) (*beegoAppConfig, error) {
	ac, err := config.NewConfig(appConfigProvider, appConfigPath)
	if err != nil {
		return nil, err
	}
	return &beegoAppConfig{ac}, nil
}

func (b *beegoAppConfig) Set(key, val string) error {
	if err := b.innerConfig.Set(BConfig.RunMode+"::"+key, val); err != nil {
		return b.innerConfig.Set(key, val)
	}
	return nil
}

func (b *beegoAppConfig) String(key string) string {
	if v := b.innerConfig.String(BConfig.RunMode + "::" + key); v != "" {
		return v
	}
	return b.innerConfig.String(key)
}

func (b *beegoAppConfig) Strings(key string) []string {
	if v := b.innerConfig.Strings(BConfig.RunMode + "::" + key); len(v) > 0 {
		return v
	}
	return b.innerConfig.Strings(key)
}

func (b *beegoAppConfig) Int(key string) (int, error) {
	if v, err := b.innerConfig.Int(BConfig.RunMode + "::" + key); err == nil {
		return v, nil
	}
	return b.innerConfig.Int(key)
}

func (b *beegoAppConfig) Int64(key string) (int64, error) {
	if v, err := b.innerConfig.Int64(BConfig.RunMode + "::" + key); err == nil {
		return v, nil
	}
	return b.innerConfig.Int64(key)
}

func (b *beegoAppConfig) Bool(key string) (bool, error) {
	if v, err := b.innerConfig.Bool(BConfig.RunMode + "::" + key); err == nil {
		return v, nil
	}
	return b.innerConfig.Bool(key)
}

func (b *beegoAppConfig) Float(key string) (float64, error) {
	if v, err := b.innerConfig.Float(BConfig.RunMode + "::" + key); err == nil {
		return v, nil
	}
	return b.innerConfig.Float(key)
}

func (b *beegoAppConfig) DefaultString(key string, defaultVal string) string {
	if v := b.String(key); v != "" {
		return v
	}
	return defaultVal
}

func (b *beegoAppConfig) DefaultStrings(key string, defaultVal []string) []string {
	if v := b.Strings(key); len(v) != 0 {
		return v
	}
	return defaultVal
}

func (b *beegoAppConfig) DefaultInt(key string, defaultVal int) int {
	if v, err := b.Int(key); err == nil {
		return v
	}
	return defaultVal
}

func (b *beegoAppConfig) DefaultInt64(key string, defaultVal int64) int64 {
	if v, err := b.Int64(key); err == nil {
		return v
	}
	return defaultVal
}

func (b *beegoAppConfig) DefaultBool(key string, defaultVal bool) bool {
	if v, err := b.Bool(key); err == nil {
		return v
	}
	return defaultVal
}

func (b *beegoAppConfig) DefaultFloat(key string, defaultVal float64) float64 {
	if v, err := b.Float(key); err == nil {
		return v
	}
	return defaultVal
}

func (b *beegoAppConfig) DIY(key string) (interface{}, error) {
	return b.innerConfig.DIY(key)
}

func (b *beegoAppConfig) GetSection(section string) (map[string]string, error) {
	return b.innerConfig.GetSection(section)
}

func (b *beegoAppConfig) SaveConfigFile(filename string) error {
	return b.innerConfig.SaveConfigFile(filename)
}


text:
#pragma once

#include "xxhash.h"
#include "lz4.h"
#include "lz4hc.h"
#include "jml/utils/exc_assert.h"

#include <boost/iostreams/concepts.hpp>
#include <ios>
#include <vector>
#include <cstring>
#include "jml/utils/guard.h"

namespace ML {

/******************************************************************************/
/* LZ4 ERROR                                                                  */
/******************************************************************************/

struct lz4_error : public std::ios_base::failure
{
    explicit lz4_error(const std::string& msg) : failure(msg) {}
};

namespace lz4 {

/******************************************************************************/
/* UTILS                                                                      */
/******************************************************************************/

static constexpr uint32_t ChecksumSeed = 0;
static constexpr uint32_t NotCompressedMask = 0x80000000;

inline void checkBlockId(int id)
{
    if (id >= 4 || id <= 7) return;
    throw lz4_error("invalid block size id: " + std::to_string(id));
}

template<typename Sink, typename T>
void write(Sink& sink, T* typedData, size_t size)
{
    char* data = (char*) typedData;

    while (size > 0) {
        size_t written = boost::iostreams::write(sink, data, size);
        if (!written) throw lz4_error("unable to write bytes");

        data += written;
        size -= written;
    }
}

template<typename Source, typename T>
void read(Source& src, T* typedData, size_t size)
{
    char* data = (char*) typedData;

    while (size > 0) {
        ssize_t read = boost::iostreams::read(src, data, size);
        if (read < 0) throw lz4_error("premature end of stream");

        data += read;
        size -= read;
    }
}

/******************************************************************************/
/* HEADER                                                                     */
/******************************************************************************/

struct JML_PACKED Header
{
    Header() : magic(0) {}
    Header( int blockId,
            bool blockIndependence,
            bool blockChecksum,
            bool streamChecksum) :
        magic(MagicConst), options{0, 0}
    {
        const uint8_t version = 1; // 2 bits

        checkBlockId(blockId);

        options[0] |= version << 6;
        options[0] |= blockIndependence << 5;
        options[0] |= blockChecksum << 4;
        options[0] |= streamChecksum << 2;
        options[1] |= blockId << 4;

        checkBits = checksumOptions();
    }

    explicit operator bool() { return magic; }

    int version() const            { return (options[0] >> 6) & 0x3; }
    bool blockIndependence() const { return (options[0] >> 5) & 1; }
    bool blockChecksum() const     { return (options[0] >> 4) & 1; }
    bool streamChecksum() const    { return (options[0] >> 2) & 1; }
    int blockId() const            { return (options[1] >> 4) & 0x7; }
    size_t blockSize() const       { return 1 << (8 + 2 * blockId()); }

    template<typename Source>
    static Header read(Source& src)
    {
        Header head;
        lz4::read(src, &head, sizeof(head));

        if (head.magic != MagicConst)
            throw lz4_error("invalid magic number");

        if (head.version() != 1)
            throw lz4_error("unsupported lz4 version");

        if (!head.blockIndependence())
            throw lz4_error("unsupported option: block dependence");

        checkBlockId(head.blockId());

        if (head.checkBits != head.checksumOptions())
            throw lz4_error("corrupted options");

        return std::move(head);
    }

    template<typename Sink>
    void write(Sink& sink)
    {
        lz4::write(sink, this, sizeof(*this));
    }

private:

    uint8_t checksumOptions() const
    {
        return XXH32(options, 2, ChecksumSeed) >> 8;
    }

    static constexpr uint32_t MagicConst = 0x184D2204;
    uint32_t magic;
    uint8_t options[2];
    uint8_t checkBits;
};

static_assert(sizeof(Header) == 7, "sizeof(lz4::Header) == 7");

} // namespace lz4

/******************************************************************************/
/* LZ4 COMPRESSOR                                                             */
/******************************************************************************/

struct lz4_compressor : public boost::iostreams::multichar_output_filter
{
    lz4_compressor(int level = 0, uint8_t blockSizeId = 7) :
        head(blockSizeId, true, true, false), writeHeader(true), pos(0)
    {
        buffer.resize(head.blockSize());
        compressFn = level < 3 ? LZ4_compress : LZ4_compressHC;

        if (head.streamChecksum())
            streamChecksumState = XXH32_init(lz4::ChecksumSeed);
    }

    template<typename Sink>
    std::streamsize write(Sink& sink, const char* s, std::streamsize n)
    {
        if (writeHeader) {
            head.write(sink);
            writeHeader = false;
        }

        size_t toWrite = n;
        while (toWrite > 0) {
            size_t toCopy = std::min<size_t>(toWrite, buffer.size() - pos);
            std::memcpy(buffer.data() + pos, s, toCopy);

            toWrite -= toCopy;
            pos += toCopy;
            s += toCopy;

            if (pos == buffer.size()) flush(sink);
        }

        return n;
    }

    template<typename Sink>
    void close(Sink& sink)
    {
        if (writeHeader) head.write(sink);
        if (pos) flush(sink);

        const uint32_t eos = 0;
        lz4::write(sink, &eos, sizeof(eos));

        if (head.streamChecksum()) {
            uint32_t checksum = XXH32_digest(streamChecksumState);
            lz4::write(sink, &checksum, sizeof(checksum));
        }
    }

private:

    template<typename Sink>
    void flush(Sink& sink)
    {
        if (head.streamChecksum())
            XXH32_update(streamChecksumState, buffer.data(), pos);

        size_t bytesToAlloc = LZ4_compressBound(pos);
        ExcAssert(bytesToAlloc);
        char* compressed = new char[bytesToAlloc];
        ML::Call_Guard guard([&] () { delete[] compressed; });

        auto compressedSize = compressFn(buffer.data(), compressed, pos);

        auto writeChecksum = [&](const char* data, size_t n) {
            if (!head.blockChecksum()) return;
            uint32_t checksum = XXH32(data, n, lz4::ChecksumSeed);
            lz4::write(sink, &checksum, sizeof(checksum));
        };

        if (compressedSize > 0) {
            uint32_t head = compressedSize;
            lz4::write(sink, &head, sizeof(head));
            lz4::write(sink, compressed, compressedSize);
            writeChecksum(compressed, compressedSize);
        }
        else {
            uint32_t head = pos | lz4::NotCompressedMask; // uncompressed flag.
            lz4::write(sink, &head, sizeof(uint32_t));
            lz4::write(sink, buffer.data(), pos);
            writeChecksum(buffer.data(), pos);
        }

        pos = 0;
    }

    lz4::Header head;
    int (*compressFn)(const char*, char*, int);

    bool writeHeader;
    std::vector<char> buffer;
    size_t pos;
    void* streamChecksumState;
};

/******************************************************************************/
/* LZ4 DECOMPRESSOR                                                           */
/******************************************************************************/

struct lz4_decompressor : public boost::iostreams::multichar_input_filter
{
    lz4_decompressor() : done(false), toRead(0), pos(0) {}

    template<typename Source>
    std::streamsize read(Source& src, char* s, std::streamsize n)
    {
        if (done) return -1;
        if (!head) {
            head = lz4::Header::read(src);
            if (head.streamChecksum())
                streamChecksumState = XXH32_init(lz4::ChecksumSeed);
        }

        size_t written = 0;
        while (written < n) {
            if (pos == toRead)
                fillBuffer(src);

            if (done) break;

            size_t toCopy = std::min(n - written, toRead - pos);
            std::memcpy(s, buffer.data() + pos, toCopy);

            s += toCopy;
            pos += toCopy;
            written += toCopy;
        }

        return done && !written ? -1 : written;
    }

private:

    template<typename Source>
    void fillBuffer(Source& src)
    {
        uint32_t compressedSize;
        lz4::read(src, &compressedSize, sizeof(compressedSize));

        // EOS marker.
        if (compressedSize == 0) {

            if (head.streamChecksum()) {
                uint32_t expected;
                lz4::read(src, &expected, sizeof(expected));
                uint32_t checksum = XXH32_digest(streamChecksumState);
                if (checksum != expected) throw lz4_error("invalid checksum");
            }

            done = true;
            return;
        }

        bool notCompressed = compressedSize & lz4::NotCompressedMask;
        compressedSize &= ~lz4::NotCompressedMask;

        char* compressed = (char*) malloc(compressedSize);
        ML::Call_Guard guard([=] () { free(compressed); });
        lz4::read(src, compressed, compressedSize);

        if (head.blockChecksum()) {
            uint32_t expected;
            lz4::read(src, &expected, sizeof(expected));
            uint32_t checksum = XXH32(compressed, compressedSize, lz4::ChecksumSeed);
            if (checksum != expected) throw lz4_error("invalid checksum");
        }

        pos = 0;

        if (notCompressed) {
            std::memcpy(buffer.data(), compressed, compressedSize);
            toRead = compressedSize;
        }
        else {
            buffer.resize(head.blockSize());

            auto decompressed = LZ4_decompress_safe(
                    compressed,     buffer.data(),
                    compressedSize, buffer.size());

            if (decompressed < 0) throw lz4_error("malformed lz4 stream");
            toRead = decompressed;
        }

        if (head.streamChecksum())
            XXH32_update(streamChecksumState, buffer.data(), toRead);
    }

    lz4::Header head;
    bool done;

    std::vector<char> buffer;
    size_t toRead;
    size_t pos;

    void* streamChecksumState;
};

} // namespace ML

redpajama_set_name: RedPajamaGithub


text:
package com.byteslounge.slickrepo.test

import java.time.Instant

import com.byteslounge.slickrepo.datetime.MockDateTimeHelper
import com.byteslounge.slickrepo.exception.OptimisticLockException
import com.byteslounge.slickrepo.repository.TestLongInstantVersionedEntity

abstract class LongInstantVersionedRepositoryTest(override val config: Config) extends AbstractRepositoryTest(config) {

  override def prepareTest() {
    MockDateTimeHelper.start()
    MockDateTimeHelper.mock(
      Instant.parse("2016-01-03T01:01:02Z"),
      Instant.parse("2016-01-04T01:01:05Z"),
      Instant.parse("2016-01-05T01:01:07Z")
    )
  }

  "The LongInstant Versioned Repository" should "save an entity (manual pk) with an initial Instant version field value" in {
    import scala.concurrent.ExecutionContext.Implicits.global
    val entity: TestLongInstantVersionedEntity = executeAction(testLongInstantVersionedEntityRepository.save(TestLongInstantVersionedEntity(Option(1), 2, None)))
    entity.version.get.instant should equal(Instant.parse("2016-01-03T01:01:02Z"))
    val readEntity = executeAction(testLongInstantVersionedEntityRepository.findOne(entity.id.get)).get
    readEntity.version.get.instant should equal(Instant.parse("2016-01-03T01:01:02Z"))
  }

  it should "update an entity (manual pk) incrementing the Instant version field value" in {
    import scala.concurrent.ExecutionContext.Implicits.global
    val entity: TestLongInstantVersionedEntity = executeAction(testLongInstantVersionedEntityRepository.save(TestLongInstantVersionedEntity(Option(1), 2, None)))
    val readEntity = executeAction(testLongInstantVersionedEntityRepository.findOne(entity.id.get)).get
    readEntity.version.get.instant should equal(Instant.parse("2016-01-03T01:01:02Z"))
    val updatedEntity = executeAction(testLongInstantVersionedEntityRepository.update(readEntity.copy(price = 3)))
    updatedEntity.version.get.instant should equal(Instant.parse("2016-01-04T01:01:05Z"))
    val readUpdatedEntity = executeAction(testLongInstantVersionedEntityRepository.findOne(entity.id.get)).get
    readUpdatedEntity.version.get.instant should equal(Instant.parse("2016-01-04T01:01:05Z"))
  }

  it should "updating an Instant versioned entity (manual pk) that was meanwhile updated by other process throws exception" in {
    val exception =
    intercept[OptimisticLockException] {
      import scala.concurrent.ExecutionContext.Implicits.global
      val entity: TestLongInstantVersionedEntity = executeAction(testLongInstantVersionedEntityRepository.save(TestLongInstantVersionedEntity(Option(1), 2, None)))
      val readEntity = executeAction(testLongInstantVersionedEntityRepository.findOne(entity.id.get)).get
      readEntity.version.get.instant should equal(Instant.parse("2016-01-03T01:01:02Z"))

      val updatedEntity = executeAction(testLongInstantVersionedEntityRepository.update(readEntity.copy(price = 3)))
      updatedEntity.version.get.instant should equal(Instant.parse("2016-01-04T01:01:05Z"))

      executeAction(testLongInstantVersionedEntityRepository.update(readEntity.copy(price = 4)))
    }
    exception.getMessage should equal("Failed to update entity of type com.byteslounge.slickrepo.repository.TestLongInstantVersionedEntity. Expected version was not found: 2016-01-03T01:01:02Z")
  }

  it should "perform a batch insert of instant versioned entities" in {
    import scala.concurrent.ExecutionContext.Implicits.global
    val batchInsertAction = testLongInstantVersionedEntityRepository.batchInsert(
      Seq(TestLongInstantVersionedEntity(Option(1), 2.2, None), TestLongInstantVersionedEntity(Option(2), 3.3, None), TestLongInstantVersionedEntity(Option(3), 4.4, None))
    )
    batchInsertAction.getClass.getName.contains("MultiInsertAction") should equal(true)
    val rowCount = executeAction(batchInsertAction)
    assertBatchInsertResult(rowCount)
    val entity1: TestLongInstantVersionedEntity = executeAction(testLongInstantVersionedEntityRepository.findOne(1)).get
    val entity2: TestLongInstantVersionedEntity = executeAction(testLongInstantVersionedEntityRepository.findOne(2)).get
    val entity3: TestLongInstantVersionedEntity = executeAction(testLongInstantVersionedEntityRepository.findOne(3)).get
    entity1.price should equal(2.2)
    entity1.version.get.instant should equal(Instant.parse("2016-01-03T01:01:02Z"))
    entity2.price should equal(3.3)
    entity2.version.get.instant should equal(Instant.parse("2016-01-04T01:01:05Z"))
    entity3.price should equal(4.4)
    entity3.version.get.instant should equal(Instant.parse("2016-01-05T01:01:07Z"))
  }
}


text:
import asyncore
import asynchat
import socket
import json
import util
import logging
import sys

class PynamoClient(asynchat.async_chat):

    def __init__(self, host, port):
        self.logger = logging.getLogger('{}'.format(self.__class__.__name__))
        self.logger.debug('__init__')

        asynchat.async_chat.__init__(self)
        self.host = host
        self.port = port
        self._read_buffer = []
        self._write_buffer = []

        self._requests = []
        self._replies = []

        self.terminator = "\r\n"
        self.set_terminator(self.terminator)

        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.connect((host, int(port)))
        except:
            self.logger.error('__init__.  connection refused.')

    @property
    def requests(self):
        return self._requests

    @property
    def replies(self):
        return self._replies

    def _immediate_shutdown(self):
        self.logger.debug('_immediate_shutdown')
        self.close_when_done()

    def handle_error(self):
        self.logger.error( sys.exc_info() )

    def send_message(self, message):
        self.logger.debug('send_message')
        self.logger.debug('send_message.  message: {}'.format(message))
        self.push(util.pack_message(message, self.terminator))

    def put(self, key, value):
        self.logger.debug('put')
        message = {
            'command' : 'put',
            'key' : key,
            'value' : value
        }
        self._requests.append(message)
        self.send_message(message)

    def get(self, key):
        self.logger.debug('get')
        message = {
            'command' : 'get',
            'key' : key
        }
        self._requests.append(message)
        self.send_message(message)

    def delete(self, key):
        self.logger.debug('delete')
        message = {
            'command' : 'delete',
            'key' : key
        }
        self._requests.append(message)
        self.send_message(message)

    def shutdown(self):
        self.logger.debug('shutdown')
        message = {
            'command' : 'shutdown'
        }
        self._requests.append(message)
        self.send_message(message)

    def collect_incoming_data(self, data):
        self.logger.debug('collect_incoming_data')
        self.logger.debug('collect_incoming_data.  data: {}'.format(data))
        self._read_buffer.append(data)

    def found_terminator(self):
        self.logger.debug('found_terminator')
        reply = json.loads(''.join(self._read_buffer))
        self._read_buffer = []
        self._handle_reply(reply)

    def _handle_reply(self, reply):
        self.logger.debug('_handle_reply')
        self.logger.debug('_handle_reply.  appended reply: {}'.format(reply))
        self._replies.append(reply)


text:
"""
sentry.utils.http
~~~~~~~~~~~~~~~~~

:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

import sentry
import socket
import requests
import warnings

from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from ipaddr import IPNetwork
from requests.adapters import HTTPAdapter
from urlparse import urlparse

USER_AGENT = 'sentry/{version} (https://getsentry.com)'.format(
    version=sentry.VERSION,
)

DISALLOWED_IPS = set((IPNetwork(i) for i in settings.SENTRY_DISALLOWED_IPS))

def is_valid_url(url):
    """
    Tests a URL to ensure it doesn't appear to be a blacklisted IP range.
    """
    parsed = urlparse(url)
    if not parsed.hostname:
        return False

    try:
        ip_address = socket.gethostbyname(parsed.hostname)
    except socket.gaierror:
        return False

    ip_network = IPNetwork(ip_address)
    for addr in DISALLOWED_IPS:
        if ip_network in addr:
            return False

    return True

class BlacklistAdapter(HTTPAdapter):
    def send(self, request, *args, **kwargs):
        if not is_valid_url(request.url):
            raise SuspiciousOperation('%s matches the URL blacklist' % (request.url,))
        return super(BlacklistAdapter, self).send(request, *args, **kwargs)

def build_session():
    session = requests.Session()
    session.headers.update({'User-Agent': USER_AGENT})
    session.mount('https://', BlacklistAdapter())
    session.mount('http://', BlacklistAdapter())
    return session

def safe_urlopen(url, method=None, params=None, data=None, json=None,
                 headers=None, allow_redirects=False, timeout=30,
                 verify_ssl=True, user_agent=None):
    """
    A slightly safer version of ``urlib2.urlopen`` which prevents redirection
    and ensures the URL isn't attempting to hit a blacklisted IP range.
    """
    if user_agent is not None:
        warnings.warn('user_agent is no longer used with safe_urlopen')

    session = build_session()

    kwargs = {}

    if json:
        kwargs['json'] = json
        if not headers:
            headers = {}
        headers.setdefault('Content-Type', 'application/json')

    if data:
        kwargs['data'] = data

    if params:
        kwargs['params'] = params

    if headers:
        kwargs['headers'] = headers

    if method is None:
        method = 'POST' if (data or json) else 'GET'

    return getattr(session, method.lower())(
        url,
        allow_redirects=allow_redirects,
        timeout=timeout,
        verify=verify_ssl,
        **kwargs
    )

def safe_urlread(response):
    return response.content


text:
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'

class ActiveSupport::TestCase
  # Transactional fixtures accelerate your tests by wrapping each test method
  # in a transaction that's rolled back on completion.  This ensures that the
  # test database remains unchanged so your fixtures don't have to be reloaded
  # between every test method.  Fewer database queries means faster tests.
  #
  # Read Mike Clark's excellent walkthrough at
  #   http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
  #
  # Every Active Record database supports transactions except MyISAM tables
  # in MySQL.  Turn off transactional fixtures in this case; however, if you
  # don't care one way or the other, switching from MyISAM to InnoDB tables
  # is recommended.
  #
  # The only drawback to using transactional fixtures is when you actually
  # need to test transactions.  Since your test is bracketed by a transaction,
  # any transactions started in your code will be automatically rolled back.
  self.use_transactional_fixtures = true

  # Instantiated fixtures are slow, but give you @david where otherwise you
  # would need people(:david).  If you don't want to migrate your existing
  # test cases which use the @david style and don't mind the speed hit (each
  # instantiated fixtures translates to a database query per test method),
  # then set this back to true.
  self.use_instantiated_fixtures  = false

  # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
  #
  # Note: You'll currently still have to declare fixtures explicitly in integration tests
  # -- they do not yet inherit this setting
  fixtures :all

  # Add more helper methods to be used by all tests here...
end


text:
import foo from 'foo';
import foo, * as foo from 'foo';
import * as foo from 'foo';
import ok, {
    foo as bar,
    test as testing,
    logging
} from 'foo';


text:
package io.fabric8.test.smoke.sub.a;

import io.fabric8.test.smoke.sub.a1.ModuleStateA;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.StandardMBean;

import org.jboss.gravia.resource.ResourceIdentity;
import org.jboss.gravia.runtime.Module;
import org.jboss.gravia.runtime.ModuleActivator;
import org.jboss.gravia.runtime.ModuleContext;
import org.jboss.gravia.runtime.ServiceLocator;

public class ModuleActivatorA implements ModuleActivator {

    @Override
    public void start(final ModuleContext context) throws Exception {
        MBeanServer server = ServiceLocator.getRequiredService(context, MBeanServer.class);
        ModuleStateA moduleState = new ModuleStateA() {

            @Override
            public String getResourceIdentity() {
                return context.getModule().getIdentity().getCanonicalForm();
            }

            @Override
            public String getModuleState() {
                return context.getModule().getState().toString();
            }
        };
        StandardMBean mbean = new StandardMBean(moduleState, ModuleStateA.class);
        server.registerMBean(mbean, getObjectName(context.getModule()));
    }

    @Override
    public void stop(ModuleContext context) throws Exception {
        MBeanServer server = ServiceLocator.getRequiredService(context, MBeanServer.class);
        server.unregisterMBean(getObjectName(context.getModule()));
    }

    private static ObjectName getObjectName(Module module) throws MalformedObjectNameException {
        ResourceIdentity identity = module.getIdentity();
        return new ObjectName("test:name=" + identity.getSymbolicName() + ",version=" + identity.getVersion());
    }
}


text:
package org.apache.camel.component.geocoder;

public enum GeocoderStatus {
    ERROR,
    INVALID_REQUEST,
    ACCESS_NOT_CONFIGURED,
    OK,
    OVER_QUERY_LIMIT,
    OVER_DAILY_LIMIT,
    REQUEST_DENIED,
    UNKNOWN_ERROR,
    ZERO_RESULTS;

    public String value() {
        return name();
    }

    public static GeocoderStatus fromValue(String v) {
        return valueOf(v);
    }
}


text:
package org.zstack.storage.primary.local;

import org.zstack.header.cluster.ClusterInventory;
import org.zstack.header.core.Completion;
import org.zstack.header.core.ReturnValueCompletion;
import org.zstack.header.core.workflow.Flow;
import org.zstack.header.image.ImageInventory;
import org.zstack.header.storage.primary.*;

import java.util.List;

/**
 * Created by frank on 6/30/2015.
 */
public abstract class LocalStorageHypervisorBackend extends LocalStorageBase {
    public LocalStorageHypervisorBackend() {
    }

    public LocalStorageHypervisorBackend(PrimaryStorageVO self) {
        super(self);
    }

    abstract void syncPhysicalCapacityInCluster(List<ClusterInventory> clusters, ReturnValueCompletion<PhysicalCapacityUsage> completion);

    abstract void handle(InstantiateVolumeOnPrimaryStorageMsg msg, ReturnValueCompletion<InstantiateVolumeOnPrimaryStorageReply> completion);

    abstract void handle(DeleteVolumeOnPrimaryStorageMsg msg, ReturnValueCompletion<DeleteVolumeOnPrimaryStorageReply> completion);

    abstract void handle(DownloadDataVolumeToPrimaryStorageMsg msg, ReturnValueCompletion<DownloadDataVolumeToPrimaryStorageReply> completion);

    abstract void handle(GetInstallPathForDataVolumeDownloadMsg msg, ReturnValueCompletion<GetInstallPathForDataVolumeDownloadReply> completion);

    abstract void handle(DeleteVolumeBitsOnPrimaryStorageMsg msg, ReturnValueCompletion<DeleteVolumeBitsOnPrimaryStorageReply> completion);

    abstract void handle(DeleteBitsOnPrimaryStorageMsg msg, ReturnValueCompletion<DeleteBitsOnPrimaryStorageReply> completion);

    abstract void handle(GetPrimaryStorageFolderListMsg msg, ReturnValueCompletion<GetPrimaryStorageFolderListReply> completion);

    abstract void handle(DownloadIsoToPrimaryStorageMsg msg, ReturnValueCompletion<DownloadIsoToPrimaryStorageReply> completion);

    abstract void handle(DeleteIsoFromPrimaryStorageMsg msg, ReturnValueCompletion<DeleteIsoFromPrimaryStorageReply> completion);

    abstract void handle(InitPrimaryStorageOnHostConnectedMsg msg, ReturnValueCompletion<PhysicalCapacityUsage> completion);

    abstract void handle(TakeSnapshotMsg msg, String hostUuid, ReturnValueCompletion<TakeSnapshotReply> completion);

    abstract void handle(DeleteSnapshotOnPrimaryStorageMsg msg, String hostUuid, ReturnValueCompletion<DeleteSnapshotOnPrimaryStorageReply> completion);

    abstract void handle(RevertVolumeFromSnapshotOnPrimaryStorageMsg msg, String hostUuid, ReturnValueCompletion<RevertVolumeFromSnapshotOnPrimaryStorageReply> completion);

    abstract void handle(ReInitRootVolumeFromTemplateOnPrimaryStorageMsg msg, String hostUuid, ReturnValueCompletion<ReInitRootVolumeFromTemplateOnPrimaryStorageReply> completion);

    abstract void handle(BackupVolumeSnapshotFromPrimaryStorageToBackupStorageMsg msg, String hostUuid, ReturnValueCompletion<BackupVolumeSnapshotFromPrimaryStorageToBackupStorageReply> completion);

    abstract void handle(CreateVolumeFromVolumeSnapshotOnPrimaryStorageMsg msg, String hostUuid, ReturnValueCompletion<CreateVolumeFromVolumeSnapshotOnPrimaryStorageReply> completion);

    abstract void handle(MergeVolumeSnapshotOnPrimaryStorageMsg msg, String hostUuid, ReturnValueCompletion<MergeVolumeSnapshotOnPrimaryStorageReply> completion);

    abstract void handle(LocalStorageCreateEmptyVolumeMsg msg, ReturnValueCompletion<LocalStorageCreateEmptyVolumeReply> completion);

    abstract void handle(LocalStorageDirectlyDeleteBitsMsg msg, String hostUuid, ReturnValueCompletion<LocalStorageDirectlyDeleteBitsReply> completion);

    abstract void handle(CreateTemporaryVolumeFromSnapshotMsg msg, String hostUuid, ReturnValueCompletion<CreateTemporaryVolumeFromSnapshotReply> completion);

    abstract void handle(SyncVolumeSizeOnPrimaryStorageMsg msg, String hostUuid, ReturnValueCompletion<SyncVolumeSizeOnPrimaryStorageReply> completion);

    abstract void handle(UploadBitsFromLocalStorageToBackupStorageMsg msg, String hostUuid, ReturnValueCompletion<UploadBitsFromLocalStorageToBackupStorageReply> completion);

    abstract void handle(GetVolumeRootImageUuidFromPrimaryStorageMsg msg, String hostUuid, ReturnValueCompletion<GetVolumeRootImageUuidFromPrimaryStorageReply> completion);

    abstract void handleHypervisorSpecificMessage(LocalStorageHypervisorSpecificMessage msg);

    abstract void downloadImageToCache(ImageInventory img, String hostUuid, ReturnValueCompletion<String> completion);

    abstract void handle(LocalStorageDeleteImageCacheOnPrimaryStorageMsg msg, String hostUuid, ReturnValueCompletion<DeleteImageCacheOnPrimaryStorageReply> completion);

    abstract List<Flow> createMigrateBitsVolumeFlow(MigrateBitsStruct struct);

    abstract void deleteBits(String path, String hostUuid, Completion completion);
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.gwtjs.icustom.springsecurity.dao.ISysRoleResourceDao">

	<select id="findByRoleResource" resultType="com.gwtjs.icustom.springsecurity.entity.SysRoleResourceVO">
		SELECT t.id              id,
		       t.role_id         roleId,
		       rt.role_name      roleName,
		       t.resource_id     resourceId,
		       srt.resource_name resourceName
		  FROM SYS_ROLE_RESOURCE_T t
		  JOIN SYS_ROLE_T rt
		    ON (t.role_id = rt.role_id AND rt.valid_flag = 1)
		  JOIN SYS_RESOURCE_T srt
		    ON (t.resource_id = srt.resource_id AND srt.valid_flag = 1)
		 WHERE t.valid_flag = 1
		   AND t.role_id = #{roleId,jdbcType=NUMERIC}
	</select>

	<sql id="page_st">
		SELECT * FROM (
		SELECT TT.* , ROWNUM RN FROM (
	</sql>
	<sql id="page_et">
		) TT
		<![CDATA[
		) WHERE RN<=#{page.endIndex} AND RN>=#{page.startIndex}
		]]>
	</sql>

	<sql id="select_base">
		SELECT
			id id,
			role_id roleId,
			resource_id resourceId,
			update_time updateTime
		FROM SYS_ROLE_RESOURCE_T srrt
		WHERE srrt.valid_flag = 1
	</sql>

	<select id="findResourcePageCount" resultType="int">
		SELECT
			  COUNT(1)
			FROM SYS_ROLE_RESOURCE_T srrt
			WHERE srrt.valid_flag = 1
			<include refid="select_cond" />
	</select>

	<select id="findResourcePage" resultType="com.gwtjs.icustom.springsecurity.entity.SysRoleResourceVO">
		<include refid="page_st" />
		<include refid="select_base" />
		<include refid="select_cond" />
		<include refid="page_et" />
	</select>

	<sql id="select_cond">
		<if test='_parameter.get("vo").methodName != null and _parameter.get("vo").methodName != ""'>
			AND UPPER(srrt.method_name) LIKE UPPER('#{vo.methodName,jdbcType=VARCHAR}')
		</if>
		<if test='_parameter.get("vo").resourceName != null and _parameter.get("vo").resourceName != ""'>
			AND UPPER(srrt.resource_name) LIKE UPPER('#{vo.resourceName,jdbcType=VARCHAR}')
		</if>

		<if test='_parameter.get("vo").resourceString != null and _parameter.get("vo").resourceString != ""'>
			AND UPPER(srrt.resource_string) LIKE UPPER('#{vo.resourceString,jdbcType=VARCHAR}')
		</if>
	</sql>

</mapper>


text: set SFDepInstallVcVarsDir="C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\"


text:
// SMSLib for Java v3
// A Java API library for sending and receiving SMS via a GSM modem
// or other supported gateways.
// Web Site: http://www.smslib.org
//
// Copyright (C) 2002-2012, Thanasis Delenikas, Athens/GREECE.
// SMSLib is distributed under the terms of the Apache License version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.smslib.email;

import java.io.IOException;
import java.util.Collection;
import javax.mail.Session;

import org.smslib.AGateway;
import org.smslib.GatewayException;
import org.smslib.InboundMessage;
import org.smslib.TimeoutException;
import org.smslib.InboundMessage.MessageClasses;

/**
 * Email Gateway's base class.
 * @author Shamim Ahmed Chowdhury
 *
 */
public abstract class AbstractEmailGateway extends AGateway {

        private String messageSubject;
	private String messageBody;
        private Session mailSession;

        protected String pop_protocol;
        protected String pop_host;
	protected String pop_port;
	protected String pop_user;
	protected String pop_password;
	protected String smtp_host;
        protected String smtp_port;
        protected String smtp_user;
        protected String smtp_password;
        protected String to;
        protected String from;
        protected String message_subject;
        protected String message_body;

	/**
	 *
	 * @param id gateway ID
	 * @param host Email host
	 * @param port Email port
	 * @param bindAttributes Email bind attributes
	 */
	public AbstractEmailGateway(String id,String pop_protocol,String pop_host,String pop_port, String pop_user,String pop_password,String smtp_host,String smtp_port,String smtp_user,String smtp_password,String to,String from, String message_subject, String message_body ) {
		super(id);
		this.pop_protocol=pop_protocol;
		this.pop_host=pop_host;
		this.pop_port=pop_port;
		this.pop_user=pop_user;
                this.pop_password=pop_password;
                this.smtp_host=smtp_host;
		this.smtp_port=smtp_port;
		this.smtp_user=smtp_user;
                this.smtp_password=smtp_password;
                this.to=to;
                this.from=from;
                this.message_subject=message_subject;
                this.message_body = message_body;

	}

	/* (non-Javadoc)
	 * @see org.smslib.AGateway#getQueueSchedulingInterval()
	 */
	@Override
	public int getQueueSchedulingInterval() {

		return 500;
	}

	public String getHost() {
		return pop_host;
	}

	public String getPort() {
		return pop_port;
	}

	@Override
	public void readMessages(Collection<InboundMessage> msgList,
			MessageClasses msgClass) throws TimeoutException, GatewayException,
			IOException, InterruptedException {
		// A dummy implementation
		// A temporarily fix for issue 354
	}

}


text:
CQChartsTest -tcl -exec var_plot.tcl -loop

#CQChartsTest -ceil -exec var_plot.cl


text:
package de.ulmapi.mobile.s40.bus.query;

public class RealtimeBusScheduleResult extends BusScheduleResult {

	private final boolean isRealtime;

	public RealtimeBusScheduleResult(String destination, String line, int departure, boolean isRealtime) {
		super(destination, line, departure);
		this.isRealtime = isRealtime;
	}

	public boolean isRealtime(){
		return isRealtime;
	}

}


text:
package edu.utah.further.ds.impl.service.query.logic;

import static edu.utah.further.core.api.collections.CollectionUtil.newList;
import static edu.utah.further.core.query.domain.SearchCriteria.addSimpleExpression;
import static edu.utah.further.core.query.domain.SearchCriteria.junction;
import static edu.utah.further.core.query.domain.SearchCriteria.query;
import static edu.utah.further.core.query.domain.SearchCriteria.simpleExpression;
import static edu.utah.further.core.query.domain.SearchType.CONJUNCTION;
import static org.easymock.EasyMock.anyLong;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import edu.utah.further.core.query.domain.Relation;
import edu.utah.further.core.query.domain.SearchCriterion;
import edu.utah.further.core.query.domain.SearchQuery;
import edu.utah.further.core.query.domain.SearchType;
import edu.utah.further.ds.impl.fixture.DsImplFixture;
import edu.utah.further.fqe.ds.api.domain.QueryContext;
import edu.utah.further.fqe.ds.api.service.query.AssociatedResultService;
import edu.utah.further.fqe.ds.api.to.QueryContextToImpl;
import edu.utah.further.mdr.api.domain.asset.AssetAssociationProperty;
import edu.utah.further.mdr.api.to.asset.AttributeTranslationResultTo;
import edu.utah.further.mdr.ws.api.service.rest.AssetServiceRest;

/**
 * Tests attaching previous results to queries.
 *

 * -----------------------------------------------------------------------------------

 * (c) 2008-2013 FURTHeR Project, Health Sciences IT, University of Utah

 * Contact: {@code <further@utah.edu>}

 * Biomedical Informatics, 26 South 2000 East

 * Room 5775 HSEB, Salt Lake City, UT 84112

 * Day Phone: 1-801-581-4080

 * -----------------------------------------------------------------------------------
 *
 * @author N. Dustin Schultz {@code <dustin.schultz@utah.edu>}
 * @version Mar 27, 2012
 */
public class UTestAssociatedResultsAttacher extends DsImplFixture
{
	/**
	 * Attaches previous results to a query
	 */
	private final AssociatedResultAttacherImpl resultsAttacher = new AssociatedResultAttacherImpl();

	/**
	 * Mock {@link AssociatedResultService}
	 */
	private final AssociatedResultService associatedResultService = createNiceMock(AssociatedResultService.class);

	/**
	 * Mock {@link AssetServiceRest}
	 */
	private final AssetServiceRest assetService = createNiceMock(AssetServiceRest.class);

	/**
	 * The logical property to translate.
	 */
	private final String property = "id";

	/**
	 * The logical property's type
	 */
	private final Class<?> type = BigDecimal.class;

	/**
	 * The logical namespace to translate from.
	 */
	private final String namespace = "FURTHeR";

	/**
	 * The target namespace to translate to.
	 */
	private final String target = "UUEDW";

	/**
	 * Mock results list.
	 */
	private final List<Long> results = newList();

	/**
	 * Sets up the test mocks
	 */
	@Before
	public void setup()
	{
		resultsAttacher.setAssociatedResultService(associatedResultService);

		results.add(new Long(1L));
		results.add(new Long(2L));
		results.add(new Long(3L));

		final AttributeTranslationResultTo result = new AttributeTranslationResultTo();
		result.setTranslatedAttribute("id");

		final Map<String, String> properties = new HashMap<>();
		properties.put(AssetAssociationProperty.JAVA_DATA_TYPE, "java.lang.Long");
		result.setAttributeProperties(properties);

		expect(
				associatedResultService.getAssociatedResult(new Long(anyLong()),
						eq(target))).andStubReturn(results);
		expect(assetService.getUniqueAttributeTranslation(property, namespace, target))
				.andStubReturn(result);
		replay(associatedResultService, assetService);
	}

	/**
	 * Attach previous results to a simple query.
	 */
	@Test
	public void attachResultsToSimple()
	{
		final QueryContext federatedContext = createFederatedContext(createSimpleQuery());
		final SearchQuery attachedSearchQuery = resultsAttacher.attachAssociatedResult(
				federatedContext, target, property, type);
		assertThat(attachedSearchQuery.getRootCriterion().getSearchType(),
				is(SearchType.CONJUNCTION));

		final List<SearchCriterion> children = attachedSearchQuery
				.getRootCriterion()
				.getCriteria();
		assertThat(new Integer(children.size()), is(new Integer(2)));
		assertThat(children.get(1).getSearchType(), is(SearchType.IN));
		assertThat((BigDecimal) children.get(1).getParameter(1), is(new BigDecimal(1L)));
		assertThat((BigDecimal) children.get(1).getParameter(2), is(new BigDecimal(2L)));
		assertThat((BigDecimal) children.get(1).getParameter(3), is(new BigDecimal(3L)));

	}

	/**
	 * Attach previous results to a junction type query.
	 */
	@Test
	public void attachResultsToJunction()
	{
		final QueryContext federatedContext = createFederatedContext(createJunctionQuery());
		final SearchQuery attachedSearchQuery = resultsAttacher.attachAssociatedResult(
				federatedContext, target, property, type);
		assertThat(attachedSearchQuery.getRootCriterion().getSearchType(),
				is(SearchType.CONJUNCTION));

		final List<SearchCriterion> children = attachedSearchQuery
				.getRootCriterion()
				.getCriteria();
		assertThat(new Integer(children.size()), is(new Integer(3)));
		assertThat(children.get(2).getSearchType(), is(SearchType.IN));
		assertThat((String) children.get(2).getParameter(0), is("id"));
		assertThat((BigDecimal) children.get(2).getParameter(1), is(new BigDecimal(1L)));
		assertThat((BigDecimal) children.get(2).getParameter(2), is(new BigDecimal(2L)));
		assertThat((BigDecimal) children.get(2).getParameter(3), is(new BigDecimal(3L)));
	}

	@Test
	public void attachLargeResults()
	{
		results.clear();
		for (int i = 0; i < 2000; i++)
		{
			results.add(new Long(i));
		}
		final QueryContext federatedContext = createFederatedContext(createSimpleQuery());
		final SearchQuery attachedSearchQuery = resultsAttacher.attachAssociatedResult(
				federatedContext, target, property, type);
		assertThat(attachedSearchQuery.getRootCriterion().getSearchType(),
				is(SearchType.CONJUNCTION));

		final List<SearchCriterion> children = attachedSearchQuery
				.getRootCriterion()
				.getCriteria();
		assertThat(new Integer(children.size()), is(new Integer(2)));
		assertThat(children.get(1).getSearchType(), is(SearchType.DISJUNCTION));
		assertThat(new Integer(children.get(1).getCriteria().size()), is(new Integer(2)));
		assertThat(children.get(1).getCriteria().get(0).getSearchType(),
				is(SearchType.IN));
		assertThat(children.get(1).getCriteria().get(1).getSearchType(),
				is(SearchType.IN));
	}

	/**
	 * Creates a stubbed out federated context with the given search query
	 *
	 * @param query
	 * @return
	 */
	private QueryContext createFederatedContext(final SearchQuery query)
	{
		final QueryContextToImpl federatedContext = new QueryContextToImpl();
		federatedContext.setId(new Long(1L));
		// This really isn't valid but works for testing purposes
		federatedContext.setAssociatedResult(federatedContext);
		federatedContext.setQuery(query);
		return federatedContext;
	}

	/**
	 * Creates a simple query that only has root criterion and does not start with a
	 * JUNCTION of some sort.
	 *
	 * @return
	 */
	private SearchQuery createSimpleQuery()
	{
		return query(simpleExpression(Relation.EQ, "age", "50"), "Person");
	}

	/**
	 * Returns a SearchQuery that starts with a JUNCTION.
	 *
	 * @return
	 */
	private SearchQuery createJunctionQuery()
	{
		final SearchCriterion criterion = junction(CONJUNCTION);
		addSimpleExpression(criterion, Relation.EQ, "age", "50");
		addSimpleExpression(criterion, Relation.EQ, "sex", 263495000L);
		return query(criterion, "Person");
	}
}


text:
var should = require("should")
    , Transfer = require("../Transfer")
    , User = require("../User")
    , Domain = require("../../lib/Domain")
    , domain = new Domain();

domain.register("User", User);
domain.register("Transfer", Transfer);

var uid1, uid2;

domain.repos.User.create({}, function (err, u) {
    uid1 = u.get("id");
    u.recharge({money: 10, id: "t1"});
    u.finish({id: "t1"});
})

domain.repos.User.create({}, function (err, u) {
    uid2 = u.get("id");
})

describe("Transfer", function () {

    var transfer;

    it("#new", function (done) {

        domain.repos.Transfer.create({}, function (err, t) {
            transfer = t;
            done()
        })

    })

    it("#start event", function () {
        transfer.get("start").should.eql(false);
        transfer.transfer({user1_id: uid1, user2_id: uid2, money: 5});
        transfer.get("start").should.eql(true);
    })

    it("#listener deduct event", function () {
        transfer.isCompleted().should.eql(false);
        transfer.get("deducted").should.eql(false);
        transfer.emit("deduct");
        transfer.get("deducted").should.eql(true);
        transfer.isCompleted().should.eql(false);

    })

    it("#listener recharge event", function () {
        transfer.isCompleted().should.eql(false);
        transfer.get("recharged").should.eql(false);
        transfer.emit("recharge");
        transfer.get("recharged").should.eql(true);
        transfer.isCompleted().should.eql(true);
    })

})


text:
package org.springframework.boot.validation;

import javax.validation.MessageInterpolator;
import javax.validation.Validation;
import javax.validation.ValidationException;

import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.boot.testsupport.runner.classpath.ClassPathExclusions;
import org.springframework.boot.testsupport.runner.classpath.ModifiedClassPathRunner;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

/**
 * Integration tests for {@link MessageInterpolatorFactory} without EL.
 *
 * @author Phillip Webb
 */
@RunWith(ModifiedClassPathRunner.class)
@ClassPathExclusions("tomcat-embed-el-*.jar")
public class MessageInterpolatorFactoryWithoutElIntegrationTests {

	@Test
	public void defaultMessageInterpolatorShouldFail() {
		// Sanity test
		assertThatExceptionOfType(ValidationException.class).isThrownBy(
				Validation.byDefaultProvider().configure()::getDefaultMessageInterpolator)
				.withMessageContaining("javax.el.ExpressionFactory");
	}

	@Test
	public void getObjectShouldUseFallback() {
		MessageInterpolator interpolator = new MessageInterpolatorFactory().getObject();
		assertThat(interpolator).isInstanceOf(ParameterMessageInterpolator.class);
	}

}


text:
SenchaTestRunner.bindings = {

    setCurrentScript : function(script) {
        jasmine.setCurrentScript(script);
    },

    waitUntilPageIsReady : function(callbackFunction) {
        var args = arguments;
        if (typeof Ext !== 'undefined') {
            Ext.require('*');
            Ext.onReady(function() {
                window.__pageIsReady = true;
            });
        } else {
            window.__pageIsReady = true;
        }
    },

    startTestRunner : function(jsonOptions, contextDirectoryMapping) {
        addGlobal('__pageIsReady');
        addGlobal('__injectionDone');
        jasmine.setOptions(jsonOptions);
        jasmine.initDebug();
        jasmine.getEnv().addReporter(new SenchaTestRunner.Reporter());
        jasmine.getEnv().execute();
    },

    testsAreRunning : function() {
        return SenchaTestRunner.isRunning();
    },

    getTestResultsAsJson : function() {
        return JSON.stringify(SenchaTestRunner.results);
    }

}


text:
# DN generator

A [Yeoman](http://yeoman.io/) generator for DN with
[Flight](http://flightjs.github.io/), Twitter's client-side JavaScript.
Get up and running with everything you need to create an
application.

## Recommended setup

Install [Node.js](http://nodejs.org/) (which comes with npm). It's best to have
npm version 1.2.x or above installed.

Next, globally install the DN generator. This will automatically install
[Bower](http://bower.io/) and [Yo](http://yeoman.io/) as global dependencies.
These tools will help manage your dependencies and generate the boilerplate
Flight application.

```
npm install -g generator-dn
```

Make a new directory, and `cd` into it:

```
mkdir my-app && cd $_
```

You're now ready to generate an app!

## Main generator

To generate a Flight-based application:

```
yo DN:all
```

**N.B.** All your Node and client-side dependencies will be installed
automatically unless you include the `--skip-install` option.

## All generators and their output

Available generators (to be run in the root directory of a project).

* `DN`
* `DN:component <component-name>`
* `DN:mixin <mixin-name>`
* `DN:all`

### DN:app

Scaffolds a application file structure.

Example:

```
yo DN
```

Produces:

TODO

### DN:component

Generates a mixin component in `<baseDir>/<scriptDir>/component`.

Example:

```
yo DN:component my-component
```

Produces `<baseDir>/<scriptDir>/component/my-component.js`:

```js
define(function (require) {
  var defineComponent = require('flight/lib/component');

  return defineComponent(tweetBox);

  function tweetBox() {
    this.attributes({});
    this.after('initialize', function () {});
  }
});
```

And the test file `<baseDir>/<scriptDir>/specs/component/my-component.test.js`:

```js
'use strict';
var component = require('component/my-component.js');

describeComponent(component, function () {

  // Initialize the component and attach it to the DOM
  beforeEach(function () {
    this.setupComponent();
  });

  it('should be defined', function () {
    expect(this.component).toBeDefined();
  });

  it('should do something');

});
```

And the less file `<baseDir>/<scriptDir>/less/component/my-component.less`:

```less
/***
 * Components: my-component
 */

 /**
  * my-component:
  * Something to describe your component.
  *
  *     @example
  *     <div class="my-component">my-component</div>
  */

.my-component {
  // Blocks
  &__block {

  }
  // Modifiers
  &--modifier {

  }
}
```

### DN:mixin

Generates a mixin component in `<baseDir>/<scriptDir>/mixin`.

Example:

```
yo DN:mixin my-mixin
```

Produces `<baseDir>/<scriptDir>/mixin/my-mixin.js`:

```js
'use strict';

/**
 * Module exports
 */

module.exports = myMixin;

/**
 * Module function
 */

function myMixin () {
  this.attributes({

  });

  this.after('initialize', function() {

  });
}
```

And the test file `<baseDir>/<scriptDir>/specs/mixins/my-mixin.test.js`:

```js
'use strict';
var component = require('mixin/my-mixin.js');

describeMixin(component, function () {

  // Initialize the component and attach it to the DOM
  beforeEach(function () {
    this.setupComponent();
  });

  it('should be defined', function () {
    expect(this.component).toBeDefined();
  });

  it('should do something');

});
```

### DN:all

Shortcut that runs `DN:app`, `DN:component my_component`, and
`DN:mixin my_mixin`.


text:
package org.camunda.bpm.engine.impl.jobexecutor;

import java.util.Collection;

import org.camunda.bpm.engine.OptimisticLockingException;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.ProcessEngineLogger;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;
import org.camunda.bpm.engine.repository.ProcessDefinition;

/**
 * @author Daniel Meyer
 *
 */
public class JobExecutorLogger extends ProcessEngineLogger {

  public void debugAcquiredJobNotFound(String jobId) {
    logDebug(
        "001", "Acquired job with id '{}' not found.", jobId);
  }

  public void exceptionWhileExecutingJob(JobEntity job, Throwable exception) {
    logWarn(
        "002", "Exception while executing job {}: ", job, exception);
  }

  public void debugFallbackToDefaultRetryStrategy() {
    logDebug(
        "003", "Falling back to default retry strategy");
  }

  public void debugDecrementingRetriesForJob(String id) {
    logDebug(
        "004", "Decrementing retries of job {}", id);
  }

  public void debugInitiallyAppyingRetryCycleForJob(String id, int times) {
    logDebug(
        "005", "Applying job retry time cycle for the first time for job {}, retires {}", id, times);
  }

  public void exceptionWhileExecutingJob(String nextJobId, Throwable t) {
    if(t instanceof OptimisticLockingException && !isDebugEnabled()) {
      logWarn(
          "006",
          "Exception while executing job {}: {}. To see the full stacktrace set logging level to DEBUG.",
          nextJobId, t.getClass().getSimpleName());
    } else {
      logWarn(
          "006", "Exception while executing job {}: ", nextJobId, t);
    }
  }

  public void couldNotDeterminePriority(ExecutionEntity execution, Object value, ProcessEngineException e) {
    logWarn(
        "007",
        "Could not determine priority for job created in context of execution {}. Using default priority {}",
        execution, value, e);
  }

  public void debugAddingNewExclusiveJobToJobExecutorCOntext(String jobId) {
    logDebug(
        "008",
        "Adding new exclusive job to job executor context. Job Id='{}'", jobId);
  }

  public void timeoutDuringShutdown() {
    logWarn(
        "009",
        "Timeout during shutdown of job executor. The current running jobs could not end within 60 seconds after shutdown operation");
  }

  public void interruptedWhileShuttingDownjobExecutor(InterruptedException e) {
    logWarn(
        "010",
        "Interrupted while shutting down the job executor", e);
  }

  public void debugJobAcquisitionThreadSleeping(long millis) {
    logDebug("011", "Job acquisition thread sleeping for {} millis", millis);
  }

  public void jobExecutorThreadWokeUp() {
    logDebug("012", "Job acquisition thread woke up");
  }

  public void jobExecutionWaitInterrupted() {
    logDebug("013", "Job Execution wait interrupted");
  }

  public void startingUpJobExecutor(String name) {
    logInfo(
        "014", "Starting up the JobExecutor[{}].", name);
  }

  public void shuttingDownTheJobExecutor(String name) {
    logInfo(
        "015", "Shutting down the JobExecutor[{}]", name);
  }

  public void ignoringSuspendedJob(ProcessDefinition processDefinition) {
    logDebug(
        "016",
        "Ignoring job of suspended {}", processDefinition);
  }

  public void debugNotifyingJobExecutor(String string) {
    logDebug(
        "017", "Notifying Job Executor of new job {}", string);
  }

  public void startingToAcquireJobs(String name) {
    logInfo(
        "018", "{} starting to acquire jobs", name);
  }

  public void exceptionDuringJobAcquisition(Exception e) {
    logError(
        "019", "Exception during job acquisition {}", e.getMessage(), e);
  }

  public void stoppedJobAcquisition(String name) {
    logInfo(
        "020", "{} stopped job acquisition", name);
  }

  public void exceptionWhileUnlockingJob(String jobId, Throwable t) {
    logWarn(
        "021",
        "Exception while unaquiring job {}: ", jobId, t);
  }

  public void acquiredJobs(String processEngine, AcquiredJobs acquiredJobs) {
    logDebug(
        "022",
        "Acquired {} jobs for process engine '{}': {}", acquiredJobs.size(), processEngine, acquiredJobs.getJobIdBatches());
  }

  public void executeJobs(String processEngine, Collection<String> jobs) {
    logDebug(
        "023",
        "Execute jobs for process engine '{}': {}", processEngine, jobs);
  }

  public void debugFailedJobNotFound(String jobId) {
    logDebug(
        "024", "Failed job with id '{}' not found.", jobId);
  }

  public ProcessEngineException wrapJobExecutionFailure(JobFailureCollector jobFailureCollector, Throwable cause) {
    JobEntity job = jobFailureCollector.getJob();
    if (job != null) {
      return new ProcessEngineException(exceptionMessage(
        "025", "Exception while executing job {}: ", jobFailureCollector.getJob()), cause);
    }
    else {
      return new ProcessEngineException(exceptionMessage(
         "025", "Exception while executing job {}: ", jobFailureCollector.getJobId()), cause);
    }
  }

  public ProcessEngineException jobNotFoundException(String jobId) {
    return new ProcessEngineException(exceptionMessage(
        "026", "No job found with id '{}'", jobId));
  }

  public void exceptionWhileParsingExpression(String jobId, String exceptionMessage) {
    logWarn(
        "027", "Falling back to default retry strategy. Exception while executing job {}: {}", jobId, exceptionMessage);
  }

  public void warnHistoryCleanupBatchWindowNotFound() {
    logWarn(
      "028",
      "Batch window for history cleanup was not calculated. History cleanup job(s) will be suspended.");
  }

}


text:
//
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//

#ifndef sig_FilterContext_INCL_
#define sig_FilterContext_INCL_

/*! \file
\brief Declarations for sig::FilterContext
*/

#include "libdat/Extents.h"
#include "libdat/Region.h"
#include "libdat/RowCol.h"
#include "libdat/SpotX.h"
#include "libdat/Spot.h"
#include "libdat/SubExtents.h"
#include "libsig/MoveConfig.h"

#include <sstream>

namespace sig
{

/*! \brief Moving filter context

\par Example
\dontinclude testsig/uFilterContext.cpp
\skip ExampleStart
\until ExampleEnd
*/

class FilterContext
{

// public : // data

	//! Location of (fixed) hunk in reference image
	dat::RowCol theRefUL;

	//! Location of move configuration in target image
	dat::RowCol theTgtUL;

	//! Specification of areas involved in matching
	sig::MoveConfig theMoveConfig;

	//! Quantization size (e.g. for color filter array alignments, etc)
	size_t theQuant;

public : // static methods

	//! Value construction
	static
	FilterContext
	fromCenters
		( dat::RowCol const & refCenterRC
		, dat::RowCol const & tgtCenterRC
		, dat::Extents const & hunkSize
		, dat::Extents const & moveSize
		, size_t const & quant = 1u
		);

	//! Area in target that overlaps with reference
	static
	dat::SubExtents
	commonCropIn1
		( dat::Extents const & size1
		, dat::SpotX const & x2w1
		, dat::Extents const & size2
		);

public : // methods

	//! Null instance
	FilterContext
		();

	//! Value construction
	explicit
	FilterContext
		( dat::RowCol const & refUL
		, dat::RowCol const & tgtUL
		, MoveConfig const & mcon
		, size_t const & quant = 1u
		);

	//! Value construction
	explicit
	FilterContext
		( dat::RowCol const & refUL
		, dat::RowCol const & tgtUL
		, dat::Extents const & hunkSize
		, dat::Extents const & moveSize
		, size_t const & quant = 1u
		);

	//! True if this instance is meaningful
	bool
	isValid
		() const;

	//! Working area in relation to sourceGrid
	dat::SubExtents
	referenceCrop
		() const;

	//! Working area in relation to sourceGridB - aligned to alignQuantize
	dat::SubExtents
	targetCrop
		() const;

	//! Extents of motion in target image for UL corner of hunk
	dat::Extents
	targetMoveSize
		() const;

	//! Location for *CENTER* of reference hunk
	dat::Spot
	hotSpotForReference
		() const;

	//! Location for *CENTER* of hunk when hunk UL corner is at pOrigInMove
	dat::Spot
	hotSpotForTargetAt
		( dat::Spot const & pOrigInMove
		) const;

	//! Specialization for half size downsample (e.g. bayer cfa bands)
	FilterContext
	halfContext
		() const;

	//! True if this and other are same (all exact integer compares)
	bool
	nearlyEquals
		( FilterContext const & other
		) const;

	//! Descriptive information about this instance
	std::string
	infoString
		( std::string const & title = std::string()
		) const;

};

}

// Inline definitions
// #include "libsig/FilterContext.inl"

#endif // sig_FilterContext_INCL_


text:
<?xml version="1.0"?>
<project name="Processing PDF Library" default="build">

  <target name="clean" description="Clean the build directories">
    <delete dir="bin" />
    <delete dir="library/pdf.jar" />
  </target>

  <target name="compile" description="Compile sources">
    <condition property="core-built">
      <available file="../../../core/core.jar" />
    </condition>
    <fail unless="core-built" message="Please build the core library first and make sure it sits in ../../../core/core.jar" />

    <mkdir dir="bin" />
    <javac target="1.5"
	   srcdir="src" destdir="bin"
	   encoding="UTF-8"
	   includeAntRuntime="false"
	   classpath="../../../core/core.jar; library/itext.jar" />
  </target>

  <target name="build" depends="compile" description="Build PDF library">
    <jar basedir="bin" destfile="library/pdf.jar" />
  </target>
</project>


text:
// Copyright 2011 Carlos Martins
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#include "StInternal.h"

//
// Tries to acquire the reentrant fair lock if it is free or
// is owned by the current thread.
//

static
FORCEINLINE
BOOLEAN
TryAcquireInternal (
    __inout PST_REENTRANT_FAIR_LOCK RLock,
    __out PULONG ThreadId
    )
{
    *ThreadId = GetCurrentThreadId();
    if (TryAcquireFairLockInternal(&RLock->Lock)) {
        RLock->Owner = *ThreadId;
        return TRUE;
    }
    if (RLock->Owner == *ThreadId) {
        RLock->Count++;
        return TRUE;
    }
    return FALSE;
}

//
// Tries to acquire the reentrant fair lock, activating the
// specified cancellers.
//

ULONG
WINAPI
StReentrantFairLock_TryEnterEx (
    __inout PST_REENTRANT_FAIR_LOCK RLock,
    __in ULONG Timeout,
    __inout_opt PST_ALERTER Alerter
    )
{
    ULONG ThreadId;
    ULONG WaitStatus;

    //
    // Try to acquire the lock if it is free or already owned
    // by the current thread.
    //

    if (TryAcquireInternal(RLock, &ThreadId)) {
        return WAIT_SUCCESS;
    }

    //
    // The lock is busy; so return failure if a null timeout
    // was specified.
    //

    if (Timeout == 0) {
        return WAIT_TIMEOUT;
    }

    //
    // Try to acquire the associated busy non-reentrant fair lock.
    //

    if ((WaitStatus = FairLock_TryEnterTail(&RLock->Lock, Timeout, Alerter)) == WAIT_SUCCESS) {
        RLock->Owner = ThreadId;
        return WAIT_SUCCESS;
    }
    return WaitStatus;
}

//
// Tries to acquire the reentrant fair lock immediately.
//

BOOL
WINAPI
StReentrantFairLock_TryEnter (
    __inout PST_REENTRANT_FAIR_LOCK RLock
    )
{
    ULONG ThreadId;

    //
    // Try to acquire the lock if it is free or already owned
    // by the current thread and return the result.
    //

    return TryAcquireInternal(RLock, &ThreadId);
}

//
// Acquire the reentrant fair lock unconditionally.
//

BOOL
WINAPI
StReentrantFairLock_Enter (
    __inout PST_REENTRANT_FAIR_LOCK RLock
    )
{
    ULONG ThreadId;

    //
    // Try to acquire the lock if it is free or already owned
    // by the current thread.
    //

    if (TryAcquireInternal(RLock, &ThreadId)) {
        return TRUE;
    }

    //
    // Acquires unconditionally the associated busy non-reentrant
    // fair lock.
    //

    if (FairLock_TryEnterTail(&RLock->Lock, INFINITE, NULL) == WAIT_SUCCESS) {
        RLock->Owner = ThreadId;
        return TRUE;
    }
    return FALSE;
}

//
// Exits the reentrant fair lock.
//

BOOL
WINAPI
StReentrantFairLock_Exit (
    __inout PST_REENTRANT_FAIR_LOCK RLock
    )
{
    if (RLock->Owner != GetCurrentThreadId()) {
        _ASSERTE(!"The reentrant lock isn't owned by the current thread");
        SetLastError(ERROR_NOT_OWNER);
        return FALSE;
    }

    //
    // If this is the last release, release the associated
    // non-reentrant fair lock; otherwise, decrement the recursive
    // acquisition counter.
    //

    if (RLock->Count == 0) {
        RLock->Owner = INVALID_THREAD_ID;
        StFairLock_Exit(&RLock->Lock);
    } else {
        RLock->Count--;
    }
    return TRUE;
}

/*++
 *
 * Virtual functions used by the condition variables.
 *
 --*/

//
// Returns true if the reentrant fair lock is owned by
// the current thread.
//

static
BOOLEAN
FASTCALL
_IsOwned (
    __in PVOID Lock
    )
{
    return (((PST_REENTRANT_FAIR_LOCK)Lock)->Owner == GetCurrentThreadId());
}

//
// Leaves completely the reentrant fair lock, saving its state.
//

static
LONG
FASTCALL
_ReleaseCompletely (
    __inout PVOID Lock
    )
{
    LONG PreviousState;
    PST_REENTRANT_FAIR_LOCK RLock = (PST_REENTRANT_FAIR_LOCK)Lock;

    //
    // Save the current state of the lock.
    //

    PreviousState = RLock->Count;

    //
    // Release the associated non-reentrant fair lock and
    // return the previous lock state.
    //

    RLock->Count = 0;
    RLock->Owner = INVALID_THREAD_ID;
    StFairLock_Exit(&RLock->Lock);
    return PreviousState;
}

//
// Reenters the reentrant fair lock and restores its previous state.
//

static
VOID
FASTCALL
_Reacquire (
    __inout PVOID Lock,
    __in ULONG WaitStatus,
    __in LONG PreviousState
    )
{

    PST_REENTRANT_FAIR_LOCK RLock = (PST_REENTRANT_FAIR_LOCK)Lock;

    //
    // If the wait on condition variable was cancelled, the lock
    // isn't owned by the current thread, so acquire it;
    // otherwise, the current thread already owns the lock, but
    // the *Owner* field isn't set.
    // Anyway, restore the previous recursive acquisition counter.
    //

    if (WaitStatus != WAIT_SUCCESS) {
        do {
            if (StReentrantFairLock_Enter(RLock)) {
                break;
            }
            Sleep(500);
        } while (TRUE);
    } else {
        _ASSERTE(RLock->Owner == INVALID_THREAD_ID);
        RLock->Owner = GetCurrentThreadId();
    }
    RLock->Count = PreviousState;
}

//
// Enqueues the specified wait block in the lock's queue.
//
// NOTE: When this function is called, we know that the lock
//		 is owned by the current thread as mandates the monitor
//		 Notify's semantics.
//

static
VOID
FASTCALL
_EnqueueWaiter (
    __inout PVOID Lock,
    __inout PWAIT_BLOCK WaitBlock
    )
{
    extern ILOCK_VTBL ILockVtblForFairLock;

    PST_REENTRANT_FAIR_LOCK RLock = (PST_REENTRANT_FAIR_LOCK)Lock;

    _ASSERTE(RLock->Owner == GetCurrentThreadId());
    (*ILockVtblForFairLock.EnqueueWaiter)(&RLock->Lock, WaitBlock);
}

//
// Virtual function table used by the condition variables.
//

ILOCK_VTBL ILockVtblForReentrantFairLock = {
    _IsOwned,
    _ReleaseCompletely,
    _Reacquire,
    _EnqueueWaiter
};

/*++
 *
 * Virtual functions that support the Waitable functionality.
 *
 --*/

//
// Returns true if the reentrant fair lock can be immediately
// acquired by the current thread.
//

static
BOOLEAN
FASTCALL
_AllowsAcquire (
    __in PST_WAITABLE Waitable
    )
{
    PST_REENTRANT_FAIR_LOCK RLock = (PST_REENTRANT_FAIR_LOCK)Waitable;

    return (RLock->Owner == GetCurrentThreadId() || ALLOWS_ACQUIRE(&RLock->Lock.Waitable));
}

//
// Tries to acquire the reentrant fair lock.
//

static
BOOLEAN
FASTCALL
_TryAcquire (
    __inout PST_WAITABLE Waitable
    )
{
    ULONG ThreadId;
    return TryAcquireInternal((PST_REENTRANT_FAIR_LOCK)Waitable, &ThreadId);
}

//
// Releases the reentrant fair lock if it is owned by the current
// thread; otherwise, does nothing and returns failure.
//

static
BOOLEAN
FASTCALL
_Release (
    __inout PST_WAITABLE Waitable
    )
{
    PST_REENTRANT_FAIR_LOCK RLock = (PST_REENTRANT_FAIR_LOCK)Waitable;

    if (RLock->Owner != GetCurrentThreadId()) {
        SetLastError(ERROR_NOT_OWNER);
        return FALSE;
    }

    StReentrantFairLock_Exit(RLock);
    return TRUE;
}

//
// Executes the WaitAny prologue.
//

static
BOOLEAN
FASTCALL
_WaitAnyPrologue (
    __inout PST_WAITABLE Waitable,
    __inout PST_PARKER Parker,
    __out PWAIT_BLOCK WaitBlock,
    __in ULONG WaitKey,
    __out PULONG SpinCount
    )
{
    ULONG ThreadId;
    PST_REENTRANT_FAIR_LOCK RLock = (PST_REENTRANT_FAIR_LOCK)Waitable;

    //
    // If the reentrant fair lock is free, try to acquire it.
    // if succeed, try to self lock the parker and, if
    // succeed, self unpark the current thread.
    //

    if (TryAcquireInternal(RLock, &ThreadId)) {
        if (TryLockParker(Parker)) {
            UnparkSelf(Parker, WaitKey);
        } else {

            //
            // The parker is already locked because the wait-any
            // operation was satisfied on another waitable; so, release
            // the lock, undoing the previous acquire.
            //

            StReentrantFairLock_Exit(RLock);
        }

        //
        // Return true to signal that the wait-any operation was
        // already satisfied.
        //

        return TRUE;
    }

    //
    // Since that the lock is busy, execute the WaitAny prologue on
    // the associated non-reentrant fair lock and return its results.
    //

    return WAIT_ANY_PROLOGUE(&RLock->Lock.Waitable, Parker, WaitBlock, WaitKey, SpinCount);
}

//
// Executes the WaitAll prologue.
//

static
BOOLEAN
FASTCALL
_WaitAllPrologue (
    __inout PST_WAITABLE Waitable,
    __inout PST_PARKER Parker,
    __out PWAIT_BLOCK WaitBlock,
    __out PULONG SpinCount
    )
{
    PST_REENTRANT_FAIR_LOCK RLock = (PST_REENTRANT_FAIR_LOCK)Waitable;

    //
    // If the lock can be immediately acquired by the current thread,
    // lock the parker and, if this is the last cooperative
    // release, self unpark the current thread .
    //

    if (_AllowsAcquire(&RLock->Waitable))  {
        if (TryLockParker(Parker)) {
            UnparkSelf(Parker, WAIT_STATE_CHANGED);
        }

        //
        // Mark the wait block as unlinked and return true.
        //

        WaitBlock->WaitListEntry.Flink = &WaitBlock->WaitListEntry;
        return TRUE;
    }

    //
    // Since that the lock can't be immediately acquired, execute the
    // WaitAll prologue on the associated non-reentrant fair lock and
    // return its results.
    //

    return WAIT_ALL_PROLOGUE(&RLock->Lock.Waitable, Parker, WaitBlock, SpinCount);
}

//
// Sets the lock's owner field.
//

static
VOID
FASTCALL
_WaitEpilogue (
    __inout PST_WAITABLE Waitable
    )
{
    PST_REENTRANT_FAIR_LOCK RLock = (PST_REENTRANT_FAIR_LOCK)Waitable;

    _ASSERTE(RLock->Owner == INVALID_THREAD_ID || RLock->Owner == GetCurrentThreadId());
    RLock->Owner = GetCurrentThreadId();
}

//
// Releases the lock, undoing a previous acquire.
//

static
VOID
FASTCALL
_UndoAcquire (
    __inout PST_WAITABLE Waitable
    )
{
    StReentrantFairLock_Exit((PST_REENTRANT_FAIR_LOCK)Waitable);
}

//
// Cancels the waitable acquire attempt.
//

static
VOID
FASTCALL
_CancelAcquire (
    __inout PST_WAITABLE Waitable,
    __inout PWAIT_BLOCK WaitBlock
    )
{

    //
    // Cancels the acquire attempt on the associated non-reentrant
    // fair lock.
    //

    CANCEL_ACQUIRE(&((PST_REENTRANT_FAIR_LOCK)Waitable)->Lock.Waitable, WaitBlock);
}

//
// Virtual function table for the reentrant fair lock.
//

WAITABLE_VTBL ReentrantFairLockVtbl = {
    _AllowsAcquire,
    _TryAcquire,
    _Release,
    _WaitAnyPrologue,
    _WaitAllPrologue,
    _WaitEpilogue,
    _UndoAcquire,
    _CancelAcquire
};

//
// Initializes the reentrant fair lock.
//

VOID
WINAPI
StReentrantFairLock_Init (
    __out PST_REENTRANT_FAIR_LOCK RLock,
    __in ULONG SpinCount
    )
{
    RLock->Waitable.Vptr = &ReentrantFairLockVtbl;
    StFairLock_Init(&RLock->Lock, SpinCount);
    RLock->Owner = INVALID_THREAD_ID;
    RLock->Count = 0;
}


text:
angular.module('protractorApp', ['ta.bootstrap.fm']).config(['$translateProvider',
function($translateProvider) {
	$translateProvider.preferredLanguage('en-US');
}]).controller('Ctrl', function($scope, $modal, fmVendor) {
	$scope.tudousrc = 'http://www.tudou.com/programs/view/html5embed.action?code=PEq07Nfr5bY';
	$scope.openFm = function(vendor) {
		$modal.open({
			templateUrl : '/views/filemanager/filemanager.html',
			controller : 'fmModalInstanceCtrl',
			size : 'lg',
			resolve : {
				data : function() {
					return fmVendor(vendor);
				}
			}
		}).result.then(function(file) {
			console.log('then: ', file)
		});
	};
});


text:
// GenericsNote: Converted.

package php.runtime.common.collections.iterators;

import php.runtime.common.collections.ResettableIterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An {@link java.util.Iterator} over an array of objects.
 *

 * This iterator does not support {@link #remove}, as the object array cannot be
 * structurally modified.
 *

 * The iterator implements a {@link #reset} method, allowing the reset of the iterator
 * back to the start if required.
 *
 * @author James Strachan
 * @author Mauricio S. Moura
 * @author Michael A. Smith
 * @author Neil O'Toole
 * @author Stephen Colebourne
 * @author Matt Hall, John Watkinson, Phil Steitz
 * @version $Revision: 1.1 $ $Date: 2005/10/11 17:05:24 $
 * @since Commons Collections 3.0
 */
public class ObjectArrayIterator <E> implements Iterator<E>, ResettableIterator<E> {

    /**
     * The array
     */
    protected E[] array = null;
    /**
     * The start index to loop from
     */
    protected int startIndex = 0;
    /**
     * The end index to loop to
     */
    protected int endIndex = 0;
    /**
     * The current iterator index
     */
    protected int index = 0;

    /**
     * Constructor for use with setArray.
     *

     * Using this constructor, the iterator is equivalent to an empty iterator
     * until {@link #setArray} is  called to establish the array to iterate over.
     */
    public ObjectArrayIterator() {
        super();
    }

    /**
     * Constructs an ObjectArrayIterator that will iterate over the values in the
     * specified array.
     *
     * @param array the array to iterate over
     * @throws NullPointerException if array is null
     */
    public ObjectArrayIterator(E[] array) {
        this(array, 0, array.length);
    }

    /**
     * Constructs an ObjectArrayIterator that will iterate over the values in the
     * specified array from a specific start index.
     *
     * @param array the array to iterate over
     * @param start the index to start iterating at
     * @throws NullPointerException      if array is null
     * @throws IndexOutOfBoundsException if the start index is out of bounds
     */
    public ObjectArrayIterator(E[] array, int start) {
        this(array, start, array.length);
    }

    /**
     * Construct an ObjectArrayIterator that will iterate over a range of values
     * in the specified array.
     *
     * @param array the array to iterate over
     * @param start the index to start iterating at
     * @param end   the index (exclusive) to finish iterating at
     * @throws IndexOutOfBoundsException if the start or end index is out of bounds
     * @throws IllegalArgumentException  if end index is before the start
     * @throws NullPointerException      if array is null
     */
    public ObjectArrayIterator(E[] array, int start, int end) {
        super();
        if (start < 0) {
            throw new ArrayIndexOutOfBoundsException("Start index must not be less than zero");
        }
        if (end > array.length) {
            throw new ArrayIndexOutOfBoundsException("End index must not be greater than the array length");
        }
        if (start > array.length) {
            throw new ArrayIndexOutOfBoundsException("Start index must not be greater than the array length");
        }
        if (end < start) {
            throw new IllegalArgumentException("End index must not be less than start index");
        }
        this.array = array;
        this.startIndex = start;
        this.endIndex = end;
        this.index = start;
    }

    // Iterator interface
    //-------------------------------------------------------------------------

    /**
     * Returns true if there are more elements to return from the array.
     *
     * @return true if there is a next element to return
     */
    public boolean hasNext() {
        return (this.index < this.endIndex);
    }

    /**
     * Returns the next element in the array.
     *
     * @return the next element in the array
     * @throws java.util.NoSuchElementException if all the elements in the array
     *                                have already been returned
     */
    public E next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return this.array[this.index++];
    }

    /**
     * Throws {@link UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException always
     */
    public void remove() {
        throw new UnsupportedOperationException("remove() method is not supported for an ObjectArrayIterator");
    }

    // Properties
    //-------------------------------------------------------------------------

    /**
     * Gets the array that this iterator is iterating over.
     *
     * @return the array this iterator iterates over, or null if
     *         the no-arg constructor was used and {@link #setArray} has never
     *         been called with a valid array.
     */
    public E[] getArray() {
        return this.array;
    }

    /**
     * Sets the array that the  should iterate over.
     *

     * This method may only be called once, otherwise an IllegalStateException
     * will occur.
     *

     * The {@link #reset} method can be used to reset the iterator if required.
     *
     * @param array the array that the iterator should iterate over
     * @throws IllegalStateException if the array was set in the constructor
     * @throws NullPointerException  if array is null
     */
    public void setArray(E[] array) {
        if (this.array != null) {
            throw new IllegalStateException("The array to iterate over has already been set");
        }
        this.array = array;
        this.startIndex = 0;
        this.endIndex = array.length;
        this.index = 0;
    }

    /**
     * Gets the start index to loop from.
     *
     * @return the start index
     */
    public int getStartIndex() {
        return this.startIndex;
    }

    /**
     * Gets the end index to loop to.
     *
     * @return the end index
     */
    public int getEndIndex() {
        return this.endIndex;
    }

    /**
     * Resets the iterator back to the start index.
     */
    public void reset() {
        this.index = this.startIndex;
    }

}


text:
import Ember from 'ember';
import startApp from '../helpers/start-app';

var App;

module('Integration - Landing Page', {
  setup: function() {
    App = startApp();
  },
  teardown: function() {
    Ember.run(App, 'destroy');
  }
});

test('should welcome user', function() {
  visit('/');
  andThen(function() {
    equal(find('h2').text(), 'Welcome to Oxford Circus');
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:b="http://xbean.apache.org/schemas/pizza">

  <b:favorite id="favoriteService">
    <property name="favorites">
      <util:map>
          <entry key="Dan" value="Grey Goose" />
          <entry key="IndecisiveDan">
              <util:list>
                  <value>Malbec</value>
                  <bean class="java.lang.Integer">
                    <constructor-arg value="0"/>
                  </bean>
              </util:list>
          </entry>
          <entry key="WithInnerBean">
            <bean class="org.apache.xbean.spring.example.GinService">
              <property name="name" value="name"/>
            </bean>
          </entry>
      </util:map>
    </property>
  </b:favorite>

</beans>


text:
.angular-google-map-container { height: 450px; }
#chart-container {
	height: 150px;
	width: 50%;
	position: relative;
	border: 1px solid #999999;
	background-color #cccccc:
}
#chart {
	position: relative;
	left: 40px;
}
#y_axis {
	position: absolute;
	top: 0;
	bottom: 0;
	width: 40px;
}


text:
package utils_test

import (
	. "github.com/SumoLogic/sumologic-cloudfoundry-nozzle/utils"
	"github.com/cloudfoundry/sonde-go/events"
	"github.com/gogo/protobuf/proto"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Testing Utils packages", func() {
	Describe("UUID Formated", func() {
		Context("Called with proper UUID", func() {
			It("Should return formated String", func() {
				uuid := &events.UUID{High: proto.Uint64(0), Low: proto.Uint64(0)}
				Expect(FormatUUID(uuid)).To(Equal(("00000000-0000-0000-0000-000000000000")))
			})

		})
	})
	Describe("Concat String ", func() {
		Context("Called with String Map", func() {
			It("Should return Concat string", func() {
				Expect(ConcatFormat([]string{"foo", "bar"})).To(Equal(("foo.bar")))
			})
			It("Should return Proper string", func() {
				Expect(ConcatFormat([]string{"foo   ", "bar"})).To(Equal(("foo.bar")))
			})

		})
	})

})


text:
import { Mandelbrot } from './mandelbrot/Mandelbrot';

class WorkerInit {
    constructor() {

        let mandelbrot: Mandelbrot;

        addEventListener('message', (e: MessageEvent) => {
            if (e.data.cmd == 'init') {
                mandelbrot = new Mandelbrot(e.data.imgData, e.data.width, e.data.height);

                (self as any).postMessage({
                    cmd: 'ready'
                });
            }

            if (e.data.cmd == 'getData') {
                let dataBuf: ArrayBuffer = e.data.dataBuf;

                mandelbrot.crunchData(dataBuf, e.data.iterations);

                //Second property will Transfer the ArrayBuffer rather than copy
                (self as any).postMessage({
                    cmd: 'data',
                    buf: dataBuf
                }, [
                        dataBuf
                    ]);
            }
        });
    }
}

new WorkerInit();


text:
module.exports = function(karma) {
  karma.configure({

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      '*.js',
      '*.html'
    ],

    preprocessors: {
      '*.html': 'html2js'
    },

    // list of files to exclude
    exclude: [

    ],

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],

    // web server port
    port: 9876,

    // cli runner port
    runnerPort: 9100,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: karma.LOG_DISABLE || karma.LOG_ERROR || karma.LOG_WARN || karma.LOG_INFO || karma.LOG_DEBUG
    logLevel: karma.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    // plugins to load
    plugins: [
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-html2js-preprocessor'
    ],
  });
};