text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=8 sts=4 et sw=4 tw=99:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef jit_VMFunctions_h
#define jit_VMFunctions_h

#include "jspubtd.h"

#include "jit/CompileInfo.h"
#include "jit/IonFrames.h"

namespace js {

class DeclEnvObject;
class ForkJoinContext;
class StaticWithObject;

namespace jit {

enum DataType {
    Type_Void,
    Type_Bool,
    Type_Int32,
    Type_Double,
    Type_Pointer,
    Type_Object,
    Type_Value,
    Type_Handle
};

struct PopValues
{
    uint32_t numValues;

    explicit PopValues(uint32_t numValues)
      : numValues(numValues)
    { }
};

// Contains information about a virtual machine function that can be called
// from JIT code. Functions described in this manner must conform to a simple
// protocol: the return type must have a special "failure" value (for example,
// false for bool, or nullptr for Objects). If the function is designed to
// return a value that does not meet this requirement - such as
// object-or-nullptr, or an integer, an optional, final outParam can be
// specified. In this case, the return type must be boolean to indicate
// failure.
//
// All functions described by VMFunction take a JSContext * as a first
// argument, and are treated as re-entrant into the VM and therefore fallible.
struct VMFunction
{
    // Global linked list of all VMFunctions.
    static VMFunction *functions;
    VMFunction *next;

    // Address of the C function.
    void *wrapped;

    // Number of arguments expected, excluding JSContext * as an implicit
    // first argument and an outparam as a possible implicit final argument.
    uint32_t explicitArgs;

    enum ArgProperties {
        WordByValue = 0,
        DoubleByValue = 1,
        WordByRef = 2,
        DoubleByRef = 3,
        // BitMask version.
        Word = 0,
        Double = 1,
        ByRef = 2
    };

    // Contains properties about the first 16 arguments.
    uint32_t argumentProperties;

    // Which arguments should be passed in float register on platforms that
    // have them.
    uint32_t argumentPassedInFloatRegs;

    // The outparam may be any Type_*, and must be the final argument to the
    // function, if not Void. outParam != Void implies that the return type
    // has a boolean failure mode.
    DataType outParam;

    // Type returned by the C function and used by the VMFunction wrapper to
    // check for failures of the C function.  Valid failure/return types are
    // boolean and object pointers which are asserted inside the VMFunction
    // constructor. If the C function use an outparam (!= Type_Void), then
    // the only valid failure/return type is boolean -- object pointers are
    // pointless because the wrapper will only use it to compare it against
    // nullptr before discarding its value.
    DataType returnType;

    // Note: a maximum of seven root types is supported.
    enum RootType {
        RootNone = 0,
        RootObject,
        RootString,
        RootPropertyName,
        RootFunction,
        RootValue,
        RootCell
    };

    // Contains an combination of enumerated types used by the gc for marking
    // arguments of the VM wrapper.
    uint64_t argumentRootTypes;

    // The root type of the out param if outParam == Type_Handle.
    RootType outParamRootType;

    // Does this function take a ForkJoinContext * or a JSContext *?
    ExecutionMode executionMode;

    // Number of Values the VM wrapper should pop from the stack when it returns.
    // Used by baseline IC stubs so that they can use tail calls to call the VM
    // wrapper.
    uint32_t extraValuesToPop;

    uint32_t argc() const {
        // JSContext * + args + (OutParam? *)
        return 1 + explicitArgc() + ((outParam == Type_Void) ? 0 : 1);
    }

    DataType failType() const {
        return returnType;
    }

    ArgProperties argProperties(uint32_t explicitArg) const {
        return ArgProperties((argumentProperties >> (2 * explicitArg)) & 3);
    }

    RootType argRootType(uint32_t explicitArg) const {
        return RootType((argumentRootTypes >> (3 * explicitArg)) & 7);
    }

    bool argPassedInFloatReg(uint32_t explicitArg) const {
        return ((argumentPassedInFloatRegs >> explicitArg) & 1) == 1;
    }

    // Return the stack size consumed by explicit arguments.
    size_t explicitStackSlots() const {
        size_t stackSlots = explicitArgs;

        // Fetch all double-word flags of explicit arguments.
        uint32_t n =
            ((1 << (explicitArgs * 2)) - 1) // = Explicit argument mask.
            & 0x55555555                    // = Mask double-size args.
            & argumentProperties;

        // Add the number of double-word flags. (expect a few loop
        // iteration)
        while (n) {
            stackSlots++;
            n &= n - 1;
        }
        return stackSlots;
    }

    // Double-size argument which are passed by value are taking the space
    // of 2 C arguments.  This function is used to compute the number of
    // argument expected by the C function.  This is not the same as
    // explicitStackSlots because reference to stack slots may take one less
    // register in the total count.
    size_t explicitArgc() const {
        size_t stackSlots = explicitArgs;

        // Fetch all explicit arguments.
        uint32_t n =
            ((1 << (explicitArgs * 2)) - 1) // = Explicit argument mask.
            & argumentProperties;

        // Filter double-size arguments (0x5 = 0b0101) and remove (& ~)
        // arguments passed by reference (0b1010 >> 1 == 0b0101).
        n = (n & 0x55555555) & ~(n >> 1);

        // Add the number of double-word transfered by value. (expect a few
        // loop iteration)
        while (n) {
            stackSlots++;
            n &= n - 1;
        }
        return stackSlots;
    }

    size_t doubleByRefArgs() const {
        size_t count = 0;

        // Fetch all explicit arguments.
        uint32_t n =
            ((1 << (explicitArgs * 2)) - 1) // = Explicit argument mask.
            & argumentProperties;

        // Filter double-size arguments (0x5 = 0b0101) and take (&) only
        // arguments passed by reference (0b1010 >> 1 == 0b0101).
        n = (n & 0x55555555) & (n >> 1);

        // Add the number of double-word transfered by refference. (expect a
        // few loop iterations)
        while (n) {
            count++;
            n &= n - 1;
        }
        return count;
    }

    VMFunction()
      : wrapped(nullptr),
        explicitArgs(0),
        argumentProperties(0),
        argumentPassedInFloatRegs(0),
        outParam(Type_Void),
        returnType(Type_Void),
        outParamRootType(RootNone),
        executionMode(SequentialExecution),
        extraValuesToPop(0)
    {
    }

    VMFunction(void *wrapped, uint32_t explicitArgs, uint32_t argumentProperties,
               uint32_t argumentPassedInFloatRegs, uint64_t argRootTypes,
               DataType outParam, RootType outParamRootType, DataType returnType,
               ExecutionMode executionMode, uint32_t extraValuesToPop = 0)
      : wrapped(wrapped),
        explicitArgs(explicitArgs),
        argumentProperties(argumentProperties),
        argumentPassedInFloatRegs(argumentPassedInFloatRegs),
        outParam(outParam),
        returnType(returnType),
        argumentRootTypes(argRootTypes),
        outParamRootType(outParamRootType),
        executionMode(executionMode),
        extraValuesToPop(extraValuesToPop)
    {
        // Check for valid failure/return type.
        JS_ASSERT_IF(outParam != Type_Void && executionMode == SequentialExecution,
                     returnType == Type_Bool);
        JS_ASSERT(returnType == Type_Bool ||
                  returnType == Type_Object);
    }

    VMFunction(const VMFunction &o) {
        init(o);
    }

    void init(const VMFunction &o) {
        JS_ASSERT(!wrapped);
        *this = o;
        addToFunctions();
    }

  private:
    // Add this to the global list of VMFunctions.
    void addToFunctions();
};

// A collection of VM functions for each execution mode.
struct VMFunctionsModal
{
    explicit VMFunctionsModal(const VMFunction &info) {
        add(info);
    }
    VMFunctionsModal(const VMFunction &info1, const VMFunction &info2) {
        add(info1);
        add(info2);
    }

    inline const VMFunction &operator[](ExecutionMode mode) const {
        JS_ASSERT((unsigned)mode < NumExecutionModes);
        return funs_[mode];
    }

  private:
    void add(const VMFunction &info) {
        JS_ASSERT((unsigned)info.executionMode < NumExecutionModes);
        funs_[info.executionMode].init(info);
    }

