text:
//
//  File: %reb-c.h
//  Summary: "General C definitions and constants"
//  Project: "Rebol 3 Interpreter and Run-time (Ren-C branch)"
//  Homepage: https://github.com/metaeducation/ren-c/
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Copyright 2012 REBOL Technologies
// Copyright 2012-2019 Rebol Open Source Contributors
// REBOL is a trademark of REBOL Technologies
//
// See README.md and CREDITS.md for more information.
//
// 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
//
//=////////////////////////////////////////////////////////////////////////=//
//
// This is a set of definitions and helpers which are generically useful for
// any project which is trying to implement portable C across a variety of
// old and new compilers/systems.
//
// Though R3-Alpha was written to mostly comply with ANSI C89, it needs 64-bit
// integers, and used the `long long` data type.  To suppress warnings in a
// C89 build related to this, use `-Wno-long-long`.  Additionally, `//` style
// comments are used, which were commonly supported by C compilers even before
// the C99 standard.  But that means this code can't be used with the switches
// `--pedantic --std=c89` (unless you convert or strip out all the comments).
//
// The Ren-C branch advanced Rebol to be able to build under C99=>C11 and
// C++98=>C++17 as well.  Some extended checks are provided for these macros
// if building under various versions of C++.  Also, C99 definitions are
// taken advantage of if they are available.
//

#ifndef REB_C_H_1020_0304  // "include guard" allows multiple #includes
#define REB_C_H_1020_0304  // numbers in case REB_C_H defined elsewhere

//=//// EXPECTS <stdint.h> OR "pstdint.h" SHIM INCLUDED ///////////////////=//
//
// Rebol's initial design targeted C89 and old-ish compilers on a variety of
// systems.  A comment here said:
//
//     "One of the biggest flaws in the C language was not
//      to indicate bitranges of integers. So, we do that here.
//      You cannot 'abstractly remove' the range of a number.
//      It is a critical part of its definition."
//
// Once C99 arrived, the file <stdint.h> offered several basic types, and
// basically covered the needs:
//
// http://en.cppreference.com/w/c/types/integer
//
// The code was changed to use either the C99 types -or- a portable shim that
// could mimic the types (with the same names) on older compilers.  It should
// be included before %reb-c.h is included.
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Note: INT32_MAX and INT32_C can be missing in C++ builds on some older
// compilers without __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS:
//
// https://sourceware.org/bugzilla/show_bug.cgi?id=15366
//
// You can run into this since pstdint.h falls back on stdint.h if it
// thinks it can.  Put those on the command line if needed.
//
// !!! One aspect of pstdint.h is that it considers 64-bit "optional".
// Some esoteric platforms may have a more hidden form of 64-bit support,
// e.g. this case from R3-Alpha for "Windows VC6 nonstandard typing":
//
//     #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
//         typedef _int64 i64;
//         typedef unsigned _int64 u64;
//         #define I64_C(c) c ## I64
//         #define U64_C(c) c ## U64
//     #endif
//
// If %pstdint.h isn't trying hard enough for an unsupported platform of
// interest to get 64-bit integers, then patches should be made there.
//

//=//// EXPECTS <stdbool.h> OR "pstdbool.h" SHIM INCLUDED /////////////////=//
//
// Historically Rebol used TRUE and FALSE uppercase macros, but so long as
// C99 has added bool to the language, there's not much point in being
// compatible with codebases that have `char* true = "Spandau";` or similar
// in them.  So Rebol can use `true` and `false.
//

//=//// EXPECTS <assert.h> TO BE INCLUDED, PATCH BUG //////////////////////=//
//
// There is a bug in older GCC where the assert macro expands arguments
// unnecessarily.  Since Rebol tries to build on fairly old systems, this
// patch corrects the issue:
//
// https://sourceware.org/bugzilla/show_bug.cgi?id=18604
//

#if !defined(assert)
    #error "Include <assert.h> before including reb-c.h"
#endif

#if !defined(NDEBUG) && defined(__GLIBC__) && defined(__GLIBC_MINOR__) \
    && (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 23))

    #undef assert
  #if !defined(__GNUC__) || defined (__STRICT_ANSI__)
    #define assert(expr) \
        ((expr) \
            ? __ASSERT_VOID_CAST (0) \
            : __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION))
  #else
    #define assert(expr) \
        ({ \
          if (expr) \
            ; /* empty */ \
          else \
            __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION); \
        })
    #endif

#endif

//=//// ISO646 ALTERNATE TOKENS FOR BOOLEAN OPERATIONS ////////////////////=//
//
// It is much more readable to see `and` and `or` instead of `&&` and `||`
// when reading expressions.  Ren-C embraces the ISO646 standard:
//
// https://en.wikipedia.org/wiki/C_alternative_tokens
//
// It also adds one more to the list: `did` for converting "truthy" values to
// boolean.  This is clearer than `not not` or `!!`:
//
// http://blog.hostilefork.com/did-programming-opposite-of-not/
//

#define did !!  // Not in iso646.h

#ifdef __cplusplus
  #if defined(_MSC_VER)
    #include <iso646.h>  // MSVC doesn't have `and`, `not`, etc. w/o this
  #else
    // legitimate compilers define them, they're even in the C++98 standard!
  #endif
#else
    // is646.h has been defined since the C90 standard of C.  But TCC doesn't
    // ship with it, and maybe other C's don't either.  The issue isn't so
    // much the file, as it is agreeing on the 11 macros, just define them.
    //
    #define and &&
    #define and_eq &=
    #define bitand &
    #define bitor |
    #define compl ~
    #define not !
    #define not_eq !=
    #define or ||
    #define or_eq |=
    #define xor ^
    #define xor_eq ^=
#endif

//=//// CPLUSPLUS_11 PREPROCESSOR DEFINE //////////////////////////////////=//
//
// Because the goal of Ren-C is ultimately to be built with C, the C++ build
// is just for static analysis and debug checks.  This means there's not much
// value in trying to tailor reduced versions of the checks to old ANSI C++98
// compilers, so the "C++ build" is an "at least C++11 build".
//
// Besides being a little less verbose to use, testing via a #define allows
// override when using with Microsoft Visual Studio via a command line
// definition.  For some reason they didn't bump the version number from 1997
// (even by MSVC 2017!!!)
//
#if defined(__cplusplus) && __cplusplus >= 201103L
    #define CPLUSPLUS_11
#elif defined(STDC_VERSION) && STDC_VERSION >= 201112L
    #define C_11
#endif

//=//// TYPE_TRAITS IN C++11 AND ABOVE ///////////////////////////////////=//
//
// One of the most powerful tools you can get from allowing a C codebase to
// compile as C++ comes from type_traits:
//
// http://en.cppreference.com/w/cpp/header/type_traits
//
// This is essentially an embedded query language for types, allowing one to
// create compile-time errors for any C construction that isn't being used
// in the way one might want.
//
#ifdef CPLUSPLUS_11
    #include <type_traits>
#endif

//=//// FEATURE TESTING AND ATTRIBUTE MACROS //////////////////////////////=//
//
// Feature testing macros __has_builtin() and __has_feature() were originally
// a Clang extension, but GCC added support for them.  If compiler doesn't
// have them, default all features unavailable.
//
// http://clang.llvm.org/docs/LanguageExtensions.html#feature-checking-macros
//
// Similarly, the __attribute__ feature is not in the C++ standard and only
// available in some compilers.  Even compilers that have __attribute__ may
// have different individual attributes available on a case-by-case basis.
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Note: Placing the attribute after the prototype seems to lead to
// complaints, and technically there is a suggestion you may only define
// attributes on prototypes--not definitions:
//
// http://stackoverflow.com/q/23917031/211160
//
// Putting the attribute *before* the prototype seems to allow it on both the
// prototype and definition in gcc, however.
//

#ifndef __has_builtin
    #define __has_builtin(x) 0
#endif

#ifndef __has_feature
    #define __has_feature(x) 0
#endif

#ifdef __GNUC__
    #define GCC_VERSION_AT_LEAST(m, n) \
        (__GNUC__ > (m) || (__GNUC__ == (m) && __GNUC_MINOR__ >= (n)))
#else
    #define GCC_VERSION_AT_LEAST(m, n) 0
#endif

//=//// UNREACHABLE CODE ANNOTATIONS //////////////////////////////////////=//
//
// Because Rebol uses `longjmp` and `exit` there are cases where a function
// might look like not all paths return a value, when those paths actually
// aren't supposed to return at all.  For instance:
//
//     int foo(int x) {
//         if (x < 1020)
//             return x + 304;
//         fail ("x is too big"); // compiler may warn about no return value
//     }
//
// One way of annotating to say this is okay is on the caller, with DEAD_END:
//
//     int foo(int x) {
//         if (x < 1020)
//             return x + 304;
//         fail ("x is too big");
//         DEAD_END; // our warning-suppression macro for applicable compilers
//     }
//
// DEAD_END is just a no-op in compilers that don't have the feature of
// suppressing the warning--which can often mean they don't have the warning
// in the first place.
//
// Another macro we define is ATTRIBUTE_NO_RETURN.  This can be put on the
// declaration site of a function like `fail()` itself, so the callsites don't
// need to be changed.  As with DEAD_END it degrades into a no-op in compilers
// that don't support it.
//

/* THESE HAVE BEEN RELOCATED TO %rebol.h, SEE DEFINITIONS THERE */

