text:
#include "unicode/utypes.h"

#if !UCONFIG_NO_FORMATTING

#include "unicode/fmtable.h"
#include "unicode/ustring.h"
#include "unicode/measure.h"
#include "unicode/curramt.h"
#include "cmemory.h"
#include "cstring.h"
#include "decNumber.h"
#include "decnumstr.h"
#include "digitlst.h"

// *****************************************************************************
// class Formattable
// *****************************************************************************

U_NAMESPACE_BEGIN

UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Formattable)

//-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.

// NOTE: As of 3.0, there are limitations to the UObject API.  It does
// not (yet) support cloning, operator=, nor operator==.  RTTI is also
// restricted in that subtype testing is not (yet) implemented.  To
// work around this, I implement some simple inlines here.  Later
// these can be modified or removed.  [alan]

// NOTE: These inlines assume that all fObjects are in fact instances
// of the Measure class, which is true as of 3.0.  [alan]

// Return TRUE if *a == *b.
static inline UBool objectEquals(const UObject* a, const UObject* b) {
    // LATER: return *a == *b;
    return *((const Measure*) a) == *((const Measure*) b);
}

// Return a clone of *a.
static inline UObject* objectClone(const UObject* a) {
    // LATER: return a->clone();
    return ((const Measure*) a)->clone();
}

// Return TRUE if *a is an instance of Measure.
static inline UBool instanceOfMeasure(const UObject* a) {
    // LATER: return a->instanceof(Measure::getStaticClassID());
    return a->getDynamicClassID() ==
        CurrencyAmount::getStaticClassID();
}

/**
 * Creates a new Formattable array and copies the values from the specified
 * original.
 * @param array the original array
 * @param count the original array count
 * @return the new Formattable array.
 */
static Formattable* createArrayCopy(const Formattable* array, int32_t count) {
    Formattable *result = new Formattable[count];
    if (result != NULL) {
        for (int32_t i=0; i<count; ++i)
            result[i] = array[i]; // Don't memcpy!
    }
    return result;
}

//-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.

/**
 * Set 'ec' to 'err' only if 'ec' is not already set to a failing UErrorCode.
 */
static void setError(UErrorCode& ec, UErrorCode err) {
    if (U_SUCCESS(ec)) {
        ec = err;
    }
}

//
//  Common initialization code, shared by constructors.
//  Put everything into a known state.
//
void  Formattable::init() {
    fValue.fInt64 = 0;
    fType = kLong;
    fDecimalStr = NULL;
    fDecimalNum = NULL;
    fBogus.setToBogus();
}

// -------------------------------------
// default constructor.
// Creates a formattable object with a long value 0.

Formattable::Formattable() {
    init();
}

// -------------------------------------
// Creates a formattable object with a Date instance.

Formattable::Formattable(UDate date, ISDATE /*isDate*/)
{
    init();
    fType = kDate;
    fValue.fDate = date;
}

// -------------------------------------
// Creates a formattable object with a double value.

Formattable::Formattable(double value)
{
    init();
    fType = kDouble;
    fValue.fDouble = value;
}

// -------------------------------------
// Creates a formattable object with an int32_t value.

Formattable::Formattable(int32_t value)
{
    init();
    fValue.fInt64 = value;
}

// -------------------------------------
// Creates a formattable object with an int64_t value.

Formattable::Formattable(int64_t value)
{
    init();
    fType = kInt64;
    fValue.fInt64 = value;
}

// -------------------------------------
// Creates a formattable object with a decimal number value from a string.

Formattable::Formattable(const StringPiece &number, UErrorCode &status) {
    init();
    setDecimalNumber(number, status);
}

// -------------------------------------
// Creates a formattable object with a UnicodeString instance.

Formattable::Formattable(const UnicodeString& stringToCopy)
{
    init();
    fType = kString;
    fValue.fString = new UnicodeString(stringToCopy);
}

// -------------------------------------
// Creates a formattable object with a UnicodeString* value.
// (adopting symantics)

Formattable::Formattable(UnicodeString* stringToAdopt)
{
    init();
    fType = kString;
    fValue.fString = stringToAdopt;
}

Formattable::Formattable(UObject* objectToAdopt)
{
    init();
    fType = kObject;
    fValue.fObject = objectToAdopt;
}

// -------------------------------------

Formattable::Formattable(const Formattable* arrayToCopy, int32_t count)
    :   UObject(), fType(kArray)
{
    init();
    fType = kArray;
    fValue.fArrayAndCount.fArray = createArrayCopy(arrayToCopy, count);
    fValue.fArrayAndCount.fCount = count;
}

// -------------------------------------
// copy constructor

Formattable::Formattable(const Formattable &source)
     :  UObject(*this)
{
    init();
    *this = source;
}

// -------------------------------------
// assignment operator

Formattable&
Formattable::operator=(const Formattable& source)
{
    if (this != &source)
    {
        // Disposes the current formattable value/setting.
        dispose();

        // Sets the correct data type for this value.
        fType = source.fType;
        switch (fType)
        {
        case kArray:
            // Sets each element in the array one by one and records the array count.
            fValue.fArrayAndCount.fCount = source.fValue.fArrayAndCount.fCount;
            fValue.fArrayAndCount.fArray = createArrayCopy(source.fValue.fArrayAndCount.fArray,
                                                           source.fValue.fArrayAndCount.fCount);
            break;
        case kString:
            // Sets the string value.
            fValue.fString = new UnicodeString(*source.fValue.fString);
            break;
        case kDouble:
            // Sets the double value.
            fValue.fDouble = source.fValue.fDouble;
            break;
        case kLong:
        case kInt64:
            // Sets the long value.
            fValue.fInt64 = source.fValue.fInt64;
            break;
        case kDate:
            // Sets the Date value.
            fValue.fDate = source.fValue.fDate;
            break;
        case kObject:
            fValue.fObject = objectClone(source.fValue.fObject);
            break;
        }

        UErrorCode status = U_ZERO_ERROR;
        if (source.fDecimalNum != NULL) {
            fDecimalNum = new DigitList(*source.fDecimalNum);
        }
        if (source.fDecimalStr != NULL) {
            fDecimalStr = new DecimalNumberString(*source.fDecimalStr, status);
            if (U_FAILURE(status)) {
                delete fDecimalStr;
                fDecimalStr = NULL;
            }
        }
    }
    return *this;
}

// -------------------------------------

UBool
Formattable::operator==(const Formattable& that) const
{
    int32_t i;

    if (this == &that) return TRUE;

    // Returns FALSE if the data types are different.
    if (fType != that.fType) return FALSE;

    // Compares the actual data values.
    UBool equal = TRUE;
    switch (fType) {
    case kDate:
        equal = (fValue.fDate == that.fValue.fDate);
        break;
    case kDouble:
        equal = (fValue.fDouble == that.fValue.fDouble);
        break;
    case kLong:
    case kInt64:
        equal = (fValue.fInt64 == that.fValue.fInt64);
        break;
    case kString:
        equal = (*(fValue.fString) == *(that.fValue.fString));
        break;
    case kArray:
        if (fValue.fArrayAndCount.fCount != that.fValue.fArrayAndCount.fCount) {
            equal = FALSE;
            break;
        }
        // Checks each element for equality.
        for (i=0; i<fValue.fArrayAndCount.fCount; ++i) {
            if (fValue.fArrayAndCount.fArray[i] != that.fValue.fArrayAndCount.fArray[i]) {
                equal = FALSE;
                break;
            }
        }
        break;
    case kObject:
        if (fValue.fObject == NULL || that.fValue.fObject == NULL) {
            equal = FALSE;
        } else {
            equal = objectEquals(fValue.fObject, that.fValue.fObject);
        }
        break;
    }

    // TODO:  compare digit lists if numeric.
    return equal;
}

// -------------------------------------

Formattable::~Formattable()
{
    dispose();
}

// -------------------------------------

void Formattable::dispose()
{
    // Deletes the data value if necessary.
    switch (fType) {
    case kString:
        delete fValue.fString;
        break;
    case kArray:
        delete[] fValue.fArrayAndCount.fArray;
        break;
    case kObject:
        delete fValue.fObject;
        break;
    default:
        break;
    }

    fType = kLong;
    fValue.fInt64 = 0;
    delete fDecimalStr;
    fDecimalStr = NULL;
    delete fDecimalNum;
    fDecimalNum = NULL;
}

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

// -------------------------------------
// Gets the data type of this Formattable object.
Formattable::Type
Formattable::getType() const
{
    return fType;
}

UBool
Formattable::isNumeric() const {
    switch (fType) {
    case kDouble:
    case kLong:
    case kInt64:
        return TRUE;
    default:
        return FALSE;
    }
}

// -------------------------------------
int32_t
//Formattable::getLong(UErrorCode* status) const
Formattable::getLong(UErrorCode& status) const
{
    if (U_FAILURE(status)) {
        return 0;
    }

    switch (fType) {
    case Formattable::kLong:
        return (int32_t)fValue.fInt64;
    case Formattable::kInt64:
        if (fValue.fInt64 > INT32_MAX) {
            status = U_INVALID_FORMAT_ERROR;
            return INT32_MAX;
        } else if (fValue.fInt64 < INT32_MIN) {
            status = U_INVALID_FORMAT_ERROR;
            return INT32_MIN;
        } else {
            return (int32_t)fValue.fInt64;
        }
    case Formattable::kDouble:
        if (fValue.fDouble > INT32_MAX) {
            status = U_INVALID_FORMAT_ERROR;
            return INT32_MAX;
        } else if (fValue.fDouble < INT32_MIN) {
            status = U_INVALID_FORMAT_ERROR;
            return INT32_MIN;
        } else {
            return (int32_t)fValue.fDouble; // loses fraction
        }
    case Formattable::kObject:
        if (fValue.fObject == NULL) {
            status = U_MEMORY_ALLOCATION_ERROR;
            return 0;
        }
        // TODO Later replace this with instanceof call
        if (instanceOfMeasure(fValue.fObject)) {
            return ((const Measure*) fValue.fObject)->
                getNumber().getLong(status);
        }
    default:
        status = U_INVALID_FORMAT_ERROR;
        return 0;
    }
}

// -------------------------------------
int64_t
Formattable::getInt64(UErrorCode& status) const
{
    if (U_FAILURE(status)) {
        return 0;
    }

    switch (fType) {
    case Formattable::kLong:
    case Formattable::kInt64:
        return fValue.fInt64;
    case Formattable::kDouble:
        if (fValue.fDouble > U_INT64_MAX) {
            status = U_INVALID_FORMAT_ERROR;
            return U_INT64_MAX;
        } else if (fValue.fDouble < U_INT64_MIN) {
            status = U_INVALID_FORMAT_ERROR;
            return U_INT64_MIN;
        } else {
            return (int64_t)fValue.fDouble;
        }
    case Formattable::kObject:
        if (fValue.fObject == NULL) {
            status = U_MEMORY_ALLOCATION_ERROR;
            return 0;
        }
        // TODO Later replace this with instanceof call
        if (instanceOfMeasure(fValue.fObject)) {
            return ((const Measure*) fValue.fObject)->
                getNumber().getInt64(status);
        }
    default:
        status = U_INVALID_FORMAT_ERROR;
        return 0;
    }
}

