text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// ==++==
//

//
// ==--==
#ifndef __exts_h__
#define __exts_h__

#define KDEXT_64BIT

#include <windows.h>
#include <winternl.h>

#if defined(_MSC_VER)
#pragma warning(disable:4245)   // signed/unsigned mismatch
#pragma warning(disable:4100)   // unreferenced formal parameter
#pragma warning(disable:4201)   // nonstandard extension used : nameless struct/union
#pragma warning(disable:4127)   // conditional expression is constant
#pragma warning(disable:4430)   // missing type specifier: C++ doesn't support default-int
#endif
#include "strike.h"

#include <wdbgexts.h>
#include <dbgeng.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// wdbgexts.h defines StackTrace which interferes with other parts of the
// system that use the StackTrace identifier
#ifdef StackTrace
#undef StackTrace
#endif

#include "platformspecific.h"

// We need to define the target address type.  This has to be used in the
// functions that read directly from the debuggee address space, vs. using
// the DAC to read the DAC-ized data structures.
#include "daccess.h"

// Convert between CLRDATA_ADDRESS and TADDR.
#define TO_TADDR(cdaddr) ((TADDR)(cdaddr))
#define TO_CDADDR(taddr) ((CLRDATA_ADDRESS)(LONG_PTR)(taddr))

// We also need a "correction" macro: there are a number of places in the DAC
// where instead of using the CLRDATA_ADDRESS sign-extension convention
// we 0-extend (most notably DacpGcHeapDetails)
#define NEED_DAC_CLRDATA_ADDRESS_CORRECTION 1
#if NEED_DAC_CLRDATA_ADDRESS_CORRECTION == 1
    // the macro below "corrects" a CDADDR to always represent the
    // sign-extended equivalent ULONG64 value of the original TADDR
    #define UL64_TO_CDA(ul64) (TO_CDADDR(TO_TADDR(ul64)))
#else
    #define UL64_TO_CDA(ul64) (ul64)
#endif // NEED_DAC_CLRDATA_ADDRESS_CORRECTION 1

// The macro below removes the sign extension, returning the
// equivalent ULONG64 value to the original TADDR. Useful when
// printing CDA values.
#define CDA_TO_UL64(cda) ((ULONG64)(TO_TADDR(cda)))

typedef struct _TADDR_RANGE
{
    TADDR start;
    TADDR end;
} TADDR_RANGE;

typedef struct _TADDR_SEGINFO
{
    TADDR segAddr;
    TADDR start;
    TADDR end;
} TADDR_SEGINFO;

#include "util.h"

#ifdef __cplusplus
extern "C" {
#endif

// Cleanup tasks to be executed when the extension is unloaded
class OnUnloadTask
{
public:
    FORCEINLINE static void Register(void (*fn)())
    {
        // append a new unload task to the head of the list
        OnUnloadTask *pNew = new OnUnloadTask(fn);
        pNew->pNext = s_pUnloadTaskList;
        s_pUnloadTaskList = pNew;
    }

    static void Run()
    {
        // walk the list of UnloadTasks and execute each in turn
        OnUnloadTask* pCur = s_pUnloadTaskList;
        while (pCur != NULL)
        {
            OnUnloadTask* pNext = pCur->pNext;
            pCur->OnUnloadFn();
            delete pCur;
            pCur = pNext;
        }
        s_pUnloadTaskList = NULL;
    }

private:
    OnUnloadTask(void(*fn)())
        : OnUnloadFn(fn)
        , pNext(NULL)
    { }

private:
    void (*OnUnloadFn)();
    OnUnloadTask* pNext;

    static OnUnloadTask *s_pUnloadTaskList;
};

#ifndef MINIDUMP

#define EXIT_API     ExtRelease

// Safe release and NULL.
#define EXT_RELEASE(Unk) \
    ((Unk) != NULL ? ((Unk)->Release(), (Unk) = NULL) : NULL)

extern PDEBUG_CONTROL2       g_ExtControl;
extern PDEBUG_DATA_SPACES    g_ExtData;
extern PDEBUG_SYMBOLS        g_ExtSymbols;
extern PDEBUG_SYSTEM_OBJECTS g_ExtSystem;
extern PDEBUG_REGISTERS      g_ExtRegisters;

#ifndef FEATURE_PAL

// Global variables initialized by query.
extern PDEBUG_CLIENT         g_ExtClient;
extern PDEBUG_DATA_SPACES2   g_ExtData2;
extern PDEBUG_SYMBOLS2       g_ExtSymbols2;
extern PDEBUG_ADVANCED3      g_ExtAdvanced3;

#else // FEATURE_PAL

extern ILLDBServices*        g_ExtServices;

#endif // FEATURE_PAL

HRESULT
ExtQuery(PDEBUG_CLIENT client);

HRESULT
ArchQuery(void);

void
ExtRelease(void);

#ifdef _DEBUG
extern DWORD_PTR g_filterHint;
#endif

extern BOOL ControlC;

inline BOOL IsInterrupt()
{
    if (!ControlC && g_ExtControl->GetInterrupt() == S_OK)
    {
        ExtOut("Command cancelled at the user's request.\n");
        ControlC = TRUE;
    }

    return ControlC;
}

//
// undef the wdbgexts
//
#undef DECLARE_API

#define DECLARE_API(extension)     \
CPPMOD HRESULT CALLBACK extension(PDEBUG_CLIENT client, PCSTR args)

class __ExtensionCleanUp
{
public:
    __ExtensionCleanUp(){}
    ~__ExtensionCleanUp(){ExtRelease();}
};

inline void EENotLoadedMessage(HRESULT Status)
{
    ExtOut("Failed to find runtime DLL (%s), 0x%08x\n", MAKEDLLNAME_A("coreclr"), Status);
    ExtOut("Extension commands need it in order to have something to do.\n");
}

inline void DACMessage(HRESULT Status)
{
    ExtOut("Failed to load data access DLL, 0x%08x\n", Status);
#ifndef FEATURE_PAL
    ExtOut("Verify that 1) you have a recent build of the debugger (6.2.14 or newer)\n");
    ExtOut("            2) the file mscordacwks.dll that matches your version of coreclr.dll is \n");
    ExtOut("                in the version directory or on the symbol path\n");
    ExtOut("            3) or, if you are debugging a dump file, verify that the file \n");
    ExtOut("                mscordacwks_<arch>_<arch>_<version>.dll is on your symbol path.\n");
    ExtOut("            4) you are debugging on supported cross platform architecture as \n");
    ExtOut("                the dump file. For example, an ARM dump file must be debugged\n");
    ExtOut("                on an X86 or an ARM machine; an AMD64 dump file must be\n");
    ExtOut("                debugged on an AMD64 machine.\n");
    ExtOut("\n");
    ExtOut("You can also run the debugger command .cordll to control the debugger's\n");
    ExtOut("load of mscordacwks.dll.  .cordll -ve -u -l will do a verbose reload.\n");
    ExtOut("If that succeeds, the SOS command should work on retry.\n");
    ExtOut("\n");
    ExtOut("If you are debugging a minidump, you need to make sure that your executable\n");
    ExtOut("path is pointing to coreclr.dll as well.\n");
#else // FEATURE_PAL
    if (Status == CORDBG_E_MISSING_DEBUGGER_EXPORTS)
    {
        ExtOut("You can run the debugger command 'setclrpath' to control the load of %s.\n", MAKEDLLNAME_A("mscordaccore"));
        ExtOut("If that succeeds, the SOS command should work on retry.\n");
    }
    else
    {
        ExtOut("Can not load or initialize %s. The target runtime may not be initialized.\n", MAKEDLLNAME_A("mscordaccore"));
    }
#endif // FEATURE_PAL
}

HRESULT CheckEEDll();

#define INIT_API_NOEE()                                         \
    HRESULT Status;                                             \
    __ExtensionCleanUp __extensionCleanUp;                      \
    if ((Status = ExtQuery(client)) != S_OK) return Status;     \
    if ((Status = ArchQuery()) != S_OK)      return Status;     \
    ControlC = FALSE;                                           \
    g_bDacBroken = TRUE;                                        \
    g_clrData = NULL;                                           \
    g_sos = NULL;

#define INIT_API_EE()                                           \
    if ((Status = CheckEEDll()) != S_OK)                        \
    {                                                           \
        EENotLoadedMessage(Status);                             \
        return Status;                                          \
    }

#define INIT_API_NODAC()                                        \
    INIT_API_NOEE()                                             \
    INIT_API_EE()

#define INIT_API_DAC()                                          \
    if ((Status = LoadClrDebugDll()) != S_OK)                   \
    {                                                           \
        DACMessage(Status);                                     \
        return Status;                                          \
    }                                                           \
    g_bDacBroken = FALSE;                                       \
    /* If LoadClrDebugDll() succeeded make sure we release g_clrData. */  \
    /* We may reconsider caching g_clrData in the future */     \
    ToRelease<IXCLRDataProcess> spIDP(g_clrData);               \
    ToRelease<ISOSDacInterface> spISD(g_sos);                   \
    ResetGlobals();

#define INIT_API()                                              \
    INIT_API_NODAC()                                            \
    INIT_API_DAC()

// Attempt to initialize DAC and SOS globals, but do not "return" on failure.
// Instead, mark the failure to initialize the DAC by setting g_bDacBroken to TRUE.
// This should be used from extension commands that should work OK even when no
// runtime is loaded in the debuggee, e.g. DumpLog, DumpStack. These extensions
// and functions they call should test g_bDacBroken before calling any DAC enabled
// feature.
#define INIT_API_NO_RET_ON_FAILURE()                            \
    INIT_API_NOEE()                                             \
    if ((Status = CheckEEDll()) != S_OK)                        \
    {                                                           \
        ExtOut("Failed to find runtime DLL (%s), 0x%08x\n", MAKEDLLNAME_A("coreclr"), Status); \
        ExtOut("Some functionality may be impaired\n");         \
    }                                                           \
    else if ((Status = LoadClrDebugDll()) != S_OK)              \
    {                                                           \
        ExtOut("Failed to load data access DLL (%s), 0x%08x\n", MAKEDLLNAME_A("mscordaccore"), Status); \
        ExtOut("Some functionality may be impaired\n");         \
    }                                                           \
    else                                                        \
    {                                                           \
        g_bDacBroken = FALSE;                                   \
        ResetGlobals();                                         \
    }                                                           \
    /* If LoadClrDebugDll() succeeded make sure we release g_clrData. */  \
    /* We may reconsider caching g_clrData in the future */     \
    ToRelease<ISOSDacInterface> spISD(g_sos);                   \
    ToRelease<IXCLRDataProcess> spIDP(g_clrData);

extern BOOL g_bDacBroken;

#define PAGE_ALIGN64(Va) ((ULONG64)((Va) & ~((ULONG64) ((LONG64) (LONG) PageSize - 1))))

extern ULONG PageSize;

//-----------------------------------------------------------------------------------------
//
//  Target platform abstraction
//
//-----------------------------------------------------------------------------------------

// some needed forward declarations
struct StackTrace_SimpleContext;
struct GCEncodingInfo;
struct SOSEHInfo;
class GCDump;

///
/// IMachine interface
///
/// Note:
/// The methods accepting target address args take them as size_t==DWORD_PTR==TADDR,
/// which means this can only provide cross platform support for same-word size
/// architectures (only ARM on x86 currently). Since this is not exposed outside SOS
/// and since the some-word-size limitation exists across EE/DAC/SOS this is not an
/// actual limitation.
///

class IMachine
{
public:
    // Returns the IMAGE_FILE_MACHINE_*** constant corresponding to the target machine
    virtual ULONG GetPlatform() const = 0;
    // Returns the size of the CONTEXT for the target machine
    virtual ULONG GetContextSize() const = 0;

    // Disassembles a managed method specified by the IPBegin-IPEnd range
    virtual void Unassembly(
                TADDR IPBegin,
                TADDR IPEnd,
                TADDR IPAskedFor,
                TADDR GCStressCodeCopy,
                GCEncodingInfo *pGCEncodingInfo,
                SOSEHInfo *pEHInfo,
                BOOL bSuppressLines,
                BOOL bDisplayOffsets) const = 0;

    // Validates whether retAddr represents a return address by unassembling backwards.
    // If the instruction before retAddr represents a target-specific call instruction
    // it attempts to identify the target of the call. If successful it sets *whereCalled
    // to the call target, otherwise it sets it to 0xffffffff.
    virtual void IsReturnAddress(
                TADDR retAddr,
                TADDR* whereCalled) const = 0;

    // If, while unwinding the stack, "PC" represents a known return address in
    // KiUserExceptionDispatcher, "stack" is used to retrieve an exception context record
    // in "cxr", and an exception record in "exr"
    virtual BOOL GetExceptionContext (
                TADDR stack,
                TADDR PC,
                TADDR *cxrAddr,
                CROSS_PLATFORM_CONTEXT * cxr,
                TADDR *exrAddr,
                PEXCEPTION_RECORD exr) const = 0;

    // Retrieves stack pointer, frame pointer, and instruction pointer from the target context
    virtual TADDR GetSP(const CROSS_PLATFORM_CONTEXT & ctx) const = 0;
    virtual TADDR GetBP(const CROSS_PLATFORM_CONTEXT & ctx) const = 0;
    virtual TADDR GetIP(const CROSS_PLATFORM_CONTEXT & ctx) const = 0;

    // Fills dest's data fields from a target specific context
    virtual void  FillSimpleContext(StackTrace_SimpleContext * dest, LPVOID srcCtx) const = 0;
    // Fills a target specific context, destCtx, from the idx-th location in a target specific
    // array of contexts that start at srcCtx
    virtual void  FillTargetContext(LPVOID destCtx, LPVOID srcCtx, int idx = 0) const = 0;

    // Retrieve some target specific output strings
    virtual LPCSTR GetDumpStackHeading() const = 0;
    virtual LPCSTR GetDumpStackObjectsHeading() const = 0;
    virtual LPCSTR GetSPName() const = 0;
    // Retrieves the non-volatile registers reported to the GC
    virtual void GetGCRegisters(LPCSTR** regNames, unsigned int* cntRegs) const = 0;

    typedef void (*printfFtn)(const char* fmt, ...);
    // Dumps the GCInfo
    virtual void DumpGCInfo(BYTE* pTable, unsigned methodSize, printfFtn gcPrintf, bool encBytes, bool bPrintHeader) const = 0;

protected:
    IMachine()           {}
    virtual ~IMachine()  {}

private:
    IMachine(const IMachine& machine);      // undefined
    IMachine & operator=(const IMachine&);   // undefined
}; // class IMachine

extern IMachine* g_targetMachine;

inline BOOL IsDbgTargetX86()    { return g_targetMachine->GetPlatform() == IMAGE_FILE_MACHINE_I386; }
inline BOOL IsDbgTargetAmd64()  { return g_targetMachine->GetPlatform() == IMAGE_FILE_MACHINE_AMD64; }
inline BOOL IsDbgTargetArm()    { return g_targetMachine->GetPlatform() == IMAGE_FILE_MACHINE_ARMNT; }
inline BOOL IsDbgTargetWin64()  { return IsDbgTargetAmd64(); }

/* Returns the instruction pointer for the given CONTEXT.  We need this and its family of
 * functions because certain headers are inconsistantly included on the various platforms,
 * meaning that we cannot use GetIP and GetSP as defined by CLR.
 */
inline CLRDATA_ADDRESS GetIP(const CROSS_PLATFORM_CONTEXT& context)
{
    return TO_CDADDR(g_targetMachine->GetIP(context));
}

/* Returns the stack pointer for the given CONTEXT.
 */
inline CLRDATA_ADDRESS GetSP(const CROSS_PLATFORM_CONTEXT& context)
{
    return TO_CDADDR(g_targetMachine->GetSP(context));
}

/* Returns the base/frame pointer for the given CONTEXT.
 */
inline CLRDATA_ADDRESS GetBP(const CROSS_PLATFORM_CONTEXT& context)
{
    return TO_CDADDR(g_targetMachine->GetBP(context));
}

//-----------------------------------------------------------------------------------------
//
//  api declaration macros & api access macros
//
//-----------------------------------------------------------------------------------------

#ifndef FEATURE_PAL

extern WINDBG_EXTENSION_APIS ExtensionApis;
#define GetExpression (ExtensionApis.lpGetExpressionRoutine)

extern ULONG TargetMachine;
extern ULONG g_TargetClass;
extern ULONG g_VDbgEng;

#else // FEATURE_PAL

#define GetExpression(exp) g_ExtServices->GetExpression(exp)

#endif // FEATURE_PAL

#define CACHE_SIZE  DT_OS_PAGE_SIZE

struct ReadVirtualCache
{
    BYTE   m_cache[CACHE_SIZE];
    TADDR  m_startCache;
    BOOL   m_cacheValid;
    ULONG  m_cacheSize;

    ReadVirtualCache() { Clear(); }
    HRESULT Read(TADDR Offset, PVOID Buffer, ULONG BufferSize, PULONG lpcbBytesRead);
    void Clear() { m_cacheValid = FALSE; m_cacheSize = CACHE_SIZE; }
};

extern ReadVirtualCache *rvCache;

#define MOVE(dst, src) rvCache->Read(TO_TADDR(src), &(dst), sizeof(dst), NULL)
#define MOVEBLOCK(dst, src, size) rvCache->Read(TO_TADDR(src), &(dst), size, NULL)

#define moveN(dst, src)                               \
{                                                     \
    HRESULT ret = MOVE(dst, src);                     \
    if (FAILED(ret)) return ret;                      \
}

#define moveBlockN(dst, src, size)                    \
{                                                     \
    HRESULT ret = MOVEBLOCK(dst, src, size);          \
    if (FAILED(ret)) return ret;                      \
}

// move cross-process: reads memory from the debuggee into
// debugger address space and returns in case of error
#define move_xp(dst, src)                             \
{                                                     \
    HRESULT ret = MOVE(dst, src);                     \
    if (FAILED(ret)) return;                          \
}

#define moveBlock(dst, src, size)                     \
{                                                     \
    HRESULT ret = MOVEBLOCK(dst, src, size);          \
    if (FAILED(ret)) return;                          \
}

#ifdef __cplusplus
#define CPPMOD extern "C"
#else
#define CPPMOD
#endif

#endif

#ifdef __cplusplus
}
#endif