//=//// STATIC ASSERT /////////////////////////////////////////////////////=//
//
// Some conditions can be checked at compile-time, instead of deferred to a
// runtime assert.  This macro triggers an error message at compile time.
// `static_assert` is an arity-2 keyword in C++11 and can act as arity-1 in
// C++17, for expedience we mock up an arity-1 form.
//
// It's possible to hack up a static assert in C:
//
// http://stackoverflow.com/questions/3385515/static-assert-in-c
//
// But it's too limited.  Since the code can (and should) be built as C++11
// to test anyway, just make it a no-op in the C build.
//
#ifdef CPLUSPLUS_11
    #define STATIC_ASSERT(cond) \
        static_assert((cond), #cond) // callsite has semicolon, see C trick
#else
    #define STATIC_ASSERT(cond) \
        struct GlobalScopeNoopTrick // https://stackoverflow.com/q/53923706
#endif

//=//// CONDITIONAL C++ NAME MANGLING MACROS //////////////////////////////=//
//
// When linking C++ code, different functions with the same name need to be
// discerned by the types of their parameters.  This means their name is
// "decorated" (or "mangled") from the fairly simple and flat convention of
// a C function.
//
// https://en.wikipedia.org/wiki/Name_mangling
// http://en.cppreference.com/w/cpp/language/language_linkage
//
// This also applies to global variables in some compilers (e.g. MSVC), and
// must be taken into account:
//
// https://stackoverflow.com/a/27939238/211160
//
// When built as C++, Ren-C must tell the compiler that functions/variables
// it exports to the outside world should *not* use C++ name mangling, so that
// they can be used sensibly from C.  But the instructions to tell it that
// are not legal in C.  This conditional macro avoids needing to put #ifdefs
// around those prototypes.
//
#if defined(__cplusplus)
    #define EXTERN_C extern "C"
#else
    // !!! There is some controversy on whether EXTERN_C should be a no-op in
    // a C build, or decay to the meaning of C's `extern`.  Notably, WinSock
    // headers from Microsoft use this "decays to extern" form:
    //
    // https://stackoverflow.com/q/47027062/
    //
    // Review if this should be changed to use an EXTERN_C_BEGIN and an
    // EXTERN_C_END style macro--which would be a no-op in the C build and
    // require manual labeling of `extern` on any exported variables.
    //
    #define EXTERN_C extern
#endif

//=//// CASTING MACROS ////////////////////////////////////////////////////=//
//
// The following code and explanation is from "Casts for the Masses (in C)":
//
// http://blog.hostilefork.com/c-casts-for-the-masses/
//
// But debug builds don't inline functions--not even no-op ones whose sole
// purpose is static analysis.  This means the cast macros add a headache when
// stepping through the debugger, and also they consume a measurable amount
// of runtime.  Hence we sacrifice cast checking in the debug builds...and the
// release C++ builds on Travis are relied upon to do the proper optimizations
// as well as report any static analysis errors.
//
// !!! C++14 gcc release builds seem to trigger bad behavior on cast() to
// a CFUNC*, and non-C++14 builds are allowing cast of `const void*` to
// non-const `char` with plain `cast()`.  Investigate as time allows.

#if !defined(CPLUSPLUS_11) || !defined(NDEBUG)
    /* These macros are easier-to-spot variants of the parentheses cast.
     * The 'm_cast' is when getting [M]utablity on a const is okay (RARELY!)
     * Plain 'cast' can do everything else (except remove volatile)
     * The 'c_cast' helper ensures you're ONLY adding [C]onst to a value
     */
    #define m_cast(t,v)     ((t)(v))
    #define cast(t,v)       ((t)(v))
    #define c_cast(t,v)     ((t)(v))
    /*
     * Q: Why divide roles?  A: Frequently, input to cast is const but you
     * "just forget" to include const in the result type, gaining mutable
     * access.  Stray writes to that can cause even time-traveling bugs, with
     * effects *before* that write is made...due to "undefined behavior".
     */
#elif defined(__cplusplus) /* for gcc -Wundef */ && (__cplusplus < 201103L)
    /* Well-intentioned macros aside, C has no way to enforce that you can't
     * cast away a const without m_cast. C++98 builds can do that, at least:
     */
    #define m_cast(t,v)     const_cast<t>(v)
    #define cast(t,v)       ((t)(v))
    #define c_cast(t,v)     const_cast<t>(v)
#else
    /* __cplusplus >= 201103L has C++11's type_traits, where we get some
     * actual power.  cast becomes a reinterpret_cast for pointers and a
     * static_cast otherwise.  We ensure c_cast added a const and m_cast
     * removed one, and that neither affected volatility.
     */
    template<typename T, typename V>
    T m_cast_helper(V v) {
        static_assert(!std::is_const<T>::value,
            "invalid m_cast() - requested a const type for output result");
        static_assert(std::is_volatile<T>::value == std::is_volatile<V>::value,
            "invalid m_cast() - input and output have mismatched volatility");
        return const_cast<T>(v);
    }
    /* construct if possible for ptr to ptr casting (non-class source) */
    template<typename T, typename V,
        typename std::enable_if<
            !std::is_class<V>::value
            && (std::is_pointer<V>::value || std::is_pointer<T>::value)
            && std::is_constructible<T, V>::value
        >::type* = nullptr>
                T cast_helper(V v) { return T {v}; }
    /* reinterpret_cast for all other ptr-to-ptr (non-class source) */
    template<typename T, typename V,
        typename std::enable_if<
            !std::is_class<V>::value
            && (std::is_pointer<V>::value || std::is_pointer<T>::value)
            && !std::is_constructible<T, V>::value
        >::type* = nullptr>
                T cast_helper(V v) { return reinterpret_cast<T>(v); }
    /* static_cast for non-pointer to non-pointer casting (non-class source) */
    template<typename T, typename V,
        typename std::enable_if<
            !std::is_class<V>::value
            && (!std::is_pointer<V>::value && !std::is_pointer<T>::value)
        >::type* = nullptr>
                T cast_helper(V v) { return static_cast<T>(v); }
    /* use static_cast on all classes, to go through their cast operators */
    template<typename T, typename V,
        typename std::enable_if<
            std::is_class<V>::value
        >::type* = nullptr>
                T cast_helper(V v) { return static_cast<T>(v); }
    template<typename T, typename V>
    T c_cast_helper(V v) {
        static_assert(!std::is_const<T>::value,
            "invalid c_cast() - did not request const type for output result");
        static_assert(std::is_volatile<T>::value == std::is_volatile<V>::value,
            "invalid c_cast() - input and output have mismatched volatility");
        return const_cast<T>(v);
    }
    #define m_cast(t, v)    m_cast_helper<t>(v)
    #define cast(t, v)      cast_helper<t>(v)
    #define c_cast(t, v)    c_cast_helper<t>(v)
#endif

//=//// nullptr SHIM FOR C, C++98 /////////////////////////////////////////=//
//
// The C language definition allows compilers to simply define NULL as 0.
// This creates ambiguity in C++ when one overloading of a function takes an
// integer, and another a pointer...since 0 can be coerced to either.  So
// a specific `nullptr` was defined to work around this.
//
// But the problem isn't just with C++.  There is a common issue in variadics
// where NULL is used to terminate a sequence of values that are interpreted
// as pointers:
//
//     variadic_print("print me", "and me", "stop @ NULL", NULL);
//
// Yet there is no way to do this in standards-compliant C.  On a platform
// where integers and pointers aren't compatible sizes or bit patterns, then
// the `0` which NULL evaluates to in that last slot can't be interpreted
// as a null pointer.  You'd have to write:
//
//     variadic_print("print me", "and me", "stop @ NULL", (char*)NULL);
//
// Because libRebol hinges on a premise of making the internal NULL signifier
// interface as a C NULL pointer, and hinges on variadics, this is a problem.
// Rather than introduce a "new" abstraction or macro, this adds a shim of
// C++11's `nullptr` to C++98, and a simple macro to C.
//
// This also means that NULL can be used in comments for the Rebol concept,
// as opposed to the C idea (though NULLED may be clearer, depending on
// context).  Either way, when discussing C's "0 pointer", say `nullptr`.
//

#if !defined(__cplusplus)
    //
    // Plain C, nullptr is not a keyword.
    //
    #define nullptr cast(void*, 0)

#elif defined(CPLUSPLUS_11) //...or above
    //
    // http://en.cppreference.com/w/cpp/language/nullptr
    // is defined as `using nullptr_t = decltype(nullptr);` in <cstddef>
    //
    #include <cstddef>
    using std::nullptr_t;
#else
    // C++98 shim from "Effective C++": https://stackoverflow.com/a/44517878
    //
    // Note: Some "newer old" C++ compilers had awareness that nullptr would
    // be added to the standard, and raise warnings by default if one tries
    // to make this definition, even when building as C++98.  To disable such
    // warnings, you would need something like `-Wno-c++0x-compat`
    //
    const                         /* this is a const object...     */
    class nullptr_t
    {
    public:
       template<class T>          /* convertible to any type       */
       operator T*() const        /* of null non-member            */
          { return 0; }           /* pointer...                    */

       template<class C, class T> /* or any type of null           */
          operator T C::*() const /* member pointer...             */
          { return 0; }

    private:
       void operator&() const;    /* Can't take address of nullptr */

    } nullptr = {};               /* and whose name is nullptr     */
#endif

//=//// NOOP a.k.a. VOID GENERATOR ////////////////////////////////////////=//
//
// VOID would be a more purposeful name, but Windows headers define that
// for the type (as used in types like LPVOID)
//
// As an added application, it is used to annotate a block that you don't
// want picked up as an argument to an `if` or anything.  It makes it more
// obvious why the block is there, and looks like a language feature:
//
//     blockscope {  // better looking, explains more than `{` by itself
//         int x = 3;
//         y = y + x;
//     }
//
#ifndef NOOP
    #define NOOP \
        ((void)(0))
#endif
#define blockscope NOOP;

//=//// ALIGNMENT SIZE ////////////////////////////////////////////////////=//
//
// Data alignment is a complex topic, which has to do with the fact that the
// following kind of assignment can be slowed down or fail entirely on
// many platforms:
//
//    char *cp = (char*)malloc(sizeof(double) + 1);
//    double *dp = (double*)(cp + 1);
//    *dp = 6.28318530718
//
// malloc() guarantees that the pointer it returns is aligned to store any
// fundamental type safely.  But skewing that pointer to not be aligned in
// a way for that type (e.g. by a byte above) means assignments and reads of
// types with more demanding alignment will fail.  e.g. a double often needs
// to read/write to pointers where `((uintptr_t)ptr % sizeof(double)) == 0`
//
// (Note: Often, not always.  For instance, Linux systems with System V ABI
// for i386 are permitted to use 4 byte boundaries instead of 8 byte for
// doubles unless you use `-malign-double`.  See page 28 of the spec:
//
// http://www.uclibc.org/docs/psABI-i386.pdf
//
// Windows 32-bit compilers seem to also permit 4 bytes.  WebAssembly does
// not seem to work when doubles are on 4 byte boundaries, however.)
//
// The C standard does not provide a way to know what the largest fundamental
// type is, even though malloc() must be compatible with it.  So if one is
// writing one's own allocator to give back memory blocks, it's necessary to
// guess.  We guess the larger of size of a double and size of a void*, though
// note this may not be enough for absolutely any type in the compiler:
//
//    "In Visual C++, the fundamental alignment is the alignment that's
//    required for a double, or 8 bytes. In code that targets 64-bit
//    platforms, it's 16 bytes.)
//

#define ALIGN_SIZE \
    (sizeof(double) > sizeof(void*) ? sizeof(double) : sizeof(void*))

#define ALIGN(s,a) \
    (((s) + (a) - 1) & ~((a) - 1)) // !!! this macro not used anywhere ATM

//=//// C FUNCTION TYPE (__cdecl) /////////////////////////////////////////=//
//
// Note that you *CANNOT* cast something like a `void *` to (or from) a
// function pointer.  Pointers to functions are not guaranteed to be the same
// size as to data, in either C or C++.  A compiler might count the number of
// functions in your program, find less than 255, and use bytes for function
// pointers:
//
// http://stackoverflow.com/questions/3941793/
//
// So if you want something to hold either a function pointer or a data
// pointer, you have to implement that as a union...and know what you're doing
// when writing and reading it.
//
// For info on the difference between __stdcall and __cdecl:
//
// http://stackoverflow.com/questions/3404372/
//
//
#ifdef TO_WINDOWS
    typedef void (__cdecl CFUNC)(void);
#else
    typedef void (CFUNC)(void);
#endif

//=//// TESTING IF A NUMBER IS FINITE /////////////////////////////////////=//
//
// C89 and C++98 had no standard way of testing for if a number was finite or
// not.  Windows and POSIX came up with their own methods.  Finally it was
// standardized in C99 and C++11:
//
// http://en.cppreference.com/w/cpp/numeric/math/isfinite
//
// The name was changed to `isfinite()`.  And conforming C99 and C++11
// compilers can omit the old versions, so one cannot necessarily fall back on
// the old versions still being there.  Yet the old versions don't have
// isfinite(), so those have to be worked around here as well.
//

#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L // C99 or later
    #define FINITE isfinite
#elif defined(CPLUSPLUS_11) // C++11 or later
    #define FINITE isfinite
#elif defined(__MINGW32__) || defined(__MINGW64__)
    #define FINITE isfinite // With --std==c++98 MinGW still has isfinite
#elif defined(TO_WINDOWS)
    #define FINITE _finite // The usual answer for Windows
#else
    #define FINITE finite // The usual answer for POSIX
#endif

//=//// PREVENT NULL ASSIGNMENTS /////////////////////////////////////////=//
//
// This came in handly for a debugging scenario, and isn't bad documentation.
//

#if !defined(CPLUSPLUS_11) || defined(NDEBUG)
    #define NEVERNULL(type) \
        type
#else
    template <typename P>
    class Never_Null {  // named so error message hints what's wrong
        typedef typename std::remove_pointer<P>::type T;
        P pointer;

      public:
        Never_Null () : pointer () {}
        Never_Null (P& pointer) : pointer (pointer) {
            assert(pointer != nullptr);
        }
        T& operator*() { return *pointer; }
        P operator->() { return pointer; }
        operator P() { return pointer; }
        P operator= (const P rhs) {  // if it returned reference, loses check
            assert(rhs != nullptr);
            this->pointer = rhs;
            return pointer;
        }
    };

    #define NEVERNULL(type) \
        Never_Null<type>
#endif

//=//// MEMORY POISONING and POINTER TRASHING /////////////////////////////=//
//
// If one wishes to indicate a region of memory as being "off-limits", modern
// tools like Address Sanitizer allow instrumented builds to augment reads
// from memory to check to see if that region is in a blacklist.
//
// These "poisoned" areas are generally sub-regions of valid malloc()'d memory
// that contain bad data.  Yet they cannot be free()d because they also
// contain some good data.  (Or it is merely desirable to avoid freeing and
// then re-allocating them for performance reasons, yet a debug build still
// would prefer to intercept accesses as if they were freed.)
//
// Also, in order to overwrite a pointer with garbage, the historical method
// of using 0xBADF00D or 0xDECAFBAD is formalized with TRASH_POINTER_IF_DEBUG.
// This makes the instances easier to find and standardizes how it is done.
// Special choices are made for 0xF4EEF4EE to indicate a freed thing, and
// 0x5AFE5AFE to indicate an allocated thing.

#if __has_feature(address_sanitizer)
    #include <sanitizer/asan_interface.h>

    #define ATTRIBUTE_NO_SANITIZE_ADDRESS __attribute__ ((no_sanitize_address))

    // <IMPORTANT> Address sanitizer's memory poisoning must not have two
    // threads both poisoning/unpoisoning the same addresses at the same time.

    #define POISON_MEMORY(reg, mem_size) \
        ASAN_POISON_MEMORY_REGION(reg, mem_size)

    #define UNPOISON_MEMORY(reg, mem_size) \
        ASAN_UNPOISON_MEMORY_REGION(reg, mem_size)
#else
    // !!! @HostileFork wrote a tiny C++ "poor man's memory poisoner" that
    // uses XOR to poison bits and then unpoison them back.  This might be
    // useful to instrument C++-based DEBUG builds on platforms that did not
    // have address sanitizer (if that ever becomes interesting).
    //
    // http://blog.hostilefork.com/poison-memory-without-asan/

    #define ATTRIBUTE_NO_SANITIZE_ADDRESS

    #define POISON_MEMORY(reg, mem_size) \
        NOOP

    #define UNPOISON_MEMORY(reg, mem_size) \
        NOOP
#endif

#ifdef NDEBUG
    #define TRASH_POINTER_IF_DEBUG(p) \
        NOOP

    #define TRASH_CFUNC_IF_DEBUG(p) \
        NOOP
#else
    #if defined(__cplusplus) // needed even if not C++11
        template<class T>
        inline static void TRASH_POINTER_IF_DEBUG(T* &p) {
            p = reinterpret_cast<T*>(static_cast<uintptr_t>(0xDECAFBAD));
        }

        template<class T>
        inline static void TRASH_CFUNC_IF_DEBUG(T* &p) {
            p = reinterpret_cast<T*>(static_cast<uintptr_t>(0xDECAFBAD));
        }

        template<class T>
        inline static void SAFETRASH_POINTER_IF_DEBUG(T* &p) {
            p = reinterpret_cast<T*>(static_cast<uintptr_t>(0x5AFE5AFE));
        }

        template<class T>
        inline static void FREETRASH_POINTER_IF_DEBUG(T* &p) {
            p = reinterpret_cast<T*>(static_cast<uintptr_t>(0xF4EEF4EEE));
        }

        template<class T>
        inline static bool IS_POINTER_TRASH_DEBUG(T* p) {
            return (
                p == reinterpret_cast<T*>(static_cast<uintptr_t>(0xDECAFBAD))
            );
        }

        template<class T>
        inline static bool IS_CFUNC_TRASH_DEBUG(T* p) {
            return (
                p == reinterpret_cast<T*>(static_cast<uintptr_t>(0xDECAFBAD))
            );
        }

        template<class T>
        inline static bool IS_POINTER_SAFETRASH_DEBUG(T* p) {
            return (
                p == reinterpret_cast<T*>(static_cast<uintptr_t>(0x5AFE5AFE))
            );
        }

        template<class T>
        inline static bool IS_POINTER_FREETRASH_DEBUG(T* p) {
            return (
                p == reinterpret_cast<T*>(static_cast<uintptr_t>(0xF4EEF4EE))
            );
        }

      #if defined(CPLUSPLUS_11)
        template<class P>
        inline static void TRASH_POINTER_IF_DEBUG(Never_Null<P> &p) {
            p = reinterpret_cast<P>(static_cast<uintptr_t>(0xDECAFBAD));
        }

        template<class P>
        inline static bool IS_POINTER_TRASH_DEBUG(Never_Null<P> &p) {
            return (
                p == reinterpret_cast<P>(static_cast<uintptr_t>(0xDECAFBAD))
            );
        }
      #endif
    #else
        #define TRASH_POINTER_IF_DEBUG(p) \
            ((p) = cast(void*, cast(uintptr_t, 0xDECAFBAD)))

        #define TRASH_CFUNC_IF_DEBUG(p) \
            ((p) = cast(CFUNC*, cast(uintptr_t, 0xDECAFBAD)))

        #define SAFETRASH_POINTER_IF_DEBUG(p) \
            ((p) = cast(void*, cast(uintptr_t, 0x5AFE5AFE)))

        #define FREETRASH_POINTER_IF_DEBUG(p) \
            ((p) = cast(void*, cast(uintptr_t, 0xF4EEF4EE)))

        #define IS_POINTER_TRASH_DEBUG(p) \
            ((p) == cast(void*, cast(uintptr_t, 0xDECAFBAD)))

        #define IS_CFUNC_TRASH_DEBUG(p) \
            ((p) == cast(CFUNC*, cast(uintptr_t, 0xDECAFBAD)))

        #define IS_POINTER_SAFETRASH_DEBUG(p) \
            ((p) == cast(void*, cast(uintptr_t, 0x5AFE5AFE)))

        #define IS_POINTER_FREETRASH_DEBUG(p) \
            ((p) == cast(void*, cast(uintptr_t, 0xF4EEF4EE)))
    #endif
#endif

//=//// MARK UNUSED VARIABLES /////////////////////////////////////////////=//
//
// Used in coordination with the `-Wunused-variable` setting of the compiler.
// While a simple cast to void is what people usually use for this purpose,
// there's some potential for side-effects with volatiles:
//
// http://stackoverflow.com/a/4030983/211160
//
// The tricks suggested there for avoiding it seem to still trigger warnings
// as compilers get new ones, so assume that won't be an issue.  As an
// added check, this gives the UNUSED() macro "teeth" in C++11:
//
// http://codereview.stackexchange.com/q/159439
//
// Though the version here is more verbose, it uses the specializations to
// avoid excessive calls to memset() in the debug build.
//

#define USED(x) \
    ((void)(x))

#if defined(NDEBUG) || !defined(CPLUSPLUS_11)
    #define UNUSED(x) \
        ((void)(x))
#else
    // Can't trash the variable if it's not an lvalue.  So for the basic
    // SFINAE overload, just cast void.  Do this also for cases that are
    // lvalues, but we don't really know how to "trash" them.
    //
    template<
        typename T,
        typename TRR = typename std::remove_reference<T>::type,
        typename std::enable_if<
            !std::is_lvalue_reference<T &&>::value
            || std::is_const<TRR>::value
            || (
                !std::is_pointer<TRR>::value
                && !std::is_arithmetic<TRR>::value
                && !std::is_pod<TRR>::value
            )
        >::type* = nullptr
    >
    void UNUSED(T && v) {
        ((void)(v));
    }

    // For example: if you have an lvalue reference to a pointer, you can
    // set it to DECAFBAD...which will likely be caught if it's a lie and it
    // is getting used in the debug build.
    //
    template<
        typename T,
        typename TRR = typename std::remove_reference<T>::type,
        typename std::enable_if<
            std::is_lvalue_reference<T &&>::value
            && !std::is_const<TRR>::value
            && std::is_pointer<TRR>::value
        >::type* = nullptr
    >
    void UNUSED(T && v) {
        static bool zero = false;
        if (zero)
            v = nullptr; // do null half the time, deterministic
        else
            TRASH_POINTER_IF_DEBUG(v); // trash the other half of the time
        zero = not zero;
    }

    // Any integral or floating type, set to a spam number.
    //
    template<
        typename T,
        typename TRR = typename std::remove_reference<T>::type,
        typename std::enable_if<
            std::is_lvalue_reference<T &&>::value
            && !std::is_const<TRR>::value
            && std::is_arithmetic<TRR>::value
            && !std::is_pointer<TRR>::value
        >::type* = nullptr
    >
    void UNUSED(T && v) {
        static bool zero = false;
        if (zero)
            v = false; // false/0 half the time, deterministic
        else
            v = true; // true/1 other half the time
        zero = not zero;
    }

    // It's unsafe to memory fill an arbitrary C++ class by value with
    // garbage bytes, because of all the "extra" stuff in them.  You can
    // crash the destructor.  But this is a C codebase which only occasionally
    // uses C++ features in the C++ build.  Most will be "Plain Old Data",
    // so fill those with garbage as well.
    //
    // (Note: this one methodology could be applied to all pod types,
    // including arithmetic and pointers, but this shows how to do it
    // with custom ways and avoids function calls to memset in non-optimized
    // debug builds for most cases.)
    //
    template<
        typename T,
        typename TRR = typename std::remove_reference<T>::type,
        typename std::enable_if<
            std::is_lvalue_reference<T &&>::value
            && !std::is_const<TRR>::value
            && std::is_pod<TRR>::value
            && (
                !std::is_pointer<TRR>::value
                && !std::is_arithmetic<TRR>::value
            )
        >::type* = nullptr
    >
    void UNUSED(T && v) {
        memset(&v, 123, sizeof(TRR));
    }
#endif

//=//// MIN AND MAX ///////////////////////////////////////////////////////=//
//
// The standard definition in C for MIN and MAX uses preprocessor macros, and
// this has fairly notorious problems of double-evaluating anything with
// side-effects:
//
// https://stackoverflow.com/a/3437484/211160
//
// It is common for MIN and MAX to be defined in C to macros; and equally
// common to assume that undefining them and redefining them to something
// that acts as it does in most codebases is "probably ok".  :-/
//
#undef MIN
#undef MAX
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#define MAX(a,b) (((a) > (b)) ? (a) : (b))

//=//// SHORTHAND FOR DEEPLY NESTED FIELDS ////////////////////////////////=//
//
// If a field is deeply nested in a structure and referred to many times in
// C, it is possible to create a local pointer to that field and then use
// a dereference to that pointer (which works for both assigning and reads).
// Since it's a `const` pointer, the compiler should optimize it out.
//
// But there's a risk that one might say `if (shorthand)` and test for the
// nullness or non-nullness of the shorthand vs. of the thing pointed to.
// This adds a check in the C++ build that you always say `if (*shorthand)`
//

#if !defined(CPLUSPLUS_11)
    #define SHORTHAND(name,ref,type) \
        type* const name = &ref
#else
    template <typename T>
    class Must_Dereference {  // named so error message hints what's wrong
        T &ref;

      public:
        Must_Dereference (T& ref) : ref (ref) {}
        T & operator*() { return ref; }
        operator bool () = delete;  // !!! Could this static_assert()?
    };

    #define SHORTHAND(name,ref,type) \
        Must_Dereference<type> name = ref
#endif

//=//// BYTE STRINGS VS UNENCODED CHARACTER STRINGS ///////////////////////=//
//
// Use these when you semantically are talking about unsigned characters as
// bytes.  For instance: if you want to count unencoded chars in 'char *' us
// strlen(), and the reader will know that is a count of letters.  If you have
// something like UTF-8 with more than one byte per character, use LEN_BYTES.
// The casting macros are derived from "Casts for the Masses (in C)":
//
// http://blog.hostilefork.com/c-casts-for-the-masses/
//
// For APPEND_BYTES_LIMIT, m is the max-size allocated for d (dest)
//
#include <string.h> // for strlen() etc, but also defines `size_t`
#define strsize strlen
#if defined(NDEBUG)
    /* These [S]tring and [B]inary casts are for "flips" between a 'char *'
     * and 'unsigned char *' (or 'const char *' and 'const unsigned char *').
     * Being single-arity with no type passed in, they are succinct to use:
     */
    #define s_cast(b)       ((char *)(b))
    #define cs_cast(b)      ((const char *)(b))
    #define b_cast(s)       ((unsigned char *)(s))
    #define cb_cast(s)      ((const unsigned char *)(s))

    #define LEN_BYTES(s) \
        strlen((const char*)(s))

    #define COPY_BYTES(d,s,n) \
        strncpy((char*)(d), (const char*)(s), (n))

    #define COMPARE_BYTES(l,r) \
        strcmp((const char*)(l), (const char*)(r))

    inline static unsigned char *APPEND_BYTES_LIMIT(
        unsigned char *dest, const unsigned char *src, size_t max
    ){
        size_t len = LEN_BYTES(dest);
        return b_cast(strncat(
            s_cast(dest), cs_cast(src), MAX(max - len - 1, 0)
        ));
    }
#else
    /* We want to ensure the input type is what we thought we were flipping,
     * particularly not the already-flipped type.  Instead of type_traits, 4
     * functions check in both C and C++ (here only during Debug builds):
     */
    inline static unsigned char *b_cast(char *s)
        { return (unsigned char*)s; }

    inline static const unsigned char *cb_cast(const char *s)
        { return (const unsigned char*)s; }

    inline static char *s_cast(unsigned char *s)
        { return (char*)s; }

    inline static const char *cs_cast(const unsigned char *s)
        { return (const char*)s; }

    // Debug build uses inline functions to ensure you pass in unsigned char *
    //
    inline static unsigned char *COPY_BYTES(
        unsigned char *dest, const unsigned char *src, size_t count
    ){
        return b_cast(strncpy(s_cast(dest), cs_cast(src), count));
    }

    inline static size_t LEN_BYTES(const unsigned char *str)
        { return strlen(cs_cast(str)); }

    inline static int COMPARE_BYTES(
        const unsigned char *lhs, const unsigned char *rhs
    ){
        return strcmp(cs_cast(lhs), cs_cast(rhs));
    }

    inline static unsigned char *APPEND_BYTES_LIMIT(
        unsigned char *dest, const unsigned char *src, size_t max
    ){
        size_t len = LEN_BYTES(dest);
        return b_cast(strncat(
            s_cast(dest), cs_cast(src), MAX(max - len - 1, 0)
        ));
    }
#endif

#endif  // !defined(REB_C_H_1020_0304)


text:
bool draw_isMaterial(GameState* g);

// Determines if the given game state is in a threefold repetition draw situation.
bool draw_isThreefold(GameState* g);

#endif

redpajama_set_name: RedPajamaGithub


text:
namespace MouseKeyboardActivityMonitor.Demo
{
    partial class TestCommonWinFormsBehaviour
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.clickableArea = new System.Windows.Forms.Label();
            this.typeArea = new System.Windows.Forms.TextBox();
            this.textBoxLog = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // clickableArea
            //
            this.clickableArea.BackColor = System.Drawing.Color.Lime;
            this.clickableArea.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.clickableArea.Location = new System.Drawing.Point(8, 9);
            this.clickableArea.Name = "clickableArea";
            this.clickableArea.Size = new System.Drawing.Size(104, 76);
            this.clickableArea.TabIndex = 0;
            this.clickableArea.Text = "Click here";
            this.clickableArea.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.clickableArea.MouseClick += new System.Windows.Forms.MouseEventHandler(this.clickableArea_MouseClick);
            this.clickableArea.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.clickableArea_MouseDoubleClick);
            this.clickableArea.MouseDown += new System.Windows.Forms.MouseEventHandler(this.clickableArea_MouseDown);
            this.clickableArea.MouseUp += new System.Windows.Forms.MouseEventHandler(this.clickableArea_MouseUp);
            //
            // typeArea
            //
            this.typeArea.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.typeArea.Location = new System.Drawing.Point(118, 9);
            this.typeArea.Multiline = true;
            this.typeArea.Name = "typeArea";
            this.typeArea.Size = new System.Drawing.Size(518, 76);
            this.typeArea.TabIndex = 1;
            //
            // textBoxLog
            //
            this.textBoxLog.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
            | System.Windows.Forms.AnchorStyles.Right)));
            this.textBoxLog.BackColor = System.Drawing.Color.White;
            this.textBoxLog.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.textBoxLog.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.textBoxLog.Location = new System.Drawing.Point(8, 91);
            this.textBoxLog.Multiline = true;
            this.textBoxLog.Name = "textBoxLog";
            this.textBoxLog.ReadOnly = true;
            this.textBoxLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.textBoxLog.Size = new System.Drawing.Size(636, 378);
            this.textBoxLog.TabIndex = 6;
            this.textBoxLog.WordWrap = false;
            //
            // TestCommonWinFormsBehaviour
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(648, 457);
            this.Controls.Add(this.textBoxLog);
            this.Controls.Add(this.typeArea);
            this.Controls.Add(this.clickableArea);
            this.Name = "TestCommonWinFormsBehaviour";
            this.Text = "TestCommonWinFormsBehaviour";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label clickableArea;
        private System.Windows.Forms.TextBox typeArea;
        private System.Windows.Forms.TextBox textBoxLog;
    }
}