// -------------------------------------
double
Formattable::getDouble(UErrorCode& status) const
{
    if (U_FAILURE(status)) {
        return 0;
    }

    switch (fType) {
    case Formattable::kLong:
    case Formattable::kInt64: // loses precision
        return (double)fValue.fInt64;
    case Formattable::kDouble:
        return fValue.fDouble;
    case Formattable::kObject:
        if (fValue.fObject == NULL) {
            status = U_MEMORY_ALLOCATION_ERROR;
            return 0;
        }
        // TODO Later replace this with instanceof call
        if (instanceOfMeasure(fValue.fObject)) {
            return ((const Measure*) fValue.fObject)->
                getNumber().getDouble(status);
        }
    default:
        status = U_INVALID_FORMAT_ERROR;
        return 0;
    }
}

const UObject*
Formattable::getObject() const {
    return (fType == kObject) ? fValue.fObject : NULL;
}

// -------------------------------------
// Sets the value to a double value d.

void
Formattable::setDouble(double d)
{
    dispose();
    fType = kDouble;
    fValue.fDouble = d;
}

// -------------------------------------
// Sets the value to a long value l.

void
Formattable::setLong(int32_t l)
{
    dispose();
    fType = kLong;
    fValue.fInt64 = l;
}

// -------------------------------------
// Sets the value to an int64 value ll.

void
Formattable::setInt64(int64_t ll)
{
    dispose();
    fType = kInt64;
    fValue.fInt64 = ll;
}

// -------------------------------------
// Sets the value to a Date instance d.

void
Formattable::setDate(UDate d)
{
    dispose();
    fType = kDate;
    fValue.fDate = d;
}

// -------------------------------------
// Sets the value to a string value stringToCopy.

void
Formattable::setString(const UnicodeString& stringToCopy)
{
    dispose();
    fType = kString;
    fValue.fString = new UnicodeString(stringToCopy);
}

// -------------------------------------
// Sets the value to an array of Formattable objects.

void
Formattable::setArray(const Formattable* array, int32_t count)
{
    dispose();
    fType = kArray;
    fValue.fArrayAndCount.fArray = createArrayCopy(array, count);
    fValue.fArrayAndCount.fCount = count;
}

// -------------------------------------
// Adopts the stringToAdopt value.

void
Formattable::adoptString(UnicodeString* stringToAdopt)
{
    dispose();
    fType = kString;
    fValue.fString = stringToAdopt;
}

// -------------------------------------
// Adopts the array value and its count.

void
Formattable::adoptArray(Formattable* array, int32_t count)
{
    dispose();
    fType = kArray;
    fValue.fArrayAndCount.fArray = array;
    fValue.fArrayAndCount.fCount = count;
}

void
Formattable::adoptObject(UObject* objectToAdopt) {
    dispose();
    fType = kObject;
    fValue.fObject = objectToAdopt;
}

// -------------------------------------
UnicodeString&
Formattable::getString(UnicodeString& result, UErrorCode& status) const
{
    if (fType != kString) {
        setError(status, U_INVALID_FORMAT_ERROR);
        result.setToBogus();
    } else {
        if (fValue.fString == NULL) {
            setError(status, U_MEMORY_ALLOCATION_ERROR);
        } else {
            result = *fValue.fString;
        }
    }
    return result;
}

// -------------------------------------
const UnicodeString&
Formattable::getString(UErrorCode& status) const
{
    if (fType != kString) {
        setError(status, U_INVALID_FORMAT_ERROR);
        return *getBogus();
    }
    if (fValue.fString == NULL) {
        setError(status, U_MEMORY_ALLOCATION_ERROR);
        return *getBogus();
    }
    return *fValue.fString;
}

// -------------------------------------
UnicodeString&
Formattable::getString(UErrorCode& status)
{
    if (fType != kString) {
        setError(status, U_INVALID_FORMAT_ERROR);
        return *getBogus();
    }
    if (fValue.fString == NULL) {
    	setError(status, U_MEMORY_ALLOCATION_ERROR);
    	return *getBogus();
    }
    return *fValue.fString;
}

// -------------------------------------
const Formattable*
Formattable::getArray(int32_t& count, UErrorCode& status) const
{
    if (fType != kArray) {
        setError(status, U_INVALID_FORMAT_ERROR);
        count = 0;
        return NULL;
    }
    count = fValue.fArrayAndCount.fCount;
    return fValue.fArrayAndCount.fArray;
}

// -------------------------------------
// Gets the bogus string, ensures mondo bogosity.

UnicodeString*
Formattable::getBogus() const
{
    return (UnicodeString*)&fBogus; /* cast away const :-( */
}

// --------------------------------------
StringPiece Formattable::getDecimalNumber(UErrorCode &status) {
    if (U_FAILURE(status)) {
        return "";
    }
    if (fDecimalStr != NULL) {
        return *fDecimalStr;
    }

    if (fDecimalNum == NULL) {
        // No decimal number for the formattable yet.  Which means the value was
        // set directly by the user as an int, int64 or double.  If the value came
        // from parsing, or from the user setting a decimal number, fDecimalNum
        // would already be set.
        //
        fDecimalNum = new DigitList;
        if (fDecimalNum == NULL) {
            status = U_MEMORY_ALLOCATION_ERROR;
            return "";
        }

        switch (fType) {
        case kDouble:
            fDecimalNum->set(this->getDouble());
            break;
        case kLong:
            fDecimalNum->set(this->getLong());
            break;
        case kInt64:
            fDecimalNum->set(this->getInt64());
            break;
        default:
            // The formattable's value is not a numeric type.
            status = U_INVALID_STATE_ERROR;
            return "";
        }
    }

    fDecimalStr = new DecimalNumberString;
    if (fDecimalStr == NULL) {
        status = U_MEMORY_ALLOCATION_ERROR;
        return "";
    }
    fDecimalNum->getDecimal(*fDecimalStr, status);

    return *fDecimalStr;
}

// ---------------------------------------
void
Formattable::adoptDigitList(DigitList *dl) {
    dispose();

    fDecimalNum = dl;

    // Set the value into the Union of simple type values.
    // Cannot use the set() functions because they would delete the fDecimalNum value,

    if (fDecimalNum->fitsIntoLong(FALSE)) {
        fType = kLong;
        fValue.fInt64 = fDecimalNum->getLong();
    } else if (fDecimalNum->fitsIntoInt64(FALSE)) {
        fType = kInt64;
        fValue.fInt64 = fDecimalNum->getInt64();
    } else {
        fType = kDouble;
        fValue.fDouble = fDecimalNum->getDouble();
    }
}

// ---------------------------------------
void
Formattable::setDecimalNumber(const StringPiece &numberString, UErrorCode &status) {
    if (U_FAILURE(status)) {
        return;
    }
    dispose();

    // Copy the input string and nul-terminate it.
    //    The decNumber library requires nul-terminated input.  StringPiece input
    //    is not guaranteed nul-terminated.  Too bad.
    //    DecimalNumberStrings automatically adds the nul.
    DecimalNumberString  s(numberString, status);
    if (U_FAILURE(status)) {
        return;
    }

    DigitList *dnum = new DigitList();
    if (dnum == NULL) {
        status = U_MEMORY_ALLOCATION_ERROR;
        return;
    }
    dnum->set(s, status);
    if (U_FAILURE(status)) {
        delete dnum;
        return;   // String didn't contain a decimal number.
    }
    adoptDigitList(dnum);

    // Note that we do not hang on to the caller's input string.
    // If we are asked for the string, we will regenerate one from fDecimalNum.
}

#if 0
//----------------------------------------------------
// console I/O
//----------------------------------------------------
#ifdef _DEBUG

#if U_IOSTREAM_SOURCE >= 199711
#include <iostream>
using namespace std;
#elif U_IOSTREAM_SOURCE >= 198506
#include <iostream.h>
#endif

#include "unicode/datefmt.h"
#include "unistrm.h"

class FormattableStreamer /* not : public UObject because all methods are static */ {
public:
    static void streamOut(ostream& stream, const Formattable& obj);

private:
    FormattableStreamer() {} // private - forbid instantiation
};

// This is for debugging purposes only.  This will send a displayable
// form of the Formattable object to the output stream.

void
FormattableStreamer::streamOut(ostream& stream, const Formattable& obj)
{
    static DateFormat *defDateFormat = 0;

    UnicodeString buffer;
    switch(obj.getType()) {
        case Formattable::kDate :
            // Creates a DateFormat instance for formatting the
            // Date instance.
            if (defDateFormat == 0) {
                defDateFormat = DateFormat::createInstance();
            }
            defDateFormat->format(obj.getDate(), buffer);
            stream << buffer;
            break;
        case Formattable::kDouble :
            // Output the double as is.
            stream << obj.getDouble() << 'D';
            break;
        case Formattable::kLong :
            // Output the double as is.
            stream << obj.getLong() << 'L';
            break;
        case Formattable::kString:
            // Output the double as is.  Please see UnicodeString console
            // I/O routine for more details.
            stream << '"' << obj.getString(buffer) << '"';
            break;
        case Formattable::kArray:
            int32_t i, count;
            const Formattable* array;
            array = obj.getArray(count);
            stream << '[';
            // Recursively calling the console I/O routine for each element in the array.
            for (i=0; i<count; ++i) {
                FormattableStreamer::streamOut(stream, array[i]);
                stream << ( (i==(count-1)) ? "" : ", " );
            }
            stream << ']';
            break;
        default:
            // Not a recognizable Formattable object.
            stream << "INVALID_Formattable";
    }
    stream.flush();
}
#endif

#endif

U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_FORMATTING */

//eof


text:
package com.alibaba.jstorm.task.backpressure;

import backtype.storm.generated.*;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;

import com.alibaba.jstorm.client.ConfigExtension;
import com.alibaba.jstorm.cluster.*;
import com.alibaba.jstorm.task.acker.Acker;
import com.alibaba.jstorm.task.master.TopoMasterCtrlEvent;
import com.alibaba.jstorm.task.master.TopoMasterCtrlEvent.EventType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.Map.Entry;

/**
 * Coordinator is responsible for the request from trigger and controller.
 * - Event from trigger:
 *   Find relative controllers (source spouts), and decide if it is required to send out the request.
 * - Event from controller:
 *   If backpressure stop event, send stop request to all target triggers.
 *
 * @author Basti Li
 */
public class BackpressureCoordinator extends Backpressure {
    private static final Logger LOG = LoggerFactory.getLogger(BackpressureCoordinator.class);

    private static final int adjustedTime = 5;

    private TopologyContext context;
    private StormTopology topology;
    private OutputCollector output;

    private int topologyMasterId;
    private Map<Integer, String> taskIdToComponentId;
    private Map<String, SpoutSpec> spouts;
    private Map<String, Bolt> bolts;

    // Map<source componentId, Map<ComponentId, backpressure info>>
    private Map<String, SourceBackpressureInfo> SourceTobackpressureInfo;

    private Integer period;

    private StormClusterState zkCluster;
    private static final String BACKPRESSURE_TAG = "Backpressure has been ";