    mozilla::Array<VMFunction, NumExecutionModes> funs_;
};

template <class> struct TypeToDataType { /* Unexpected return type for a VMFunction. */ };
template <> struct TypeToDataType<bool> { static const DataType result = Type_Bool; };
template <> struct TypeToDataType<JSObject *> { static const DataType result = Type_Object; };
template <> struct TypeToDataType<DeclEnvObject *> { static const DataType result = Type_Object; };
template <> struct TypeToDataType<JSString *> { static const DataType result = Type_Object; };
template <> struct TypeToDataType<JSFlatString *> { static const DataType result = Type_Object; };
template <> struct TypeToDataType<HandleObject> { static const DataType result = Type_Handle; };
template <> struct TypeToDataType<HandleString> { static const DataType result = Type_Handle; };
template <> struct TypeToDataType<HandlePropertyName> { static const DataType result = Type_Handle; };
template <> struct TypeToDataType<HandleFunction> { static const DataType result = Type_Handle; };
template <> struct TypeToDataType<Handle<StaticWithObject *> > { static const DataType result = Type_Handle; };
template <> struct TypeToDataType<Handle<StaticBlockObject *> > { static const DataType result = Type_Handle; };
template <> struct TypeToDataType<HandleScript> { static const DataType result = Type_Handle; };
template <> struct TypeToDataType<HandleValue> { static const DataType result = Type_Handle; };
template <> struct TypeToDataType<MutableHandleValue> { static const DataType result = Type_Handle; };

// Convert argument types to properties of the argument known by the jit.
template <class T> struct TypeToArgProperties {
    static const uint32_t result =
        (sizeof(T) <= sizeof(void *) ? VMFunction::Word : VMFunction::Double);
};
template <> struct TypeToArgProperties<const Value &> {
    static const uint32_t result = TypeToArgProperties<Value>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<HandleObject> {
    static const uint32_t result = TypeToArgProperties<JSObject *>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<HandleString> {
    static const uint32_t result = TypeToArgProperties<JSString *>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<HandlePropertyName> {
    static const uint32_t result = TypeToArgProperties<PropertyName *>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<HandleFunction> {
    static const uint32_t result = TypeToArgProperties<JSFunction *>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<Handle<StaticWithObject *> > {
    static const uint32_t result = TypeToArgProperties<StaticWithObject *>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<Handle<StaticBlockObject *> > {
    static const uint32_t result = TypeToArgProperties<StaticBlockObject *>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<HandleScript> {
    static const uint32_t result = TypeToArgProperties<JSScript *>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<HandleValue> {
    static const uint32_t result = TypeToArgProperties<Value>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<MutableHandleValue> {
    static const uint32_t result = TypeToArgProperties<Value>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<HandleShape> {
    static const uint32_t result = TypeToArgProperties<Shape *>::result | VMFunction::ByRef;
};
template <> struct TypeToArgProperties<HandleTypeObject> {
    static const uint32_t result = TypeToArgProperties<types::TypeObject *>::result | VMFunction::ByRef;
};

// Convert argument type to whether or not it should be passed in a float
// register on platforms that have them, like x64.
template <class T> struct TypeToPassInFloatReg {
    static const uint32_t result = 0;
};
template <> struct TypeToPassInFloatReg<double> {
    static const uint32_t result = 1;
};

// Convert argument types to root types used by the gc, see MarkJitExitFrame.
template <class T> struct TypeToRootType {
    static const uint32_t result = VMFunction::RootNone;
};
template <> struct TypeToRootType<HandleObject> {
    static const uint32_t result = VMFunction::RootObject;
};
template <> struct TypeToRootType<HandleString> {
    static const uint32_t result = VMFunction::RootString;
};
template <> struct TypeToRootType<HandlePropertyName> {
    static const uint32_t result = VMFunction::RootPropertyName;
};
template <> struct TypeToRootType<HandleFunction> {
    static const uint32_t result = VMFunction::RootFunction;
};
template <> struct TypeToRootType<HandleValue> {
    static const uint32_t result = VMFunction::RootValue;
};
template <> struct TypeToRootType<MutableHandleValue> {
    static const uint32_t result = VMFunction::RootValue;
};
template <> struct TypeToRootType<HandleShape> {
    static const uint32_t result = VMFunction::RootCell;
};
template <> struct TypeToRootType<HandleTypeObject> {
    static const uint32_t result = VMFunction::RootCell;
};
template <> struct TypeToRootType<HandleScript> {
    static const uint32_t result = VMFunction::RootCell;
};
template <> struct TypeToRootType<Handle<StaticBlockObject *> > {
    static const uint32_t result = VMFunction::RootObject;
};
template <> struct TypeToRootType<Handle<StaticWithObject *> > {
    static const uint32_t result = VMFunction::RootCell;
};
template <class T> struct TypeToRootType<Handle<T> > {
    // Fail for Handle types that aren't specialized above.
};

template <class> struct OutParamToDataType { static const DataType result = Type_Void; };
template <> struct OutParamToDataType<Value *> { static const DataType result = Type_Value; };
template <> struct OutParamToDataType<int *> { static const DataType result = Type_Int32; };
template <> struct OutParamToDataType<uint32_t *> { static const DataType result = Type_Int32; };
template <> struct OutParamToDataType<uint8_t **> { static const DataType result = Type_Pointer; };
template <> struct OutParamToDataType<bool *> { static const DataType result = Type_Bool; };
template <> struct OutParamToDataType<double *> { static const DataType result = Type_Double; };
template <> struct OutParamToDataType<MutableHandleValue> { static const DataType result = Type_Handle; };
template <> struct OutParamToDataType<MutableHandleObject> { static const DataType result = Type_Handle; };
template <> struct OutParamToDataType<MutableHandleString> { static const DataType result = Type_Handle; };

template <class> struct OutParamToRootType {
    static const VMFunction::RootType result = VMFunction::RootNone;
};
template <> struct OutParamToRootType<MutableHandleValue> {
    static const VMFunction::RootType result = VMFunction::RootValue;
};
template <> struct OutParamToRootType<MutableHandleObject> {
    static const VMFunction::RootType result = VMFunction::RootObject;
};
template <> struct OutParamToRootType<MutableHandleString> {
    static const VMFunction::RootType result = VMFunction::RootString;
};

template <class> struct MatchContext { };
template <> struct MatchContext<JSContext *> {
    static const ExecutionMode execMode = SequentialExecution;
};
template <> struct MatchContext<ExclusiveContext *> {
    static const ExecutionMode execMode = SequentialExecution;
};
template <> struct MatchContext<ForkJoinContext *> {
    static const ExecutionMode execMode = ParallelExecution;
};
template <> struct MatchContext<ThreadSafeContext *> {
    // ThreadSafeContext functions can be called from either mode, but for
    // calling from parallel they should be wrapped first, so we default to
    // SequentialExecution here.
    static const ExecutionMode execMode = SequentialExecution;
};

#define FOR_EACH_ARGS_1(Macro, Sep, Last) Macro(1) Last(1)
#define FOR_EACH_ARGS_2(Macro, Sep, Last) FOR_EACH_ARGS_1(Macro, Sep, Sep) Macro(2) Last(2)
#define FOR_EACH_ARGS_3(Macro, Sep, Last) FOR_EACH_ARGS_2(Macro, Sep, Sep) Macro(3) Last(3)
#define FOR_EACH_ARGS_4(Macro, Sep, Last) FOR_EACH_ARGS_3(Macro, Sep, Sep) Macro(4) Last(4)
#define FOR_EACH_ARGS_5(Macro, Sep, Last) FOR_EACH_ARGS_4(Macro, Sep, Sep) Macro(5) Last(5)
#define FOR_EACH_ARGS_6(Macro, Sep, Last) FOR_EACH_ARGS_5(Macro, Sep, Sep) Macro(6) Last(6)

#define COMPUTE_INDEX(NbArg) NbArg
#define COMPUTE_OUTPARAM_RESULT(NbArg) OutParamToDataType<A ## NbArg>::result
#define COMPUTE_OUTPARAM_ROOT(NbArg) OutParamToRootType<A ## NbArg>::result
#define COMPUTE_ARG_PROP(NbArg) (TypeToArgProperties<A ## NbArg>::result << (2 * (NbArg - 1)))
#define COMPUTE_ARG_ROOT(NbArg) (uint64_t(TypeToRootType<A ## NbArg>::result) << (3 * (NbArg - 1)))
#define COMPUTE_ARG_FLOAT(NbArg) (TypeToPassInFloatReg<A ## NbArg>::result) << (NbArg - 1)
#define SEP_OR(_) |
#define NOTHING(_)

#define FUNCTION_INFO_STRUCT_BODY(ForEachNb)                                            \
    static inline ExecutionMode executionMode() {                                       \
        return MatchContext<Context>::execMode;                                         \
    }                                                                                \
    static inline DataType returnType() {                                               \
        return TypeToDataType<R>::result;                                               \
    }                                                                                \
    static inline DataType outParam() {                                                 \
        return ForEachNb(NOTHING, NOTHING, COMPUTE_OUTPARAM_RESULT);                    \
    }                                                                                \
    static inline RootType outParamRootType() {                                         \
        return ForEachNb(NOTHING, NOTHING, COMPUTE_OUTPARAM_ROOT);                      \
    }                                                                                \
    static inline size_t NbArgs() {                                                     \
        return ForEachNb(NOTHING, NOTHING, COMPUTE_INDEX);                              \
    }                                                                                \
    static inline size_t explicitArgs() {                                               \
        return NbArgs() - (outParam() != Type_Void ? 1 : 0);                            \
    }                                                                                \
    static inline uint32_t argumentProperties() {                                       \
        return ForEachNb(COMPUTE_ARG_PROP, SEP_OR, NOTHING);                            \
    }                                                                                \
    static inline uint32_t argumentPassedInFloatRegs() {                                \
        return ForEachNb(COMPUTE_ARG_FLOAT, SEP_OR, NOTHING);                           \
    }                                                                                \
    static inline uint64_t argumentRootTypes() {                                        \
        return ForEachNb(COMPUTE_ARG_ROOT, SEP_OR, NOTHING);                            \
    }                                                                                \
    explicit FunctionInfo(pf fun, PopValues extraValuesToPop = PopValues(0))            \
        : VMFunction(JS_FUNC_TO_DATA_PTR(void *, fun), explicitArgs(),                  \
                     argumentProperties(), argumentPassedInFloatRegs(),                 \
                     argumentRootTypes(), outParam(), outParamRootType(),               \
                     returnType(), executionMode(),                                     \
                     extraValuesToPop.numValues)                                        \
    { }

template <typename Fun>
struct FunctionInfo {
};

// VMFunction wrapper with no explicit arguments.
template <class R, class Context>
struct FunctionInfo<R (*)(Context)> : public VMFunction {
    typedef R (*pf)(Context);

    static inline ExecutionMode executionMode() {
        return MatchContext<Context>::execMode;
    }
    static inline DataType returnType() {
        return TypeToDataType<R>::result;
    }
    static inline DataType outParam() {
        return Type_Void;
    }
    static inline RootType outParamRootType() {
        return RootNone;
    }
    static inline size_t explicitArgs() {
        return 0;
    }
    static inline uint32_t argumentProperties() {
        return 0;
    }
    static inline uint32_t argumentPassedInFloatRegs() {
        return 0;
    }
    static inline uint64_t argumentRootTypes() {
        return 0;
    }
    explicit FunctionInfo(pf fun)
      : VMFunction(JS_FUNC_TO_DATA_PTR(void *, fun), explicitArgs(),
                   argumentProperties(), argumentPassedInFloatRegs(),
                   argumentRootTypes(), outParam(), outParamRootType(),
                   returnType(), executionMode())
    { }
};

// Specialize the class for each number of argument used by VMFunction.
// Keep it verbose unless you find a readable macro for it.
template <class R, class Context, class A1>
struct FunctionInfo<R (*)(Context, A1)> : public VMFunction {
    typedef R (*pf)(Context, A1);
    FUNCTION_INFO_STRUCT_BODY(FOR_EACH_ARGS_1)
};

template <class R, class Context, class A1, class A2>
struct FunctionInfo<R (*)(Context, A1, A2)> : public VMFunction {
    typedef R (*pf)(Context, A1, A2);
    FUNCTION_INFO_STRUCT_BODY(FOR_EACH_ARGS_2)
};

template <class R, class Context, class A1, class A2, class A3>
struct FunctionInfo<R (*)(Context, A1, A2, A3)> : public VMFunction {
    typedef R (*pf)(Context, A1, A2, A3);
    FUNCTION_INFO_STRUCT_BODY(FOR_EACH_ARGS_3)
};

template <class R, class Context, class A1, class A2, class A3, class A4>
struct FunctionInfo<R (*)(Context, A1, A2, A3, A4)> : public VMFunction {
    typedef R (*pf)(Context, A1, A2, A3, A4);
    FUNCTION_INFO_STRUCT_BODY(FOR_EACH_ARGS_4)
};

template <class R, class Context, class A1, class A2, class A3, class A4, class A5>
    struct FunctionInfo<R (*)(Context, A1, A2, A3, A4, A5)> : public VMFunction {
    typedef R (*pf)(Context, A1, A2, A3, A4, A5);
    FUNCTION_INFO_STRUCT_BODY(FOR_EACH_ARGS_5)
};

template <class R, class Context, class A1, class A2, class A3, class A4, class A5, class A6>
    struct FunctionInfo<R (*)(Context, A1, A2, A3, A4, A5, A6)> : public VMFunction {
    typedef R (*pf)(Context, A1, A2, A3, A4, A5, A6);
    FUNCTION_INFO_STRUCT_BODY(FOR_EACH_ARGS_6)
};

#undef FUNCTION_INFO_STRUCT_BODY

#undef FOR_EACH_ARGS_6
#undef FOR_EACH_ARGS_5
#undef FOR_EACH_ARGS_4
#undef FOR_EACH_ARGS_3
#undef FOR_EACH_ARGS_2
#undef FOR_EACH_ARGS_1

#undef COMPUTE_INDEX
#undef COMPUTE_OUTPARAM_RESULT
#undef COMPUTE_OUTPARAM_ROOT
#undef COMPUTE_ARG_PROP
#undef COMPUTE_ARG_FLOAT
#undef SEP_OR
#undef NOTHING

class AutoDetectInvalidation
{
    JSContext *cx_;
    IonScript *ionScript_;
    Value *rval_;
    bool disabled_;

    void setReturnOverride();

  public:
    AutoDetectInvalidation(JSContext *cx, Value *rval, IonScript *ionScript = nullptr);

    void disable() {
        JS_ASSERT(!disabled_);
        disabled_ = true;
    }

    ~AutoDetectInvalidation() {
        if (!disabled_ && ionScript_->invalidated())
            setReturnOverride();
    }
};

bool InvokeFunction(JSContext *cx, HandleObject obj0, uint32_t argc, Value *argv, Value *rval);
JSObject *NewGCObject(JSContext *cx, gc::AllocKind allocKind, gc::InitialHeap initialHeap);

bool CheckOverRecursed(JSContext *cx);
bool CheckOverRecursedWithExtra(JSContext *cx, BaselineFrame *frame,
                                uint32_t extra, uint32_t earlyCheck);

bool DefVarOrConst(JSContext *cx, HandlePropertyName dn, unsigned attrs, HandleObject scopeChain);
bool SetConst(JSContext *cx, HandlePropertyName name, HandleObject scopeChain, HandleValue rval);
bool MutatePrototype(JSContext *cx, HandleObject obj, HandleValue value);
bool InitProp(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue value);

template<bool Equal>
bool LooselyEqual(JSContext *cx, MutableHandleValue lhs, MutableHandleValue rhs, bool *res);

template<bool Equal>
bool StrictlyEqual(JSContext *cx, MutableHandleValue lhs, MutableHandleValue rhs, bool *res);

bool LessThan(JSContext *cx, MutableHandleValue lhs, MutableHandleValue rhs, bool *res);
bool LessThanOrEqual(JSContext *cx, MutableHandleValue lhs, MutableHandleValue rhs, bool *res);
bool GreaterThan(JSContext *cx, MutableHandleValue lhs, MutableHandleValue rhs, bool *res);
bool GreaterThanOrEqual(JSContext *cx, MutableHandleValue lhs, MutableHandleValue rhs, bool *res);

template<bool Equal>
bool StringsEqual(JSContext *cx, HandleString left, HandleString right, bool *res);

bool IteratorMore(JSContext *cx, HandleObject obj, bool *res);

// Allocation functions for JSOP_NEWARRAY and JSOP_NEWOBJECT and parallel array inlining
JSObject *NewInitParallelArray(JSContext *cx, HandleObject templateObj);
JSObject *NewInitArray(JSContext *cx, uint32_t count, types::TypeObject *type);
JSObject *NewInitObject(JSContext *cx, HandleObject templateObject);
JSObject *NewInitObjectWithClassPrototype(JSContext *cx, HandleObject templateObject);

bool ArrayPopDense(JSContext *cx, HandleObject obj, MutableHandleValue rval);
bool ArrayPushDense(JSContext *cx, HandleObject obj, HandleValue v, uint32_t *length);
bool ArrayShiftDense(JSContext *cx, HandleObject obj, MutableHandleValue rval);
JSObject *ArrayConcatDense(JSContext *cx, HandleObject obj1, HandleObject obj2, HandleObject res);
JSString *ArrayJoin(JSContext *cx, HandleObject array, HandleString sep);

bool CharCodeAt(JSContext *cx, HandleString str, int32_t index, uint32_t *code);
JSFlatString *StringFromCharCode(JSContext *cx, int32_t code);

bool SetProperty(JSContext *cx, HandleObject obj, HandlePropertyName name, HandleValue value,
                 bool strict, jsbytecode *pc);

bool InterruptCheck(JSContext *cx);

void *MallocWrapper(JSRuntime *rt, size_t nbytes);
JSObject *NewCallObject(JSContext *cx, HandleShape shape, HandleTypeObject type);
JSObject *NewSingletonCallObject(JSContext *cx, HandleShape shape);
JSObject *NewStringObject(JSContext *cx, HandleString str);

bool SPSEnter(JSContext *cx, HandleScript script);
bool SPSExit(JSContext *cx, HandleScript script);

bool OperatorIn(JSContext *cx, HandleValue key, HandleObject obj, bool *out);
bool OperatorInI(JSContext *cx, uint32_t index, HandleObject obj, bool *out);

bool GetIntrinsicValue(JSContext *cx, HandlePropertyName name, MutableHandleValue rval);

bool CreateThis(JSContext *cx, HandleObject callee, MutableHandleValue rval);

void GetDynamicName(JSContext *cx, JSObject *scopeChain, JSString *str, Value *vp);

bool FilterArgumentsOrEval(JSContext *cx, JSString *str);

#ifdef JSGC_GENERATIONAL
void PostWriteBarrier(JSRuntime *rt, JSObject *obj);
void PostGlobalWriteBarrier(JSRuntime *rt, JSObject *obj);
#endif

uint32_t GetIndexFromString(JSString *str);

bool DebugPrologue(JSContext *cx, BaselineFrame *frame, jsbytecode *pc, bool *mustReturn);
bool DebugEpilogue(JSContext *cx, BaselineFrame *frame, jsbytecode *pc, bool ok);
bool DebugEpilogueOnBaselineReturn(JSContext *cx, BaselineFrame *frame, jsbytecode *pc);

bool StrictEvalPrologue(JSContext *cx, BaselineFrame *frame);
bool HeavyweightFunPrologue(JSContext *cx, BaselineFrame *frame);

bool NewArgumentsObject(JSContext *cx, BaselineFrame *frame, MutableHandleValue res);

JSObject *InitRestParameter(JSContext *cx, uint32_t length, Value *rest, HandleObject templateObj,
                            HandleObject res);

bool HandleDebugTrap(JSContext *cx, BaselineFrame *frame, uint8_t *retAddr, bool *mustReturn);
bool OnDebuggerStatement(JSContext *cx, BaselineFrame *frame, jsbytecode *pc, bool *mustReturn);

bool EnterWith(JSContext *cx, BaselineFrame *frame, HandleValue val,
               Handle<StaticWithObject *> templ);
bool LeaveWith(JSContext *cx, BaselineFrame *frame);

bool PushBlockScope(JSContext *cx, BaselineFrame *frame, Handle<StaticBlockObject *> block);
bool PopBlockScope(JSContext *cx, BaselineFrame *frame);
bool DebugLeaveBlock(JSContext *cx, BaselineFrame *frame, jsbytecode *pc);

bool InitBaselineFrameForOsr(BaselineFrame *frame, InterpreterFrame *interpFrame,
                             uint32_t numStackValues);

JSObject *CreateDerivedTypedObj(JSContext *cx, HandleObject descr,
                                HandleObject owner, int32_t offset);

bool ArraySpliceDense(JSContext *cx, HandleObject obj, uint32_t start, uint32_t deleteCount);

bool Recompile(JSContext *cx);
JSString *RegExpReplace(JSContext *cx, HandleString string, HandleObject regexp,
                        HandleString repl);
JSString *StringReplace(JSContext *cx, HandleString string, HandleString pattern,
                        HandleString repl);

bool SetDenseElement(JSContext *cx, HandleObject obj, int32_t index, HandleValue value,
                     bool strict);

#ifdef DEBUG
void AssertValidObjectPtr(JSContext *cx, JSObject *obj);
void AssertValidStringPtr(JSContext *cx, JSString *str);
void AssertValidSymbolPtr(JSContext *cx, JS::Symbol *sym);
void AssertValidValue(JSContext *cx, Value *v);
#endif

JSObject *TypedObjectProto(JSObject *obj);

void MarkValueFromIon(JSRuntime *rt, Value *vp);
void MarkShapeFromIon(JSRuntime *rt, Shape **shapep);
void MarkTypeObjectFromIon(JSRuntime *rt, types::TypeObject **typep);

// Helper for generatePreBarrier.
inline void *
IonMarkFunction(MIRType type)
{
    switch (type) {
      case MIRType_Value:
        return JS_FUNC_TO_DATA_PTR(void *, MarkValueFromIon);
      case MIRType_Shape:
        return JS_FUNC_TO_DATA_PTR(void *, MarkShapeFromIon);
      case MIRType_TypeObject:
        return JS_FUNC_TO_DATA_PTR(void *, MarkTypeObjectFromIon);
      default: MOZ_CRASH();
    }
}

} // namespace jit
} // namespace js

#endif /* jit_VMFunctions_h */


text:
<?php

namespace PhpBench\Config;

interface ConfigProcessor
{
    public function process(ConfigLoader $loader, string $path, array $config): array;
}

redpajama_set_name: RedPajamaGithub


text:
This is my repo for learning C programming.  This repo is currently based off following [Learn C The Hard Way](http://c.learncodethehardway.org/book/).

This repo may not be useful for anyone else, but its backup for me =).

## End Goal

Port [Lightweight Java Profiler](https://github.com/dcapwell/lightweight-java-profiler) to C.

Be able to work with C/C++ code within Java.


text:
ROOT = ../../../../..

DIR = Providers/ManagedSystem/UNIXProviders/DiskSpaceCheck

include $(ROOT)/mak/config.mak

LIBRARY = UNIX_DiskSpaceCheckProvider

EXTRA_INCLUDES += -I/usr/local/include -I./..

SOURCES = \
	../CIMHelper.cpp \
	UNIX_DiskSpaceCheckMain.cpp \
	UNIX_DiskSpaceCheck.cpp \
	UNIX_DiskSpaceCheckProvider.cpp

ifeq ($(OS), aix)
	SOURCES += UNIX_DiskSpaceCheck_AIX.cpp
endif
ifeq ($(OS), darwin)
	SOURCES += UNIX_DiskSpaceCheck_DARWIN.cpp
endif
ifeq ($(OS), freebsd)
	SOURCES += UNIX_DiskSpaceCheck_FREEBSD.cpp
endif
ifeq ($(OS), hpux)
	SOURCES += UNIX_DiskSpaceCheck_HPUX.cpp
endif
ifeq ($(OS), linux)
	SOURCES += UNIX_DiskSpaceCheck_LINUX.cpp
endif
ifeq ($(OS), solaris)
	SOURCES += UNIX_DiskSpaceCheck_SOLARIS.cpp
endif
ifeq ($(OS), tru64)
	SOURCES += UNIX_DiskSpaceCheck_TRU64.cpp
endif
ifeq ($(OS), vms)
	SOURCES += UNIX_DiskSpaceCheck_VMS.cpp
endif
ifeq ($(OS), win32)
	SOURCES += UNIX_DiskSpaceCheck_WIN32.cpp
endif
ifeq ($(OS), zos)
	SOURCES += UNIX_DiskSpaceCheck_ZOS.cpp
endif
ifeq (, $(filter aix,darwin,freebsd,hpux,linux,solaris,tru64,vms,win32,zos $(OS)))

else
	SOURCES += UNIX_DiskSpaceCheck_STUB.cpp
endif

LIBRARIES = \
	pegprovider \
	pegclient \
	pegcommon \
	pegquerycommon \
	pegqueryexpression \
	pegcql \
	pegwql

EXTRA_LIBRARIES = \
	-pthread \
	-lutil \
	-lgeom \
	-lkvm \
	-lcam

include $(ROOT)/mak/dynamic-library.mak


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

 -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd">
    <fixture name="sandbox_customer" module="Magento_Paypal" type="virtual" repository_class="Magento\Paypal\Test\Repository\SandboxCustomer" class="Magento\Paypal\Test\Fixture\SandboxCustomer">
        <field name="email" />
        <field name="password" />
        <field name="confirm_password" />
        <field name="first_name" />
        <field name="last_name" />
        <field name="street" />
        <field name="city" />
        <field name="state" />
        <field name="zip" />
        <field name="phone_number" />
        <field name="card_number" />
        <field name="expiry_date" />
        <field name="csc" />
    </fixture>
</config>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.chenlb.mmseg4j</groupId>
    <artifactId>mmseg4j</artifactId>
    <version>1.8.7-SNAPSHOT</version>
  </parent>
  <groupId>com.chenlb.mmseg4j</groupId>
  <artifactId>mmseg4j-core-with-dic</artifactId>
  <name>mmseg4j-core-with-dic</name>
	<packaging>jar</packaging>

	<build>
		<sourceDirectory>../src</sourceDirectory>
		<testSourceDirectory>../test</testSourceDirectory>
		<resources>
			<resource>
				<directory>../data</directory>
				<includes>
					<include>chars.dic</include>
					<include>units.dic</include>
					<include>words.dic</include>
				</includes>
				<targetPath>data</targetPath>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<directory>../data</directory>
				<includes>
					<include>*.dic</include>
				</includes>
				<targetPath>data</targetPath>
			</testResource>
		</testResources>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
					<encoding>UTF-8</encoding>
					<excludes>
						<exclude>**/analysis/**</exclude>
						<exclude>**/solr/**</exclude>
					</excludes>
				</configuration>
				<executions>
					<execution>
						<id>default-testCompile</id>
						<phase>test-compile</phase>
						<configuration>
							<testExcludes>
								<exclude>**/analysis/**</exclude>
								<exclude>**/lucene/**</exclude>
							</testExcludes>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
package org.opensims.db.om;

import org.apache.torque.om.Persistent;

/**
 * The skeleton for this class was autogenerated by Torque on:
 *
 * [Fri Nov 11 14:00:11 CST 2005]
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 */

public  class HostOrgLink
    extends org.opensims.db.om.BaseHostOrgLink
    implements Persistent
{
}


text:
package com.sun.xml.ws.client;

import com.sun.istack.Nullable;
import com.sun.xml.ws.api.Cancelable;
import com.sun.xml.ws.util.CompletedFuture;

import jakarta.xml.ws.AsyncHandler;
import jakarta.xml.ws.Response;
import jakarta.xml.ws.WebServiceException;
import java.util.Map;
import java.util.concurrent.FutureTask;

/**
 * {@link Response} implementation. When Runnbale is executed, it just hands the
 * request to Fiber and returns. When the Fiber finishes the execution, it sets
 * response in the {@link FutureTask}
 *
 * @author Jitendra Kotamraju
 */
public final class AsyncResponseImpl<T> extends FutureTask<T> implements Response<T>, ResponseContextReceiver {

    /**
     * Optional {@link AsyncHandler} that gets invoked
     * at the completion of the task.
     */
    private final AsyncHandler<T> handler;
    private ResponseContext responseContext;
    private final Runnable callable;
    private Cancelable cancelable;

    /**
     *
     * @param runnable
     *      This {@link Runnable} is executed asynchronously.
     * @param handler
     *      Optional {@link AsyncHandler} to invoke at the end
     *      of the processing. Can be null.
     */
    public AsyncResponseImpl(Runnable runnable, @Nullable AsyncHandler<T> handler) {
        super(runnable, null);
        this.callable = runnable;
        this.handler = handler;
    }

    @Override
    public void run() {
        // override so that AsyncInvoker calls set()
        // when Fiber calls the callback
        try {
            callable.run();
        } catch (WebServiceException e) {
            //it could be a WebServiceException or a ProtocolException or any RuntimeException
            // resulting due to some internal bug.
            set(null, e);
        } catch (Throwable e) {
            //its some other exception resulting from user error, wrap it in
            // WebServiceException
            set(null, new WebServiceException(e));
        }
    }

    @Override
    public ResponseContext getContext() {
        return responseContext;
    }

    @Override
    public void setResponseContext(ResponseContext rc) {
        responseContext = rc;
    }

    public void set(final T v, final Throwable t) {
        // call the handler before we mark the future as 'done'
        if (handler!=null) {
            try {
                /*
                  {@link Response} object passed into the callback.
                  We need a separate {@link java.util.concurrent.Future} because we don't want {@link ResponseImpl}
                  to be marked as 'done' before the callback finishes execution.
                  (That would provide implicit synchronization between the application code
                  in the main thread and the callback code, and is compatible with the JAX-RI 2.0 FCS.
                 */
                class CallbackFuture<T> extends CompletedFuture<T> implements Response<T> {
                    public CallbackFuture(T v, Throwable t) {
                        super(v, t);
                    }

                    @Override
                    public Map<String, Object> getContext() {
                        return AsyncResponseImpl.this.getContext();
                    }
                }
                handler.handleResponse(new CallbackFuture<>(v, t));
            } catch (Throwable e) {
                super.setException(e);
                return;
            }
        }
        if (t != null) {
            super.setException(t);
        } else {
            super.set(v);
        }
    }

    public void setCancelable(Cancelable cancelable) {
    	this.cancelable = cancelable;
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
    	if (cancelable != null)
    		cancelable.cancel(mayInterruptIfRunning);
    	return super.cancel(mayInterruptIfRunning);
    }
}


text:
package evs4j.impl.timeout;

import evs4j.impl.SRPConnection;
import evs4j.impl.SRPState;

public class TokenDroppedTimeout extends Timeout {

    public TokenDroppedTimeout(long timeout) {
	super(timeout);
    }

    public void execute(SRPConnection conn, SRPState state, long now) {
	if (hasExpired(now)) {
	    if (DEBUG) conn.log("Token retransmission timeout expired");
	    state.tokenDroppedTimeoutExpired();
	}
    }

}


text:
using namespace llvm;

namespace {

TEST(ScopeExitTest, Basic) {
  struct Callable {
    bool &Called;
    Callable(bool &Called) : Called(Called) {}
    Callable(Callable &&RHS) : Called(RHS.Called) {}
    void operator()() { Called = true; }
  };
  bool Called = false;
  {
    auto g = make_scope_exit(Callable(Called));
    EXPECT_FALSE(Called);
  }
  EXPECT_TRUE(Called);
}

TEST(ScopeExitTest, Release) {
  int Count = 0;
  auto Increment = [&] { ++Count; };
  {
    auto G = make_scope_exit(Increment);
    auto H = std::move(G);
    auto I = std::move(G);
    EXPECT_EQ(0, Count);
  }
  EXPECT_EQ(1, Count);
  {
    auto G = make_scope_exit(Increment);
    G.release();
  }
  EXPECT_EQ(1, Count);
}

} // end anonymous namespace


text:
'use strict';

var bind = require('bind-ponyfill');
var StateEmitter = require('state-emitter');
var Publisher = require('frame-message').Publisher;
var Subscriber = require('frame-message').Subscriber;

function Server(opts) {
  opts = opts || {};

  this._stateEmitter = new StateEmitter();
  this._publisher = new Publisher(opts);
  this._subscriber = new Subscriber(opts);
  this._methods = {};

  this._subscriber.subscribe(bind(function(type, params) {
    if (type !== 'call') {
      return;
    }
    this._call(params);
  }, this));

  this.addMethod('connect', bind(function(cb) {
    cb(null, this._methods);
  }, this));

  this._publisher.publish('ready');
}

Server.prototype._call = function(params) {
  if (!params) {
    throw new Error('params is required');
  }

  this._stateEmitter.once(params.methodName + 'Ready', bind(function(method) {
    var cb = this._createCallback(params.cid);
    var args = params.args.concat([cb]);
    method.apply({}, args);
  }, this));
};

Server.prototype._createCallback = function(cid) {
  if (cid) {
    return bind(function() {
      var msg = {
        cid: cid,
        args: Array.prototype.slice.call(arguments)
      };
      this._publisher.publish('response', msg);
    }, this);
  }
  return function() {};
};

Server.prototype.addMethod = function(methodName, method) {
  if (!methodName) {
    throw new Error('methodName is required');
  }
  if (typeof methodName !== 'string') {
    throw new Error('methodName has to be a string');
  }
  if (method === null || typeof method !== 'function') {
    throw new Error('method has to be a callback function');
  }

  this._methods[methodName] = method;

  this._publisher.publish('newMethod', methodName);
  this._stateEmitter.state(methodName + 'Ready', method);
};

Server.prototype.addMethods = function(scope) {
  if (typeof scope !== 'object') {
    throw new Error('scope should be an object');
  }

  for (var methodName in scope) {
    this.addMethod(methodName, scope[methodName]);
  }
};

module.exports = Server;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015 Red Hat, Inc. and/or its affiliates.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~       http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.uberfire</groupId>
    <artifactId>uberfire-workbench</artifactId>
    <version>1.0.0-SNAPSHOT</version>
  </parent>

  <artifactId>uberfire-workbench-processors</artifactId>
  <packaging>jar</packaging>

  <name>UberFire Workbench Processors</name>
  <description>UberFire Workbench Processors</description>

  <dependencies>

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

    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <proc>none</proc>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
package com.google.cloud.dns;

import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.cloud.BaseServiceException;
import com.google.cloud.RetryHelper.RetryHelperException;
import com.google.cloud.http.BaseHttpServiceException;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.Set;

/**
 * DNS service exception.
 */
public final class DnsException extends BaseHttpServiceException {

  // see: https://cloud.google.com/dns/troubleshooting
  private static final Set<Error> RETRYABLE_ERRORS = ImmutableSet.of(
      new Error(429, null, true),
      new Error(500, null, false),
      new Error(502, null, false),
      new Error(503, null, false),
      new Error(null, "userRateLimitExceeded", true),
      new Error(null, "rateLimitExceeded", true));
  private static final long serialVersionUID = 490302380416260252L;

  public DnsException(IOException exception, boolean idempotent) {
    super(exception, idempotent, RETRYABLE_ERRORS);
  }

  public DnsException(GoogleJsonError error, boolean idempotent) {
    super(error, idempotent, RETRYABLE_ERRORS);
  }

  public DnsException(int code, String message, Throwable cause) {
    super(code, message, null, true, RETRYABLE_ERRORS, cause);
  }

  /**
   * Translate RetryHelperException to the DnsException that caused the error. This method will
   * always throw an exception.
   *
   * @throws DnsException when {@code ex} was caused by a {@code DnsException}
   */
  static DnsException translateAndThrow(RetryHelperException ex) {
    BaseServiceException.translate(ex);
    throw new DnsException(UNKNOWN_CODE, ex.getMessage(), ex.getCause());
  }
}


text:
```sh
$ cordova plugin add co.asku.cordova.intercom --variable API_KEY="ios_sdk-0000..." --variable APP_ID="zz..."
```

## JS API

All functions are on the `cordova.plugins.intercom` object.

### `startSession`

Starts the user's session using their unique identifier (either or email or id).

```js
cordova.plugins.intercom.startSession({ id: 1 });
// OR
cordova.plugins.intercom.startSession({ email: 'user@asku.co' });
```

### `openMessages`

Opens the Intercom messages list UI.

```js
cordova.plugins.intercom.openMessages();
```

### `updateAttributes`

Updates the user properties for this user in Intercom.

```js
cordova.plugins.intercom.updateAttributes({
  name: 'Josh',
  favorite_pizza: 'pepperoni'
});
```

### `logEvent`

Sends a user interaction event to Intercom.

```js
cordova.plugins.intercom.logEvent('ate-pizza', {
  flavor: 'cheese'
});
```

### `checkForUnreadMessages`

Tell Intercom to look for unread messages and present them to the user, overlayed on the web
content. It's recommended to call this between each page view.

```js
cordova.plugins.intercom.checkForUnreadMessages();
```


text:
<?php

namespace Controllers\Users;

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Models\Users\PasswordReset;
use Models\Users\User;
use Models\Utilities\GUID;
use Controllers\BaseController;

use \DateTime;
use \DateTimeZone;

class PasswordResetsController extends BaseController {

	// create
	//
	public function postCreate() {
		$user = User::getByUsername(Input::get('username'));
		$user = $user ? $user : User::getByEmail(Input::get('email'));

		if( ! $user ){
			return Response::json(array( 'success' => true));
		}

		$passwordResetNonce = $nonce = GUID::create();
		$passwordReset = new PasswordReset(array(
			'password_reset_key' => Hash::make($passwordResetNonce),
			'user_uid' => $user->user_uid
		));
		$passwordReset->save();
		$passwordReset->send($nonce);

		return Response::json(array( 'success' => true));
	}

	// get by key
	//
	public function getIndex($passwordResetNonce, $passwordResetId){
		$passwordReset = PasswordReset::where('password_reset_id', '=', $passwordResetId)->first();

		if( ! $passwordReset ){
			return Response::make('Password reset key not found.', 401);
		}

		if( ! Hash::check($passwordResetNonce, $passwordReset->password_reset_key ) ){
			return Response::make('Password reset key invalid.', 401);
		}

		$time = new DateTime( $passwordReset->create_date, new DateTimeZone('GMT') );
		if( ( gmdate('U') - $time->getTimestamp() ) > 1800 ){
			return Response::make('Password reset key expired.', 401);
		}

		unset( $passwordReset->user_uid );
		unset( $passwordReset->email );
		unset( $passwordReset->create_date );
		unset( $passwordReset->password_reset_key );

		return $passwordReset;
	}

	// update password
	//
	public function updateIndex($passwordResetId) {
		$pr = PasswordReset::where('password_reset_id', '=', $passwordResetId)->first();

		$user = User::getIndex($pr->user_uid);
		$password = Input::get('password');
		$user->modifyPassword($password);

		// destroy password reset if present
		//
		$pr->delete();

		$cfg = array(
			'url' => Config::get('app.cors_url') ?: '',
			'user' => $user
		);

		Mail::send('emails.password-changed', $cfg, function($message) use ($user) {
			$message->to($user->email, $user->getFullName());
			$message->subject('SWAMP Password Changed');
		});

		// return response
		//
		return Response::json(array('success' => true));
	}

	// delete by key
	//
	public function deleteIndex($passwordResetNonce) {
		$passwordReset = PasswordReset::where('password_reset_key', '=', Hash::make( $passwordResetNonce ))->first();
		$passwordReset->delete();
		return $passwordReset;
	}
}


text:
using System;
using AllGreen.Runner.WPF.Core.ViewModels;
using AllGreen.Core;
using Caliburn.Micro;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace AllGreen.Runner.WPF.Core.Tests
{
    [TestClass]
    public class SpecStepViewModelTests
    {
        [TestMethod]
        public void PropertyChangedTests()
        {
            TestHelper.TestPropertyChanged(new SpecStepViewModel())
                .Action(vm => vm.Message = "new message").Changes("Message")
                .Action(vm => vm.Status = SpecStatus.Passed).Changes("Status")
                .Action(vm => vm.Trace = new BindableCollection<SpecTraceStepViewModel>()).Changes("Trace");
        }

        [TestMethod]
        public void CreateTest()
        {
            SpecStep specStep = new SpecStep
            {
                Message = "Message",
                Status = SpecStatus.Failed,
                Trace = "Trace"
            };

            SpecStepViewModel specStepViewModel = SpecStepViewModel.Create(specStep, Mock.Of<IFileLocationParser>(), Mock.Of<IFileLocationMapper>());
            specStepViewModel.ShouldBeEquivalentTo(specStep, o => o.Excluding(si => si.PropertyPath.EndsWith("IsNotifying") || si.PropertyPath == "Trace" || si.PropertyPath == "MappedLocation"));
            specStepViewModel.Trace.ShouldAllBeEquivalentTo(new object[] { SpecTraceStepViewModel.Create("Trace", null, null) });
        }

        [TestMethod]
        public void CreateAndMapFileLocation()
        {
            SpecStep specStep = new SpecStep
            {
                Message = "Message",
                ErrorLocation = "file.js:10:12",
                Status = SpecStatus.Failed
            };

            FileLocation fileLocation = new FileLocation("file.js", @"C:\content\file.js", 10, 12);

            Mock<IFileLocationParser> fileLocationParserMock = new Mock<IFileLocationParser>();
            fileLocationParserMock.Setup(flp => flp.Parse("file.js:10:12")).Returns(fileLocation);

            Mock<IFileLocationMapper> fileLocationMapperMock = new Mock<IFileLocationMapper>();
            fileLocationMapperMock.Setup(flm => flm.Map(fileLocation)).Returns<FileLocation>(fl => fl);

            SpecStepViewModel specStepViewModel = SpecStepViewModel.Create(specStep, fileLocationParserMock.Object, fileLocationMapperMock.Object);
            specStepViewModel.ShouldBeEquivalentTo(specStep, o => o.Excluding(si => si.PropertyPath.EndsWith("IsNotifying") || si.PropertyPath == "Trace" || si.PropertyPath == "ErrorLocation" || si.PropertyPath == "MappedLocation"));
            specStepViewModel.ErrorLocation.ShouldBeEquivalentTo(new { Filename = "file.js", FullPath = @"C:\content\file.js", LineNumber = 10, ColumnNumber = 12 });
            specStepViewModel.MappedLocation.ShouldBeEquivalentTo(new { Filename = "file.js", FullPath = @"C:\content\file.js", LineNumber = 10, ColumnNumber = 12 });
        }

        [TestMethod]
        public void CreateWithMultilineTrace()
        {
            SpecStep specStep = new SpecStep
            {
                Trace = "Trace line 1\nTrace line 2"
            };

            SpecStepViewModel specStepViewModel = SpecStepViewModel.Create(specStep, Mock.Of<IFileLocationParser>(), null);
            specStepViewModel.Trace.ShouldAllBeEquivalentTo(new object[] {
                SpecTraceStepViewModel.Create("Trace line 1", null, null), SpecTraceStepViewModel.Create("Trace line 2", null, null) });
        }
    }
}


text:
namespace html5 {
namespace html {
namespace interface {

}}}

#endif //GUARD_HTML5_HTML_INTERFACE_FORM_HH_INCLUDED


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Lauro Reis</logradouro><bairro>Pacheco</bairro><cidade>Caucaia</cidade><uf>CE</uf><cep>61626650</cep></feed>


text:
/*********************************************************************************************************************/
/*   File Name: pack_file.cpp                                                                                */
/*   Author: Ing. Jesus Rocha <chuyangel.rm@gmail.com>, July 2016.                                                   */
/*   Copyright (C) Angsys, - All Rights Reserved                                                                     */
/*   Confidential Information of Angsys. Not for disclosure or distribution without the author's prior written       */
/*   consent. This file contains code, techniques and know-how which is confidential and proprietary to Jesus Rocha  */
/*                                                                                */
/*********************************************************************************************************************/

#include "pch.h"
#include "ang/core/files.hpp"

using namespace ang;
using namespace ang::core;
using namespace ang::core::files;

namespace ang
{
	namespace core
	{
		namespace files
		{

			class packed_file_impl
				: public bean
				, public ifile
			{
			private:
				path _path;
				ifile_t _original_source;
				file_flags_t _flags;
				ulong64 _size;
				ulong64 _offset;
				ulong64 _cursor;

				ibuffer_t _mapped_buffer;

			public:
				packed_file_impl();

			private:
				virtual~packed_file_impl();

			public: //overrides
				bool create(path_view path, open_flags_t flags, ifile_t original_source, ulong64 offset, ulong64 size);
				bool is_created()const;
				bool close();

			public: //Methos
				virtual streams::stream_mode_t mode()const override;
				virtual path file_path()const override;
				virtual file_size_t stream_size()const override;
				virtual bool stream_size(file_size_t) override;
				virtual void format(text::encoding_t)override;
				virtual text::encoding_t format()const override;
				virtual bool move_to(file_cursor_t, file_reference_t) override;
				virtual file_size_t position()const override;
				virtual wsize read(pointer buffer, wsize size, text::text_format_t)override;
				virtual wsize write(pointer buffer, wsize size, text::text_format_t)override;
				virtual wsize read(pointer buffer, wsize size, text::encoding_t)override;
				virtual wsize write(pointer buffer, wsize size, text::encoding_t)override;
				virtual wsize read(ibuffer_view_t buffer, text::encoding_t = text::encoding::binary)override;
				virtual wsize write(ibuffer_view_t buffer, text::encoding_t = text::encoding::binary)override;
				virtual ibuffer_t map(wsize size, file_cursor_t offset)override;
				virtual bool unmap(ibuffer_t, wsize)override;
				virtual bool set_mutex(core::async::mutex_ptr_t)override;

			};

		}
	}
}

bool load_directory_recursive(files::path const& root_path, files::path const& subpath, file_cursor_t& header_size, file_cursor_t& offset, collections::smart_vector<collections::pair<files::path, pack_file_info>>& files)
{
#if defined WINDOWS_PLATFORM
	WIN32_FIND_DATAW ffd;
	LARGE_INTEGER filesize;

	files::path path = root_path;

	if (!subpath.is_empty() && subpath->length() > 0)
		path += "/"_sv + subpath;

	path += "/*"_sv;

	HANDLE  hFind = FindFirstFileW((path_view)path, &ffd);

	if (INVALID_HANDLE_VALUE == hFind)
	{
		HRESULT hr = GetLastError();
		return false;
	}

	do
	{
		if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			if (ffd.cFileName != L"."_sv && ffd.cFileName != L".."_sv)
			{
				files::path _subpath = subpath;
				if (!subpath.is_empty() && subpath->length() > 0)
					_subpath += "/"_sv;
				_subpath += path_view(ffd.cFileName);
				load_directory_recursive(root_path, _subpath, header_size, offset, files);
			}
		}
		else
		{
			filesize.LowPart = ffd.nFileSizeLow;
			filesize.HighPart = ffd.nFileSizeHigh;

			files::path _subpath = subpath;
			if (!subpath.is_empty() && subpath->length() > 0)
				_subpath += "/"_sv;
			_subpath += path_view(ffd.cFileName);

			files += {_subpath, { (file_size_t)filesize.QuadPart, offset } };
			offset += filesize.QuadPart;
			header_size += sizeof(pack_file_info) + _subpath->length() * sizeof(wchar) + sizeof(uint);
		}
	} while (FindNextFileW(hFind, &ffd) != 0);
	FindClose(hFind);
#else
#endif
	return true;
}

bool pack_file::create_pack_from_folder(path_view in_path, path_view out_path)
{
	collections::smart_vector<collections::pair<files::path, pack_file_info>> paths;
#if defined WINDOWS_PLATFORM
	file_cursor_t offset = 0;
	file_cursor_t header_size = 0;

	load_directory_recursive(in_path, L""_sv, header_size, offset, paths);

	output_binary_file_t out_file = new output_binary_file(out_path);
	if (!out_file->is_valid())
		return false;

	ulong64 count = paths->counter();
	//out_file->write(&count, sizeof(count));
	out_file->write([&](streams::ibinary_output_stream_t stream)->bool
	{
		stream << paths->counter();
		for(collections::pair<files::path, pack_file_info>& info : paths)
		{
			info.value.offset += header_size;
			stream << info.value.offset << info.value.size << info.key;
		}
		files::path path = in_path;
		path += "/*"_sv;
		auto end = path->end();
		for(collections::pair<files::path, pack_file_info>& info : paths)
		{
			path->replace(info.key, end, collections::iterator<wchar>(path.get(), null, path->length()));
			input_binary_file_t file = new input_binary_file(path);
			if (file->is_valid())
			{
				buffer_t buff = new(file->file_size()) buffer();
				file->read(buff->buffer_ptr(), buff->buffer_size());
				stream->write(buff->buffer_ptr(), buff->buffer_size());
			}
			else
			{
				stream->move_to(info.value().size, ang::streams::stream_reference::current);
			}

		}
		return true;
	}, 0, offset + header_size + sizeof(ulong64));

#endif
	return true;
}

pack_file::pack_file()
{

}

pack_file::~pack_file()
{

}

bool pack_file::is_child_of(type_name_t name)
{
	return name == type_name<pack_file>()
		|| file::is_child_of(name)
		|| name == type_name<ifile_system>();
}

bool pack_file::is_kind_of(type_name_t name)const
{
	return name == type_name<pack_file>()
		|| file::is_kind_of(name)
		|| name == type_name<ifile_system>();
}

bool pack_file::query_object(type_name_t name, unknown_ptr_t out)
{
	if (out == null)
		return false;

	if (name == type_name<pack_file>())
	{
		*out = static_cast<pack_file*>(this);
		return true;
	}
	else if (file::query_object(name, out))
	{
		return true;
	}
	else if (name == type_name<ifile_system>())
	{
		*out = static_cast<ifile_system*>(this);
		return true;
	}
	return false;
}

bool pack_file::create(path_view path, open_flags_t flags)
{
	return false;
}

smart_array<path> pack_file::paths()const
{
	return null;
}

bool pack_file::register_paths(path_view path)
{
	return false;
}

bool pack_file::create_file_handle(path_view path, open_flags_t flags, ifile_ptr_t out)
{
	if (flags.is_active(open_flags::access_out))
		return false;

	return true;
}

bool pack_file::open(path_view path, input_text_file_t& out)
{
	out = null;
	return false;
}

bool pack_file::open(path_view, output_text_file_t& out)
{
	out = null;
	return false;
}

bool pack_file::open(path_view path, input_binary_file_t& out)
{
	out = null;
	return false;
}

bool pack_file::open(path_view, output_binary_file_t& out)
{
	out = null;
	return false;
}


text:
@implementation NSAttributedString (Shortcuts)

+ (id)attributedString {
    return [[self alloc] init];
}

@end


text:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;

public class StatItem : MonoBehaviour {
	public Text statName;
	public Text statValue;
	public Text description;
	public Image icon;
	public Text levelBonus;
}


text:
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Threading;
using TradeHub.StrategyRunner.UserInterface.Common.Interface;

namespace TradeHub.StrategyRunner.UserInterface.Common.Utility
{
    /// <summary>
    /// Derived VirtualizatingCollection, performing loading asychronously.
    /// </summary>
    /// <typeparam name="T">The type of items in the collection</typeparam>
    public class AsyncVirtualizingCollection<T> : VirtualizingCollection<T>, INotifyCollectionChanged, INotifyPropertyChanged
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncVirtualizingCollection<T>"/> class.
        /// </summary>
        /// <param name="itemsProvider">The items provider.</param>
        public AsyncVirtualizingCollection(IItemsProvider<T> itemsProvider)
            : base(itemsProvider)
        {
            _synchronizationContext = SynchronizationContext.Current;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncVirtualizingCollection<T>"/> class.
        /// </summary>
        /// <param name="itemsProvider">The items provider.</param>
        /// <param name="pageSize">Size of the page.</param>
        public AsyncVirtualizingCollection(IItemsProvider<T> itemsProvider, int pageSize)
            : base(itemsProvider, pageSize)
        {
            _synchronizationContext = SynchronizationContext.Current;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncVirtualizingCollection<T>"/> class.
        /// </summary>
        /// <param name="itemsProvider">The items provider.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="pageTimeout">The page timeout.</param>
        public AsyncVirtualizingCollection(IItemsProvider<T> itemsProvider, int pageSize, int pageTimeout)
            : base(itemsProvider, pageSize, pageTimeout)
        {
            _synchronizationContext = SynchronizationContext.Current;
        }

        #endregion

        #region SynchronizationContext

        private readonly SynchronizationContext _synchronizationContext;

        /// <summary>
        /// Gets the synchronization context used for UI-related operations. This is obtained as
        /// the current SynchronizationContext when the AsyncVirtualizingCollection is created.
        /// </summary>
        /// <value>The synchronization context.</value>
        protected SynchronizationContext SynchronizationContext
        {
            get { return _synchronizationContext; }
        }

        #endregion

        #region INotifyCollectionChanged

        /// <summary>
        /// Occurs when the collection changes.
        /// </summary>
        public event NotifyCollectionChangedEventHandler CollectionChanged;

        /// <summary>
        /// Raises the <see cref="E:CollectionChanged"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param>
        protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            NotifyCollectionChangedEventHandler h = CollectionChanged;
            if (h != null)
                h(this, e);
        }

        /// <summary>
        /// Fires the collection reset event.
        /// </summary>
        private void FireCollectionReset()
        {
            NotifyCollectionChangedEventArgs e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
            OnCollectionChanged(e);
        }

        #endregion

        #region INotifyPropertyChanged

        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Raises the <see cref="E:PropertyChanged"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChangedEventHandler h = PropertyChanged;
            if (h != null)
                h(this, e);
        }

        /// <summary>
        /// Fires the property changed event.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        private void FirePropertyChanged(string propertyName)
        {
            PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
            OnPropertyChanged(e);
        }

        #endregion

        #region IsLoading

        private bool _isLoading;

        /// <summary>
        /// Gets or sets a value indicating whether the collection is loading.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this collection is loading; otherwise, <c>false</c>.
        /// </value>
        public bool IsLoading
        {
            get
            {
                return _isLoading;
            }
            set
            {
                if ( value != _isLoading )
                {
                    _isLoading = value;
                }
                FirePropertyChanged("IsLoading");
            }
        }

        #endregion

        #region Load overrides

        /// <summary>
        /// Asynchronously loads the count of items.
        /// </summary>
        protected override void LoadCount()
        {
            Count = 0;
            IsLoading = true;
            ThreadPool.QueueUserWorkItem(LoadCountWork);
        }

        /// <summary>
        /// Performed on background thread.
        /// </summary>
        /// <param name="args">None required.</param>
        private void LoadCountWork(object args)
        {
            int count = FetchCount();
            SynchronizationContext.Send(LoadCountCompleted, count);
        }

        /// <summary>
        /// Performed on UI-thread after LoadCountWork.
        /// </summary>
        /// <param name="args">Number of items returned.</param>
        private void LoadCountCompleted(object args)
        {
            Count = (int)args;
            IsLoading = false;
            FireCollectionReset();
        }

        /// <summary>
        /// Asynchronously loads the page.
        /// </summary>
        /// <param name="index">The index.</param>
        protected override void LoadPage(int index)
        {
            IsLoading = true;
            ThreadPool.QueueUserWorkItem(LoadPageWork, index);
        }

        /// <summary>
        /// Performed on background thread.
        /// </summary>
        /// <param name="args">Index of the page to load.</param>
        private void LoadPageWork(object args)
        {
            int pageIndex = (int)args;
            IList<T> page = FetchPage(pageIndex);
            SynchronizationContext.Send(LoadPageCompleted, new object[]{ pageIndex, page });
        }

        /// <summary>
        /// Performed on UI-thread after LoadPageWork.
        /// </summary>
        /// <param name="args">object[] { int pageIndex, IList(T) page }</param>
        private void LoadPageCompleted(object args)
        {
            int pageIndex = (int)((object[]) args)[0];
            IList<T> page = (IList<T>)((object[])args)[1];

            PopulatePage(pageIndex, page);
            IsLoading = false;
            FireCollectionReset();
        }

        #endregion

        /// <summary>
        /// Not supported.
        /// </summary>
        /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
        /// <exception cref="T:System.NotSupportedException">
        /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
        /// </exception>
        public new void Add(T item)
        {
            base.ItemsProvider.AddItem(item);
            LoadCountWork(0);
            LoadPage(0);
            //IList<T> page = FetchPage(0);
            //SynchronizationContext.Send(LoadPageCompleted, new object[] { 0, page });
            //throw new NotSupportedException();
        }
    }
}


text:
@implementation ARGeoCoordinate

@synthesize geoLocation;

@synthesize radialDistance, inclination, azimuth;

@synthesize dataObject;

- (float)angleFromCoordinate:(CLLocationCoordinate2D)first toCoordinate:(CLLocationCoordinate2D)second {
	float longitudinalDifference = second.longitude - first.longitude;
	float latitudinalDifference = second.latitude - first.latitude;
	float possibleAzimuth = (M_PI * .5f) - atan(latitudinalDifference / longitudinalDifference);
	if (longitudinalDifference > 0) return possibleAzimuth;
	else if (longitudinalDifference < 0) return possibleAzimuth + M_PI;
	else if (latitudinalDifference < 0) return M_PI;

	return 0.0f;
}

- (void)calibrateUsingOrigin:(CLLocation *)origin useAltitude:(BOOL) useAltitude {

	if (!self.geoLocation) return;

	double baseDistance = [origin distanceFromLocation:self.geoLocation];

	self.radialDistance = sqrt(pow(origin.altitude - self.geoLocation.altitude, 2) + pow(baseDistance, 2));

	float angle = sin(ABS(origin.altitude - self.geoLocation.altitude) / self.radialDistance);

    if (!useAltitude) {
        angle = 0;
    }

	if (origin.altitude > self.geoLocation.altitude) angle = -angle;

	self.inclination = angle;
	self.azimuth = [self angleFromCoordinate:origin.coordinate toCoordinate:self.geoLocation.coordinate];
}

+ (ARGeoCoordinate *)coordinateWithLocation:(CLLocation *)location {
	ARGeoCoordinate *newCoordinate = [[ARGeoCoordinate alloc] init];
	newCoordinate.geoLocation = location;

	return newCoordinate;
}

- (NSUInteger)hash{
	return ([dataObject hash] + (int)(self.radialDistance + self.inclination + self.azimuth));
}

- (BOOL)isEqual:(id)other {
    if (other == self)
        return YES;
    if (!other || ![other isKindOfClass:[self class]])
        return NO;
    return [self isEqualToCoordinate:other];
}

- (BOOL)isEqualToCoordinate:(ARGeoCoordinate *)otherCoordinate {
    if (self == otherCoordinate) return YES;

	BOOL equal = self.radialDistance == otherCoordinate.radialDistance;
	equal &= self.inclination == otherCoordinate.inclination;
	equal &= self.azimuth == otherCoordinate.azimuth;
	equal &= self.dataObject == otherCoordinate.dataObject;

	return equal;
}

- (NSString *)description {
	return [NSString stringWithFormat:@"r: %.3fm φ: %.3f° θ: %.3f°", self.radialDistance, radiansToDegrees(self.azimuth), radiansToDegrees(self.inclination)];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (C) Red Hat, Inc. http://redhat.com Licensed under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with the License. You may obtain
  a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
  law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
  BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
  the specific language governing permissions and limitations under the License. -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <groupId>org.jboss.amq</groupId>
    <artifactId>mq-project</artifactId>
    <version>6.2.0.redhat-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.jboss.amq</groupId>
  <artifactId>jboss-a-mq-cpp</artifactId>
  <packaging>pom</packaging>

  <name>JBoss A-MQ CMS Client :: Distribution</name>

  <prerequisites>
    <maven>3.0.2</maven>
  </prerequisites>

  <build>
    <defaultGoal>install</defaultGoal>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <id>unix-bin</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <descriptors>
                <descriptor>src/main/descriptors/assembly.xml</descriptor>
              </descriptors>
              <finalName>${project.artifactId}-${project.version}</finalName>
              <appendAssemblyId>false</appendAssemblyId>
              <filters>
                <filter>${project.basedir}/src/main/descriptors/unix.properties</filter>
              </filters>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>com.googlecode.maven-download-plugin</groupId>
        <artifactId>maven-download-plugin</artifactId>
        <version>1.1.0</version>
        <executions>
          <execution>
            <id>download-activemq-cpp-tar</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>wget</goal>
            </goals>
            <configuration>
              <url>http://archive.apache.org/dist/activemq/activemq-cpp/${activemqcpp.version}/activemq-cpp-library-${activemqcpp.version}-src.tar.gz</url>
              <unpack>false</unpack>
              <outputDirectory>target/dependencies/</outputDirectory>
            </configuration>
          </execution>
          <execution>
            <id>download-activemq-cpp-zip</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>wget</goal>
            </goals>
            <configuration>
              <url>http://archive.apache.org/dist/activemq/activemq-cpp/${activemqcpp.version}/activemq-cpp-library-${activemqcpp.version}-src.zip</url>
              <unpack>false</unpack>
              <outputDirectory>target/dependencies/</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
    <pluginManagement>
      <plugins>
        <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence
          on the Maven build itself. -->
        <plugin>
          <groupId>org.eclipse.m2e</groupId>
          <artifactId>lifecycle-mapping</artifactId>
          <version>1.0.0</version>
          <configuration>
            <lifecycleMappingMetadata>
              <pluginExecutions>
                <pluginExecution>
                  <pluginExecutionFilter>
                    <groupId>
                      org.apache.karaf.tooling
                    </groupId>
                    <artifactId>
                      features-maven-plugin
                    </artifactId>
                    <versionRange>
                      [2.2.2-fuse-02-06,)
                    </versionRange>
                    <goals>
                      <goal>
                        add-features-to-repo
                      </goal>
                    </goals>
                  </pluginExecutionFilter>
                  <action>
                    <ignore />
                  </action>
                </pluginExecution>
              </pluginExecutions>
            </lifecycleMappingMetadata>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


text:
layout: post
title: How Political is Food?
author: Craig Eley
date: 2014-12-01
tags: [politics, TTBOOK]
---

Last week I wrote a post on Alice Waters and the politics of food that [went live over on TTBOOK](http://www.ttbook.org/book/how-political-food) on Thanksgiving. It's something that's been stewing since I read [this *New Yorker* article](http://www.newyorker.com/magazine/2014/11/03/shut-eat) on "foodie culture," and is essentially a response to it. The post got branded an "essay" somewhere in the chain before it went live, but I think it's a little short and informal for that; it's really more akin to something I would post here than a fully fleshed out "essay," but you get the picture.

I'm hoping to do more pieces like this—both written, and, eventually, audio—and the TTBOOK website gives me a nice platform for doing so. I'm probably not going to post here every time I produce something, but I'll tag my posts so you can follow along via RSS if you're so inclined.

[The article](http://www.ttbook.org/book/how-political-food)

[The RSS feed](http://www.ttbook.org/taxonomy/term/22956/feed)


text:
/**
* \file can.h
* \author Heinz-Jürgen Oertel, port GmbH
* $Revision: 1.1 $
* $Date: 2003/07/18 00:11:46 $
*
* can4linux interface definitions
*
*
*
*/

#ifndef __CAN_H
#define __CAN_H

#ifndef __KERNEL__
#include <sys/time.h>
#endif
 /*---------- the can message structure */

#define CAN_MSG_LENGTH 8		/**< maximum length of a CAN frame */

#define MSG_RTR		(1<<0)		/**< RTR Message */
#define MSG_OVR		(1<<1)		/**< CAN controller Msg overflow error */
#define MSG_EXT		(1<<2)		/**< extended message format */
#define MSG_PASSIVE	(1<<4)		/**< controller in error passive */
#define MSG_BUSOFF      (1<<5)		/**< controller Bus Off  */
#define MSG_       	(1<<6)		/**<  */
#define MSG_BOVR	(1<<7)		/**< receive/transmit buffer overflow */
/**
* mask used for detecting CAN errors in the canmsg_t flags field
*/
#define MSG_ERR_MASK	(MSG_OVR + MSG_PASSIVE + MSG_BUSOFF + MSG_BOVR)

/**
* The CAN message structure.
* Used for all data transfers between the application and the driver
* using read() or write().
*/
typedef struct {
    /** flags, indicating or controlling special message properties */
    int             flags;
    int             cob;	 /**< CAN object number, used in Full CAN  */
    unsigned   long id;		 /**< CAN message ID, 4 bytes  */
    struct timeval  timestamp;	 /**< time stamp for received messages */
    short      int  length;	 /**< number of bytes in the CAN message */
    unsigned   char data[CAN_MSG_LENGTH]; /**< data, 0...8 bytes */
} canmsg_t;

/**
---------- IOCTL requests */

#define COMMAND 	 0	/**< IOCTL command request */
#define CONFIG 		 1	/**< IOCTL configuration request */
#define SEND 		 2	/**< IOCTL request */
#define RECEIVE 	 3	/**< IOCTL request */
#define CONFIGURERTR 	 4	/**< IOCTL request */
#define STATUS           5      /**< IOCTL status request */

/*---------- CAN ioctl parameter types */

/**
 IOCTL Command request parameter structure */
typedef struct Command_par {
    int cmd;			/**< special driver command */
    int error;	 		/**< return value */
    unsigned long retval;	/**< return value */
} Command_par_t ;

/**
 IOCTL Configuration request parameter structure */
typedef struct Config_par {
    int target;			/**< special configuration target */
    unsigned long val1;		/**< 1. parameter for the target */
    unsigned long val2;		/**< 2. parameter for the target */
    int error;	 		/**< return value for errno */
    unsigned long retval;	/**< return value */
} Config_par_t ;

/**
 IOCTL CAN controller status request parameter structure */
typedef struct CanSja1000Status_par {
    unsigned int baud;			/**< actual bit rate */
    unsigned char status;		/**< CAN controller status register */
    unsigned int error_warning_limit;	/**< the error warning limit */
    unsigned int rx_errors;		/**< content of RX error counter */
    unsigned int tx_errors;		/**< content of TX error counter */
    unsigned int error_code;		/**< content of error code register */
    unsigned int rx_buffer_size;	/**< size of rx buffer  */
    unsigned int rx_buffer_used;	/**< number of messages */
    unsigned int tx_buffer_size;	/**< size of tx buffer  */
    unsigned int tx_buffer_used;	/**< number of messages */
    unsigned long retval;		/**< return value */
} CanSja1000Status_par_t;

/**
 IOCTL Send request parameter structure */
typedef struct Send_par {
    canmsg_t *Tx;		/**< CAN message struct  */
    int error;	 		/**< return value for errno */
    unsigned long retval;	/**< return value */
} Send_par_t ;

/**
 IOCTL Receive request parameter structure */
typedef struct Receive_par {
    canmsg_t *Rx;		/**< CAN message struct  */
    int error;	 		/**< return value for errno */
    unsigned long retval;	/**< return value */
} Receive_par_t ;

/**
IOCTL ConfigureRTR request parameter structure */
typedef struct ConfigureRTR_par {
    unsigned message;		/**< CAN message ID */
    canmsg_t *Tx;		/**< CAN message struct  */
    int error;	 		/**< return value for errno */
    unsigned long retval;	/**< return value */
} ConfigureRTR_par_t ;

/**
---------- IOCTL Command subcommands */

# define CMD_START	1
# define CMD_STOP 	2
# define CMD_RESET	3

/**
---------- IOCTL Configure targets */

# define CONF_ACC   	0	/* mask and code */
# define CONF_ACCM   	1	/* mask only */
# define CONF_ACCC   	2	/* code only */
# define CONF_TIMING	3	/* bit timing */
# define CONF_OMODE 	4	/* output control register */
# define CONF_FILTER	5
# define CONF_FENABLE	6
# define CONF_FDISABLE	7

#endif 	/* __CAN_H */


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Usuario;

/**
 * UsuarioSearch represents the model behind the search form about `app\models\Usuario`.
 */
class UsuarioSearch extends Usuario
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['nick', 'password', 'auth_key'], 'safe'],
            [['activo'], 'boolean'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Usuario::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'activo' => $this->activo,
        ]);

        $query->andFilterWhere(['like', 'nick', $this->nick])
            ->andFilterWhere(['like', 'password', $this->password])
            ->andFilterWhere(['like', 'auth_key', $this->auth_key]);

        return $dataProvider;
    }
}