text:
package http

import (
	"bytes"
	"encoding/gob"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/ansel1/merry"
	"github.com/go-graphite/carbonapi/carbonapipb"
	"github.com/go-graphite/carbonapi/cmd/carbonapi/config"
	"github.com/go-graphite/carbonapi/date"
	"github.com/go-graphite/carbonapi/expr"
	"github.com/go-graphite/carbonapi/expr/functions/cairo/png"
	"github.com/go-graphite/carbonapi/expr/types"
	"github.com/go-graphite/carbonapi/pkg/parser"
	utilctx "github.com/go-graphite/carbonapi/util/ctx"
	"github.com/go-graphite/carbonapi/zipper/helper"
	pb "github.com/go-graphite/protocol/carbonapi_v3_pb"
	"github.com/lomik/zapwriter"
	stringutils "github.com/msaf1980/go-stringutils"
	uuid "github.com/satori/go.uuid"
	"go.uber.org/zap"
)

func cleanupParams(r *http.Request) {
	// make sure the cache key doesn't say noCache, because it will never hit
	r.Form.Del("noCache")

	// jsonp callback names are frequently autogenerated and hurt our cache
	r.Form.Del("jsonp")

	// Strip some cache-busters.  If you don't want to cache, use noCache=1
	r.Form.Del("_salt")
	r.Form.Del("_ts")
	r.Form.Del("_t") // Used by jquery.graphite.js
}

func setError(w http.ResponseWriter, accessLogDetails *carbonapipb.AccessLogDetails, msg string, status int, carbonapiUUID string) {
	w.Header().Set(ctxHeaderUUID, carbonapiUUID)
	http.Error(w, http.StatusText(status)+": "+msg, status)
	accessLogDetails.Reason = msg
	accessLogDetails.HTTPCode = int32(status)
}

func getCacheTimeout(logger *zap.Logger, r *http.Request, defaultTimeout int32) int32 {
	if tstr := r.FormValue("cacheTimeout"); tstr != "" {
		t, err := strconv.Atoi(tstr)
		if err != nil {
			logger.Error("failed to parse cacheTimeout",
				zap.String("cache_string", tstr),
				zap.Error(err),
			)
		} else {
			return int32(t)
		}
	}

	return defaultTimeout
}

func renderHandler(w http.ResponseWriter, r *http.Request) {
	t0 := time.Now()
	uid := uuid.NewV4()

	// TODO: Migrate to context.WithTimeout
	// ctx, _ := context.WithTimeout(context.TODO(), config.Config.ZipperTimeout)
	ctx := utilctx.SetUUID(r.Context(), uid.String())
	username, _, _ := r.BasicAuth()
	requestHeaders := utilctx.GetLogHeaders(ctx)

	logger := zapwriter.Logger("render").With(
		zap.String("carbonapi_uuid", uid.String()),
		zap.String("username", username),
		zap.Any("request_headers", requestHeaders),
	)

	srcIP, srcPort := splitRemoteAddr(r.RemoteAddr)

	accessLogger := zapwriter.Logger("access")
	var accessLogDetails = &carbonapipb.AccessLogDetails{
		Handler:        "render",
		Username:       username,
		CarbonapiUUID:  uid.String(),
		URL:            r.URL.RequestURI(),
		PeerIP:         srcIP,
		PeerPort:       srcPort,
		Host:           r.Host,
		Referer:        r.Referer(),
		URI:            r.RequestURI,
		RequestHeaders: requestHeaders,
	}

	logAsError := false
	defer func() {
		deferredAccessLogging(accessLogger, accessLogDetails, t0, logAsError)
	}()

	ApiMetrics.Requests.Add(1)

	err := r.ParseForm()
	if err != nil {
		setError(w, accessLogDetails, err.Error(), http.StatusBadRequest, uid.String())
		logAsError = true
		return
	}

	targets := r.Form["target"]
	from := r.FormValue("from")
	until := r.FormValue("until")
	template := r.FormValue("template")
	maxDataPoints, _ := strconv.ParseInt(r.FormValue("maxDataPoints"), 10, 64)
	ctx = utilctx.SetMaxDatapoints(ctx, maxDataPoints)
	useCache := !parser.TruthyBool(r.FormValue("noCache"))
	noNullPoints := parser.TruthyBool(r.FormValue("noNullPoints"))
	// status will be checked later after we'll setup everything else
	format, ok, formatRaw := getFormat(r, pngFormat)

	var jsonp string

	if format == jsonFormat {
		// TODO(dgryski): check jsonp only has valid characters
		jsonp = r.FormValue("jsonp")
	}

	timestampFormat := strings.ToLower(r.FormValue("timestampFormat"))
	if timestampFormat == "" {
		timestampFormat = "s"
	}

	timestampMultiplier := int64(1)
	switch timestampFormat {
	case "s":
		timestampMultiplier = 1
	case "ms", "millisecond", "milliseconds":
		timestampMultiplier = 1000
	case "us", "microsecond", "microseconds":
		timestampMultiplier = 1000000
	case "ns", "nanosecond", "nanoseconds":
		timestampMultiplier = 1000000000
	default:
		setError(w, accessLogDetails, "unsupported timestamp format, supported: 's', 'ms', 'us', 'ns'", http.StatusBadRequest, uid.String())
		logAsError = true
		return
	}

	responseCacheTimeout := getCacheTimeout(logger, r, config.Config.ResponseCacheConfig.DefaultTimeoutSec)
	backendCacheTimeout := getCacheTimeout(logger, r, config.Config.BackendCacheConfig.DefaultTimeoutSec)

	cleanupParams(r)

	// normalize from and until values
	now := timeNow()
	now32 := now.Unix()
	qtz := r.FormValue("tz")
	from32 := date.DateParamToEpoch(from, qtz, now.Add(-24*time.Hour).Unix(), config.Config.DefaultTimeZone)
	until32 := date.DateParamToEpoch(until, qtz, now.Unix(), config.Config.DefaultTimeZone)

	var responseCacheKey string

	if len(config.Config.TruncateTime) > 0 {
		duration := time.Second * time.Duration(until32-from32)
		from32 = timestampTruncate(from32, duration, config.Config.TruncateTime)
		until32 = timestampTruncate(until32, duration, config.Config.TruncateTime)
		responseCacheKey = responseCacheComputeKey(from32, until32, targets, formatRaw, maxDataPoints, noNullPoints, template)
		if duration <= time.Hour && now32-until32 < 60 {
			// short cache ttl
			responseCacheTimeout = config.Config.ResponseCacheConfig.ShortTimeoutSec
			backendCacheTimeout = config.Config.BackendCacheConfig.ShortTimeoutSec
		}
	} else {
		responseCacheKey = r.Form.Encode()
	}

	accessLogDetails.UseCache = useCache
	accessLogDetails.FromRaw = from
	accessLogDetails.From = from32
	accessLogDetails.UntilRaw = until
	accessLogDetails.Until = until32
	accessLogDetails.Tz = qtz
	accessLogDetails.CacheTimeout = responseCacheTimeout
	accessLogDetails.Format = formatRaw
	accessLogDetails.Targets = targets

	if !ok || !format.ValidRenderFormat() {
		setError(w, accessLogDetails, "unsupported format specified: "+formatRaw, http.StatusBadRequest, uid.String())
		logAsError = true
		return
	}

	if format == protoV3Format {
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			accessLogDetails.HTTPCode = http.StatusBadRequest
			accessLogDetails.Reason = "failed to parse message body: " + err.Error()
			http.Error(w, "bad request (failed to parse format): "+err.Error(), http.StatusBadRequest)
			return
		}

		var pv3Request pb.MultiFetchRequest
		err = pv3Request.Unmarshal(body)

		if err != nil {
			accessLogDetails.HTTPCode = http.StatusBadRequest
			accessLogDetails.Reason = "failed to parse message body: " + err.Error()
			http.Error(w, "bad request (failed to parse format): "+err.Error(), http.StatusBadRequest)
			return
		}

		from32 = pv3Request.Metrics[0].StartTime
		until32 = pv3Request.Metrics[0].StopTime
		targets = make([]string, len(pv3Request.Metrics))
		for i, r := range pv3Request.Metrics {
			targets[i] = r.PathExpression
		}
	}

	if useCache {
		tc := time.Now()
		response, err := config.Config.ResponseCache.Get(responseCacheKey)
		td := time.Since(tc).Nanoseconds()
		ApiMetrics.RenderCacheOverheadNS.Add(td)

		accessLogDetails.CarbonzipperResponseSizeBytes = 0
		accessLogDetails.CarbonapiResponseSizeBytes = int64(len(response))

		if err == nil {
			ApiMetrics.RequestCacheHits.Add(1)
			writeResponse(w, http.StatusOK, response, format, jsonp, uid.String())
			accessLogDetails.FromCache = true
			return
		}
		ApiMetrics.RequestCacheMisses.Add(1)
	}

	if from32 == until32 {
		setError(w, accessLogDetails, "Invalid or empty time range", http.StatusBadRequest, uid.String())
		logAsError = true
		return
	}

	defer func() {
		if r := recover(); r != nil {
			logger.Error("panic during eval:",
				zap.String("cache_key", responseCacheKey),
				zap.Any("reason", r),
				zap.Stack("stack"),
			)
			logAsError = true
			var answer string
			if config.Config.HTTPResponseStackTrace {
				answer = fmt.Sprintf("%v\nStack trace: %v", r, zap.Stack("").String)
			} else {
				answer = fmt.Sprint(r)
			}
			setError(w, accessLogDetails, answer, http.StatusInternalServerError, uid.String())
		}
	}()

	errors := make(map[string]merry.Error)

	var backendCacheKey string
	if len(config.Config.TruncateTime) > 0 {
		backendCacheKey = backendCacheComputeKeyAbs(from32, until32, targets)
	} else {
		backendCacheKey = backendCacheComputeKey(from, until, targets)
	}

	results, err := backendCacheFetchResults(logger, useCache, backendCacheKey, accessLogDetails)

	if err != nil {
		ApiMetrics.BackendCacheMisses.Add(1)

		results = make([]*types.MetricData, 0)
		values := make(map[parser.MetricRequest][]*types.MetricData)

		for _, target := range targets {
			exp, e, err := parser.ParseExpr(target)
			if err != nil || e != "" {
				msg := buildParseErrorString(target, e, err)
				setError(w, accessLogDetails, msg, http.StatusBadRequest, uid.String())
				logAsError = true
				return
			}

			ApiMetrics.RenderRequests.Add(1)

			result, err := expr.FetchAndEvalExp(ctx, exp, from32, until32, values)
			if err != nil {
				errors[target] = merry.Wrap(err)
			}

			results = append(results, result...)
		}

		for mFetch := range values {
			expr.SortMetrics(values[mFetch], mFetch)
		}

		if len(errors) == 0 {
			backendCacheStoreResults(logger, backendCacheKey, results, backendCacheTimeout)
		}
	}

	size := 0
	for _, result := range results {
		size += result.Size()
	}

	var body []byte

	returnCode := http.StatusOK
	if len(results) == 0 {
		// Obtain error code from the errors
		// In case we have only "Not Found" errors, result should be 404
		// Otherwise it should be 500
		returnCode, errMsgs := helper.MergeHttpErrorMap(errors)
		logger.Debug("error response or no response", zap.Strings("error", errMsgs))
		// Allow override status code for 404-not-found replies.
		if returnCode == 404 {
			returnCode = config.Config.NotFoundStatusCode
		}

		if returnCode == 400 || returnCode == http.StatusForbidden || returnCode >= 500 {
			setError(w, accessLogDetails, strings.Join(errMsgs, ","), returnCode, uid.String())
			logAsError = true
			return
		}
	}

	switch format {
	case jsonFormat:
		if maxDataPoints != 0 {
			types.ConsolidateJSON(maxDataPoints, results)
			accessLogDetails.MaxDataPoints = maxDataPoints
		}

		body = types.MarshalJSON(results, timestampMultiplier, noNullPoints)
	case protoV2Format:
		body, err = types.MarshalProtobufV2(results)
		if err != nil {
			setError(w, accessLogDetails, err.Error(), http.StatusInternalServerError, uid.String())
			logAsError = true
			return
		}
	case protoV3Format:
		body, err = types.MarshalProtobufV3(results)
		if err != nil {
			setError(w, accessLogDetails, err.Error(), http.StatusInternalServerError, uid.String())
			logAsError = true
			return
		}
	case rawFormat:
		body = types.MarshalRaw(results)
	case csvFormat:
		body = types.MarshalCSV(results)
	case pickleFormat:
		body = types.MarshalPickle(results)
	case pngFormat:
		body = png.MarshalPNGRequest(r, results, template)
	case svgFormat:
		body = png.MarshalSVGRequest(r, results, template)
	}

	accessLogDetails.Metrics = targets
	accessLogDetails.CarbonzipperResponseSizeBytes = int64(size)
	accessLogDetails.CarbonapiResponseSizeBytes = int64(len(body))

	writeResponse(w, returnCode, body, format, jsonp, uid.String())

	if len(results) != 0 {
		tc := time.Now()
		config.Config.ResponseCache.Set(responseCacheKey, body, responseCacheTimeout)
		td := time.Since(tc).Nanoseconds()
		ApiMetrics.RenderCacheOverheadNS.Add(td)
	}

	gotErrors := len(errors) > 0
	accessLogDetails.HaveNonFatalErrors = gotErrors
}