    public BackpressureCoordinator(OutputCollector output, TopologyContext topologyContext, Integer taskId) {
        super(topologyContext.getStormConf());
        this.context = topologyContext;
        this.topology = topologyContext.getRawTopology();
        this.spouts = new HashMap<String, SpoutSpec>();
        if (this.topology.get_spouts() != null) {
            this.spouts.putAll(this.topology.get_spouts());
        }
        this.bolts = new HashMap<String, Bolt>();
        if (this.topology.get_bolts() != null) {
            this.bolts.putAll(this.topology.get_bolts());
        }
        this.taskIdToComponentId = topologyContext.getTaskToComponent();
        this.topologyMasterId = taskId;

        this.output = output;

        int checkInterval = ConfigExtension.getBackpressureCheckIntervl(context.getStormConf());
        int sampleNum = ConfigExtension.getBackpressureTriggerSampleNumber(context.getStormConf());
        this.period = checkInterval * sampleNum;

        this.zkCluster = topologyContext.getZkCluster();
        try {
            this.SourceTobackpressureInfo = zkCluster.get_backpressure_info(context.getTopologyId());
            if (this.SourceTobackpressureInfo == null) {
                this.SourceTobackpressureInfo = new HashMap<String, SourceBackpressureInfo>();
            } else {
                LOG.info("Successfully retrieve existing SourceTobackpressureInfo from zk: " + SourceTobackpressureInfo);
            }
        } catch (Exception e) {
            LOG.warn("Failed to get SourceTobackpressureInfo from zk", e);
            this.SourceTobackpressureInfo = new HashMap<String, SourceBackpressureInfo>();
        }
    }

    private Set<String> getInputSpoutsForBolt(StormTopology topology, String boltComponentId, Set<String> componentsTraversed) {
        Set<String> ret = new TreeSet<String>();

        if (componentsTraversed == null) {
            componentsTraversed = new HashSet<String>();
        }

        Bolt bolt = bolts.get(boltComponentId);
        if (bolt == null) {
            return ret;
        }

        ComponentCommon common = bolt.get_common();
        Set<GlobalStreamId> inputstreams = common.get_inputs().keySet();
        Set<String> inputComponents = new TreeSet<String>();
        for (GlobalStreamId streamId : inputstreams) {
            inputComponents.add(streamId.get_componentId());
        }

        Set<String> spoutComponentIds = new HashSet<String>(spouts.keySet());
        Set<String> boltComponentIds = new HashSet<String>(bolts.keySet());
        for (String inputComponent : inputComponents) {
            // Skip the components which has been traversed before, to avoid dead loop when there are loop bolts in topology
            if (componentsTraversed.contains(inputComponent)) {
                continue;
            } else {
                componentsTraversed.add(inputComponent);
            }

            if (spoutComponentIds.contains(inputComponent)) {
                ret.add(inputComponent);
            } else if (boltComponentIds.contains(inputComponent)) {
                Set<String> inputs = getInputSpoutsForBolt(topology, inputComponent, componentsTraversed);
                ret.addAll(inputs);
            }
        }

        return ret;
    }

    public void process(Tuple input) {
        if (isBackpressureEnable == false) {
            return;
        }

        int sourceTask = input.getSourceTask();
        String componentId = taskIdToComponentId.get(sourceTask);
        if (componentId == null) {
            LOG.warn("Receive tuple from unknown task-" + sourceTask);
            return;
        }

        if (spouts.keySet().contains(componentId)) {
            if (SourceTobackpressureInfo.get(componentId) != null) {
                handleEventFromSpout(sourceTask, input);
            }
        } else if (bolts.keySet().contains(componentId)) {
            handleEventFromBolt(sourceTask, input);
        }
    }

    public void updateBackpressureConfig(Map conf) {
        updateConfig(conf);

        if (isBackpressureEnable == false) {
            LOG.info("Disable backpressure in coordinator.");
            SourceTobackpressureInfo.clear();
        } else {
            LOG.info("Enable backpressure in coordinator.");
        }

        TopoMasterCtrlEvent updateBpConfig = new TopoMasterCtrlEvent(EventType.updateBackpressureConfig, new ArrayList<Object>());
        updateBpConfig.addEventValue(conf);
        Values values = new Values(updateBpConfig);
        Set<Integer> targetTasks = new TreeSet<Integer>(taskIdToComponentId.keySet());
        targetTasks.remove(topologyMasterId);
        targetTasks.removeAll(context.getComponentTasks(Acker.ACKER_COMPONENT_ID));
        sendBackpressureMessage(targetTasks, values, EventType.updateBackpressureConfig);

        reportBackpressureStatus();
    }

    private boolean checkSpoutsUnderBackpressure(Set<String> spouts) {
        boolean ret = false;

        if (spouts != null) {
            for (String spout : spouts) {
                SourceBackpressureInfo backpressureInfo = SourceTobackpressureInfo.get(spout);
                if (backpressureInfo != null && backpressureInfo.getTasks().size() > 0) {
                    ret = true;
                    break;
                }
            }
        }

        return ret;
    }

    private TargetBackpressureInfo getBackpressureInfoBySourceSpout(String sourceSpout, String targetComponentId, boolean created) {
        TargetBackpressureInfo ret = null;

        SourceBackpressureInfo info = SourceTobackpressureInfo.get(sourceSpout);
        if (info == null) {
            if (created) {
                info = new SourceBackpressureInfo();
                SourceTobackpressureInfo.put(sourceSpout, info);
            }
        } else {
            ret = info.getTargetTasks().get(targetComponentId);
        }

        if (ret == null && created) {
            ret = new TargetBackpressureInfo();
            info.getTargetTasks().put(targetComponentId, ret);
        }
        return ret;
    }

    private boolean checkIntervalExpired(long time) {
        boolean ret = false;
        if (time != 0) {
            if (System.currentTimeMillis() - time > period) {
                ret = true;
            }
        }
        return ret;
    }

    private void sendBackpressureMessage(Set<Integer> targetTasks, Values value, EventType backpressureType) {
        for (Integer taskId : targetTasks) {
            output.emitDirect(taskId, Common.TOPOLOGY_MASTER_CONTROL_STREAM_ID, value);
            LOG.debug("Send " + backpressureType.toString() + " request to taskId-" + taskId);
        }
    }

    private void handleEventFromSpout(int sourceTask, Tuple input) {
        TopoMasterCtrlEvent ctrlEvent = (TopoMasterCtrlEvent) input.getValueByField("ctrlEvent");
        EventType type = ctrlEvent.getEventType();

        boolean update = false;
        if (type.equals(EventType.stopBackpressure)) {
            String spoutComponentId = taskIdToComponentId.get(sourceTask);
            SourceBackpressureInfo info = SourceTobackpressureInfo.remove(spoutComponentId);
            if (info != null) {
                info.getTasks().remove(sourceTask);
                if (info.getTasks().size() == 0) {
                    for (Entry<String, TargetBackpressureInfo> entry : info.getTargetTasks().entrySet()) {
                        String componentId = entry.getKey();

                        // Make sure if all source spouts for this bolt are NOT under backpressure mode.
                        Set<String> sourceSpouts = getInputSpoutsForBolt(topology, componentId, null);
                        if (checkSpoutsUnderBackpressure(sourceSpouts) == false) {
                            Set<Integer> tasks = new TreeSet<Integer>();
                            tasks.addAll(context.getComponentTasks(componentId));
                            sendBackpressureMessage(tasks, new Values(ctrlEvent), type);
                        }
                    }
                }
                update = true;
            } else {
                LOG.error("Received event from non-recorded spout-" + sourceTask);
            }

        } else {
            LOG.warn("Received unexpected event, " + type.toString());
        }

        // If task set under backpressure has been changed, report the latest status
        if (update) {
            reportBackpressureStatus();
        }
    }

    private void handleEventFromBolt(int sourceTask, Tuple input) {
        String componentId = taskIdToComponentId.get(sourceTask);
        Set<String> inputSpouts = getInputSpoutsForBolt(topology, componentId, null);

        TopoMasterCtrlEvent ctrlEvent = (TopoMasterCtrlEvent) input.getValueByField("ctrlEvent");
        EventType type = ctrlEvent.getEventType();
        Set<Integer> notifyList = new TreeSet<Integer>();
        Values values = null;
        TargetBackpressureInfo info = null;
        boolean update = false;
        if (type.equals(EventType.startBackpressure)) {
            int flowCtrlTime = (Integer) ctrlEvent.getEventValue().get(0);
            for (String spout : inputSpouts) {
                info = getBackpressureInfoBySourceSpout(spout, componentId, true);
                SourceBackpressureInfo sourceInfo = SourceTobackpressureInfo.get(spout);
                update = info.getTasks().add(sourceTask);
                boolean add = false;
                if (System.currentTimeMillis() - sourceInfo.getLastestTimeStamp() > period) {
                    add = true;
                } else {
                    EventType lastestBpEvent = sourceInfo.getLastestBackpressureEvent();
                    if (lastestBpEvent != null && lastestBpEvent.equals(EventType.startBackpressure) == false) {
                        add = true;
                    }

                    int maxFlowCtrlTime = sourceInfo.getMaxFlowCtrlTime();
                    if ((flowCtrlTime - maxFlowCtrlTime > adjustedTime || maxFlowCtrlTime == -1) &&
                            flowCtrlTime >= 0) {
                        add = true;
                    }
                }
                info.setFlowCtrlTime(flowCtrlTime);
                info.setBackpressureStatus(type);

                if (add) {
                    info.setTimeStamp(System.currentTimeMillis());
                    // Only when the number of bolt tasks sending request is more than a configured number, coordinator will
                    // send out backpressure request to controller. It is used to avoid the problem that very few tasks might
                    // cause the over control.
                    double taskBpRatio = Double.valueOf(info.getTasks().size()) / Double.valueOf(context.getComponentTasks(componentId).size()) ;
                    if (taskBpRatio >= triggerBpRatio) {
                        Set<Integer> spoutTasks = new TreeSet<Integer>(context.getComponentTasks(spout));
                        if (spoutTasks != null) {
                            SourceTobackpressureInfo.get(spout).getTasks().addAll(spoutTasks);
                            notifyList.addAll(spoutTasks);
                        }
                    } else {
                        update = false;
                    }
                } else {
                    update = false;
                }
            }

            List<Object> value = new ArrayList<Object>();
            value.add(info.getFlowCtrlTime());
            TopoMasterCtrlEvent startBp = new TopoMasterCtrlEvent(EventType.startBackpressure, value);
            values = new Values(startBp);
        } else if (type.equals(EventType.stopBackpressure)) {
            for (String spout : inputSpouts) {
                info = getBackpressureInfoBySourceSpout(spout, componentId, false);
                SourceBackpressureInfo sourceInfo = SourceTobackpressureInfo.get(spout);
                if (info != null) {
                    Set<Integer> tasks = info.getTasks();
                    if (tasks != null) {
                        if(tasks.remove(sourceTask)) {
                            update = true;
                        }
                    }
                }

                if (sourceInfo != null && checkIntervalExpired(sourceInfo.getLastestTimeStamp())) {
                    info.setTimeStamp(System.currentTimeMillis());
                    Set<Integer> spoutTasks = new TreeSet<Integer>(context.getComponentTasks(spout));
                    if (spoutTasks != null) {
                        notifyList.addAll(spoutTasks);
                    }
                    info.setBackpressureStatus(type);
                }
            }

            // Check if all source spouts are Not under backpressure. If so, notify the bolt.
            if (checkSpoutsUnderBackpressure(inputSpouts) == false) {
                notifyList.add(sourceTask);
            }

            TopoMasterCtrlEvent stoptBp = new TopoMasterCtrlEvent(EventType.stopBackpressure, null);
            values = new Values(stoptBp);
        } else {
            LOG.warn("Received unknown event " + type.toString());
        }

        sendBackpressureMessage(notifyList, values, type);

        // If task set under backpressure has been changed, report the latest status
        if (update) {
            LOG.info("inputspouts=" + inputSpouts + " for " + componentId + "-" + sourceTask + ", eventType=" + type.toString());
            reportBackpressureStatus();
        }
    }