#endif // __exts_h__


text:
package groupBy;

/**
 * The Mapper class for an SQL groupby query.
 * The Grouping key becomes the key for map output
 */

import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class Map extends Mapper<LongWritable, Text, Text, DoubleWritable> {

    @Override
    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String line = value.toString();
        String[] data = line.split(",");

        if (data[0].equals("SYMBOL")) {
            return;
        }

        if (data[1].equals("EQ")) {

            String symbol = data[0];
            Double openPrice = Double.parseDouble(data[2]);
            context.write(new Text(symbol), new DoubleWritable(openPrice));
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

<html>
<head>
    <title>Riot todo</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="todo.css">

    <!--[if lt IE 9]>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.0.5/es5-shim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script>html5.addElements('todo')</script>
    <![endif]-->

</head>

<body>

<todo></todo>

<script src="todo.tag" type="riot/tag"></script>
<script src="https://rawgit.com/riot/riot/master/riot%2Bcompiler.min.js"></script>

<script>
    riot.mount('todo', {
        title: 'I want to behave!',
        items: [
            { title: 'Avoid excessive caffeine', done: true },
            { title: 'Hidden item',  hidden: true },
            { title: 'Be less provocative'  },
            { title: 'Be nice to people' }
        ]
    })
</script>

</body>

</html>


text:
function(get_rocksdb_version version_var)
  file(READ "${CMAKE_CURRENT_SOURCE_DIR}/include/rocksdb/version.h" version_header_file)
  foreach(component MAJOR MINOR PATCH)
    string(REGEX MATCH "#define ROCKSDB_${component} ([0-9]+)" _ ${version_header_file})
    set(ROCKSDB_VERSION_${component} ${CMAKE_MATCH_1})
  endforeach()
  set(${version_var} "${ROCKSDB_VERSION_MAJOR}.${ROCKSDB_VERSION_MINOR}.${ROCKSDB_VERSION_PATCH}" PARENT_SCOPE)
endfunction()


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

#include <node.h>

#include "clang-c/Index.h"

#include <climits>
#include <cstring>

class StringValue {
 public:
  StringValue(CXString str) : str_(str) { }

  ~StringValue() { clang_disposeString(str_); }

  v8::Handle<v8::String> operator* () {
    return v8::String::New(clang_getCString(str_));
  }

 private:
  CXString str_;
};

template<typename T>
class Wrapper {
 public:
  v8::Handle<v8::Object> Wrap(const T& val) {
    v8::HandleScope scope;
    v8::Handle<v8::Object> obj = ctor_->NewInstance();
    T* pval = new T(val);
    obj->SetPointerInInternalField(0, pval);
    v8::Persistent<v8::Object> weak = v8::Persistent<v8::Object>::New(obj);
    weak.MakeWeak(pval, &Dtor);
    weak.MarkIndependent();
    return scope.Close(obj);
  }

  const T& Unwrap(v8::Handle<v8::Value> value) {
    assert(template_->HasInstance(value));
    return *static_cast<T*>(v8::Handle<v8::Object>::Cast(value)->GetPointerFromInternalField(0));
  }

  v8::Handle<v8::FunctionTemplate> Template() {
    if (template_.IsEmpty()) Init();
    return template_;
  }

  v8::Handle<v8::Function> Constructor() {
    if (ctor_.IsEmpty()) {
      ctor_ = v8::Persistent<v8::Function>::New(Template()->GetFunction());
    }
    return ctor_;
  }

  v8::Handle<v8::ObjectTemplate> Prototype() {
    return Template()->PrototypeTemplate();
  }

 private:
  void Init() {
    template_ = v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New());
    template_->InstanceTemplate()->SetInternalFieldCount(1);
  }

  static void Dtor(v8::Persistent<v8::Value> obj, void* ptr) {
    obj.Dispose();
    obj.Clear();
    delete static_cast<T*>(ptr);
  }

  v8::Persistent<v8::FunctionTemplate> template_;
  v8::Persistent<v8::Function> ctor_;
};

Wrapper<CXCursor> Cursor;
Wrapper<CXType> Type;

struct VisitorData {
  v8::Handle<v8::Function> callback_;
  v8::TryCatch try_catch_;
};

static CXChildVisitResult Visitor(CXCursor cursor,
                                  CXCursor parent,
                                  CXClientData data) {
  v8::HandleScope scope;

  VisitorData* visitor_data = static_cast<VisitorData*>(data);

  assert(!visitor_data->try_catch_.HasCaught());

  v8::Handle<v8::Value> args[2] = { Cursor.Wrap(cursor), Cursor.Wrap(parent) };

  v8::Local<v8::Value> result =
      visitor_data->callback_->Call(v8::Context::GetCurrent()->Global(), 2, args);

  if (visitor_data->try_catch_.HasCaught()) {
    return CXChildVisit_Break;
  }

  return static_cast<CXChildVisitResult>(result->Int32Value());
}

static v8::Handle<v8::Value> CursorVisit(const v8::Arguments& args) {
  v8::HandleScope scope;

  assert(args.Length() == 1);
  assert(args[0]->IsFunction());

  VisitorData data;
  data.callback_ = v8::Handle<v8::Function>::Cast(args[0]);
  unsigned result = clang_visitChildren(Cursor.Unwrap(args.This()), &Visitor, &data);
  if (data.try_catch_.HasCaught()) {
    return data.try_catch_.ReThrow();
  }
  return v8::Integer::NewFromUnsigned(result);
}

#define SIMPLE_METHOD0(Name, WrapResult, func, UnwrapThis)              \
  static v8::Handle<v8::Value> Name (const v8::Arguments& args) {       \
    v8::HandleScope scope;                                              \
    assert(args.Length() == 0);                                         \
    return scope.Close(WrapResult (func (UnwrapThis(args.This()))));     \
  }

SIMPLE_METHOD0(CursorSpelling, *StringValue, clang_getCursorSpelling, Cursor.Unwrap)
SIMPLE_METHOD0(CursorUSR, *StringValue, clang_getCursorUSR, Cursor.Unwrap)
SIMPLE_METHOD0(CursorKind, v8::Integer::New, clang_getCursorKind, Cursor.Unwrap)
SIMPLE_METHOD0(CursorDefinition, Cursor.Wrap, clang_getCursorDefinition, Cursor.Unwrap)
SIMPLE_METHOD0(CursorCanonical, Cursor.Wrap, clang_getCanonicalCursor, Cursor.Unwrap)
SIMPLE_METHOD0(CursorType, Type.Wrap, clang_getCursorType, Cursor.Unwrap)
SIMPLE_METHOD0(CursorIsStatic, v8::Boolean::New, clang_CXXMethod_isStatic, Cursor.Unwrap)
SIMPLE_METHOD0(CursorAccess, v8::Integer::New, clang_getCXXAccessSpecifier, Cursor.Unwrap)
SIMPLE_METHOD0(CursorDisplay, *StringValue, clang_getCursorDisplayName, Cursor.Unwrap)
SIMPLE_METHOD0(CursorParent, Cursor.Wrap, clang_getCursorSemanticParent, Cursor.Unwrap)
SIMPLE_METHOD0(CursorUnderlyingType, Type.Wrap, clang_getTypedefDeclUnderlyingType, Cursor.Unwrap)
SIMPLE_METHOD0(CursorSpecialized, Cursor.Wrap, clang_getSpecializedCursorTemplate, Cursor.Unwrap)
SIMPLE_METHOD0(CursorIsNull, v8::Boolean::New, clang_Cursor_isNull, Cursor.Unwrap)

#define BIND(proto, name, func) (proto)->Set(v8::String::New(#name), v8::FunctionTemplate::New(&func))

#define BINDCONST(t, name, value) (t)->Set(v8::String::New(#name), v8::Integer::New(value))

static v8::Handle<v8::Function> RegisterCursor() {
  v8::HandleScope scope;
  BIND(Cursor.Prototype(), spelling, CursorSpelling);
  BIND(Cursor.Prototype(), usr, CursorUSR);
  BIND(Cursor.Prototype(), kind, CursorKind);
  BIND(Cursor.Prototype(), definition, CursorDefinition);
  BIND(Cursor.Prototype(), canonical, CursorCanonical);
  BIND(Cursor.Prototype(), visit, CursorVisit);
  BIND(Cursor.Prototype(), type, CursorType);
  BIND(Cursor.Prototype(), isStatic, CursorIsStatic);
  BIND(Cursor.Prototype(), access, CursorAccess);
  BIND(Cursor.Prototype(), display, CursorDisplay);
  BIND(Cursor.Prototype(), parent, CursorParent);
  BIND(Cursor.Prototype(), underlyingType, CursorUnderlyingType);
  BIND(Cursor.Prototype(), specialized, CursorSpecialized);
  BIND(Cursor.Prototype(), isNull, CursorIsNull);

  /*
  ** Generated with:
  **   cat /usr/local/include/clang-c/Index.h |                         \
  **   perl -n -e'/CXCursor_([\w_]+).*=/ && print "BINDCONST(Cursor.Template(), $1, CXCursor_$1);\n"' | \
  **   sort |                                                           \
  **   uniq
  */
  BINDCONST(Cursor.Template(), AddrLabelExpr, CXCursor_AddrLabelExpr);
  BINDCONST(Cursor.Template(), AnnotateAttr, CXCursor_AnnotateAttr);
  BINDCONST(Cursor.Template(), ArraySubscriptExpr, CXCursor_ArraySubscriptExpr);
  BINDCONST(Cursor.Template(), AsmLabelAttr, CXCursor_AsmLabelAttr);
  BINDCONST(Cursor.Template(), BinaryOperator, CXCursor_BinaryOperator);
  BINDCONST(Cursor.Template(), BlockExpr, CXCursor_BlockExpr);
  BINDCONST(Cursor.Template(), BreakStmt, CXCursor_BreakStmt);
  BINDCONST(Cursor.Template(), CStyleCastExpr, CXCursor_CStyleCastExpr);
  BINDCONST(Cursor.Template(), CXXAccessSpecifier, CXCursor_CXXAccessSpecifier);
  BINDCONST(Cursor.Template(), CXXBaseSpecifier, CXCursor_CXXBaseSpecifier);
  BINDCONST(Cursor.Template(), CXXBoolLiteralExpr, CXCursor_CXXBoolLiteralExpr);
  BINDCONST(Cursor.Template(), CXXCatchStmt, CXCursor_CXXCatchStmt);
  BINDCONST(Cursor.Template(), CXXConstCastExpr, CXCursor_CXXConstCastExpr);
  BINDCONST(Cursor.Template(), CXXDeleteExpr, CXCursor_CXXDeleteExpr);
  BINDCONST(Cursor.Template(), CXXDynamicCastExpr, CXCursor_CXXDynamicCastExpr);
  BINDCONST(Cursor.Template(), CXXFinalAttr, CXCursor_CXXFinalAttr);
  BINDCONST(Cursor.Template(), CXXForRangeStmt, CXCursor_CXXForRangeStmt);
  BINDCONST(Cursor.Template(), CXXFunctionalCastExpr, CXCursor_CXXFunctionalCastExpr);
  BINDCONST(Cursor.Template(), CXXMethod, CXCursor_CXXMethod);
  BINDCONST(Cursor.Template(), CXXNewExpr, CXCursor_CXXNewExpr);
  BINDCONST(Cursor.Template(), CXXNullPtrLiteralExpr, CXCursor_CXXNullPtrLiteralExpr);
  BINDCONST(Cursor.Template(), CXXOverrideAttr, CXCursor_CXXOverrideAttr);
  BINDCONST(Cursor.Template(), CXXReinterpretCastExpr, CXCursor_CXXReinterpretCastExpr);
  BINDCONST(Cursor.Template(), CXXStaticCastExpr, CXCursor_CXXStaticCastExpr);
  BINDCONST(Cursor.Template(), CXXThisExpr, CXCursor_CXXThisExpr);
  BINDCONST(Cursor.Template(), CXXThrowExpr, CXCursor_CXXThrowExpr);
  BINDCONST(Cursor.Template(), CXXTryStmt, CXCursor_CXXTryStmt);
  BINDCONST(Cursor.Template(), CXXTypeidExpr, CXCursor_CXXTypeidExpr);
  BINDCONST(Cursor.Template(), CallExpr, CXCursor_CallExpr);
  BINDCONST(Cursor.Template(), CaseStmt, CXCursor_CaseStmt);
  BINDCONST(Cursor.Template(), CharacterLiteral, CXCursor_CharacterLiteral);
  BINDCONST(Cursor.Template(), ClassDecl, CXCursor_ClassDecl);
  BINDCONST(Cursor.Template(), ClassTemplate, CXCursor_ClassTemplate);
  BINDCONST(Cursor.Template(), ClassTemplatePartialSpecialization, CXCursor_ClassTemplatePartialSpecialization);
  BINDCONST(Cursor.Template(), CompoundAssignOperator, CXCursor_CompoundAssignOperator);
  BINDCONST(Cursor.Template(), CompoundLiteralExpr, CXCursor_CompoundLiteralExpr);
  BINDCONST(Cursor.Template(), CompoundStmt, CXCursor_CompoundStmt);
  BINDCONST(Cursor.Template(), ConditionalOperator, CXCursor_ConditionalOperator);
  BINDCONST(Cursor.Template(), Constructor, CXCursor_Constructor);
  BINDCONST(Cursor.Template(), ContinueStmt, CXCursor_ContinueStmt);
  BINDCONST(Cursor.Template(), ConversionFunction, CXCursor_ConversionFunction);
  BINDCONST(Cursor.Template(), DeclRefExpr, CXCursor_DeclRefExpr);
  BINDCONST(Cursor.Template(), DeclStmt, CXCursor_DeclStmt);
  BINDCONST(Cursor.Template(), DefaultStmt, CXCursor_DefaultStmt);
  BINDCONST(Cursor.Template(), Destructor, CXCursor_Destructor);
  BINDCONST(Cursor.Template(), DoStmt, CXCursor_DoStmt);
  BINDCONST(Cursor.Template(), EnumConstantDecl, CXCursor_EnumConstantDecl);
  BINDCONST(Cursor.Template(), EnumDecl, CXCursor_EnumDecl);
  BINDCONST(Cursor.Template(), FieldDecl, CXCursor_FieldDecl);
  BINDCONST(Cursor.Template(), FirstAttr, CXCursor_FirstAttr);
  BINDCONST(Cursor.Template(), FirstDecl, CXCursor_FirstDecl);
  BINDCONST(Cursor.Template(), FirstExpr, CXCursor_FirstExpr);
  BINDCONST(Cursor.Template(), FirstInvalid, CXCursor_FirstInvalid);
  BINDCONST(Cursor.Template(), FirstPreprocessing, CXCursor_FirstPreprocessing);
  BINDCONST(Cursor.Template(), FirstRef, CXCursor_FirstRef);
  BINDCONST(Cursor.Template(), FirstStmt, CXCursor_FirstStmt);
  BINDCONST(Cursor.Template(), FloatingLiteral, CXCursor_FloatingLiteral);
  BINDCONST(Cursor.Template(), ForStmt, CXCursor_ForStmt);
  BINDCONST(Cursor.Template(), FunctionDecl, CXCursor_FunctionDecl);
  BINDCONST(Cursor.Template(), FunctionTemplate, CXCursor_FunctionTemplate);
  BINDCONST(Cursor.Template(), GCCAsmStmt, CXCursor_GCCAsmStmt);
  BINDCONST(Cursor.Template(), GNUNullExpr, CXCursor_GNUNullExpr);
  BINDCONST(Cursor.Template(), GenericSelectionExpr, CXCursor_GenericSelectionExpr);
  BINDCONST(Cursor.Template(), GotoStmt, CXCursor_GotoStmt);
  BINDCONST(Cursor.Template(), IBActionAttr, CXCursor_IBActionAttr);
  BINDCONST(Cursor.Template(), IBOutletAttr, CXCursor_IBOutletAttr);
  BINDCONST(Cursor.Template(), IBOutletCollectionAttr, CXCursor_IBOutletCollectionAttr);
  BINDCONST(Cursor.Template(), IfStmt, CXCursor_IfStmt);
  BINDCONST(Cursor.Template(), ImaginaryLiteral, CXCursor_ImaginaryLiteral);
  BINDCONST(Cursor.Template(), InclusionDirective, CXCursor_InclusionDirective);
  BINDCONST(Cursor.Template(), IndirectGotoStmt, CXCursor_IndirectGotoStmt);
  BINDCONST(Cursor.Template(), InitListExpr, CXCursor_InitListExpr);
  BINDCONST(Cursor.Template(), IntegerLiteral, CXCursor_IntegerLiteral);
  BINDCONST(Cursor.Template(), InvalidCode, CXCursor_InvalidCode);
  BINDCONST(Cursor.Template(), InvalidFile, CXCursor_InvalidFile);
  BINDCONST(Cursor.Template(), LabelRef, CXCursor_LabelRef);
  BINDCONST(Cursor.Template(), LabelStmt, CXCursor_LabelStmt);
  BINDCONST(Cursor.Template(), LambdaExpr, CXCursor_LambdaExpr);
  BINDCONST(Cursor.Template(), LastAttr, CXCursor_LastAttr);
  BINDCONST(Cursor.Template(), LastDecl, CXCursor_LastDecl);
  BINDCONST(Cursor.Template(), LastExpr, CXCursor_LastExpr);
  BINDCONST(Cursor.Template(), LastInvalid, CXCursor_LastInvalid);
  BINDCONST(Cursor.Template(), LastPreprocessing, CXCursor_LastPreprocessing);
  BINDCONST(Cursor.Template(), LastRef, CXCursor_LastRef);
  BINDCONST(Cursor.Template(), LastStmt, CXCursor_LastStmt);
  BINDCONST(Cursor.Template(), LinkageSpec, CXCursor_LinkageSpec);
  BINDCONST(Cursor.Template(), MSAsmStmt, CXCursor_MSAsmStmt);
  BINDCONST(Cursor.Template(), MacroDefinition, CXCursor_MacroDefinition);
  BINDCONST(Cursor.Template(), MacroExpansion, CXCursor_MacroExpansion);
  BINDCONST(Cursor.Template(), MacroInstantiation, CXCursor_MacroInstantiation);
  BINDCONST(Cursor.Template(), MemberRef, CXCursor_MemberRef);
  BINDCONST(Cursor.Template(), MemberRefExpr, CXCursor_MemberRefExpr);
  BINDCONST(Cursor.Template(), Namespace, CXCursor_Namespace);
  BINDCONST(Cursor.Template(), NamespaceAlias, CXCursor_NamespaceAlias);
  BINDCONST(Cursor.Template(), NamespaceRef, CXCursor_NamespaceRef);
  BINDCONST(Cursor.Template(), NoDeclFound, CXCursor_NoDeclFound);
  BINDCONST(Cursor.Template(), NonTypeTemplateParameter, CXCursor_NonTypeTemplateParameter);
  BINDCONST(Cursor.Template(), NotImplemented, CXCursor_NotImplemented);
  BINDCONST(Cursor.Template(), NullStmt, CXCursor_NullStmt);
  BINDCONST(Cursor.Template(), ObjCAtCatchStmt, CXCursor_ObjCAtCatchStmt);
  BINDCONST(Cursor.Template(), ObjCAtFinallyStmt, CXCursor_ObjCAtFinallyStmt);
  BINDCONST(Cursor.Template(), ObjCAtSynchronizedStmt, CXCursor_ObjCAtSynchronizedStmt);
  BINDCONST(Cursor.Template(), ObjCAtThrowStmt, CXCursor_ObjCAtThrowStmt);
  BINDCONST(Cursor.Template(), ObjCAtTryStmt, CXCursor_ObjCAtTryStmt);
  BINDCONST(Cursor.Template(), ObjCAutoreleasePoolStmt, CXCursor_ObjCAutoreleasePoolStmt);
  BINDCONST(Cursor.Template(), ObjCBoolLiteralExpr, CXCursor_ObjCBoolLiteralExpr);
  BINDCONST(Cursor.Template(), ObjCBridgedCastExpr, CXCursor_ObjCBridgedCastExpr);
  BINDCONST(Cursor.Template(), ObjCCategoryDecl, CXCursor_ObjCCategoryDecl);
  BINDCONST(Cursor.Template(), ObjCCategoryImplDecl, CXCursor_ObjCCategoryImplDecl);
  BINDCONST(Cursor.Template(), ObjCClassMethodDecl, CXCursor_ObjCClassMethodDecl);
  BINDCONST(Cursor.Template(), ObjCClassRef, CXCursor_ObjCClassRef);
  BINDCONST(Cursor.Template(), ObjCDynamicDecl, CXCursor_ObjCDynamicDecl);
  BINDCONST(Cursor.Template(), ObjCEncodeExpr, CXCursor_ObjCEncodeExpr);
  BINDCONST(Cursor.Template(), ObjCForCollectionStmt, CXCursor_ObjCForCollectionStmt);
  BINDCONST(Cursor.Template(), ObjCImplementationDecl, CXCursor_ObjCImplementationDecl);
  BINDCONST(Cursor.Template(), ObjCInstanceMethodDecl, CXCursor_ObjCInstanceMethodDecl);
  BINDCONST(Cursor.Template(), ObjCInterfaceDecl, CXCursor_ObjCInterfaceDecl);
  BINDCONST(Cursor.Template(), ObjCIvarDecl, CXCursor_ObjCIvarDecl);
  BINDCONST(Cursor.Template(), ObjCMessageExpr, CXCursor_ObjCMessageExpr);
  BINDCONST(Cursor.Template(), ObjCPropertyDecl, CXCursor_ObjCPropertyDecl);
  BINDCONST(Cursor.Template(), ObjCProtocolDecl, CXCursor_ObjCProtocolDecl);
  BINDCONST(Cursor.Template(), ObjCProtocolExpr, CXCursor_ObjCProtocolExpr);
  BINDCONST(Cursor.Template(), ObjCProtocolRef, CXCursor_ObjCProtocolRef);
  BINDCONST(Cursor.Template(), ObjCSelectorExpr, CXCursor_ObjCSelectorExpr);
  BINDCONST(Cursor.Template(), ObjCStringLiteral, CXCursor_ObjCStringLiteral);
  BINDCONST(Cursor.Template(), ObjCSuperClassRef, CXCursor_ObjCSuperClassRef);
  BINDCONST(Cursor.Template(), ObjCSynthesizeDecl, CXCursor_ObjCSynthesizeDecl);
  BINDCONST(Cursor.Template(), OverloadedDeclRef, CXCursor_OverloadedDeclRef);
  BINDCONST(Cursor.Template(), PackExpansionExpr, CXCursor_PackExpansionExpr);
  BINDCONST(Cursor.Template(), ParenExpr, CXCursor_ParenExpr);
  BINDCONST(Cursor.Template(), ParmDecl, CXCursor_ParmDecl);
  BINDCONST(Cursor.Template(), PreprocessingDirective, CXCursor_PreprocessingDirective);
  BINDCONST(Cursor.Template(), ReturnStmt, CXCursor_ReturnStmt);
  BINDCONST(Cursor.Template(), SEHExceptStmt, CXCursor_SEHExceptStmt);
  BINDCONST(Cursor.Template(), SEHFinallyStmt, CXCursor_SEHFinallyStmt);
  BINDCONST(Cursor.Template(), SEHTryStmt, CXCursor_SEHTryStmt);
  BINDCONST(Cursor.Template(), SizeOfPackExpr, CXCursor_SizeOfPackExpr);
  BINDCONST(Cursor.Template(), StmtExpr, CXCursor_StmtExpr);
  BINDCONST(Cursor.Template(), StringLiteral, CXCursor_StringLiteral);
  BINDCONST(Cursor.Template(), StructDecl, CXCursor_StructDecl);
  BINDCONST(Cursor.Template(), SwitchStmt, CXCursor_SwitchStmt);
  BINDCONST(Cursor.Template(), TemplateRef, CXCursor_TemplateRef);
  BINDCONST(Cursor.Template(), TemplateTemplateParameter, CXCursor_TemplateTemplateParameter);
  BINDCONST(Cursor.Template(), TemplateTypeParameter, CXCursor_TemplateTypeParameter);
  BINDCONST(Cursor.Template(), TranslationUnit, CXCursor_TranslationUnit);
  BINDCONST(Cursor.Template(), TypeAliasDecl, CXCursor_TypeAliasDecl);
  BINDCONST(Cursor.Template(), TypeRef, CXCursor_TypeRef);
  BINDCONST(Cursor.Template(), TypedefDecl, CXCursor_TypedefDecl);
  BINDCONST(Cursor.Template(), UnaryExpr, CXCursor_UnaryExpr);
  BINDCONST(Cursor.Template(), UnaryOperator, CXCursor_UnaryOperator);
  BINDCONST(Cursor.Template(), UnexposedAttr, CXCursor_UnexposedAttr);
  BINDCONST(Cursor.Template(), UnexposedDecl, CXCursor_UnexposedDecl);
  BINDCONST(Cursor.Template(), UnexposedExpr, CXCursor_UnexposedExpr);
  BINDCONST(Cursor.Template(), UnexposedStmt, CXCursor_UnexposedStmt);
  BINDCONST(Cursor.Template(), UnionDecl, CXCursor_UnionDecl);
  BINDCONST(Cursor.Template(), UsingDeclaration, CXCursor_UsingDeclaration);
  BINDCONST(Cursor.Template(), UsingDirective, CXCursor_UsingDirective);
  BINDCONST(Cursor.Template(), VarDecl, CXCursor_VarDecl);
  BINDCONST(Cursor.Template(), VariableRef, CXCursor_VariableRef);
  BINDCONST(Cursor.Template(), WhileStmt, CXCursor_WhileStmt);

  BINDCONST(Cursor.Template(), VisitBreak, CXChildVisit_Break);
  BINDCONST(Cursor.Template(), VisitContinue, CXChildVisit_Continue);
  BINDCONST(Cursor.Template(), VisitRecurse, CXChildVisit_Recurse);

  BINDCONST(Cursor.Template(), CXXInvalidAccessSpecifier, CX_CXXInvalidAccessSpecifier);
  BINDCONST(Cursor.Template(), CXXPublic, CX_CXXPublic);
  BINDCONST(Cursor.Template(), CXXProtected, CX_CXXProtected);
  BINDCONST(Cursor.Template(), CXXPrivate, CX_CXXPrivate);

  return scope.Close(Cursor.Constructor());
}

#define COMPLEX_METHOD0(Name, WrapResult, R, func, A, UnwrapThis)       \
  R Name##Impl (A arg0) { func; }                                       \
  static v8::Handle<v8::Value> Name (const v8::Arguments& args) {       \
    v8::HandleScope scope;                                              \
    assert(args.Length() == 0);                                         \
    return scope.Close(WrapResult (Name##Impl (UnwrapThis(args.This())))); \
  }

SIMPLE_METHOD0(TypePointee, Type.Wrap, clang_getPointeeType, Type.Unwrap)
SIMPLE_METHOD0(TypeCanonical, Type.Wrap, clang_getCanonicalType, Type.Unwrap)
SIMPLE_METHOD0(TypeDeclaration, Cursor.Wrap, clang_getTypeDeclaration, Type.Unwrap)
COMPLEX_METHOD0(TypeKind, v8::Integer::New, CXTypeKind, return arg0.kind, const CXType&, Type.Unwrap)
COMPLEX_METHOD0(TypeSpelling, *StringValue, CXString, return clang_getTypeKindSpelling(arg0.kind), const CXType&, Type.Unwrap)
SIMPLE_METHOD0(TypeResult, Type.Wrap, clang_getResultType, Type.Unwrap)
COMPLEX_METHOD0(TypeArgs, v8::Handle<v8::Value>, v8::Handle<v8::Value>, { \
    unsigned argc = clang_getNumArgTypes(arg0);                         \
    if (argc == UINT_MAX) return v8::Null();                            \
    v8::Handle<v8::Array> args = v8::Array::New(argc);                  \
    for (unsigned i = 0; i < argc; i++) args->Set(i, Type.Wrap(clang_getArgType(arg0, i))); \
    return args;                                                        \
  }, const CXType&, Type.Unwrap)

SIMPLE_METHOD0(TypeIsVariadic, v8::Boolean::New, clang_isFunctionTypeVariadic, Type.Unwrap);

static v8::Handle<v8::Function> RegisterType() {
  v8::HandleScope scope;
  BIND(Type.Prototype(), declaration, TypeDeclaration);
  BIND(Type.Prototype(), kind, TypeKind);
  BIND(Type.Prototype(), canonical, TypeCanonical);
  BIND(Type.Prototype(), result, TypeResult);
  BIND(Type.Prototype(), args, TypeArgs);
  BIND(Type.Prototype(), pointee, TypePointee);
  BIND(Type.Prototype(), spelling, TypeSpelling);
  BIND(Type.Prototype(), isVariadic, TypeIsVariadic);

  /*
  ** Generated with:
  **   cat /usr/local/include/clang-c/Index.h |                         \
  **   perl -n -e'/CXType_([\w_]+).*=/ && print "BINDCONST(Type.Template(), $1, CXType_$1);\n"' | \
  **   sort |                                                           \
  **   uniq
  */
  BINDCONST(Type.Template(), BlockPointer, CXType_BlockPointer);
  BINDCONST(Type.Template(), Bool, CXType_Bool);
  BINDCONST(Type.Template(), Char16, CXType_Char16);
  BINDCONST(Type.Template(), Char32, CXType_Char32);
  BINDCONST(Type.Template(), Char_S, CXType_Char_S);
  BINDCONST(Type.Template(), Char_U, CXType_Char_U);
  BINDCONST(Type.Template(), Complex, CXType_Complex);
  BINDCONST(Type.Template(), ConstantArray, CXType_ConstantArray);
  BINDCONST(Type.Template(), Dependent, CXType_Dependent);
  BINDCONST(Type.Template(), Double, CXType_Double);
  BINDCONST(Type.Template(), Enum, CXType_Enum);
  BINDCONST(Type.Template(), FirstBuiltin, CXType_FirstBuiltin);
  BINDCONST(Type.Template(), Float, CXType_Float);
  BINDCONST(Type.Template(), FunctionNoProto, CXType_FunctionNoProto);
  BINDCONST(Type.Template(), FunctionProto, CXType_FunctionProto);
  BINDCONST(Type.Template(), Int, CXType_Int);
  BINDCONST(Type.Template(), Int128, CXType_Int128);
  BINDCONST(Type.Template(), Invalid, CXType_Invalid);
  BINDCONST(Type.Template(), LValueReference, CXType_LValueReference);
  BINDCONST(Type.Template(), LastBuiltin, CXType_LastBuiltin);
  BINDCONST(Type.Template(), Long, CXType_Long);
  BINDCONST(Type.Template(), LongDouble, CXType_LongDouble);
  BINDCONST(Type.Template(), LongLong, CXType_LongLong);
  BINDCONST(Type.Template(), NullPtr, CXType_NullPtr);
  BINDCONST(Type.Template(), ObjCClass, CXType_ObjCClass);
  BINDCONST(Type.Template(), ObjCId, CXType_ObjCId);
  BINDCONST(Type.Template(), ObjCInterface, CXType_ObjCInterface);
  BINDCONST(Type.Template(), ObjCObjectPointer, CXType_ObjCObjectPointer);
  BINDCONST(Type.Template(), ObjCSel, CXType_ObjCSel);
  BINDCONST(Type.Template(), Overload, CXType_Overload);
  BINDCONST(Type.Template(), Pointer, CXType_Pointer);
  BINDCONST(Type.Template(), RValueReference, CXType_RValueReference);
  BINDCONST(Type.Template(), Record, CXType_Record);
  BINDCONST(Type.Template(), SChar, CXType_SChar);
  BINDCONST(Type.Template(), Short, CXType_Short);
  BINDCONST(Type.Template(), Typedef, CXType_Typedef);
  BINDCONST(Type.Template(), UChar, CXType_UChar);
  BINDCONST(Type.Template(), UInt, CXType_UInt);
  BINDCONST(Type.Template(), UInt128, CXType_UInt128);
  BINDCONST(Type.Template(), ULong, CXType_ULong);
  BINDCONST(Type.Template(), ULongLong, CXType_ULongLong);
  BINDCONST(Type.Template(), UShort, CXType_UShort);
  BINDCONST(Type.Template(), Unexposed, CXType_Unexposed);
  BINDCONST(Type.Template(), Vector, CXType_Vector);
  BINDCONST(Type.Template(), Void, CXType_Void);
  BINDCONST(Type.Template(), WChar, CXType_WChar);

  return scope.Close(Type.Constructor());
}

class Context {
 public:
  Context(CXIndex index, CXTranslationUnit tu) : index_(index), tu_(tu) { }
  ~Context() {
    if (tu_ != NULL) clang_disposeTranslationUnit(tu_);
    if (index_ != NULL) clang_disposeIndex(index_);
  }

  Context(const Context& other) {
    index_ = other.index_;
    tu_ = other.tu_;
    const_cast<Context&>(other).index_ = NULL;
    const_cast<Context&>(other).tu_ = NULL;
  }

  CXTranslationUnit tu() const { return tu_; }
 private:
  CXIndex index_;
  CXTranslationUnit tu_;
};

Wrapper<Context> ContextT;

COMPLEX_METHOD0(ContextCursor,
                Cursor.Wrap,
                CXCursor,
                return clang_getTranslationUnitCursor(arg0.tu()),
                const Context&,
                ContextT.Unwrap);

static v8::Handle<v8::Function> RegisterContext() {
  v8::HandleScope scope;
  BIND(ContextT.Prototype(), cursor, ContextCursor);
  return ContextT.Constructor();
}

class String {
 public:
  String() : str_(NULL) { }
  ~String() { delete[] str_; }

  void Copy(const char* str, int length) {
    str_ = new char[length + 1];
    strncpy(str_, str, length);
    str_[length] = '\0';
  }

  const char* str() { return str_; }
 private:
  char* str_;
};

static v8::Handle<v8::Value> Parse(const v8::Arguments& args) {
  v8::HandleScope scope;

  int argc;

  v8::Handle<v8::Array> arr;
  if (args.Length() == 1 && args[0]->IsArray()) {
    arr = v8::Handle<v8::Array>::Cast(args[0]);
    argc = arr->Length();
  } else {
    argc = args.Length();
  }

  String* strargs = new String[argc];
  for (int i = 0; i < argc; i++) {
    v8::String::AsciiValue arg(arr.IsEmpty() ? args[i] : arr->Get(i));
    if (arg.length() == 0) {
      delete[] strargs;
      return v8::ThrowException(v8::Exception::Error(v8::String::New("expected string arguments")));
    }
    strargs[i].Copy(*arg, arg.length());
  }

  const char** argv = new const char* [argc];
  for (int i = 0; i < argc; i++) {
    argv[i] = strargs[i].str();
  }

  CXIndex index = clang_createIndex(0, 0);
  CXTranslationUnit tu = clang_parseTranslationUnit(index, 0, argv, argc, 0, 0, CXTranslationUnit_None);

  delete[] argv;
  delete[] strargs;

  if (tu == NULL) {
    clang_disposeIndex(index);
    return v8::ThrowException(v8::Exception::Error(v8::String::New("failed to parse translation unit")));
  }

  for (unsigned i = 0, n = clang_getNumDiagnostics(tu); i != n; ++i) {
    CXString str = clang_formatDiagnostic(
        clang_getDiagnostic(tu, i), clang_defaultDiagnosticDisplayOptions());
    fprintf(stderr, "%s\n", clang_getCString(str));
    clang_disposeString(str);
  }

  return scope.Close(ContextT.Wrap(Context(index, tu)));
}

static void Register(v8::Handle<v8::Object> exports) {
  v8::HandleScope scope;
  exports->Set(v8::String::New("Cursor"), RegisterCursor());
  exports->Set(v8::String::New("Type"), RegisterType());
  RegisterContext();
  exports->Set(v8::String::New("Parse"), v8::FunctionTemplate::New(&Parse)->GetFunction());
}

NODE_MODULE(libclang, Register);


text:
#ifndef _OTF_HEADERDECODER_H
#define _OTF_HEADERDECODER_H

#include <cstdint>
#include <memory>
#include <vector>
#include <string>
#include <algorithm>

#include "Token.h"

namespace sbe {
namespace otf {

class OtfHeaderDecoder
{
public:
    OtfHeaderDecoder(std::shared_ptr<std::vector<Token>> tokens) :
        m_tokens(tokens)
    {
        m_encodedLength = tokens->at(0).encodedLength();

        std::for_each(tokens->begin(), tokens->end(), [&](Token& token)
        {
            const std::string& name = token.name();
            const Encoding& encoding = token.encoding();

            if (name == "blockLength")
            {
                m_blockLengthOffset = token.offset();
                m_blockLengthType = encoding.primitiveType();
                m_blockLengthByteOrder = encoding.byteOrder();
            }
            else if (name == "templateId")
            {
                m_templateIdOffset = token.offset();
                m_templateIdType = encoding.primitiveType();
                m_templateIdByteOrder = encoding.byteOrder();
            }
            else if (name == "schemaId")
            {
                m_schemaIdOffset = token.offset();
                m_schemaIdType = encoding.primitiveType();
                m_schemaIdByteOrder = encoding.byteOrder();
            }
            else if (name == "version")
            {
                m_schemaVersionOffset = token.offset();
                m_schemaVersionType = encoding.primitiveType();
                m_schemaVersionByteOrder = encoding.byteOrder();
            }

        });
    }

    inline std::uint32_t encodedLength() const
    {
        return static_cast<std::uint32_t>(m_encodedLength);
    }

    /*
     * All elements must be unsigned integers according to RC3
     */

    std::uint64_t getTemplateId(const char *headerBuffer)
    {
        return Encoding::getUInt(m_templateIdType, m_templateIdByteOrder, headerBuffer + m_templateIdOffset);
    }

    std::uint64_t getSchemaId(const char *headerBuffer)
    {
        return Encoding::getUInt(m_schemaIdType, m_schemaIdByteOrder, headerBuffer + m_schemaIdOffset);
    }

    std::uint64_t getSchemaVersion(const char *headerBuffer)
    {
        return Encoding::getUInt(m_schemaVersionType, m_schemaVersionByteOrder, headerBuffer + m_schemaVersionOffset);
    }

    std::uint64_t getBlockLength(const char *headerBuffer)
    {
        return Encoding::getUInt(m_blockLengthType, m_blockLengthByteOrder, headerBuffer + m_blockLengthOffset);
    }

private:
    std::shared_ptr<std::vector<Token>> m_tokens;
    std::int32_t m_encodedLength;
    std::int32_t m_blockLengthOffset;
    std::int32_t m_templateIdOffset;
    std::int32_t m_schemaIdOffset;
    std::int32_t m_schemaVersionOffset;
    PrimitiveType m_blockLengthType;
    PrimitiveType m_templateIdType;
    PrimitiveType m_schemaIdType;
    PrimitiveType m_schemaVersionType;
    ByteOrder m_blockLengthByteOrder;
    ByteOrder m_templateIdByteOrder;
    ByteOrder m_schemaIdByteOrder;
    ByteOrder m_schemaVersionByteOrder;
};

}}

#endif


text:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT TOP 20 st.[text] AS [SQL]
     , cp.cacheobjtype
     , cp.objtype
     , COALESCE(DB_NAME(st.dbid), DB_NAME(CAST(pa.value AS INT))+'*', 'Resource') AS [DatabaseName]
     , cp.usecounts AS [Plan usage]
     , qp.query_plan
  FROM sys.dm_exec_cached_plans cp
 CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
 CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp
 OUTER APPLY sys.dm_exec_plan_attributes(cp.plan_handle) pa
 WHERE pa.attribute = 'dbid'
   AND st.[text] LIKE '%CREATE PROCEDURE%';


text:
#ifndef MSOUTLOOKREFERENCEATTACHMENTCOLLECTIONOPERATIONS_H
#define MSOUTLOOKREFERENCEATTACHMENTCOLLECTIONOPERATIONS_H

#import "MSOutlookModels.h"
#import "api/api.h"
#import "core/core.h"
#import "MSOutlookAttachmentCollectionOperations.h"

/** MSOutlookReferenceAttachmentCollectionOperations
 *
 */
@interface MSOutlookReferenceAttachmentCollectionOperations : MSOutlookAttachmentCollectionOperations

@end

#endif


text:
package cz.lbenda.dataman;

/**
 * Created by Lukas Benda <lbenda @ lbenda.cz> on 4.9.15.
 */
public class UserImpl implements User {
  private final String username;
  public UserImpl(String username) {
    this.username = username;
  }
  @Override public String getUsername() { return username; }
}


text:
{% extends 'base_products.html' %}
{% block content %}

Product detail

	Back

	{% if product %}

{{product.name}}

{{product.description}}

Price $ {{product.price}}

	{% else %}

Not found products

	{% endif %}

{% endblock %}


text:
// This file contains style definitions that can be used by CKEditor plugins.
//
// The most common use for it is the "stylescombo" plugin which shows the Styles drop-down
// list containing all styles in the editor toolbar. Other plugins, like
// the "div" plugin, use a subset of the styles for their features.
//
// If you do not have plugins that depend on this file in your editor build, you can simply
// ignore it. Otherwise it is strongly recommended to customize this file to match your
// website requirements and design properly.
//
// For more information refer to: http://docs.ckeditor.com/#!/guide/dev_styles-section-style-rules

CKEDITOR.stylesSet.add( 'default', [
	/* Block Styles */
	{ name : 'คำพูด (Quote)'		, element : 'blockquote'},
	{ name : 'โค้ด (Code)'		, element : 'code' },
	{ name : 'ข้อความ (Message)'		, element : 'div', attributes : { 'class' : 'message' } },
	{ name : 'คำเตือน (Warning)'		, element : 'div', attributes : { 'class' : 'warning' } },
	{ name : 'Image center'		, element : 'figure', attributes : { 'class' : 'center' } },
	/* Inline Styles */
	{ name : 'Span tag'		, element : 'span' },
	{ name : 'สำคัญ (Important)'		, element : 'em' },
	{ name : 'เน้นข้อความ (Bold)'		, element : 'strong' },
	{ name : 'หมายเหตุ (Comment)'		, element : 'span', attributes : { 'class' : 'comment' } }
]);

CKEDITOR.stylesSet.add( 'print', [
	{ name : 'ช่องกรอกข้อความ'		, element : 'span', attributes : { 'class' : 'line' } },
	{ name : 'ขึ้นหน้าใหม่เมื่อพิมพ์'		, element : 'p', attributes : { 'class' : 'splitpage' } }
]);


text:
<?php  namespace Controllers;
use Models\Comentarios as Comentarios;
use Models\Noticias as Noticias;
use Models\Usuarios as Usuarios;

  class dashboardController{
    //atributos
    private $comentarios;
    private $noticias;

    public function __construct(){
      $this->comentarios = new Comentarios();
      $this->noticias = new Noticias();

    }
    public function index(){

    }
      public function agregar(){
        if($_POST){
           $this->comentarios->set("contenido", $_POST['contenido']);
           $this->comentarios->set("autor", null);
           $this->comentarios->add();
           header("location: " . URL);

       }
       }
       public function eliminar($id){
     }

     public function editar($id){

       }

       public function login(){
         if($_POST){
           //echo $_POST['emaillogin'];
           //echo $_POST['passlogin'];
           $usuario=new Usuarios();
           $usuario->set("password",$_POST['passlogin']);
           $usuario->set("email",$_POST['emaillogin']);
           $user=$usuario->login();
           //print_r($user);
           //print_r(count($user));
           if(count($user)>1){
             header('Location:'.URL.'noticias/agregar');
           }else{
             header('Location:'.URL.'dashboard/login');
           }
         }
       }

       public function dashboard(){

       }

       public function listarNoticias(){
         $datos = $this->noticias->listar();
         return $datos;
       }
       public function listarComentarios(){
         $datos = $this->comentarios->listar();
         return $datos;
       }

       public function sendEmail(){
         $para      = 'maasprilla35@misena.edu.co';
         $titulo    = 'Correo de Contacto';
         $mensaje   = $_POST['message'];
         $cabeceras = 'From: '.$_POST['email'];

         mail($para, $titulo, $mensaje, $cabeceras);
         return true;
       }
    }

    $dash= new dashboardController();

    ?>


text:
The scenarios in this directory provide a suite of stress tests that test the Event Hubs producer and buffered producer client types for long-term durability and reliability. For more in-depth information about the Azure SDK stress test tools, see the [stress test readme](https://github.com/Azure/azure-sdk-tools/blob/main/tools/stress-cluster/chaos/README.md).

Test runs can call any of the following tests:
- "EventProducerTest"
- "BufferedProducerTest"
- "BurstBufferedProducerTest"
- "ProcessorTest"
- "ConsumerTest"

Or, you can run all tests with the "--all" flag.

## Getting started

### Install the package

```cmd
(env) <git root>/sdk/eventhub/Azure.Messaging.EventHubs/stress/src> dotnet clean
(env) <git root>/sdk/eventhub/Azure.Messaging.EventHubs/stress/src> dotnet publish
```

### Prerequisites

When tests are run locally, Azure resources need to be created prior to running the test. This can be done through the Azure CLI, an ARM pr bicep file, or the Azure Portal. The bicep file included in this directory can be used to [deploy all resources](https://docs.microsoft.com/azure/azure-resource-manager/bicep/deploy-to-resource-group?tabs=azure-cli) aside from the application insights portal.

To run the compiled .dll file, navigate to the `<git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0` directory.

### Authenticate the client

The user is required to input the connection strings upon request on the command line when the test is being run, or include them in a .env file. To use the CLI input, add the `-i` or `--interactive` flag to the call:

#### Running stress tests locally
```cmd
(env) <git root>/sdk/eventhub/Azure.Messaging.EventHubs/stress/src> dotnet build './sdk/eventhub/Azure.Messaging.EventHubs/stress/src/' --configuration Release
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --tests <test/s-to-run> --interactive
```

To see the variable names for the environment file, see `EnvironmentVariables.cs`, The path to the environment file needs to be stored in the environment variable `$ENV_FILE`. In this case, do not include the `--interactive flag`. For more information about what specific resources are needed for each test, see the "Scenario Information" section below.

The recommended approach is to run tests one at a time when running locally.
To run any one test, run the following:
```cmd
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --tests <test/s-to-run> --interactive
```
If running all tests is desired, run the following:
```cmd
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --all --interactive
```

## Key concepts

### Scenario: Event Producer Test
This test requires an event hub namespace, an event hub, and an application insights resource. Note that an event hub may experience throttling if too few partitions are used. This test creates 2 producers and has 5 concurrent processes per producer sending batches of events. This is a long-running, consistent volume test. To run this test in interactive mode, run the following:
```cmd
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --tests EventProducerTest --interactive
```

### Scenario: Event Buffered Producer Test
This test requires an event hub namespace, an event hub, and an application insights resource. This test creates 2 producers and continuously sends to each producer separately. This is a long-running, consistent volume test. To run this test in interactive mode, run the following:
```cmd
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --tests BufferedProducerTest --interactive
```

### Scenario: Burst Buffered Producer Test
This test requires an event hub namespace, an event hub, and an application insights resource. This test creates 2 producers and sends sets of events to each producer separately every 15 minutes. This is a long-running, variable volume test. To run this test in interactive mode, run the following:
```cmd
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --tests BurstBufferedProducerTest --interactive
```

### Scenario: Processor Test
This test requires an event hub namespace, an event hub, a storage account, a storage blob and an application insights resource. This test creates a producer for each partition. Events are augmented with properties to help the processor independently validate ordering and delivery. This test creates two processors to do this. To run this test in interactive mode, run the following:
```cmd
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --tests ProcessorTest --interactive
```

### Scenario: Consumer Test
This test requires an event hub namespace, an event hub, and an application insights resource. This test creates a producer for each partition. Events are augmented with properties to help the consumers independently validate ordering and delivery. This test creates a consumer for each partition within the same process to do this. To run this test in interactive mode, run the following:
```cmd
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --tests ConsumerTest --interactive
```

### Seeing Metrics and Logging in App Insights
All metrics and logging are sent to App Insights via the Instrumentation Key provided during the initialization of the test. A brief explanation of the metrics collection approach is described below.
- Any exceptions that occur are tracked by the telemetry client as exception telemetry. They can be accessed through the logs by filtering for exceptions, or through the application insights portal in the "Exceptions" blade. If an exception occured during send, the exception telemetry will include a "process" property containing "send"
- Successful enqueues and sends are tracked through Metrics. For the buffered producer, the total number of enqueues is tracked, and the actual sends include the ability to separate counts into partition Ids.

See the `Metrics.cs` file for more information about individual metrics and what they mean.

## Examples

#### Local Stress Test Run

With a .env file:
```cmd
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --all
```

Without a .env file:
```cmd
(env) <git root>/artifacts/bin/Azure.Messaging.EventHubs.Stress/Release/net6.0> dotnet Azure.Messaging.EventHubs.Stress.dll --all --interactive
```

## Troubleshooting

- Ensure that all connection strings, instrumentation keys, and event hub names are correct. If using an environment file, make sure they are properly defined and set in the correct variables as defined in `EnvironmentVariables.cs`

## Next steps

### Deploying a stress test
In order to deploy stress tests to be run in kubernetes clusters, run:
```cmd
(env) <git root>/eng/common/scripts/stress-testing/deploy-stress-tests.ps1 `
>>     -Login `
>>     -PushImages
```
This command requires Azure login credentials.

## Contributing

This project welcomes contributions and suggestions.  Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

Please see our [contributing guide](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/eventhub/Azure.Messaging.EventHubs/CONTRIBUTING.md) for more information.

![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net%2Fsdk%2Feventhub%2FAzure.Messaging.EventHubs%2Fstress%2FREADME.png)


text:
<?php namespace App\Http\Controllers\Back;

use App\Http\Controllers\Controller;
use App\Http\Requests\CommentRequest;
use Illuminate\Http\Request;
use App\Repositories\CommentRepository;
use App\Repositories\UserRepository;

class CommentController extends Controller {

	/**
	 * The CommentRepository instance.
	 *
	 * @var App\Repositories\CommentRepository
	 */
	protected $comment_gestion;

	/**
	 * Create a new CommentController instance.
	 *
	 * @param  App\Repositories\CommentRepository $comment_gestion
	 * @return void
	 */
	public function __construct(
		CommentRepository $comment_gestion)
	{
		$this->comment_gestion = $comment_gestion;

		$this->middleware('admin', ['except' => ['store', 'edit', 'update', 'destroy']]);
		$this->middleware('auth', ['only' => ['store', 'update', 'destroy']]);
		$this->middleware('ajax', ['only' => ['updateSeen', 'update', 'valid']]);
	}

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		$comments = $this->comment_gestion->index(4);
		$links = $comments->render();
		$url = config('medias.url');
		return view('back.blog.comments', compact('comments', 'links','url'));
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @param  App\requests\CommentRequest $request
	 * @return Response
	 */
	public function store(
		CommentRequest $request)
	{
		$this->comment_gestion->store($request->all(), $request->user()->id);

		if($request->user()->valid)
		{
			return redirect()->back();
		}

		return redirect()->back()->with('warning', trans('front/blog.warning'));
	}

	/**
	 * Update "seen" in the specified resource in storage.
	 *
	 * @param  Illuminate\Http\Request $request
	 * @param  int  $id
	 * @return Response
	 */
	public function updateSeen(
		Request $request,
		$id)
	{
		$this->comment_gestion->update($request->input('seen'), $id);

		return response()->json();
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  App\requests\CommentRequest $request
	 * @param  int  $id
	 * @return Response
	 */
	public function update(
		CommentRequest $request,
		$id)
	{
		$id = $request->segment(2);
		$content = $request->input('comments' . $id);
		$this->comment_gestion->updateContent($content, $id);

		return response()->json(['id' => $id, 'content' => $content]);
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  Illuminate\Http\Request $request
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy(
		Request $request,
		$id)
	{
		$this->comment_gestion->destroy($id);

		if($request->ajax())
		{
			return response()->json(['id' => $id]);
		}

		return redirect('admin/pages/comment');
	}

	/**
	 * Validate an user
	 *
	 * @param  Illuminate\Http\Request $request
	 * @param  App\Repositories\UserRepository $user_gestion
	 * @param  int  $id
     * @return Response
	 */
	public function valid(
		Request $request,
		UserRepository $user_gestion,
		$id)
	{
		$user_gestion->valid($request->input('valid'), $id);

		return response()->json();
	}

}


text:
<?php
$this->load->view('includes/header');
$this->load->view('includes/menu');
if ($screen!='') $this->load->view('screen/'.$screen);
$this->load->view('includes/footer');


text:
       Apakah unit kerja Saudara mendanai kegiatan litbang yang pelaksanaannya dilakukan oleh unit kerja/institusi lain (belanja litbang extramural) selama tahun {{$ctrl.year - 1}}?

              <input type="checkbox" ng-checked="!!$ctrl.checked">Ya

              <input type="checkbox" ng-checked="!$ctrl.checked">Tidak

          <input type="text" id="first-name" value="{{detail.institusi | institusi:$ctrl.institusi}}" required="required" class="form-control col-md-7 col-xs-12" placeholder="Instruksi Pelaksana">

Rp

          <input type="text" id="first-name" ng-model="detail.jumlah_dana" required="required" class="form-control col-md-7 col-xs-12" placeholder="Rp">

Comment

{{$ctrl.answer.comment}}

      <button class="btn btn-sm btn-success"  ng-disabled="($ctrl.answer.status=='diterima' || $ctrl.answer.status=='ditolak') || $ctrl.statusUpdated" ng-click="$ctrl.approve()">Approve</button>
      <button class="btn btn-sm btn-danger"  ng-disabled="($ctrl.answer.status=='diterima' || $ctrl.answer.status=='ditolak') || $ctrl.statusUpdated" ng-click="$ctrl.reject()" >Reject</button>


text:
<?
namespace Seyon\Nodejs\ChatBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('seyon_nodejs_chat');

        $rootNode
            ->children()
                ->scalarNode('template')
                    ->defaultValue('SeyonNodejsChatBundle::layout.html.twig')
                ->end()
                ->scalarNode('ip')
                    ->defaultValue('localhost')
                ->end()
                ->integerNode('port')
                    ->defaultValue('3000')
                ->end()
                ->scalarNode('file')
                    ->defaultValue('/socket.io/socket.io.js')
                ->end()
                ->booleanNode('debug')
                    ->defaultFalse()
                ->end()
                ->arrayNode('roles')
                    ->children()
                        ->scalarNode('admin')
                            ->defaultValue('ROLE_ADMIN')
                        ->end()
                        ->scalarNode('moderator')
                            ->defaultValue('ROLE_MODERATOR')
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}


text:
package org.apache.rocketmq.console.model.request;

import com.google.common.base.Objects;

import java.util.List;

public class TopicConfigInfo {

    private List<String> clusterNameList;
    private List<String> brokerNameList;

    /** topicConfig */
    private String topicName;
    private int writeQueueNums;
    private int readQueueNums;
    private int perm;
    private boolean order;

    public List<String> getClusterNameList() {
        return clusterNameList;
    }

    public void setClusterNameList(List<String> clusterNameList) {
        this.clusterNameList = clusterNameList;
    }

    /** topicConfig */

    public List<String> getBrokerNameList() {
        return brokerNameList;
    }

    public void setBrokerNameList(List<String> brokerNameList) {
        this.brokerNameList = brokerNameList;
    }

    public String getTopicName() {
        return topicName;
    }

    public void setTopicName(String topicName) {
        this.topicName = topicName;
    }

    public int getWriteQueueNums() {
        return writeQueueNums;
    }

    public void setWriteQueueNums(int writeQueueNums) {
        this.writeQueueNums = writeQueueNums;
    }

    public int getReadQueueNums() {
        return readQueueNums;
    }

    public void setReadQueueNums(int readQueueNums) {
        this.readQueueNums = readQueueNums;
    }

    public int getPerm() {
        return perm;
    }

    public void setPerm(int perm) {
        this.perm = perm;
    }

    public boolean isOrder() {
        return order;
    }

    public void setOrder(boolean order) {
        this.order = order;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        TopicConfigInfo that = (TopicConfigInfo) o;
        return writeQueueNums == that.writeQueueNums &&
            readQueueNums == that.readQueueNums &&
            perm == that.perm &&
            order == that.order &&
            Objects.equal(topicName, that.topicName);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(topicName, writeQueueNums, readQueueNums, perm, order);
    }

}


text:
There's a trick with margins to horizontally center block elements:
  margin: 0 auto;

#What did you learn about CSS positioning?
CSS positioning is wonky and unintuitive.

#What aspects of your design did you find easiest to implement?
nav bars, text formatting, and background colors are very easy.

#What was most difficult?
Positioning! Especially vertical positioning, which makes me want to cry.

#What did you learn about adding and formatting elements with CSS in this challenge?
There seems to be a lot of disagreement in the web design community about the best way to lay out CSS code. I read a lot about atomic CSS, BEM, and OOCSS and there doesn't seem to be any consensus.


text:
import React from 'react'
import Moment from 'react-moment'

import Card from '../../elements/Card/Card.js'

const GithubEvent = ({ data }) => {
  const event = data
  if (!event) return null

  let eventData = {
    date: event.created_at,
    actorName: event.actor.display_login,
    repoName: event.repo.name,
    repoLink: event.repo.url.replace('api.github.com/repos', 'github.com'),
    payloadText: '',
  }

  switch (event.type) {
    case 'PushEvent':
      eventData.payloadText = `pushed commit '${
        event.payload.commits[0].message
      }' to`
      break
    case 'IssueCommentEvent':
      eventData.payloadText = `commented: "${
        event.payload.comment.body
      }" in issue ${event.payload.issue.title} in`
      break
    case 'CreateEvent':
      eventData.payloadText = `created ${event.payload.ref_type}`
      break
    case 'DeleteEvent':
      eventData.payloadText = `deleted ${event.payload.ref_type} ${
        event.payload.ref
      } in`
      break
    case 'PullRequestEvent':
      eventData.payloadText = `${event.payload.action} PR #${
        event.payload.number
      }: ${event.payload.pull_request.title} in`
      break
    case 'WatchEvent':
      eventData.payloadText = `${event.payload.action} watching`
      break
    case 'ForkEvent':
      eventData.payloadText = `forked ${event.payload.forkee.name} from`
      break
    default:
      eventData.payloadText = `unrecognized event case`
  }

  return (
    <Card className="github-event">
      <Moment date={eventData.date} format="Do MMM YYYY HH:mm" />

{eventData.actorName}

{eventData.payloadText}

        {eventData.repoName}

    </Card>
  )
}

export default GithubEvent


text:
package org.polyforms.repository.spring;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.Proxy;

import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.polyforms.repository.aop.RepositoryInterceptor;
import org.polyforms.repository.spi.ExecutorFinder;
import org.polyforms.repository.spi.RepositoryMatcher;
import org.springframework.aop.MethodMatcher;

public class RepositoryAdvisorTest {
    private RepositoryMatcher repositoryMatcher;
    private MethodMatcher methodMatcher;

    @Before
    public void setUp() {
        repositoryMatcher = EasyMock.createMock(RepositoryMatcher.class);
        final RepositoryInterceptor repositoryInterceptor = new RepositoryInterceptor(
                EasyMock.createMock(ExecutorFinder.class));
        methodMatcher = new RepositoryAdvisor(repositoryInterceptor, repositoryMatcher).getPointcut()
                .getMethodMatcher();
    }

    @Test
    public void matches() throws NoSuchMethodException {
        repositoryMatcher.matches(MockClass.class);
        EasyMock.expectLastCall().andReturn(true);
        EasyMock.replay(repositoryMatcher);

        Assert.assertTrue(methodMatcher.matches(MockClass.class.getMethod("abstractMethod", new Class<?>[0]),
                MockClass.class));
        EasyMock.verify(repositoryMatcher);
    }

    @Test
    public void notMatches() throws NoSuchMethodException {
        repositoryMatcher.matches(MockClass.class);
        EasyMock.expectLastCall().andReturn(false);
        EasyMock.replay(repositoryMatcher);

        Assert.assertFalse(methodMatcher.matches(MockClass.class.getMethod("abstractMethod", new Class<?>[0]),
                MockClass.class));
        EasyMock.verify(repositoryMatcher);
    }

    @Test
    public void matchesEnhancer() throws NoSuchMethodException {
        final Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(MockClass.class);
        enhancer.setCallbackTypes(new Class<?>[] { MethodInterceptor.class });
        final Class<?> proxyClass = enhancer.createClass();

        repositoryMatcher.matches(MockClass.class);
        EasyMock.expectLastCall().andReturn(true);
        EasyMock.replay(repositoryMatcher);

        Assert.assertTrue(methodMatcher.matches(proxyClass.getMethod("abstractMethod", new Class<?>[0]), proxyClass));
        EasyMock.verify(repositoryMatcher);
    }

    @Test
    public void matchesProxy() throws NoSuchMethodException {
        final Class<?> proxyClass = Proxy.getProxyClass(MockInterface.class.getClassLoader(),
                new Class<?>[] { MockInterface.class });

        repositoryMatcher.matches(MockInterface.class);
        EasyMock.expectLastCall().andReturn(true);
        EasyMock.replay(repositoryMatcher);

        Assert.assertTrue(methodMatcher.matches(
                proxyClass.getMethod("abstractMethod", new Class<?>[] { Object.class }), proxyClass));
        EasyMock.verify(repositoryMatcher);
    }

    @Test
    public void notMatchesConcret() throws NoSuchMethodException {
        Assert.assertFalse(methodMatcher.matches(MockClass.class.getMethod("concretMethod", new Class<?>[0]),
                MockClass.class));
    }

    public static abstract class MockClass {
        public void concretMethod() {
        }

        public abstract void abstractMethod();
    }

    public interface MockInterface extends GenericInterface<Integer> {
    }

    public interface GenericInterface<T> {
        void abstractMethod(T object);
    }
}


text:
({
	handleClick: function(cmp) {
		var current = cmp.get("v.selected");
        if (current === false) {
        	cmp.set("v.selected", !current);
        } else {
        	this.toggleState(cmp);
        }
	},

    toggleState: function(cmp) {
    	var ascending = cmp.get("v.isAscending");

    	cmp.getValue("v.isAscending").setValue(!ascending, true);
    	this.updateDirection(cmp, !ascending)
    },

    updateDirection: function(cmp, ascending) {
    	var asc = ascending || cmp.get("v.isAscending");
    	var ascLabel = cmp.find("ascLabel").getElement();
    	var descLabel = cmp.find("descLabel").getElement();

    	if (asc) {
    		$A.util.addClass(ascLabel, "visible");
    		$A.util.removeClass(descLabel, "visible");
    	} else {
    		$A.util.addClass(descLabel, "visible");
    		$A.util.removeClass(ascLabel, "visible");
    	}
    }
})


text:
package com.wehelp.wehelp.controllers;

import android.app.Application;
import android.util.Log;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.wehelp.wehelp.classes.Event;
import com.wehelp.wehelp.classes.EventRequirement;
import com.wehelp.wehelp.classes.User;
import com.wehelp.wehelp.classes.Util;
import com.wehelp.wehelp.classes.WeHelpApp;
import com.wehelp.wehelp.services.EventService;
import com.wehelp.wehelp.services.IServiceArrayResponseCallback;
import com.wehelp.wehelp.services.IServiceErrorCallback;
import com.wehelp.wehelp.services.IServiceResponseCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class EventController {

    EventService eventService;
    public Gson gson;
    private ArrayList<Event> listEvents;
    public WeHelpApp weHelpApp;

    public Event eventTemp = null;
    public boolean errorService = false;
    public JSONObject errorMessages = null;
    public boolean addUserOk = false;
    public boolean removeUserOk = false;

    public EventController() {

    }

    public ArrayList<Event> getListEvents() {
        return this.listEvents;
    }

    public void setListEvents(ArrayList<Event> listEvents) {
        this.listEvents = listEvents;
    }

    public EventController(EventService eventService, Gson gson, Application application) {
        this.eventService = eventService;
        this.gson = gson;
        this.weHelpApp = (WeHelpApp)application;
    }

    public void getEvents(double lat, double lng, int perimetro) {
        this.errorService = false;
        this.setListEvents(null);
        this.errorMessages = null;

        this.eventService.getEvents(lat, lng, perimetro, new IServiceArrayResponseCallback() {
            @Override
            public void execute(JSONArray response) {
                System.out.println("get events response: "+response);
                setListEvents(JsonArrayToEventList(response));
            }
        }, new IServiceErrorCallback() {
            @Override
            public void execute(VolleyError error) {
                setListEvents(new ArrayList<Event>());
                errorService = true;
                errorMessages = Util.ServiceErrorToJson(error);
            }
        });
    }

    public void getParticipatingEvents(int userId) {
        this.errorService = false;
        this.setListEvents(null);
        this.errorMessages = null;

        this.eventService.getParticipatingEvents(userId, new IServiceArrayResponseCallback() {
            @Override
            public void execute(JSONArray response) {
                setListEvents(JsonArrayToEventList(response));
            }
        }, new IServiceErrorCallback() {
            @Override
            public void execute(VolleyError error) {
                setListEvents(new ArrayList<Event>());
                errorService = true;
                errorMessages = Util.ServiceErrorToJson(error);
            }
        });
    }

    public void getMyEvents(int userId) {
        this.errorService = false;
        this.setListEvents(null);
        this.errorMessages = null;

        this.eventService.getMyEvents(userId, new IServiceArrayResponseCallback() {
            @Override
            public void execute(JSONArray response) {
                setListEvents(JsonArrayToEventList(response));
            }
        }, new IServiceErrorCallback() {
            @Override
            public void execute(VolleyError error) {
                setListEvents(new ArrayList<Event>());
                errorService = true;
                errorMessages = Util.ServiceErrorToJson(error);
            }
        });
    }

    public ArrayList<Event> JsonArrayToEventList(JSONArray jsonArray) {
        ArrayList<Event> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++)
        {
            try {
                Event event = gson.fromJson(jsonArray.get(i).toString(), Event.class);
                list.add(event);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    public Event JsonToEvent(JSONObject jsonObject) {
        return gson.fromJson(jsonObject.toString(), Event.class);
    }

    public void createEvent(Event event) throws JSONException {
        this.eventTemp = null;
        this.errorService = false;
        this.errorMessages = null;

        this.eventService.createEvent(event, new IServiceResponseCallback() {
            @Override
            public void execute(JSONObject response) {
                Log.d("WeHelpWs", response.toString());
                eventTemp = JsonToEvent(response);
            }
        }, new IServiceErrorCallback() {
            @Override
            public void execute(VolleyError error) {
                Log.d("WeHelpWS", "Error: " + error.getMessage());
                errorService = true;
                errorMessages = Util.ServiceErrorToJson(error);
            }
        });
    }

    public void addUser(final Event event, final User user, ArrayList<EventRequirement> listRequirements) throws JSONException {
        this.errorService = false;
        this.errorMessages = null;
        this.addUserOk = false;

        this.eventService.addUser(event, user, listRequirements, new IServiceResponseCallback() {
            @Override
            public void execute(JSONObject response) {
                Log.d("WeHelpWs", "Usuário " + user.getId() + " participando do evento " + event.getId());
                addUserOk = true;
            }
        }, new IServiceErrorCallback() {
            @Override
            public void execute(VolleyError error) {
                Log.d("WeHelpWS", "Error: " + error.getMessage());
                errorService = true;
                errorMessages = Util.ServiceErrorToJson(error);
            }
        });
    }

    public void removeUser(final Event event, final User user) throws JSONException {
        this.errorService = false;
        this.errorMessages = null;
        this.eventService.removeUser(event, user, new IServiceResponseCallback() {
            @Override
            public void execute(JSONObject response) {
                Log.d("WeHelpWs", "Usuário " + user.getId() + " removido do evento " + event.getId());
                removeUserOk = true;
            }
        }, new IServiceErrorCallback() {
            @Override
            public void execute(VolleyError error) {
                Log.d("WeHelpWS", "Error: " + error.getMessage());
                errorService = true;
                errorMessages = Util.ServiceErrorToJson(error);
            }
        });
    }

    public void addRequirement(final Event event, final EventRequirement requirement) throws JSONException {
        this.errorService = false;
        this.errorMessages = null;
        this.eventService.addRequirement(event, requirement, new IServiceResponseCallback() {
            @Override
            public void execute(JSONObject response) {
                Log.d("WeHelpWs", "Requisito " + requirement.getDescricao() + " adicionado ao evento " + event.getId());
                event.getRequisitos().add(gson.fromJson(response.toString(), EventRequirement.class));
            }
        }, new IServiceErrorCallback() {
            @Override
            public void execute(VolleyError error) {
                Log.d("WeHelpWS", "Error: " + error.getMessage());
                errorService = true;
                errorMessages = Util.ServiceErrorToJson(error);
            }
        });
    }

    public void deleteEvent(final Event event) throws JSONException {
        this.errorService = false;
        this.errorMessages = null;
        this.eventService.deleteEvent(event, new IServiceResponseCallback() {
            @Override
            public void execute(JSONObject response) {
                Log.d("WeHelpWs", "Evento " + event.getId() + " deletado");
                removeUserOk = true;
            }
        }, new IServiceErrorCallback() {
            @Override
            public void execute(VolleyError error) {
                Log.d("WeHelpWS", "Error: " + error.getMessage());
                errorService = true;
                errorMessages = Util.ServiceErrorToJson(error);
            }
        });
    }
}


text:
#include "GeometryIntersect.h"

#ifdef _DEBUG
#include <Core/Math/GeometryIntersect.inl>
#endif

namespace Core
{

} //namespace Core


text:
using System;
using System.Collections.Generic;
using System.Linq;
using FizzWare.NBuilder;
using Moq;
using NUnit.Framework;
using ReMi.BusinessEntities.Auth;
using ReMi.BusinessEntities.ProductRequests;
using ReMi.CommandHandlers.ProductRequests;
using ReMi.Commands.ProductRequests;
using ReMi.TestUtils.UnitTests;
using ReMi.Contracts.Cqrs.Commands;
using ReMi.Contracts.Cqrs.Events;
using ReMi.DataAccess.BusinessEntityGateways.ProductRequests;
using ReMi.Events.ProductRequests;

namespace ReMi.CommandHandlers.Tests.ProductRequests
{
    public class UpdateProductRequestRegistrationCommandHandlerTests : TestClassFor<UpdateProductRequestRegistrationCommandHandler>
    {
        private Mock<IProductRequestRegistrationGateway> _productRequestRegistrationGatewayMock;
        private Mock<IPublishEvent> _publishEventMock;

        protected override UpdateProductRequestRegistrationCommandHandler ConstructSystemUnderTest()
        {
            return new UpdateProductRequestRegistrationCommandHandler
            {
                ProductRequestRegistrationGatewayFactory = () => _productRequestRegistrationGatewayMock.Object,
                PublishEvent = _publishEventMock.Object
            };
        }

        protected override void TestInitialize()
        {
            _productRequestRegistrationGatewayMock = new Mock<IProductRequestRegistrationGateway>();
            _publishEventMock = new Mock<IPublishEvent>();

            base.TestInitialize();
        }

        [Test]
        public void Handle_ShouldCallGateway_WhenInvoked()
        {
            var registrationId = Guid.NewGuid();

            var registration = SetupGateway(registrationId);

            var command = BuildCommand(registration);

            Sut.Handle(command);

            _productRequestRegistrationGatewayMock.Verify(o => o.UpdateProductRequestRegistration(registration), Times.Once);
        }

        [Test]
        public void Handle_ShouldSetChangedByAccountId_WhenInvoked()
        {
            var registrationId = Guid.NewGuid();

            var registration = SetupGateway(registrationId);

            var command = BuildCommand(registration);

            Sut.Handle(command);

            _productRequestRegistrationGatewayMock.Verify(o =>
                o.UpdateProductRequestRegistration(
                    It.Is<ProductRequestRegistration>(x => x.CreatedByAccountId == command.CommandContext.UserId)), Times.Once);
        }

        [Test]
        public void Handle_ShouldNotSendNotification_WhenTasksEmpty()
        {
            var registrationId = Guid.NewGuid();

            var registration = SetupGateway(registrationId);

            var command = BuildCommand(registration);

            Sut.Handle(command);

            _publishEventMock.Verify(o => o.Publish(It.IsAny<IEvent>()), Times.Never);
        }

        [Test]
        public void Handle_ShouldSendNotification_WhenTasksAdded()
        {
            var registrationId = Guid.NewGuid();

            var taskId = Guid.NewGuid();

            var existingTasks = new ProductRequestRegistrationTask[0];
            var updatedTasks = new[] { new ProductRequestRegistrationTask { ProductRequestTaskId = taskId } };

            var registration = SetupGateway(registrationId, updatedTasks, existingTasks);

            var command = BuildCommand(registration);

            Sut.Handle(command);

            _publishEventMock.Verify(o => o.Publish(It.Is<ProductRequestRegistrationUpdatedEvent>(ev =>
                ev.ChangedTasks.Count() == 1 && ev.ChangedTasks.First() == taskId)), Times.Exactly(1));
        }

        [Test]
        public void Handle_ShouldNotSendNotification_WhenExistingTasksNotChanged()
        {
            var registrationId = Guid.NewGuid();

            var taskId = Guid.NewGuid();

            var existingTasks = new[] { new ProductRequestRegistrationTask { ProductRequestTaskId = taskId, IsCompleted = false } };
            var updatedTasks = new[] { new ProductRequestRegistrationTask { ProductRequestTaskId = taskId, IsCompleted = false } };

            var registration = SetupGateway(registrationId, updatedTasks, existingTasks);

            var command = BuildCommand(registration);

            Sut.Handle(command);

            _publishEventMock.Verify(o => o.Publish(It.IsAny<IEvent>()), Times.Never);
        }

        [Test]
        public void Handle_ShouldSendNotification_WhenIsCompletedChanged()
        {
            var registrationId = Guid.NewGuid();

            var taskId = Guid.NewGuid();

            var existingTasks = new[] { new ProductRequestRegistrationTask { ProductRequestTaskId = taskId, IsCompleted = false } };
            var updatedTasks = new[] { new ProductRequestRegistrationTask { ProductRequestTaskId = taskId, IsCompleted = true } };

            var registration = SetupGateway(registrationId, updatedTasks, existingTasks);

            var command = BuildCommand(registration);

            Sut.Handle(command);

            _publishEventMock.Verify(o => o.Publish(It.Is<ProductRequestRegistrationUpdatedEvent>(ev =>
                ev.ChangedTasks.Count() == 1 && ev.ChangedTasks.First() == taskId)), Times.Exactly(1));
        }

        [Test]
        public void Handle_ShouldSendNotification_WhenCommentChanged()
        {
            var registrationId = Guid.NewGuid();

            var taskId = Guid.NewGuid();

            var existingTasks = new[] { new ProductRequestRegistrationTask { ProductRequestTaskId = taskId, Comment = null } };
            var updatedTasks = new[] { new ProductRequestRegistrationTask { ProductRequestTaskId = taskId, Comment = "AAA" } };

            var registration = SetupGateway(registrationId, updatedTasks, existingTasks);

            var command = BuildCommand(registration);

            Sut.Handle(command);

            _publishEventMock.Verify(o => o.Publish(It.Is<ProductRequestRegistrationUpdatedEvent>(ev =>
                ev.ChangedTasks.Count() == 1 && ev.ChangedTasks.First() == taskId)), Times.Exactly(1));
        }

        [Test]
        public void Handle_ShouldSendOnlyChangedNotification_WhenInvoked()
        {
            var registrationId = Guid.NewGuid();

            var taskId = Guid.NewGuid();

            var existingTasks = new[]
            {
                new ProductRequestRegistrationTask { ProductRequestTaskId = taskId, Comment = null },
                new ProductRequestRegistrationTask { ProductRequestTaskId = Guid.NewGuid(), Comment = null }
            };
            var updatedTasks = new[]
            {
                new ProductRequestRegistrationTask { ProductRequestTaskId = taskId, Comment = "AAA" },
                new ProductRequestRegistrationTask { ProductRequestTaskId = Guid.NewGuid(), Comment = "Not existing task" }
            };

            var registration = SetupGateway(registrationId, updatedTasks, existingTasks);

            var command = BuildCommand(registration);

            Sut.Handle(command);

            _publishEventMock.Verify(o => o.Publish(It.Is<ProductRequestRegistrationUpdatedEvent>(ev =>
                ev.ChangedTasks.Count() == 1 && ev.ChangedTasks.First() == taskId)), Times.Exactly(1));
        }

        private ProductRequestRegistration SetupGateway(Guid externalId,
            IEnumerable<ProductRequestRegistrationTask> updatedTasks = null,
            IEnumerable<ProductRequestRegistrationTask> existingTasks = null)
        {
            var registration = Builder<ProductRequestRegistration>.CreateNew()
                .With(o => o.ExternalId, externalId)
                .With(o => o.CreatedByAccountId, Guid.Empty)
                .With(o => o.Tasks, updatedTasks)
                .Build();

            var existingRegistration = Builder<ProductRequestRegistration>.CreateNew()
               .With(o => o.ExternalId, externalId)
               .With(o => o.CreatedByAccountId, Guid.Empty)
               .With(o => o.Tasks, existingTasks)
               .Build();

            _productRequestRegistrationGatewayMock.Setup(o => o.GetRegistration(externalId))
                .Returns(existingRegistration);

            return registration;
        }

        private UpdateProductRequestRegistrationCommand BuildCommand(ProductRequestRegistration registration)
        {
            var command = new UpdateProductRequestRegistrationCommand
            {
                CommandContext = new CommandContext
                {
                    UserId = Guid.NewGuid()
                },
                Registration = registration
            };

            return command;
        }
    }
}


text:
layout: page
title: Inspired Corporation Party
date: 2016-05-24
author: William Cooke
tags: weekly links, java
status: published
summary: In malesuada fermentum dui. Pellentesque habitant morbi.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 06/03/2017
  endDate: 06/08/2017
  ctyhocn: ELPGDHX
  groupCode: ICP
published: true
---
Vestibulum turpis metus, varius at congue ut, finibus in elit. Integer fermentum eu arcu quis egestas. Quisque nec eleifend justo. Aenean gravida tellus non mi tincidunt finibus. Ut consectetur diam purus, dignissim pharetra ipsum suscipit id. Maecenas sagittis velit quis molestie luctus. Donec ornare rutrum rutrum. Curabitur imperdiet quam et augue feugiat faucibus. Integer sit amet libero ac lacus lobortis condimentum cursus eget arcu. In hac habitasse platea dictumst.
Praesent quis sem ultricies, aliquam lectus eu, congue ipsum. Curabitur gravida, turpis sit amet interdum facilisis, nibh magna suscipit nibh, in placerat sapien ligula ut augue. Sed eu turpis non risus commodo posuere vel at felis. Nam eu sapien eu lorem dignissim tincidunt. Curabitur facilisis sit amet ante a cursus. Sed sed turpis tortor. Aenean ornare condimentum ipsum vulputate pulvinar.

* Pellentesque non justo non ipsum mollis sagittis in sed quam
* Pellentesque vitae est in dui maximus molestie ac ac augue.

Donec quis lacus a eros fermentum efficitur. Fusce lorem enim, facilisis sit amet turpis a, dignissim pharetra nibh. Mauris eu ante at leo tempor volutpat. Maecenas eget vulputate velit, ac pharetra velit. Nulla vitae pharetra elit. Integer est massa, gravida et felis vel, vestibulum placerat purus. Morbi ac eros lectus. Suspendisse suscipit in orci nec finibus.


text:
import java.util.Iterator;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;

@ObfuscatedName("hb")
public class class226 implements Iterator {
   @ObfuscatedName("o")
   @ObfuscatedSignature(
      signature = "Lhk;"
   )
   IterableDualNodeQueue field2671;
   @ObfuscatedName("k")
   @ObfuscatedSignature(
      signature = "Lht;"
   )
   CacheableNode field2672;
   @ObfuscatedName("t")
   @ObfuscatedSignature(
      signature = "Lht;"
   )
   CacheableNode field2673;

   @ObfuscatedSignature(
      signature = "(Lhk;)V"
   )
   class226(IterableDualNodeQueue var1) {
      this.field2673 = null;
      this.field2671 = var1;
      this.field2672 = this.field2671.sentinel.previous;
      this.field2673 = null;
   }

   public Object next() {
      CacheableNode var1 = this.field2672;
      if(var1 == this.field2671.sentinel) {
         var1 = null;
         this.field2672 = null;
      } else {
         this.field2672 = var1.previous;
      }

      this.field2673 = var1;
      return var1;
   }

   public void remove() {
      if(this.field2673 == null) {
         throw new IllegalStateException();
      } else {
         this.field2673.unlinkDual();
         this.field2673 = null;
      }
   }

   public boolean hasNext() {
      return this.field2671.sentinel != this.field2672;
   }
}


text:
package shestakov;

public class Calculator {

	private double result = 0;

	public void addiction(double first, double second) {
		this.result = first + second;
		System.out.println("Addiction: " + this.result);
	}

	public void substraction(double first, double second) {
		this.result = first - second;
		System.out.println("Substraction: " + this.result);
	}

	public void multiplication(double first, double second) {
		this.result = first * second;
		System.out.println("Multiplication: " + this.result);
	}

	public void division(double first, double second) {
		this.result = first / second;
		System.out.println("Division: " + this.result);
	}
}