func responseCacheComputeKey(from, until int64, targets []string, format string, maxDataPoints int64, noNullPoints bool, template string) string {
	var responseCacheKey stringutils.Builder
	responseCacheKey.Grow(256)
	responseCacheKey.WriteString("from:")
	responseCacheKey.WriteInt(from, 10)
	responseCacheKey.WriteString(" until:")
	responseCacheKey.WriteInt(until, 10)
	responseCacheKey.WriteString(" targets:")
	responseCacheKey.WriteString(strings.Join(targets, ","))
	responseCacheKey.WriteString(" format:")
	responseCacheKey.WriteString(format)
	if maxDataPoints > 0 {
		responseCacheKey.WriteString(" maxDataPoints:")
		responseCacheKey.WriteInt(maxDataPoints, 10)
	}
	if noNullPoints {
		responseCacheKey.WriteString(" noNullPoints")
	}
	if len(template) > 0 {
		responseCacheKey.WriteString(" template:")
		responseCacheKey.WriteString(template)
	}
	return responseCacheKey.String()
}

func backendCacheComputeKey(from, until string, targets []string) string {
	var backendCacheKey bytes.Buffer
	backendCacheKey.WriteString("from:")
	backendCacheKey.WriteString(from)
	backendCacheKey.WriteString(" until:")
	backendCacheKey.WriteString(until)
	backendCacheKey.WriteString(" targets:")
	backendCacheKey.WriteString(strings.Join(targets, ","))
	return backendCacheKey.String()
}

func backendCacheComputeKeyAbs(from, until int64, targets []string) string {
	var backendCacheKey stringutils.Builder
	backendCacheKey.Grow(128)
	backendCacheKey.WriteString("from:")
	backendCacheKey.WriteInt(from, 10)
	backendCacheKey.WriteString(" until:")
	backendCacheKey.WriteInt(until, 10)
	backendCacheKey.WriteString(" targets:")
	backendCacheKey.WriteString(strings.Join(targets, ","))
	return backendCacheKey.String()
}

func backendCacheFetchResults(logger *zap.Logger, useCache bool, backendCacheKey string, accessLogDetails *carbonapipb.AccessLogDetails) ([]*types.MetricData, error) {
	if !useCache {
		return nil, errors.New("useCache is false")
	}

	backendCacheResults, err := config.Config.BackendCache.Get(backendCacheKey)

	if err != nil {
		return nil, err
	}

	var results []*types.MetricData
	cacheDecodingBuf := bytes.NewBuffer(backendCacheResults)
	dec := gob.NewDecoder(cacheDecodingBuf)
	err = dec.Decode(&results)

	if err != nil {
		logger.Error("Error decoding cached backend results")
		return nil, err
	}

	accessLogDetails.UsedBackendCache = true
	ApiMetrics.BackendCacheHits.Add(1)

	return results, nil
}

func backendCacheStoreResults(logger *zap.Logger, backendCacheKey string, results []*types.MetricData, backendCacheTimeout int32) {
	var serializedResults bytes.Buffer
	enc := gob.NewEncoder(&serializedResults)
	err := enc.Encode(results)

	if err != nil {
		logger.Error("Error encoding backend results for caching")
		return
	}

	config.Config.BackendCache.Set(backendCacheKey, serializedResults.Bytes(), backendCacheTimeout)
}


text:
#include "LuaState.h"
#include "ModulePart_Base.h"
#include <co/IModule.h>

namespace lua {

/*!
	A co.IModulePart that wraps a Lua script in a module's dir.
 */
class LuaModulePart : public ModulePart_Base
{
public:
	LuaModulePart()
	{
		lua_State* L = LuaState::getL();
		assert( lua_type( L, -1 ) == LUA_TTABLE );

		// save the module table in the registry indexed by our own pointer
		lua_pushlightuserdata( L, this );
		lua_pushvalue( L, -2 );
		lua_rawset( L, LUA_REGISTRYINDEX );

		lua_pop( L, 1 );
	}

	~LuaModulePart()
	{
		// if the Lua module was not torn down yet...
		lua_State* L = LuaState::getL();
		if( L )
		{
			// clean our registry entry (i.e. the module table)
			lua_pushlightuserdata( L, this );
			lua_pushnil( L );
			lua_rawset( L, LUA_REGISTRYINDEX );
		}
	}

	void initialize( co::IModule* module )
	{
		callScriptMethod( "initialize", module );
	}

	void integrate( co::IModule* module )
	{
		callScriptMethod( "integrate", module );
	}

	void integratePresentation( co::IModule* module )
	{
		callScriptMethod( "integratePresentation", module );
	}

	void disintegrate( co::IModule* module )
	{
		callScriptMethod( "disintegrate", module );
	}

	void dispose( co::IModule* )
	{
		/*
			Ignored. For simplicity, Lua modules don't directly handle 'dispose'
			events, as it could cause major inter-dependence problems during the
			system tear-down sequence. Not a real problem since the 'dispose'
			event is easily replaced by the 'disintegrate' event in combination
			with the Lua garbage collector.
		 */
	}

private:
	void callScriptMethod( const char* methodName, co::IModule* module )
	{
		lua_State* L = LuaState::getL();
		assert( L );

		// reserve stack space for the method function
		lua_pushnil( L );

		// get the module table
		lua_pushlightuserdata( L, this );
		lua_rawget( L, LUA_REGISTRYINDEX );

		assert( lua_type( L, -1 ) == LUA_TTABLE );

		// try to get the method function
		lua_getfield( L, -1, methodName );
		if( !lua_isfunction( L, -1 ) )
		{
			// method not defined, skip this call
			lua_pop( L, 3 );
			return;
		}

		// move the method function below the module table
		lua_replace( L, -3 );

		// push the 'module' argument and call the method
		LuaState::push( L, module );
		LuaState::call( L, 2, 0 );
	}
};

CORAL_EXPORT_COMPONENT( LuaModulePart, ModulePart );

} // namespace lua

redpajama_set_name: RedPajamaGithub


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

Copyright (c) 2013-2015 Sierra Wireless and others.

All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v1.0 which accompany this distribution.

The Eclipse Public License is available at
   http://www.eclipse.org/legal/epl-v10.html
and the Eclipse Distribution License is available at
   http://www.eclipse.org/org/documents/edl-v10.html.

Contributors:
    Sierra Wireless - initial API and implementation

 -->