    private Set<Integer> getTasksUnderBackpressure() {
        Set<Integer> ret = new HashSet<Integer>();

        for (Entry<String, SourceBackpressureInfo> entry : SourceTobackpressureInfo.entrySet()) {
            SourceBackpressureInfo sourceInfo = entry.getValue();
            if (sourceInfo.getTasks().size() > 0) {
                ret.addAll(sourceInfo.getTasks());

                for (Entry<String, TargetBackpressureInfo> targetEntry: sourceInfo.getTargetTasks().entrySet()) {
                    ret.addAll(targetEntry.getValue().getTasks());
                }

            }
        }

        return ret;
    }

    private void reportBackpressureStatus() {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            Set<Integer> underTasks = getTasksUnderBackpressure();
            stringBuilder.append(BACKPRESSURE_TAG);
            if (underTasks.isEmpty()){
                stringBuilder.append("closed ");
            }else {
                stringBuilder.append("opened: ");
                stringBuilder.append(underTasks);
            }
            zkCluster.report_task_error(context.getTopologyId(), context.getThisTaskId(), stringBuilder.toString(), BACKPRESSURE_TAG);
            zkCluster.set_backpressure_info(context.getTopologyId(), SourceTobackpressureInfo);
            LOG.info(stringBuilder.toString());
        } catch (Exception e) {
            LOG.error("can't update backpressure state ", e);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{{<govuk_template}}

{{$head}}
  {{>includes/elements_head}}
  {{>includes/elements_scripts}}
{{/head}}

{{$propositionHeader}}
  {{>includes/propositional_navigation3}}
{{/propositionHeader}}

{{$headerClass}}with-proposition{{/headerClass}}

{{$content}}

  <form id="medical-form" class="form">

      Your consultant's contact details

        Consultant's Phone Number

          For example, '01792 123456'

        <input id="q8-a1" name="q8-a1" type="text" maxlength="11" class="form-control" onkeyup="answer(this,'{{flow}}','{{conditions}}')">

        Consultant's Email Address

          For example, 'doc@hospital.com'

        <input id="q9-a1" name="q9-a1" type="text" class="form-control" onkeyup="answer(this,'{{flow}}','{{conditions}}')">

      <input id="continue" type="button" class="button" value="Continue" onclick="decision(this,'{{flow}}','{{conditions}}')"/>

Back

  </form>

{{/content}}

{{$bodyEnd}}
{{/bodyEnd}}

{{/govuk_template}}


text:
package com.cloudera.sqoop.mapreduce;

import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.OutputFormat;
import com.cloudera.sqoop.manager.ExportJobContext;

/**
 * @deprecated Moving to use org.apache.sqoop namespace.
 */
public class JdbcExportJob
    extends org.apache.sqoop.mapreduce.JdbcExportJob {

  public JdbcExportJob(final ExportJobContext context) {
    super(context);
  }

  public JdbcExportJob(final ExportJobContext ctxt,
      final Class<? extends Mapper> mapperClass,
      final Class<? extends InputFormat> inputFormatClass,
      final Class<? extends OutputFormat> outputFormatClass) {
    super(ctxt, mapperClass, inputFormatClass, outputFormatClass);
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings version="2.1"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <jaxb:globalBindings generateElementProperty="false"/>
</jaxb:bindings>


text:
@interface UITextView (SFPlaceholder)

- (void)sf_setPlaceholder:(NSString *)placeholder;

@end


text:
[![Slack Status](http://cebeci.koding.com/slackin/badge.svg)](https://cebeci.koding.com/slackin/)
[![Docker Pulls](https://img.shields.io/docker/pulls/koding/koding.svg?maxAge=2592000)](https://hub.docker.com/r/koding/koding/)

The Simplest Way to Manage Your Entire Dev Infrastructure!

Koding is a development platform that orchestrates your dev
environment. Developers get everything they need to spin up
full-stack, project-specific environments in seconds. Share them, update them,
and manage infrastructure from a simple interface.

You can try Koding now on [koding.com](https://www.koding.com)

## Quick Start with Docker-Compose

Easiest way to run Koding is to install `docker-compose` which
can be found [here](https://docs.docker.com/compose/install/). For the
rest you can follow these steps:

```bash
git clone https://github.com/koding/docker-compose.git koding-docker-compose
cd koding-docker-compose
# Requires docker-compose version >= 1.6
docker-compose up -d
```

Now you are able to access Koding via port `8090` (e.g. [localhost:8090](http://localhost:8090)) on your host.

## Run Koding on Koding.com

Yes, you can run koding on [koding.com](https://www.koding.com) by using
the provided [.koding.yml](https://github.com/koding/koding/blob/master/.koding.yml)

For more information about stacks: [koding.com/docs](https://www.koding.com/docs/creating-an-aws-stack)

## Getting started for Development

You need to install following software packages to run Koding:

- [git](https://git-scm.com)
- [docker](https://www.docker.com)
- [docker-compose](https://www.docker.com/products/docker-compose)

### Start developing

You are now ready to run Koding.

```bash
git clone https://github.com/koding/koding.git
cd koding
docker-compose -f docker-compose-init.yml run init
docker-compose up
```

If you don't have a powerful computer, this may take a while at first, slow computers may take up to 15 minutes before they build the entire system. Please be patient. Once it is up and running, everything will be smooth and very fast.

Now you can navigate to http://localhost:8090 to see your local Koding
instance. Enjoy! (If you don't see it, keep waiting, it will show up)

When you edit files on your host computer, they will be visible in the
runtime environment. Watchers will automatically restart backend workers, re-compile frontend code. You don't need to do anything for it.

### Tips

If you need to execute some commands in runtime
environment, here is how you can start a shell in
backend service container:

```bash
docker-compose exec backend bash
```

You can follow [coffeescript-styleguide](https://github.com/koding/styleguide-coffeescript)
that we are relying on.

## Running Koding on Local Machine

This is if you don't want to do docker-compose way and install everything locally, (not recommended).

### Software Prerequisites

- [Go](http://www.golang.org/) v1.7
- [Node.js](https://nodejs.org/en/) v0.10
- [CoffeeScript](http://coffeescript.org/) v1.8.0
- [Supervisor](http://supervisord.org/)

### Start developing

Follow these steps for running the instance:

```bash
git clone https://github.com/koding/koding.git /your/koding/path
cd /your/koding/path
node -v # make sure your node version is not greater than `0.10.x`
npm -v # make sure your npm version is 2.15.x
coffee -v # make sure your coffeeScript version must be 1.8
npm install
```

You should have packages ready for running build specific scripts.

```bash
./configure # create necessary config files
./run install # start to install dependencies
./run buildservices # build the services
./run # run all services
```

As a result, you will have a file watcher watching your backend files
(both node, and golang) and restart services when it's necessary. Now open up
another terminal and run following commands:

```bash
cd /your/koding/path
cd client # move into frontend client folder
npm install # install client dependencies
make # this will run a client watcher for you
```

Right now you should have 2 different watchers for (1) your backend files,
(2)for your frontend client files.
Now you can navigate to [](http://localhost:8090) to see your local Koding
instance. Enjoy!

## License

Koding is licensed under [Apache 2.0](https://github.com/koding/koding/blob/master/LICENSE).

## Contribute

The main purpose of this repository to continue evolve Koding in order to make it more
stable and create the best development experience ever. If you're interested
in helping with that, please check our [open
issues](https://github.com/koding/koding/issues). You can also join the
conversation in our [slack team]!

[slack team]: http://cebeci.koding.com/slackin/


text:
class AccountDelegateLookupPage < Lookups

  element(:chart_code) { |b| b.frm.text_field(name: 'chartOfAccountsCode') }
  element(:number) { |b| b.frm.text_field(name: 'accountNumber') }
  element(:document_type_name) { |b| b.frm.text_field(name: 'financialDocumentTypeCode') }
  element(:account_delegate_principal_name) { |b| b.frm.text_field(name: 'accountDelegate.principalName') }

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Arch.CMessaging.Client.Core.Ioc.Utility
{
    internal class NamespaceList
    {
        private Dictionary<string, NamespaceList> index = new Dictionary<string, NamespaceList>();
        private int level;

        private NamespaceList(int level)
        {
            this.level = level;
        }

        public static NamespaceList Create()
        {
            return new NamespaceList(1);
        }

        public int Count
        {
            get
            {
                return index.Count;
            }
        }

        public void Add(string[] ns)
        {
            if (ns == null)
                throw new ArgumentNullException("ns");

            if (ns.Length >= level)
            {
                var key = ns[level - 1].Trim();
                if (!index.ContainsKey(key))
                {
                    if (ns.Length == level)
                    {
                        index.Add(key, null);
                    }
                    else
                    {
                        var list = new NamespaceList(level + 1);
                        list.Add(ns);
                        index.Add(key, list);
                    }
                }
                else
                {
                    if (ns.Length > level)
                    {
                        var list = index[key];
                        if (list != null)
                            list.Add(ns);
                    }
                }
            }
        }

        public bool Include(string[] ns)
        {
            if (ns == null)
                throw new ArgumentNullException("ns");

            if (ns.Length >= level)
            {
                var key = ns[level - 1].Trim();
                if (index.ContainsKey(key))
                {
                    var list = index[key];
                    if (list == null)
                        return true;

                    return list.Include(ns);
                }
            }

            return false;
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. H. Maiden, Crit. revis. Eucalyptus 8:42. 1929

#### Original name
null

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cqu.edu.ebmis.mapper.ProductBaseInfoMapper">

    <!-- 定义的resultMap,可以解决类的属性名和数据库列名不一致的问题-->
  <resultMap id="BaseResultMap" type="com.cqu.edu.ebmis.domain.ProductBaseInfoDO">
    <id column="productInnerId" jdbcType="BIGINT" property="productInnerId" />
    <result column="platform" jdbcType="VARCHAR" property="platform" />
    <result column="productName" jdbcType="VARCHAR" property="productName" />
    <result column="productURL" jdbcType="VARCHAR" property="productURL"/>
    <result column="singleKeyword" jdbcType="VARCHAR" property="keyword" />
    <result column="isValid" jdbcType="INTEGER" property="isValid" />
    <result column="checked" jdbcType="INTEGER" property="checked" />
    <result column="userName" jdbcType="VARCHAR" property="userName" />
    <result column="recheckPersonNum" jdbcType="INTEGER" property="recheckPersonNum" />
    <result column="monthSaleCount" jdbcType="DOUBLE" property="monthSaleCount" />
  </resultMap>
  <sql id="Base_Column_List" >
    productInnerId, platform, productName, productURL,singleKeyword, isValid, checked,userName
  </sql>
  <sql id="Base_Column_List1" >
    a.productInnerId, a.platform, a.productName, a.productURL,a.singleKeyword, a.isValid, a.checked,a.userName,a.extractTime
  </sql>
   <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select
    <include refid="Base_Column_List" />
    from product_baseinfo
    where productInnerId = #{productInnerId,jdbcType=BIGINT}
  </select>

  <select id="selectAllProduct" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from product_baseinfo
    order by extractTime
  </select>
  <select id="selectRecheckPersonProductData" resultMap="BaseResultMap">
    SELECT userName,COUNT(productInnerId) recheckPersonNum FROM product_baseinfo WHERE checked=1 GROUP BY userName
     limit #{offset},#{size}
  </select>
  <select id="selectRecheckPersonProductNum" resultType="int">
    select
    count(*)
    from ( SELECT userName,COUNT(productInnerId) recheckPersonNum FROM product_baseinfo WHERE checked=1 GROUP BY userName) a
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from product_baseinfo
    where productInnerId = #{productInnerId,jdbcType=BIGINT}
  </delete>

  <update id="isNotUpdateProduct" parameterType="com.cqu.edu.ebmis.domain.ProductBaseInfoDO" >
    update product_baseinfo
    set isValid = 0
    where productInnerId = #{productInnerId,jdbcType=BIGINT}
  </update>
  <update id="update" parameterType="com.cqu.edu.ebmis.domain.ProductBaseInfoDO" >
    update product_baseinfo
    set isValid = #{isValid,jdbcType=INTEGER},
    checked = #{checked,jdbcType=INTEGER},
    userName=#{userName,jdbcType=VARCHAR},
    recheckPersonTime=#{recheckPersonTime,jdbcType=TIMESTAMP}
    where productInnerId = #{productInnerId,jdbcType=BIGINT}
  </update>
  <!-- 产品基本数据复核 修改关键词 -->
  <update id="updateKeyWord" parameterType="com.cqu.edu.ebmis.domain.ProductBaseInfoDO" >
    update product_baseinfo
    set singleKeyword=#{keyword,jdbcType=VARCHAR}
    where productInnerId = #{productInnerId,jdbcType=BIGINT}
  </update>

  <select id="selectByPage" resultMap="BaseResultMap">
    select
    *
    from product_baseinfo
    order by extractTime
    limit #{offset},#{size}
  </select>
  <!-- 初始页搜索 -->
  <select id="selectAllSearchProduct" resultMap="BaseResultMap">
    select
    *
    from product_baseinfo where productName like #{word} or platform like #{word} or singleKeyword like #{word}
    <if test="checkedNum!=-1"> and checked=#{checkedNum}</if>
    order by extractTime
    limit #{offset},#{size}
  </select>
  <!-- 初始页搜索的条数 -->
  <select id="selectAllSearchProductNum" resultType="int">
    select
    count(*)
    from product_baseinfo where productName like #{word} or platform like #{word} or singleKeyword like #{word}
    <if test="checkedNum!=-1"> and checked=#{checkedNum}</if>
    order by extractTime
  </select>

   <select id="selectAllCount" resultType="int">
    select
    count(*)
    from product_baseinfo
  </select>

  <select id="selectCheckedByPage" resultMap="BaseResultMap">
  	select
  	<include refid="Base_Column_List1" />,e.monthSaleCount
  	from product_baseinfo a INNER JOIN
    (select b.productinnerid,b.monthSaleCount from productmonitor b INNER JOIN
      (select productinnerid ,max(c.productMonitorInnerId) as maxPMid from productmonitor c GROUP BY productInnerId ) d
       on  b.productMonitorInnerId=d.maxPMid  ) e
   	ON a.productInnerId=e.productInnerId
  	where a.checked=#{checked,jdbcType=INTEGER} and a.isValid=1
  	order by e.monthSaleCount desc
 	limit #{offset},#{size}
  </select>

  <select id="selectCheckedCount" resultType="int"  parameterType="java.lang.Integer">
 	select
    count(*)
    from product_baseinfo
    where checked=#{checked,jdbcType=INTEGER} and isValid=1
  </select>

  <select id="select" resultMap="BaseResultMap" parameterType="java.util.HashMap" >
    select
    <include refid="Base_Column_List" />
    from product_baseinfo
    where 1=1
    	<if test="checked!=null"> and checked=#{checked}</if>
    	<if test="isValid!=null"> and isValid=#{isValid}</if>
        <if test="platform!=null"> and platform=#{platform}</if>
        <if test="keyword!=null"> and singleKeyword=#{keyword}</if>
        <if test="key!=null"> and (productName like CONCAT('%',#{key},'%') or singleKeyword like CONCAT('%',#{key},'%'))</if>
        <if test="categoryCode!=null"> and categoryCode in <foreach collection="categoryCode"  item="item" index="index" open="(" separator="," close=")">#{item}</foreach>
        </if>
        <if test="size!=null"> limit #{size}</if><if test="size!=null and offset!=null">, #{offset}</if>

  </select>

  <select id="selectCount" resultType="int"  parameterType="java.util.HashMap">
 	select
    count(*)
    from product_baseinfo
    where 1=1
    	<if test="checked!=null"> and checked=#{checked}</if>
    	<if test="isValid!=null"> and isValid=#{isValid}</if>
        <if test="platform!=null"> and platform=#{platform}</if>
        <if test="keyword!=null"> and singleKeyword=#{keyword}</if>
        <if test="key!=null"> and (productName like CONCAT('%',#{key},'%') or singleKeyword like CONCAT('%',#{key},'%'))</if>
        <if test="categoryCode!=null"> and categoryCode in <foreach collection="categoryCode"  item="item" index="index" open="(" separator="," close=")">#{item}</foreach>
        </if>
  </select>
 <!-- 层级分页查找全部商品-->
  <select id="getLevelList" resultMap="BaseResultMap">
    SELECT <include refid="Base_Column_List1" />,e.monthSaleCount
  	from product_baseinfo a INNER JOIN
    (select b.productinnerid,b.monthSaleCount from productmonitor b INNER JOIN
      (select productinnerid ,max(c.productMonitorInnerId) as maxPMid from productmonitor c GROUP BY productInnerId ) d
       on  b.productMonitorInnerId=d.maxPMid  ) e
   	ON a.productInnerId=e.productInnerId WHERE 1=1 <if test="checkedNum!=-1"> and a.checked=#{checkedNum}</if><if test="platform!='请选择'"> and a.platform=#{platform}</if><if test="level0!='请选择'"> and a.singleKeyword IN
    (SELECT 三级 FROM threeclassificationtable WHERE 1=1 <if test="level0!='请选择'"> and 零级=#{level0}</if><if test="level1!='请选择'"> and 一级=#{level1}</if>
    <if test="level2!='请选择'"> and 二级=#{level2}</if><if test="level3!='请选择'"> and 三级=#{level3}</if>)</if> order by e.monthSaleCount desc limit #{offset},#{size}
  </select>
 <!-- 层级分页查找全部商品的数量-->
  <select id="getLevelListNum" resultType="int">
    SELECT count(productInnerId) FROM product_baseinfo WHERE 1=1 <if test="checkedNum!=-1"> and checked=#{checkedNum}</if><if test="platform!='请选择'"> and platform=#{platform}</if><if test="level0!='请选择'"> and singleKeyword IN
    (SELECT 三级 FROM threeclassificationtable WHERE 1=1 <if test="level0!='请选择'"> and 零级=#{level0}</if><if test="level1!='请选择'"> and 一级=#{level1}</if>
    <if test="level2!='请选择'"> and 二级=#{level2}</if><if test="level3!='请选择'"> and 三级=#{level3}</if>)</if>
  </select>
 <!-- 层级分页搜索查找商品-->
  <select id="getLevelSearchProduct" resultMap="BaseResultMap">
    SELECT <include refid="Base_Column_List1" />,e.monthSaleCount
  	from product_baseinfo a INNER JOIN
    (select b.productinnerid,b.monthSaleCount from productmonitor b INNER JOIN
      (select productinnerid ,max(c.productMonitorInnerId) as maxPMid from productmonitor c GROUP BY productInnerId ) d
       on  b.productMonitorInnerId=d.maxPMid  ) e
   	ON a.productInnerId=e.productInnerId WHERE ( a.productName like #{word} or a.singleKeyword like #{word} or a.userName like #{word})
    <if test="checkedNum!=-1"> and a.checked=#{checkedNum}</if><if test="platform!='请选择'"> and a.platform=#{platform}</if><if test="level0!='请选择'">and a.singleKeyword IN
    (SELECT 三级 FROM threeclassificationtable WHERE 1=1 <if test="level0!='请选择'"> and 零级=#{level0}</if><if test="level1!='请选择'"> and 一级=#{level1}</if>
    <if test="level2!='请选择'"> and 二级=#{level2}</if><if test="level3!='请选择'"> and 三级=#{level3}</if>)</if> order by e.monthSaleCount desc limit #{offset},#{size}
  </select>
 <!-- 层级分页查找全部商品的数量-->
  <select id="getLevelSearchProductNum" resultType="int">
    SELECT count(productInnerId) FROM product_baseinfo WHERE (productName like #{word} or singleKeyword like #{word} or userName like #{word})
    <if test="checkedNum!=-1"> and checked=#{checkedNum}</if><if test="platform!='请选择'"> and platform=#{platform}</if><if test="level0!='请选择'"> and singleKeyword IN
    (SELECT 三级 FROM threeclassificationtable WHERE 1=1 <if test="level0!='请选择'"> and 零级=#{level0}</if><if test="level1!='请选择'"> and 一级=#{level1}</if>
    <if test="level2!='请选择'"> and 二级=#{level2}</if><if test="level3!='请选择'"> and 三级=#{level3}</if>)</if>
  </select>

</mapper>


text:
{% extends "base.html" %}
{% load static %}

{% block css %}
    <link href="{% static 'generated_css/addtocal_base.min.css' %}" rel="stylesheet">
{% endblock %}

{% block extra-js %}

    {% if request.user.is_authenticated %}

    {% endif %}
{% endblock %}

{% block title %}LAN - {{ object.title }}{% endblock %}

{% block content %}

        {% if request.user.is_authenticated and not request.user in object.attendees.all %}

Sign in to event

Get an officer to sign you in at the event

        {% endif %}

{{ object.title }}

Location:

{{ object.location }}

Starts:

{{ object.start_time }}

Ends:

{{ object.end_time }}

                    <var class="atc_event">
                        <var class="atc_date_start">{{ object.start_time }}</var>
                        <var class="atc_date_end">{{ object.end_time }}</var>
                        <var class="atc_timezone">America/Chicago</var>
                        <var class="atc_title">{{ object.title }}</var>
                        <var class="atc_description">{{ object.description }}</var>
                        <var class="atc_location">{{ object.location }}</var>
                        <var class="atc_organizer">{{ object.creator.full_name }}</var>
                        <var class="atc_organizer_email">{{ object.creator.email }}</var>
                    </var>

Creator:

{{ object.creator.full_name }}

                {% if not object.is_gm_or_om or request.user.is_active %}

Description:

{{ object.description }}

                {% endif %}

Attendees:

{{ object.attendees.all|length }}

                {% if request.user.is_staff %}

                            Name
                            Email

                        {% for attendee in object.attendees.all %}

                                {{ attendee.full_name }}
                                {{ attendee.email }}

                        {% endfor %}

                {% endif %}

{% endblock content %}


text:
/*****************************************************************************
 * Preamble
 *****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_vout_display.h>
#include <vlc_picture_pool.h>

#include <directfb.h>

/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
static int  Open (vlc_object_t *);
static void Close(vlc_object_t *);

vlc_module_begin()
    set_shortname("DirectFB")
    set_category(CAT_VIDEO)
    set_subcategory(SUBCAT_VIDEO_VOUT)
    set_description(N_("DirectFB video output http://www.directfb.org/"))
    set_capability("vout display", 35)
    add_shortcut("directfb")
    set_callbacks(Open, Close)
vlc_module_end()

/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
static picture_pool_t *Pool  (vout_display_t *, unsigned);
static void           Display(vout_display_t *, picture_t *, subpicture_t *);
static int            Control(vout_display_t *, int, va_list);
static void           Manage (vout_display_t *);

/* */
static int  OpenDisplay (vout_display_t *);
static void CloseDisplay(vout_display_t *);

/* */
struct vout_display_sys_t {
    /* */
    IDirectFB             *directfb;
    IDirectFBSurface      *primary;
    DFBSurfacePixelFormat pixel_format;

    /* */
    int width;
    int height;

    /* */
    picture_pool_t *pool;
};

/* */
static int Open(vlc_object_t *object)
{
    vout_display_t *vd = (vout_display_t *)object;
    vout_display_sys_t *sys;

    /* Allocate structure */
    vd->sys = sys = malloc(sizeof(*sys));
    if (!sys)
        return VLC_ENOMEM;

    sys->directfb = NULL;
    sys->primary  = NULL;
    sys->width    = 0;
    sys->height   = 0;
    sys->pool     = NULL;

    /* Init DirectFB */
    if (DirectFBInit(NULL,NULL) != DFB_OK) {
        msg_Err(vd, "Cannot init DirectFB");
        free(sys);
        return VLC_EGENERIC;
    }

    if (OpenDisplay(vd)) {
        msg_Err(vd, "Cannot create primary surface");
        Close(VLC_OBJECT(vd));
        return VLC_EGENERIC;
    }
    vout_display_DeleteWindow(vd, NULL);

    /* */
    video_format_t fmt = vd->fmt;

    switch (sys->pixel_format) {
    case DSPF_RGB332:
        /* 8 bit RGB (1 byte, red 3@5, green 3@2, blue 2@0) */
        fmt.i_chroma = VLC_CODEC_RGB8;
        fmt.i_rmask = 0x7 << 5;
        fmt.i_gmask = 0x7 << 2;
        fmt.i_bmask = 0x3 << 0;
        break;
    case DSPF_RGB16:
        /* 16 bit RGB (2 byte, red 5@11, green 6@5, blue 5@0) */
        fmt.i_chroma = VLC_CODEC_RGB16;
        fmt.i_rmask = 0x1f << 11;
        fmt.i_gmask = 0x3f <<  5;
        fmt.i_bmask = 0x1f <<  0;
        break;
    case DSPF_RGB24:
        /* 24 bit RGB (3 byte, red 8@16, green 8@8, blue 8@0) */
        fmt.i_chroma = VLC_CODEC_RGB24;
        fmt.i_rmask = 0xff << 16;
        fmt.i_gmask = 0xff <<  8;
        fmt.i_bmask = 0xff <<  0;
        break;
    case DSPF_RGB32:
        /* 24 bit RGB (4 byte, nothing@24, red 8@16, green 8@8, blue 8@0) */
        fmt.i_chroma = VLC_CODEC_RGB32;
        fmt.i_rmask = 0xff << 16;
        fmt.i_gmask = 0xff <<  8;
        fmt.i_bmask = 0xff <<  0;
        break;
    default:
        msg_Err(vd, "unknown screen depth %i", sys->pixel_format);
        Close(VLC_OBJECT(vd));
        return VLC_EGENERIC;
    }

    fmt.i_width  = sys->width;
    fmt.i_height = sys->height;

    /* */
    vout_display_info_t info = vd->info;
    info.has_hide_mouse = true;

    /* */
    vd->fmt     = fmt;
    vd->info    = info;
    vd->pool    = Pool;
    vd->prepare = NULL;
    vd->display = Display;
    vd->control = Control;
    vd->manage  = Manage;

    /* */
    vout_display_SendEventFullscreen(vd, true);
    vout_display_SendEventDisplaySize(vd, fmt.i_width, fmt.i_height, true);
    return VLC_SUCCESS;
}

static void Close(vlc_object_t *object)
{
    vout_display_t *vd = (vout_display_t *)object;
    vout_display_sys_t *sys = vd->sys;

    if (sys->pool)
        picture_pool_Delete(sys->pool);

    CloseDisplay(vd);
    free(sys);
}

/* */
static picture_pool_t *Pool(vout_display_t *vd, unsigned count)
{
    vout_display_sys_t *sys = vd->sys;

    if (!sys->pool)
        sys->pool = picture_pool_NewFromFormat(&vd->fmt, count);
    return sys->pool;
}

static void Display(vout_display_t *vd, picture_t *picture, subpicture_t *subpicture)
{
    vout_display_sys_t *sys = vd->sys;

    IDirectFBSurface *primary = sys->primary;

    void *pixels;
    int  pitch;
    if (primary->Lock(primary, DSLF_WRITE, &pixels, &pitch) == DFB_OK) {
        picture_resource_t rsc;

        memset(&rsc, 0, sizeof(rsc));
        rsc.p[0].p_pixels = pixels;
        rsc.p[0].i_lines  = sys->height;
        rsc.p[0].i_pitch  = pitch;

        picture_t *direct = picture_NewFromResource(&vd->fmt, &rsc);
        if (direct) {
            picture_Copy(direct, picture);
            picture_Release(direct);
        }

        if (primary->Unlock(primary) == DFB_OK)
            primary->Flip(primary, NULL, 0);
    }
    picture_Release(picture);
    VLC_UNUSED(subpicture);
}

static int Control(vout_display_t *vd, int query, va_list args)
{
    switch (query) {
    case VOUT_DISPLAY_CHANGE_DISPLAY_SIZE: {
        const vout_display_cfg_t *cfg = va_arg(args, const vout_display_cfg_t *);
        if (cfg->display.width  != vd->fmt.i_width ||
            cfg->display.height != vd->fmt.i_height)
            return VLC_EGENERIC;
        return VLC_SUCCESS;
    }
    default:
        msg_Err(vd, "Unsupported query in vout display directfb");
        return VLC_EGENERIC;
    }
}

static void Manage (vout_display_t *vd)
{
    VLC_UNUSED(vd);
}

static int OpenDisplay(vout_display_t *vd)
{
    vout_display_sys_t *sys = vd->sys;

    DFBSurfaceDescription dsc;
    /*dsc.flags = DSDESC_CAPS | DSDESC_HEIGHT | DSDESC_WIDTH;*/
    dsc.flags = DSDESC_CAPS;
    dsc.caps  = DSCAPS_PRIMARY | DSCAPS_FLIPPING;
    /*dsc.width = 352;*/
    /*dsc.height = 240;*/

    IDirectFB *directfb = NULL;
    if (DirectFBCreate(&directfb) != DFB_OK || !directfb)
        return VLC_EGENERIC;
    sys->directfb = directfb;

    IDirectFBSurface *primary = NULL;
    if (directfb->CreateSurface(directfb, &dsc, &primary) || !primary)
        return VLC_EGENERIC;
    sys->primary = primary;

    primary->GetSize(primary, &sys->width, &sys->height);
    primary->GetPixelFormat(primary, &sys->pixel_format);
    primary->FillRectangle(primary, 0, 0, sys->width, sys->height);
    primary->Flip(primary, NULL, 0);

    return VLC_SUCCESS;
}

static void CloseDisplay(vout_display_t *vd)
{
    vout_display_sys_t *sys = vd->sys;

    IDirectFBSurface *primary = sys->primary;
    if (primary)
        primary->Release(primary);

    IDirectFB *directfb = sys->directfb;
    if (directfb)
        directfb->Release(directfb);
}


text:
define(
	 ({
		commonMedia: {
			mediaSelector: {
				lblSelect1: "Medijs",
				lblSelect2: "Saturs",
				lblMap: "Karte",
				lblImage: "Attēls",
				lblVideo: "Video",
				lblExternal: "Web lapa",
				disabled: "Šo funkciju administrators ir atspējojis",
				url: "Lai manuālie ievadītu attēla web adresi",
				userLookup: "Ielādēt albumus",
				notImplemented: "Vēl nav ieviests.",
				noData: "Nav atrasts publisks albums"
			},
			imageSelector: {
				lblStep1: "Izvēlēties servisu",
				lblStep2: "Izvēlēties mediju",
				lblStep3: "Konfigurēt"
			},
			imageSelectorHome: {
				explain: "Ielādējiet attēlus no sociālajiem medijiem
 vai tieši no URL"
			},
			imageSelectorFlickr: {
				userInputLbl: "Lietotāja vārds",
				signInMsg2: "Lietotājs nav atrasts",
				loadingFailed: "Ielāde neizdevās"
			},
			imageSelectorFacebook: {
				leftHeader: "Facebook Lietotājs",
				rightHeader: "Facebook Lapa",
				pageExplain: "Facebook lapa ir publisks zīmols/produkts vai slavenība, piem., esrigis. Jūs varat saņemt lapas nosaukumu, pēc pirmās \'/\' lapas URL.",
				pageInputLbl: "Lapas nosaukums",
				lookupMsgError: "Lapa nav atrasta"
			},
			imageSelectorPicasa: {
				userInputLbl: "E-pasta adrese vai Picasa/Google+ ID",
				signInMsg2: "Konts nav atrasts",
				howToFind: "Kā atrast Picasa vai Google+ konta ID",
				howToFind2: "Kopēt ciparus starp pirmo un otro \'/\' no jebkura Picasa vai G+ lapa"
			},
			videoSelectorCommon: {
				check: "Pārbaudīt",
				notFound: "Video nav atrasts",
				found: "Video atrasts",
				select: "Atlasīt šo video"
			},
			videoSelectorHome: {
				other: "Cits"
			},
			videoSelectorYoutube: {
				url: "Youtube video URL",
				pageInputLbl: "Lietotāja vārds",
				lookupMsgError: "Lietotājs nav atrasts",
				howToFind: "Kā atrast YouTube lietotāja vārdu",
				howToFind2: "Lietotāja vārds ir attēlots zem video",
				found: "Atrasts",
				noData: "Nav atrasti publiski video"
			},
			videoSelectorVimeo: {
				url: "Vimeo video URL"
			},
			videoSelectorOther: {
				explain1: "Aplikācija nevar atskaņot neapstrādātus video (piemēram, avi, mpeg), bet var atskaņot mitinātus video failus ar iebūvētiem atskaņotājiem (piemēram, YouTube vai Vimeo).",
				explain2: "Lielākā daļa video mitināšanas pakalpojumu piedāvā šo funkciju, jums ir jāatrod iespēja iedarināt video, nokopēt saņemto kodu un izmantot %WEBPAGE%.",
				explain3: "Ja video vēlaties mitināt pats, varat arī izveidot HTML lapu, kurā tiek izmantots video atskaņotājs (piemēram, %EXAMPLE%), mitināt šo lapu un arī izmantot %WEBPAGE%.",
				webpage: "Web lapas funkcija"
			},
			webpageSelectorHome: {
				lblUrl: "Web lapas URL",
				lblEmbed: "Iedarināt kodu",
				lblOR: "VAI",
				lblError1: "Kļūda, notīriet vienu no diviem ievades laukiem.",
				lblError2: "Iegultais kods var saturēt tikai vienu %IFRAMETAG%",
				configure: "Konfigurēt"
			},
			mediaConfigure: {
				lblURL: "URL",
				lblURLPH: "Attēla URL ir jāsākas ar http:// un jābeidzas ar .jpg vai .png",
				lblURLError: "Šķiet, ka šis attēls nav derīgs. Lūdzu, norādiet tiešu saiti uz attēla failu (parasti URL beidzas ar .jpg vai .png). Saites uz web lapu, kurā atrodas attēls, nedarbosies.",
				lblURLCheck: "Notiek attēla pārbaude...",
				lblLabel: "Attēla teksts",
				lblLabel1: "Uzraksts",
				lblLabel2: "Novietot virs teksta",
				lblLabel3: "Neviens",
				lblLabelPH: "Ievadiet tekstu...",
				lblMaximize: "Attēla stūrī iekļaut maksimizēšanas pogu",
				lblMaximizeHelp: "Ieteicams tikai augstas kvalitātes foto",
				lblPosition: "Pozīcija",
				lblPosition1: "Centrs",
				lblPosition2: "Aizpildīt",
				lblPosition3: "Ietilpināt",
				lblPosition4: "Izstiept",
				lblPosition5: "Pielāgots",
				tooltipDimension: "Vērtību var norādīt \'px\' vai \'%\'",
				tooltipDimension2: "Vērtība ir jānorāda pikseļos",
				lblPosition2Explain: "(var apgriezt)",
				lblPosition3Explain: "(netiks apgriezts)",
				lblPosition3Explain2: "(platums vienmēr atbildīs panelim)",
				lblPosition4Explain: "(var tikt izkropļots)",
				unloadLbl: "Izlādēt, ja lasītājs pārvietojas uz citurieni",
				unloadHelp: "Ja web lapā ir audio vai video datu nesējs, saglabājiet šo opciju kā atzīmētu, lai tad, kad lasītājs pārvietojas uz citu vietu, netiktu demonstrēts saturs. Noņemiet atzīmi, piemēram, gadījumos, ja vēlaties atskaņot skaņu celiņu, kamēr lasītājs pārskata stāstu.
Ja web lapa ir aplikācija, noņemiet šīs opcijas atlasi, lai tad, kad lasītājs atgriežas tajā, aplikācija netiktu ielādēta atkārtoti."
			},
			editorActionGeocode: {
				lblTitle: "Adreses vai vietas noteikšana",
				mapMarkerExplain: "Noklikšķinot uz saites, lietotājam tiks rādīts kartes punkts"
			},
			editorActionMedia: {
				lblTitle: "Galvenā posma satura maiņa"
			},
			editorInlineMedia: {
				lblTitle: "Attēla, video vai web lapas ievietošana"
			}
		}
	})
);


text:
module.exports = File

var eos = require('end-of-stream')
var EventEmitter = require('events').EventEmitter
var FileStream = require('./file-stream')
var inherits = require('inherits')
var path = require('path')
var render = require('render-media')
var stream = require('readable-stream')
var streamToBlobURL = require('stream-to-blob-url')
var streamToBuffer = require('stream-with-known-length-to-buffer')

inherits(File, EventEmitter)

/**
 * @param {Torrent} torrent torrent that the file belongs to
 * @param {Object} file file object from the parsed torrent
 */
function File (torrent, file) {
  EventEmitter.call(this)

  this._torrent = torrent

  this.name = file.name
  this.path = file.path
  this.length = file.length
  this.offset = file.offset

  this.done = false

  var start = file.offset
  var end = start + file.length - 1

  this._startPiece = start / this._torrent.pieceLength | 0
  this._endPiece = end / this._torrent.pieceLength | 0

  if (this.length === 0) {
    this.done = true
    this.emit('done')
  }
}

/**
 * Selects the file to be downloaded, but at a lower priority than files with streams.
 * Useful if you know you need the file at a later stage.
 */
File.prototype.select = function (priority) {
  if (this.length === 0) return
  this._torrent.select(this._startPiece, this._endPiece, priority)
}

/**
 * Deselects the file, which means it won't be downloaded unless someone creates a stream
 * for it.
 */
File.prototype.deselect = function () {
  if (this.length === 0) return
  this._torrent.deselect(this._startPiece, this._endPiece, false)
}

/**
 * Create a readable stream to the file. Pieces needed by the stream will be prioritized
 * highly and fetched from the swarm first.
 *
 * @param {Object=} opts
 * @param {number} opts.start start stream at byte (inclusive)
 * @param {number} opts.end end stream at byte (inclusive)
 * @return {FileStream}
 */
File.prototype.createReadStream = function (opts) {
  var self = this
  if (this.length === 0) {
    var empty = new stream.PassThrough()
    process.nextTick(function () {
      empty.end()
    })
    return empty
  }

  var fileStream = new FileStream(self, opts)
  self._torrent.select(fileStream._startPiece, fileStream._endPiece, true, function () {
    fileStream._notify()
  })
  eos(fileStream, function () {
    self._torrent.deselect(fileStream._startPiece, fileStream._endPiece, true)
  })
  return fileStream
}

/**
 * @param {function} cb
 */
File.prototype.getBuffer = function (cb) {
  streamToBuffer(this.createReadStream(), this.length, cb)
}

/**
 * @param {function} cb
 */
File.prototype.getBlobURL = function (cb) {
  if (typeof window === 'undefined') throw new Error('browser-only method')
  var mime = render.mime[path.extname(this.name).toLowerCase()]
  streamToBlobURL(this.createReadStream(), mime, cb)
}

/**
 * @param {Element|string} elem
 * @param {function} cb
 */
File.prototype.appendTo = function (elem, cb) {
  if (typeof window === 'undefined') throw new Error('browser-only method')
  render.append(this, elem, cb)
}

/**
 * @param {Element|string} elem
 * @param {function} cb
 */
File.prototype.renderTo = function (elem, cb) {
  if (typeof window === 'undefined') throw new Error('browser-only method')
  render.render(this, elem, cb)
}


text:
Node Problem Detector
---------------------

Installs the [Node Problem Detector](https://github.com/kubernetes/node-problem-detector).

## Configuration

See [values](values.yaml).

**Note**: Additional log monitors and custom plugins can be added in the [monitors](monitors) folder and activated via [values](values.yaml).


text:
if (-not (Test-Path "$env:LocalAppData\FreeCommanderXE\Settings")) {
  if (-not (Test-Path "$env:LocalAppData\FreeCommanderXE")) {
    New-Item -Path "$env:LocalAppData\FreeCommanderXE" -ItemType Directory | Out-Null
  }

  New-Item -Path "$env:LocalAppData\FreeCommanderXE\Settings" -ItemType Directory | Out-Null
}

Copy-Item -Path "$PSScriptRoot\..\content\*" `
  -Destination "$env:LocalAppData\FreeCommanderXE\Settings" -Recurse -Force

$files = Get-ChildItem -Path "$env:SystemDrive\etc" -Filter "FreeCommander.*"

if ($files.Count -gt 0) {
  Copy-Item -Path "$env:SystemDrive\etc\FreeCommander.*" `
    -Destination "$env:LocalAppData\FreeCommanderXE\Settings" -Force
}


text:
namespace {

#pragma pack(push, 1)
struct InternalThunk {
  // This struct contains roughly the following code:
  // sub esp, 8                             // Create working space
  // push edx                               // Save register
  // mov edx, [esp + 0xc]                   // Get return adddress
  // mov [esp + 8], edx                     // Store return address
  // mov dword ptr [esp + 0xc], 0x7c401200  // Store extra argument
  // mov dword ptr [esp + 4], 0x40010203    // Store address to jump to
  // pop edx                                // Restore register
  // ret                                    // Jump to interceptor
  //
  // This code only modifies esp and eip so it must work with to normal calling
  // convention. It is assembled as:
  //
  // 00 83ec08           sub     esp,8
  // 03 52               push    edx
  // 04 8b54240c         mov     edx,dword ptr [esp + 0Ch]
  // 08 89542408         mov     dword ptr [esp + 8], edx
  // 0c c744240c0012407c mov     dword ptr [esp + 0Ch], 7C401200h
  // 14 c744240403020140 mov     dword ptr [esp + 4], 40010203h
  // 1c 5a               pop     edx
  // 1d c3               ret
  InternalThunk() {
    opcodes_1 = 0x5208ec83;
    opcodes_2 = 0x0c24548b;
    opcodes_3 = 0x08245489;
    opcodes_4 = 0x0c2444c7;
    opcodes_5 = 0x042444c7;
    opcodes_6 = 0xc35a;
    extra_argument = 0;
    interceptor_function = 0;
  };
  ULONG opcodes_1;         // = 0x5208ec83
  ULONG opcodes_2;         // = 0x0c24548b
  ULONG opcodes_3;         // = 0x08245489
  ULONG opcodes_4;         // = 0x0c2444c7
  ULONG extra_argument;
  ULONG opcodes_5;         // = 0x042444c7
  ULONG interceptor_function;
  USHORT opcodes_6;         // = 0xc35a
};
#pragma pack(pop)

};  // namespace

namespace sandbox {

NTSTATUS ResolverThunk::Init(const void* target_module,
                             const void* interceptor_module,
                             const char* target_name,
                             const char* interceptor_name,
                             const void* interceptor_entry_point,
                             void* thunk_storage,
                             size_t storage_bytes) {
  if (NULL == thunk_storage || 0 == storage_bytes ||
      NULL == target_module || NULL == target_name)
    return STATUS_INVALID_PARAMETER;

  if (storage_bytes < GetThunkSize())
    return STATUS_BUFFER_TOO_SMALL;

  NTSTATUS ret = STATUS_SUCCESS;
  if (NULL == interceptor_entry_point) {
    ret = ResolveInterceptor(interceptor_module, interceptor_name,
                             &interceptor_entry_point);
    if (!NT_SUCCESS(ret))
      return ret;
  }

  ret = ResolveTarget(target_module, target_name, &target_);
  if (!NT_SUCCESS(ret))
    return ret;

  interceptor_ = interceptor_entry_point;

  return ret;
}

size_t ResolverThunk::GetInternalThunkSize() const {
  return sizeof(InternalThunk);
}

bool ResolverThunk::SetInternalThunk(void* storage, size_t storage_bytes,
                                     const void* original_function,
                                     const void* interceptor) {
  if (storage_bytes < sizeof(InternalThunk))
    return false;

  InternalThunk* thunk = new(storage, NT_PLACE) InternalThunk;

#pragma warning(push)
#pragma warning(disable: 4311)
  // These casts generate warnings because they are 32 bit specific.
  thunk->interceptor_function = reinterpret_cast<ULONG>(interceptor);
  thunk->extra_argument = reinterpret_cast<ULONG>(original_function);
#pragma warning(pop)

  return true;
}

NTSTATUS ResolverThunk::ResolveInterceptor(const void* interceptor_module,
                                           const char* interceptor_name,
                                           const void** address) {
  DCHECK_NT(address);
  if (!interceptor_module)
    return STATUS_INVALID_PARAMETER;

  PEImage pe(interceptor_module);
  if (!pe.VerifyMagic())
    return STATUS_INVALID_IMAGE_FORMAT;

  *address = pe.GetProcAddress(interceptor_name);

  if (!(*address))
    return STATUS_PROCEDURE_NOT_FOUND;

  return STATUS_SUCCESS;
}

NTSTATUS ResolverThunk::ResolveTarget(const void* module,
                                      const char* function_name,
                                      void** address) {
  const void** casted = const_cast<const void**>(address);
  return ResolverThunk::ResolveInterceptor(module, function_name, casted);
}

}  // namespace sandbox


text:
import { lazy } from 'react';

import { retryPromiseDebug as debug } from './debug';

/**
 * Returns function that retries the given function until it succeeds or throws
 * error after the maxAttempts attempts.
 *
 * @param {()=>Promise<T>} fn
 * @param {number} maxAttempts
 * @param {number} interval
 * @returns {()=>Promise<T>}
 */
export function retry(fn, maxAttempts = 5, interval = 1000) {
  return async function () {
    try {
      return await fn();
    } catch (err) {
      debug('error happened while retrying:', err);
      if (maxAttempts > 1) {
        await new Promise((resolve) => setTimeout(resolve, interval));
        return await retry(fn, maxAttempts - 1, interval)();
      }
      throw err;
    }
  };
}

/**
 * Use React.lazy with retry
 *
 * @param {()=>Promise} fn
 */
export function lazyRetry(fn) {
  return lazy(retry(fn));
}


text:
void register_OutputStream_class();

#endif//OutputStream_hpp__pyplusplus_wrapper


text:
title: Finite model theory
published: 2016-10-14
modified: 2016-10-14
tags: model theory
type: topic
showTOC: True
---

[Link](https://simons.berkeley.edu/talks/finite-and-algorithmic-model-theory)

# 1 Definability and undefinability

* Expressive power of logics on class of finite structures.
* Problems in computer science (complexity theory, database theory) are naturally questions about expressive power of logics.

$$Mod(\ph) = \set{\mathbb A}{ \mathbb A \vDash \ph}.$$
Here $\mathbb A$ ranges over finite relational structures.

What classes of structures are definable? (Set of possible $Mod(\ph)$'s for $\ph$ in logic $\mathcal L$.)

* Syntactic restrictions on $\ph$ vs. semantic restrictions on $Mod(\ph)$.
* Computational complexity of $Mod(\ph)$ vs. syntactic complexity of $\ph$.

## Expressive power

Relational vocabulary: finite set $A$ with relations $R_1,\ldots, R_m$ and constants $c_1,\ldots, c_n$.

A property of finite structures is any isomorphism-closed class of
structures. (Morphisms are permutations. Ex. graph ismomorphisms.)
Given logic, for which properties $P$ is there a sentence $\ph$ such that $\mathbb A\in P\iff A\vDash \ph$.

Ex. colored graphs: one binary relation $E^2$ and some unary relations $C_i^1$. First-order logic formulas involve these relations and $\wedge, \vee, \neg, \exists, \forall$.

* Vertex cover of size at most $k$. ($k$ fixed)
* 3-colorability when allow quantification over sets of vertices.

Compactness, completeness, preservation fail. (What are these exactly?)

Methods:

* Ehrenfeucht-Fraisse Games and related model-comparison games
* Locality Theorems
* Automata-based methods
* Complexity
* Asymptotic Combinatorics

Equivalence means satisfying the same statements in the logic. On finite structures, two structures are equivalent iff they are isomorphic.

Quantifier rank:

1. For atoms, $qr(\ph)=0$.
2. $qr(\neg \psi) = qr(\psi)$.
3. $qr(\psi_1\wedge/\vee \psi_2) = \max_i(qr(\psi_i))$.
4. $qr(\exists/\forall x \psi) = qr(\psi)+1$.

$\mathbb A\equiv_p \mathbb B$ iff for all $qr(\ph)\le p$, $A\vDash \ph\iff B\vDash \ph$.

$S$ is definable by first order sentence iff $S$ is closed under $\equiv_p$ for some $p$. (13) ??
(Is $S$ on finite set? What does "finite relational vocab" mean?)
(Is this trivial by taking $p=|A|$?)
(NO: $A$ is of arbitrary finite size!)

Ex. I think connectedness is not first-order!

Define **partial isomorphism**.

Ehrenfeucht-Fraisse game:

For $p$ rounds:

* Spoiler choose one structure and an element of that structure.
* Duplicator responds with element of other structure $a_i$.

After $p$ rounds, Duplicator wins if $a_i\mapsto b_i$ is partial iso. Duplicator has winning strategy iff $\mathbb A\equiv_p \mathbb B$.

Proof: choose the witnesses of existence, going to the other structure for a $\forall$ because negated $\forall$ gives $\exists$.

So to show not definable, for every $p$ produce $\mathbb A_p$, $\mathbb B_p$ such that one is in $S$, and duplicator wins.

Ex. Not definable: 2-colorability, even cardinality, connectivity.

(Duplicator's strategy is to ensure that after r moves, the distance between corresponding pairs of pebbles is either equal or $2p^r$.)

Alternative: stratify by number of free variables (in any sub-formula), $\equiv^k$. $\equiv^k\implies \equiv_k$.

Connectivity and 2-colorability are axiomatizable in $L^k$ (define $path_{\le l}$, $disconnect_l$); even cardinality is not.
(I'm confused... why can we reuse variables?? 21)

$\equiv_p, \equiv^k$ have finitely/infinitely many equivalence classes.

How is the pebble game different?? 23


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.connectedvmware.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.connectedvmware.fluent.models.InventoryItemInner;

/** An instance of this class provides access to all the operations defined in InventoryItemsClient. */
public interface InventoryItemsClient {
    /**
     * Implements InventoryItem PUT method.
     *
     *
Create Or Update InventoryItem.
     *
     * @param resourceGroupName The Resource Group Name.
     * @param vcenterName Name of the vCenter.
     * @param inventoryItemName Name of the inventoryItem.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return defines the inventory item.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    InventoryItemInner create(String resourceGroupName, String vcenterName, String inventoryItemName);

    /**
     * Implements InventoryItem PUT method.
     *
     *
Create Or Update InventoryItem.
     *
     * @param resourceGroupName The Resource Group Name.
     * @param vcenterName Name of the vCenter.
     * @param inventoryItemName Name of the inventoryItem.
     * @param body Request payload.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return defines the inventory item along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<InventoryItemInner> createWithResponse(
        String resourceGroupName,
        String vcenterName,
        String inventoryItemName,
        InventoryItemInner body,
        Context context);

    /**
     * Gets InventoryItem.
     *
     *
Implements InventoryItem GET method.
     *
     * @param resourceGroupName The Resource Group Name.
     * @param vcenterName Name of the vCenter.
     * @param inventoryItemName Name of the inventoryItem.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return defines the inventory item.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    InventoryItemInner get(String resourceGroupName, String vcenterName, String inventoryItemName);

    /**
     * Gets InventoryItem.
     *
     *
Implements InventoryItem GET method.
     *
     * @param resourceGroupName The Resource Group Name.
     * @param vcenterName Name of the vCenter.
     * @param inventoryItemName Name of the inventoryItem.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return defines the inventory item along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<InventoryItemInner> getWithResponse(
        String resourceGroupName, String vcenterName, String inventoryItemName, Context context);

    /**
     * Deletes an inventoryItem.
     *
     *
Implements inventoryItem DELETE method.
     *
     * @param resourceGroupName The Resource Group Name.
     * @param vcenterName Name of the vCenter.
     * @param inventoryItemName Name of the inventoryItem.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    void delete(String resourceGroupName, String vcenterName, String inventoryItemName);

    /**
     * Deletes an inventoryItem.
     *
     *
Implements inventoryItem DELETE method.
     *
     * @param resourceGroupName The Resource Group Name.
     * @param vcenterName Name of the vCenter.
     * @param inventoryItemName Name of the inventoryItem.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<Void> deleteWithResponse(
        String resourceGroupName, String vcenterName, String inventoryItemName, Context context);

    /**
     * Implements GET inventoryItems in a vCenter.
     *
     *
Returns the list of inventoryItems of the given vCenter.
     *
     * @param resourceGroupName The Resource Group Name.
     * @param vcenterName Name of the vCenter.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of InventoryItems as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<InventoryItemInner> listByVCenter(String resourceGroupName, String vcenterName);

    /**
     * Implements GET inventoryItems in a vCenter.
     *
     *
Returns the list of inventoryItems of the given vCenter.
     *
     * @param resourceGroupName The Resource Group Name.
     * @param vcenterName Name of the vCenter.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of InventoryItems as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<InventoryItemInner> listByVCenter(String resourceGroupName, String vcenterName, Context context);
}


text:
package com.facebook.react.devsupport;

import android.app.Activity;
import android.app.Dialog;
import android.view.View;
import android.view.Window;
import com.facebook.react.R;

/** Dialog for displaying JS errors in LogBox. */
public class LogBoxDialog extends Dialog {
  public LogBoxDialog(Activity context, View reactRootView) {
    super(context, R.style.Theme_Catalyst_LogBox);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(reactRootView);
  }
}


text:
local prefix = ARGV[1]
local ttl = tonumber(ARGV[2])
local max = tonumber(ARGV[3])
local term = ARGV[4]
local i = 1
-- Iterate through all prefixes of a given term
while i <= #term do
  local set = prefix..term:sub(1, i)
  print('INDEX', set)
  -- Find the length of the set, if we are not at the max number, add
  -- the element with a score of 1. Otherwise, remove the element with
  -- the lowest score, and add the new element with that score + 1
  local len = tonumber(redis.call('ZCARD', set))
  if len < max then
    -- Normal element adding
    redis.call('ZINCRBY', set, 1, term)
  else
    -- Lowest element replacement
    local member, score = unpack(redis.call('ZREVRANGE', set, -1, -1))
    score = score or 0
    redis.call('ZREM', set, member)
    redis.call('ZINCRBY', set, tonumber(score) + 1, term)
  end
  if ttl then redis.call('EXPIRE', set, ttl) end
  i = i + 1
end
return 1


text:
namespace Format.Utils {

    describe("Numeric toExponentialMinMax", () => {

        let value = 123.456;

        it("should return/throw the best fitting value/error for its Number.toFixed handler", () => {

            expect(Numeric.toExponentialMinMax(value, 0, 7)).toBe("1.23456e+2");
            expect(Numeric.toExponentialMinMax(value, 0, 5)).toBe("1.23456e+2");
            expect(Numeric.toExponentialMinMax(value, undefined, 7)).toBe("1.23456e+2");
            expect(Numeric.toExponentialMinMax(value, null, 6)).toBe("1.23456e+2");
            expect(Numeric.toExponentialMinMax(value, undefined, 5)).toBe("1.23456e+2");
            expect(Numeric.toExponentialMinMax(value, null, 3)).toBe("1.235e+2");
            expect(Numeric.toExponentialMinMax(value, 4, undefined)).toBe("1.23456e+2");
            expect(Numeric.toExponentialMinMax(value, 2, null)).toBe("1.23456e+2");
            expect(Numeric.toExponentialMinMax(value, 6, null)).toBe("1.234560e+2");
            expect(Numeric.toExponentialMinMax(value, 7, undefined)).toBe("1.2345600e+2");
            expect(Numeric.toExponentialMinMax(value, 0, 0)).toBe("1e+2");
            expect(Numeric.toExponentialMinMax(value, undefined, null)).toBe("1.23456e+2");

            expect(() => Numeric.toExponentialMinMax(value, -1, undefined)).toThrowError(RangeError);
            expect(() => Numeric.toExponentialMinMax(value, null, -1)).toThrowError(RangeError);
        });

        it("should throw appropriate errors during parameters' validation", () => {

            expect(() => Numeric.toExponentialMinMax(null, 0, 0)).toThrowError(Errors.ArgumentNullError);
            expect(() => Numeric.toExponentialMinMax(undefined, 0, 0)).toThrowError(Errors.ArgumentNullError);

            expect(() => Numeric.toExponentialMinMax(NaN, 0, 0)).toThrowError(Errors.ArgumentError);
            expect(() => Numeric.toExponentialMinMax(Infinity, 0, 0)).toThrowError(Errors.ArgumentError);
            expect(() => Numeric.toExponentialMinMax(value, NaN, 0)).toThrowError(Errors.ArgumentError);
            expect(() => Numeric.toExponentialMinMax(value, 1, NaN)).toThrowError(Errors.ArgumentError);
            expect(() => Numeric.toExponentialMinMax(value, Infinity, undefined)).toThrowError(Errors.ArgumentError);
            expect(() => Numeric.toExponentialMinMax(value, null, Infinity)).toThrowError(Errors.ArgumentError);

            expect(() => Numeric.toExponentialMinMax(value, 1, 0)).toThrowError(RangeError);
            expect(() => Numeric.toExponentialMinMax(value, 0, 21)).toThrowError(RangeError);
        });
    });
}