text:
#include "config.h"
#include "bindings/v8/ScriptDebugServer.h"

#include "DebuggerScriptSource.h"
#include "V8JavaScriptCallFrame.h"
#include "bindings/v8/ScopedPersistent.h"
#include "bindings/v8/ScriptObject.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8ScriptRunner.h"
#include "core/inspector/JavaScriptCallFrame.h"
#include "core/inspector/ScriptDebugListener.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
#include "wtf/dtoa/utils.h"

namespace WebCore {

namespace {

class ClientDataImpl : public v8::Debug::ClientData {
public:
    ClientDataImpl(PassOwnPtr<ScriptDebugServer::Task> task) : m_task(task) { }
    virtual ~ClientDataImpl() { }
    ScriptDebugServer::Task* task() const { return m_task.get(); }
private:
    OwnPtr<ScriptDebugServer::Task> m_task;
};

}

v8::Local<v8::Value> ScriptDebugServer::callDebuggerMethod(const char* functionName, int argc, v8::Handle<v8::Value> argv[])
{
    v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(m_debuggerScript.get()->Get(v8::String::NewSymbol(functionName)));
    ASSERT(v8::Context::InContext());
    return V8ScriptRunner::callInternalFunction(function, m_debuggerScript.get(), argc, argv, m_isolate);
}

class ScriptDebugServer::ScriptPreprocessor {
    WTF_MAKE_NONCOPYABLE(ScriptPreprocessor);
public:
    ScriptPreprocessor(const String& preprocessorScript, v8::Isolate* isolate)
        : m_isolate(isolate)
    {
        v8::HandleScope scope(m_isolate);

        v8::Local<v8::Context> context = v8::Context::New(m_isolate);
        if (context.IsEmpty())
            return;
        v8::Context::Scope contextScope(context);

        String wrappedScript = "(" + preprocessorScript + ")";
        v8::Handle<v8::String> preprocessor = v8::String::New(wrappedScript.utf8().data(), wrappedScript.utf8().length());

        v8::Local<v8::Value> preprocessorFunction = V8ScriptRunner::compileAndRunInternalScript(preprocessor, m_isolate);
        if (preprocessorFunction.IsEmpty() || !preprocessorFunction->IsFunction())
            return;

        m_utilityContext.set(isolate, context);
        m_preprocessorFunction.set(isolate, v8::Handle<v8::Function>::Cast(preprocessorFunction));
    }

    String preprocessSourceCode(const String& sourceCode, const String& sourceName)
    {
        v8::HandleScope handleScope(m_isolate);

        if (m_preprocessorFunction.isEmpty())
            return sourceCode;

        v8::Local<v8::Context> context = v8::Local<v8::Context>::New(m_utilityContext.get());
        v8::Context::Scope contextScope(context);

        v8::Handle<v8::String> sourceCodeString = v8::String::New(sourceCode.utf8().data(), sourceCode.utf8().length());

        v8::Handle<v8::String> sourceNameString = v8::String::New(sourceName.utf8().data(), sourceName.utf8().length());
        v8::Handle<v8::Value> argv[] = { sourceCodeString, sourceNameString };
        v8::Handle<v8::Value> resultValue = V8ScriptRunner::callInternalFunction(m_preprocessorFunction.newLocal(m_isolate), context->Global(), WTF_ARRAY_LENGTH(argv), argv, m_isolate);

        if (!resultValue.IsEmpty() && resultValue->IsString()) {
            v8::String::Utf8Value utf8Value(resultValue);
            return String::fromUTF8(*utf8Value, utf8Value.length());
        }
        return sourceCode;
    }

    ~ScriptPreprocessor()
    {
    }

private:
    ScopedPersistent<v8::Context> m_utilityContext;
    String m_preprocessorBody;
    ScopedPersistent<v8::Function> m_preprocessorFunction;
    v8::Isolate* m_isolate;
};

ScriptDebugServer::ScriptDebugServer(v8::Isolate* isolate)
    : m_pauseOnExceptionsState(DontPauseOnExceptions)
    , m_breakpointsActivated(true)
    , m_runningNestedMessageLoop(false)
    , m_isolate(isolate)
{
}

ScriptDebugServer::~ScriptDebugServer()
{
}

String ScriptDebugServer::setBreakpoint(const String& sourceID, const ScriptBreakpoint& scriptBreakpoint, int* actualLineNumber, int* actualColumnNumber)
{
    v8::HandleScope scope;
    v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
    v8::Context::Scope contextScope(debuggerContext);

    v8::Local<v8::Object> args = v8::Object::New();
    args->Set(v8::String::NewSymbol("sourceID"), v8String(sourceID, debuggerContext->GetIsolate()));
    args->Set(v8::String::NewSymbol("lineNumber"), v8::Integer::New(scriptBreakpoint.lineNumber, debuggerContext->GetIsolate()));
    args->Set(v8::String::NewSymbol("columnNumber"), v8::Integer::New(scriptBreakpoint.columnNumber, debuggerContext->GetIsolate()));
    args->Set(v8::String::NewSymbol("condition"), v8String(scriptBreakpoint.condition, debuggerContext->GetIsolate()));

    v8::Handle<v8::Function> setBreakpointFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8::String::NewSymbol("setBreakpoint")));
    v8::Handle<v8::Value> breakpointId = v8::Debug::Call(setBreakpointFunction, args);
    if (!breakpointId->IsString())
        return "";
    *actualLineNumber = args->Get(v8::String::NewSymbol("lineNumber"))->Int32Value();
    *actualColumnNumber = args->Get(v8::String::NewSymbol("columnNumber"))->Int32Value();
    return toWebCoreString(breakpointId->ToString());
}

void ScriptDebugServer::removeBreakpoint(const String& breakpointId)
{
    v8::HandleScope scope(m_isolate);
    v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
    v8::Context::Scope contextScope(debuggerContext);

    v8::Local<v8::Object> args = v8::Object::New();
    args->Set(v8::String::NewSymbol("breakpointId"), v8String(breakpointId, debuggerContext->GetIsolate()));

    v8::Handle<v8::Function> removeBreakpointFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8::String::NewSymbol("removeBreakpoint")));
    v8::Debug::Call(removeBreakpointFunction, args);
}

void ScriptDebugServer::clearBreakpoints()
{
    ensureDebuggerScriptCompiled();
    v8::HandleScope scope(m_isolate);
    v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
    v8::Context::Scope contextScope(debuggerContext);

    v8::Handle<v8::Function> clearBreakpoints = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8::String::NewSymbol("clearBreakpoints")));
    v8::Debug::Call(clearBreakpoints);
}

void ScriptDebugServer::setBreakpointsActivated(bool activated)
{
    ensureDebuggerScriptCompiled();
    v8::HandleScope scope(m_isolate);
    v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
    v8::Context::Scope contextScope(debuggerContext);

    v8::Local<v8::Object> args = v8::Object::New();
    args->Set(v8::String::NewSymbol("enabled"), v8::Boolean::New(activated));
    v8::Handle<v8::Function> setBreakpointsActivated = v8::Local<v8::Function>::Cast(m_debuggerScript.newLocal(m_isolate)->Get(v8::String::NewSymbol("setBreakpointsActivated")));
    v8::Debug::Call(setBreakpointsActivated, args);

    m_breakpointsActivated = activated;
}

ScriptDebugServer::PauseOnExceptionsState ScriptDebugServer::pauseOnExceptionsState()
{
    ensureDebuggerScriptCompiled();
    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(v8::Debug::GetDebugContext());

    v8::Handle<v8::Value> argv[] = { v8Undefined() };
    v8::Handle<v8::Value> result = callDebuggerMethod("pauseOnExceptionsState", 0, argv);
    return static_cast<ScriptDebugServer::PauseOnExceptionsState>(result->Int32Value());
}

void ScriptDebugServer::setPauseOnExceptionsState(PauseOnExceptionsState pauseOnExceptionsState)
{
    ensureDebuggerScriptCompiled();
    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(v8::Debug::GetDebugContext());

    v8::Handle<v8::Value> argv[] = { v8::Int32::New(pauseOnExceptionsState) };
    callDebuggerMethod("setPauseOnExceptionsState", 1, argv);
}

void ScriptDebugServer::setPauseOnNextStatement(bool pause)
{
    if (isPaused())
        return;
    if (pause)
        v8::Debug::DebugBreak(m_isolate);
    else
        v8::Debug::CancelDebugBreak(m_isolate);
}

bool ScriptDebugServer::canBreakProgram()
{
    if (!m_breakpointsActivated)
        return false;

    // FIXME: Remove this check once m_isolate->GetCurrentContext() does not crash.
    if (!v8::Context::InContext())
        return false;

    v8::HandleScope scope(m_isolate);
    return !m_isolate->GetCurrentContext().IsEmpty();
}

void ScriptDebugServer::breakProgram()
{
    if (!canBreakProgram())
        return;

    v8::HandleScope scope(m_isolate);
    if (m_breakProgramCallbackTemplate.isEmpty()) {
        v8::Handle<v8::FunctionTemplate> templ = v8::FunctionTemplate::New();
        templ->SetCallHandler(&ScriptDebugServer::breakProgramCallback, v8::External::New(this));
        m_breakProgramCallbackTemplate.set(m_isolate, templ);
    }

    m_pausedContext = m_isolate->GetCurrentContext();
    v8::Handle<v8::Function> breakProgramFunction = m_breakProgramCallbackTemplate.newLocal(m_isolate)->GetFunction();
    v8::Debug::Call(breakProgramFunction);
    m_pausedContext.Clear();
}

void ScriptDebugServer::continueProgram()
{
    if (isPaused())
        quitMessageLoopOnPause();
    m_executionState.clear();
}

void ScriptDebugServer::stepIntoStatement()
{
    ASSERT(isPaused());
    v8::Handle<v8::Value> argv[] = { m_executionState.get() };
    callDebuggerMethod("stepIntoStatement", 1, argv);
    continueProgram();
}

void ScriptDebugServer::stepOverStatement()
{
    ASSERT(isPaused());
    v8::Handle<v8::Value> argv[] = { m_executionState.get() };
    callDebuggerMethod("stepOverStatement", 1, argv);
    continueProgram();
}

void ScriptDebugServer::stepOutOfFunction()
{
    ASSERT(isPaused());
    v8::Handle<v8::Value> argv[] = { m_executionState.get() };
    callDebuggerMethod("stepOutOfFunction", 1, argv);
    continueProgram();
}