<Configuration status="warn" strict="true" name="leshan client demo"
               packages="org.apache.logging.log4j.test">

  <Appenders>
    <Appender type="Console" name="STDOUT">
      <Layout type="PatternLayout" pattern="[%d %p %C{0}] %m%n"/>
    </Appender>
  </Appenders>

  <Loggers>
    <Logger name="org.eclipse.leshan" level="info" additivity="false" >
      <AppenderRef ref="STDOUT"/>
    </Logger>
    <Root level="warn">
      <AppenderRef ref="STDOUT"/>
    </Root>
  </Loggers>

</Configuration>


text:
#import "FBTestDaemonConnection.h"

#import <XCTest/XCTestDriverInterface-Protocol.h>
#import <XCTest/XCTestManager_DaemonConnectionInterface-Protocol.h>
#import <XCTest/XCTestManager_IDEInterface-Protocol.h>

#import <FBControlCore/FBControlCore.h>

#import <DTXConnectionServices/DTXConnection.h>
#import <DTXConnectionServices/DTXProxyChannel.h>
#import <DTXConnectionServices/DTXRemoteInvocationReceipt.h>
#import <DTXConnectionServices/DTXTransport.h>

#import <IDEiOSSupportCore/DVTAbstractiOSDevice.h>

#import <objc/runtime.h>

#import "XCTestBootstrapError.h"
#import "FBTestManagerAPIMediator.h"
#import "FBDeviceOperator.h"
#import "FBTestManagerContext.h"
#import "FBTestDaemonResult.h"

/**
 An Enumeration of Mutually-Exclusive Test Daemon States.
 */
typedef NS_ENUM(NSUInteger, FBTestDaemonConnectionState) {
  FBTestDaemonConnectionStateNotConnected = 0,
  FBTestDaemonConnectionStateConnecting = 1,
  FBTestDaemonConnectionStateReadyToExecuteTestPlan = 2,
  FBTestDaemonConnectionStateRunningTestPlan = 3,
  FBTestDaemonConnectionStateEndedTestPlan = 4,
  FBTestDaemonConnectionStateResultAvailable = 5,
};

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wprotocol"
#pragma clang diagnostic ignored "-Wincomplete-implementation"

@interface FBTestDaemonConnection () <XCTestManager_IDEInterface>

@property (nonatomic, weak, readonly) id<XCTestManager_IDEInterface, NSObject> interface;
@property (nonatomic, strong, readonly) FBTestManagerContext *context;
@property (nonatomic, strong, readonly) id<FBDeviceOperator> deviceOperator;
@property (nonatomic, strong, readonly) dispatch_queue_t queue;
@property (nonatomic, nullable, strong, readonly) id<FBControlCoreLogger> logger;

@property (atomic, assign, readwrite) FBTestDaemonConnectionState state;
@property (atomic, assign, readwrite) long long daemonProtocolVersion;
@property (atomic, nullable, strong, readwrite) FBTestDaemonResult *result;
@property (atomic, nullable, strong, readwrite) id<XCTestManager_DaemonConnectionInterface> daemonProxy;
@property (atomic, nullable, strong, readwrite) DTXConnection *daemonConnection;

@end

@implementation FBTestDaemonConnection

#pragma mark Initializers

+ (instancetype)connectionWithContext:(FBTestManagerContext *)context deviceOperator:(id<FBDeviceOperator>)deviceOperator interface:(id<XCTestManager_IDEInterface, NSObject>)interface queue:(dispatch_queue_t)queue logger:(nullable id<FBControlCoreLogger>)logger
{
  return [[self alloc] initWithWithContext:context deviceOperator:deviceOperator interface:interface queue:queue logger:logger];
}

- (instancetype)initWithWithContext:(FBTestManagerContext *)context deviceOperator:(id<FBDeviceOperator>)deviceOperator interface:(id<XCTestManager_IDEInterface, NSObject>)interface queue:(dispatch_queue_t)queue logger:(nullable id<FBControlCoreLogger>)logger
{
  self = [super init];
  if (!self) {
    return nil;
  }

  _context = context;
  _deviceOperator = deviceOperator;
  _interface = interface;
  _queue = queue;
  _logger = [logger withPrefix:[NSString stringWithFormat:@"%@:", deviceOperator.udid]];

  _state = FBTestDaemonConnectionStateNotConnected;

  return self;
}

#pragma mark NSObject

- (NSString *)description
{
  return [NSString stringWithFormat:
    @"Test Daemon Connection %@",
    [FBTestDaemonConnection stringForDaemonConnectionState:self.state]
  ];
}

#pragma mark Delegate Forwarding

- (BOOL)respondsToSelector:(SEL)selector
{
  return [super respondsToSelector:selector] || [self.interface respondsToSelector:selector];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
  return [super methodSignatureForSelector:selector] ?: [(id)self.interface methodSignatureForSelector:selector];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
  if ([self.interface respondsToSelector:invocation.selector]) {
    [invocation invokeWithTarget:self.interface];
  } else {
    [super forwardInvocation:invocation];
  }
}

#pragma mark Public

- (nullable FBTestDaemonResult *)connectWithTimeout:(NSTimeInterval)timeout
{
  if (self.result) {
    return self.result;
  }
  if (self.state != FBTestDaemonConnectionStateNotConnected) {
    XCTestBootstrapError *error = [XCTestBootstrapError describeFormat:@"State should be '%@' got '%@", [FBTestDaemonConnection stringForDaemonConnectionState:FBTestDaemonConnectionStateNotConnected], [FBTestDaemonConnection stringForDaemonConnectionState:self.state]];
    return [self concludeWithResult:[FBTestDaemonResult failedInError:error]];
  }

  [self connect];
  BOOL waitSuccess = [NSRunLoop.currentRunLoop spinRunLoopWithTimeout:timeout untilTrue:^BOOL{
    return self.state != FBTestDaemonConnectionStateConnecting;
  }];

  if (!waitSuccess) {
    XCTestBootstrapError *error = [[XCTestBootstrapError
      describeFormat:@"Timed out %f seconds waiting for daemon connection", timeout]
      code:XCTestBootstrapErrorCodeStartupTimeout];
    return [self concludeWithResult:[FBTestDaemonResult failedInError:error]];
  }
  if (self.state != FBTestDaemonConnectionStateReadyToExecuteTestPlan) {
    XCTestBootstrapError *error = [XCTestBootstrapError
      describeFormat:@"Daemon not in expected state '%@', was in state '%@'", [FBTestDaemonConnection stringForDaemonConnectionState:FBTestDaemonConnectionStateReadyToExecuteTestPlan], [FBTestDaemonConnection stringForDaemonConnectionState:self.state]];
    return [self concludeWithResult:[FBTestDaemonResult failedInError:error]];
  }
  return nil;
}

- (nullable FBTestDaemonResult *)notifyTestPlanStarted
{
  if (self.state != FBTestDaemonConnectionStateReadyToExecuteTestPlan) {
    XCTestBootstrapError *error =  [XCTestBootstrapError describeFormat:@"State should be '%@' got '%@", [FBTestDaemonConnection stringForDaemonConnectionState:FBTestDaemonConnectionStateReadyToExecuteTestPlan], [FBTestDaemonConnection stringForDaemonConnectionState:self.state]];
    return [self concludeWithResult:[FBTestDaemonResult failedInError:error]];
  }

  [self.logger log:@"Daemon Notified of start of test plan"];
  self.state = FBTestDaemonConnectionStateRunningTestPlan;
  return nil;
}

- (nullable FBTestDaemonResult *)notifyTestPlanEnded
{
  if (self.state != FBTestDaemonConnectionStateRunningTestPlan) {
    XCTestBootstrapError *error = [XCTestBootstrapError describeFormat:@"State should be '%@' got '%@", [FBTestDaemonConnection stringForDaemonConnectionState:FBTestDaemonConnectionStateRunningTestPlan], [FBTestDaemonConnection stringForDaemonConnectionState:self.state]];
    return [self concludeWithResult:[FBTestDaemonResult failedInError:error]];
  }

  [self.logger log:@"Daemon Notified of end of test plan"];
  self.state = FBTestDaemonConnectionStateEndedTestPlan;
  return nil;
}

- (nullable FBTestDaemonResult *)checkForResult
{
  return self.result;
}

- (FBTestDaemonResult *)disconnect
{
  [self.logger logFormat:@"Disconnecting Daemon from state '%@'", [FBTestDaemonConnection stringForDaemonConnectionState:self.state]];

  FBTestDaemonResult *result = nil;
  if (self.state == FBTestDaemonConnectionStateEndedTestPlan) {
    result = [self concludeWithResult:FBTestDaemonResult.success];
  } else {
    result = [self concludeWithResult:FBTestDaemonResult.clientRequestedDisconnect];
  }

  [self.daemonConnection suspend];
  [self.daemonConnection cancel];
  self.daemonConnection = nil;
  self.daemonProxy = nil;
  self.daemonProtocolVersion = 0;

  return result;
}

#pragma mark Private

- (void)connect
{
  self.state = FBTestDaemonConnectionStateConnecting;
  [self.logger log:@"Starting the daemon connection"];
  dispatch_async(self.queue, ^{
    NSError *innerError = nil;
    DTXTransport *transport = [self.deviceOperator makeTransportForTestManagerServiceWithLogger:self.logger error:&innerError];
    if (innerError || !transport) {
      XCTestBootstrapError *error = [[XCTestBootstrapError
        describe:@"Failed to created secondary test manager transport"]
        causedBy:innerError];
      [self concludeWithResult:[FBTestDaemonResult failedInError:error]];
    }
    [self createDaemonConnectionWithTransport:transport];
  });
}