text:
<?php
namespace Icecave\Pasta\AST\Func;

use Icecave\Pasta\AST\Expr\QualifiedIdentifier;

class ObjectTypeHint extends TypeHint
{
    public function __construct(QualifiedIdentifier $typeName)
    {
        $this->typeName = $typeName;
    }

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

    public function setTypeName(QualifiedIdentifier $typeName)
    {
        $this->typeName = $typeName;
    }

    private $typeName;
}


text:
package com.anadathur.elastic.easymapping

import javax.lang.model.element.Modifier
import com.squareup.javapoet.MethodSpec.Builder
import com.squareup.javapoet._

class DefaultMappingGen extends TypeGenerator {
  import scala.collection.JavaConversions._
  val generators = List(
    generateMappingType _,
    generateDefaultMappingType _,
    generateMappingTypeProperty _,
    generateDefaultMappingTypeProperty _
  )

  override def apply(config: Config): List[TypeSpec] = {
    generators.map(_.apply(config)).toList
  }

  def generateDefaultMappingType(config: Config): TypeSpec = {
    val params = getParamsOfMappingType(config)
    val builder =
      TypeSpec.classBuilder("DefaultMappingType")
        .addModifiers(Modifier.PUBLIC)
        .addSuperinterface(config.mappingTypeClass)
        .addFields(params.values.map {_.fieldBuilder.addModifiers(privFinal: _*).build() }.toList)

    val constructorParams = params.values.map { _.paramBuilder.build() }

    val codeBlockBuilder = CodeBlock.builder()
    for (param <- params.values) {
      codeBlockBuilder.addStatement(s"this.${param.name} = ${param.name}")
    }

    val constructorBuilder =
      MethodSpec.constructorBuilder()
        .addModifiers(Modifier.PUBLIC)
        .addParameters(constructorParams.toList)
        .addCode(codeBlockBuilder.build())
    val methods = getMethodBuilders(params).map { case (name, typeName, bldr) =>
        bldr.addCode(CodeBlock.builder().addStatement(s"return $name").build())
          .build()
    }

    val hashSet: ClassName = ClassName.get("java.util", "HashSet")
    val simpleMethod =
      MethodSpec.methodBuilder("isSimpleType")
        .returns(TypeName.BOOLEAN)
        .addModifiers(Modifier.PUBLIC)
        .addStatement("$T set = new $T<>()",  hashSet, hashSet)

    Array("string", "integer", "long", "float", "double", "boolean", "date").foreach {name =>
      simpleMethod.addStatement("set.add($S)", name)
    }

    simpleMethod.addStatement("return set.contains(this.typeName)")

    builder.addMethod(constructorBuilder.build())
      .addMethods(methods.toList)
      .addMethod(simpleMethod.build())
      .build()
  }