bool ScriptDebugServer::setScriptSource(const String& sourceID, const String& newContent, bool preview, String* error, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>& errorData, ScriptValue* newCallFrames, ScriptObject* result)
{
    class EnableLiveEditScope {
    public:
        EnableLiveEditScope() { v8::Debug::SetLiveEditEnabled(true); }
        ~EnableLiveEditScope() { v8::Debug::SetLiveEditEnabled(false); }
    };

    ensureDebuggerScriptCompiled();
    v8::HandleScope scope;

    OwnPtr<v8::Context::Scope> contextScope;
    v8::Handle<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
    if (!isPaused())
        contextScope = adoptPtr(new v8::Context::Scope(debuggerContext));

    v8::Handle<v8::Value> argv[] = { v8String(sourceID, debuggerContext->GetIsolate()), v8String(newContent, debuggerContext->GetIsolate()), v8Boolean(preview) };

    v8::Local<v8::Value> v8result;
    {
        EnableLiveEditScope enableLiveEditScope;
        v8::TryCatch tryCatch;
        tryCatch.SetVerbose(false);
        v8result = callDebuggerMethod("liveEditScriptSource", 3, argv);
        if (tryCatch.HasCaught()) {
            v8::Local<v8::Message> message = tryCatch.Message();
            if (!message.IsEmpty())
                *error = toWebCoreStringWithUndefinedOrNullCheck(message->Get());
            else
                *error = "Unknown error.";
            return false;
        }
    }
    ASSERT(!v8result.IsEmpty());
    v8::Local<v8::Object> resultTuple = v8result->ToObject();
    int code = static_cast<int>(resultTuple->Get(0)->ToInteger()->Value());
    switch (code) {
    case 0:
        {
            v8::Local<v8::Value> normalResult = resultTuple->Get(1);
            if (normalResult->IsObject())
                *result = ScriptObject(ScriptState::current(), normalResult->ToObject());
            // Call stack may have changed after if the edited function was on the stack.
            if (!preview && isPaused())
                *newCallFrames = currentCallFrame();
            return true;
        }
    // Compile error.
    case 1:
        {
            RefPtr<TypeBuilder::Debugger::SetScriptSourceError::CompileError> compileError =
                TypeBuilder::Debugger::SetScriptSourceError::CompileError::create()
                    .setMessage(toWebCoreStringWithUndefinedOrNullCheck(resultTuple->Get(2)))
                    .setLineNumber(resultTuple->Get(3)->ToInteger()->Value())
                    .setColumnNumber(resultTuple->Get(4)->ToInteger()->Value());

            *error = toWebCoreStringWithUndefinedOrNullCheck(resultTuple->Get(1));
            errorData = TypeBuilder::Debugger::SetScriptSourceError::create();
            errorData->setCompileError(compileError);
            return false;
        }
    }
    *error = "Unknown error.";
    return false;
}

void ScriptDebugServer::updateCallStack(ScriptValue* callFrame)
{
    if (isPaused())
        *callFrame = currentCallFrame();
}

void ScriptDebugServer::setScriptPreprocessor(const String& preprocessorBody)
{
    m_scriptPreprocessor.clear();
    if (!preprocessorBody.isEmpty())
        m_scriptPreprocessor = adoptPtr(new ScriptPreprocessor(preprocessorBody, m_isolate));
}

ScriptValue ScriptDebugServer::currentCallFrame()
{
    ASSERT(isPaused());
    v8::Handle<v8::Value> argv[] = { m_executionState.get() };
    v8::Handle<v8::Value> currentCallFrameV8 = callDebuggerMethod("currentCallFrame", 1, argv);

    ASSERT(!currentCallFrameV8.IsEmpty());
    if (!currentCallFrameV8->IsObject())
        return ScriptValue(v8::Null());

    RefPtr<JavaScriptCallFrame> currentCallFrame = JavaScriptCallFrame::create(v8::Debug::GetDebugContext(), v8::Handle<v8::Object>::Cast(currentCallFrameV8));
    v8::Context::Scope contextScope(m_pausedContext);
    return ScriptValue(toV8(currentCallFrame.release(), v8::Handle<v8::Object>(), m_pausedContext->GetIsolate()));
}

void ScriptDebugServer::interruptAndRun(PassOwnPtr<Task> task, v8::Isolate* isolate)
{
    v8::Debug::DebugBreakForCommand(new ClientDataImpl(task), isolate);
}

void ScriptDebugServer::runPendingTasks()
{
    v8::Debug::ProcessDebugMessages();
}

static ScriptDebugServer* toScriptDebugServer(v8::Handle<v8::Value> data)
{
    void* p = v8::Handle<v8::External>::Cast(data)->Value();
    return static_cast<ScriptDebugServer*>(p);
}

void ScriptDebugServer::breakProgramCallback(const v8::FunctionCallbackInfo<v8::Value>& args)
{
    ASSERT(2 == args.Length());

    ScriptDebugServer* thisPtr = toScriptDebugServer(args.Data());
    v8::Handle<v8::Value> exception;
    v8::Handle<v8::Array> hitBreakpoints;
    thisPtr->breakProgram(v8::Handle<v8::Object>::Cast(args[0]), exception, hitBreakpoints);
}

void ScriptDebugServer::breakProgram(v8::Handle<v8::Object> executionState, v8::Handle<v8::Value> exception, v8::Handle<v8::Array> hitBreakpointNumbers)
{
    // Don't allow nested breaks.
    if (isPaused())
        return;

    ScriptDebugListener* listener = getDebugListenerForContext(m_pausedContext);
    if (!listener)
        return;

    Vector<String> breakpointIds;
    if (!hitBreakpointNumbers.IsEmpty()) {
        breakpointIds.resize(hitBreakpointNumbers->Length());
        for (size_t i = 0; i < hitBreakpointNumbers->Length(); i++)
            breakpointIds[i] = toWebCoreStringWithUndefinedOrNullCheck(hitBreakpointNumbers->Get(i));
    }

    m_executionState.set(m_isolate, executionState);
    ScriptState* currentCallFrameState = ScriptState::forContext(m_pausedContext);
    listener->didPause(currentCallFrameState, currentCallFrame(), ScriptValue(exception), breakpointIds);

    m_runningNestedMessageLoop = true;
    runMessageLoopOnPause(m_pausedContext);
    m_runningNestedMessageLoop = false;
}

void ScriptDebugServer::breakProgram(const v8::Debug::EventDetails& eventDetails, v8::Handle<v8::Value> exception, v8::Handle<v8::Array> hitBreakpointNumbers)
{
    m_pausedContext = eventDetails.GetEventContext();
    breakProgram(eventDetails.GetExecutionState(), exception, hitBreakpointNumbers);
    m_pausedContext.Clear();
}

void ScriptDebugServer::v8DebugEventCallback(const v8::Debug::EventDetails& eventDetails)
{
    ScriptDebugServer* thisPtr = toScriptDebugServer(eventDetails.GetCallbackData());
    thisPtr->handleV8DebugEvent(eventDetails);
}

void ScriptDebugServer::handleV8DebugEvent(const v8::Debug::EventDetails& eventDetails)
{
    v8::DebugEvent event = eventDetails.GetEvent();

    if (event == v8::BreakForCommand) {
        ClientDataImpl* data = static_cast<ClientDataImpl*>(eventDetails.GetClientData());
        data->task()->run();
        return;
    }

    if (event != v8::Break && event != v8::Exception && event != v8::AfterCompile && event != v8::BeforeCompile)
        return;

    v8::Handle<v8::Context> eventContext = eventDetails.GetEventContext();
    ASSERT(!eventContext.IsEmpty());

    ScriptDebugListener* listener = getDebugListenerForContext(eventContext);
    if (listener) {
        v8::HandleScope scope;
        v8::Local<v8::Context> debugContext = v8::Debug::GetDebugContext();
        v8::Isolate* isolate = debugContext->GetIsolate();
        if (event == v8::BeforeCompile) {

            if (!m_scriptPreprocessor)
                return;

            OwnPtr<ScriptPreprocessor> preprocessor(m_scriptPreprocessor.release());
            v8::Context::Scope contextScope(debugContext);
            v8::Handle<v8::Function> getScriptSourceFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.get()->Get(v8::String::New("getScriptSource")));
            v8::Handle<v8::Value> argv[] = { eventDetails.GetEventData() };
            v8::Handle<v8::Value> script = V8ScriptRunner::callInternalFunction(getScriptSourceFunction, m_debuggerScript.get(), WTF_ARRAY_LENGTH(argv), argv, isolate);

            v8::Handle<v8::Function> getScriptNameFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.get()->Get(v8::String::New("getScriptName")));
            v8::Handle<v8::Value> argv1[] = { eventDetails.GetEventData() };
            v8::Handle<v8::Value> scriptName = V8ScriptRunner::callInternalFunction(getScriptNameFunction, m_debuggerScript.get(), WTF_ARRAY_LENGTH(argv1), argv1, isolate);
            v8::Handle<v8::Function> setScriptSourceFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.get()->Get(v8::String::New("setScriptSource")));
            String patchedScript = preprocessor->preprocessSourceCode(toWebCoreStringWithUndefinedOrNullCheck(script), toWebCoreStringWithUndefinedOrNullCheck(scriptName));

            v8::Handle<v8::Value> argv2[] = { eventDetails.GetEventData(), v8String(patchedScript, isolate) };
            V8ScriptRunner::callInternalFunction(setScriptSourceFunction, m_debuggerScript.get(), WTF_ARRAY_LENGTH(argv2), argv2, isolate);
            m_scriptPreprocessor = preprocessor.release();
        } else if (event == v8::AfterCompile) {
            v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
            v8::Handle<v8::Function> getAfterCompileScript = v8::Local<v8::Function>::Cast(m_debuggerScript.get()->Get(v8::String::NewSymbol("getAfterCompileScript")));
            v8::Handle<v8::Value> argv[] = { eventDetails.GetEventData() };
            v8::Handle<v8::Value> value = V8ScriptRunner::callInternalFunction(getAfterCompileScript, m_debuggerScript.get(), WTF_ARRAY_LENGTH(argv), argv, isolate);
            ASSERT(value->IsObject());
            v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
            dispatchDidParseSource(listener, object);
        } else if (event == v8::Exception) {
            v8::Local<v8::StackTrace> stackTrace = v8::StackTrace::CurrentStackTrace(1);
            // Stack trace is empty in case of syntax error. Silently continue execution in such cases.
            if (!stackTrace->GetFrameCount())
                return;
            v8::Handle<v8::Object> eventData = eventDetails.GetEventData();
            v8::Handle<v8::Value> exceptionGetterValue = eventData->Get(v8::String::NewSymbol("exception"));
            ASSERT(!exceptionGetterValue.IsEmpty() && exceptionGetterValue->IsFunction());
            v8::Handle<v8::Value> exception = V8ScriptRunner::callInternalFunction(v8::Handle<v8::Function>::Cast(exceptionGetterValue), eventData, 0, 0, isolate);
            breakProgram(eventDetails, exception, v8::Handle<v8::Array>());
        } else if (event == v8::Break) {
            v8::Handle<v8::Function> getBreakpointNumbersFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.get()->Get(v8::String::NewSymbol("getBreakpointNumbers")));
            v8::Handle<v8::Value> argv[] = { eventDetails.GetEventData() };
            v8::Handle<v8::Value> hitBreakpoints = V8ScriptRunner::callInternalFunction(getBreakpointNumbersFunction, m_debuggerScript.get(), WTF_ARRAY_LENGTH(argv), argv, isolate);
            ASSERT(hitBreakpoints->IsArray());

            breakProgram(eventDetails, v8::Handle<v8::Value>(), hitBreakpoints.As<v8::Array>());
        }
    }
}

void ScriptDebugServer::dispatchDidParseSource(ScriptDebugListener* listener, v8::Handle<v8::Object> object)
{
    String sourceID = toWebCoreStringWithUndefinedOrNullCheck(object->Get(v8::String::NewSymbol("id")));

    ScriptDebugListener::Script script;
    script.url = toWebCoreStringWithUndefinedOrNullCheck(object->Get(v8::String::NewSymbol("name")));
    script.source = toWebCoreStringWithUndefinedOrNullCheck(object->Get(v8::String::NewSymbol("source")));
    script.sourceMappingURL = toWebCoreStringWithUndefinedOrNullCheck(object->Get(v8::String::NewSymbol("sourceMappingURL")));
    script.startLine = object->Get(v8::String::NewSymbol("startLine"))->ToInteger()->Value();
    script.startColumn = object->Get(v8::String::NewSymbol("startColumn"))->ToInteger()->Value();
    script.endLine = object->Get(v8::String::NewSymbol("endLine"))->ToInteger()->Value();
    script.endColumn = object->Get(v8::String::NewSymbol("endColumn"))->ToInteger()->Value();
    script.isContentScript = object->Get(v8::String::NewSymbol("isContentScript"))->ToBoolean()->Value();

    listener->didParseSource(sourceID, script);
}