- (DTXConnection *)createDaemonConnectionWithTransport:(DTXTransport *)transport
{
  DTXConnection *connection = [[objc_lookUpClass("DTXConnection") alloc] initWithTransport:transport];
  [connection registerDisconnectHandler:^{
    [self daemonDisconnectedWithState:self.state];
  }];
  [self.logger logFormat:@"Resuming the daemon connection."];
  self.daemonConnection = connection;

  [connection resume];
  DTXProxyChannel *channel = [connection
    makeProxyChannelWithRemoteInterface:@protocol(XCTestManager_DaemonConnectionInterface)
    exportedInterface:@protocol(XCTestManager_IDEInterface)];
  [channel setExportedObject:self queue:dispatch_get_main_queue()];
  self.daemonProxy = (id<XCTestManager_DaemonConnectionInterface>)channel.remoteObjectProxy;

  [self.logger logFormat:@"Whitelisting test process ID %d", self.context.testRunnerPID];
  DTXRemoteInvocationReceipt *receipt = [self.daemonProxy _IDE_initiateControlSessionForTestProcessID:@(self.context.testRunnerPID) protocolVersion:@(FBProtocolVersion)];
  [receipt handleCompletion:^(NSNumber *version, NSError *error) {
    if (error) {
      [self.logger log:@"Error in establishing daemon connection, trying legacy protocol"];
      [self setupDaemonConnectionViaLegacyProtocol];
      return;
    }
    self.daemonProtocolVersion = version.integerValue;
    [self.logger logFormat:@"Got whitelisting response and daemon protocol version %lld", self.daemonProtocolVersion];
    [self.logger log:@"Ready to execute test plan"];
    self.state = FBTestDaemonConnectionStateReadyToExecuteTestPlan;
  }];
  return connection;
}

- (FBTestDaemonResult *)daemonDisconnectedWithState:(FBTestDaemonConnectionState)state
{
  [self.logger logFormat:@"Notified that daemon disconnected from state '%@'", [FBTestDaemonConnection stringForDaemonConnectionState:state]];
  if (self.result) {
    return self.result;
  }
  if (state != FBTestDaemonConnectionStateEndedTestPlan) {
    XCTestBootstrapError *error = [XCTestBootstrapError
      describeFormat:@"Disconnected with state %@", [FBTestDaemonConnection stringForDaemonConnectionState:state]];
    return [self concludeWithResult:[FBTestDaemonResult failedInError:error]];
  }
  return [self concludeWithResult:FBTestDaemonResult.success];
}

- (DTXRemoteInvocationReceipt *)setupDaemonConnectionViaLegacyProtocol
{
  DTXRemoteInvocationReceipt *receipt = [self.daemonProxy _IDE_initiateControlSessionForTestProcessID:@(self.context.testRunnerPID)];
  [receipt handleCompletion:^(NSNumber *version, NSError *error) {
    if (error) {
      [self.logger logFormat:@"Error in whitelisting response from testmanagerd: %@ (%@), ignoring for now.", error.localizedDescription, error.localizedRecoverySuggestion];
    } else {
      self.daemonProtocolVersion = version.integerValue;
      [self.logger logFormat:@"Got legacy whitelisting response, daemon protocol version is 14"];
    }
    [self.logger log:@"Daemon Connection connected via legacy protocol"];
    self.state = FBTestDaemonConnectionStateReadyToExecuteTestPlan;
  }];
  return receipt;
}

+ (NSString *)stringForDaemonConnectionState:(FBTestDaemonConnectionState)state
{
  switch (state) {
    case FBTestDaemonConnectionStateNotConnected:
      return @"not connected";
    case FBTestDaemonConnectionStateConnecting:
      return @"connecting";
    case FBTestDaemonConnectionStateReadyToExecuteTestPlan:
      return @"ready to execute test plan";
    case FBTestDaemonConnectionStateRunningTestPlan:
      return @"executing test plan";
    case FBTestDaemonConnectionStateEndedTestPlan:
      return @"ended test plan";
    case FBTestDaemonConnectionStateResultAvailable:
      return @"result available";
    default:
      return @"unknown";
  }
}

- (FBTestDaemonResult *)concludeWithResult:(FBTestDaemonResult *)result
{
  if (self.result) {
    return self.result;
  }
  [self.logger logFormat:@"Daemon Connection Ended with result: %@", result];
  self.result = result;
  self.state = FBTestDaemonConnectionStateResultAvailable;
  return result;
}

@end

#pragma clang diagnostic pop


text:
// Code generated by Wire protocol buffer compiler, do not edit.
// Source file: google/protobuf/descriptor.proto
package com.google.protobuf;

import com.squareup.wire.EnumAdapter;
import com.squareup.wire.FieldEncoding;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoAdapter;
import com.squareup.wire.ProtoReader;
import com.squareup.wire.ProtoWriter;
import com.squareup.wire.WireEnum;
import com.squareup.wire.WireField;
import com.squareup.wire.internal.Internal;
import java.io.IOException;
import java.lang.Boolean;
import java.lang.Deprecated;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import java.util.List;
import okio.ByteString;

/**
 * ===================================================================
 * Options
 * Each of the definitions above may have "options" attached.  These are
 * just annotations which may cause code to be generated slightly differently
 * or may contain hints for code that manipulates protocol messages.
 *
 * Clients may define custom options as extensions of the *Options messages.
 * These extensions may not yet be known at parsing time, so the parser cannot
 * store the values in them.  Instead it stores them in a field in the *Options
 * message called uninterpreted_option. This field must have the same name
 * across all *Options messages. We then use this field to populate the
 * extensions when we build a descriptor, at which point all protos have been
 * parsed and so all extensions are known.
 *
 * Extension numbers for custom options may be chosen as follows:
 * * For options which will only be used within a single application or
 *   organization, or for experimental options, use field numbers 50000
 *   through 99999.  It is up to you to ensure that you do not use the
 *   same number for multiple options.
 * * For options which will be published and used publicly by multiple
 *   independent entities, e-mail protobuf-global-extension-registry@google.com
 *   to reserve extension numbers. Simply provide your project name (e.g.
 *   Objective-C plugin) and your project website (if available) -- there's no
 *   need to explain how you intend to use them. Usually you only need one
 *   extension number. You can declare multiple options with only one extension
 *   number by putting them in a sub-message. See the Custom Options section of
 *   the docs for examples:
 *   https://developers.google.com/protocol-buffers/docs/proto#options
 *   If this turns out to be popular, a web service will be set up
 *   to automatically assign option numbers.
 */
public final class FileOptions extends Message<FileOptions, FileOptions.Builder> {
  public static final ProtoAdapter<FileOptions> ADAPTER = new ProtoAdapter_FileOptions();

  private static final long serialVersionUID = 0L;

  public static final String DEFAULT_JAVA_PACKAGE = "";

  public static final String DEFAULT_JAVA_OUTER_CLASSNAME = "";

  public static final Boolean DEFAULT_JAVA_MULTIPLE_FILES = false;

  public static final Boolean DEFAULT_JAVA_GENERATE_EQUALS_AND_HASH = false;

  public static final Boolean DEFAULT_JAVA_STRING_CHECK_UTF8 = false;

  public static final OptimizeMode DEFAULT_OPTIMIZE_FOR = OptimizeMode.SPEED;

  public static final String DEFAULT_GO_PACKAGE = "";

  public static final Boolean DEFAULT_CC_GENERIC_SERVICES = false;

  public static final Boolean DEFAULT_JAVA_GENERIC_SERVICES = false;

  public static final Boolean DEFAULT_PY_GENERIC_SERVICES = false;

  public static final Boolean DEFAULT_PHP_GENERIC_SERVICES = false;

  public static final Boolean DEFAULT_DEPRECATED = false;

  public static final Boolean DEFAULT_CC_ENABLE_ARENAS = false;

  public static final String DEFAULT_OBJC_CLASS_PREFIX = "";

  public static final String DEFAULT_CSHARP_NAMESPACE = "";

  public static final String DEFAULT_SWIFT_PREFIX = "";

  public static final String DEFAULT_PHP_CLASS_PREFIX = "";

  public static final String DEFAULT_PHP_NAMESPACE = "";