  def getMethodBuilders(params: Map[String, MetaParam]) =
    params.values.map { method =>
      (method.name, method.typeName, method.methodBuilder)
    }

  def getMethodName(name: String, typeName: TypeName) =
    (if (typeName.equals(TypeName.BOOLEAN)) "is" else "get") + name.capitalize

  def generateMappingType(config: Config): TypeSpec = {
    val fields =
      List("string", "integer", "long", "float", "double", "boolean", "date", "binary", "object", "nested")
        .map { name =>
          FieldSpec.builder(classOf[String], name.toUpperCase + "_TYPE")
             .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
            .initializer("\"" + name + "\"")
            .build()
        }

    val builders: Iterable[(String, TypeName, Builder)] = getMethodBuilders(getParamsOfMappingType(config))
    val builder =
      TypeSpec.interfaceBuilder("MappingType")
        .addModifiers(Modifier.PUBLIC)
        .addMethods(builders.map {_._3.addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC).build()}.toList)
        .addMethod(
          MethodSpec.methodBuilder("isSimpleType")
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .returns(TypeName.BOOLEAN)
            .build()
        )
        .addFields(fields)

    builder.build()
  }

  def generateMappingTypeProperty(config: Config): TypeSpec = {
    val methods = getMethodBuilders(getParamsOfMappingTypeParam(config)).map { case (name, tName, bldr) =>
      bldr.addModifiers(pubAbs: _*).build()
     }

    TypeSpec.interfaceBuilder("MappingTypeProperty")
      .addModifiers(Modifier.PUBLIC)
      .addMethods(methods.toList)
      .build()
  }

  def generateDefaultMappingTypeProperty(config: Config): TypeSpec = {
    val param: Map[String, MetaParam] = getParamsOfMappingTypeParam(config)
    val methods = getMethodBuilders(param).map { case (name, tName, bldr) =>
      bldr.addModifiers(Modifier.PUBLIC)
        .addStatement("return $N", name)
        .build()
    }

    val block = CodeBlock.builder()
    param.values.foreach { p => block.addStatement("this.$N = $N", p.name, p.name)}
    TypeSpec.classBuilder("DefaultMappingTypeProperty")
      .addModifiers(Modifier.PUBLIC)
      .addMethod(
        MethodSpec.constructorBuilder()
          .addModifiers(Modifier.PUBLIC)
          .addParameters(param.values.map(_.paramBuilder.build()).toList)
          .addCode(block.build())
          .build()
      )
      .addFields(param.values.map(_.fieldBuilder.addModifiers(privFinal: _*).build()).toList)
      .addMethods(methods.toList)
      .build()

  }
}


text:
$(document).ready(function()
{
	/* Define menu click toggle handlers */
	$("#meatlover_button").click(function()
	{
		$("#meatlover_items").toggle("slow");
	});

	$("#healthlover_button").click(function()
	{
		$("#healthlover_items").toggle("fast");
	});

	$("#drink_button").click(function()
	{
		$("#drink_items").toggle(2000);
	});

	/** Define item hover animation handlers (for left and right actions) */
	$("ol").hover(
		function()
		{
			$(this).animate({ marginLeft:38, marginRight: 0 });

		},
		function()
		{
			$(this).animate({ marginLeft:18, marginRight: 18 });
		}
	);
});


text:
#ifndef CORE_BASIS_CRVQUADRATICLGN_H
#define CORE_BASIS_CRVQUADRATICLGN_H 1

#include <Core/Basis/CrvLinearLgn.h>
#include <Core/Basis/share.h>

namespace SCIRun {
namespace Core {
namespace Basis {

/// Class for describing unit geometry of CrvLinearLgn
class SCISHARE CrvQuadraticLgnUnitElement : public CrvLinearLgnUnitElement {
public:
  static double unit_vertices[3][1]; ///< Parametric coordinates of vertices of unit edge