void ScriptDebugServer::ensureDebuggerScriptCompiled()
{
    if (!m_debuggerScript.get().IsEmpty())
        return;

    v8::HandleScope scope(m_isolate);
    v8::Context::Scope contextScope(v8::Debug::GetDebugContext());
    v8::Handle<v8::String> source = v8String(String(reinterpret_cast<const char*>(DebuggerScriptSource_js), sizeof(DebuggerScriptSource_js)), m_isolate);
    v8::Local<v8::Value> value = V8ScriptRunner::compileAndRunInternalScript(source, m_isolate);
    ASSERT(!value.IsEmpty());
    ASSERT(value->IsObject());
    m_debuggerScript.set(m_isolate, v8::Handle<v8::Object>::Cast(value));
}

v8::Local<v8::Value> ScriptDebugServer::functionScopes(v8::Handle<v8::Function> function)
{
    ensureDebuggerScriptCompiled();

    v8::Handle<v8::Value> argv[] = { function };
    return callDebuggerMethod("getFunctionScopes", 1, argv);
}

v8::Local<v8::Value> ScriptDebugServer::getInternalProperties(v8::Handle<v8::Object>& object)
{
    if (m_debuggerScript.get().IsEmpty())
        return v8::Local<v8::Value>::New(m_isolate, v8::Undefined());

    v8::Handle<v8::Value> argv[] = { object };
    return callDebuggerMethod("getInternalProperties", 1, argv);
}

v8::Handle<v8::Value> ScriptDebugServer::setFunctionVariableValue(v8::Handle<v8::Value> functionValue, int scopeNumber, const String& variableName, v8::Handle<v8::Value> newValue)
{
    v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
    if (m_debuggerScript.get().IsEmpty())
        return v8::ThrowException(v8::String::New("Debugging is not enabled."));

    v8::Handle<v8::Value> argv[] = {
        functionValue,
        v8::Handle<v8::Value>(v8::Integer::New(scopeNumber)),
        v8String(variableName, debuggerContext->GetIsolate()),
        newValue
    };
    return callDebuggerMethod("setFunctionVariableValue", 4, argv);
}

bool ScriptDebugServer::isPaused()
{
    return !m_executionState.get().IsEmpty();
}

void ScriptDebugServer::compileScript(ScriptState* state, const String& expression, const String& sourceURL, String* scriptId, String* exceptionMessage)
{
    v8::HandleScope handleScope;
    v8::Handle<v8::Context> context = state->context();
    if (context.IsEmpty())
        return;
    v8::Isolate* isolate = context->GetIsolate();
    v8::Context::Scope contextScope(context);

    v8::Handle<v8::String> source = v8String(expression, isolate);
    v8::TryCatch tryCatch;
    v8::Local<v8::Script> script = V8ScriptRunner::compileScript(source, sourceURL, TextPosition(), 0, isolate);
    if (tryCatch.HasCaught()) {
        v8::Local<v8::Message> message = tryCatch.Message();
        if (!message.IsEmpty())
            *exceptionMessage = toWebCoreStringWithUndefinedOrNullCheck(message->Get());
        return;
    }
    if (script.IsEmpty())
        return;

    *scriptId = toWebCoreStringWithUndefinedOrNullCheck(script->Id());
    m_compiledScripts.set(*scriptId, adoptPtr(new ScopedPersistent<v8::Script>(script)));
}

void ScriptDebugServer::clearCompiledScripts()
{
    m_compiledScripts.clear();
}

void ScriptDebugServer::runScript(ScriptState* state, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionMessage)
{
    if (!m_compiledScripts.contains(scriptId))
        return;
    v8::HandleScope handleScope;
    ScopedPersistent<v8::Script>* scriptHandle = m_compiledScripts.get(scriptId);
    v8::Local<v8::Script> script = v8::Local<v8::Script>::New(scriptHandle->get());
    m_compiledScripts.remove(scriptId);
    if (script.IsEmpty())
        return;

    v8::Handle<v8::Context> context = state->context();
    if (context.IsEmpty())
        return;
    v8::Context::Scope contextScope(context);
    v8::TryCatch tryCatch;
    v8::Local<v8::Value> value = V8ScriptRunner::runCompiledScript(script, state->scriptExecutionContext());
    *wasThrown = false;
    if (tryCatch.HasCaught()) {
        *wasThrown = true;
        *result = ScriptValue(tryCatch.Exception());
        v8::Local<v8::Message> message = tryCatch.Message();
        if (!message.IsEmpty())
            *exceptionMessage = toWebCoreStringWithUndefinedOrNullCheck(message->Get());
    } else
        *result = ScriptValue(value);
}

} // namespace WebCore


text:
package com.all.app;

public class NoBeanDefinedException extends RuntimeException {

	private static final long serialVersionUID = 1L;

}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

import coursereg.models
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('coursereg', '0004_auto_20160731_1541'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='course',
            name='credits',
        ),
        migrations.RemoveField(
            model_name='course',
            name='term',
        ),
        migrations.RemoveField(
            model_name='course',
            name='last_reg_date',
        ),
        migrations.RemoveField(
            model_name='course',
            name='last_drop_date',
        ),
        migrations.AlterField(
            model_name='course',
            name='new_term',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='coursereg.Term'),
        ),
        migrations.RenameField(
            model_name='course',
            old_name='new_term',
            new_name='term',
        ),
        migrations.RenameField(
            model_name='course',
            old_name='new_credits',
            new_name='credits',
        ),
        migrations.RemoveField(
            model_name='participant',
            name='state',
        ),
        migrations.RemoveField(
            model_name='participant',
            name='grade',
        ),
        migrations.RenameField(
            model_name='participant',
            old_name='new_grade',
            new_name='grade',
        ),
        migrations.AlterField(
            model_name='participant',
            name='created_at',
            field=models.DateTimeField(auto_now_add=True),
        ),
        migrations.AlterField(
            model_name='participant',
            name='updated_at',
            field=models.DateTimeField(auto_now=True),
        ),
        migrations.AlterField(
            model_name='department',
            name='abbreviation',
            field=models.CharField(max_length=100, unique=True),
        ),
        migrations.AlterField(
            model_name='notification',
            name='origin',
            field=models.IntegerField(choices=[(0, 'Adviser'), (1, 'Instructor'), (2, 'DCC'), (3, 'Other'), (4, 'Student')], default=2),
        ),

    ]


text:
#ifndef IVW_HEDGEHOG2D_H
#define IVW_HEDGEHOG2D_H

#include <modules/vectorfieldvisualizationgl/vectorfieldvisualizationglmoduledefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/processors/processor.h>
#include <inviwo/core/ports/imageport.h>
#include <inviwo/core/ports/meshport.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/properties/boolproperty.h>
#include <inviwo/core/datastructures/geometry/basicmesh.h>
#include <inviwo/core/properties/optionproperty.h>
#include <inviwo/core/properties/compositeproperty.h>
#include <random>

namespace inviwo {

/**
 * \class HedgeHog2D
 *
 * \brief VERY_BRIEFLY_DESCRIBE_THE_CLASS
 *
 * DESCRIBE_THE_CLASS
 */
class IVW_MODULE_VECTORFIELDVISUALIZATIONGL_API HedgeHog2D : public Processor {

    enum class GlyphType {
        Arrow,
        Quiver
    };

public:
    virtual const ProcessorInfo getProcessorInfo() const override;
    static const ProcessorInfo processorInfo_;
    HedgeHog2D();
    virtual ~HedgeHog2D();

    virtual void process() override;

private:
    ImageInport vectorFeild_;
    MeshOutport mesh_;

    FloatProperty glyphScale_;
    IntVec2Property numberOfGlyphs_;
    BoolProperty jitter_;
    TemplateOptionProperty<GlyphType> glyphType_;

    FloatVec4Property color_;

    CompositeProperty arrowSettings_;
    FloatProperty arrowBaseWidth_;
    FloatProperty arrowHookWidth_;
    FloatProperty arrowHeadRatio_;

    CompositeProperty quiverSettings_;
    FloatProperty quiverHookWidth_;
    FloatProperty quiverHeadRatio_;

    std::random_device rd_;
    std::mt19937 mt_;

    void adjustVisibilites();

    vec4 getColor(const dvec2 &velocity);

    void createArrow(BasicMesh &mesh, IndexBufferRAM &index, float x, float y, float dx, float dy, const dvec2 &velocity);
    void createQuiver(BasicMesh &mesh, IndexBufferRAM &index, float x, float y, float dx, float dy, const dvec2 &velocity);
};

} // namespace

#endif // IVW_HEDGEHOG2D_H


text:
package org.apache.falcon.rerun.event;

/**
 * Event representing a retry.
 */
public class RetryEvent extends RerunEvent {

    private int attempts;
    private int failRetryCount;

    //SUSPEND CHECKSTYLE CHECK ParameterNumberCheck
    public RetryEvent(String clusterName, String wfId, String parentId, long msgInsertTime,
                      long delay, String entityType, String entityName, String instance,
                      int runId, int attempts, int failRetryCount, String workflowUser) {
        super(clusterName, wfId, parentId, msgInsertTime, delay, entityType, entityName,
                instance, runId, workflowUser);
        this.attempts = attempts;
        this.failRetryCount = failRetryCount;
    }
    //RESUME CHECKSTYLE CHECK ParameterNumberCheck

    public int getAttempts() {
        return attempts;
    }

    public int getFailRetryCount() {
        return failRetryCount;
    }

    public void setFailRetryCount(int failRetryCount) {
        this.failRetryCount = failRetryCount;
    }

    @Override
    public String toString() {

        return "clusterName=" + clusterName + SEP + "wfId=" + wfId + SEP
                + "msgInsertTime=" + msgInsertTime + SEP + "delayInMilliSec="
                + delayInMilliSec + SEP + "entityType=" + entityType + SEP
                + "entityName=" + entityName + SEP + "instance=" + instance
                + SEP + "runId=" + runId + SEP + "attempts=" + attempts + SEP
                + "failRetryCount=" + failRetryCount + SEP + "workflowUser=" + workflowUser;
    }

}


text:
#include <aws/quicksight/model/DescribeFolderRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::QuickSight::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

DescribeFolderRequest::DescribeFolderRequest() :
    m_awsAccountIdHasBeenSet(false),
    m_folderIdHasBeenSet(false)
{
}

