var weather = require('weather-js');
var moment = require('moment');
var request = require('request');
var pubsub = require('@google-cloud/pubsub');
var ApiAiAssistant = require('actions-on-google').ApiAiAssistant;

var pubsubClient = pubsub({ projectId: 'your-google-project-id' });
var topicName = 'MocktailsMixerMessages';

exports.webhook = function(req, res) {

  var respData = {
    'speech': 'This is default speech.',
    'displayText': 'This is default display text.',
    'data': {},
    'contextOut': [],
    'source': ''
  };

  var intent = req.body.result.metadata.intentName;
  console.log('intent = ' + intent);

  switch (intent) {

    case 'prime_pump_start':

      var whichPump = req.body.result.parameters.which_pump;
      console.log('whichPump = ' + whichPump);

      createTopic(function(topic) {

        var pubData = { 'intent': 'prime_pump_start', 'which_pump': whichPump };

        publishMessage(topic, JSON.stringify(pubData), function() {

          var s = 'Priming pump ' + whichPump + '.';
          respData.speech = s;
          respData.displayText = s;
          res.json(respData);
        });
      });

      break;

    case 'prime_pump_end':

      createTopic(function(topic) {

        var pubData = { 'intent': 'prime_pump_end' };

        publishMessage(topic, JSON.stringify(pubData), function() {

          var s = 'Stopped priming pump.';
          respData.speech = s;
          respData.displayText = s;
          res.json(respData);
        });
      });

      break;

    case 'make_drink':

      var drink = req.body.result.parameters.drink;
      console.log('drink = ' + drink);

      createTopic(function(topic) {

        var pubData = { 'intent': 'make_drink', 'drink': drink };

        publishMessage(topic, JSON.stringify(pubData), function() {

          var s = 'Coming right up. While I make your drink, would you like to hear the weather or your fortune?';
          respData.speech = s;
          respData.displayText = s;
          res.json(respData);
        });
      });

      break;

    case 'chuck_norris':

      requestChuckNorris(function(jokeText) {

        // set assistant speech and display text
        respData.speech = jokeText;
        respData.displayText = jokeText;

        // serve response
        res.json(respData);
      });
      break;

    case 'resp_weather':

      console.log('about to call getWeather()');

      var zip = req.body.result.parameters.zip_code;
      console.log('zip =' + zip);

      getWeather(zip, function(respText) {

        console.log('inside getWeather() callback');
        respData.speech = respText;
        respData.displayText = respText;
        res.json(respData);
      });

      break;

    default:

      console.log('switch-case in default');
      res.json(respData);

      break;
  }
};

function createTopic(callback) {

  if (!callback) {
    console.log('no callback');
    return;
  }

  pubsubClient.createTopic(topicName, function(error, topic) {

    // topic already exists
    if (error && error.code === 409) {

      console.log('topic created');

      // callback(topic);
      callback(pubsubClient.topic(topicName));
      return;
    }

    if (error) {
      console.log(error);
      return;
    }

    callback(pubsubClient.topic(topicName));
  });
}

function publishMessage(topic, message, callback) {

  topic.publish(message, function(error) {

    if (error) {
      console.log('Publish error:');
      console.log(error);
      return;
    }

    console.log('publish successful');

    if (callback) {
      callback();
    }
  });
}

function requestChuckNorris(callback) {

  if (!callback) {
    console.log('Chuck norris doesnt need a callback function, but you do.');
    return;
  }

  request('http://api.icndb.com/jokes/random?limitTo=[nerdy]&exclude=[explicit]', function(error, response, body) {

    var json = JSON.parse(body);

    if (json.type !== 'success') {
      callback('Error, Chuck Norris round-housed the server rack.');
    } else {
      callback(json.value.joke);
    }
  });
}

function getWeather(zip, callback) {

  if (!callback) {
    console.log('No callback.');
    return;
  }

  weather.find({search: zip, degreeType: 'F'}, function(err, result) {

    if (err) {
      console.log(err);
      callback('There has been an error with the weather service.');
      return;
    }

    callback('The temperature in ' + result[0].location.name + ' is ' + result[0].current.temperature + ' degrees.');
  });
}


/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* 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/. */

#include "avmplus.h"
//#define DOPROF
//#include "../vprof/vprof.h"

namespace avmplus
{
    ScriptObject::ScriptObject(VTable* _vtable, ScriptObject* _delegate) :
#ifdef DEBUGGER
        AvmPlusScriptableObject(sotObject(_vtable)),
#endif // DEBUGGER
        vtable(_vtable),
        // note that it's substantially more efficient to initialize this in the ctor
        // list vs. a later explicit call to setDelegate, as we don't have to check for marking
        // nor decrement an existing value...
        delegate(_delegate)
    {
        AvmAssert(vtable->traits->isResolved());

        // Ensure that our object is large enough to hold its extra traits data.
        AvmAssert(MMgc::GC::Size(this) >= vtable->traits->getTotalSize());
    }

    ScriptObject::ScriptObject(VTable* _vtable, ScriptObject* _delegate, int capacity) :
#ifdef DEBUGGER
        AvmPlusScriptableObject(sotObject(_vtable)),
#endif // DEBUGGER
        vtable(_vtable),
        // note that it's substantially more efficient to initialize this in the ctor
        // list vs. a later explicit call to setDelegate, as we don't have to check for marking
        // nor decrement an existing value...
        delegate(_delegate)
    {
        AvmAssert(vtable->traits->isResolved());

        // Ensure that our object is large enough to hold its extra traits data.
        AvmAssert(MMgc::GC::Size(this) >= vtable->traits->getTotalSize());

        //if capacity not specified then initialize the hashtable lazily
        if (vtable->traits->needsHashtable() && capacity)
        {
            initHashtable(capacity);
        }
    }

    // Not actually entirely trivial, as it decrements reference counts
    // manually, not just by GCMember smart pointer destructors.
#ifdef DRC_TRIVIAL_DESTRUCTOR
    ScriptObject::~ScriptObject()
    {
        //setDelegate(NULL); -- no longer necessary
        vtable->traits->destroyInstance(this);
    }
#endif

    /* The storage for a ScriptObject or a subclass SO of ScriptObject is
     * laid out as follows.
     *
     *   - first the bits of the C++ class; if there are pointers here
     *     then they must be traced explicitly by the appropriate class's
     *     gcTrace method
     *   - then the bits for the ActionScript slots
     *   - optionally an InlineHashtable for dynamic properties
     *
     * The in-line slots are native and their representation is described
     * by the Traits object (vtable->traits).  They are not named, but named
     * lookup is possible by going to the Traits object, which contains
     * a name->slot map.
     *
     * The InlineHashtable always stores Atoms.
     */
    bool ScriptObject::gcTrace(MMgc::GC* gc, size_t cursor)
    {
        (void)cursor;
        gc->TraceLocation(&vtable);
        gc->TraceLocation(&delegate);
        traits()->traceSlots(gc, this);
        if (traits()->needsHashtable())
        {
            // Avoid initializing the hash table here
            InlineHashtable* iht = getTableNoInit();
            // The iht pointer can be NULL for Dictionary objects that
            // haven't had init called yet.
            if(iht)
                iht->gcTrace(gc);
        }

        return false;
    }

    void ScriptObject::initHashtable(int capacity /*=InlineHashtable::kDefaultCapacity*/)
    {
        AvmAssert(vtable->traits->isDictionary() == 0); //should not be called DictionaryObject uses HeapHashtable

        MMGC_MEM_TYPE(this);
        union {
            uint8_t* p;
            InlineHashtable* iht;
        };
        p = (uint8_t*)this + vtable->traits->getHashtableOffset();
        iht->initializeWithDontEnumSupport(this->gc(), capacity);

#ifdef DEBUGGER
        if (getSampler())
        {
            getSampler()->addDependentObject(this, iht);
        }
#endif
    }

    InlineHashtable* ScriptObject::getTable() const
    {
        AvmAssert(vtable->traits->getHashtableOffset() != 0);
        union {
            uint8_t* p;
            InlineHashtable* iht;
            HeapHashtable** hht;
        };
        p = (uint8_t*)this + vtable->traits->getHashtableOffset();
        if(!vtable->traits->isDictionary())
        {
            if (iht->needsInitialize())
                const_cast<ScriptObject*>(this)->initHashtable();
            return iht;
        }
        else
        {
            //DictionaryObjects store pointer to HeapHashtable at
            //the hashtable offset
            if (*hht == NULL)
            {
                // ugh... if we are here, it means that a Dictionary subclass didn't
                // call the Dictionary ctor via super(), so our HeapHashtable was never created.
                // This is a horrible band-aid: lazily create it here. (Since the
                // ctor was never called, we'll just assume weakKeys = false.) This is
                // a horrible encapsulation violation, but a proper fix requires a fairly
                // sweeping rethinking of ScriptObject, so this will have to do short-term.
                MMgc::GC* gc = this->gc();
                // if we are lazy-initing here, it means our ctor was never called:
                // so, just assume weakKeys = false.
                HeapHashtable* ht = HeapHashtable::create(gc);
                WB(gc, this, hht, ht);
#ifdef DEBUGGER
                if (getSampler() && ht)
                {
                    getSampler()->addDependentObject(this, ht->get_ht());
                }
#endif
            }
            InlineHashtable *ihp = (*hht)->get_ht();
            AvmAssertMsg(ihp != NULL, "Illegal to call getTable before Dictionary init is called");
            return ihp;
        }
    }