  /**
   * Sets the Java package where classes generated from this .proto will be
   * placed.  By default, the proto package is used, but this is often
   * inappropriate because proto packages do not normally start with backwards
   * domain names.
   */
  @WireField(
      tag = 1,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String java_package;

  /**
   * If set, all the classes from the .proto file are wrapped in a single
   * outer class with the given name.  This applies to both Proto1
   * (equivalent to the old "--one_java_file" option) and Proto2 (where
   * a .proto always translates to a single class, but you may want to
   * explicitly choose the class name).
   */
  @WireField(
      tag = 8,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String java_outer_classname;

  /**
   * If set true, then the Java code generator will generate a separate .java
   * file for each top-level message, enum, and service defined in the .proto
   * file.  Thus, these types will *not* be nested inside the outer class
   * named by java_outer_classname.  However, the outer class will still be
   * generated to contain the file's getDescriptor() method as well as any
   * top-level extensions defined in the file.
   */
  @WireField(
      tag = 10,
      adapter = "com.squareup.wire.ProtoAdapter#BOOL"
  )
  public final Boolean java_multiple_files;

  /**
   * This option does nothing.
   */
  @WireField(
      tag = 20,
      adapter = "com.squareup.wire.ProtoAdapter#BOOL"
  )
  @Deprecated
  public final Boolean java_generate_equals_and_hash;

  /**
   * If set true, then the Java2 code generator will generate code that
   * throws an exception whenever an attempt is made to assign a non-UTF-8
   * byte sequence to a string field.
   * Message reflection will do the same.
   * However, an extension field still accepts non-UTF-8 byte sequences.
   * This option has no effect on when used with the lite runtime.
   */
  @WireField(
      tag = 27,
      adapter = "com.squareup.wire.ProtoAdapter#BOOL"
  )
  public final Boolean java_string_check_utf8;

  @WireField(
      tag = 9,
      adapter = "com.google.protobuf.FileOptions$OptimizeMode#ADAPTER"
  )
  public final OptimizeMode optimize_for;

  /**
   * Sets the Go package where structs generated from this .proto will be
   * placed. If omitted, the Go package will be derived from the following:
   *   - The basename of the package import path, if provided.
   *   - Otherwise, the package statement in the .proto file, if present.
   *   - Otherwise, the basename of the .proto file, without extension.
   */
  @WireField(
      tag = 11,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String go_package;

  /**
   * Should generic services be generated in each language?  "Generic" services
   * are not specific to any particular RPC system.  They are generated by the
   * main code generators in each language (without additional plugins).
   * Generic services were the only kind of service generation supported by
   * early versions of google.protobuf.
   *
   * Generic services are now considered deprecated in favor of using plugins
   * that generate code specific to your particular RPC system.  Therefore,
   * these default to false.  Old code which depends on generic services should
   * explicitly set them to true.
   */
  @WireField(
      tag = 16,
      adapter = "com.squareup.wire.ProtoAdapter#BOOL"
  )
  public final Boolean cc_generic_services;

  @WireField(
      tag = 17,
      adapter = "com.squareup.wire.ProtoAdapter#BOOL"
  )
  public final Boolean java_generic_services;

  @WireField(
      tag = 18,
      adapter = "com.squareup.wire.ProtoAdapter#BOOL"
  )
  public final Boolean py_generic_services;

  @WireField(
      tag = 42,
      adapter = "com.squareup.wire.ProtoAdapter#BOOL"
  )
  public final Boolean php_generic_services;

  /**
   * Is this file deprecated?
   * Depending on the target platform, this can emit Deprecated annotations
   * for everything in the file, or it will be completely ignored; in the very
   * least, this is a formalization for deprecating files.
   */
  @WireField(
      tag = 23,
      adapter = "com.squareup.wire.ProtoAdapter#BOOL"
  )
  public final Boolean deprecated;

  /**
   * Enables the use of arenas for the proto messages in this file. This applies
   * only to generated classes for C++.
   */
  @WireField(
      tag = 31,
      adapter = "com.squareup.wire.ProtoAdapter#BOOL"
  )
  public final Boolean cc_enable_arenas;

  /**
   * Sets the objective c class prefix which is prepended to all objective c
   * generated classes from this .proto. There is no default.
   */
  @WireField(
      tag = 36,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String objc_class_prefix;

  /**
   * Namespace for generated classes; defaults to the package.
   */
  @WireField(
      tag = 37,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String csharp_namespace;

  /**
   * By default Swift generators will take the proto package and CamelCase it
   * replacing '.' with underscore and use that to prefix the types/symbols
   * defined. When this options is provided, they will use this value instead
   * to prefix the types/symbols defined.
   */
  @WireField(
      tag = 39,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String swift_prefix;

  /**
   * Sets the php class prefix which is prepended to all php generated classes
   * from this .proto. Default is empty.
   */
  @WireField(
      tag = 40,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String php_class_prefix;

  /**
   * Use this option to change the namespace of php generated classes. Default
   * is empty. When this option is empty, the package name will be used for
   * determining the namespace.
   */
  @WireField(
      tag = 41,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String php_namespace;

  /**
   * The parser stores options it doesn't recognize here.
   * See the documentation for the "Options" section above.
   */
  @WireField(
      tag = 999,
      adapter = "com.google.protobuf.UninterpretedOption#ADAPTER",
      label = WireField.Label.REPEATED
  )
  public final List<UninterpretedOption> uninterpreted_option;

  public FileOptions(Builder builder, ByteString unknownFields) {
    super(ADAPTER, unknownFields);
    this.java_package = builder.java_package;
    this.java_outer_classname = builder.java_outer_classname;
    this.java_multiple_files = builder.java_multiple_files;
    this.java_generate_equals_and_hash = builder.java_generate_equals_and_hash;
    this.java_string_check_utf8 = builder.java_string_check_utf8;
    this.optimize_for = builder.optimize_for;
    this.go_package = builder.go_package;
    this.cc_generic_services = builder.cc_generic_services;
    this.java_generic_services = builder.java_generic_services;
    this.py_generic_services = builder.py_generic_services;
    this.php_generic_services = builder.php_generic_services;
    this.deprecated = builder.deprecated;
    this.cc_enable_arenas = builder.cc_enable_arenas;
    this.objc_class_prefix = builder.objc_class_prefix;
    this.csharp_namespace = builder.csharp_namespace;
    this.swift_prefix = builder.swift_prefix;
    this.php_class_prefix = builder.php_class_prefix;
    this.php_namespace = builder.php_namespace;
    this.uninterpreted_option = Internal.immutableCopyOf("uninterpreted_option", builder.uninterpreted_option);
  }

  @Override
  public Builder newBuilder() {
    Builder builder = new Builder();
    builder.java_package = java_package;
    builder.java_outer_classname = java_outer_classname;
    builder.java_multiple_files = java_multiple_files;
    builder.java_generate_equals_and_hash = java_generate_equals_and_hash;
    builder.java_string_check_utf8 = java_string_check_utf8;
    builder.optimize_for = optimize_for;
    builder.go_package = go_package;
    builder.cc_generic_services = cc_generic_services;
    builder.java_generic_services = java_generic_services;
    builder.py_generic_services = py_generic_services;
    builder.php_generic_services = php_generic_services;
    builder.deprecated = deprecated;
    builder.cc_enable_arenas = cc_enable_arenas;
    builder.objc_class_prefix = objc_class_prefix;
    builder.csharp_namespace = csharp_namespace;
    builder.swift_prefix = swift_prefix;
    builder.php_class_prefix = php_class_prefix;
    builder.php_namespace = php_namespace;
    builder.uninterpreted_option = Internal.copyOf("uninterpreted_option", uninterpreted_option);
    builder.addUnknownFields(unknownFields());
    return builder;
  }

  @Override
  public boolean equals(Object other) {
    if (other == this) return true;
    if (!(other instanceof FileOptions)) return false;
    FileOptions o = (FileOptions) other;
    return unknownFields().equals(o.unknownFields())
        && Internal.equals(java_package, o.java_package)
        && Internal.equals(java_outer_classname, o.java_outer_classname)
        && Internal.equals(java_multiple_files, o.java_multiple_files)
        && Internal.equals(java_generate_equals_and_hash, o.java_generate_equals_and_hash)
        && Internal.equals(java_string_check_utf8, o.java_string_check_utf8)
        && Internal.equals(optimize_for, o.optimize_for)
        && Internal.equals(go_package, o.go_package)
        && Internal.equals(cc_generic_services, o.cc_generic_services)
        && Internal.equals(java_generic_services, o.java_generic_services)
        && Internal.equals(py_generic_services, o.py_generic_services)
        && Internal.equals(php_generic_services, o.php_generic_services)
        && Internal.equals(deprecated, o.deprecated)
        && Internal.equals(cc_enable_arenas, o.cc_enable_arenas)
        && Internal.equals(objc_class_prefix, o.objc_class_prefix)
        && Internal.equals(csharp_namespace, o.csharp_namespace)
        && Internal.equals(swift_prefix, o.swift_prefix)
        && Internal.equals(php_class_prefix, o.php_class_prefix)
        && Internal.equals(php_namespace, o.php_namespace)
        && uninterpreted_option.equals(o.uninterpreted_option);
  }

  @Override
  public int hashCode() {
    int result = super.hashCode;
    if (result == 0) {
      result = unknownFields().hashCode();
      result = result * 37 + (java_package != null ? java_package.hashCode() : 0);
      result = result * 37 + (java_outer_classname != null ? java_outer_classname.hashCode() : 0);
      result = result * 37 + (java_multiple_files != null ? java_multiple_files.hashCode() : 0);
      result = result * 37 + (java_generate_equals_and_hash != null ? java_generate_equals_and_hash.hashCode() : 0);
      result = result * 37 + (java_string_check_utf8 != null ? java_string_check_utf8.hashCode() : 0);
      result = result * 37 + (optimize_for != null ? optimize_for.hashCode() : 0);
      result = result * 37 + (go_package != null ? go_package.hashCode() : 0);
      result = result * 37 + (cc_generic_services != null ? cc_generic_services.hashCode() : 0);
      result = result * 37 + (java_generic_services != null ? java_generic_services.hashCode() : 0);
      result = result * 37 + (py_generic_services != null ? py_generic_services.hashCode() : 0);
      result = result * 37 + (php_generic_services != null ? php_generic_services.hashCode() : 0);
      result = result * 37 + (deprecated != null ? deprecated.hashCode() : 0);
      result = result * 37 + (cc_enable_arenas != null ? cc_enable_arenas.hashCode() : 0);
      result = result * 37 + (objc_class_prefix != null ? objc_class_prefix.hashCode() : 0);
      result = result * 37 + (csharp_namespace != null ? csharp_namespace.hashCode() : 0);
      result = result * 37 + (swift_prefix != null ? swift_prefix.hashCode() : 0);
      result = result * 37 + (php_class_prefix != null ? php_class_prefix.hashCode() : 0);
      result = result * 37 + (php_namespace != null ? php_namespace.hashCode() : 0);
      result = result * 37 + uninterpreted_option.hashCode();
      super.hashCode = result;
    }
    return result;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    if (java_package != null) builder.append(", java_package=").append(java_package);
    if (java_outer_classname != null) builder.append(", java_outer_classname=").append(java_outer_classname);
    if (java_multiple_files != null) builder.append(", java_multiple_files=").append(java_multiple_files);
    if (java_generate_equals_and_hash != null) builder.append(", java_generate_equals_and_hash=").append(java_generate_equals_and_hash);
    if (java_string_check_utf8 != null) builder.append(", java_string_check_utf8=").append(java_string_check_utf8);
    if (optimize_for != null) builder.append(", optimize_for=").append(optimize_for);
    if (go_package != null) builder.append(", go_package=").append(go_package);
    if (cc_generic_services != null) builder.append(", cc_generic_services=").append(cc_generic_services);
    if (java_generic_services != null) builder.append(", java_generic_services=").append(java_generic_services);
    if (py_generic_services != null) builder.append(", py_generic_services=").append(py_generic_services);
    if (php_generic_services != null) builder.append(", php_generic_services=").append(php_generic_services);
    if (deprecated != null) builder.append(", deprecated=").append(deprecated);
    if (cc_enable_arenas != null) builder.append(", cc_enable_arenas=").append(cc_enable_arenas);
    if (objc_class_prefix != null) builder.append(", objc_class_prefix=").append(objc_class_prefix);
    if (csharp_namespace != null) builder.append(", csharp_namespace=").append(csharp_namespace);
    if (swift_prefix != null) builder.append(", swift_prefix=").append(swift_prefix);
    if (php_class_prefix != null) builder.append(", php_class_prefix=").append(php_class_prefix);
    if (php_namespace != null) builder.append(", php_namespace=").append(php_namespace);
    if (!uninterpreted_option.isEmpty()) builder.append(", uninterpreted_option=").append(uninterpreted_option);
    return builder.replace(0, 2, "FileOptions{").append('}').toString();
  }

  public static final class Builder extends Message.Builder<FileOptions, Builder> {
    public String java_package;

    public String java_outer_classname;

    public Boolean java_multiple_files;

    public Boolean java_generate_equals_and_hash;

    public Boolean java_string_check_utf8;

    public OptimizeMode optimize_for;

    public String go_package;

    public Boolean cc_generic_services;

    public Boolean java_generic_services;

    public Boolean py_generic_services;

    public Boolean php_generic_services;

    public Boolean deprecated;

    public Boolean cc_enable_arenas;

    public String objc_class_prefix;

    public String csharp_namespace;

    public String swift_prefix;

    public String php_class_prefix;

    public String php_namespace;

    public List<UninterpretedOption> uninterpreted_option;

    public Builder() {
      uninterpreted_option = Internal.newMutableList();
    }

    /**
     * Sets the Java package where classes generated from this .proto will be
     * placed.  By default, the proto package is used, but this is often
     * inappropriate because proto packages do not normally start with backwards
     * domain names.
     */
    public Builder java_package(String java_package) {
      this.java_package = java_package;
      return this;
    }

    /**
     * If set, all the classes from the .proto file are wrapped in a single
     * outer class with the given name.  This applies to both Proto1
     * (equivalent to the old "--one_java_file" option) and Proto2 (where
     * a .proto always translates to a single class, but you may want to
     * explicitly choose the class name).
     */
    public Builder java_outer_classname(String java_outer_classname) {
      this.java_outer_classname = java_outer_classname;
      return this;
    }

    /**
     * If set true, then the Java code generator will generate a separate .java
     * file for each top-level message, enum, and service defined in the .proto
     * file.  Thus, these types will *not* be nested inside the outer class
     * named by java_outer_classname.  However, the outer class will still be
     * generated to contain the file's getDescriptor() method as well as any
     * top-level extensions defined in the file.
     */
    public Builder java_multiple_files(Boolean java_multiple_files) {
      this.java_multiple_files = java_multiple_files;
      return this;
    }

    /**
     * This option does nothing.
     */
    @Deprecated
    public Builder java_generate_equals_and_hash(Boolean java_generate_equals_and_hash) {
      this.java_generate_equals_and_hash = java_generate_equals_and_hash;
      return this;
    }

    /**
     * If set true, then the Java2 code generator will generate code that
     * throws an exception whenever an attempt is made to assign a non-UTF-8
     * byte sequence to a string field.
     * Message reflection will do the same.
     * However, an extension field still accepts non-UTF-8 byte sequences.
     * This option has no effect on when used with the lite runtime.
     */
    public Builder java_string_check_utf8(Boolean java_string_check_utf8) {
      this.java_string_check_utf8 = java_string_check_utf8;
      return this;
    }

    public Builder optimize_for(OptimizeMode optimize_for) {
      this.optimize_for = optimize_for;
      return this;
    }

    /**
     * Sets the Go package where structs generated from this .proto will be
     * placed. If omitted, the Go package will be derived from the following:
     *   - The basename of the package import path, if provided.
     *   - Otherwise, the package statement in the .proto file, if present.
     *   - Otherwise, the basename of the .proto file, without extension.
     */
    public Builder go_package(String go_package) {
      this.go_package = go_package;
      return this;
    }

    /**
     * Should generic services be generated in each language?  "Generic" services
     * are not specific to any particular RPC system.  They are generated by the
     * main code generators in each language (without additional plugins).
     * Generic services were the only kind of service generation supported by
     * early versions of google.protobuf.
     *
     * Generic services are now considered deprecated in favor of using plugins
     * that generate code specific to your particular RPC system.  Therefore,
     * these default to false.  Old code which depends on generic services should
     * explicitly set them to true.
     */
    public Builder cc_generic_services(Boolean cc_generic_services) {
      this.cc_generic_services = cc_generic_services;
      return this;
    }

    public Builder java_generic_services(Boolean java_generic_services) {
      this.java_generic_services = java_generic_services;
      return this;
    }

    public Builder py_generic_services(Boolean py_generic_services) {
      this.py_generic_services = py_generic_services;
      return this;
    }

    public Builder php_generic_services(Boolean php_generic_services) {
      this.php_generic_services = php_generic_services;
      return this;
    }

    /**
     * Is this file deprecated?
     * Depending on the target platform, this can emit Deprecated annotations
     * for everything in the file, or it will be completely ignored; in the very
     * least, this is a formalization for deprecating files.
     */
    public Builder deprecated(Boolean deprecated) {
      this.deprecated = deprecated;
      return this;
    }

    /**
     * Enables the use of arenas for the proto messages in this file. This applies
     * only to generated classes for C++.
     */
    public Builder cc_enable_arenas(Boolean cc_enable_arenas) {
      this.cc_enable_arenas = cc_enable_arenas;
      return this;
    }

    /**
     * Sets the objective c class prefix which is prepended to all objective c
     * generated classes from this .proto. There is no default.
     */
    public Builder objc_class_prefix(String objc_class_prefix) {
      this.objc_class_prefix = objc_class_prefix;
      return this;
    }

    /**
     * Namespace for generated classes; defaults to the package.
     */
    public Builder csharp_namespace(String csharp_namespace) {
      this.csharp_namespace = csharp_namespace;
      return this;
    }

    /**
     * By default Swift generators will take the proto package and CamelCase it
     * replacing '.' with underscore and use that to prefix the types/symbols
     * defined. When this options is provided, they will use this value instead
     * to prefix the types/symbols defined.
     */
    public Builder swift_prefix(String swift_prefix) {
      this.swift_prefix = swift_prefix;
      return this;
    }

    /**
     * Sets the php class prefix which is prepended to all php generated classes
     * from this .proto. Default is empty.
     */
    public Builder php_class_prefix(String php_class_prefix) {
      this.php_class_prefix = php_class_prefix;
      return this;
    }

    /**
     * Use this option to change the namespace of php generated classes. Default
     * is empty. When this option is empty, the package name will be used for
     * determining the namespace.
     */
    public Builder php_namespace(String php_namespace) {
      this.php_namespace = php_namespace;
      return this;
    }

    /**
     * The parser stores options it doesn't recognize here.
     * See the documentation for the "Options" section above.
     */
    public Builder uninterpreted_option(List<UninterpretedOption> uninterpreted_option) {
      Internal.checkElementsNotNull(uninterpreted_option);
      this.uninterpreted_option = uninterpreted_option;
      return this;
    }

    @Override
    public FileOptions build() {
      return new FileOptions(this, super.buildUnknownFields());
    }
  }

  /**
   * Generated classes can be optimized for speed or code size.
   */
  public enum OptimizeMode implements WireEnum {
    /**
     * Generate complete code for parsing, serialization,
     */
    SPEED(1),

    /**
     * etc.
     * Use ReflectionOps to implement these methods.
     */
    CODE_SIZE(2),

    /**
     * Generate code using MessageLite and the lite runtime.
     */
    LITE_RUNTIME(3);

    public static final ProtoAdapter<OptimizeMode> ADAPTER = new ProtoAdapter_OptimizeMode();

    private final int value;

    OptimizeMode(int value) {
      this.value = value;
    }

    /**
     * Return the constant for {@code value} or null.
     */
    public static OptimizeMode fromValue(int value) {
      switch (value) {
        case 1: return SPEED;
        case 2: return CODE_SIZE;
        case 3: return LITE_RUNTIME;
        default: return null;
      }
    }

    @Override
    public int getValue() {
      return value;
    }

    private static final class ProtoAdapter_OptimizeMode extends EnumAdapter<OptimizeMode> {
      ProtoAdapter_OptimizeMode() {
        super(OptimizeMode.class);
      }

      @Override
      protected OptimizeMode fromValue(int value) {
        return OptimizeMode.fromValue(value);
      }
    }
  }

  private static final class ProtoAdapter_FileOptions extends ProtoAdapter<FileOptions> {
    public ProtoAdapter_FileOptions() {
      super(FieldEncoding.LENGTH_DELIMITED, FileOptions.class);
    }

    @Override
    public int encodedSize(FileOptions value) {
      return ProtoAdapter.STRING.encodedSizeWithTag(1, value.java_package)
          + ProtoAdapter.STRING.encodedSizeWithTag(8, value.java_outer_classname)
          + ProtoAdapter.BOOL.encodedSizeWithTag(10, value.java_multiple_files)
          + ProtoAdapter.BOOL.encodedSizeWithTag(20, value.java_generate_equals_and_hash)
          + ProtoAdapter.BOOL.encodedSizeWithTag(27, value.java_string_check_utf8)
          + OptimizeMode.ADAPTER.encodedSizeWithTag(9, value.optimize_for)
          + ProtoAdapter.STRING.encodedSizeWithTag(11, value.go_package)
          + ProtoAdapter.BOOL.encodedSizeWithTag(16, value.cc_generic_services)
          + ProtoAdapter.BOOL.encodedSizeWithTag(17, value.java_generic_services)
          + ProtoAdapter.BOOL.encodedSizeWithTag(18, value.py_generic_services)
          + ProtoAdapter.BOOL.encodedSizeWithTag(42, value.php_generic_services)
          + ProtoAdapter.BOOL.encodedSizeWithTag(23, value.deprecated)
          + ProtoAdapter.BOOL.encodedSizeWithTag(31, value.cc_enable_arenas)
          + ProtoAdapter.STRING.encodedSizeWithTag(36, value.objc_class_prefix)
          + ProtoAdapter.STRING.encodedSizeWithTag(37, value.csharp_namespace)
          + ProtoAdapter.STRING.encodedSizeWithTag(39, value.swift_prefix)
          + ProtoAdapter.STRING.encodedSizeWithTag(40, value.php_class_prefix)
          + ProtoAdapter.STRING.encodedSizeWithTag(41, value.php_namespace)
          + UninterpretedOption.ADAPTER.asRepeated().encodedSizeWithTag(999, value.uninterpreted_option)
          + value.unknownFields().size();
    }

    @Override
    public void encode(ProtoWriter writer, FileOptions value) throws IOException {
      ProtoAdapter.STRING.encodeWithTag(writer, 1, value.java_package);
      ProtoAdapter.STRING.encodeWithTag(writer, 8, value.java_outer_classname);
      ProtoAdapter.BOOL.encodeWithTag(writer, 10, value.java_multiple_files);
      ProtoAdapter.BOOL.encodeWithTag(writer, 20, value.java_generate_equals_and_hash);
      ProtoAdapter.BOOL.encodeWithTag(writer, 27, value.java_string_check_utf8);
      OptimizeMode.ADAPTER.encodeWithTag(writer, 9, value.optimize_for);
      ProtoAdapter.STRING.encodeWithTag(writer, 11, value.go_package);
      ProtoAdapter.BOOL.encodeWithTag(writer, 16, value.cc_generic_services);
      ProtoAdapter.BOOL.encodeWithTag(writer, 17, value.java_generic_services);
      ProtoAdapter.BOOL.encodeWithTag(writer, 18, value.py_generic_services);
      ProtoAdapter.BOOL.encodeWithTag(writer, 42, value.php_generic_services);
      ProtoAdapter.BOOL.encodeWithTag(writer, 23, value.deprecated);
      ProtoAdapter.BOOL.encodeWithTag(writer, 31, value.cc_enable_arenas);
      ProtoAdapter.STRING.encodeWithTag(writer, 36, value.objc_class_prefix);
      ProtoAdapter.STRING.encodeWithTag(writer, 37, value.csharp_namespace);
      ProtoAdapter.STRING.encodeWithTag(writer, 39, value.swift_prefix);
      ProtoAdapter.STRING.encodeWithTag(writer, 40, value.php_class_prefix);
      ProtoAdapter.STRING.encodeWithTag(writer, 41, value.php_namespace);
      UninterpretedOption.ADAPTER.asRepeated().encodeWithTag(writer, 999, value.uninterpreted_option);
      writer.writeBytes(value.unknownFields());
    }

    @Override
    public FileOptions decode(ProtoReader reader) throws IOException {
      Builder builder = new Builder();
      long token = reader.beginMessage();
      for (int tag; (tag = reader.nextTag()) != -1;) {
        switch (tag) {
          case 1: builder.java_package(ProtoAdapter.STRING.decode(reader)); break;
          case 8: builder.java_outer_classname(ProtoAdapter.STRING.decode(reader)); break;
          case 9: {
            try {
              builder.optimize_for(OptimizeMode.ADAPTER.decode(reader));
            } catch (ProtoAdapter.EnumConstantNotFoundException e) {
              builder.addUnknownField(tag, FieldEncoding.VARINT, (long) e.value);
            }
            break;
          }
          case 10: builder.java_multiple_files(ProtoAdapter.BOOL.decode(reader)); break;
          case 11: builder.go_package(ProtoAdapter.STRING.decode(reader)); break;
          case 16: builder.cc_generic_services(ProtoAdapter.BOOL.decode(reader)); break;
          case 17: builder.java_generic_services(ProtoAdapter.BOOL.decode(reader)); break;
          case 18: builder.py_generic_services(ProtoAdapter.BOOL.decode(reader)); break;
          case 20: builder.java_generate_equals_and_hash(ProtoAdapter.BOOL.decode(reader)); break;
          case 23: builder.deprecated(ProtoAdapter.BOOL.decode(reader)); break;
          case 27: builder.java_string_check_utf8(ProtoAdapter.BOOL.decode(reader)); break;
          case 31: builder.cc_enable_arenas(ProtoAdapter.BOOL.decode(reader)); break;
          case 36: builder.objc_class_prefix(ProtoAdapter.STRING.decode(reader)); break;
          case 37: builder.csharp_namespace(ProtoAdapter.STRING.decode(reader)); break;
          case 39: builder.swift_prefix(ProtoAdapter.STRING.decode(reader)); break;
          case 40: builder.php_class_prefix(ProtoAdapter.STRING.decode(reader)); break;
          case 41: builder.php_namespace(ProtoAdapter.STRING.decode(reader)); break;
          case 42: builder.php_generic_services(ProtoAdapter.BOOL.decode(reader)); break;
          case 999: builder.uninterpreted_option.add(UninterpretedOption.ADAPTER.decode(reader)); break;
          default: {
            FieldEncoding fieldEncoding = reader.peekFieldEncoding();
            Object value = fieldEncoding.rawProtoAdapter().decode(reader);
            builder.addUnknownField(tag, fieldEncoding, value);
          }
        }
      }
      reader.endMessage(token);
      return builder.build();
    }

    @Override
    public FileOptions redact(FileOptions value) {
      Builder builder = value.newBuilder();
      Internal.redactElements(builder.uninterpreted_option, UninterpretedOption.ADAPTER);
      builder.clearUnknownFields();
      return builder.build();
    }
  }
}


text:
using Audit.Core;
using System;
using System.Configuration;
using System.Runtime.Remoting.Messaging;
using System.ServiceModel.Configuration;

namespace Audit.WCF
{
    /// <summary>
    /// AuditBehavior element for Audit.Wcf behavior configuration.
    /// </summary>
    public class AuditBehavior : BehaviorExtensionElement
    {
        private const string WcfContextScopeKey = "AuditScope";

        /// <summary>
        /// Gets the current audit scope for the running thread.
        /// Get this property from an audited WCF method to get the current audit scope.
        /// </summary>
        public static IAuditScope CurrentAuditScope
        {
            get
            {
                return CallContext.LogicalGetData(WcfContextScopeKey) as IAuditScope;
            }
            internal set
            {
                CallContext.LogicalSetData(WcfContextScopeKey, value);
            }
        }

        /// <summary>
        /// Gets or sets the event type.
        /// Can contain the following placeholders:
        /// - {contract}: Replaced with the contract name (service interface name)
        /// - {operation}: Replaces with the operation name (service method name)
        /// </summary>
        [ConfigurationProperty("eventType", IsRequired = false)]
        public virtual string EventType
        {
            get
            {
                return this["eventType"] as string;
            }
            set
            {
                this["eventType"] = value;
            }
        }

        /// <summary>
        /// Gets the type of behavior.
        /// </summary>
        /// <value>The type of the behavior.</value>
        public override Type BehaviorType
        {
            get
            {
                return typeof(AuditBehaviorAttribute);
            }
        }

        /// <summary>
        /// Creates a behavior extension based on the current configuration settings.
        /// </summary>
        /// <returns>The behavior extension.</returns>
        protected override object CreateBehavior()
        {
            return new AuditBehaviorAttribute(EventType);
        }
    }
}


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace core\event;
defined('MOODLE_INTERNAL') || die();

/**
 * Class course_module_updated
 *
 * Class for event to be triggered when a course module is updated.
 *
 * @package    core
 * @since      Moodle 2.6
 * @copyright  2013 Ankit Agarwal
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later.
 */
class course_module_updated extends base {

    /**
     * Set basic properties for the event.
     */
    protected function init() {
        $this->data['objecttable'] = 'course_modules';
        $this->data['crud'] = 'u';
        $this->data['level'] = self::LEVEL_TEACHING;
    }

    /**
     * Returns localised general event name.
     *
     * @return string
     */
    public static function get_name() {
        return get_string('eventcoursemoduleupdated', 'core');
    }

    /**
     * Returns non-localised event description with id's for admin use only.
     *
     * @return string
     */
    public function get_description() {
        return 'The ' . $this->other['modulename'] . ' module with instance id ' . $this->other['instanceid'] .
                ' was updated by user with id ' . $this->userid;
    }

    /**
     * Returns relevant URL.
     * @return \moodle_url
     */
    public function get_url() {
        return new \moodle_url('/mod/' . $this->other['modulename'] . '/view.php', array('id' => $this->objectid));
    }

    /**
     * Legacy event name.
     *
     * @return string legacy event name
     */
    public static function get_legacy_eventname() {
        return 'mod_updated';
    }

    /**
     * Legacy event data.
     *
     * @return \stdClass
     */
    protected function get_legacy_eventdata() {
        $eventdata = new \stdClass();
        $eventdata->modulename = $this->other['modulename'];
        $eventdata->name       = $this->other['name'];
        $eventdata->cmid       = $this->objectid;
        $eventdata->courseid   = $this->courseid;
        $eventdata->userid     = $this->userid;
        return $eventdata;
    }

    /**
     * replace add_to_log() statement.
     *
     * @return array of parameters to be passed to legacy add_to_log() function.
     */
    protected function get_legacy_logdata() {
        return array ($this->courseid, "course", "update mod", "../mod/" . $this->other['modulename'] . "/view.php?id=" .
                $this->objectid, $this->other['modulename'] . " " . $this->other['instanceid']);
    }

    /**
     * custom validations
     *
     * Throw \coding_exception notice in case of any problems.
     */
    protected function validate_data() {
        if (!isset($this->other['modulename'])) {
            throw new \coding_exception("Field other['modulename'] cannot be empty");
        }
        if (!isset($this->other['instanceid'])) {
            throw new \coding_exception("Field other['instanceid'] cannot be empty");
        }
        if (!isset($this->other['name'])) {
            throw new \coding_exception("Field other['name'] cannot be empty");
        }
    }

    /**
     * Set data to create new event from course module.
     *
     * @param \cm_info|\stdClass $cm course module instance, as returned by {@link get_coursemodule_from_id}
     *                     or {@link get_coursemodule_from_instance}.
     * @param \context_module $modcontext module context instance
     * @return \core\event\base returns instance of new event
     * @since Moodle 2.6.3
     */
    public static final function create_from_cm($cm, $modcontext = null) {
        // If not set, get the module context.
        if (empty($modcontext)) {
            $modcontext = \context_module::instance($cm->id);
        }

        // Create event object for course module update action.
        $event = static::create(array(
            'context'  => $modcontext,
            'objectid' => $cm->id,
            'other'    => array(
                'modulename' => $cm->modname,
                'instanceid' => $cm->instance,
                'name'       => $cm->name,
            )
        ));
        return $event;
    }
}


text: module.exports = require("npm:is-array@1.0.1/index");


text:
package examples

object RefSpecExamples extends StyleTraitExamples {

  val name: String = "RefSpec"

  val description: String = """RefSpec allows you to define tests as methods, which saves one function literal per test compared to style classes that represent tests as functions. Fewer function literals translates into faster compile times and fewer generated class files, which can help minimize build times. As a result, using Spec can be a good choice in large projects where build times are a concern as well as when generating large numbers of tests programatically via static code generators."""

  val exampleUsage: String =
    """import org.scalatest._
      |import refspec._
      |
      |class SetSpec extends RefSpec {
      |  override def withFixture(test: NoArgTest) = { // Define a shared fixture
      |    // Shared setup (run at beginning of each test)
      |    try test()
      |    finally {
      |      // Shared cleanup (run at end of each test)
      |    }
      |  }
      |
      |  // Describe a scope for a subject, in this case: "A Set"
      |  object `A Set` { // All tests within these curly braces are about "A Set"
      |
      |    // Can describe nested scopes that "narrow" its outer scopes
      |    object `(when empty)` { // All tests within these curly braces are about "A Set (when empty)"
      |
      |      def `should have size 0` = {    // Here, 'it' refers to "A Set (when empty)". The full name
      |        assert(Set.empty.size == 0) // of this test is: "A Set (when empty) should have size 0"
      |      }
      |      def `should produce NoSuchElementException when head is invoked` = { // Define another test
      |        intercept[NoSuchElementException] {
      |          Set.empty.head
      |        }
      |      }
      |      @Ignore def `should should be empty` = { // To ignore a test, change 'it' to 'ignore'...
      |        assert(Set.empty.isEmpty)
      |      }
      |    }
      |
      |    // Describe a second nested scope that narrows "A Set" in a different way
      |    object `(when non-empty)` { // All tests within these curly braces are about "A Set (when non-empty)"
      |
      |      def `should have the correct size` = { // Here, 'it' refers to "A Set (when non-empty)". This test's full
      |        assert(Set(1, 2, 3).size == 3)     // name is: "A Set (when non-empty) should have the correct size"
      |      }
      |      // Define a pending test by using { pending } for the body
      |      def `return a contained value when head is invoked` = { pending }
      |      import org.scalatest.tags.Slow
      |      @Slow def `should be non-empty` = { // Tag a test by placing a tag object after the test name
      |        assert(Set(1, 2, 3).nonEmpty)
      |      }
      |    }
      |  }
      |}
      |
      |@DoNotDiscover // Disable discovery of a test class
      |class InvisibleSpec extends RefSpec { /*code omitted*/ }
      |
      |@Ignore // Ignore all tests in a test class
      |class IgnoredSpec extends RefSpec { /*code omitted*/ }
      |
      |import tags.Slow
      |@Slow // Mark all tests in a test class with a tag
      |class SlowSpec extends RefSpec { /*code omitted*/ }
      |""".stripMargin

  val play2Example: String =
    """import org.scalatest._
      |import play.api.test._
      |import play.api.test.Helpers._
      |
      |class ExampleSpec extends Spec with Matchers {
      |  object `Application should` {
      |    def `send 404 on a bad request` {
      |      running(FakeApplication()) {
      |        route(FakeRequest(GET, "/boum")) shouldBe None
      |      }
      |    }
      |    def `render the index page` {
      |      running(FakeApplication()) {
      |        val home = route(FakeRequest(GET, "/")).get
      |        status(home) shouldBe OK
      |        contentType(home) shouldBe Some("text/html")
      |        contentAsString(home) should include ("ScalaTest")
      |      }
      |    }
      |  }
      |}""".stripMargin

  val doNotDiscover: String =
    """import org.scalatest._
      |@DoNotDiscover
      |class SetSpec extends Spec { /*code omitted*/ }
    """.stripMargin

  val ignoreTest: String =
    """import org.scalatest._
      |class SetSpec extends Spec {
      |  @Ignore def `should have size 0` { /*code omitted*/ }
      |}""".stripMargin

  val pendingTest: String =
    """import org.scalatest._
      |class SetSpec extends Spec {
      |  def `should have size 0` { pending }
      |}""".stripMargin

  val taggingTest: String =
    """import org.scalatest._
      |import tags.Retryable
      |class SetSpec extends Spec {
      |  @Retryable def `should have size 0` { /*code omitted*/ }
      |}""".stripMargin

  val infoTest: String =
    """import org.scalatest._
      |class SetSpec extends Spec {
      |  def `should have size 0` {
      |    info("Some information.")
      |    /*code omitted*/
      |  }
      |}""".stripMargin

  val fixtureNoArgTest: String =
    """import org.scalatest._
      |class SetSpec extends Spec {
      |  def setup() { /*code omitted*/ }
      |  def cleanup() { /*code omitted*/ }
      |  override protected def withFixture(test: NoArgTest) = {
      |    setup()
      |    try test() finally cleanup()
      |  }
      |}""".stripMargin

  val fixtureOneArgTest: String =
    """import org.scalatest._
      |class SetSpec extends fixture.Spec {
      |  def setup() { /*code omitted*/ }
      |  def cleanup() { /*code omitted*/ }
      |  type FixtureParam = String
      |  override protected def withFixture(test: OneArgTest) = {
      |    setup()
      |    try test("this is a fixture param") finally cleanup()
      |  }
      |}""".stripMargin

  val seleniumExample: String =
    """import org.scalatest._
      |import selenium._
      |class BlogSpec extends Spec with WebBrowser with HtmlUnit {
      |  val host = "http://localhost:9000/"
      |  def `The blog app home page should have the correct title` {
      |    go to (host + "index.html")
      |    pageTitle should be ("Awesome Blog")
      |  }
      |}""".stripMargin
}


text:
package com.musingscafe.tastybytes.graph;

/**
 * Created by ayadav on 12/29/16.
 */
public class IntegerGraphWithAdjListDriver {
    public static void main(String[] args) {
        minimumDistance();
    }

    private static void minimumDistance() {
        IntegerGraphWithAdjList graphWithLongerPathFirstInList = getGraphWithLongerPathFirstInList();
        IntegerGraphWithAdjList graphWithShorterPathFirstInList = getGraphWithShorterPathFirstInList();

        System.out.println();
        System.out.println(graphWithLongerPathFirstInList.minimumDistance(0, 2));

        System.out.println();
        System.out.println(graphWithShorterPathFirstInList.minimumDistance(0, 2));

        System.out.println();
        graphWithLongerPathFirstInList.dfs(0);
    }

    private static void simpleBFS() {
        whenLongerPathComesFirstInAdjList();
        System.out.println();
        whenShorterPathComesFirstInAdjList();

        /*
        Output:

        0 -> 3 1
        1 -> 2
        2 ->
        3 -> 4
        4 -> 2

        Print bfs, whenLongerPathComesFirstInAdjList
        0 3 1 4 2
        0 -> 1 3
        1 -> 2
        2 ->
        3 -> 4
        4 -> 2

        Print bfs, whenShorterPathComesFirstInAdjList
        0 1 3 2

        Conclusion: BFS is use to find shortest path in an unweighted graph but it in itself does not give shortest path.
        There are plenty of references on internet which says "BFS gives shortest path".
         */
    }

    private static void whenShorterPathComesFirstInAdjList() {
        IntegerGraphWithAdjList graph = getGraphWithShorterPathFirstInList();

        graph.print();

        System.out.println();
        System.out.println("Print bfs, whenShorterPathComesFirstInAdjList");
        graph.bfs(0);
    }

    private static IntegerGraphWithAdjList getGraphWithShorterPathFirstInList() {
        IntegerGraphWithAdjList graph = new IntegerGraphWithAdjList();
        graph.addEdge(0, 3);
        graph.addEdge(3, 4);
        graph.addEdge(4, 2);
        graph.addEdge(0, 1);
        graph.addEdge(1, 2);
        return graph;
    }

    private static void whenLongerPathComesFirstInAdjList() {
        IntegerGraphWithAdjList graph = getGraphWithLongerPathFirstInList();

        graph.print();

        System.out.println();
        System.out.println("Print bfs, whenLongerPathComesFirstInAdjList");
        graph.bfs(0);
    }

    private static IntegerGraphWithAdjList getGraphWithLongerPathFirstInList() {
        IntegerGraphWithAdjList graph = new IntegerGraphWithAdjList();
        graph.addEdge(0, 1);
        graph.addEdge(1, 2);
        graph.addEdge(0, 3);
        graph.addEdge(3, 4);
        graph.addEdge(4, 2);
        return graph;
    }
}


text:
const settings = require('../../../settings.js');

// validates authentication based on the server's defined authentication settings
function validateAuth (req, res) {
    if(!settings.authType
        || (settings.authType == "basic" && req.body.password == settings.basicAuthPassword)){
        res.parcel.setStatus(200);
    }else{
        res.parcel.setStatus(401);
    }
    res.parcel.deliver();
}

module.exports = {
    validateAuth: validateAuth
};


text:
public class ListNode {
	int val;
	ListNode next;

	ListNode(int x) {
		val = x;
		next = null;
	}

	public String toString() {
		if (this.next != null)
			return "" + this.val + "" + this.next.toString();
		return "" + this.val;
	}
}