  CrvQuadraticLgnUnitElement() {}
  virtual ~CrvQuadraticLgnUnitElement() {}

  static int number_of_vertices() { return 3; } ///< return number of vertices
  static int dofs() { return 3; } ///< return degrees of freedom
};

/// Class for handling of element of type curve with
/// quadratic lagrangian interpolation
template <class T>
  class CrvQuadraticLgn : public BasisAddNodes<T>,
                          public CrvApprox,
			  public CrvGaussian2<double>,
        public CrvSamplingSchemes,
			  public CrvQuadraticLgnUnitElement,
        public CrvElementWeights
{
public:
  typedef T value_type;

  CrvQuadraticLgn() {}
  virtual ~CrvQuadraticLgn() {}

  static int polynomial_order() { return 2; }

  template<class VECTOR>
  inline void get_weights(const VECTOR& coords, double *w) const
    { get_quadratic_weights(coords,w); }

  template<class VECTOR>
  inline void get_derivate_weights(const VECTOR& coords, double *w) const
    { get_quadratic_derivate_weights(coords,w); }

  /// get value at parametric coordinate
  template <class ElemData, class VECTOR>
  T interpolate(const VECTOR &coords, const ElemData &cd) const
  {
    double w[3];
    get_quadratic_weights(coords, w);

    return T(
        w[0] * cd.node0() +
	      w[1] * cd.node1() +
	      w[2] * this->nodes_[cd.edge0_index()]);
  }

  /// get derivative weight factors at parametric coordinate

  /// get first derivative at parametric coordinate
  template <class ElemData, class VECTOR1, class VECTOR2>
  void derivate(const VECTOR1 &coords, const ElemData &cd,
		VECTOR2 &derivs) const
  {
    double w[3];
    get_quadratic_derivate_weights(coords, w);

    derivs.resize(1);
    derivs[0] = static_cast<typename VECTOR2::value_type>(
        w[0] * cd.node0()
      + w[1] * cd.node1()
      + w[2] * this->nodes_[cd.edge0_index()]);
  }

  /// get parametric coordinate for value within the element
  template <class ElemData, class VECTOR>
  bool get_coords(VECTOR &coords, const T& value,
		  const ElemData &cd) const
  {
    CrvLocate< CrvQuadraticLgn<T> > CL;
    return CL.get_coords(this, coords, value, cd);
  }

  /// get arc length for edge
  template <class ElemData>
  double get_arc_length(const unsigned edge, const ElemData &cd) const
  {
    return get_arc1d_length<CrvGaussian2<double> >(this, edge, cd);
  }

  /// get area
  template <class ElemData>
    double get_area(const unsigned /* face */, const ElemData & /* cd */) const
  {
    return 0.;
  }

  /// get volume
  template <class ElemData>
    double get_volume(const ElemData & /* cd */) const
  {
    return 0.;
  }

  static  const std::string type_name(int n = -1);

  virtual void io (Piostream& str);

};

template <class T>
const std::string
CrvQuadraticLgn<T>::type_name(int n)
{
  ASSERT((n >= -1) && n <= 1);
  if (n == -1)
  {
    static const std::string name = TypeNameGenerator::make_template_id(type_name(0), type_name(1));
    return name;
  }
  else if (n == 0)
  {
    static const std::string nm("CrvQuadraticLgn");
    return nm;
  } else {
    return find_type_name((T *)0);
  }
}

}}
template <class T>
const TypeDescription* get_type_description(Core::Basis::CrvQuadraticLgn<T> *)
{
  static TypeDescription* td = 0;
  if(!td){
    const TypeDescription *sub = get_type_description((T*)0);
    TypeDescription::td_vec *subs = new TypeDescription::td_vec(1);
    (*subs)[0] = sub;
    td = new TypeDescription("CrvQuadraticLgn", subs,
      std::string(__FILE__),
      "SCIRun",
      TypeDescription::BASIS_E);
  }
  return td;
}

const int CRVQUADRATICLGN_VERSION = 1;
template <class T>
void
  Core::Basis::CrvQuadraticLgn<T>::io(Piostream &stream)
{
  stream.begin_class(get_type_description(this)->get_name(),
    CRVQUADRATICLGN_VERSION);
  Pio(stream, this->nodes_);
  stream.end_class();
}
}

#endif


text:
#ifndef Yarr_h
#define Yarr_h

#include <limits.h>

#include "YarrInterpreter.h"
#include "YarrPattern.h"

namespace JSC { namespace Yarr {

#define YarrStackSpaceForBackTrackInfoPatternCharacter 1 // Only for !fixed quantifiers.
#define YarrStackSpaceForBackTrackInfoCharacterClass 1 // Only for !fixed quantifiers.
#define YarrStackSpaceForBackTrackInfoBackReference 2
#define YarrStackSpaceForBackTrackInfoAlternative 1 // One per alternative.
#define YarrStackSpaceForBackTrackInfoParentheticalAssertion 1
#define YarrStackSpaceForBackTrackInfoParenthesesOnce 1 // Only for !fixed quantifiers.
#define YarrStackSpaceForBackTrackInfoParenthesesTerminal 1
#define YarrStackSpaceForBackTrackInfoParentheses 2

static const unsigned quantifyInfinite = UINT_MAX;

// The below limit restricts the number of "recursive" match calls in order to
// avoid spending exponential time on complex regular expressions.
static const unsigned matchLimit = 1000000;

enum JSRegExpResult {
    JSRegExpMatch = 1,
    JSRegExpNoMatch = 0,
    JSRegExpErrorNoMatch = -1,
    JSRegExpErrorHitLimit = -2,
    JSRegExpErrorNoMemory = -3,
    JSRegExpErrorInternal = -4
};

PassOwnPtr<BytecodePattern> byteCompile(YarrPattern&, BumpPointerAllocator*);
int interpret(BytecodePattern*, const UChar* input, unsigned start, unsigned length, int* output);

} } // namespace JSC::Yarr

#endif // Yarr_h


text:
import os.path

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)

MANAGERS = ADMINS

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(PROJECT_ROOT, 'download.db'),
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''

# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'n309^dwk=@+g72ko--8vjyz&1v0u%xf#*0=wzr=2n#f3hb0a=l'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
    # 'django.template.loaders.eggs.load_template_source',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

ROOT_URLCONF = 'example.urls'

TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'download',
    'sendfile',
)

# SENDFILE settings
SENDFILE_BACKEND = 'sendfile.backends.development'
#SENDFILE_BACKEND = 'sendfile.backends.xsendfile'
#SENDFILE_BACKEND = 'sendfile.backends.nginx'
SENDFILE_ROOT = os.path.join(PROJECT_ROOT, 'protected')
SENDFILE_URL = '/protected'


text:
function PoseM = MosquitoFlightSimNormal(PoseM,L,nIters,timeStep,mu,sigma)
% Simulates a group of mosquitoes in an area LxL meters using a random
% walk model that is biased toward a normal distribution centered at
% (mu(1),mu(2)) with a standard deviation of sigma.
%
% Authors: Mary Burbage (mcfieler@uh.edu), Aaron Becker (atbecker@uh.edu)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%% parameters
%defaults
if nargin<3
    disp('Aborted:  Insufficient parameters passed')
    return
end
if nargin<4
    timeStep = 1;
    mu = [L/2 L/2];
    sigma = L/10;
elseif nargin<5
    mu = [L/2 L/2];
    sigma = L/10;
elseif nargin<6
    sigma = L/10;
end

%set mosquito flight parameters
headingstdM = 3.0; %heading randomness for the mosquitos
velocitystdM = 0.4; %m/s  (The Biology of Mosquitos, Vol. II, A.N.Clements)

[nM,~]=size(PoseM);

%%% Loop for simulating movement
for i = 1:nIters
    Sm = PoseM(:,4);

    %generate a normal distribution of target positions centered at mu and
    %with a standard deviation of sigma
    targetPoseM = repmat(mu,nM,1) + randn(nM,2)*sigma;
    %set biasheading toward target position
    deltaY = targetPoseM(:,2)-PoseM(:,2);
    deltaX = targetPoseM(:,1)-PoseM(:,1);
    biasheading=atan2(deltaY,deltaX);
    %generate a random component for the heading direction
    headingchange = headingstdM*(-1 + 2*rand(nM,1));
    %new heading = bias + random component
    theta = biasheading+headingchange.*Sm;
    %add a random velocity
    movement = velocitystdM*rand(nM,1)*timeStep;
    X = PoseM(:,1) + movement.*cos(theta).*Sm;
    Y = PoseM(:,2) + movement.*sin(theta).*Sm;
    % use the toroidal assumption to wrap everything back to L x L
    X = X-L*(X>L);
    X = X+L*(X<0);
    Y = Y-L*(Y>L);
    Y = Y+L*(Y<0);
    PoseM = [X,Y,theta,Sm];
end


text:
<resources>
    <style name="SelectorTheme" parent="@android:style/Theme.DeviceDefault">
    </style>
</resources>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Olivier Jan: Le résumé</title>
  <meta property="og:title" content="Olivier Jan: Le résumé" />
  <meta property="og:image" content="https://olivierjan.com/resume/img/working.jpg" />
  <meta name="description" content="Software Platform Engineer with experience leveraging agile, DevOps, and CI/CD to manage large scale distributed platforms both on prem and in public cloud.">
  <meta property="og:description" content="Software Platform Engineer with experience leveraging agile, DevOps, and CI/CD to manage large scale distributed platforms both on prem and in public cloud." />
  <meta name="author" content="Olivier Jan">

  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

  <link href="https://fonts.googleapis.com/css?family=Saira+Extra+Condensed:100,200,300,400,500,600,700,800,900" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet">
  <link href="https://use.fontawesome.com/releases/v5.10.1/css/all.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css" rel="stylesheet">

  <link href="https://olivierjan.com/resume/css/resume.css" rel="stylesheet">
  <link href="https://olivierjan.com/resume/css/tweaks.css" rel="stylesheet">
  <meta name="generator" content="Hugo 0.57.2" />

      Olivier Jan

    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

              Compétences

              Expériences

              Publications

              Engagements

              Distinctions

              Education

              Intérêts

              Langues

Olivier
            Jan

3 rue Ladevèze 42000 Saint-Etienne, FR ·
            olivi-remove-er.jan@protonmail.com

Spécialiste des systèmes d'information dans des domaines comme le monitoring, l'intégration et le déploiement continu, l'infrastructure as code, la culture DevOps, le développement Agile.

 Compétences

Ansible et Terraform

Nagios

Prometheus et Grafana

ELK

Packer et Vagrant

Kubernetes

Jenkins/Gitlab/Github

Docker et LXC

Nginx et Apache2

Haproxy

 Expériences

Responsable Innovation et Stratégie Open Source

Adista

Sélection des technologies adaptées pour répondre aux offres du commerce.

Architecture des plate-formes d'hébergement Cloud.

Sensibilisation et formation interne sur DevOps et automatisation « CI/CD ».

            2016-04 /

Co-gérant

Co-fondateur et gérant

Définition du service de monitoring et architecture.

Gestion commerciale et support technique.

Rédaction d'articles sur la performance web.

            2013-08 / 2016-04

Directeur Projet Open Source

Capensis

Spécifications techniques et fonctionnelles, architecture de la solution d'hypervision.

Management de l'équipe de développement en mode Agile « 5 personnes ».

Rédaction d'articles techniques sur le monitoring.

Construction et animation de la communauté des clients et utilisateurs.

            2011-01 / 2013-08

Expert Monitoring

GFI

Leader technique sur les solutions de monitoring et supervision Open Source.

Architecture d'une solution nationale de supervision basée sur Nagios pour +1000 serveurs.

Management du pôle d'expertise national Supervision de GFI « 8 personnes ».

            2006-09 / 2010-09

CEO

EasyWay Consultants LTD

Création de la société à Hong-Kong.