    bool ScriptObject::isOwnAtomPropertyHere(Atom name, Atom *recv) const
    {
        AvmAssert(this->vtable->traits->getHashtableOffset() != 0);
        Atom const value = this->getTable()->getNonEmpty(name);
        if (!InlineHashtable::isEmpty(value))
        {
            *recv = value;
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * traverse the delegate chain looking for a value.
     * [ed] it's okay to look only at the HT's in the delegate chain because
     * delegate values may only be instances of Object.  They cannot be objects
     * with slots.  We don't need to look at traits at each step.
     * todo - enforce this rule
     * @param name
     * @return
     */
    Atom ScriptObject::getAtomProperty(Atom name) const
    {
        if (!traits()->needsHashtable())
        {
            return getAtomPropertyFromProtoChain(name, delegate, traits());
        }
        else
        {
            Stringp s = core()->atomToString(name);
            AvmAssert(s->isInterned());
            Atom ival = s->getIntAtom();
            if (ival)
            {
                name = ival;
            }

            // dynamic lookup on this object
            const ScriptObject *o = this;
            do
            {
                // ensure prototype is dynamic
                if (!o->vtable->traits->getHashtableOffset())
                    continue;

                Atom value;
                if (o->isOwnAtomPropertyHere(name, &value))
                    return value;
            }
            while ((o = o->delegate) != NULL);
            return undefinedAtom;
        }
    }

    Atom ScriptObject::getAtomPropertyFromProtoChain(Atom name, ScriptObject* o, Traits *origObjTraits) const
    {
        // todo will delegate always be non-null here?
        if (o != NULL)
        {
            Atom searchname = name;
            Stringp s = core()->atomToString(name);
            AvmAssert(s->isInterned());
            Atom ival = s->getIntAtom();
            if (ival)
            {
                searchname = ival;
            }
            do
            {
                // ensure prototype is dynamic
                if (!o->vtable->traits->getHashtableOffset())
                    continue;
                Atom value;
                if (o->isOwnAtomPropertyHere(searchname, &value))
                    return value;
            }
            while ((o = o->delegate) != NULL);
        }
        // NOTE use default public since name is not used
        Multiname multiname(core()->getAnyPublicNamespace(), AvmCore::atomToString(name));
        toplevel()->throwReferenceError(kReadSealedError, &multiname, origObjTraits);
        // unreached
        return undefinedAtom;
    }

    bool ScriptObject::hasMultinameProperty(const Multiname* multiname) const
    {
        if (traits()->needsHashtable() && multiname->isValidDynamicName())
            {
                return hasAtomProperty(multiname->getName()->atom());
            }
            else
            {
            // ISSUE should this walk the proto chain?
            return false;
        }
    }

    bool ScriptObject::hasAtomProperty(Atom name) const
    {
        if (traits()->needsHashtable())
        {
            Stringp s = core()->atomToString(name);
            AvmAssert(s->isInterned());
            Atom ival = s->getIntAtom();
            if (ival)
            {
                name = ival;
            }

            return getTable()->contains(name);
        }
        else
        {
            // ISSUE should this walk the proto chain?
            return false;
        }
    }

    void ScriptObject::throwWriteSealedError(const Multiname& name)
    {
        toplevel()->throwReferenceError(kWriteSealedError, name, traits());
    }

    void ScriptObject::throwWriteSealedError(Atom name)
    {
        AvmCore* core = this->core();
        throwWriteSealedError(Multiname(core->getAnyPublicNamespace(), core->intern(name)));
    }

    void ScriptObject::throwCantInstantiateError()
    {
        Multiname qname(traits()->ns(), traits()->name());
        toplevel()->argumentErrorClass()->throwError(kCantInstantiateError, core()->toErrorString(&qname));
    }

    void ScriptObject::setAtomProperty(Atom name, Atom value)
    {
        if (traits()->needsHashtable())
        {
            Stringp s = core()->atomToString(name);
            AvmAssert(s->isInterned());
            Atom ival = s->getIntAtom();
            if (ival)
            {
                name = ival;
            }

            MMGC_MEM_TYPE(this);
            getTable()->add (name, value);
            MMGC_MEM_TYPE(NULL);
        }
        else
        {
            throwWriteSealedError(name);
        }
    }

    void ScriptObject::setMultinameProperty(const Multiname* name, Atom value)
    {
        if (traits()->needsHashtable() && name->isValidDynamicName())
        {
            setStringProperty(name->getName(), value);
        }
        else
        {
            throwWriteSealedError(*name);
        }
    }

    bool ScriptObject::getAtomPropertyIsEnumerable(Atom name) const
    {
        if (traits()->needsHashtable())
        {
            Stringp s = core()->atomToString(name);
            AvmAssert(s->isInterned());
            Atom ival = s->getIntAtom();
            if (ival)
            {
                name = ival;
            }

            return getTable()->getAtomPropertyIsEnumerable(name);
        }
        else
        {
            // ISSUE should this walk the proto chain?
            return false;
        }
    }

    void ScriptObject::setAtomPropertyIsEnumerable(Atom name, bool enumerable)
    {
        if (traits()->needsHashtable())
        {
            Stringp s = core()->atomToString(name);
            AvmAssert(s->isInterned());
            Atom ival = s->getIntAtom();
            if (ival)
            {
                name = ival;
            }

            getTable()->setAtomPropertyIsEnumerable(name, enumerable);
        }
        else
        {
            throwWriteSealedError(name);
        }
    }

    bool ScriptObject::deleteAtomProperty(Atom name)
    {
        if (traits()->needsHashtable())
        {
            Stringp s = core()->atomToString(name);
            AvmAssert(s->isInterned());
            Atom ival = s->getIntAtom();
            if (ival)
            {
                name = ival;
            }

            getTable()->remove(name);
            return true;
        }
        else
        {
            return false;
        }
    }

    bool ScriptObject::deleteMultinameProperty(const Multiname* name)
    {
        if (traits()->needsHashtable() && name->isValidDynamicName())
        {
            return deleteStringProperty(name->getName());
        }
        else
        {
            return false;
        }
    }

    Atom ScriptObject::getUintProperty(uint32_t i) const
    {
        // N.B.: a key present in ScriptObject must be interned string;
        // thus uninterned implies absent (cf. bugzilla 556023).

        AvmCore* core = this->core();

        if (!(i&MAX_INTEGER_MASK))
        {
            if (!traits()->needsHashtable())
            {
                Stringp interned;
                bool present = core->isInternedUint(i, &interned);
                if (present)
                {
                    Atom name = interned->atom();
                    return getAtomPropertyFromProtoChain(name, delegate,
                                                         traits());
                }
                else
                {
                    return undefinedAtom;
                }
            }
            else
            {
                // dynamic lookup on this object
                Atom name = core->uintToAtom (i);
                const ScriptObject *o = this;
                do
                {
                    // ensure prototype is dynamic
                    if (!o->vtable->traits->getHashtableOffset())
                        continue;

                    Atom value;
                    if (o->isOwnAtomPropertyHere(name, &value))
                        return value;
                }
                while ((o = o->delegate) != NULL);
                return undefinedAtom;
            }
        }
        else
        {
            Stringp interned;
            bool present;
            present = core->isInternedUint(i, &interned);
            if (present)
            {
                return getAtomProperty(interned->atom());
            }
            else
            {
                return undefinedAtom;
            }
        }
    }

    void ScriptObject::setUintProperty(uint32_t i, Atom value)
    {
        AvmCore* core = this->core();
        if (!(i&MAX_INTEGER_MASK))
        {
            Atom name = core->uintToAtom (i);
            if (traits()->needsHashtable())
            {
                MMGC_MEM_TYPE(this);
                getTable()->add(name, value);
                MMGC_MEM_TYPE(NULL);
            }
            else
            {
                throwWriteSealedError(core->internUint32(i)->atom());
            }
        }
        else
        {
            setAtomProperty(core->internUint32(i)->atom(), value);
        }
    }

    bool ScriptObject::delUintProperty(uint32_t i)
    {
        AvmCore* core = this->core();
        if (!(i&MAX_INTEGER_MASK))
        {
            Atom name = core->uintToAtom (i);
            if (traits()->needsHashtable())
            {
                getTable()->remove(name);
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return deleteAtomProperty(core->internUint32(i)->atom());
        }
    }

    bool ScriptObject::hasUintProperty(uint32_t i) const
    {
        AvmCore* core = this->core();
        if (!(i&MAX_INTEGER_MASK))
        {
            Atom name = core->uintToAtom (i);
            if (traits()->needsHashtable())
            {
                return getTable()->contains(name);
            }
            else
            {
                // ISSUE should this walk the proto chain?
                return false;
            }
        }
        else
        {
            return hasAtomProperty(core->internUint32(i)->atom());
        }
    }

    Atom ScriptObject::getMultinameProperty(const Multiname* multiname) const
    {
        if (multiname->isValidDynamicName())
        {
            return getStringProperty(multiname->getName());
        }
        else
        {
            Toplevel* toplevel = this->toplevel();

            if (multiname->isNsset())
                toplevel->throwReferenceError(kReadSealedErrorNs, multiname, traits());
            else
                toplevel->throwReferenceError(kReadSealedError, multiname, traits());
            return undefinedAtom;
        }
    }

    // this = argv[0] (ignored)
    // arg1 = argv[1]
    // argN = argv[argc]
    Atom ScriptObject::callProperty(const Multiname* multiname, int argc, Atom* argv)
    {
        Atom method = getMultinameProperty(multiname);
        if (!AvmCore::isObject(method))
            toplevel()->throwTypeError(kCallOfNonFunctionError, core()->toErrorString(multiname));
        argv[0] = atom(); // replace receiver
        return avmplus::op_call(toplevel(), method, argc, argv);
    }

    Atom ScriptObject::getDescendants(const Multiname* /*name*/) const
    {
        toplevel()->throwTypeError(kDescendentsError, core()->toErrorString(traits()));
        return undefinedAtom;// not reached
    }

    bool ScriptObject::isGlobalObject() const
    {
        return traits()->posType() == TRAITSTYPE_SCRIPT;
    }

#ifdef AVMPLUS_VERBOSE
    PrintWriter& ScriptObject::print(PrintWriter& prw) const
    {
        (traits()->name() != NULL) ? prw << traits()
                                   : prw << "{}";
        return prw << "@" << asAtomHex(atom());
    }
#endif

    Atom ScriptObject::defaultValue()
    {
        AvmCore *core = this->core();
        Toplevel* toplevel = this->toplevel();

        Atom atomv_out[1];

        // call this.valueOf()
        // NOTE use callers versioned public to get correct valueOf
        Multiname tempname(core->findPublicNamespace(), core->kvalueOf);
        atomv_out[0] = atom();
        Atom result = toplevel->callproperty(atom(), &tempname, 0, atomv_out, vtable);

        // if result is primitive, return it
        if (atomKind(result) != kObjectType)
            return result;

        // otherwise call this.toString()
        tempname.setName(core->ktoString);
        atomv_out[0] = atom();
        result = toplevel->callproperty(atom(), &tempname, 0, atomv_out, vtable);

        // if result is primitive, return it
        if (atomKind(result) != kObjectType)
            return result;

        // could not convert to primitive.
        toplevel->throwTypeError(kConvertToPrimitiveError, core->toErrorString(traits()));
        return undefinedAtom;
    }

    // Execute the ToString algorithm as described in ECMA-262 Section 9.8.
    // This is ToString(ToPrimitive(input argument, hint String))
    // ToPrimitive(input argument, hint String) calls [[DefaultValue]]
    // described in ECMA-262 8.6.2.6.  The [[DefaultValue]] algorithm
    // with hint String is inlined here.
    Stringp ScriptObject::toString()
    {
        AvmCore *core = this->core();
        Toplevel* toplevel = this->toplevel();

        Atom atomv_out[1];

        // call this.toString()
        // NOTE use callers versioned public to get correct toString
        Multiname tempname(core->findPublicNamespace(), core->ktoString);
        atomv_out[0] = atom();
        Atom result = toplevel->callproperty(atom(), &tempname, 0, atomv_out, vtable);

        // if result is primitive, return its ToString
        if (atomKind(result) != kObjectType)
            return core->string(result);

        // otherwise call this.valueOf()
        tempname.setName(core->kvalueOf);
        atomv_out[0] = atom();
        result = toplevel->callproperty(atom(), &tempname, 0, atomv_out, vtable);

        // if result is primitive, return it
        if (atomKind(result) != kObjectType)
            return core->string(result);

        // could not convert to primitive.
        toplevel->throwTypeError(kConvertToPrimitiveError, core->toErrorString(traits()));
        return NULL; // unreachable
    }

    // this = argv[0] (ignored)
    // arg1 = argv[1]
    // argN = argv[argc]
    Atom ScriptObject::call(int /*argc*/, Atom* /*argv*/)
    {
        // TypeError in ECMA to execute a non-function
        // NOTE use default public since name is not used
        Multiname name(core()->getAnyPublicNamespace(), core()->kvalue);
        toplevel()->throwTypeError(kCallOfNonFunctionError, core()->toErrorString(&name));
        return undefinedAtom;
    }

    // this = argv[0] (ignored)
    // arg1 = argv[1]
    // argN = argv[argc]
    Atom ScriptObject::construct(int /*argc*/, Atom* /*argv*/)
    {
        // TypeError in ECMA to execute a non-function
        toplevel()->throwTypeError(kConstructOfNonFunctionError);
        return undefinedAtom;
    }

    Atom ScriptObject::applyTypeArgs(int /*argc*/, Atom* /*argv*/)
    {
        toplevel()->throwTypeError(kTypeAppOfNonParamType);
        return undefinedAtom;
    }

    Atom ScriptObject::getSlotAtom(uint32_t slot, AvmCore *core)
    {
        Traits* traits = this->traits();
        const TraitsBindingsp td = traits->getTraitsBindings();
        // repeated if-else is actually more performant than a switch statement in this case.
        // SST_atom is most common case, put it first
        void* p;
        const SlotStorageType sst = td->calcSlotAddrAndSST(slot, (void*)this, p);
        if (sst == SST_atom)
        {
            return *((const Atom*)p);
        }
        else if (sst == SST_double)
        {
            return core->doubleToAtom(*((const double*)p));
        }
#ifdef VMCFG_FLOAT
        else if (sst == SST_float)
        {
            return traits->core->floatToAtom(*((const float*)p));
        }
        else if (sst == SST_float4)
        {
            return traits->core->float4ToAtom(AvmThunkUnbox_FLOAT4(float4_t, *((Atom*)p)) );
        }
#endif // VMCFG_FLOAT
        else if (sst == SST_int32)
        {
            return core->intToAtom(*((const int32_t*)p));
        }
        else if (sst == SST_uint32)
        {
            return core->uintToAtom(*((const int32_t*)p));
        }
        else if (sst == SST_bool32)
        {
            return (*((const int32_t*)p)<<3)|kBooleanType;
        }
        else if (sst == SST_string)
        {
            return (*((const Stringp*)p))->atom(); // may be null|kStringType, that's ok
        }
        else if (sst == SST_namespace)
        {
            return (*((const Namespacep*)p))->atom(); // may be null|kNamespaceType, no problemo
        }
        else // if (sst == SST_scriptobject)
        {
            AvmAssert(sst == SST_scriptobject);
            return (*((const ScriptObject**)p))->atom(); // may be null|kObjectType, copacetic
        }
    }

    Atom ScriptObject::getSlotAtom(uint32_t slot)
    {
        return getSlotAtom(slot, this->traits()->core);
    }

    ScriptObject* ScriptObject::getSlotObject(uint32_t slot)
    {
        Traits* traits = this->traits();
        const TraitsBindingsp td = traits->getTraitsBindings();
        void* p;
        const SlotStorageType sst = td->calcSlotAddrAndSST(slot, (void*)this, p);

        // based on profiling of Flex apps, it's *much* more common for the slot in this case
        // to have a type (vs "atom"), so check for that first...
        if (sst == SST_scriptobject)
        {
            return *((ScriptObject**)p);
        }
        else if (sst == SST_atom)
        {
            Atom const a = *((const Atom*)p);

            // don't call AvmCore::isObject(); it checks for null, which we don't care about here
            if (atomKind(a) == kObjectType)
                return (ScriptObject*)atomPtr(a);

            // else fall thru and return null
        }

        return NULL;
    }

    // note: coerceAndSetSlotAtom now includes a simplified and streamlined version
    // of Toplevel::coerce. If you modify that code, you might need to modify this code.
    void ScriptObject::coerceAndSetSlotAtom(uint32_t slot, Atom value)
    {
        Traits* traits = this->traits();
        const TraitsBindingsp td = traits->getTraitsBindings();
        void* p;
        const SlotStorageType sst = td->calcSlotAddrAndSST(slot, (void*)this, p);
        // repeated if-else is actually more performant than a switch statement in this case.
        // SST_atom is most common case, put it first
        if (sst == SST_atom)
        {
            // no call to coerce() needed, since anything will fit here... with one exception:
            // BUILTIN_object needs to convert undefined->null (though BUILTIN_any does not).
            // it's cheaper to do that here than call out to coerce().
            AvmAssert(td->getSlotTraits(slot) == NULL || td->getSlotTraits(slot)->builtinType == BUILTIN_object);
            if (value == undefinedAtom && td->getSlotTraits(slot) != NULL)
                value = nullObjectAtom;
            WBATOM(traits->core->GetGC(), this, (Atom*)p, value);
        }
        else if (sst == SST_double)
        {
            *((double*)p) = AvmCore::number(value);
        }
#ifdef VMCFG_FLOAT
        else if (sst == SST_float)
        {
            *((float*)p) = AvmCore::singlePrecisionFloat(value);
        }
        else if (sst == SST_float4)
        {
            float4_t* ptr = reinterpret_cast<float4_t*>(p);
            AvmCore::float4(ptr, value);
        }
#endif // VMCFG_FLOAT
        else if (sst == SST_int32)
        {
            *((int32_t*)p) = AvmCore::integer(value);
        }
        else if (sst == SST_uint32)
        {
            *((uint32_t*)p) = AvmCore::toUInt32(value);
        }
        else if (sst == SST_bool32)
        {
            *((int32_t*)p) = AvmCore::boolean(value);
        }
        else
        {
            // null/undefined -> NULL for all of these
            if (AvmCore::isNullOrUndefined(value))
            {
                value = (Atom)0; // don't bother setting tag bits
            }
            else if (sst == SST_string)
            {
                value = (Atom)traits->core->string(value); // don't bother setting tag bits
            }
            else if (sst == SST_namespace)
            {
                // Namespace is final, so we don't have to do the hard work
                if (atomKind(value) != kNamespaceType)
                    goto failure;
            }
            else // if (sst == SST_scriptobject)
            {
                AvmAssert(sst == SST_scriptobject);
                if (atomKind(value) != kObjectType || !AvmCore::atomToScriptObject(value)->traits()->subtypeof(td->getSlotTraits(slot)))
                    goto failure;
            }
            WBRC(traits->core->GetGC(), this, p, atomPtr(value));
        }
        return;

    failure:
        toplevel()->throwTypeError(kCheckTypeFailedError, traits->core->atomToErrorString(value), traits->core->toErrorString(td->getSlotTraits(slot)));
        return;
    }

    Atom ScriptObject::nextName(int index)
    {
        if (!traits()->needsHashtable())
            return nullStringAtom;

        AvmAssert(index > 0);

        InlineHashtable* ht = getTable();
        Atom m = ht->keyAt(index);
        return AvmCore::isNullOrUndefined(m) ? nullStringAtom : m;
    }

    Atom ScriptObject::nextValue(int index)
    {
        if (!traits()->needsHashtable())
            return undefinedAtom;

        AvmAssert(index > 0);

        InlineHashtable* ht = getTable();
        Atom m = ht->keyAt(index);
        if (AvmCore::isNullOrUndefined(m))
            return nullStringAtom;
        return ht->valueAt(index);
    }

    int ScriptObject::nextNameIndex(int index)
    {
        AvmAssert(index >= 0);

        if (!traits()->needsHashtable())
            return 0;

        return getTable()->next(index);
    }

#ifdef DEBUGGER
    uint64_t ScriptObject::bytesUsed() const
    {
        uint64_t bytesUsed = traits()->getTotalSize();
        if(traits()->needsHashtable())
        {
            if (traits()->isDictionary())
            {
                union {
                    uint8_t* p;
                    HeapHashtable** hht;
                };
                p = (uint8_t*)this + traits()->getHashtableOffset();
                bytesUsed += (*hht)->bytesUsed();
            }
            else
            {
                bytesUsed += getTable()->bytesUsed();
            }
        }
        return bytesUsed;
    }

    void ScriptObject::registerDependentObjects(IMemorySampler *memSampler)
    {
        if (traits()->needsHashtable())
        {
            InlineHashtable* ht = getTableNoInit();
            if (ht)
            {
                memSampler->addDependentObject(this, ht);
            }
        }
    }
#endif

    Stringp ScriptObject::implToString() const
    {
        AvmCore* core = this->core();
        Traits* t = this->traits();
        Stringp s = core->concatStrings(core->newConstantStringLatin1("[object "), t->name());
        return core->concatStrings(s, core->newConstantStringLatin1("]"));
    }

    uint32_t ScriptObject::getLengthProperty()
    {
        Toplevel* toplevel = this->toplevel();
        AvmCore* core = toplevel->core();
        Multiname mname(core->getAnyPublicNamespace(), core->klength);
        Atom lenAtm = toplevel->getproperty(this->atom(), &mname, this->vtable);
        return AvmCore::toUInt32(lenAtm);
    }

    void ScriptObject::setLengthProperty(uint32_t newLen)
    {
        Toplevel* toplevel = this->toplevel();
        AvmCore* core = toplevel->core();
        Multiname mname(core->getAnyPublicNamespace(), core->klength);
        Atom lenAtm = core->uintToAtom(newLen);
        toplevel->setproperty(this->atom(), &mname, lenAtm, this->vtable);
    }
}


cmake_minimum_required(VERSION 3.1)

get_filename_component(PROJECT_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME)
project(${PROJECT_NAME})

set(kdtree_HEADERS
    ANN/ANN.h
    ANN/ANNperf.h
    ANN/ANNx.h
    ANN/bd_tree.h
    ANN/kd_fix_rad_search.h
    ANN/kd_pr_search.h
    ANN/kd_search.h
    ANN/kd_split.h
    ANN/kd_tree.h
    ANN/kd_util.h
    ANN/pr_queue.h
    ANN/pr_queue_k.h
    ETH_Kd_Tree/kdTree.h
    ETH_Kd_Tree/PriorityQueue.h
    ETH_Kd_Tree/QueryGrid.h
    ETH_Kd_Tree/vector2D.h
    ETH_Kd_Tree/vector3D.h
    FLANN/config.h
    FLANN/defines.h
    FLANN/flann.hpp
    FLANN/general.h
    FLANN/algorithms/all_indices.h
    FLANN/algorithms/autotuned_index.h
    FLANN/algorithms/center_chooser.h
    FLANN/algorithms/composite_index.h
    FLANN/algorithms/dist.h
    FLANN/algorithms/hierarchical_clustering_index.h
    FLANN/algorithms/kdtree_index.h
    FLANN/algorithms/kdtree_single_index.h
    FLANN/algorithms/kmeans_index.h
    FLANN/algorithms/linear_index.h
    FLANN/algorithms/lsh_index.h
    FLANN/algorithms/nn_index.h
    FLANN/nn/ground_truth.h
    FLANN/nn/index_testing.h
    FLANN/util/allocator.h
    FLANN/util/any.h
    FLANN/util/dynamic_bitset.h
    FLANN/util/heap.h
    FLANN/util/logger.h
    FLANN/util/lsh_table.h
    FLANN/util/matrix.h
    FLANN/util/params.h
    FLANN/util/random.h
    FLANN/util/result_set.h
    FLANN/util/sampling.h
    FLANN/util/saving.h
    FLANN/util/serialization.h
    FLANN/util/timer.h
    nanoflann/nanoflann.hpp
    )

set(kdtree_SOURCES
    ANN/ANN.cpp
    ANN/bd_fix_rad_search.cpp
    ANN/bd_pr_search.cpp
    ANN/bd_search.cpp
    ANN/bd_tree.cpp
    ANN/brute.cpp
    ANN/kd_dump.cpp
    ANN/kd_fix_rad_search.cpp
    ANN/kd_pr_search.cpp
    ANN/kd_search.cpp
    ANN/kd_split.cpp
    ANN/kd_tree.cpp
    ANN/kd_util.cpp
    ANN/perf.cpp
    ETH_Kd_Tree/kdTree.cpp
    )

add_library(${PROJECT_NAME} STATIC ${kdtree_SOURCES} ${kdtree_HEADERS})

set_target_properties(${PROJECT_NAME} PROPERTIES FOLDER "3rd_party")

if (MSVC)
    target_compile_definitions(${PROJECT_NAME} PRIVATE
        _CRT_SECURE_NO_WARNINGS
        _CRT_SECURE_NO_DEPRECATE
        )
endif()


#pragma once

#include "Capstone/capstone.h"

class CAssemblyView : public CWindowImpl<CAssemblyView> {
public:
	DECLARE_WND_CLASS_EX(nullptr, 0, NULL);

	CAssemblyView(cs_insn* insts, int count);

	BEGIN_MSG_MAP(CAssemblyView)
		MESSAGE_HANDLER(WM_CREATE, OnCreate)
		MESSAGE_HANDLER(WM_SIZE, OnSize)
		MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
		MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnBackColor)
	END_MSG_MAP()

private:
	LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
	LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
	LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
	LRESULT OnBackColor(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);

private:
	CEdit m_Edit;
	cs_insn* m_Inst;
	int m_Count;
};


package com.coderising.ood.srp.service;

import java.util.List;

import com.coderising.ood.srp.common.Configuration;
import com.coderising.ood.srp.common.ConfigurationKeys;
import com.coderising.ood.srp.entity.Email;
import com.coderising.ood.srp.entity.Product;
import com.coderising.ood.srp.entity.User;

public class EmailService {

	public Email generateEmail(User user,List<Product> products,Configuration configuration){
		Email email = new Email();
		email.setFromAddress(configuration.getProperty(ConfigurationKeys.EMAIL_ADMIN));
		email.setToAddress(user.getEmailAddress());
		email.setSubject("您关注的产品降价了");
		StringBuffer message=new StringBuffer("尊敬的 "+user.getUserName()+", 您关注的产品:");
		for(Product product:products){
			message.append(product.getProductDesc()+" ");
		}
		message.append("降价了，欢迎购买!");
		email.setMessage(message.toString());
		return email;
	}
	/**
	 * 发送一封Email
	 * @param email
	 */
	public void sendEmail(Email email){
		if(email != null ){
			//假装发了一封邮件
			StringBuilder buffer = new StringBuilder();
			buffer.append("From:").append(email.getFromAddress()).append("\n");
			buffer.append("To:").append(email.getToAddress()).append("\n");
			buffer.append("Subject:").append(email.getSubject()).append("\n");
			buffer.append("Content:").append(email.getMessage()).append("\n");
			System.out.println(buffer.toString());
		}else{
			System.out.println("email 为空，发送邮件失败！");
		}
	}
}


/* Norwegian Nynorsk initialisation for the jQuery UI date picker plugin. */
/* Written by Bjørn Johansen (post@bjornjohansen.no). */
jQuery(function($){
	$.datepicker.regional['nn'] = {
		closeText: 'Lukk',
		prevText: '«Førre',
		nextText: 'Neste»',
		currentText: 'I dag',
		monthNames: ['januar','februar','mars','april','mai','juni','juli','august','september','oktober','november','desember'],
		monthNamesShort: ['jan','feb','mar','apr','mai','jun','jul','aug','sep','okt','nov','des'],
		dayNamesShort: ['sun','mån','tys','ons','tor','fre','lau'],
		dayNames: ['sundag','måndag','tysdag','onsdag','torsdag','fredag','laurdag'],
		dayNamesMin: ['su','må','ty','on','to','fr','la'],
		weekHeader: 'Veke',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''
	};
	$.datepicker.setDefaults($.datepicker.regional['nn']);
});


query ($id: Int!) {
  Staff(id: $id) {
    id
    name {
      first
      last
      native
    }
    description
    language
  }
}


import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

export class AppComponent {
	getWidth() : any {
		if (document.body.offsetWidth < 850) {
			return '90%';
		}

		return 850;
	}
}


var standaloneLibDir = "lib/jasmine-" + jasmineVersion;

function root(path) { return "./" + path; }
function libJasmineCore(path) { return root("lib/jasmine-core/" + path); }
function libConsole() { return "lib/console/" }
function dist(path) { return root("dist/" + path); }

module.exports = {
  standalone: {
    options: {
      archive: root("dist/jasmine-standalone-" + global.jasmineVersion + ".zip")
    },

    files: [
      { src: [ root("MIT.LICENSE") ] },
      {
        src: [ "jasmine_favicon.png"],
        dest: standaloneLibDir,
        expand: true,
        cwd: root("images")
      },
      {
        src: [
          "jasmine.js",
          "jasmine-html.js",
          "jasmine.css"
        ],
        dest: standaloneLibDir,
        expand: true,
        cwd: libJasmineCore("")
      },
      {
        src: [
          "console.js"
        ],
        dest: standaloneLibDir,
        expand: true,
        cwd: libConsole()
      },
      {
        src: [ "boot.js" ],
        dest: standaloneLibDir,
        expand: true,
        cwd: libJasmineCore("boot")
      },
      {
        src: [ "SpecRunner.html" ],
        dest: root(""),
        expand: true,
        cwd: dist("tmp")
      },
      {
        src: [ "*.js" ],
        dest: "src",
        expand: true,
        cwd: libJasmineCore("example/src/")
      },
      {
        src: [ "*.js" ],
        dest: "spec",
        expand: true,
        cwd: libJasmineCore("example/spec/")
      }
    ]
  }
};


{% extends "_templates/base.html" %}
{% set page_title = "Upgrading to 5.x" %}
{% block content %}
{% markdown %}
# Upgrading to 5.x {: .page-header }

The 5.0 version brings some breaking changes, mostly surrounding upload requests.

If you are upgrading from a 3.x version, be sure to also read the [Upgrading to 4.x document](upgrading-to-4.html).

### Resume data persisted using localStorage for traditional endpoints
Fine Uploader no longer uses cookies to persist auto-resume data for traditional endpoints.  Now, all auto-resume
data is persisted to `localStorage` for all endpoint handlers.

This means that any existing auto-resume records will be lost when you switch to a 5.x version if you utilize
a traditional endpoint handler.

### Persisted resume data format changed for S3 and Azure upload endpoints
This means that any existing resume records will be ignored.  This format change was required to
support the new concurrent chunking feature.

### Most XHR requests will now contain an Accept header
This is probably not technically a breaking change, but it should be mentioned here just in case your
server, for some reason, is not expecting this header on requests from Fine Uploader.  This change
affects all `XMLHttpRequest` originated requests sent to local servers
(i.e. not requests sent to S3/Azure).

Your can look at this header to programmatically determine the correct Content-Type for your response,
but you should **NOT** rely on this value for upload requests in IE9 and older since the Accept header
is set by the browser and is not reflective of the expected response Content-Type.  Also, ajax requests
sent in IE9 and IE8 in a cross-origin environment will not contain this header, since
the `XDomainRequest` transport is used and does not allow headers to be specified.

### Removed all utility functions that deal with cookies
As a result of the switch from cookies to `localStorage`, we removed these cookie-related utility
functions as they are no longer needed by Fine Uploader.  If you were utilizing these utility functions for your app,
consider importing a cookie library as a replacement, such as [jquery-cookie][jcookie] or [Cookies][Cookies].

The specific removed util functions were:

* `qq.areCookiesEnabled`
* `qq.getCookie`
* `qq.setCookie`
* `qq.deleteCookie`

### Changes to `resume` option
The `id` property of the `resume` option was removed.  Very few integrators, if any, were making use of this option.
If you were making use of this option property, any existing resume records will be lost when you upgrade to 5.x.

Also, for traditional endpoints, the `cookiesExpireIn` option has changed to `recordsExpireIn`.  This is related to
the switch from cookies to `localStorage`.

### onResume callback is no longer promissory
A promise is no longer an acceptable return type from an `onResume` callback.  It was unclear what benefit this
provided, and supporting this made the code more complicated.  Due to a long-standing oversight in the code,
promises were only accepted from `onResume` callbacks when using the traditional endpoint handler anyway.

### Chunked request only sent for traditional endpoints if necessary
If the chunking.partSize value is greater than or equal to the size of the
file, no chunking will occur. Note that a chunked request is different from
a non-chunked request due to differing headers, and the fact that the
message-body of a chunked request contains a Blob, while a non-chunked request
message-body contains a File (assuming the file is not a scaled version and
the original file is not a Blob itself).

This means that, even if chunking is enabled, a chunked upload request is
only sent to traditional endpoints if the associated file can be broken into
more than 1 chunk.  This behavior is consistent with the way all other
endpoints have functioned.  Previously, a chunked request would always be
sent for traditional endpoints if chunking was supported and enabled.

### `drawThumbnail` API method only passes one argument to rejected promise callback
This was done to bring the API that Fine Uploader exposes in compliance with the A+ promises spec.  While
`qq.Promise` is not A+ compliant, use of other promise implementations when communicating with Fine Uploader
is now supported.  Since the spec indicates that only one argument can be passed to a resolve or reject callback,
the promise returned by the [`drawThumbnail` API method][drawthumbnail] had to be modified.  The resolve callback
already was only passed one argument (the container element), this breaking change only affects the reject callback.
Previously, two arguments were passed, in the event of an error, to the reject callback: the container element, and
an error message.  Now, an object with `container` and `error` properties is the only argument.

[Cookies]: https://github.com/ScottHamper/Cookies
[drawthumbnail]: api/methods.html#drawThumbnail
[jcookie]: https://github.com/carhartl/jquery-cookie

{% endmarkdown %}
{% endblock %}


<?xml version="1.0" encoding="UTF-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
  <file original="modules/dashgoals/dashgoals.php" source-language="en-US" target-language="en" datatype="plaintext">
    <body>
      <trans-unit id="50698c5b8ffaf2b7dd089898a244a668">
        <source>Dashboard Goals</source>
        <target>Dashboard Goals</target>
        <note>Line: 49</note>
      </trans-unit>
      <trans-unit id="ac73c1d4a6befbca8cecf2171cd45d4f">
        <source>Adds a block with your store's forecast.</source>
        <target>Adds a block with your store's forecast.</target>
        <note>Line: 50</note>
      </trans-unit>
      <trans-unit id="86f5978d9b80124f509bdb71786e929e">
        <source>January</source>
        <target>January</target>
        <note>Line: 54</note>
      </trans-unit>
      <trans-unit id="659e59f062c75f81259d22786d6c44aa">
        <source>February</source>
        <target>February</target>
        <note>Line: 55</note>
      </trans-unit>
      <trans-unit id="fa3e5edac607a88d8fd7ecb9d6d67424">
        <source>March</source>
        <target>March</target>
        <note>Line: 56</note>
      </trans-unit>
      <trans-unit id="3fcf026bbfffb63fb24b8de9d0446949">
        <source>April</source>
        <target>April</target>
        <note>Line: 57</note>
      </trans-unit>
      <trans-unit id="195fbb57ffe7449796d23466085ce6d8">
        <source>May</source>
        <target>May</target>
        <note>Line: 58</note>
      </trans-unit>
      <trans-unit id="688937ccaf2a2b0c45a1c9bbba09698d">
        <source>June</source>
        <target>June</target>
        <note>Line: 59</note>
      </trans-unit>
      <trans-unit id="1b539f6f34e8503c97f6d3421346b63c">
        <source>July</source>
        <target>July</target>
        <note>Line: 60</note>
      </trans-unit>
      <trans-unit id="41ba70891fb6f39327d8ccb9b1dafb84">
        <source>August</source>
        <target>August</target>
        <note>Line: 61</note>
      </trans-unit>
      <trans-unit id="cc5d90569e1c8313c2b1c2aab1401174">
        <source>September</source>
        <target>September</target>
        <note>Line: 62</note>
      </trans-unit>
      <trans-unit id="eca60ae8611369fe28a02e2ab8c5d12e">
        <source>October</source>
        <target>October</target>
        <note>Line: 63</note>
      </trans-unit>
      <trans-unit id="7e823b37564da492ca1629b4732289a8">
        <source>November</source>
        <target>November</target>
        <note>Line: 64</note>
      </trans-unit>
      <trans-unit id="82331503174acbae012b2004f6431fa5">
        <source>December</source>
        <target>December</target>
        <note>Line: 65</note>
      </trans-unit>
      <trans-unit id="71241798130f714cbd2786df3da2cf0b">
        <source>Average cart value</source>
        <target>Average cart value</target>
        <note>Line: 193</note>
      </trans-unit>
      <trans-unit id="9ac642c5ef334ea05256563f921bb304">
        <source>Goal exceeded</source>
        <target>Goal exceeded</target>
        <note>Line: 198</note>
      </trans-unit>
      <trans-unit id="7c103c9bbbaecee07ca898ed65667cbf">
        <source>Goal not reached</source>
        <target>Goal not reached</target>
        <note>Line: 199</note>
      </trans-unit>
      <trans-unit id="eb233580dc419f03df5905f175606e4d">
        <source>Goal set:</source>
        <target>Goal set:</target>
        <note>Line: 489</note>
      </trans-unit>
    </body>
  </file>
  <file original="modules/dashgoals/views/templates/hook/config.tpl" source-language="en-US" target-language="en" datatype="plaintext">
    <body>
      <trans-unit id="e4c3da18c66c0147144767efeb59198f">
        <source>Conversion Rate</source>
        <target>Conversion Rate</target>
        <note>Line: 33</note>
      </trans-unit>
    </body>
  </file>
  <file original="modules/dashgoals/views/templates/hook/dashboard_zone_two.tpl" source-language="en-US" target-language="en" datatype="plaintext">
    <body>
      <trans-unit id="e7935ae6c516d89405ec532359d2d75a">
        <source>Traffic</source>
        <target>Traffic</target>
        <note>Line: 58</note>
      </trans-unit>
      <trans-unit id="3bb1503332637805beddb73a2dd1fe1b">
        <source>Conversion</source>
        <target>Conversion</target>
        <note>Line: 61</note>
      </trans-unit>
      <trans-unit id="8c804960da61b637c548c951652b0cac">
        <source>Average Cart Value</source>
        <target>Average Cart Value</target>
        <note>Line: 64</note>
      </trans-unit>
      <trans-unit id="89c1265be62d3ba835a3d963db5956b0">
        <source>Forecast</source>
        <target>Forecast</target>
        <note>Line: 38</note>
      </trans-unit>
    </body>
  </file>
</xliff>


/* Class = "UITableViewSection"; headerTitle = "Basics"; ObjectID = "0UP-No-gFa"; */
"0UP-No-gFa.headerTitle" = "Basics";

/* Class = "UITableViewSection"; headerTitle = "Filtering"; ObjectID = "4sM-rh-exU"; */
"4sM-rh-exU.headerTitle" = "Filtering";

/* Class = "UILabel"; text = "Basic Usage"; ObjectID = "DSZ-fY-z3N"; */
"DSZ-fY-z3N.text" = "Basic Usage";

/* Class = "UINavigationItem"; title = "Examples"; ObjectID = "JaI-xQ-Do9"; */
"JaI-xQ-Do9.title" = "Examples";

/* Class = "UITableViewSection"; headerTitle = "Appearance"; ObjectID = "JiI-DQ-t3T"; */
"JiI-DQ-t3T.headerTitle" = "Appearance";

/* Class = "UILabel"; text = "Custom Asset Order by PHFetchOptions"; ObjectID = "LNS-Of-WlE"; */
"LNS-Of-WlE.text" = "Custom Asset Order by PHFetchOptions";

/* Class = "UILabel"; text = "Custom Album Order by PHFetchOptions"; ObjectID = "TjC-o1-rUV"; */
"TjC-o1-rUV.text" = "Custom Album Order by PHFetchOptions";

/* Class = "UILabel"; text = "Custom Album Cell & Layout"; ObjectID = "V01-fT-RbR"; */
"V01-fT-RbR.text" = "Custom Album Cell & Layout";

/* Class = "UILabel"; text = "Show/Hide Empty Albums"; ObjectID = "ZnK-wU-zl5"; */
"ZnK-wU-zl5.text" = "Show/Hide Empty Albums";

/* Class = "UILabel"; text = "Custom Asset Cell & Layout"; ObjectID = "bFM-04-mtq"; */
"bFM-04-mtq.text" = "Custom Asset Cell & Layout";

/* Class = "UILabel"; text = "Custom Asset Filter by PHFetchOptions"; ObjectID = "fd7-wl-qNV"; */
"fd7-wl-qNV.text" = "Custom Asset Filter by PHFetchOptions";

/* Class = "UILabel"; text = "Custom Album Filter by PHFetchOptions"; ObjectID = "gbd-aR-wJN"; */
"gbd-aR-wJN.text" = "Custom Album Filter by PHFetchOptions";

/* Class = "UILabel"; text = "Custom Album Filter by Block"; ObjectID = "kN3-jP-3pt"; */
"kN3-jP-3pt.text" = "Custom Album Filter by Block";

/* Class = "UILabel"; text = "Custom Album Order by Block"; ObjectID = "kgI-yV-i1T"; */
"kgI-yV-i1T.text" = "Custom Album Order by Block";

/* Class = "UITableViewSection"; headerTitle = "Sorting"; ObjectID = "mxV-kP-Klc"; */
"mxV-kP-Klc.headerTitle" = "Sorting";

/* Class = "UILabel"; text = "Show/Hide Hidden Album"; ObjectID = "pp8-mo-h2x"; */
"pp8-mo-h2x.text" = "Show/Hide Hidden Album";


<Ui xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
  <Script file="MainPanel.lua" />
  <Script file="BrowsePanel.lua" />
  <Script file="ManagerPanel.lua" />
  <Script file="CreatePanel.lua" />
  <Script file="ApplicantPanel.lua" />
  <Script file="ExchangePanel.lua" />
  <Script file="MallPanel.lua" />
  <Script file="RewardPanel.lua" />
  <Script file="ActivitiesParent.lua" />
  <Script file="ActivitiesSummary.lua" />
  <Script file="ActivitiesMall.lua" />
  <Script file="ActivitiesLottery.lua" />
  <Script file="AppParent.lua" />
  <Script file="AppFollowQueryPanel.lua" />
  <Script file="AppFollowPanel.lua" />
  <Script file="RecentPanel.lua" />
  <Script file="OptionPanel.lua" />
  <Script file="PlayerInfoDialog.lua" />
  <Script file="AppQrDialog.lua" />
  <Script file="DataBroker.lua" />
</Ui>


loadProjectFile -file "C:\cygwin\home\matt\usrp2\fpga\boot_cpld/boot_cpld.ipf"
setMode -ss
setMode -sm
setMode -hw140
setMode -spi
setMode -acecf
setMode -acempm
setMode -pff
setMode -bs
setMode -bs
setMode -bs
setMode -bs
setCable -port auto
Identify
identifyMPM
assignFile -p 1 -file "C:/cygwin/home/matt/usrp2/fpga/boot_cpld/boot_cpld.jed"
Program -p 1 -e -v -defaultVersion 0
Program -p 1 -e -v -defaultVersion 0
Program -p 1 -e -v -defaultVersion 0
Program -p 1 -e -v -defaultVersion 0
Program -p 1 -e -v -defaultVersion 0
Program -p 1 -e -v -defaultVersion 0
Identify
identifyMPM
Identify
identifyMPM
Identify
identifyMPM
Identify
identifyMPM
Identify
identifyMPM
setMode -bs
deleteDevice -position 1


/*
 * Copyright by the original author or authors.
 *
 * 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.
 */

package org.bitcoinj.core;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;

import java.io.ByteArrayOutputStream;

import javax.annotation.Nullable;

import com.google.common.primitives.UnsignedBytes;
import org.bitcoinj.params.Networks;
import org.bitcoinj.script.Script;

/**
 *
Implementation of native segwit addresses. They are composed of two parts:

 *
 *

 *
A human-readable part (HRP) which is a string the specifies the network. See
 * {@link NetworkParameters#getSegwitAddressHrp()}.

 *
A data part, containing the witness version (encoded as an OP_N operator) and program (encoded by re-arranging
 * bits into groups of 5).

 *

 *
 *
See BIP173 for details.

 *
 *
However, you don't need to care about the internals. Use {@link #fromBech32(NetworkParameters, String)},
 * {@link #fromHash(NetworkParameters, byte[])} or {@link #fromKey(NetworkParameters, ECKey)} to construct a native
 * segwit address.

 */
public class SegwitAddress extends Address {
    public static final int WITNESS_PROGRAM_LENGTH_PKH = 20;
    public static final int WITNESS_PROGRAM_LENGTH_SH = 32;
    public static final int WITNESS_PROGRAM_MIN_LENGTH = 2;
    public static final int WITNESS_PROGRAM_MAX_LENGTH = 40;

    /**
     * Private constructor. Use {@link #fromBech32(NetworkParameters, String)},
     * {@link #fromHash(NetworkParameters, byte[])} or {@link #fromKey(NetworkParameters, ECKey)}.
     *
     * @param params
     *            network this address is valid for
     * @param witnessVersion
     *            version number between 0 and 16
     * @param witnessProgram
     *            hash of pubkey or script (for version 0)
     */
    private SegwitAddress(NetworkParameters params, int witnessVersion, byte[] witnessProgram)
            throws AddressFormatException {
        this(params, encode(witnessVersion, witnessProgram));
    }

    /**
     * Helper for the above constructor.
     */
    private static byte[] encode(int witnessVersion, byte[] witnessProgram) throws AddressFormatException {
        byte[] convertedProgram = convertBits(witnessProgram, 0, witnessProgram.length, 8, 5, true);
        byte[] bytes = new byte[1 + convertedProgram.length];
        bytes[0] = (byte) (witnessVersion & 0xff);
        System.arraycopy(convertedProgram, 0, bytes, 1, convertedProgram.length);
        return bytes;
    }

    /**
     * Private constructor. Use {@link #fromBech32(NetworkParameters, String)},
     * {@link #fromHash(NetworkParameters, byte[])} or {@link #fromKey(NetworkParameters, ECKey)}.
     *
     * @param params
     *            network this address is valid for
     * @param data
     *            in segwit address format, before bit re-arranging and bech32 encoding
     * @throws AddressFormatException
     *             if any of the sanity checks fail
     */
    private SegwitAddress(NetworkParameters params, byte[] data) throws AddressFormatException {
        super(params, data);
        if (data.length < 1)
            throw new AddressFormatException.InvalidDataLength("Zero data found");
        final int witnessVersion = getWitnessVersion();
        if (witnessVersion < 0 || witnessVersion > 16)
            throw new AddressFormatException("Invalid script version: " + witnessVersion);
        byte[] witnessProgram = getWitnessProgram();
        if (witnessProgram.length < WITNESS_PROGRAM_MIN_LENGTH || witnessProgram.length > WITNESS_PROGRAM_MAX_LENGTH)
            throw new AddressFormatException.InvalidDataLength("Invalid length: " + witnessProgram.length);
        // Check script length for version 0
        if (witnessVersion == 0 && witnessProgram.length != WITNESS_PROGRAM_LENGTH_PKH
                && witnessProgram.length != WITNESS_PROGRAM_LENGTH_SH)
            throw new AddressFormatException.InvalidDataLength(
                    "Invalid length for address version 0: " + witnessProgram.length);
    }

    /**
     * Returns the witness version in decoded form. Only version 0 is in use right now.
     *
     * @return witness version, between 0 and 16
     */
    public int getWitnessVersion() {
        return bytes[0] & 0xff;
    }

    /**
     * Returns the witness program in decoded form.
     *
     * @return witness program
     */
    public byte[] getWitnessProgram() {
        // skip version byte
        return convertBits(bytes, 1, bytes.length - 1, 5, 8, false);
    }

    @Override
    public byte[] getHash() {
        return getWitnessProgram();
    }

    /**
     * Get the type of output script that will be used for sending to the address. This is either
     * {@link Script.ScriptType#P2WPKH} or {@link Script.ScriptType#P2WSH}.
     *
     * @return type of output script
     */
    @Override
    public Script.ScriptType getOutputScriptType() {
        int version = getWitnessVersion();
        checkState(version == 0);
        int programLength = getWitnessProgram().length;
        if (programLength == WITNESS_PROGRAM_LENGTH_PKH)
            return Script.ScriptType.P2WPKH;
        if (programLength == WITNESS_PROGRAM_LENGTH_SH)
            return Script.ScriptType.P2WSH;
        throw new IllegalStateException("Cannot happen.");
    }

    @Override
    public String toString() {
        return toBech32();
    }

    /**
     * Construct a {@link SegwitAddress} from its textual form.
     *
     * @param params
     *            expected network this address is valid for, or null if the network should be derived from the bech32
     * @param bech32
     *            bech32-encoded textual form of the address
     * @return constructed address
     * @throws AddressFormatException
     *             if something about the given bech32 address isn't right
     */
    public static SegwitAddress fromBech32(@Nullable NetworkParameters params, String bech32)
            throws AddressFormatException {
        Bech32.Bech32Data bechData = Bech32.decode(bech32);
        if (params == null) {
            for (NetworkParameters p : Networks.get()) {
                if (bechData.hrp.equals(p.getSegwitAddressHrp()))
                    return new SegwitAddress(p, bechData.data);
            }
            throw new AddressFormatException.InvalidPrefix("No network found for " + bech32);
        } else {
            if (bechData.hrp.equals(params.getSegwitAddressHrp()))
                return new SegwitAddress(params, bechData.data);
            throw new AddressFormatException.WrongNetwork(bechData.hrp);
        }
    }

    /**
     * Construct a {@link SegwitAddress} that represents the given hash, which is either a pubkey hash or a script hash.
     * The resulting address will be either a P2WPKH or a P2WSH type of address.
     *
     * @param params
     *            network this address is valid for
     * @param hash
     *            20-byte pubkey hash or 32-byte script hash
     * @return constructed address
     */
    public static SegwitAddress fromHash(NetworkParameters params, byte[] hash) {
        return new SegwitAddress(params, 0, hash);
    }

    /**
     * Construct a {@link SegwitAddress} that represents the public part of the given {@link ECKey}. Note that an
     * address is derived from a hash of the public key and is not the public key itself.
     *
     * @param params
     *            network this address is valid for
     * @param key
     *            only the public part is used
     * @return constructed address
     */
    public static SegwitAddress fromKey(NetworkParameters params, ECKey key) {
        checkArgument(key.isCompressed(), "only compressed keys allowed");
        return fromHash(params, key.getPubKeyHash());
    }

    /**
     * Returns the textual form of the address.
     *
     * @return textual form encoded in bech32
     */
    public String toBech32() {
        return Bech32.encode(params.getSegwitAddressHrp(), bytes);
    }

    /**
     * Helper for re-arranging bits into groups.
     */
    private static byte[] convertBits(final byte[] in, final int inStart, final int inLen, final int fromBits,
            final int toBits, final boolean pad) throws AddressFormatException {
        int acc = 0;
        int bits = 0;
        ByteArrayOutputStream out = new ByteArrayOutputStream(64);
        final int maxv = (1 << toBits) - 1;
        final int max_acc = (1 << (fromBits + toBits - 1)) - 1;
        for (int i = 0; i < inLen; i++) {
            int value = in[i + inStart] & 0xff;
            if ((value >>> fromBits) != 0) {
                throw new AddressFormatException(
                        String.format("Input value '%X' exceeds '%d' bit size", value, fromBits));
            }
            acc = ((acc << fromBits) | value) & max_acc;
            bits += fromBits;
            while (bits >= toBits) {
                bits -= toBits;
                out.write((acc >>> bits) & maxv);
            }
        }
        if (pad) {
            if (bits > 0)
                out.write((acc << (toBits - bits)) & maxv);
        } else if (bits >= fromBits || ((acc << (toBits - bits)) & maxv) != 0) {
            throw new AddressFormatException("Could not convert bits, invalid padding");
        }
        return out.toByteArray();
    }

    /**
     * {@inheritDoc}
     *
     * @param o other {@code Address} object
     * @return comparison result
     */
    @Override
    public int compareTo(Address o) {
        int result = compareAddressPartial(o);
        if (result != 0) return result;

        // Compare the bytes
        return UnsignedBytes.lexicographicalComparator().compare(this.bytes, o.bytes);
    }
}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
package org.apache.logging.log4j.status;

import java.io.IOException;
import java.io.PrintStream;

import org.apache.logging.log4j.Level;

/**
 * StatusListener that writes to the Console.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class StatusConsoleListener implements StatusListener {

    private Level level = Level.FATAL;
    private String[] filters;
    private final PrintStream stream;

    /**
     * Creates the StatusConsoleListener using the supplied Level.
     * @param level The Level of status messages that should appear on the console.
     */
    public StatusConsoleListener(final Level level) {
        this(level, System.out);
    }

    /**
     * Creates the StatusConsoleListener using the supplied Level. Make sure not to use a logger stream of some sort
     * to avoid creating an infinite loop of indirection!
     * @param level The Level of status messages that should appear on the console.
     * @param stream The PrintStream to write to.
     * @throws IllegalArgumentException if the PrintStream argument is {@code null}.
     */
    public StatusConsoleListener(final Level level, final PrintStream stream) {
        if (stream == null) {
            throw new IllegalArgumentException("You must provide a stream to use for this listener.");
        }
        this.level = level;
        this.stream = stream;
    }

    /**
     * Sets the level to a new value.
     * @param level The new Level.
     */
    public void setLevel(final Level level) {
        this.level = level;
    }

    /**
     * Return the Log Level for which the Listener should receive events.
     * @return the Log Level.
     */
    @Override
    public Level getStatusLevel() {
        return this.level;
    }

    /**
     * Writes status messages to the console.
     * @param data The StatusData.
     */
    @Override
    public void log(final StatusData data) {
        if (!filtered(data)) {
            stream.println(data.getFormattedStatus());
        }
    }

    /**
     * Adds package name filters to exclude.
     * @param filters An array of package names to exclude.
     */
    public void setFilters(final String... filters) {
        this.filters = filters;
    }

    private boolean filtered(final StatusData data) {
        if (filters == null) {
            return false;
        }
        final String caller = data.getStackTraceElement().getClassName();
        for (final String filter : filters) {
            if (caller.startsWith(filter)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void close() throws IOException {
        // only want to close non-system streams
        if (this.stream != System.out && this.stream != System.err) {
            this.stream.close();
        }
    }
}


<?xml version="1.0" standalone="no" ?>
<!DOCTYPE pov SYSTEM "/usr/share/cgc-docs/replay.dtd">
<pov>
<cbid>service</cbid>
<replay>
    <write><data>UUUUUUUU</data></write>
    <read><delim>\x0a</delim><match><data>What is your name?\x0a</data></match></read>
    <write><data>User\x0a</data></write>
    <read><delim>\x0a</delim><match><data>Hi\x2c User\x0a</data></match></read>
    <read><delim>\x3e</delim><match><pcre>.*?0 B ></pcre></match></read>
    <write><data>15 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?1 B ></pcre></match></read>
    <write><data>5 12\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?2 B ></pcre></match></read>
    <write><data>0 13\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?3 B ></pcre></match></read>
    <write><data>10 10\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?4 B ></pcre></match></read>
    <write><data>9 5\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?5 B ></pcre></match></read>
    <write><data>16 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?6 B ></pcre></match></read>
    <write><data>14 6\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?7 B ></pcre></match></read>
    <write><data>8 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?8 B ></pcre></match></read>
    <write><data>18 8\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?9 B ></pcre></match></read>
    <write><data>5 14\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?10 B ></pcre></match></read>
    <write><data>16 0\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?11 B ></pcre></match></read>
    <write><data>1 10\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?12 B ></pcre></match></read>
    <write><data>9 9\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?13 B ></pcre></match></read>
    <write><data>14 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?14 B ></pcre></match></read>
    <write><data>16 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?14 B ></pcre></match></read>
    <write><data>4 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?14 B ></pcre></match></read>
    <write><data>19 14\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?14 B ></pcre></match></read>
    <write><data>7 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?15 B ></pcre></match></read>
    <write><data>2 2\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?16 B ></pcre></match></read>
    <write><data>3 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?17 B ></pcre></match></read>
    <write><data>3 17\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?18 B ></pcre></match></read>
    <write><data>16 11\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?19 B ></pcre></match></read>
    <write><data>17 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?20 B ></pcre></match></read>
    <write><data>14 19\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?20 B ></pcre></match></read>
    <write><data>6 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?20 B ></pcre></match></read>
    <write><data>8 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?21 B ></pcre></match></read>
    <write><data>15 4\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?21 B ></pcre></match></read>
    <write><data>4 5\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?22 B ></pcre></match></read>
    <write><data>0 16\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?23 B ></pcre></match></read>
    <write><data>16 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?24 B ></pcre></match></read>
    <write><data>13 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?25 B ></pcre></match></read>
    <write><data>1 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?26 B ></pcre></match></read>
    <write><data>11 10\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?27 B ></pcre></match></read>
    <write><data>pass\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?28 B ></pcre></match></read>
    <write><data>0 12\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?29 B ></pcre></match></read>
    <write><data>8 10\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?30 B ></pcre></match></read>
    <write><data>8 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?31 B ></pcre></match></read>
    <write><data>6 3\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?31 B ></pcre></match></read>
    <write><data>7 4\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?32 B ></pcre></match></read>
    <write><data>14 13\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?33 B ></pcre></match></read>
    <write><data>9 19\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?33 B ></pcre></match></read>
    <write><data>2 13\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?34 B ></pcre></match></read>
    <write><data>6 2\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?34 B ></pcre></match></read>
    <write><data>8 16\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?35 B ></pcre></match></read>
    <write><data>2 13\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?35 B ></pcre></match></read>
    <write><data>4 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?36 B ></pcre></match></read>
    <write><data>pass\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?37 B ></pcre></match></read>
    <write><data>11 10\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?37 B ></pcre></match></read>
    <write><data>9 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?38 B ></pcre></match></read>
    <write><data>9 19\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?38 B ></pcre></match></read>
    <write><data>0 11\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?39 B ></pcre></match></read>
    <write><data>11 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?40 B ></pcre></match></read>
    <write><data>7 6\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?41 B ></pcre></match></read>
    <write><data>12 10\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?42 B ></pcre></match></read>
    <write><data>6 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?42 B ></pcre></match></read>
    <write><data>0 16\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?42 B ></pcre></match></read>
    <write><data>19 11\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?42 B ></pcre></match></read>
    <write><data>5 16\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?43 B ></pcre></match></read>
    <write><data>5 4\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?44 B ></pcre></match></read>
    <write><data>18 0\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?44 B ></pcre></match></read>
    <write><data>4 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?44 B ></pcre></match></read>
    <write><data>5 0\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?45 B ></pcre></match></read>
    <write><data>8 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?45 B ></pcre></match></read>
    <write><data>17 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?46 B ></pcre></match></read>
    <write><data>16 19\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?46 B ></pcre></match></read>
    <write><data>11 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?47 B ></pcre></match></read>
    <write><data>pass\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?48 B ></pcre></match></read>
    <write><data>16 6\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?49 B ></pcre></match></read>
    <write><data>0 14\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?50 B ></pcre></match></read>
    <write><data>5 9\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?51 B ></pcre></match></read>
    <write><data>17 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?52 B ></pcre></match></read>
    <write><data>18 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?53 B ></pcre></match></read>
    <write><data>8 2\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?54 B ></pcre></match></read>
    <write><data>10 9\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?55 B ></pcre></match></read>
    <write><data>11 9\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?56 B ></pcre></match></read>
    <write><data>17 0\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?56 B ></pcre></match></read>
    <write><data>11 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?56 B ></pcre></match></read>
    <write><data>1 13\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?57 B ></pcre></match></read>
    <write><data>19 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?57 B ></pcre></match></read>
    <write><data>16 0\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?57 B ></pcre></match></read>
    <write><data>16 19\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?57 B ></pcre></match></read>
    <write><data>7 6\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?57 B ></pcre></match></read>
    <write><data>7 10\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?58 B ></pcre></match></read>
    <write><data>1 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?59 B ></pcre></match></read>
    <write><data>14 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?59 B ></pcre></match></read>
    <write><data>10 16\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?60 B ></pcre></match></read>
    <write><data>1 8\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?61 B ></pcre></match></read>
    <write><data>7 12\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?62 B ></pcre></match></read>
    <write><data>14 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?63 B ></pcre></match></read>
    <write><data>13 5\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?63 B ></pcre></match></read>
    <write><data>3 6\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?64 B ></pcre></match></read>
    <write><data>17 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?65 B ></pcre></match></read>
    <write><data>19 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?65 B ></pcre></match></read>
    <write><data>10 0\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?66 B ></pcre></match></read>
    <write><data>10 4\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?66 B ></pcre></match></read>
    <write><data>11 19\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?66 B ></pcre></match></read>
    <write><data>15 9\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?67 B ></pcre></match></read>
    <write><data>4 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?67 B ></pcre></match></read>
    <write><data>pass\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?68 B ></pcre></match></read>
    <write><data>13 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?69 B ></pcre></match></read>
    <write><data>19 6\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?69 B ></pcre></match></read>
    <write><data>5 11\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?70 B ></pcre></match></read>
    <write><data>6 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?70 B ></pcre></match></read>
    <write><data>14 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?70 B ></pcre></match></read>
    <write><data>1 13\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?70 B ></pcre></match></read>
    <write><data>6 17\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?71 B ></pcre></match></read>
    <write><data>11 6\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?72 B ></pcre></match></read>
    <write><data>11 14\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?73 B ></pcre></match></read>
    <write><data>1 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?73 B ></pcre></match></read>
    <write><data>17 3\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?73 B ></pcre></match></read>
    <write><data>1 12\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?74 B ></pcre></match></read>
    <write><data>6 16\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?75 B ></pcre></match></read>
    <write><data>9 8\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?75 B ></pcre></match></read>
    <write><data>4 18\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?76 B ></pcre></match></read>
    <write><data>3 5\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?76 B ></pcre></match></read>
    <write><data>7 19\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?76 B ></pcre></match></read>
    <write><data>2 17\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?77 B ></pcre></match></read>
    <write><data>5 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?78 B ></pcre></match></read>
    <write><data>12 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?79 B ></pcre></match></read>
    <write><data>9 9\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?79 B ></pcre></match></read>
    <write><data>6 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?79 B ></pcre></match></read>
    <write><data>10 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?80 B ></pcre></match></read>
    <write><data>4 4\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?81 B ></pcre></match></read>
    <write><data>9 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?81 B ></pcre></match></read>
    <write><data>19 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?81 B ></pcre></match></read>
    <write><data>12 1\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?82 B ></pcre></match></read>
    <write><data>17 9\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?82 B ></pcre></match></read>
    <write><data>16 17\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?83 B ></pcre></match></read>
    <write><data>9 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?83 B ></pcre></match></read>
    <write><data>3 4\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?83 B ></pcre></match></read>
    <write><data>8 13\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?84 B ></pcre></match></read>
    <write><data>13 5\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?84 B ></pcre></match></read>
    <write><data>0 7\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?85 B ></pcre></match></read>
    <write><data>14 15\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?86 B ></pcre></match></read>
    <write><data>2 14\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?87 B ></pcre></match></read>
    <write><data>16 13\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?88 B ></pcre></match></read>
    <write><data>18 12\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?89 B ></pcre></match></read>
    <write><data>0 14\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?89 B ></pcre></match></read>
    <write><data>4 3\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?89 B ></pcre></match></read>
    <write><data>11 10\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?89 B ></pcre></match></read>
    <write><data>8 8\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?89 B ></pcre></match></read>
    <write><data>5 13\x0a</data></write>
    <read><delim>\x3e</delim><match><pcre>.*?90 B ></pcre></match></read>
    <write><data>10 5\x0a</data></write>
    <read><delim>User</delim><match><pcre>.*?Game Over Stones Exhausted
You are a Winner, User</pcre></match></read>
</replay>
</pov>


/*
 * TLS PRF P_SHA384
 * Copyright (c) 2011-2019, Jouni Malinen <j@w1.fi>
 *
 * This software may be distributed under the terms of the BSD license.
 * See README for more details.
 */

#include "utils/includes.h"

#include "utils/common.h"
#include "sha384.h"

/**
 * tls_prf_sha384 - Pseudo-Random Function for TLS v1.2 (P_SHA384, RFC 5246)
 * @secret: Key for PRF
 * @secret_len: Length of the key in bytes
 * @label: A unique label for each purpose of the PRF
 * @seed: Seed value to bind into the key
 * @seed_len: Length of the seed
 * @out: Buffer for the generated pseudo-random key
 * @outlen: Number of bytes of key to generate
 * Returns: 0 on success, -1 on failure.
 *
 * This function is used to derive new, cryptographically separate keys from a
 * given key in TLS. This PRF is defined in RFC 5246, Chapter 5.
 */
int tls_prf_sha384(const u8 *secret, size_t secret_len, const char *label,
		   const u8 *seed, size_t seed_len, u8 *out, size_t outlen)
{
	size_t clen;
	u8 A[SHA384_MAC_LEN];
	u8 P[SHA384_MAC_LEN];
	size_t pos;
	const unsigned char *addr[3];
	size_t len[3];

	addr[0] = A;
	len[0] = SHA384_MAC_LEN;
	addr[1] = (unsigned char *) label;
	len[1] = os_strlen(label);
	addr[2] = seed;
	len[2] = seed_len;

	/*
	 * RFC 5246, Chapter 5
	 * A(0) = seed, A(i) = HMAC(secret, A(i-1))
	 * P_hash = HMAC(secret, A(1) + seed) + HMAC(secret, A(2) + seed) + ..
	 * PRF(secret, label, seed) = P_SHA384(secret, label + seed)
	 */

	if (hmac_sha384_vector(secret, secret_len, 2, &addr[1], &len[1], A) < 0)
		return -1;

	pos = 0;
	while (pos < outlen) {
		if (hmac_sha384_vector(secret, secret_len, 3, addr, len, P) <
		    0 ||
		    hmac_sha384(secret, secret_len, A, SHA384_MAC_LEN, A) < 0)
			return -1;

		clen = outlen - pos;
		if (clen > SHA384_MAC_LEN)
			clen = SHA384_MAC_LEN;
		os_memcpy(out + pos, P, clen);
		pos += clen;
	}

	return 0;
}


/*
  Title:
    Welcome!

  Description:
    Your start-up's BA has told marketing that your website has a large audience in Scandinavia and surrounding countries.
    Marketing thinks it would be great to welcome visitors to the site in their own language.
    Luckily you already use an API that detects the user's location, so this is an easy win.

    The Task
      Think of a way to store the languages as a database (eg an object).
      The languages are listed below so you can copy and paste!
      Write a 'welcome' function that takes a parameter 'language' (always a string),
      and returns a greeting - if you have it in your database.
      It should default to English if the language is not in the database, or in the event of an invalid input.

    The Database
      english: 'Welcome',
      czech: 'Vitejte',
      danish: 'Velkomst',
      dutch: 'Welkom',
      estonian: 'Tere tulemast',
      finnish: 'Tervetuloa',
      flemish: 'Welgekomen',
      french: 'Bienvenue',
      german: 'Willkommen',
      irish: 'Failte',
      italian: 'Benvenuto',
      latvian: 'Gaidits',
      lithuanian: 'Laukiamas',
      polish: 'Witamy',
      spanish: 'Bienvenido',
      swedish: 'Valkommen',
      welsh: 'Croeso'

    Possible invalid inputs include
      IP_ADDRESS_INVALID - not a valid ipv4 or ipv6 ip address
      IP_ADDRESS_NOT_FOUND - ip address not in the database
      IP_ADDRESS_REQUIRED - no ip address was supplied

  Kata Link:
    https://www.codewars.com/kata/welcome

  Discuss Link:
    https://www.codewars.com/kata/welcome/discuss

  Solutions Link:
    https://www.codewars.com/kata/welcome/solutions
*/

// Long Solution
const database = {
  english: 'Welcome',
  czech: 'Vitejte',
  danish: 'Velkomst',
  dutch: 'Welkom',
  estonian: 'Tere tulemast',
  finnish: 'Tervetuloa',
  flemish: 'Welgekomen',
  french: 'Bienvenue',
  german: 'Willkommen',
  irish: 'Failte',
  italian: 'Benvenuto',
  latvian: 'Gaidits',
  lithuanian: 'Laukiamas',
  polish: 'Witamy',
  spanish: 'Bienvenido',
  swedish: 'Valkommen',
  welsh: 'Croeso',
}

const greet = language => database[language] || database.english

// Function Export
module.exports = greet


Word Source

Learn more about the origins of words with the Word Source skill.

Currently looking up words via the Online Etymology Dictionary (http://www.etymonline.com/) but look for more sources to be added soon.

The list of words to look up is currently at 7,949. Look for the number of words to be increased soon.

Alexa, ask Word Source about the word car

Alexa, ask Word Source about the origin of the word colony

Alexa, ask Word Source what is the etymology of plant

Simply ask Alexa about any word to learn about its origins.


#include "pugixml.hpp"

#include <iostream>

const char* node_types[] =
{
    "null", "document", "element", "pcdata", "cdata", "comment", "pi", "declaration"
};

// tag::impl[]
struct simple_walker: pugi::xml_tree_walker
{
    virtual bool for_each(pugi::xml_node& node)
    {
        for (int i = 0; i < depth(); ++i) std::cout << "  "; // indentation

        std::cout << node_types[node.type()] << ": name='" << node.name() << "', value='" << node.value() << "'\n";

        return true; // continue traversal
    }
};
// end::impl[]

int main()
{
    pugi::xml_document doc;
    if (!doc.load_file("tree.xml")) return -1;

    // tag::traverse[]
    simple_walker walker;
    doc.traverse(walker);
    // end::traverse[]
}

// vim:et


/*!
 * Ext JS Library 3.4.0
 * Copyright(c) 2006-2011 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */
.x-combo-list {
    border:2px solid #232732;
    background-color:#555566;
    font:normal 15px tahoma, arial, helvetica, sans-serif;
}

.x-combo-list-inner {
    background-color:#414551;
}

.x-combo-list-hd {
    font:bold 14px tahoma, arial, helvetica, sans-serif;
    color:#fff;
    background-image: url(../images/default/layout/panel-title-light-bg.gif);
    border-bottom-color:#98c0f4;
}

.x-resizable-pinned .x-combo-list-inner {
    border-bottom-color:#98c0f4;
}

.x-combo-list-item {
    border-color:#556;
}

.x-combo-list .x-combo-selected {
	border-color:#e5872c !important;
    background-color:#e5872c;
}

.x-combo-list .x-toolbar {
    border-top-color:#98c0f4;
}

.x-combo-list-small {
    font:normal 14px tahoma, arial, helvetica, sans-serif;
}


import { Server, Model, Serializer } from "miragejs";

describe("External | Shared | Serializers | Base | Assorted Collections", function () {
  let server;

  beforeEach(function () {
    server = new Server({
      models: {
        wordSmith: Model,
        greatPhoto: Model,
      },

      serializers: {
        application: Serializer,
        greatPhoto: Serializer.extend({
          attrs: ["id", "title"],
        }),
      },
    });
  });

  afterEach(function () {
    server.shutdown();
  });

  test(`an array of assorted collections can be serialized`, () => {
    let wordSmiths = [
      { id: "1", name: "Link" },
      { id: "2", name: "Zelda" },
      { id: "3", name: "Epona" },
    ];
    let greatPhotos = [
      { id: "1", title: "Amazing", location: "Hyrule" },
      { id: "2", title: "greatPhoto", location: "Goron City" },
    ];

    server.db.loadData({ wordSmiths, greatPhotos });

    let result = server.serializerOrRegistry.serialize([
      server.schema.wordSmiths.all(),
      server.schema.greatPhotos.all(),
    ]);

    expect(result).toEqual({
      wordSmiths: wordSmiths,
      greatPhotos: greatPhotos.map((attrs) => {
        delete attrs.location;
        return attrs;
      }),
    });
  });
});


/*
 *
 * Copyright 2017 gRPC authors.
 *
 * 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.
 *
 */

#ifndef GRPC_LOAD_REPORTING_H
#define GRPC_LOAD_REPORTING_H

#include <grpc/impl/codegen/port_platform.h>

#ifdef __cplusplus
extern "C" {
#endif

/** Metadata key for the gRPC LB load balancer token.
 *
 * The value corresponding to this key is an opaque token that is given to the
 * frontend as part of each pick; the frontend sends this token to the backend
 * in each request it sends when using that pick. The token is used by the
 * backend to verify the request and to allow the backend to report load to the
 * gRPC LB system. */
#define GRPC_LB_TOKEN_MD_KEY "lb-token"

/** Metadata key for gRPC LB cost reporting.
 *
 * The value corresponding to this key is an opaque binary blob reported by the
 * backend as part of its trailing metadata containing cost information for the
 * call. */
#define GRPC_LB_COST_MD_KEY "lb-cost-bin"

#ifdef __cplusplus
}
#endif

#endif /* GRPC_LOAD_REPORTING_H */


//
//  SwiftSpec.swift
//  Archimedes
//
//  Created by Justin Spahr-Summers on 2014-10-02.
//  Copyright (c) 2014 GitHub. All rights reserved.
//

import Foundation
import Nimble
import Quick

// Without this, the Swift stdlib won't be linked into the test target (even if
// “Embedded Content Contains Swift Code” is enabled).
class SwiftSpec: QuickSpec {
	override func spec() {
		expect(true).to(beTruthy())
	}
}


//
//  MetalInterp.hpp
//  MNN
//
//  Created by MNN on 2019/01/30.
//  Copyright © 2018, Alibaba Group Holding Limited
//

#ifndef MetalInterp_hpp
#define MetalInterp_hpp

#include "core/Execution.hpp"
#include "MetalDefine.h"

#if MNN_METAL_ENABLED
namespace MNN {

class MetalInterp : public Execution {
public:
    MetalInterp(Backend *backend, float widthScale, float heightScale, int32_t outputWidth, int32_t outputHeight,
                int32_t reiszeType, bool alignCorner);
    virtual ~MetalInterp() = default;
    virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override;

private:
    float mWidthScale;
    float mHeightScale;
    int32_t mOutputWidth;
    int32_t mOutputHeight;
    int32_t mReiszeType;
    bool mAlignCorner;
};

} // namespace MNN
#endif /* MNN_METAL_ENABLED */
#endif /* MetalInterp_hpp */