Aws::String DescribeFolderRequest::SerializePayload() const
{
  return {};
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<scriptmodule xmlns="http://xlt.xceptance.com/xlt-script/2" version="6">
  <description>Select sort by via position.</description>
  <parameter name="sortByPosition" desc="sort by position"/>
  <parameter name="sortByLabel_varName" desc="sort by label as var name"/>
  <command name="assertElementPresent" target="css=#main #primary .search-result-options .sort-by #grid-sort-header"/>
  <command name="storeText" target="css=#main #primary .search-result-options .sort-by #grid-sort-header option:nth-of-type(@{sortByPosition})" value="@{sortByLabel_varName}"/>
  <command name="select" target="id=grid-sort-header" value="label=${@{sortByLabel_varName}}"/>
  <command name="waitForText" target="css=#main #primary .search-result-options .sort-by #grid-sort-header option[selected]" value="${@{sortByLabel_varName}}"/>
  <command name="waitForText" target="css=#main #primary .search-result-options .sort-by #grid-sort-footer option[selected]" value="${@{sortByLabel_varName}}"/>
</scriptmodule>


text:
from blazeweb.content import Content

class HelloWorld(Content):

    def create(self, name=u'world'):
        return u'hello %s' % name


text:
<?php

namespace app\controllers;

use app\helpers\Query;
use Yii;
use yii\web\Controller;

class RawController extends Controller
{
    /**
     * Test #2: Single Database Query
     */
    public function actionDb()
    {
        $statement = Yii::$app->db->createCommand('SELECT id, randomNumber FROM World WHERE id = :id');
        $world = $statement->bindValue(':id', mt_rand(1, 10000))->queryOne();
        $world['id'] = (int)$world['id'];
        $world['randomNumber'] = (int)$world['randomNumber'];

        return $this->asJson($world);
    }

    /**
     * Test #3: Multiple Database Queries
     */
    public function actionQueries($queries)
    {
        $queries = Query::clamp($queries);

        $statement = Yii::$app->db->createCommand('SELECT id, randomNumber FROM World WHERE id = :id');

        $worlds = [];
        while (0 < $queries--) {
            $result = $statement->bindValue(':id', mt_rand(1, 10000))->queryOne();
            $result['id'] = (int)$result['id'];
            $result['randomNumber'] = (int)$result['randomNumber'];
            $worlds[] = $result;
        }

        return $this->asJson($worlds);
    }

    /**
     * Test #4: Fortunes
     */
    public function actionFortunes()
    {
        $fortunes = Yii::$app->db->createCommand('SELECT id, message FROM Fortune')->queryAll();
        $fortunes[] = ['id' => 0, 'message' => 'Additional fortune added at request time.'];

        usort($fortunes, function ($left, $right) {
            return strcmp($left['message'], $right['message']);
        });

        $this->view->title = 'Fortunes';

        return $this->render('fortunes', ['fortunes' => $fortunes]);
    }

    /**
     * Test #5: Database Updates
     */
    public function actionUpdates($queries)
    {
        $queries = Query::clamp($queries);

        $selectCommand = Yii::$app->db->createCommand('SELECT randomNumber FROM World WHERE id = :id');
        $updateCommand = Yii::$app->db->createCommand('UPDATE World SET randomNumber = :num WHERE id = :id');

        $worlds = [];

        while (0 < $queries--) {
            $id = mt_rand(1, 10000);
            $randomNumber = mt_rand(1, 1000);
            $selectCommand->bindParam(':id', $id)->queryScalar();
            $updateCommand->bindValues([':id' => $id, ':num' => $randomNumber])->execute();

            $worlds[] = ['id' => $id, 'randomNumber' => $randomNumber];
        }

        return $this->asJson($worlds);
    }
}


text:
require 'spec_helper'
require 'spec/support/run_test_app'

describe "sidekiq loader" do
  run_sidekiq
  before { app.wait_start }

  it 'starts and stops the app cleanly' do
    app.start.wait_start
    app.stop
    expect(app.status).to be_success
  end

end


text:
<?xml version="1.0" encoding="utf-8" ?>
<module navigationDisplayOrder="0">
  <homeTabPanelTabClass>tabHotel</homeTabPanelTabClass>
</module>


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

import javax.jms.BytesMessage;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge;

/**
 * @version $Revision$
 */
public class ConsumeMessageConverterTest extends CamelTestSupport {

    @Override
    protected JndiRegistry createRegistry() throws Exception {
        JndiRegistry jndi = super.createRegistry();
        jndi.bind("myMessageConverter", new MyMessageConverter());
        return jndi;
    }

    protected CamelContext createCamelContext() throws Exception {
        CamelContext camelContext = super.createCamelContext();

        ConnectionFactory connectionFactory = CamelJmsTestHelper.createConnectionFactory();
        camelContext.addComponent("activemq", jmsComponentAutoAcknowledge(connectionFactory));

        return camelContext;
    }

    @Test
    public void testTextMessage() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.message(0).body().isInstanceOf(TextMessage.class);

        template.sendBody("activemq:queue:hello", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testBytesMessage() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.message(0).body().isInstanceOf(BytesMessage.class);

        template.sendBody("activemq:queue:hello", "Hello World".getBytes());

        assertMockEndpointsSatisfied();
    }

    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from("activemq:queue:hello?messageConverter=#myMessageConverter").to("mock:result");
            }
        };
    }

    private class MyMessageConverter implements MessageConverter {

        public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
            return null;
        }

        public Object fromMessage(Message message) throws JMSException, MessageConversionException {
            // just return the underlying JMS message directly so we can test that this converter is used
            return message;
        }
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Multiple Language EBU Timed Text Sample</title>
    <meta name="description" content="" />

    <link rel="stylesheet" href="../../contrib/akamai/controlbar/controlbar.css">

            <video preload="auto" autoplay="true" > </video>

                00:00:00

                <input type="range" id="volumebar" class="volumebar" value="1" min="0" max="1" step=".01"/>

                00:00:00

                    <input type="range" id="seekbar" value="0" class="seekbar" min="0" step="0.01"/>


text:
#include <modules/vectorfieldvisualization/properties/pathlineproperties.h>

#include <inviwo/core/properties/ordinalproperty.h>                              // for DoublePr...
#include <modules/vectorfieldvisualization/properties/integrallineproperties.h>  // for Integral...

namespace inviwo {

const std::string PathLineProperties::classIdentifier = "org.inviwo.PathLineProperties";
std::string PathLineProperties::getClassIdentifier() const { return classIdentifier; }

PathLineProperties::PathLineProperties(std::string_view identifier, std::string_view displayName)
    : IntegralLineProperties(identifier, displayName)
    , startT_("startT", "Start at timestep", 0, 0, 1) {
    setUpProperties();
}

PathLineProperties::PathLineProperties(const PathLineProperties& rhs)
    : IntegralLineProperties(rhs), startT_(rhs.startT_) {
    setUpProperties();
}

PathLineProperties* PathLineProperties::clone() const { return new PathLineProperties(*this); }

PathLineProperties::~PathLineProperties() {}

void PathLineProperties::setUpProperties() { addProperty(startT_); }

}  // namespace inviwo


text:
namespace crashpad {
namespace test {
namespace {

TEST(MinidumpFileWriter, Empty) {
  MinidumpFileWriter minidump_file;
  StringFile string_file;
  ASSERT_TRUE(minidump_file.WriteEverything(&string_file));
  ASSERT_EQ(sizeof(MINIDUMP_HEADER), string_file.string().size());

  const MINIDUMP_DIRECTORY* directory;
  const MINIDUMP_HEADER* header =
      MinidumpHeaderAtStart(string_file.string(), &directory);
  ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 0, 0));
  EXPECT_FALSE(directory);
}

class TestStream final : public internal::MinidumpStreamWriter {
 public:
  TestStream(MinidumpStreamType stream_type,
             size_t stream_size,
             uint8_t stream_value)
      : stream_data_(stream_size, stream_value), stream_type_(stream_type) {}

  ~TestStream() override {}

  // MinidumpStreamWriter:
  MinidumpStreamType StreamType() const override {
    return stream_type_;
  }

 protected:
  // MinidumpWritable:
  size_t SizeOfObject() override {
    EXPECT_GE(state(), kStateFrozen);
    return stream_data_.size();
  }

  bool WriteObject(FileWriterInterface* file_writer) override {
    EXPECT_EQ(state(), kStateWritable);
    return file_writer->Write(&stream_data_[0], stream_data_.size());
  }

 private:
  std::string stream_data_;
  MinidumpStreamType stream_type_;

  DISALLOW_COPY_AND_ASSIGN(TestStream);
};

TEST(MinidumpFileWriter, OneStream) {
  MinidumpFileWriter minidump_file;
  const time_t kTimestamp = 0x155d2fb8;
  minidump_file.SetTimestamp(kTimestamp);

  const size_t kStreamSize = 5;
  const MinidumpStreamType kStreamType = static_cast<MinidumpStreamType>(0x4d);
  const uint8_t kStreamValue = 0x5a;
  auto stream =
      make_scoped_ptr(new TestStream(kStreamType, kStreamSize, kStreamValue));
  minidump_file.AddStream(stream.Pass());

  StringFile string_file;
  ASSERT_TRUE(minidump_file.WriteEverything(&string_file));

  const size_t kDirectoryOffset = sizeof(MINIDUMP_HEADER);
  const size_t kStreamOffset = kDirectoryOffset + sizeof(MINIDUMP_DIRECTORY);
  const size_t kFileSize = kStreamOffset + kStreamSize;

  ASSERT_EQ(kFileSize, string_file.string().size());

  const MINIDUMP_DIRECTORY* directory;
  const MINIDUMP_HEADER* header =
      MinidumpHeaderAtStart(string_file.string(), &directory);
  ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, kTimestamp));
  ASSERT_TRUE(directory);

  EXPECT_EQ(kStreamType, directory[0].StreamType);
  EXPECT_EQ(kStreamSize, directory[0].Location.DataSize);
  EXPECT_EQ(kStreamOffset, directory[0].Location.Rva);

  const uint8_t* stream_data = MinidumpWritableAtLocationDescriptor<uint8_t>(
      string_file.string(), directory[0].Location);
  ASSERT_TRUE(stream_data);

  std::string expected_stream(kStreamSize, kStreamValue);
  EXPECT_EQ(0, memcmp(stream_data, expected_stream.c_str(), kStreamSize));
}