Travail complet à distance.

Infrastructure Linux et applications web.

            2004-07 / 2006-09

Responsable des Activités Internet

Courtage et Communication

Développement et administration des sites e-commerce.

Travail sur site et à distance.

Management de l'équipe Internet « 3 personnes ».

            2000-07 / 2004-07

Resonsable Informatique

ARIFOPE

Administration des postes de travail MacOS.

Administration des serveurs Internet.

Développement de contenus digitaux « CD-ROM et Internet ».

Formation des utilisateurs régionaux à Internet.

            1995-09 / 1999-01

Responsable d'agence

International Computer

Commercial Mac et PC.

Support technique clients.

Gestion de l'agence « commande, livraison, stock, facturation ».

            1992-01 / 1995-09

 Publications

Time to say goodbye to your Nagios based setup

Slideshare - 2014

Conférence donnée à Nuremberg lors de l'OSMC.

Wooster: Website Booster

CheckMyWebsite - 2013

Un blog sur la performance, le monitoring, l'optimisation et tout ce qui permet d'améliorer votre site web.

Monitoring Solutions for the Next Decade

Slideshare - 2011

Conférence donnée à Nuremberg et Bolzano en anglais puis Strasbourg en français.

Nagios au cœur de la supervision Open Source

ENI Editions - 2009

Livre complet sur l'architecture et la configuration de Nagios.

 Engagements

Meetup Nantes Monitoring

Organisateur

Organisateur  et animateur des meetups nantais pendant 2 ans.

            2015

Communauté Francophone de la Supervision Libre

Co-fondateur

Création et animation d'une communauté de passionés de monitoring Open Source.

            2010

 Distinctions

Administrateur Xen Server

Citrix

            2009

Certification ITIL

ITIL

            2008

 Education

Université Catholique de l'Ouest

Licence

Activités Physiques et Sportives

Pédagogie

Psychologie

Anatomie

Biomécanique

                  1985-09 / 1989-06

Fédération Française de Handball

Brevet d'Etat 1er degré

Handball

Pédagogie

Arbitrage

Encadrement

                  1988-09 / 1989-04

 Centres d'intérêts

Voyages

L'important n'est pas la destination…

Ile Maurice

Réunion

Hong-Kong

Croatie

Musique

Amateur de musique et musicien électronique.

Rock

House

Jazz

Mix

Production

Live

Sport

Ancien professeur d'éducation physique et sportive.

Squash

Handball

Natation

Voile

Trail

Nature

Savoir où se trouve sa vraie place.

Randonnée

Trail

Natation

Moto

 Langues

Français

native

Anglais

advanced

Allemand

intermediate


text:
* This repository is complete and will no longer be updated.
You will find the project of components for Angular2 on https://github.com/DSI-HUG which is the official project of the University Hospital of Geneva - Switzerland*

* Ce référentiel est terminé et ne sera plus mise à jour.
Vous retrouverez la suite de projet de composants pour Angular2 sur  https://github.com/DSI-HUG qui est le projet officiel de l'Hôpital Universitaire de Genève - Suisse*

npm : https://www.npmjs.com/package/@deja-js/component

-------------------

# @deja-js/angular2
This is the home for the KillingJokeCHOrg/dejajs team's Angular2 components for Angular 2 and material.

## Intro

This repository is a Angular2 components library, with a demo application to testing it.

### Node.js and npm

Node.js and Node's package manager, npm, are used for installing dependencies,
running the build steps, and running tests.

### Getting started

Begin by cloning the repository.

Use npm to get dependencies:

`npm install`

Take a look at the `src` folder. All components and demo application are placed here.

## Running demo app

`npm start`

and navigate to `http://localhost:5200`.


text:
package ezbake.frack.eventbus.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class CopyHelper {
    public static <T> T deepCopyObject(T orig) {
        Object obj = null;
        try {
            // Write the object out to a byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bos);
            out.writeObject(orig);
            out.flush();
            out.close();

            // Make an input stream from the byte array and read
            // a copy of the object back in.
            ObjectInputStream in = new ObjectInputStream(
                    new ByteArrayInputStream(bos.toByteArray()));
            obj = in.readObject();
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
        return (T)obj;
    }
}


text:
umask 077
set -e

MYNAME="$0"

# emulate realpath(), in case coreutils or equivalent is not installed.
abspath() {
    f="$*"
    if test -d "$f"; then
        dir="$f"
        base=""
    else
        dir="$(dirname "$f")"
        base="/$(basename "$f")"
    fi
    dir="$(cd "$dir" && pwd)"
    echo "$dir$base"
}

# find the tor binary
if test $# -ge 1; then
  TOR_BINARY="$1"
  shift
else
  TOR_BINARY="${TESTING_TOR_BINARY:-./src/app/tor}"
fi

TOR_BINARY="$(abspath "$TOR_BINARY")"

echo "Using Tor binary '$TOR_BINARY'."

# make a safe space for temporary files
DATA_DIR=$(mktemp -d -t tor_parseconf_tests.XXXXXX)
trap 'rm -rf "$DATA_DIR"' 0

# This is where we look for examples
EXAMPLEDIR="$(dirname "$0")"/conf_examples

case "$(uname -s)" in
    CYGWIN*) WINDOWS=1;;
    MINGW*) WINDOWS=1;;
    MSYS*) WINDOWS=1;;
    *) WINDOWS=0;;
esac

####
# BUG WORKAROUND FOR 31757:
#  On Appveyor, it seems that Tor sometimes randomly fails to produce
#  output with --dump-config.  Whil we are figuring this out, do not treat
#  windows errors as hard failures.
####
if test "$WINDOWS" = 1; then
    EXITCODE=0
else
    EXITCODE=1
fi

FINAL_EXIT=0
NEXT_TEST=

# Log a failure message to stderr, using $@ as a printf string and arguments
# Set NEXT_TEST to "yes" and FINAL_EXIT to $EXITCODE.
fail_printf()
{
    printf "FAIL: " >&2
    # The first argument is a printf string, so this warning is spurious
    # shellcheck disable=SC2059
    printf "$@" >&2
    NEXT_TEST="yes"
    FINAL_EXIT=$EXITCODE
}

# Log a failure message to stderr, using $@ as a printf string and arguments
# Exit with status $EXITCODE.
die_printf()
{
    printf "FAIL: CRITICAL error in '%s':" "$MYNAME" >&2
    # The first argument is a printf string, so this warning is spurious
    # shellcheck disable=SC2059
    printf "$@" >&2
    exit $EXITCODE
}

if test "$WINDOWS" = 1; then
    FILTER="dos2unix"
else
    FILTER="cat"
fi

EMPTY="${DATA_DIR}/EMPTY"
touch "$EMPTY" || die_printf "Couldn't create empty file '%s'.\\n" \
                             "$EMPTY"
NON_EMPTY="${DATA_DIR}/NON_EMPTY"
echo "This pattern should not match any log messages" \
     > "$NON_EMPTY" || die_printf "Couldn't create non-empty file '%s'.\\n" \
                                  "$NON_EMPTY"

STANDARD_LIBS="libevent\\|openssl\\|zlib"
# Lib names are restricted to [a-z0-9]* at the moment
# We don't actually want to support foreign accents here
# shellcheck disable=SC2018,SC2019
TOR_LIBS_ENABLED="$("$TOR_BINARY" --verify-config \
                      -f "$EMPTY" --defaults-torrc "$EMPTY" \
                    | sed -n 's/.* Tor .* running on .* with\(.*\)\./\1/p' \
                    | tr 'A-Z' 'a-z' | tr ',' '\n' \
                    | grep -v "$STANDARD_LIBS" | grep -v "n/a" \
                    | sed 's/\( and\)* \(lib\)*\([a-z0-9]*\) .*/\3/' \
                    | sort | tr '\n' '_')"
# Remove the last underscore, if there is one
TOR_LIBS_ENABLED=${TOR_LIBS_ENABLED%_}

# If we ever have more than 3 optional libraries, we'll need more code here
TOR_LIBS_ENABLED_COUNT="$(echo "$TOR_LIBS_ENABLED_SEARCH" \
                          | tr ' ' '\n' | wc -l)"
if test "$TOR_LIBS_ENABLED_COUNT" -gt 3; then
    die_printf "Can not handle more than 3 optional libraries.\\n"
fi
# Brute-force the combinations of libraries
TOR_LIBS_ENABLED_SEARCH_3="$(echo "$TOR_LIBS_ENABLED" \
    | sed -n \
      's/^\([^_]*\)_\([^_]*\)_\([^_]*\)$/_\1_\2 _\1_\3 _\2_\3 _\1 _\2 _\3/p')"
TOR_LIBS_ENABLED_SEARCH_2="$(echo "$TOR_LIBS_ENABLED" \
    | sed -n 's/^\([^_]*\)_\([^_]*\)$/_\1 _\2/p')"
TOR_LIBS_ENABLED_SEARCH="_$TOR_LIBS_ENABLED \
                           $TOR_LIBS_ENABLED_SEARCH_3 \
                           $TOR_LIBS_ENABLED_SEARCH_2"
TOR_LIBS_ENABLED_SEARCH="$(echo "$TOR_LIBS_ENABLED_SEARCH" | tr ' ' '\n' \
                           | grep -v '^_*$' | tr '\n' ' ')"

TOR_MODULES_DISABLED="$("$TOR_BINARY" --list-modules | grep ': no' \
                        | cut -d ':' -f1 | sort | tr '\n' '_')"
# Remove the last underscore, if there is one
TOR_MODULES_DISABLED=${TOR_MODULES_DISABLED%_}

echo "Tor is configured with:"
echo "Optional Libraries: ${TOR_LIBS_ENABLED:-(None)}"
if test "$TOR_LIBS_ENABLED"; then
    echo "Optional Library Search List: $TOR_LIBS_ENABLED_SEARCH"
fi
echo "Disabled Modules: ${TOR_MODULES_DISABLED:-(None)}"

# Yes, unix uses "0" for a successful command
TRUE=0
FALSE=1

# Run tor --verify-config on the torrc $1, and defaults torrc $2, which may
# be $EMPTY. Pass tor the extra command line arguments $3, which will be
# passed unquoted.
# Send tor's standard output to stderr.
log_verify_config()
{
    # show the command we're about to execute
    # log_verify_config() is only called when we've failed
    printf "Tor --verify-config said:\\n" >&2
    printf "$ %s %s %s %s %s %s %s\\n" \
    "$TOR_BINARY" --verify-config \
                  -f "$1" \
                  --defaults-torrc "$2" \
                  "$3" \
                  >&2
    # We need cmdline unquoted
    # shellcheck disable=SC2086
    "$TOR_BINARY" --verify-config \
                  -f "$1" \
                  --defaults-torrc "$2" \
                  $3 \
                  >&2 \
        || true
}

# Run "tor --dump-config short" on the torrc $1, and defaults torrc $2, which
# may be $EMPTY. Pass tor the extra command line arguments $3, which will be
# passed unquoted. Send tor's standard output to $4.
#
# Set $FULL_TOR_CMD to the tor command line that was executed.
#
# If tor fails, fail_printf() using the file name $5, and context $6,
# which may be an empty string. Then run log_verify_config().
dump_config()
{
    if test "$6"; then
        CONTEXT=" $6"
    else
        CONTEXT=""
    fi

    # keep the command we're about to execute, and show if it we fail
    FULL_TOR_CMD=$(printf "$ %s %s %s %s %s %s %s %s" \
         "$TOR_BINARY" --dump-config short \
                       -f "$1" \
                       --defaults-torrc "$2" \
                       "$3"
             )
    # We need cmdline unquoted
    # shellcheck disable=SC2086
    if ! "$TOR_BINARY" --dump-config short \
                       -f "$1" \
                       --defaults-torrc "$2" \
                       $3 \
                       > "$4"; then
        fail_printf "'%s': Tor --dump-config reported an error%s:\\n%s\\n" \
                    "$5" \
                    "$CONTEXT" \
                    "$FULL_TOR_CMD"
        log_verify_config "$1" \
                          "$2" \
                          "$3"
    fi
}