TEST(MinidumpFileWriter, ThreeStreams) {
  MinidumpFileWriter minidump_file;
  const time_t kTimestamp = 0x155d2fb8;
  minidump_file.SetTimestamp(kTimestamp);

  const size_t kStream0Size = 5;
  const MinidumpStreamType kStream0Type = static_cast<MinidumpStreamType>(0x6d);
  const uint8_t kStream0Value = 0x5a;
  auto stream0 = make_scoped_ptr(
      new TestStream(kStream0Type, kStream0Size, kStream0Value));
  minidump_file.AddStream(stream0.Pass());

  // Make the second stream's type be a smaller quantity than the first stream's
  // to test that the streams show up in the order that they were added, not in
  // numeric order.
  const size_t kStream1Size = 3;
  const MinidumpStreamType kStream1Type = static_cast<MinidumpStreamType>(0x4d);
  const uint8_t kStream1Value = 0xa5;
  auto stream1 = make_scoped_ptr(
      new TestStream(kStream1Type, kStream1Size, kStream1Value));
  minidump_file.AddStream(stream1.Pass());

  const size_t kStream2Size = 1;
  const MinidumpStreamType kStream2Type = static_cast<MinidumpStreamType>(0x7e);
  const uint8_t kStream2Value = 0x36;
  auto stream2 = make_scoped_ptr(
      new TestStream(kStream2Type, kStream2Size, kStream2Value));
  minidump_file.AddStream(stream2.Pass());

  StringFile string_file;
  ASSERT_TRUE(minidump_file.WriteEverything(&string_file));

  const size_t kDirectoryOffset = sizeof(MINIDUMP_HEADER);
  const size_t kStream0Offset =
      kDirectoryOffset + 3 * sizeof(MINIDUMP_DIRECTORY);
  const size_t kStream1Padding = 3;
  const size_t kStream1Offset = kStream0Offset + kStream0Size + kStream1Padding;
  const size_t kStream2Padding = 1;
  const size_t kStream2Offset = kStream1Offset + kStream1Size + kStream2Padding;
  const size_t kFileSize = kStream2Offset + kStream2Size;

  ASSERT_EQ(kFileSize, string_file.string().size());

  const MINIDUMP_DIRECTORY* directory;
  const MINIDUMP_HEADER* header =
      MinidumpHeaderAtStart(string_file.string(), &directory);
  ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 3, kTimestamp));
  ASSERT_TRUE(directory);

  EXPECT_EQ(kStream0Type, directory[0].StreamType);
  EXPECT_EQ(kStream0Size, directory[0].Location.DataSize);
  EXPECT_EQ(kStream0Offset, directory[0].Location.Rva);
  EXPECT_EQ(kStream1Type, directory[1].StreamType);
  EXPECT_EQ(kStream1Size, directory[1].Location.DataSize);
  EXPECT_EQ(kStream1Offset, directory[1].Location.Rva);
  EXPECT_EQ(kStream2Type, directory[2].StreamType);
  EXPECT_EQ(kStream2Size, directory[2].Location.DataSize);
  EXPECT_EQ(kStream2Offset, directory[2].Location.Rva);

  const uint8_t* stream0_data = MinidumpWritableAtLocationDescriptor<uint8_t>(
      string_file.string(), directory[0].Location);
  ASSERT_TRUE(stream0_data);

  std::string expected_stream0(kStream0Size, kStream0Value);
  EXPECT_EQ(0, memcmp(stream0_data, expected_stream0.c_str(), kStream0Size));

  const int kZeroes[16] = {};
  ASSERT_GE(sizeof(kZeroes), kStream1Padding);
  EXPECT_EQ(0, memcmp(stream0_data + kStream0Size, kZeroes, kStream1Padding));

  const uint8_t* stream1_data = MinidumpWritableAtLocationDescriptor<uint8_t>(
      string_file.string(), directory[1].Location);
  ASSERT_TRUE(stream1_data);

  std::string expected_stream1(kStream1Size, kStream1Value);
  EXPECT_EQ(0, memcmp(stream1_data, expected_stream1.c_str(), kStream1Size));

  ASSERT_GE(sizeof(kZeroes), kStream2Padding);
  EXPECT_EQ(0, memcmp(stream1_data + kStream1Size, kZeroes, kStream2Padding));

  const uint8_t* stream2_data = MinidumpWritableAtLocationDescriptor<uint8_t>(
      string_file.string(), directory[2].Location);
  ASSERT_TRUE(stream2_data);

  std::string expected_stream2(kStream2Size, kStream2Value);
  EXPECT_EQ(0, memcmp(stream2_data, expected_stream2.c_str(), kStream2Size));
}

TEST(MinidumpFileWriter, ZeroLengthStream) {
  MinidumpFileWriter minidump_file;

  const size_t kStreamSize = 0;
  const MinidumpStreamType kStreamType = static_cast<MinidumpStreamType>(0x4d);
  auto stream = make_scoped_ptr(new TestStream(kStreamType, kStreamSize, 0));
  minidump_file.AddStream(stream.Pass());

  StringFile string_file;
  ASSERT_TRUE(minidump_file.WriteEverything(&string_file));

  const size_t kDirectoryOffset = sizeof(MINIDUMP_HEADER);
  const size_t kStreamOffset = kDirectoryOffset + sizeof(MINIDUMP_DIRECTORY);
  const size_t kFileSize = kStreamOffset + kStreamSize;

  ASSERT_EQ(kFileSize, string_file.string().size());

  const MINIDUMP_DIRECTORY* directory;
  const MINIDUMP_HEADER* header =
      MinidumpHeaderAtStart(string_file.string(), &directory);
  ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 1, 0));
  ASSERT_TRUE(directory);

  EXPECT_EQ(kStreamType, directory[0].StreamType);
  EXPECT_EQ(kStreamSize, directory[0].Location.DataSize);
  EXPECT_EQ(kStreamOffset, directory[0].Location.Rva);
}

TEST(MinidumpFileWriter, InitializeFromSnapshot_Basic) {
  const uint32_t kSnapshotTime = 0x4976043c;
  const timeval kSnapshotTimeval = { static_cast<time_t>(kSnapshotTime), 0 };

  TestProcessSnapshot process_snapshot;
  process_snapshot.SetSnapshotTime(kSnapshotTimeval);

  auto system_snapshot = make_scoped_ptr(new TestSystemSnapshot());
  system_snapshot->SetCPUArchitecture(kCPUArchitectureX86_64);
  system_snapshot->SetOperatingSystem(SystemSnapshot::kOperatingSystemMacOSX);
  process_snapshot.SetSystem(system_snapshot.Pass());

  MinidumpFileWriter minidump_file_writer;
  minidump_file_writer.InitializeFromSnapshot(&process_snapshot);

  StringFile string_file;
  ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file));

  const MINIDUMP_DIRECTORY* directory;
  const MINIDUMP_HEADER* header =
      MinidumpHeaderAtStart(string_file.string(), &directory);
  ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 5, kSnapshotTime));
  ASSERT_TRUE(directory);

  EXPECT_EQ(kMinidumpStreamTypeSystemInfo, directory[0].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_SYSTEM_INFO>(
                  string_file.string(), directory[0].Location));

  EXPECT_EQ(kMinidumpStreamTypeMiscInfo, directory[1].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_MISC_INFO_4>(
                  string_file.string(), directory[1].Location));

  EXPECT_EQ(kMinidumpStreamTypeThreadList, directory[2].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_THREAD_LIST>(
                  string_file.string(), directory[2].Location));

  EXPECT_EQ(kMinidumpStreamTypeModuleList, directory[3].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_MODULE_LIST>(
                  string_file.string(), directory[3].Location));

  EXPECT_EQ(kMinidumpStreamTypeMemoryList, directory[4].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_MEMORY_LIST>(
                  string_file.string(), directory[4].Location));
}

TEST(MinidumpFileWriter, InitializeFromSnapshot_Exception) {
  // In a 32-bit environment, this will give a "timestamp out of range" warning,
  // but the test should complete without failure.
  const uint32_t kSnapshotTime = 0xfd469ab8;
  MSVC_SUPPRESS_WARNING(4309);  // Truncation of constant value.
  const timeval kSnapshotTimeval = { static_cast<time_t>(kSnapshotTime), 0 };

  TestProcessSnapshot process_snapshot;
  process_snapshot.SetSnapshotTime(kSnapshotTimeval);

  auto system_snapshot = make_scoped_ptr(new TestSystemSnapshot());
  system_snapshot->SetCPUArchitecture(kCPUArchitectureX86_64);
  system_snapshot->SetOperatingSystem(SystemSnapshot::kOperatingSystemMacOSX);
  process_snapshot.SetSystem(system_snapshot.Pass());

  auto thread_snapshot = make_scoped_ptr(new TestThreadSnapshot());
  InitializeCPUContextX86_64(thread_snapshot->MutableContext(), 5);
  process_snapshot.AddThread(thread_snapshot.Pass());

  auto exception_snapshot = make_scoped_ptr(new TestExceptionSnapshot());
  InitializeCPUContextX86_64(exception_snapshot->MutableContext(), 11);
  process_snapshot.SetException(exception_snapshot.Pass());

  // The module does not have anything that needs to be represented in a
  // MinidumpModuleCrashpadInfo structure, so no such structure is expected to
  // be present, which will in turn suppress the addition of a
  // MinidumpCrashpadInfo stream.
  auto module_snapshot = make_scoped_ptr(new TestModuleSnapshot());
  process_snapshot.AddModule(module_snapshot.Pass());

  MinidumpFileWriter minidump_file_writer;
  minidump_file_writer.InitializeFromSnapshot(&process_snapshot);

  StringFile string_file;
  ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file));

  const MINIDUMP_DIRECTORY* directory;
  const MINIDUMP_HEADER* header =
      MinidumpHeaderAtStart(string_file.string(), &directory);
  ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 6, kSnapshotTime));
  ASSERT_TRUE(directory);

  EXPECT_EQ(kMinidumpStreamTypeSystemInfo, directory[0].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_SYSTEM_INFO>(
                  string_file.string(), directory[0].Location));

  EXPECT_EQ(kMinidumpStreamTypeMiscInfo, directory[1].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_MISC_INFO_4>(
                  string_file.string(), directory[1].Location));

  EXPECT_EQ(kMinidumpStreamTypeThreadList, directory[2].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_THREAD_LIST>(
                  string_file.string(), directory[2].Location));

  EXPECT_EQ(kMinidumpStreamTypeException, directory[3].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_EXCEPTION_STREAM>(
                  string_file.string(), directory[3].Location));

  EXPECT_EQ(kMinidumpStreamTypeModuleList, directory[4].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_MODULE_LIST>(
                  string_file.string(), directory[4].Location));

  EXPECT_EQ(kMinidumpStreamTypeMemoryList, directory[5].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_MEMORY_LIST>(
                  string_file.string(), directory[5].Location));
}

TEST(MinidumpFileWriter, InitializeFromSnapshot_CrashpadInfo) {
  const uint32_t kSnapshotTime = 0x15393bd3;
  const timeval kSnapshotTimeval = { static_cast<time_t>(kSnapshotTime), 0 };

  TestProcessSnapshot process_snapshot;
  process_snapshot.SetSnapshotTime(kSnapshotTimeval);

  auto system_snapshot = make_scoped_ptr(new TestSystemSnapshot());
  system_snapshot->SetCPUArchitecture(kCPUArchitectureX86_64);
  system_snapshot->SetOperatingSystem(SystemSnapshot::kOperatingSystemMacOSX);
  process_snapshot.SetSystem(system_snapshot.Pass());

  auto thread_snapshot = make_scoped_ptr(new TestThreadSnapshot());
  InitializeCPUContextX86_64(thread_snapshot->MutableContext(), 5);
  process_snapshot.AddThread(thread_snapshot.Pass());

  auto exception_snapshot = make_scoped_ptr(new TestExceptionSnapshot());
  InitializeCPUContextX86_64(exception_snapshot->MutableContext(), 11);
  process_snapshot.SetException(exception_snapshot.Pass());

  // The module needs an annotation for the MinidumpCrashpadInfo stream to be
  // considered useful and be included.
  auto module_snapshot = make_scoped_ptr(new TestModuleSnapshot());
  std::vector<std::string> annotations_list(1, std::string("annotation"));
  module_snapshot->SetAnnotationsVector(annotations_list);
  process_snapshot.AddModule(module_snapshot.Pass());

  MinidumpFileWriter minidump_file_writer;
  minidump_file_writer.InitializeFromSnapshot(&process_snapshot);

  StringFile string_file;
  ASSERT_TRUE(minidump_file_writer.WriteEverything(&string_file));

  const MINIDUMP_DIRECTORY* directory;
  const MINIDUMP_HEADER* header =
      MinidumpHeaderAtStart(string_file.string(), &directory);
  ASSERT_NO_FATAL_FAILURE(VerifyMinidumpHeader(header, 7, kSnapshotTime));
  ASSERT_TRUE(directory);

  EXPECT_EQ(kMinidumpStreamTypeSystemInfo, directory[0].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_SYSTEM_INFO>(
                  string_file.string(), directory[0].Location));

  EXPECT_EQ(kMinidumpStreamTypeMiscInfo, directory[1].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_MISC_INFO_4>(
                  string_file.string(), directory[1].Location));

  EXPECT_EQ(kMinidumpStreamTypeThreadList, directory[2].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_THREAD_LIST>(
                  string_file.string(), directory[2].Location));

  EXPECT_EQ(kMinidumpStreamTypeException, directory[3].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_EXCEPTION_STREAM>(
                  string_file.string(), directory[3].Location));

  EXPECT_EQ(kMinidumpStreamTypeModuleList, directory[4].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_MODULE_LIST>(
                  string_file.string(), directory[4].Location));

  EXPECT_EQ(kMinidumpStreamTypeCrashpadInfo, directory[5].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MinidumpCrashpadInfo>(
                  string_file.string(), directory[5].Location));

  EXPECT_EQ(kMinidumpStreamTypeMemoryList, directory[6].StreamType);
  EXPECT_TRUE(MinidumpWritableAtLocationDescriptor<MINIDUMP_MEMORY_LIST>(
                  string_file.string(), directory[6].Location));
}

TEST(MinidumpFileWriterDeathTest, SameStreamType) {
  MinidumpFileWriter minidump_file;

  const size_t kStream0Size = 5;
  const MinidumpStreamType kStream0Type = static_cast<MinidumpStreamType>(0x4d);
  const uint8_t kStream0Value = 0x5a;
  auto stream0 = make_scoped_ptr(
      new TestStream(kStream0Type, kStream0Size, kStream0Value));
  minidump_file.AddStream(stream0.Pass());

  // It is an error to add a second stream of the same type.
  const size_t kStream1Size = 3;
  const MinidumpStreamType kStream1Type = static_cast<MinidumpStreamType>(0x4d);
  const uint8_t kStream1Value = 0xa5;
  auto stream1 = make_scoped_ptr(
      new TestStream(kStream1Type, kStream1Size, kStream1Value));
  ASSERT_DEATH_CHECK(minidump_file.AddStream(stream1.Pass()),
                     "already present");
}

}  // namespace
}  // namespace test
}  // namespace crashpad


text:
/**
 * American English translation for bootstrap-datepicker
 */
;(function($){
	$.fn.datepicker.dates['en-US'] = {
		days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
		daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
		daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
		months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
		monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
		today: "Today",
		monthsTitle: "Months",
		clear: "Clear",
		weekStart: 0,
		format: "m/d/yyyy"
	};
}(jQuery));


text:
<?php
namespace Exzcute\EzTool;

use Exzcute\EzTool\models\Permission;
use Exzcute\EzTool\models\Menu;

class MenuManager
{
	public $permissions = [];
	public $config = [];
	public $active = null;
	public $actives = [];

	private $config_name = 'eztool.menu';

	public function __construct()
	{
		$this->config = config($this->config_name);
		$this->permissions = $this->config['permissions'];
	}

	private function _shareData()
	{
		view()->share('config', $this->config);
		view()->share('permissions', $this->permissions);
	}

	public function setPermission($permissions=[])
	{
		foreach ($permissions as $key => $value) {
			$this->permissions[$key] = $value;
			\Config::set("{$this->config_name}.permissions.$key", $value);
		}
		return $this->permissions;
	}

	public function getPermission()
	{
		return $this->permissions;
	}

	public function config($config=[])
	{
		foreach ($config as $key => $value) {
			$this->config[$key] = $value;
			\Config::set("{$this->config_name}.$key", $value);
		}
		return $this->config;
	}

	public function style()
	{
		$this->_shareData();

		return view('eztool::menu_manager.style');
	}

	public function script()
	{
		$this->_shareData();

		$permission_list = Permission::getList();

		return view('eztool::menu_manager.script')
		->with('permission_list',$permission_list);
	}

	public function loadStyle()
	{
		return '<link rel="stylesheet" href="'.url($this->config['style_url']).'">';
	}

	public function loadScript()
	{
		return '<script src="'.url($this->config['script_url']).'"></script>';
	}

	public function get()
	{
		return Menu::whereNull('parent')->orderBy('order')->get();
	}

	public function setActive($name)
	{
		$this->active = $name;
		return $name;
	}

	public function getActive($parent_id=null)
	{
		if($parent_id==null)
		{
			$menu = Menu::whereName($this->active)->first();
		}else{
			$menu = Menu::find($parent_id);
		}

		if($menu){
			$this->actives[] = $menu->name;
			if($menu->parent!=null){
				self::getActive($menu->parent);
			}
		}

		return $this->actives;
	}

	public function isActive($name)
	{
		if(!$this->actives)
		{
			self::getActive();
		}

		return in_array($name,$this->actives);
	}

	public function render()
	{
		$this->_shareData();

		if(!\Sentinel::hasAccess($this->permissions['view'])) return view('eztool::no_permission');

		return view('eztool::menu_manager.render');
	}

}


text:
import { handleSuccess, handleFailure } from './assert-promise';

function createAllowedTest(promise, successMessage, failureMessage, extraMessage) {
  async();
  extraMessage = extraMessage ? ' - ' + extraMessage : '';
  return promise
    .then(handleSuccess(successMessage + extraMessage), handleFailure(failureMessage + extraMessage))
    .finally(asyncDone);
}

function createForbidTest(promise, successMessage, failureMessage, extraMessage, statusCode) {
  if (extraMessage && !statusCode) {
    if (typeof extraMessage === 'number' || !isNaN(parseInt(extraMessage, 10))) {
      statusCode = extraMessage;
      extraMessage = null;
    }
  }
  async();
  extraMessage = extraMessage ? ' - ' + extraMessage : '';
  return promise
    .then(handleFailure(failureMessage + extraMessage))
    .catch(function(error) {
      if (statusCode) {
        equal(error.status || error.jqXHR && error.jqXHR.status, statusCode, "returns expected HTTP " + statusCode + " response");
      }
      return handleSuccess(successMessage + extraMessage)(error);
    })
    .finally(asyncDone);
}

function async() {
  QUnit.stop();
}
function asyncDone(arg) {
  QUnit.start();
  return arg;
}

export { createAllowedTest, createForbidTest };


text:
absolute_path() {
  (cd "$1" && pwd)
}

scripts_path=$(absolute_path "$(dirname "$0")")

fly -t production set-pipeline \
    -p bosh-agent \
    -c $scripts_path/pipeline.yml \
    --load-vars-from <(lpass show -G "bosh-agent concourse secrets" --notes)


text:
package org.thilanka.messaging.domain;

import org.thilanka.device.pin.PinDirection;
import org.thilanka.device.pin.PinProperty;
import org.thilanka.device.pin.PinValue;

/**
 * The java class that represents the payload that gets serialized to json and
 * back during the communication with AppInventor and the AndroidThings board.
 *
 * @author Thilanka Munasinghe (thilankawillbe@gmail.com)
 *
 */
public class Payload {

  private PeripheralIO mPeripheralIO;

  private Action mAction;

  private String mName;

  private PinProperty mProperty;

  private PinValue mValue;

  private String mAndroidThingsBoard;

  private PinDirection mDirection;

  private String mLabel = "default";

  private double mDoubleValue;

  /**
   * @return the PeripheralIO
   */
  public PeripheralIO getPeripheralIO() {
    return mPeripheralIO;
  }

  /**
   * @param pPeripheralIO
   *          the PeripheralIO to set
   */
  public void setPeripheralIO(PeripheralIO pPeripheralIO) {
    mPeripheralIO = pPeripheralIO;
  }

  /**
   * @return what type of message action this is.
   */
  public Action getAction() {
    return mAction;
  }

  /**
   * Sets the given message action for this GPIO pin.
   *
   * @param pAction
   */
  public void setAction(Action pAction) {
    mAction = pAction;
  }

  /**
   * @return the corresponding name of the pin.
   */
  public String getName() {
    return mName;
  }

  /**
   * @param pName
   *          the name of the pin to set
   */
  public void setName(String pName) {
    mName = pName;
  }

  /**
   * @return the property
   */
  public PinProperty getProperty() {
    return mProperty;
  }

  /**
   * @param property
   *          the property to set
   */
  public void setProperty(PinProperty pProperty) {
    mProperty = pProperty;
  }

  /**
   * @return the value
   */
  public PinValue getValue() {
    return mValue;
  }

  /**
   * @param pValue
   *          the value to set
   */
  public void setValue(PinValue pValue) {
    mValue = pValue;
  }

  /**
   * @return the value if it is a double.
   */
  public double getDoubleValue() {
    return mDoubleValue;
  }

  /**
   * Set the value if it is a double
   *
   * @param pDoubleValue
   */
  public void setDoubleValue(double pDoubleValue) {
    mDoubleValue = pDoubleValue;
  }

  /**
   * @return the AndroidThingsBoard
   */
  public String getAndroidThingsBoard() {
    return mAndroidThingsBoard;
  }

  /**
   * @param pAndroidThingsBoard
   *          the AndroidThingsBoard to set
   */
  public void setAndroidThingsBoard(String pAndroidThingsBoard) {
    mAndroidThingsBoard = pAndroidThingsBoard;
  }

  /**
   * @return the Direction
   */
  public PinDirection getDirection() {
    return mDirection;
  }

  /**
   * @param pDirection
   *          the direction to set
   */
  public void setDirection(PinDirection pDirection) {
    mDirection = pDirection;
  }

  /**
   * @return the label
   */
  public String getLabel() {
    return mLabel;
  }

  /**
   * @param pLabel
   *          the label to set
   */
  public void setLabel(String pLabel) {
    mLabel = pLabel;
  }

  public boolean isInvalid() {
    // TODO Auto-generated method stub
    return false;
  }

  @Override
  public String toString() {
    return getClass().getSimpleName() + " [Peripheral IO : " + mPeripheralIO
        + "number:" + mName + ", property:"
        + (mProperty == null ? "" : mProperty.toString())
        + ", value:" + (mValue == null ? "" : mValue.toString())
        + ", doubleValue:" + mDoubleValue
        + ", androidThingsBoard:"
        + mAndroidThingsBoard + ", direction:" + (mDirection == null
            ? PinDirection.IN.toString() : mDirection.toString())
        + ", label: " + mLabel + "]";
  }
}


text:
Modify Jekyll's Site, Pages and Posts at different points during the site processing stream.