# Run "$FILTER" on the input $1.
# Send the standard output to $2.
# If tor fails, log a failure message using the file name $3, and context $4,
# which may be an empty string.
filter()
{
    if test "$4"; then
        CONTEXT=" $4"
    else
        CONTEXT=""
    fi

    "$FILTER" "$1" \
              > "$2" \
        || fail_printf "'%s': Filter '%s' reported an error%s.\\n" \
                       "$3" \
                       "$FILTER" \
                       "$CONTEXT"
}

# Compare the expected file $1, and output file $2.
#
# If they are different, fail. Log the differences between the files.
# Run log_verify_config() with torrc $3, defaults torrc $4, and command
# line $5, to log Tor's error messages.
#
# If the file contents are identical, returns true. Otherwise, return false.
#
# Log failure messages using fail_printf(), with the expected file name,
# context $6, which may be an empty string, and the tor command line $7.
check_diff()
{
    if test "$6"; then
        CONTEXT=" $6"
    else
        CONTEXT=""
    fi

    if cmp "$1" "$2" > /dev/null; then
        return "$TRUE"
    else
        fail_printf "'%s': Tor --dump-config said%s:\\n%s\\n" \
                    "$1" \
                    "$CONTEXT" \
                    "$7"
        diff -u "$1" "$2" >&2 \
            || true
        log_verify_config "$3" \
                          "$4" \
                          "$5"
        return "$FALSE"
    fi
}

# Run "tor --dump-config short" on the torrc $1, and defaults torrc $2, which
# may be $EMPTY. Pass tor the extra command line arguments $3, which will be
# passed unquoted. Send tor's standard output to $4, after running $FILTER
# on it.
#
# If tor fails, run log_verify_config().
#
# Compare the expected file $5, and output file. If they are different, fail.
# If this is the first step that failed in this test, run log_verify_config().
#
# If the file contents are identical, returns true. Otherwise, return false,
# and log the differences between the files.
#
# Log failure messages using fail_printf(), with the expected file name, and
# context $6, which may be an empty string.
check_dump_config()
{
    OUTPUT="$4"
    OUTPUT_RAW="${OUTPUT}_raw"

    FULL_TOR_CMD=
    dump_config "$1" \
                "$2" \
                "$3" \
                "$OUTPUT_RAW" \
                "$5" \
                "$6"

    filter "$OUTPUT_RAW" \
           "$OUTPUT" \
           "$5" \
           "$6"

    if check_diff "$5" \
                  "$OUTPUT" \
                  "$1" \
                  "$2" \
                  "$3" \
                  "$6" \
                  "$FULL_TOR_CMD"; then
        return "$TRUE"
    else
        return "$FALSE"
    fi
}

# Check if $1 is an empty file.
# If it is, fail_printf() using $2 as the type of file.
# Returns true if the file is empty, false otherwise.
check_empty_pattern()
{
    if ! test -s "$1"; then
        fail_printf "%s file '%s' is empty, and will match any output.\\n" \
                    "$2" \
                    "$1"
        return "$TRUE"
    else
        return "$FALSE"
    fi
}

# Run tor --verify-config on the torrc $1, and defaults torrc $2, which may
# be $EMPTY. Pass tor the extra command line arguments $3, which will be
# passed unquoted. Send tor's standard output to $4.
#
# Set $FULL_TOR_CMD to the tor command line that was executed.
#
# If tor's exit status does not match the boolean $5, fail_printf()
# using the file name $6, and context $7, which is required.
verify_config()
{
    RESULT=$TRUE

    # keep the command we're about to execute, and show if it we fail
    FULL_TOR_CMD=$(printf "$ %s %s %s %s %s %s %s" \
    "$TOR_BINARY" --verify-config \
                  -f "$1" \
                  --defaults-torrc "$2" \
                  "$3"
             )
    # We need cmdline unquoted
    # shellcheck disable=SC2086
    "$TOR_BINARY" --verify-config \
                  -f "$1" \
                  --defaults-torrc "$2" \
                  $3 \
                  > "$4" || RESULT=$FALSE

    # Convert the actual and expected results to boolean, and compare
    if test $((! (! RESULT))) -ne $((! (! $5))); then
        fail_printf "'%s': Tor --verify-config did not %s:\\n%s\\n" \
                    "$6" \
                    "$7" \
                    "$FULL_TOR_CMD"
        cat "$4" >&2
    fi
}

# Check for the patterns in the match file $1, in the output file $2.
# Uses grep with the entire contents of the match file as the pattern.
# (Not "grep -f".)
#
# If the pattern does not match any lines in the output file, fail.
# Log the pattern, and the entire contents of the output file.
#
# Log failure messages using fail_printf(), with the match file name,
# context $3, and tor command line $4, which are required.
check_pattern()
{
    expect_log="$(cat "$1")"
    if ! grep "$expect_log" "$2" > /dev/null; then
        fail_printf "Expected %s '%s':\\n%s\\n" \
                    "$3" \
                    "$1" \
                    "$expect_log"
        printf "Tor --verify-config said:\\n%s\\n" \
               "$4" >&2
        cat "$2" >&2
    fi
}

# Run tor --verify-config on the torrc $1, and defaults torrc $2, which may
# be $EMPTY. Pass tor the extra command line arguments $3, which will be
# passed unquoted. Send tor's standard output to $4.
#
# If tor's exit status does not match the boolean $5, fail.
#
# Check for the patterns in the match file $6, in the output file.
# Uses grep with the entire contents of the match file as the pattern.
# (Not "grep -f".) The match file must not be empty.
#
# If the pattern does not match any lines in the output file, fail.
# Log the pattern, and the entire contents of the output file.
#
# Log failure messages using fail_printf(), with the match file name,
# and context $7, which is required.
check_verify_config()
{
    if check_empty_pattern "$6" "$7"; then
        return
    fi

    FULL_TOR_CMD=
    verify_config "$1" \
                  "$2" \
                  "$3" \
                  "$4" \
                  "$5" \
                  "$6" \
                  "$7"

    check_pattern "$6" \
                  "$4" \
                  "$7" \
                  "$FULL_TOR_CMD"
}

for dir in "${EXAMPLEDIR}"/*; do
    NEXT_TEST=

    if ! test -d "$dir"; then
       # Only count directories.
       continue
    fi

    testname="$(basename "${dir}")"
    # We use printf since "echo -n" is not standard
    printf "%s: " \
           "$testname"

    PREV_DIR="$(pwd)"
    cd "$dir"

    if test -f "./torrc.defaults"; then
        DEFAULTS="./torrc.defaults"
    else
        DEFAULTS="${DATA_DIR}/EMPTY"
    fi

    if test -f "./cmdline"; then
        CMDLINE="$(cat ./cmdline)"
    else
        CMDLINE=""
    fi

    EXPECTED=
    EXPECTED_LOG=
    ERROR=
    # Search for a custom result file for any combination of enabled optional
    # libraries
    # The libs in the list are [A-Za-z0-9_]* and space-separated.
    # shellcheck disable=SC2086
    for lib_suffix in $TOR_LIBS_ENABLED_SEARCH ""; do
        # Search for a custom result file for any disabled modules
        for mod_suffix in "_no_${TOR_MODULES_DISABLED}" ""; do
            suffix="${lib_suffix}${mod_suffix}"

            if test -f "./expected${suffix}"; then

                # Check for broken configs
                if test -f "./error${suffix}"; then
                    fail_printf "Found both '%s' and '%s'.%s\\n" \
                                "${dir}/expected${suffix}" \
                                "${dir}/error${suffix}" \
                                "(Only one of these files should exist.)"
                    break
                fi

                EXPECTED="./expected${suffix}"
                if test -f "./expected_log${suffix}"; then
                    EXPECTED_LOG="./expected_log${suffix}"
                fi
                break

            elif test -f "./error${suffix}"; then
                ERROR="./error${suffix}"
                break
            fi
        done

        # Exit as soon as the inner loop finds a file, or fails
        if test -f "$EXPECTED" || test -f "$ERROR" || test "$NEXT_TEST"; then
            break
        fi
    done

    if test "$NEXT_TEST"; then
        # The test failed inside the file search loop: go to the next test
        continue
    elif test -f "$EXPECTED"; then
        # This case should succeed: run dump-config and see if it does.

        if check_dump_config "./torrc" \
                             "$DEFAULTS" \
                             "$CMDLINE" \
                             "${DATA_DIR}/output.${testname}" \
                             "$EXPECTED" \
                             ""; then
            # Check round-trip.
            check_dump_config "${DATA_DIR}/output.${testname}" \
                              "$EMPTY" \
                              "" \
                              "${DATA_DIR}/output_2.${testname}" \
                              "$EXPECTED" \
                              "on round-trip" || true
        fi

        if test -f "$EXPECTED_LOG"; then
            # This case should succeed: run verify-config and see if it does.

            check_verify_config "./torrc" \
                                "$DEFAULTS" \
                                "$CMDLINE" \
                                "${DATA_DIR}/output_log.${testname}" \
                                "$TRUE" \
                                "$EXPECTED_LOG" \
                                "log success"
        else
            printf "\\nNOTICE: Missing '%s_log' file:\\n" \
                   "$EXPECTED" >&2
            log_verify_config "./torrc" \
                              "$DEFAULTS" \
                              "$CMDLINE"
        fi

   elif test -f "$ERROR"; then
        # This case should fail: run verify-config and see if it does.

        check_verify_config "./torrc" \
                            "$DEFAULTS" \
                            "$CMDLINE" \
                            "${DATA_DIR}/output.${testname}" \
                            "$FALSE" \
                            "$ERROR" \
                            "log error"
    else
        # This case is not actually configured with a success or a failure.
        # call that an error.
        fail_printf "Did not find ${dir}/*expected or ${dir}/*error.\\n"
    fi

    if test -z "$NEXT_TEST"; then
        echo "OK"
    fi

    cd "$PREV_DIR"

done

exit "$FINAL_EXIT"


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'ngMaterial',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$locationProvider', '$routeProvider',
  function($locationProvider, $routeProvider) {
    $locationProvider.hashPrefix('!');
    $routeProvider.otherwise({redirectTo: '/view1'});
}])
.controller('appCtrl', ['$location', function($location) {
  var vm = this;
  vm.beerview = function() { $location.path('/view1'); }
  vm.whiskeyview = function() { $location.path('/view2'); }
}]);


text:
/* Project Description:
 * This project creates a simple USB  device that appears as a USB gamepad on Windows  and can drive LEDs and take in buttons to control X-Plane.
 * Also includes MAX7221 routines for driving LEDs and 7 segment type displays.
 * This project is Opes Source under the
***************************************************************************** */

#include <device.h>
#include <stdio.h>

void StartUp (void); 		/* Function prototype for component startup API */
void ReadJoystick (void);   /* Function prototype for reading and altering data for joystick information */
void ReadButtons (void);    /* Function prototype for reading and altering data for button information */

//MAX7221
void MAX7221_StartUp(void);

//static uint16 X_Axis=0, Y_Axis=0;
static int16 X_Data=0, Y_Data=0;
static int8 Joystick_Data[3] = {0, 0, 0}; /*[0] = X-Axis, [1] = Y-Axis, [2] = Buttons */