[![Build Status](https://travis-ci.org/octopress/hooks.svg)](https://travis-ci.org/octopress/hooks)
[![Gem Version](http://img.shields.io/gem/v/octopress-hooks.svg)](https://rubygems.org/gems/octopress-hooks)
[![License](http://img.shields.io/:license-mit-blue.svg)](http://octopress.mit-license.org)

## Installation

Add this line to your application's Gemfile:

    gem 'octopress-hooks'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install octopress-hooks

## Hook timeline

This is the order in which hooks are triggered.

1. Site `reset`
2. Site `pre_read`
3. Site `post_read`
4. Post/Page/Document `post_init`
5. Site `pre_render`
6. Site `merge_payload`
5. Post/Page/Document `pre_render`
7. Post/Page/Document `merge_payload`
8. Post/Page/Document `post_render`
9. Post/Page/Document `post_write`
10. Site `post_write`

## Usage

First extend the appropriate Hook class.

- `Octopress::Hooks::Site` - access Jekyll's Site instance.
- `Octopress::Hooks::Page` - access to each of Jekyll's Page instances.
- `Octopress::Hooks::Post` - access to each of Jekyll's Post instances.
- `Octopress::Hooks::Document` - access to each of Jekyll's Collection Documents instances.

Then add a method based on when you want to trigger your hooks.

#### Site Hooks

The Site class has three methods. Here's an example.

```ruby
class MySiteHook < Octopress::Hooks::Site
  def reset(site)
  end

  def pre_read(site)
  end

  def post_read(site)
  end

  def pre_render(site)
  end

  # Return a hash to merge into payload
  #
  def merge_payload(payload, site)
    {}
  end

  def post_write(site)
  end
end
```

Use the `reset` hook to reset variables to before each build. It's mostly useful to support `--watch` builds.

Use the `pre_read` hook to modify the site instance before posts, pages and static files are read.

Use the `post_read` hook to modify the site instance after posts, pages and static files are read but before generators are triggered.

Use the `pre_render` hook to modify the site instance before posts and pages are rendered.

Use the `merge_paylod` hook to modify the site payload or merge custom data into it. This data will be available to all documents when they are rendered. This method must return a hash.

Use the `post_write` to trigger and action after all documents have been written to disk.

#### Post/Page/Documents hooks

The Page, Post and Document hooks have four methods and are identical except that Post hooks only operate on posts, and Page hooks only operate on pages and Document hooks only Operate on Collection Documents. Here's an example of a Page hook.

```ruby
class MyPageHook < Octopress::Hooks::Page

  def post_init(page)
  end

  def pre_render(page)
  end

  # Return a hash to merge into payload
  #
  def merge_payload(payload, page)
    {}
  end

  def post_render(page)
  end

  def post_write(page)
  end
end
```

The `post_init` method lets you access the post or page class instance immediately after it has been initialized. This allows you to
modify the instance before the Site compiles its payload, which includes arrays of each page and post.

With `pre_render` you can parse and modify page contents before it is processed by Liquid, Markdown, Textile and the like, and rendered to HTML.

Use the `merge_paylod` hook to modify the page and site payload or merge custom data into it. Changes to the payload will only affect this page when it is rendered. This method must return a hash to be merged.

With `post_render` you can access pages and posts after it has been converted into HTML. You might use this option if you want to modify generated HTML. At this stage, be sure to modify the `page.output` if you want change what the page displays.

With `post_write` you can execute a code block after a page or post has been successfully written to disk.

To work with all page types, you'd do something like this.

```ruby
module Toaster
  class ProcessAll < Octopress::Hooks::All
    def pre_render(item)
      item.content.gsub!(/bread/, 'toast')
    end
  end
end
```

To process pages, posts, or documents individually, you'd do this.

```ruby
module Samurai
  class ProcessPosts < Octopress::Hooks::Post
    def pre_render(post)
      post.gsub!(/bread/, 'sliced bread')
    end
  end

  class ProcessPages < Octopress::Hooks::Page
    def pre_render(page)
      post.gsub!(/bread/, 'sliced bread')
    end
  end

  class ProcessPages < Octopress::Hooks::Document
    def pre_render(page)
      post.gsub!(/bread/, 'sliced bread')
    end
  end
end
```

## Contributing

1. Fork it ( https://github.com/octopress/hooks/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package org.apache.camel.model;

import java.io.InputStream;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.impl.JndiRegistry;
import org.junit.Test;

public class LoadRouteFromXmlWithOnExceptionTest extends ContextTestSupport {

    @Override
    protected JndiRegistry createRegistry() throws Exception {
        JndiRegistry jndi = super.createRegistry();
        jndi.bind("myProcessor", new MyProcessor());
        return jndi;
    }

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    @Test
    public void testLoadRouteFromXmlWitOnException() throws Exception {
        InputStream is = getClass().getResourceAsStream("barOnExceptionRoute.xml");
        context.addRouteDefinitions(is);
        context.start();

        assertNotNull("Loaded bar route should be there", context.getRoute("bar"));
        assertEquals(1, context.getRoutes().size());

        // test that loaded route works
        getMockEndpoint("mock:bar").expectedBodiesReceived("Bye World");
        getMockEndpoint("mock:error").expectedBodiesReceived("Kabom");

        template.sendBody("direct:bar", "Bye World");
        template.sendBody("direct:bar", "Kabom");

        assertMockEndpointsSatisfied();
    }

    private static final class MyProcessor implements Processor {

        public void process(Exchange exchange) throws Exception {
            String body = exchange.getIn().getBody(String.class);
            if ("Kabom".equals(body)) {
                throw new IllegalArgumentException("Damn");
            }
        }
    }
}


text:
<?php
class Search_class extends MY_Model
{

	private $tbl_pages = 'pages';
	private $tbl_articles = 'articles';

	// ------------------------ PUBLIC METHODS ------------------------ //

	/**
	 * I initiate this class
	 * @access public
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();
	}

	/**
	 * I return records matching a search term
	 * @access public
	 * @param string $search_term
	 * @param array $search_result_exclusions the slugs of pages to exclude from search results
	 * @return array
	 */
	function get_search_results($search_term, $search_result_exclusions)
	{
		$search_term = $this->db->escape_str($search_term);
		return $this->db->query('
			SELECT id, slug, title, content, \'page\' AS type
			FROM ' . $this->tbl_pages . '
			WHERE 1 = 1
			AND FIND_IN_SET(slug, \'' . implode(',',$search_result_exclusions) . '\') = 0
			AND (
				title LIKE \'%' . $search_term . '%\'
				OR content LIKE \'%' . $search_term . '%\'
			)
			UNION
			SELECT id, slug, title, content, \'article\' AS type
			FROM ' . $this->tbl_articles . '
			WHERE title LIKE \'%' . $search_term . '%\'
				OR content LIKE \'%' . $search_term . '%\'

			ORDER BY title
		');
	}

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>net.aimeizi</groupId>
		<artifactId>hibernate-search-example</artifactId>
		<version>1.0.0</version>
	</parent>

	<artifactId>hibernate-example</artifactId>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>log4j-over-slf4j</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jul-to-slf4j</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>p6spy</groupId>
			<artifactId>p6spy</artifactId>
		</dependency>
		<dependency>
			<groupId>com.googlecode.log4jdbc</groupId>
			<artifactId>log4jdbc</artifactId>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<exclusions>
				<exclusion>
					<artifactId>commons-lang</artifactId>
					<groupId>commons-lang</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<exclusions>
				<exclusion>
					<artifactId>spring-aop</artifactId>
					<groupId>org.springframework</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
		</dependency>

		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.0-api</artifactId>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-search</artifactId>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-search-analyzers</artifactId>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-search-infinispan</artifactId>
		</dependency>

		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache-core</artifactId>
		</dependency>

		<dependency>
			<groupId>IKAnalyzer</groupId>
			<artifactId>IKAnalyzer</artifactId>
		</dependency>

		<dependency>
			<groupId>net.paoding.analysis.analyzer</groupId>
			<artifactId>paoding-analyzer</artifactId>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
		</dependency>

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
		</dependency>

		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>

	</dependencies>

	<build>
		<finalName>hibernate-example</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat6-maven-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>maven-jetty-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>jboss-maven-plugin</artifactId>
				<configuration>
					<hostName>localhost</hostName>
					<port>8080</port>
					<jbossHome>D:/jboss-4.2.3.GA</jbossHome>
					<fileName>target/maven-framework.war</fileName>
					<serverName>all</serverName>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.jboss.as.plugins</groupId>
				<artifactId>jboss-as-maven-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>false</downloadJavadocs>
					<wtpversion>2.0</wtpversion>
					<additionalConfig>
						<file>
							<name>.settings/org.eclipse.core.resources.prefs</name>
							<content>
						<![CDATA[eclipse.preferences.version=1${line.separator}encoding/<project>=${project.build.sourceEncoding}${line.separator}]]>
							</content>
						</file>
					</additionalConfig>
				</configuration>
			</plugin>

		</plugins>
	</build>
</project>


text:
@implementation PhotoSeriesEntity

@dynamic addr;
@dynamic comment_count;
@dynamic cover_url;
@dynamic descriptions;
@dynamic dig_count;
@dynamic feed_id;
@dynamic images;
@dynamic is_repost;
@dynamic publish_time;
@dynamic recommend_content;
@dynamic recommend_count;
@dynamic repost_count;
@dynamic topic;
@dynamic uid;

@end


text:
{% extends "website/base.html" %}
{% load website_tags wagtailcore_tags wagtailimages_tags %}

{% block content %}

      {{ intro|richtext }}

        {% for webimage in self.webimages %}
          {% if webimage.author and webimage.license %}

              {% image webimage original as rendition %}
              {% image webimage fill-35x35-c100 %}
              {{webimage.title}}, by
              {% if webimage.source %}
                {{webimage.author}},
              {% else %}
                {{webimage.author}},
              {% endif %}
              {% if webimage.license == 'Consent' %}
                 Proprietary: Consent granted ({{website.notes}})
              {% elif webimage.license == 'Other' %}
                 {{website.notes}}
              {% else %}
                 {% license_link webimage.license %}
              {% endif %}

          {% endif %}
        {% endfor %}

{% endblock %}


text:
<?php

namespace Symfony\Component\Ldap\Tests\Security;

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Ldap\Adapter\CollectionInterface;
use Symfony\Component\Ldap\Adapter\QueryInterface;
use Symfony\Component\Ldap\Entry;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Ldap\Security\CheckLdapCredentialsListener;
use Symfony\Component\Ldap\Security\LdapBadge;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\Event\CheckPassportEvent;
use Symfony\Contracts\Service\ServiceLocatorTrait;

class CheckLdapCredentialsListenerTest extends TestCase
{
    private $ldap;

    protected function setUp(): void
    {
        if (!interface_exists(AuthenticatorInterface::class)) {
            $this->markTestSkipped('This test requires symfony/security-http:^5.1');
        }

        $this->ldap = $this->createMock(LdapInterface::class);
    }

    /**
     * @dataProvider provideShouldNotCheckPassport
     */
    public function testShouldNotCheckPassport($authenticator, $passport)
    {
        $this->ldap->expects($this->never())->method('bind');

        $listener = $this->createListener();
        $listener->onCheckPassport(new CheckPassportEvent($authenticator, $passport));
    }

    public function provideShouldNotCheckPassport()
    {
        if (!interface_exists(AuthenticatorInterface::class)) {
            $this->markTestSkipped('This test requires symfony/security-http:^5.1');
        }

        // no LdapBadge
        yield [new TestAuthenticator(), new Passport(new UserBadge('test'), new PasswordCredentials('s3cret'))];

        // ldap already resolved
        $badge = new LdapBadge('app.ldap');
        $badge->markResolved();
        yield [new TestAuthenticator(), new Passport(new UserBadge('test'), new PasswordCredentials('s3cret'), [$badge])];
    }

    public function testPasswordCredentialsAlreadyResolvedThrowsException()
    {
        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('LDAP authentication password verification cannot be completed because something else has already resolved the PasswordCredentials.');

        $badge = new PasswordCredentials('s3cret');
        $badge->markResolved();
        $passport = new Passport(new UserBadge('test'), $badge, [new LdapBadge('app.ldap')]);

        $listener = $this->createListener();
        $listener->onCheckPassport(new CheckPassportEvent(new TestAuthenticator(), $passport));
    }

    public function testInvalidLdapServiceId()
    {
        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('Cannot check credentials using the "not_existing_ldap_service" ldap service, as such service is not found. Did you maybe forget to add the "ldap" service tag to this service?');

        $listener = $this->createListener();
        $listener->onCheckPassport($this->createEvent('s3cr3t', new LdapBadge('not_existing_ldap_service')));
    }

    /**
     * @dataProvider provideWrongPassportData
     */
    public function testWrongPassport($passport)
    {
        $this->expectException(\LogicException::class);
        $this->expectExceptionMessage('LDAP authentication requires a passport containing a user and password credentials, authenticator "'.TestAuthenticator::class.'" does not fulfill these requirements.');

        $listener = $this->createListener();
        $listener->onCheckPassport(new CheckPassportEvent(new TestAuthenticator(), $passport));
    }

    public function provideWrongPassportData()
    {
        if (!interface_exists(AuthenticatorInterface::class)) {
            $this->markTestSkipped('This test requires symfony/security-http:^5.1');
        }

        // no password credentials
        yield [new SelfValidatingPassport(new UserBadge('test'), [new LdapBadge('app.ldap')])];

        // no user passport
        $passport = $this->createMock(PassportInterface::class);
        $passport->expects($this->any())->method('hasBadge')->with(LdapBadge::class)->willReturn(true);
        $passport->expects($this->any())->method('getBadge')->with(LdapBadge::class)->willReturn(new LdapBadge('app.ldap'));
        yield [$passport];
    }

    public function testEmptyPasswordShouldThrowAnException()
    {
        $this->expectException(BadCredentialsException::class);
        $this->expectExceptionMessage('The presented password cannot be empty.');

        $listener = $this->createListener();
        $listener->onCheckPassport($this->createEvent(''));
    }

    public function testBindFailureShouldThrowAnException()
    {
        $this->expectException(BadCredentialsException::class);
        $this->expectExceptionMessage('The presented password is invalid.');

        $this->ldap->expects($this->any())->method('bind')->willThrowException(new ConnectionException());

        $listener = $this->createListener();
        $listener->onCheckPassport($this->createEvent());
    }

    public function testQueryForDn()
    {
        $collection = new \ArrayIterator([new Entry('')]);

        $query = $this->getMockBuilder(QueryInterface::class)->getMock();
        $query->expects($this->once())->method('execute')->willReturn($collection);

        $this->ldap->expects($this->at(0))->method('bind')->with('elsa', 'test1234A$');
        $this->ldap->expects($this->any())->method('escape')->with('Wouter', '', LdapInterface::ESCAPE_FILTER)->willReturn('wouter');
        $this->ldap->expects($this->once())->method('query')->with('{username}', 'wouter_test')->willReturn($query);

        $listener = $this->createListener();
        $listener->onCheckPassport($this->createEvent('s3cr3t', new LdapBadge('app.ldap', '{username}', 'elsa', 'test1234A$', '{username}_test')));
    }

    public function testEmptyQueryResultShouldThrowAnException()
    {
        $this->expectException(BadCredentialsException::class);
        $this->expectExceptionMessage('The presented username is invalid.');

        $collection = $this->getMockBuilder(CollectionInterface::class)->getMock();

        $query = $this->getMockBuilder(QueryInterface::class)->getMock();
        $query->expects($this->once())->method('execute')->willReturn($collection);

        $this->ldap->expects($this->at(0))->method('bind')->with('elsa', 'test1234A$');
        $this->ldap->expects($this->once())->method('query')->willReturn($query);

        $listener = $this->createListener();
        $listener->onCheckPassport($this->createEvent('s3cr3t', new LdapBadge('app.ldap', '{username}', 'elsa', 'test1234A$', '{username}_test')));
    }

    private function createEvent($password = 's3cr3t', $ldapBadge = null)
    {
        return new CheckPassportEvent(
            new TestAuthenticator(),
            new Passport(new UserBadge('Wouter', function () { return new User('Wouter', null, ['ROLE_USER']); }), new PasswordCredentials($password), [$ldapBadge ?? new LdapBadge('app.ldap')])
        );
    }

    private function createListener()
    {
        $ldapLocator = new class(['app.ldap' => function () {
            return $this->ldap;
        }]) implements ContainerInterface {
            use ServiceLocatorTrait;
        };

        return new CheckLdapCredentialsListener($ldapLocator);
    }
}

if (interface_exists(AuthenticatorInterface::class)) {
    class TestAuthenticator implements AuthenticatorInterface
    {
        public function supports(Request $request): ?bool
        {
        }

        public function authenticate(Request $request): PassportInterface
        {
        }

        public function createAuthenticatedToken(PassportInterface $passport, string $firewallName): TokenInterface
        {
        }

        public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
        {
        }

        public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
        {
        }
    }
}


text:
// /  Created by Jesse MacFadyen on 10-05-29.
//  Copyright 2010 Nitobi. All rights reserved.
//  Copyright 2012, Randy McMillan

#import "ChildBrowserViewController.h"

@implementation ChildBrowserViewController

@synthesize imageURL, isImage;
@synthesize delegate, orientationDelegate;
@synthesize spinner, webView, addressLabel;
@synthesize closeBtn, refreshBtn, backBtn, fwdBtn, safariBtn;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

+ (NSString*)resolveImageResource:(NSString*)resource
{
    NSString* systemVersion = [[UIDevice currentDevice] systemVersion];
    BOOL isLessThaniOS4 = ([systemVersion compare:@"4.0" options:NSNumericSearch] == NSOrderedAscending);

    if (isLessThaniOS4) {
        return [NSString stringWithFormat:@"%@.png", resource];
    } else {
        if (([[UIScreen mainScreen] respondsToSelector:@selector(scale)] == YES) && ([[UIScreen mainScreen] scale] == 2.00)) {
            return [NSString stringWithFormat:@"%@@2x.png", resource];
        }
    }

    return resource; // if all else fails
}

- (ChildBrowserViewController*)initWithScale:(BOOL)enabled
{
    self = [super init];
    self.scaleEnabled = enabled;
    return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.refreshBtn.image = [UIImage imageNamed:[[self class] resolveImageResource:@"ChildBrowser.bundle/but_refresh"]];
    self.backBtn.image = [UIImage imageNamed:[[self class] resolveImageResource:@"ChildBrowser.bundle/arrow_left"]];
    self.fwdBtn.image = [UIImage imageNamed:[[self class] resolveImageResource:@"ChildBrowser.bundle/arrow_right"]];
    self.safariBtn.image = [UIImage imageNamed:[[self class] resolveImageResource:@"ChildBrowser.bundle/compass"]];

    self.webView.delegate = self;
    self.webView.scalesPageToFit = TRUE;
    self.webView.backgroundColor = [UIColor whiteColor];
    NSLog(@"View did load");
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    NSLog(@"View did UN-load");
}

- (void)dealloc
{
    self.webView.delegate = nil;
    self.delegate = nil;
    self.orientationDelegate = nil;

#if !__has_feature(objc_arc)
    self.webView = nil;
    self.closeBtn = nil;
    self.refreshBtn = nil;
    self.addressLabel = nil;
    self.backBtn = nil;
    self.fwdBtn = nil;
    self.safariBtn = nil;
    self.spinner = nil;

    [super dealloc];
#endif
}

- (void)closeBrowser
{
    if (self.delegate != nil) {
        [self.delegate onClose];
    }
    if ([self respondsToSelector:@selector(presentingViewController)]) {
        // Reference UIViewController.h Line:179 for update to iOS 5 difference - @RandyMcMillan
        [[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
    } else {
        [[self parentViewController] dismissModalViewControllerAnimated:YES];
    }
}

- (IBAction)onDoneButtonPress:(id)sender
{
    [self closeBrowser];
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]];
    [self.webView loadRequest:request];
}

- (IBAction)onSafariButtonPress:(id)sender
{
    if (self.delegate != nil) {
        [self.delegate onOpenInSafari];
    }

    if (self.isImage) {
        NSURL* pURL = [NSURL URLWithString:self.imageURL];
        [[UIApplication sharedApplication] openURL:pURL];
    } else {
        NSURLRequest* request = self.webView.request;
        [[UIApplication sharedApplication] openURL:request.URL];
    }
}

- (void)loadURL:(NSString*)url
{
    NSLog(@"Opening Url : %@", url);

    if ([url hasSuffix:@".png"] ||
        [url hasSuffix:@".jpg"] ||
        [url hasSuffix:@".jpeg"] ||
        [url hasSuffix:@".bmp"] ||
        [url hasSuffix:@".gif"]) {
        self.imageURL = nil;
        self.imageURL = url;
        self.isImage = YES;
        NSString* htmlText = @"";
        htmlText = [htmlText stringByReplacingOccurrencesOfString:@"IMGSRC" withString:url];

        [self.webView loadHTMLString:htmlText baseURL:[NSURL URLWithString:@""]];
    } else {
        self.imageURL = @"";
        self.isImage = NO;
        NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
        [self.webView loadRequest:request];
    }
    self.webView.hidden = NO;
}

- (void)webViewDidStartLoad:(UIWebView*)sender
{
    self.addressLabel.text = @"Loading...";
    self.backBtn.enabled = self.webView.canGoBack;
    self.fwdBtn.enabled = self.webView.canGoForward;

    [self.spinner startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView*)sender
{
    NSURLRequest* request = self.webView.request;

    NSLog(@"New Address is : %@", request.URL.absoluteString);
    self.addressLabel.text = request.URL.absoluteString;
    self.backBtn.enabled = self.webView.canGoBack;
    self.fwdBtn.enabled = self.webView.canGoForward;
    [self.spinner stopAnimating];

    if (self.delegate != NULL) {
        [self.delegate onChildLocationChange:request.URL.absoluteString];
    }
}

/*- (void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error {
    NSLog (@"webView:didFailLoadWithError");
    [spinner stopAnimating];
    addressLabel.text = @"Failed";
    if (error != NULL) {
        UIAlertView *errorAlert = [[UIAlertView alloc]
                                   initWithTitle: [error localizedDescription]
                                   message: [error localizedFailureReason]
                                   delegate:nil
                                   cancelButtonTitle:@"OK"
                                   otherButtonTitles:nil];
        [errorAlert show];
        [errorAlert release];
    }
}
*/

#pragma mark CDVOrientationDelegate

- (BOOL)shouldAutorotate
{
    if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotate)]) {
        return [self.orientationDelegate shouldAutorotate];
    }

    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(supportedInterfaceOrientations)]) {
        return [self.orientationDelegate supportedInterfaceOrientations];
    }

    return UIInterfaceOrientationPortrait;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ((self.orientationDelegate != nil) && [self.orientationDelegate respondsToSelector:@selector(shouldAutorotateToInterfaceOrientation:)]) {
        return [self.orientationDelegate shouldAutorotateToInterfaceOrientation:interfaceOrientation];
    }

    return YES;
}

@end


text:
package com.opengamma.masterdb.security.hibernate.future;

/**
 * A Hibernate bean representation of
 * {@link com.opengamma.financial.security.future.StockFutureSecurity}.
 */
public class StockFutureBean extends FutureSecurityBean {

  @Override
  public <T> T accept(final Visitor<T> visitor) {
    return visitor.visitStockFutureType(this);
  }

}