static unsigned char Buttons = 0x0c;
static uint32 delay = 0;
int main()
{
    StartUp(); 								/* Calls the proper start API for all the components */

	for(;;)
    {
    	while(!USBFS_1_bGetEPAckState(1)); 	/* Wait for ACK before loading data */
		//ReadJoystick();						/* Calls function to read joystick movement */
		//ReadButtons();						/* Calls function to monitor button presses */

        if(delay++>100)
        {
            if((Buttons&0x0f) == 0x0A)
            {
                Buttons = 0x05;
                Pin_LED_Write(0x01);
            }
            else
            {
                Buttons = 0x0A;
                Pin_LED_Write(0x00);
            }
            delay=0;
        }
        //uint8 test = Button_A_Read();
        if(Button_A_Read() == 0)
        {
            Buttons = Buttons | 0x10;
        }
        else
        {
            Buttons = Buttons & 0x0f;
        }

		X_Data = 100-(delay*2);
        Joystick_Data[0] = X_Data;
		Joystick_Data[1] = Y_Data;
		Joystick_Data[2] = Buttons;

		USBFS_1_LoadInEP(1, (uint8 *)Joystick_Data, 3); /* Load latest mouse data into EP1 and send to PC */
    }
    return 0;
}

void StartUp (void)
{
	CYGlobalIntEnable;           					/* Enable Global interrupts */

	USBFS_1_Start(0, USBFS_1_DWR_VDDD_OPERATION);	/* Start USBFS operation/device 0 and with 5V operation */
	while(!USBFS_1_bGetConfiguration());			/* Wait for Device to enumerate */
    USBFS_1_LoadInEP(1, (uint8 *)Joystick_Data, 3); /* Loads an inital value into EP1 and sends it out to the PC */

}

uint8 MAX7221_Data[8] = {0,0,0,0,0,0,0,0};
void MAX7221_WriteRegister(uint8 addr, uint8 data)
{
    uint16 output = 0x0000;
    output = (addr << 8) + data;
    SPI_MAX7221_WriteTxData(output);
}

void MAX7221_UpdateDigit(uint8 digit)
{
    MAX7221_WriteRegister(digit+1,MAX7221_Data[digit]);
}

void MAX7221_LEDOn(uint8 index) // [5:3]=digit  [2:0]=segment
{
    uint8 digit = (index&0x38) >> 3;
    uint8 mask = 0x01 << (index&0x07);
    MAX7221_Data[digit] |= mask;
    MAX7221_UpdateDigit(digit);
}

void MAX7221_LEDOff(uint8 index) // [5:3]=digit  [2:0]=segment
{
    uint8 digit = (index&0x38) >> 3;
    uint8 mask = 0x01 << (index&0x07);
    MAX7221_Data[digit] &= (!mask);
    MAX7221_UpdateDigit(digit);
}

void MAX7221_SetDecodeMode(uint8 mode)
{
    MAX7221_WriteRegister(0x09,mode);
}

void MAX7221_SetIntensity(uint8 intensity)
{
    MAX7221_WriteRegister(0x0A,intensity);
}

void MAX7221_SetScanLimit(uint8 limit)
{
    MAX7221_WriteRegister(0x0B,limit);
}

void MAX7221_Shutdown(uint8 shutdown)
{
    MAX7221_WriteRegister(0x0C, shutdown);
}

void MAX7221_StartUp()
{
    SPI_MAX7221_Start();
}

/* End of File */


text:
import Transform from '@ember-data/serializer/transform';

export default class Raw extends Transform {
    deserialize(serialized) {
        return serialized;
    }

    serialize(deserialized) {
        return deserialized;
    }
}


text:
class AsyncMock {
	//region Fields

	private _mustFail : boolean;
	private _success : () => void;
	private _error : () => void;

	//endregion Fields

	//region Constructors

	constructor() {
		this._mustFail = false;
	}

	//endregion Constructors

	//region Methods

	//region Private Methods

	//endregion Private Methods

	//region Public Methods

	setSuccess(func : () => void) : AsyncMock {
		this._success = func;
		return this;
	}

	setError(func : () => void) : AsyncMock {
		this._error = func;
		return this;
	}

	mustFail() : AsyncMock {
		this._mustFail = true;
		return this;
	}

	run() : void {
		setTimeout(() => {
			if (this._mustFail) {
				this._error();
			} else {
				this._success();
			}
		}, 0);
	}

	//endregion Public Methods

	//endregion Methods
}


text:
require 'uri'
require 'cgi'
require 'date'
require 'json'
require 'base64'
require 'erb'
require 'securerandom'
require 'time'
require 'timeliness'
require 'faraday'
require 'faraday-cookie_jar'
require 'concurrent'
require 'ms_rest'
require '2015-12-01/generated/azure_mgmt_features/module_definition'
require 'ms_rest_azure'

module Azure::Features::Mgmt::V2015_12_01
  autoload :Features,                                           '2015-12-01/generated/azure_mgmt_features/features.rb'
  autoload :FeatureClient,                                      '2015-12-01/generated/azure_mgmt_features/feature_client.rb'

  module Models
    autoload :OperationDisplay,                                   '2015-12-01/generated/azure_mgmt_features/models/operation_display.rb'
    autoload :FeatureProperties,                                  '2015-12-01/generated/azure_mgmt_features/models/feature_properties.rb'
    autoload :Operation,                                          '2015-12-01/generated/azure_mgmt_features/models/operation.rb'
    autoload :FeatureOperationsListResult,                        '2015-12-01/generated/azure_mgmt_features/models/feature_operations_list_result.rb'
    autoload :OperationListResult,                                '2015-12-01/generated/azure_mgmt_features/models/operation_list_result.rb'
    autoload :FeatureResult,                                      '2015-12-01/generated/azure_mgmt_features/models/feature_result.rb'
  end
end


text:
#include "second_service.h"

USING_NS_QRDEMO;

bool SecondService::init()
{
    qInfo("second service initializing");
    return true;
}


text:
(function(){
Template.__checkName("comment_form");
Template["comment_form"] = new Template("Template.comment_form", (function() {
  var view = this;
  return Blaze.If(function() {
    return Spacebars.call(view.lookup("canComment"));
  }, function() {
    return [ "\n    ", HTML.DIV({
      "class": "comment-new module"
    }, "\n      ", HTML.FORM("\n        ", HTML.DIV({
      "class": "comment-field",
      id: "editor"
    }, "\n          ", HTML.TEXTAREA({
      id: "comment",
      rows: "3",
      autofocus: "autofocus"
    }), "\n        "), "\n        ", HTML.DIV({
      "class": "comment-submit"
    }, "\n          ", HTML.BUTTON({
      type: "submit",
      "class": "comment-submit-button btn btn-primary btn-submit",
      value: function() {
        return Spacebars.mustache(view.lookup("_"), "add_comment");
      },
      title: "(⌘+enter)"
    }, Blaze.View("lookup:_", function() {
      return Spacebars.mustache(view.lookup("_"), "add_comment");
    })), "\n        "), "\n      "), "\n    "), "\n  " ];
  }, function() {
    return [ "\n    ", HTML.P(Blaze.View("lookup:reason", function() {
      return Spacebars.mustache(view.lookup("reason"));
    })), "\n  " ];
  });
}));

})();


text:
  static const EGLint configAttribs[] = {
          EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
          EGL_BLUE_SIZE, 8,
          EGL_GREEN_SIZE, 8,
          EGL_RED_SIZE, 8,
          EGL_DEPTH_SIZE, 8,
          EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
          EGL_NONE
  };

  static const int pbufferWidth = 9;
  static const int pbufferHeight = 9;

  static const EGLint pbufferAttribs[] = {
        EGL_WIDTH, pbufferWidth,
        EGL_HEIGHT, pbufferHeight,
        EGL_NONE,
  };

// use eglGetDisplay or device/platform extensions to select display
#define USE_EGL_GET_DISPLAY
//#undef USE_EGL_GET_DISPLAY

// use egl surface or manually managed FBO as render target
#define USE_EGL_SURFACE
//#undef USE_EGL_SURFACE

int main(int argc, char *argv[])
{

    // 1. Initialize EGL
#ifdef USE_EGL_GET_DISPLAY
    // obtain the display via default display.
    EGLDisplay eglDpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
#else
    // obtain display by specifying an appropriate device. This is the preferred method today.

    // load the function pointers for the device,platform extensions
    PFNEGLQUERYDEVICESEXTPROC eglQueryDevicesEXT =
               (PFNEGLQUERYDEVICESEXTPROC) eglGetProcAddress("eglQueryDevicesEXT");
    if(!eglQueryDevicesEXT) {
         printf("ERROR: extension eglQueryDevicesEXT not available");
         return(-1);
    }

    PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT =
               (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
    if(!eglGetPlatformDisplayEXT) {
         printf("ERROR: extension eglGetPlatformDisplayEXT not available");
         return(-1);
    }

    static const int MAX_DEVICES = 16;
    EGLDeviceEXT devices[MAX_DEVICES];
    EGLint numDevices;

    eglQueryDevicesEXT(MAX_DEVICES, devices, &numDevices);

    EGLDisplay eglDpy = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, devices[0], 0);
#endif

    EGLint major, minor;

    eglInitialize(eglDpy, &major, &minor);

    // 2. Select appropriate configuration
    EGLint numConfigs;
    EGLConfig eglCfg;

    eglChooseConfig(eglDpy, configAttribs, &eglCfg, 1, &numConfigs);

    // 3. Bind the API
    eglBindAPI(EGL_OPENGL_API);

    // 4. create the context
    EGLContext eglCtx = eglCreateContext(eglDpy, eglCfg, EGL_NO_CONTEXT, NULL);

#ifdef USE_EGL_SURFACE
    // 5. create the surface and make the context current current
    EGLSurface eglSurf = eglCreatePbufferSurface(eglDpy, eglCfg, pbufferAttribs);
    eglMakeCurrent(eglDpy, eglSurf, eglSurf, eglCtx);
#else
    // 5. make the context current without a surface
    eglMakeCurrent(eglDpy, EGL_NO_SURFACE, EGL_NO_SURFACE, eglCtx);

    // manually create the OpenGL buffers and textures: A  framebuffer object with associated
    // texture and depth buffers.

    // create a 2D texture as the color buffer
    GLuint texId;
    glGenTextures(1, &texId);
    glBindTexture(GL_TEXTURE_2D,  texId);
    glTexImage2D(GL_TEXTURE_2D, 0,  GL_RGBA8,  pbufferWidth, pbufferHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glBindTexture(GL_TEXTURE_2D, 0);

    // create a renderbuffer for storing the depth component
    GLuint rbId;
    glGenRenderbuffers(1, &rbId);
    glBindRenderbuffer(GL_RENDERBUFFER, rbId);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, pbufferWidth, pbufferHeight);
    glBindRenderbuffer(GL_RENDERBUFFER, 0);

    // create the framebuffer and attach the texture (color buffer) and the renderbuffer (depth buffer)
    GLuint fbId;
    glGenFramebuffers(1, &fbId);
    glBindFramebuffer(GL_FRAMEBUFFER, fbId);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texId, 0);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbId);

    // set the buffer dimensions
    glViewport(0, 0, pbufferWidth, pbufferHeight);
#endif

    // Rendering a basic triangle
    glClearColor(0.0, 0.0, 0.0, 0.0);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBegin(GL_TRIANGLES);
    glColor3f(0.1, 0.2, 0.3);

    glVertex3f(-0.5, 0.5, 0);
    glVertex3f( 0.5, 0.5, 0);
    glVertex3f( 0, -0.5, 0);
    glEnd();

    // Read the triangle data back into a buffer
    unsigned char* data = (unsigned char*) malloc(4 * pbufferWidth * pbufferHeight);

    glReadPixels(0, 0, pbufferWidth, pbufferHeight, GL_RGBA, GL_UNSIGNED_BYTE, data);

    // write  the data out in ppm format
    printf("P3\n");
    printf("%d %d\n", pbufferWidth, pbufferHeight);
    printf("255 \n");
    int i=0;
    for(int y=0; y<pbufferHeight; y++){
      for(int x=0; x<pbufferWidth; x++) {
          printf("%2d %2d %2d ",(int) data[i+2],(int) data[i+1], (int) data[i+0]);
          i+=4;
      }
     printf("\n");
    }

    // cleanup
    free(data);

    eglTerminate(eglDpy);
    return 0;
}