text:
.class public Landroid/widget/AbsoluteLayout;
.super Landroid/view/ViewGroup;
.source "AbsoluteLayout.java"

# annotations
.annotation runtime Landroid/widget/RemoteViews$RemoteView;
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/widget/AbsoluteLayout$LayoutParams;
    }
.end annotation

.annotation runtime Ljava/lang/Deprecated;
.end annotation

# direct methods
.method public constructor <init>(Landroid/content/Context;)V
    .locals 0
    .param p1, "context"    # Landroid/content/Context;

    .prologue
    .line 43
    invoke-direct {p0, p1}, Landroid/view/ViewGroup;-><init>(Landroid/content/Context;)V

    .line 44
    return-void
.end method

.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
    .locals 0
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "attrs"    # Landroid/util/AttributeSet;

    .prologue
    .line 47
    invoke-direct {p0, p1, p2}, Landroid/view/ViewGroup;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V

    .line 48
    return-void
.end method

.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V
    .locals 0
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "attrs"    # Landroid/util/AttributeSet;
    .param p3, "defStyle"    # I

    .prologue
    .line 52
    invoke-direct {p0, p1, p2, p3}, Landroid/view/ViewGroup;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V

    .line 53
    return-void
.end method

# virtual methods
.method protected checkLayoutParams(Landroid/view/ViewGroup$LayoutParams;)Z
    .locals 1
    .param p1, "p"    # Landroid/view/ViewGroup$LayoutParams;

    .prologue
    .line 136
    instance-of v0, p1, Landroid/widget/AbsoluteLayout$LayoutParams;

    return v0
.end method

.method protected generateDefaultLayoutParams()Landroid/view/ViewGroup$LayoutParams;
    .locals 3

    .prologue
    const/4 v2, 0x0

    const/4 v1, -0x2

    .line 103
    new-instance v0, Landroid/widget/AbsoluteLayout$LayoutParams;

    invoke-direct {v0, v1, v1, v2, v2}, Landroid/widget/AbsoluteLayout$LayoutParams;-><init>(IIII)V

    return-object v0
.end method

.method public generateLayoutParams(Landroid/util/AttributeSet;)Landroid/view/ViewGroup$LayoutParams;
    .locals 2
    .param p1, "attrs"    # Landroid/util/AttributeSet;

    .prologue
    .line 130
    new-instance v0, Landroid/widget/AbsoluteLayout$LayoutParams;

    invoke-virtual {p0}, Landroid/widget/AbsoluteLayout;->getContext()Landroid/content/Context;

    move-result-object v1

    invoke-direct {v0, v1, p1}, Landroid/widget/AbsoluteLayout$LayoutParams;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V

    return-object v0
.end method

.method protected generateLayoutParams(Landroid/view/ViewGroup$LayoutParams;)Landroid/view/ViewGroup$LayoutParams;
    .locals 1
    .param p1, "p"    # Landroid/view/ViewGroup$LayoutParams;

    .prologue
    .line 141
    new-instance v0, Landroid/widget/AbsoluteLayout$LayoutParams;

    invoke-direct {v0, p1}, Landroid/widget/AbsoluteLayout$LayoutParams;-><init>(Landroid/view/ViewGroup$LayoutParams;)V

    return-object v0
.end method

.method protected onLayout(ZIIII)V
    .locals 8
    .param p1, "changed"    # Z
    .param p2, "l"    # I
    .param p3, "t"    # I
    .param p4, "r"    # I
    .param p5, "b"    # I

    .prologue
    .line 109
    invoke-virtual {p0}, Landroid/widget/AbsoluteLayout;->getChildCount()I

    move-result v3

    .line 111
    .local v3, "count":I
    const/4 v4, 0x0

    .local v4, "i":I
    :goto_0
    if-ge v4, v3, :cond_1

    .line 112
    invoke-virtual {p0, v4}, Landroid/widget/AbsoluteLayout;->getChildAt(I)Landroid/view/View;

    move-result-object v0

    .line 113
    .local v0, "child":Landroid/view/View;
    invoke-virtual {v0}, Landroid/view/View;->getVisibility()I

    move-result v6

    const/16 v7, 0x8

    if-eq v6, v7, :cond_0

    .line 115
    invoke-virtual {v0}, Landroid/view/View;->getLayoutParams()Landroid/view/ViewGroup$LayoutParams;

    move-result-object v5

    check-cast v5, Landroid/widget/AbsoluteLayout$LayoutParams;

    .line 118
    .local v5, "lp":Landroid/widget/AbsoluteLayout$LayoutParams;
    iget v6, p0, Landroid/widget/AbsoluteLayout;->mPaddingLeft:I

    iget v7, v5, Landroid/widget/AbsoluteLayout$LayoutParams;->x:I

    add-int v1, v6, v7

    .line 119
    .local v1, "childLeft":I
    iget v6, p0, Landroid/widget/AbsoluteLayout;->mPaddingTop:I

    iget v7, v5, Landroid/widget/AbsoluteLayout$LayoutParams;->y:I

    add-int v2, v6, v7

    .line 120
    .local v2, "childTop":I
    invoke-virtual {v0}, Landroid/view/View;->getMeasuredWidth()I

    move-result v6

    add-int/2addr v6, v1

    invoke-virtual {v0}, Landroid/view/View;->getMeasuredHeight()I

    move-result v7

    add-int/2addr v7, v2

    invoke-virtual {v0, v1, v2, v6, v7}, Landroid/view/View;->layout(IIII)V

    .line 111
    .end local v1    # "childLeft":I
    .end local v2    # "childTop":I
    .end local v5    # "lp":Landroid/widget/AbsoluteLayout$LayoutParams;
    :cond_0
    add-int/lit8 v4, v4, 0x1

    goto :goto_0

    .line 126
    .end local v0    # "child":Landroid/view/View;
    :cond_1
    return-void
.end method

.method protected onMeasure(II)V
    .locals 11
    .param p1, "widthMeasureSpec"    # I
    .param p2, "heightMeasureSpec"    # I

    .prologue
    const/4 v10, 0x0

    .line 57
    invoke-virtual {p0}, Landroid/widget/AbsoluteLayout;->getChildCount()I

    move-result v3

    .line 59
    .local v3, "count":I
    const/4 v6, 0x0

    .line 60
    .local v6, "maxHeight":I
    const/4 v7, 0x0

    .line 63
    .local v7, "maxWidth":I
    invoke-virtual {p0, p1, p2}, Landroid/widget/AbsoluteLayout;->measureChildren(II)V

    .line 66
    const/4 v4, 0x0

    .local v4, "i":I
    :goto_0
    if-ge v4, v3, :cond_1

    .line 67
    invoke-virtual {p0, v4}, Landroid/widget/AbsoluteLayout;->getChildAt(I)Landroid/view/View;

    move-result-object v0

    .line 68
    .local v0, "child":Landroid/view/View;
    invoke-virtual {v0}, Landroid/view/View;->getVisibility()I

    move-result v8

    const/16 v9, 0x8

    if-eq v8, v9, :cond_0

    .line 72
    invoke-virtual {v0}, Landroid/view/View;->getLayoutParams()Landroid/view/ViewGroup$LayoutParams;

    move-result-object v5

    check-cast v5, Landroid/widget/AbsoluteLayout$LayoutParams;

    .line 75
    .local v5, "lp":Landroid/widget/AbsoluteLayout$LayoutParams;
    iget v8, v5, Landroid/widget/AbsoluteLayout$LayoutParams;->x:I

    invoke-virtual {v0}, Landroid/view/View;->getMeasuredWidth()I

    move-result v9

    add-int v2, v8, v9

    .line 76
    .local v2, "childRight":I
    iget v8, v5, Landroid/widget/AbsoluteLayout$LayoutParams;->y:I

    invoke-virtual {v0}, Landroid/view/View;->getMeasuredHeight()I

    move-result v9

    add-int v1, v8, v9

    .line 78
    .local v1, "childBottom":I
    invoke-static {v7, v2}, Ljava/lang/Math;->max(II)I

    move-result v7

    .line 79
    invoke-static {v6, v1}, Ljava/lang/Math;->max(II)I

    move-result v6

    .line 66
    .end local v1    # "childBottom":I
    .end local v2    # "childRight":I
    .end local v5    # "lp":Landroid/widget/AbsoluteLayout$LayoutParams;
    :cond_0
    add-int/lit8 v4, v4, 0x1

    goto :goto_0

    .line 84
    .end local v0    # "child":Landroid/view/View;
    :cond_1
    iget v8, p0, Landroid/widget/AbsoluteLayout;->mPaddingLeft:I

    iget v9, p0, Landroid/widget/AbsoluteLayout;->mPaddingRight:I

    add-int/2addr v8, v9

    add-int/2addr v7, v8

    .line 85
    iget v8, p0, Landroid/widget/AbsoluteLayout;->mPaddingTop:I

    iget v9, p0, Landroid/widget/AbsoluteLayout;->mPaddingBottom:I

    add-int/2addr v8, v9

    add-int/2addr v6, v8

    .line 88
    invoke-virtual {p0}, Landroid/widget/AbsoluteLayout;->getSuggestedMinimumHeight()I

    move-result v8

    invoke-static {v6, v8}, Ljava/lang/Math;->max(II)I

    move-result v6

    .line 89
    invoke-virtual {p0}, Landroid/widget/AbsoluteLayout;->getSuggestedMinimumWidth()I

    move-result v8

    invoke-static {v7, v8}, Ljava/lang/Math;->max(II)I

    move-result v7

    .line 91
    invoke-static {v7, p1, v10}, Landroid/widget/AbsoluteLayout;->resolveSizeAndState(III)I

    move-result v8

    invoke-static {v6, p2, v10}, Landroid/widget/AbsoluteLayout;->resolveSizeAndState(III)I

    move-result v9

    invoke-virtual {p0, v8, v9}, Landroid/widget/AbsoluteLayout;->setMeasuredDimension(II)V

    .line 93
    return-void
.end method

.method public shouldDelayChildPressedState()Z
    .locals 1

    .prologue
    .line 146
    const/4 v0, 0x0

    return v0
.end method


text:
// device.h
// author: ulno
// created: 2018-07-16
//
// One ulnoiot device (actor or sensor connected to node)

// General note, in ulnoiot, we pass as convenience all values as strings.
// So other types have to be converted in such a as string or from one.

#ifndef _ULNOIOT_DEVICE_H_
#define _ULNOIOT_DEVICE_H_

#include <functional>
#include <AsyncMqttClient.h>

#include <ulnoiot-default.h>
#include <toolbox.h>

class Subdevice {
    private:
        Ustring name; // subdevice name (added to the device name)
        bool _subscribed = false;
        void init(const char* subname, bool subscribed);
        #define ULNOIOT_ON_RECEIVE_CALLBACK std::function<bool(const Ustring&)>
        ULNOIOT_ON_RECEIVE_CALLBACK receive_cb = NULL;
    public:
        Ustring measured_value; // the just measured value (after calling measure)
        Ustring current_value;
        Ustring& value() { return current_value; }
        Ustring& get() { return current_value; }
        Subdevice& with_receive_cb(ULNOIOT_ON_RECEIVE_CALLBACK cb) {
            receive_cb = cb;
            return *this;
        }
        bool call_receive_cb(Ustring& payload);
        const Ustring& get_name() const { return name; }
        const Ustring& key() const { return name; }
        bool subscribed() { return _subscribed; }
        Subdevice(const char* subname, bool subscribed) {
            init(subname, subscribed);
        }
        Subdevice(const char* subname) {
            init(subname, false);
        }
};

class Device {
    protected:
        Fixed_Map<Subdevice, ULNOIOT_MAX_SUBDEVICES> subdevices;
    private:
        Ustring name; // device name and mqtt-topic extension
        bool _ignore_case = true;
        bool _report_change = true;
        bool _needs_publishing = false;

        // This is the callback which is called based on a value change
        // it gets passed the triggering device. Last measured values can be
        // read from the globally defined device.
        // TODO: commented example
        #define ULNOIOT_ON_CHANGE_CALLBACK std::function<void()>
        ULNOIOT_ON_CHANGE_CALLBACK _on_change_cb=NULL;

        // This is the callback which is used for filtering and influencing values
        // It does not get the current device passed as parameter. The value can
        // be read from measured_value in the globally defined device. This
        // measure_value can be now modified. It is declared valid via
        // returning true and invalid via returning false or returning an empty
        // string (set first char to 0).
        // TODO: commented example
        #define ULNOIOT_FILTER_CALLBACK std::function<bool()>
        ULNOIOT_FILTER_CALLBACK _filter_cb=NULL;

    protected:
        bool _started = false;

    public:
        Device(const char* _name);
        //// Getters & Setters
        Device& with_ignore_case(bool ignore_case) {
            _ignore_case = ignore_case;
            return *this;
        }
        Device& set_ignore_case(bool ignore_case) {
            return with_ignore_case(ignore_case);
        }

        bool get_ignore_case() {
            return _ignore_case;
        }

        void call_on_change_callback() {
            if(_on_change_cb != NULL) {
                _on_change_cb();
            }
        }

        bool needs_publishing() {
            return _needs_publishing;
        }

        // publish current value(s) and resets needs_publishing state
        bool publish(AsyncMqttClient& mqtt_client, Ustring& node_topic);

        Ustring& value(unsigned long index);
        Ustring& value() { return value(0); }
        Ustring& measured_value(unsigned long index);
        Ustring& measured_value() { return measured_value(0); }
        const Ustring& get_name() const { return name; }
        //const char* get_name() const { return name.as_cstr(); }
        const Ustring& key() const { return name; }

        virtual ~Device() {
            // usually nothing has to be done here
            // This virtual method needs to be defined to prevent warning
            // from cpp-compiler
        }

        Device& with_report_change(bool report_change) {
            _report_change = report_change;
            return *this;
        }
        Device& set_report_change(bool report_change) {
            return with_report_change(report_change);
        }
        Device& report_change(bool report_change) {
            return with_report_change(report_change);
        }
        Device& with_on_change_callback(ULNOIOT_ON_CHANGE_CALLBACK on_change_cb) {
            _on_change_cb = on_change_cb;
            return *this;
        }
        Device& set_on_change_callback(ULNOIOT_ON_CHANGE_CALLBACK on_change_cb) {
            return with_on_change_callback(on_change_cb);
        }
        Device& with_on_change(ULNOIOT_ON_CHANGE_CALLBACK on_change_cb) {
            return with_on_change_callback(on_change_cb);
        }
        Device& set_on_change(ULNOIOT_ON_CHANGE_CALLBACK on_change_cb) {
            return with_on_change_callback(on_change_cb);
        }
        Device& on_change(ULNOIOT_ON_CHANGE_CALLBACK on_change_cb) {
            return with_on_change_callback(on_change_cb);
        }
        Device& on_change_callback(ULNOIOT_ON_CHANGE_CALLBACK on_change_cb) {
            return with_on_change_callback(on_change_cb);
        }
        Device& with_filter_callback(ULNOIOT_FILTER_CALLBACK filter_cb) {
            _filter_cb = filter_cb;
            return *this;
        }
        Device& set_filter_callback(ULNOIOT_FILTER_CALLBACK filter_cb) {
            return with_filter_callback(filter_cb);
        }
        Device& with_filter(ULNOIOT_FILTER_CALLBACK filter_cb) {
            return with_filter_callback(filter_cb);
        }
        Device& set_filter(ULNOIOT_FILTER_CALLBACK filter_cb) {
            return with_filter_callback(filter_cb);
        }
        Device& filter(ULNOIOT_FILTER_CALLBACK filter_cb) {
            return with_filter_callback(filter_cb);
        }
        Device& filter_callback(ULNOIOT_FILTER_CALLBACK filter_cb) {
            return with_filter_callback(filter_cb);
        }

        Subdevice* add_subdevice(Subdevice* sd) {
            ulog("add_subdevice: device: %s subdev: >%s<", name.as_cstr(), sd->get_name().as_cstr());
            if(subdevices.add(sd)) {
                ulog("add_subdevice >%s< succeeded.", sd->get_name().as_cstr());
                return sd;
            } else {
                ulog("add_subdevice >%s< failed.", sd->get_name().as_cstr());
                return NULL;
            }
        }

        Subdevice* subdevice(unsigned long index) {
            return subdevices.get(index);
        }

        bool subdevices_for_each(std::function<bool(Subdevice&)> func) {
            return subdevices.for_each(func);
        }

        bool started() { return _started; }

        /* poll_measure
         * This calls measure and filters and sets if necessary default values.
         * This will be called very often from event loop
         * Will return if current measurement was successful or invalid.
         * */
        bool poll_measure();

        /* check_changes
         * returns True if new values were measured and sets the publishing flag
         * This will be called very often from event loop
         * This only reports change when the measured (and filtered)
         * value is new (has changed) and report_changes is set.
         * If a change happened and a callback is set, the callback is called.
         * */
        bool check_changes();

        /* measure_init
         * Can be overloaded to allow re-initialization of some hardware
         * elements. For example a respective i2c bus due to a very weird
         * implementation of TwoWire in Wire.h
         * */
        virtual void measure_init() {}; // usually do nothing here

        /* start
         * This usually needs to be overwritten
         * Any physical initialization has to go here.
         * This is executed by the system right after all the rest has been
         * intialized - right before the first subscription.
         * If something with the physical initialization goes wrong, started
         * should stay false. If physical intitialization worked this method
         * needs to set _started to true;
         * TODO: make protected?
         * */
        virtual void start() { _started = true; }

        /* measure
         * Does nothing by default.
         * Usually this needs to be overwritten.
         * It should make sure to trigger necessary steps to
         * measure from the physical hardware a sensor value (or
         * several values from a multi sensor).
         * It needs to set in measured_value the currently measured value.
         * If no value can be measured (or has not been), it should return
         * false. If measuring was successful, return True.
         * This is called from update to trigger the actual value generation.
         * If device is not marked as started, measure will not be called.
         * TODO: make protected?
         * */
        virtual bool measure() { return true; }
};

//// Some filters
// TODO: check how to turn this in a functor class that does not die when used
#define filter_average(TYPE, buflen, dev) [&] { \
        static TYPE sum = 0; \
        static size_t values_count = 0; \
        TYPE v; \
        if(std::is_same<TYPE, double>::value) { \
            v = dev.measured_value().as_float(); \
        } else { \
            v = dev.measured_value().as_int(); \
        } \
        sum += v; \
        values_count ++; \
        if(values_count >= buflen) { \
            dev.measured_value().from(sum/values_count); \
            values_count = 0; \
            sum = 0; \
            return true; \
        } \
        return false; \
    }

/* The Jeff McClintock running median estimate.
 * base: https://stackoverflow.com/questions/10930732/c-efficiently-calculating-a-running-median
 * */
#define filter_jmc_median(update_ms, dev) [&] { \
        static double median = 0.0; \
        static double average = 0.0; \
        static unsigned long last_time = millis(); \
        double sample = dev.measured_value().as_float(); \
        average += ( sample - average ) * 0.1; \
        median += copysign( average * 0.01, sample - median ); \
        unsigned long current = millis() ; \
        if(current - last_time >= update_ms) { \
            dev.measured_value().from(average); \
            last_time = current; \
            return true; \
        } \
        return false; \
    }

/* Derivation of jmc median over small time intervals */
#define filter_jmc_interval_median(interval, dev) [&] { \
        static double median; \
        static double average; \
        static bool undefined = true; \
        static unsigned long start_time; \
        if(undefined) { \
            start_time = millis(); \
            median = 0.0; \
            average = 0.0; \
            undefined = false; \
        } \
        double sample = dev.measured_value().as_float(); \
        average += ( sample - average ) * 0.1; \
        median += copysign( average * 0.01, sample - median ); \
        unsigned long current = millis() ; \
        if(current - start_time >= interval) { \
            dev.measured_value().from(average); \
            undefined = true; /* trigger reset */ \
            return true; \
        } \
        return false; \
    }

/* Turn analog values into binary with a threshold level */
#define filter_binarize(cutoff, high, low, dev) [&] { \
        if(dev.measured_value().equals(low)) return false; \
        if(dev.measured_value().equals(high)) return false; \
        double sample = dev.measured_value().as_float(); \
        if(sample>=cutoff) { \
            dev.measured_value().from(high); \
        } else { \
            dev.measured_value().from(low); \
        } \
        return true; \
    }

/* round to the next multiple of base */
#define filter_round(base, dev) [&] { \
        long v = (long)(dev.measured_value().as_float()/(base)+0.5); \
        dev.measured_value().from(v*(base)); \
        return true; \
    }

/* return maximum one value per time interval (interval in ms) */
#define filter_limit_time(interval, dev) [&] { \
        static unsigned long last_time; \
        unsigned long current = millis() ; \
        if(!dev.measured_value().empty() \
           && current - last_time >= interval) { \
            last_time = current; \
            return true; \
        } \
        return false; \
    }

#endif // _ULNOIOT_DEVICE_H_

redpajama_set_name: RedPajamaGithub


text:
//Open source under MIT license. https://github.com/PrismTower/BigInteger

#include "BigInteger.h"

namespace UPmath
{
	std::random_device gRandomDevice;

	const BigInteger BigInteger::kBigInteger_0 = BigInteger(0);
	const BigInteger BigInteger::kBigInteger_1 = BigInteger(1);

	BigInteger::BigInteger() { }

	BigInteger::BigInteger(int num)
	{
		if (num) {
			if (num < 0) { negativity = true; num = -num; }
			(_valPtr = new uint32[capacity = size = 1])[0] = num;
		}
	}

	BigInteger::BigInteger(long long num) : BigInteger((unsigned long long)(num < 0 ? -num : num)) { negativity = (num < 0); }
	BigInteger::BigInteger(unsigned long long num)
	{
		static_assert(sizeof(long long) / sizeof(uint32) == 2, "Compile error in BigInteger(long long)");
		_valPtr = new uint32[capacity = 2];
		if (num) _valPtr[0] = static_cast<uint32>(num), ++size;
		num >>= BITS_OF_DWORD;
		if (num) _valPtr[1] = static_cast<uint32>(num), ++size;
	}

	BigInteger::BigInteger(bool isHexadecimal, const std::string& str)
	{
		int i = 0, strLen = (int)str.length(), t;
		bool neg_ = false;
		if (str[i] == '-') { neg_ = true; ++i; }
		else if (str[i] == '+') ++i;
		if (!isHexadecimal)
		{
			while (i < strLen && (t = (int)str[i] - '0') >= 0 && t < 10) {
				BigInteger tupi = *this <<= 1;
				*this <<= 2; *this += tupi; *this += BigInteger(t);
				++i;
			}
		}
		else
		{
			(_valPtr = new uint32[capacity = 1])[0] = 0;
			if (strLen >= 2 && ( ('\x5F' & str[i + 1]) == 'X')) i += 2;
			while (i < strLen && (t = (int)str[i] - '0') >= 0) {
				if (t > 9) {
					t = (int)(str[i] & '\x5F') - 'A' + 10;
					if ((t < 10) | (t >= 16)) break;
				}
				*this <<= 4;
				this->_valPtr[0] |= t;
				if (size == 0 && t) ++size;
				++i;
			}
		}
		negativity = neg_;
	}

	BigInteger::BigInteger(const BigInteger& source)
	{
		negativity = source.negativity;
		size = source.size;
		capacity = _getMinimumCapacity(size);
		_valPtr = new uint32[capacity];
		uint32 *_temptr = _valPtr, *_srcptr = source._valPtr;
		for (uint32* _comptr = _temptr + size; _temptr < _comptr; ++_temptr, ++_srcptr)	*_temptr = *_srcptr;
	}

	const BigInteger& BigInteger::operator=(const BigInteger& source)
	{
		if (this == &source) return *this;
		if (source.size > this->capacity) {
			delete[] this->_valPtr;
			this->_valPtr = new uint32[this->capacity = _getMinimumCapacity(source.size)];
		}
		negativity = source.negativity;
		size = source.size;
		uint32 *_temptr = _valPtr, *_srcptr = source._valPtr;
		for (uint32* _comptr = _temptr + size; _temptr < _comptr; ++_temptr, ++_srcptr)	*_temptr = *_srcptr;
		return *this;
	}

	const BigInteger& BigInteger::operator=(BigInteger&& source)
	{
		delete[] _valPtr;
		_valPtr = source._valPtr;
		negativity = source.negativity;
		capacity = source.capacity;
		size = source.size;
		source._valPtr = nullptr;
		source.capacity = source.size = 0;
		return *this;
	}

	BigInteger::BigInteger(BigInteger&& source)
	{
		_valPtr = source._valPtr;
		negativity = source.negativity;
		capacity = source.capacity;
		size = source.size;
		source._valPtr = nullptr;
		source.capacity = source.size = 0;
	}

	BigInteger::BigInteger(const std::string& str) :
		BigInteger((str.length() >= 2 && str[0] == '0' && (('\x5F' & str[1]) == 'X')), str) { }

	void BigInteger::_setSize(uint32 maxPossibleSize)
	{
		if ((size = maxPossibleSize))
			for (uint32* ptr = _valPtr + size; --ptr >= _valPtr; --size)
				if (*ptr) break;
	}

	unsigned char BigInteger::_requiredCapacityList[129] = 	{
		0, 1, 2, 4, 4, 8, 8, 8, 8, 16, 16, 16, 16, 16, 16, 16, 16, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
		64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
		128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
		128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 };

	uint32 BigInteger::_calcMinimumCapacity(uint32 size_)
	{
		uint32 minCap = (size_ < sizeof(_requiredCapacityList)) ? 1 : 256;
		while (size_ > minCap) minCap <<= 1;
		return minCap;
	}

	int BigInteger::compareAbsoluteValueTo(const BigInteger& rhs) const
	{
		if (size != rhs.size)
			return (size > rhs.size) ? 1 : -1;
		for (uint32 i = size; i > 0; ) {
			--i;
			if (_valPtr[i] != rhs._valPtr[i])
				return (_valPtr[i] > rhs._valPtr[i]) ? 1 : -1;
		}
		return 0;
	}

	int BigInteger::compareTo(const BigInteger& rhs) const
	{
		if (negativity != rhs.negativity) {
			if (0 == (size | rhs.size)) return 0;
			return negativity ? -1 : 1;
		}
		int result = compareAbsoluteValueTo(rhs);
		return negativity ? -result : result;
	}

	//only if abs(rhs) <= abs(*this)
	void BigInteger::_absSubtract(const BigInteger& rhs)
	{
		bool borrowFlag = false;
		uint32* ptr = _valPtr;
		for (uint32 ti = 0; ti < rhs.size; ++ti, ++ptr) {
			uint32 temp = *ptr;
			*ptr -= rhs._valPtr[ti];
			*ptr -= borrowFlag;
			borrowFlag = (*ptr > temp) | ((*ptr == temp) & borrowFlag);
		}
		if (borrowFlag) while (true) if ((*(ptr++))--) break;
		_setSize(size);
	}

	const BigInteger& BigInteger::operator+=(const BigInteger& rhs)
	{
		if (this == &rhs) *this <<= 1;
		else if (negativity == rhs.negativity)
		{
			uint32 commonPiecesCount = (size > rhs.size) ? rhs.size : size;
			uint32 *l_ptr, *r_ptr, *c_ptr;
			if (commonPiecesCount != rhs.size)
			{//rhs is longer
				if (capacity < rhs.size) {
					uint32* newptr = new uint32[capacity = _getMinimumCapacity(rhs.size)];
					for (c_ptr = (l_ptr = _valPtr) + size; l_ptr < c_ptr; ++newptr, ++l_ptr) *newptr = *l_ptr;
					delete[] _valPtr;
					_valPtr = newptr - size;
				}
				l_ptr = _valPtr + size;
				r_ptr = rhs._valPtr + size;
				c_ptr = rhs._valPtr + (size = rhs.size);
				while (r_ptr < c_ptr) *(l_ptr++) = *(r_ptr++);
			}
			l_ptr = _valPtr;
			r_ptr = rhs._valPtr;
			bool carryFlag = false;
			for (c_ptr = rhs._valPtr + commonPiecesCount; r_ptr < c_ptr; ++l_ptr, ++r_ptr)
			{
				*l_ptr += *r_ptr;
				*l_ptr += carryFlag;
				carryFlag = (*l_ptr < *r_ptr) | ((*l_ptr == *r_ptr) & carryFlag);
			}
			if (carryFlag) {
				for (c_ptr = _valPtr + size; l_ptr < c_ptr; ++l_ptr) if (++*l_ptr) break;
				if (l_ptr == c_ptr) {
					if (capacity > size)
						_valPtr[size++] = 1;
					else {
						l_ptr = new uint32[capacity <<= 1];
						c_ptr = l_ptr + size;
						while (l_ptr < c_ptr) *(l_ptr++) = *(_valPtr++);
						*l_ptr = 1;
						delete[] (_valPtr -= size);
						_valPtr = l_ptr - size++;
					}
				}
			}
		}
		else if (compareAbsoluteValueTo(rhs) >= 0)
			this->_absSubtract(rhs);
		else
		{
			BigInteger absGreaterOne(rhs);
			absGreaterOne._absSubtract(*this);
			*this = std::move(absGreaterOne);
		}
		return *this;
	}

	const BigInteger& BigInteger::operator-=(const BigInteger& rhs)
	{
		if (this == &rhs) { this->size = 0; return *this; }
		_SharedMemBigInteger signModified_rhs(rhs);
		signModified_rhs.negativity = !rhs.negativity;
		*this += signModified_rhs;
		return *this;
	}

	const BigInteger& BigInteger::operator>>=(const uint32 shift)
	{
		uint32 a = shift / BITS_OF_DWORD;
		if (a >= size) { this->size = 0; return *this; }
		else if (a) {
			uint32 i = 0;
			size -= a;
			do {
				_valPtr[i] = _valPtr[i + a];
				++i;
			} while (i < size);
			for (a += size; i < a; ++i) _valPtr[i] = 0;
		}
		a = shift & (BITS_OF_DWORD - 1);
		if (a && size)
		{
			uint32 pm1 = size - 1;
			for (uint32 i = 0; i < pm1; ++i)
				_valPtr[i] = (_valPtr[i] >> a) | ((_valPtr[i + 1] & ((1 << a) - 1)) << (32 - a));
			if (0 == (_valPtr[pm1] >>= a)) --size;
		}
		return *this;
	}

	const BigInteger& BigInteger::operator<<=(const uint32 shift)
	{
		if (size)
		{
			uint32 a = shift / BITS_OF_DWORD, b = shift & (BITS_OF_DWORD - 1);
			bool newMemAlloced = false;
			if (b) ++a;
			if (a) {
				uint32 *souptr, *tarptr, *comptr;
				if (capacity < (size += a)) {
					newMemAlloced = true;
					capacity = _getMinimumCapacity(size);
					tarptr = new uint32[capacity];
					comptr = tarptr + size;
					tarptr += capacity;
					while (tarptr > comptr) *(--tarptr) = 0;
				}
				else
					tarptr = _valPtr + size;
				souptr = _valPtr + (size - a);
				while (souptr > _valPtr) *(--tarptr) = *(--souptr);
				for (comptr = tarptr - a; tarptr > comptr; ) *(--tarptr) = 0;
				if (newMemAlloced) {
					delete[] _valPtr;
					_valPtr = tarptr;
				}
			}
			if (b) *this >>= (BITS_OF_DWORD - b);
		}
		return *this;
	}

	BigInteger operator*(const BigInteger& lhs, const BigInteger& rhs)
	{//multipication
		BigInteger ret = BigInteger::_absMultiply(lhs, rhs);
		ret.negativity = (lhs.negativity != rhs.negativity);
		return ret;
	}

	void BigInteger::_seperateToHigherAndLowerHalfs(BigInteger* dst) const
	{
		uint32 halfCapacity = capacity >> 1;
		dst[0]._valPtr = _valPtr + halfCapacity;
		dst[0].size = (size < halfCapacity) ? 0 : size - halfCapacity;
		dst[0].capacity = _getMinimumCapacity(dst[0].size);
		dst[1]._valPtr = _valPtr;
		dst[1]._setSize((size < halfCapacity) ? size : halfCapacity);
		dst[1].capacity = _getMinimumCapacity(dst[1].size);
	}

	BigInteger BigInteger::_absMultiply(const BigInteger& lhs, const BigInteger& rhs)
	{
		if ((!lhs.size) | (!rhs.size)) return BigInteger();
#ifdef FFT_MULTIPLICATION
		uint32 sizeSum = lhs.size + rhs.size;
		if (sizeSum == 2) return BigInteger((unsigned long long)lhs._valPtr[0] * rhs._valPtr[0]);
		if (sizeSum <= FFT_MAX_N / (BITS_OF_DWORD / FFT_WORD_BITLEN)) {
			BigInteger ret;
			_FFTMultiply(ret, lhs, rhs);
			return ret;
		}
#endif
		if (lhs.capacity != rhs.capacity)
		{
			const BigInteger& longer = (lhs.capacity >= rhs.capacity) ? lhs : rhs;
			const BigInteger& shorter = (lhs.capacity >= rhs.capacity) ? rhs : lhs;
			unsigned char _sharedMemBigIntegers[2 * sizeof(BigInteger)];
			BigInteger* sharedMemeoryBigIntegers = reinterpret_cast<BigInteger*>(_sharedMemBigIntegers);
			longer._seperateToHigherAndLowerHalfs(sharedMemeoryBigIntegers);//initialize read only variables
			BigInteger ret = _absMultiply(sharedMemeoryBigIntegers[0], shorter);
			ret <<= (longer.capacity << 4);
			ret += _absMultiply(sharedMemeoryBigIntegers[1], shorter);
			return ret;
		}
		if (lhs.capacity > 1)
		{
			unsigned char _sharedMemBigIntegers[4 * sizeof(BigInteger)];
			BigInteger *lhsParts = reinterpret_cast<BigInteger*>(_sharedMemBigIntegers), *rhsParts = 2 + lhsParts;//read only variables
			lhs._seperateToHigherAndLowerHalfs(lhsParts);
			rhs._seperateToHigherAndLowerHalfs(rhsParts);//initialize read only variables
			BigInteger higher_part = _absMultiply(lhsParts[0], rhsParts[0]);
			BigInteger lower_part = _absMultiply(lhsParts[1], rhsParts[1]);
			BigInteger mid_part = higher_part + lower_part;
			mid_part += ((lhsParts[1] - lhsParts[0]) * (rhsParts[0] - rhsParts[1]));
			higher_part <<= (lhs.capacity * BITS_OF_DWORD);
			mid_part <<= (lhs.capacity * (BITS_OF_DWORD / 2));
			higher_part += (mid_part += lower_part);
			return higher_part;
		}
		return BigInteger((unsigned long long)*lhs._valPtr * *rhs._valPtr);
	}

	//Set *this to remainder and return the quotient.
	//It is ok to execute this->absDivideAndSetThisToRemainder(*this)
	BigInteger BigInteger::absDivideAndSetThisToRemainder(const BigInteger& rhs)
	{
		int pDiff = this->size - rhs.size;
		if (0 == rhs.size) throw std::logic_error("Divide by zero");
		if (pDiff < 0) return BigInteger();
		int pow = pDiff * BITS_OF_DWORD;
		int lhsLeftmostBitLen = 0, rhsLeftmostBitLen = 0;
		for (uint32 lhsLeftmost = _valPtr[size - 1], rhsLeftmost = rhs._valPtr[rhs.size - 1]; lhsLeftmost | rhsLeftmost; ) {
			if (lhsLeftmost) ++lhsLeftmostBitLen;
			if (rhsLeftmost) ++rhsLeftmostBitLen;
			lhsLeftmost >>= 1; rhsLeftmost >>= 1;
		}
		pow += 1 + lhsLeftmostBitLen - rhsLeftmostBitLen;
		if (pow <= 0) return BigInteger();
		BigInteger newrhs(rhs);//ok if &rhs == this
		newrhs <<= --pow;
		int leftMostBit = pow;
		bool fillOne = !(newrhs.compareAbsoluteValueTo(*this) > 0);
		if (fillOne)
			this->_absSubtract(newrhs);
		else if (--leftMostBit < 0)
			return BigInteger();
		bool* binaryList = new bool[pow + 1];
		binaryList[pow] = fillOne;
		while (--pow >= 0) {
			newrhs >>= 1;
			fillOne = binaryList[pow] = !(newrhs.compareAbsoluteValueTo(*this) > 0);
			if (fillOne) this->_absSubtract(newrhs);
		}
		BigInteger ret;
		ret.size = 1 + ((uint32)leftMostBit / BITS_OF_DWORD);
		ret._valPtr = new uint32[ret.capacity = _getMinimumCapacity(ret.size)];
		for (uint32 piece = 0; pow < leftMostBit; ++piece) {
			ret._valPtr[piece] = 0;
			int biMax = leftMostBit - pow;
			if (biMax > BITS_OF_DWORD) biMax = BITS_OF_DWORD;
			for (int bi = 0; bi < biMax; ++bi)
				ret._valPtr[piece] |= ((uint32)binaryList[++pow] << bi);
		}
		delete[] binaryList;
		return ret;
	}

	const BigInteger& BigInteger::operator/=(const BigInteger& rhs)
	{
		bool neg_ = (this->negativity != rhs.negativity);
		*this = this->absDivideAndSetThisToRemainder(rhs);
		this->negativity = neg_;
		return *this;
	}

	const BigInteger& BigInteger::operator%=(const BigInteger& rhs)
	{
		this->absDivideAndSetThisToRemainder(rhs);
		return *this;
	}

	int BigInteger::intValue() const
	{
		if (size == 0) return 0;
		int ret = _valPtr[0] & 0x7FFFFFFF;
		return negativity ? -ret : ret;
	}

	double BigInteger::doubleValue() const
	{
		double ret = 0.0;
		for (uint32 i = 0; i < size; ++i) {
			ret *= (double)0x100000000;
			ret += _valPtr[i];
		}
		return negativity ? -ret : ret;
	}

	const std::string BigInteger::toString() const
	{
		if (size == 0) return std::string("0");
		uint32 t = (size * 10) + 2;
		char* buffer = new char[t];
		char* c = buffer + t;
		*(--c) = '\0';
		const BigInteger ten(10);
		BigInteger* newthis = new BigInteger(*this);
		do {
			BigInteger* temptr = new BigInteger(newthis->absDivideAndSetThisToRemainder(ten));
			*(--c) = *(newthis->_valPtr) + '0';
			delete newthis;
			newthis = temptr;
		} while (newthis->size);
		delete newthis;
		if (negativity) *(--c) = '-';
		std::string ret(c);
		delete[] buffer;
		return ret;
	}

	char* BigInteger::toHexadecimalCharArray() const
	{
		char* c_str = new char[(size << 3) + 2];
		char* c = c_str;
		if (size)
		{
			if (negativity) *(c++) = '-';
			uint32 *v_ptr;
			for (v_ptr = _valPtr + size; v_ptr > _valPtr; ) {
				uint32 piece = *(--v_ptr), shifting = BITS_OF_DWORD;
				do {
					shifting -= 4;
					uint32 letter = (piece >> shifting) & 0xF;
					*(c++) = (letter > 9) ? ('A' - 10 + letter) : ('0' + letter);
				} while (shifting);
			}
		}
		else *(c++) = '0';
		*c = '\0';
		return c_str;
	}

	bool* BigInteger::convertAbsToBinaryArray(size_t* out_digitsSize) const
	{
		if (!this->size) {
			*out_digitsSize = 0;
			return nullptr;
		}
		size_t digitsSize = this->size * BITS_OF_DWORD;
		bool* ret = new bool[digitsSize];
		for (uint32 i = 0, pieceIndex = 0; pieceIndex < this->size; ++pieceIndex, i += BITS_OF_DWORD)
		{
			uint32 piece = this->_valPtr[pieceIndex];
			ret[i + 0] = (piece & (1 << 0)) != 0; ret[i + 1] = (piece & (1 << 1)) != 0;	ret[i + 2] = (piece & (1 << 2)) != 0; ret[i + 3] = (piece & (1 << 3)) != 0;
			ret[i + 4] = (piece & (1 << 4)) != 0; ret[i + 5] = (piece & (1 << 5)) != 0;	ret[i + 6] = (piece & (1 << 6)) != 0; ret[i + 7] = (piece & (1 << 7)) != 0;
			ret[i + 8] = (piece & (1 << 8)) != 0; ret[i + 9] = (piece & (1 << 9)) != 0; ret[i + 10] = (piece & (1 << 10)) != 0; ret[i + 11] = (piece & (1 << 11)) != 0;
			ret[i + 12] = (piece & (1 << 12)) != 0;	ret[i + 13] = (piece & (1 << 13)) != 0;	ret[i + 14] = (piece & (1 << 14)) != 0;	ret[i + 15] = (piece & (1 << 15)) != 0;
			static_assert(BITS_OF_DWORD == 32, "convertAbsToBinaryArray");
			ret[i + 16] = (piece & (1 << 16)) != 0;	ret[i + 17] = (piece & (1 << 17)) != 0;	ret[i + 18] = (piece & (1 << 18)) != 0;	ret[i + 19] = (piece & (1 << 19)) != 0;
			ret[i + 20] = (piece & (1 << 20)) != 0;	ret[i + 21] = (piece & (1 << 21)) != 0;	ret[i + 22] = (piece & (1 << 22)) != 0;	ret[i + 23] = (piece & (1 << 23)) != 0;
			ret[i + 24] = (piece & (1 << 24)) != 0;	ret[i + 25] = (piece & (1 << 25)) != 0;	ret[i + 26] = (piece & (1 << 26)) != 0;	ret[i + 27] = (piece & (1 << 27)) != 0;
			ret[i + 28] = (piece & (1 << 28)) != 0;	ret[i + 29] = (piece & (1 << 29)) != 0;	ret[i + 30] = (piece & (1 << 30)) != 0;	ret[i + 31] = (piece & (1 << 31)) != 0;
		}
		if (out_digitsSize) {
			do { --digitsSize; } while (!ret[digitsSize]);
			*out_digitsSize = ++digitsSize;
		}
		return ret;
	}

	size_t BigInteger::getBitLength() const
	{
		if (size == 0) return 0;
		size_t lowerBound = size * BITS_OF_DWORD - BITS_OF_DWORD;
		uint32 x = _valPtr[size - 1];
		while (x) { ++lowerBound; x >>= 1; }
		return lowerBound;
	}

	BigInteger BigInteger::sqrt(bool ceilling) const
	{//x = (prev_x + *this/prev_x) / 2
		if (this->negativity && this->size != 0) throw std::logic_error("Cannot evaluate square root of a negative Biginteger.");
		BigInteger x(1), prev_x;
		do {
			prev_x = x;
			x += *this / prev_x;
			x >>= 1;
		} while (x != prev_x);
		if (ceilling) {
			BigInteger xSquared = x * x;
			if (xSquared < *this) x += kBigInteger_1;
		}
		return x;
	}

	BigInteger BigInteger::pow(uint32 positive_exponent) const
	{
		if (0 == positive_exponent) return BigInteger(1);
		BigInteger t = this->pow(positive_exponent >> 1);
		BigInteger tSquared = _absMultiply(t, t);
		if (positive_exponent & 1) {
			BigInteger ret = _absMultiply(*this, tSquared);
			ret.negativity = this->negativity;
			return ret;
		}
		return tSquared;
	}

	//`m` must be a odd number and larger than BigInteger(2) to apply montgomeryModPow method
	BigInteger BigInteger::modPow(const BigInteger& exponent, const BigInteger& m) const
	{
		if (0 == exponent.size) return BigInteger(1);
		if ((0 == m.size) | m.negativity) throw std::logic_error("modular for `modPow` function must be positive.");
		if (1 == (m._valPtr[0] | m.size)) return BigInteger(0);
		bool montgomeryModPow = m._valPtr[0] & 1;
		size_t digitsSizeOfExponent;
		bool* binaryArrayOfExponent = exponent.convertAbsToBinaryArray(&digitsSizeOfExponent);
		BigInteger base = exponent.negativity ? this->modInverse(m) : *this;
		if (base.compareAbsoluteValueTo(m) > 0) base.absDivideAndSetThisToRemainder(m);
		if (base.negativity) base += m;
		BigInteger result = !montgomeryModPow ?
			base._trivialModPow(binaryArrayOfExponent, digitsSizeOfExponent, m) :
			base._montgomeryModPow(binaryArrayOfExponent, digitsSizeOfExponent, m);
		delete[] binaryArrayOfExponent;
		return result;
	}

	BigInteger BigInteger::_trivialModPow(bool* binaryArrayOfExponent, size_t bitsOfExponent, const BigInteger& m) const
	{
		BigInteger result(1), newResult;
		BigInteger tSquared(*this), thisPow_i;
		for (size_t i = 0; i < bitsOfExponent; ++i) {
			thisPow_i = std::move(tSquared);
			if (binaryArrayOfExponent[i]) {
				newResult = _absMultiply(result, thisPow_i);
				newResult.absDivideAndSetThisToRemainder(m);
				result = std::move(newResult);
			}
			tSquared = _absMultiply(thisPow_i, thisPow_i);
			tSquared.absDivideAndSetThisToRemainder(m);
		}
		return result;
	}

	//http://www.hackersdelight.org/MontgomeryMultiplication.pdf
	BigInteger BigInteger::_montgomeryModPow(bool* binaryArrayOfExponent, size_t bitsOfExponent, const BigInteger& m) const
	{
		BigInteger r(1);
		r <<= m.size * BITS_OF_DWORD;
		BigInteger r_tmp(r), m_tmp(m);
		_EEAstruct eeaStruct = _extendedEuclid(&r_tmp, &m_tmp);
		BigInteger r_slash = std::move(*eeaStruct.x);
		BigInteger m_slash = std::move(*eeaStruct.y); m_slash.negativity = !m_slash.negativity;
		delete eeaStruct.d; delete eeaStruct.x; delete eeaStruct.y;

		BigInteger result_mf(r), newResult;
		BigInteger thisPow_2i(*this * r), thisPow_i;
		result_mf.absDivideAndSetThisToRemainder(m);
		thisPow_2i.absDivideAndSetThisToRemainder(m);
		for (size_t i = 0; i < bitsOfExponent; ++i) {
			thisPow_i = std::move(thisPow_2i);
			if (binaryArrayOfExponent[i]) {
				newResult = result_mf * thisPow_i;//t = a_ * b_
				BigInteger tm_slash = newResult * m_slash;//tm'
				if (tm_slash.size > m.size) tm_slash.size = m.size;//tm' mod r
				newResult += tm_slash * m;// (t + (tm' mod r)m)
				newResult >>= BITS_OF_DWORD * m.size;//u = (t + (tm' mod r)m) / r
				if (newResult.compareAbsoluteValueTo(m) >= 0) newResult._absSubtract(m);//if (u >= m) return u - m;
				result_mf = std::move(newResult);
			}
			thisPow_2i = thisPow_i * thisPow_i;
			BigInteger tm_slash = thisPow_2i * m_slash;
			if (tm_slash.size > m.size) tm_slash.size = m.size;
			thisPow_2i += tm_slash * m;
			thisPow_2i >>= BITS_OF_DWORD * m.size;
			if (thisPow_2i.compareAbsoluteValueTo(m) >= 0) thisPow_2i._absSubtract(m);
		}

		BigInteger result = result_mf * r.modInverse(m);
		result.absDivideAndSetThisToRemainder(m);
		if (result < 0) result += m;
		return result;
	}

	//return BigInteger(0) when the inverse doesnot exist
	BigInteger BigInteger::modInverse(const BigInteger& m) const
	{
		if ((0 == m.size) | m.negativity) throw std::logic_error("modular for `modInverse` function must be positive.");
		if (gcd(*this, m) != kBigInteger_1) return BigInteger(0);
		BigInteger a_(*this), m_(m);
		_EEAstruct eeaStruct = _extendedEuclid(&a_, &m_);
		BigInteger ddd = *this * *eeaStruct.x + m * *eeaStruct.y;
		BigInteger ret = std::move(*eeaStruct.x);
		delete eeaStruct.d; delete eeaStruct.x; delete eeaStruct.y;
		if (ret.negativity) ret += m;
		return ret;
	}

	BigInteger::_EEAstruct BigInteger::_extendedEuclid(BigInteger* a, BigInteger* b)
	{
		if (b->size == 0) return BigInteger::_EEAstruct{ new BigInteger(*a), new BigInteger(1), new BigInteger(0) };
		bool neg_ = (a->negativity != b->negativity);
		BigInteger quotient = a->absDivideAndSetThisToRemainder(*b);
		quotient.negativity = neg_;
		BigInteger::_EEAstruct ts = _extendedEuclid(b, a);
		*ts.x -= quotient * *ts.y;
		return BigInteger::_EEAstruct{ ts.d, ts.y, ts.x };
	}

	BigInteger BigInteger::gcd(const BigInteger& a, const BigInteger& b)
	{
		BigInteger a_(a), b_(b);
		BigInteger* result = _euclidGcd(&a_, &b_);
		BigInteger ret = std::move(*result);
		ret.negativity = false;
		return ret;
	}

	BigInteger* BigInteger::_euclidGcd(BigInteger* a, BigInteger* b)
	{
		if (b->size == 0) return a;
		a->absDivideAndSetThisToRemainder(*b);
		return _euclidGcd(b, a);
	}

	//Set `confidenceFactor` <= 0 to run Deterministic Robin-Miller Primality Test.
	//When testing integers contain more than 1000 bits, it makes it a LITTLE BIT faster to
	//set `confidenceFactor` to a positive number at the expense of
	//the probability of getting a wrong result is no more than 4^(-confidenceFactor)
	bool BigInteger::isPrime(int confidenceFactor) const
	{
		if (0 == size || negativity) return false;
		if (1 == size && _valPtr[0] <= 3) return (_valPtr[0] > 1);
		if ((_valPtr[0] & 1) == 0) return false;
		BigInteger thisMinus1(*this); thisMinus1 += BigInteger(-1);
		double ln_n = log(size * BITS_OF_DWORD);
		int maxTesterForDeterministicResult = (int)(2.0 * ln_n * ln_n);
		BigInteger a(1);
		if (size <= 2) goto qwordTest;
		if (maxTesterForDeterministicResult <= confidenceFactor) goto drmpt;
		if (confidenceFactor > 0)
		{
qwordTest:	const char kTestNumbers[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 };
			int index = 0;
			do {
				a._valPtr[0] = kTestNumbers[index];
				if (a.compareAbsoluteValueTo(thisMinus1) >= 0) return true;
				if (!_MillerRabinPrimalityTest(a, thisMinus1)) return false;
			} while (++index < sizeof(kTestNumbers) / sizeof(char));
			if (size > 2) {
				confidenceFactor -= (sizeof(kTestNumbers) / sizeof(char));
				std::mt19937 mt(gRandomDevice());
				do {
					a._valPtr[0] = mt();
					if (a._valPtr[0] < 41) a._valPtr[0] += 41;
					if (!_MillerRabinPrimalityTest(a, thisMinus1)) return false;
				} while (--confidenceFactor > 0);
			}
		}
		else
		{
drmpt:		uint32 base = 2;
			do {
				a._valPtr[0] = base;
				if (!_MillerRabinPrimalityTest(a, thisMinus1)) return false;
			} while (++base <= (uint32)maxTesterForDeterministicResult);
		}
		return true;
	}

	//	http://www.sti15.com/nt/pseudoprimes.html
	bool BigInteger::weakerBailliePSWPrimeTest() const
	{
		if (0 == size || negativity) return false;
		if (1 == size && _valPtr[0] <= 3) return (_valPtr[0] > 1);
		if ((_valPtr[0] & 1) == 0) return false;
		BigInteger thisMinus1(*this); thisMinus1 += BigInteger(-1);
		BigInteger a(2);
		if (!_MillerRabinPrimalityTest(a, thisMinus1)) return false;
		if (_LucasPseudoprimeTest()) {
			a._valPtr[0] = 3;
			if (_MillerRabinPrimalityTest(a, thisMinus1)) return true;
			throw std::logic_error("Severe logic flaw detected during `weakerBailliePSWPrimeTest`, please report this issue.");
		}
		return false;
	}

	bool BigInteger::_MillerRabinPrimalityTest(const BigInteger& a, const BigInteger& thisMinus1) const
	{//logically wrong when *this <= 2
		if (a.modPow(thisMinus1, *this) != kBigInteger_1) return false;
		BigInteger u(thisMinus1);
		do { u >>= 1; } while ((u._valPtr[0] & 1) == 0);
		BigInteger x = a.modPow(u, *this);
		do {
			BigInteger y = _absMultiply(x, x);
			y.absDivideAndSetThisToRemainder(*this);
			if (y == kBigInteger_1 && x != kBigInteger_1 && x != thisMinus1) return false;
			x = std::move(y);
			u <<= 1;
		} while (u < *this);
		if (x != kBigInteger_1) return false;
		return true;
	}

	//Calculating the Jacobi symbol according to the properties at https://en.wikipedia.org/wiki/Jacobi_symbol
	int BigInteger::JacobiSymbol(const BigInteger& upperArgument, const BigInteger& lowerArgument)
	{
		if ((!lowerArgument.testBit(0)) | lowerArgument.negativity)
			throw std::logic_error("lowerArgument of function `JacobiSymbol` must be a positive odd number.");
		BigInteger denominator(lowerArgument);
		BigInteger numerator(upperArgument);
		if (numerator.negativity) {
			numerator.absDivideAndSetThisToRemainder(denominator);
			numerator += denominator;
		}
		return _JacobiSymbolImpl(&numerator, &denominator);
	}

	//	http://math.fau.edu/richman/jacobi.htm
	int BigInteger::_JacobiSymbolImpl(BigInteger* numerator, BigInteger* denominator)
	{
		if (denominator->size == 1 && denominator->_valPtr[0] == 1) return 1;//"Following the normal convention for the empty product, (Z / 1) = 1 for all `Z` "
		if (numerator->size == 0) return 0;
		numerator->absDivideAndSetThisToRemainder(*denominator);
		unsigned countFactorsOf2 = 0;
		for (; false == numerator->testBit(0) && numerator->size != 0; *numerator >>= 1) ++countFactorsOf2;
		if (gcd(*numerator, *denominator) != 1) return 0;
		int ret = 1;
		if (countFactorsOf2 & 1) {
			uint32 m = denominator->_valPtr[0] % 8;
			ret = ((m == 1) | (m == 7)) ? 1 : -1;
		}
		if (denominator->_valPtr[0] % 4 == 3 && numerator->_valPtr[0] % 4 == 3) ret = -ret;
		return ret * _JacobiSymbolImpl(denominator, numerator);
	}

	//	http://stackoverflow.com/questions/38343738/lucas-probable-prime-test
	std::pair<BigInteger, BigInteger> BigInteger::_getModLucasSequence(const BigInteger& k, const BigInteger& D, const BigInteger& P, const BigInteger& Q) const
	{
		BigInteger U_n(1), V_n(P), Q_n(Q);
		if (V_n < 0) { V_n.absDivideAndSetThisToRemainder(*this); V_n += *this; }
		if (Q_n < 0) { Q_n.absDivideAndSetThisToRemainder(*this); Q_n += *this;	}
		BigInteger U(!k.testBit(0) ? 0 : 1);
		BigInteger V(!k.testBit(0) ? 2 : V_n);
		BigInteger n(k);
		n >>= 1;
		while (n.size)
		{
			BigInteger U2 = _absMultiply(U_n, V_n);
			U2.absDivideAndSetThisToRemainder(*this);
			BigInteger V2 = _absMultiply(V_n, V_n);
			V2 -= (Q_n << 1);
			V2.absDivideAndSetThisToRemainder(*this);
			if (V2 < 0) V2 += *this;
			BigInteger Q2 = _absMultiply(Q_n, Q_n);
			Q2.absDivideAndSetThisToRemainder(*this);
			if ((n._valPtr[0] & 1)) {
				BigInteger newU = _absMultiply(U, V2) + _absMultiply(V, U2);
				if (newU.testBit(0)) newU += *this;
				newU >>= 1;
				newU.absDivideAndSetThisToRemainder(*this);
				BigInteger newV = _absMultiply(V, V2) + _absMultiply(U, U2) * D;
				if (newV.testBit(0)) newV += *this;
				newV >>= 1;
				newV.absDivideAndSetThisToRemainder(*this);
				if (newV < 0) newV += *this;
				U = std::move(newU);
				V = std::move(newV);
			}
			U_n = std::move(U2);
			V_n = std::move(V2);
			Q_n = std::move(Q2);
			n >>= 1;
		}
		return std::pair<BigInteger, BigInteger>(U, V);
	}

	bool BigInteger::_LucasPseudoprimeTest() const
	{//logically wrong when *this is small
		int D = 5;
		do {
			if (gcd(D, *this) != 1) return 0;
			if (JacobiSymbol(D, *this) == -1) break;
			D = -D + ((D < 0) ? 2 : -2);
		} while (true);
		const BigInteger Q((1 - D) / 4);
		BigInteger deltaThis(*this); deltaThis += 1;
		std::pair<BigInteger, BigInteger> UV = this->_getModLucasSequence(deltaThis, D, 1, Q);
		return (UV.first.size == 0);
	}

	//Warnning: not suitable when *this has more than 10k bits
	BigInteger BigInteger::nextProbablePrime() const
	{
		if (this->negativity || this->size == 0) return BigInteger(2);
		BigInteger ret(*this);
		if (ret.size == 1)
			while (true) if ((ret += kBigInteger_1).isPrime()) return ret;
		if ((ret._valPtr[0] & 1) == 0) ++ret._valPtr[0];
		else ret += 2;
		const char kTestNumbers[] = { 3, 5, 7, 11, 13, 17, 19, 23 };
		BigInteger m(2);
		static_assert(sizeof(char) == 1, "");
		uint32 modList[sizeof(kTestNumbers)];
		for (int i = 0; i < sizeof(kTestNumbers); ++i) {
			m._valPtr[0] = kTestNumbers[i];
			BigInteger x(ret);
			x.absDivideAndSetThisToRemainder(m);
			modList[i] = x.size ? x._valPtr[0] : 0;
		}
		while (true)
		{
			bool multipleOfTestNumbers = false;
			for (int i = 0; i < sizeof(kTestNumbers); ++i) {
				if (0 == modList[i] % kTestNumbers[i]) multipleOfTestNumbers = true;
				modList[i] += 2;//it may overflow until we find a next prime if *this is very large
			}
			if (!multipleOfTestNumbers && ret.weakerBailliePSWPrimeTest()) return ret;
			ret += 2;
		}
	}

	//for cryptography
	BigInteger::BigInteger(const void* dataPtr, size_t dataSize)
	{
		size = (dataSize + sizeof(uint32) - 1) / sizeof(uint32);
		_valPtr = new uint32[capacity = _getMinimumCapacity(size)];
		memcpy(_valPtr, dataPtr, dataSize);
		memset(reinterpret_cast<char*>(_valPtr) + dataSize, 0, capacity * sizeof(uint32) - dataSize);
		_setSize(size);
	}

	void BigInteger::saveBytesToBuffer(char* dst, size_t writingSize) const
	{
		size_t integerSizeInByte = size * sizeof(uint32);
		if (integerSizeInByte >= writingSize) memcpy(dst, _valPtr, writingSize);
		else {
			memcpy(dst, _valPtr, integerSizeInByte);
			memset(dst + integerSizeInByte, 0, writingSize - integerSizeInByte);
		}
	}

	void BigInteger::setLowerBitsToRandom(uint32 bitLength)
	{
		if (bitLength == 0) return;
		std::mt19937 mt(gRandomDevice());
		uint32 newSize = (bitLength + BITS_OF_DWORD - 1) / BITS_OF_DWORD;
		if (newSize > size)	{
			size = newSize;
			if (size > capacity) _valPtr = new uint32[capacity = _getMinimumCapacity(size)];
			_valPtr[size - 1] = 0;
		}
		uint32 i = 0;
		while (bitLength >= BITS_OF_DWORD) {
			_valPtr[i++] ^= mt();
			bitLength -= BITS_OF_DWORD;
		}
		if (bitLength) _valPtr[i] ^= (mt() & ((1 << bitLength) - 1));
		_setSize(size);
	}

	bool BigInteger::testBit(uint32 bitPos) const
	{
		uint32 dwordIndex = bitPos / BITS_OF_DWORD;
		if (dwordIndex >= size) return false;
		uint32 bitIndex = bitPos % BITS_OF_DWORD;
		return 0 != (_valPtr[dwordIndex] & (1 << bitIndex));
	}

	BigInteger::_SharedMemBigInteger::_SharedMemBigInteger(uint32 size_, uint32* val)
	{
		_valPtr = val;
		_setSize(size_);
		capacity = _getMinimumCapacity(size);
	}

#ifdef FFT_MULTIPLICATION
	bool BigInteger::_isRootsOfUnityInitialized = false;

	namespace BigInteger_FFT_Precedures
	{
		struct Complex {
			double re, im;
			Complex(double _re = 0.0, double _im = 0.0) : re(_re), im(_im) { }
			static Complex add(const Complex& lhs, const Complex& rhs) { return Complex(lhs.re + rhs.re, lhs.im + rhs.im); }
			static Complex subtract(const Complex& lhs, const Complex& rhs) { return Complex(lhs.re - rhs.re, lhs.im - rhs.im); }
			static Complex multiply(const Complex& lhs, const Complex& rhs) { return Complex(lhs.re * rhs.re - lhs.im * rhs.im, lhs.re * rhs.im + lhs.im * rhs.re); }
		};

#define FFT_WORD_SIZE (FFT_WORD_BITLEN / 8)
		/*const union {
		uint32 uint_value;
		char char_value[4];
		} _EndianCheckUnion = { 0x11223344 };
		constexpr bool _IS_LITTLE_ENDIAN() { return _EndianCheckUnion.char_value[0] == 0x44; }*/

		struct Coefficients {
			unsigned short *begin, *end;
			static_assert(sizeof(unsigned short) == FFT_WORD_SIZE, "Length of FFT_WORD is 16bits, which differs from sizeof(unsigned short).");
			uint32 interval;
			uint32 n;
			Coefficients(const BigInteger& src, uint32 n) : interval(1), n(n) { src._FFTgetBeginAndEndOfVal(begin, end); }
			inline Complex getComplexNumber(uint32 i) const
			{
				if (_IS_LITTLE_ENDIAN())
					return Complex(begin + i < end ? (double)begin[i] : 0.0);
				else {//WARNING: no tests has been done for big endian machines.
					if (begin + i >= end) return Complex();
					if ((size_t)begin & FFT_WORD_SIZE) return (double)begin[i - 1];
					return (double)begin[i + 1];
				}
			}
		};

		struct ValueRepresentation {
			Complex* begin;
			uint32 interval;
			uint32 n;
			ValueRepresentation(Complex* src, uint32 n) : interval(1), n(n), begin(src) { }
			inline const Complex& getComplexNumber(uint32 i) const { return begin[i]; }
		};

		Complex kRootsOfUnity[FFT_MAX_N];
		void initRootsOfUnity()
		{
			const double scale = 6.2831853071795864769 / FFT_MAX_N;
			for (int i = 0; i < FFT_MAX_N; ++i) {
				kRootsOfUnity[i].re = cos(i * scale);
				kRootsOfUnity[i].im = sin(i * scale);
			}
		}

		inline uint32 getIndexOfPower(uint32 omegaIndex, uint32 pow) { return (omegaIndex * pow) % FFT_MAX_N; }

		//`InputType` is either `Coefficients` (isReverse = false)  or  `ValueRepresentation` (isReverse = true for reverse transform)
		template <bool isReverse, typename InputType>
		void FFT(Complex* dst, InputType& src, uint32 omegaIndex)
		{//Warning: src.n cannot be smaller than 4
			if (src.n <= 4) {
				Complex x = src.getComplexNumber(0);
				Complex y = src.getComplexNumber(src.interval * 2);
				Complex buffer0 = Complex::add(x, y);
				Complex buffer1 = Complex::subtract(x, y);
				x = src.getComplexNumber(src.interval);
				y = src.getComplexNumber(src.interval * 3);
				Complex buffer2 = Complex::add(x, y);
				Complex buffer3 = Complex::subtract(x, y);
				Complex wjAo = buffer2;
				dst[0] = Complex::add(buffer0, wjAo);
				dst[2] = Complex::subtract(buffer0, wjAo);
				wjAo = !isReverse ? Complex(-buffer3.im, buffer3.re) : Complex(buffer3.im, -buffer3.re);
				dst[1] = Complex::add(buffer1, wjAo);
				dst[3] = Complex::subtract(buffer1, wjAo);
				return;
			}
			auto srcBeginBackup = src.begin + src.interval;
			src.interval <<= 1;
			src.n >>= 1;
			FFT<isReverse>(dst, src, getIndexOfPower(omegaIndex, 2));//A even
			std::swap(src.begin, srcBeginBackup);
			FFT<isReverse>(dst + src.n, src, getIndexOfPower(omegaIndex, 2));//A odd
			std::swap(src.begin, srcBeginBackup);
			for (uint32 j = 0; j < src.n; ++j) {
				Complex wjAo = Complex::multiply(kRootsOfUnity[getIndexOfPower(omegaIndex, j)], (dst + src.n)[j]);
				(dst + src.n)[j] = Complex::subtract(dst[j], wjAo);
				dst[j] = Complex::add(dst[j], wjAo);
			}
			src.interval >>= 1;
			src.n <<= 1;
		}

	}//namespace BigInteger_FFT_Precedures

	void BigInteger::_FFTMultiply(BigInteger& dst, const BigInteger& lhs, const BigInteger& rhs, void* buffer)
	{
		if ((!lhs.size) | (!rhs.size)) { dst.size = 0; return; }
		const uint32 n = _getMinimumCapacity(lhs.size + rhs.size) * BITS_OF_DWORD / FFT_WORD_BITLEN;
		const uint32 kOmegaIndex = FFT_MAX_N / n;
		if (0 == kOmegaIndex) { dst = _absMultiply(lhs, rhs); return; }
		if (!_isRootsOfUnityInitialized) {//initialize  (1 + 0i) ^ (1/n)
			BigInteger_FFT_Precedures::initRootsOfUnity();
			_isRootsOfUnityInitialized = true;
		}
		bool newMemAlloced = (nullptr == buffer);
		if (newMemAlloced) buffer = operator new(n * 2 * sizeof(BigInteger_FFT_Precedures::Complex));
		BigInteger_FFT_Precedures::Complex* _buffer = reinterpret_cast<BigInteger_FFT_Precedures::Complex*>(buffer);
		//multi-threading benefits little here
		BigInteger_FFT_Precedures::Coefficients A(lhs, n);
		BigInteger_FFT_Precedures::Complex* lhsValues = _buffer;
		BigInteger_FFT_Precedures::FFT<false>(lhsValues, A, kOmegaIndex);
		BigInteger_FFT_Precedures::Coefficients B(rhs, n);
		BigInteger_FFT_Precedures::Complex* rhsValues = lhsValues + n;
		BigInteger_FFT_Precedures::FFT<false>(rhsValues, B, kOmegaIndex);
		for (uint32 j = 0; j < n; ++j, ++rhsValues)
			*rhsValues = BigInteger_FFT_Precedures::Complex::multiply(*lhsValues++, *rhsValues);
		BigInteger_FFT_Precedures::ValueRepresentation C(rhsValues - n, n);//C[i] = A[i] * B[i]
		BigInteger_FFT_Precedures::Complex* products = _buffer;
		BigInteger_FFT_Precedures::FFT<true>(products, C, FFT_MAX_N - kOmegaIndex);

		uint32 newCapa = n / (BITS_OF_DWORD / FFT_WORD_BITLEN);
		if (newCapa > dst.capacity) {
			delete[] dst._valPtr;
			dst._valPtr = new uint32[dst.capacity = newCapa];
		}
		unsigned long long t = 0;
		static_assert(sizeof(unsigned long long) > sizeof(uint32), "");
		const double reciprocal_of_n = 1.0 / n;
		for (uint32 pieceIndex = 0; pieceIndex < newCapa; ++pieceIndex) {
			//double er = abs(round((products)->re / n) - (products)->re / n); if (er > __dbgFFTMaxError) __dbgFFTMaxError = er;
			t += (unsigned long long)((products++)->re * reciprocal_of_n + 0.5);
			dst._valPtr[pieceIndex] = t & ((1 << FFT_WORD_BITLEN) - 1);
			t >>= FFT_WORD_BITLEN;
			//er = abs(round((products)->re / n) - (products)->re / n); if (er > __dbgFFTMaxError) __dbgFFTMaxError = er;
			t += (unsigned long long)((products++)->re * reciprocal_of_n + 0.5);
			dst._valPtr[pieceIndex] |= (uint32(t) << FFT_WORD_BITLEN);
			t >>= FFT_WORD_BITLEN;
		}
		dst._setSize(newCapa);

		if (newMemAlloced) operator delete(buffer);
	}

#endif // FFT_MULTIPLICATION

}//namespace UPMath


text:
package com.navercorp.pinpoint.common.server.bo.codec.stat;

import com.navercorp.pinpoint.common.server.bo.stat.ActiveTraceBo;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * @author HyunGil Jeong
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-test.xml")
public class ActiveTraceEncoderTest extends AgentStatEncoderTestBase<ActiveTraceBo> {

    @Override
    protected List<ActiveTraceBo> createAgentStats(String agentId, long initialTimestamp, int numStats) {
        return TestAgentStatFactory.createActiveTraceBos(agentId, initialTimestamp, numStats);
    }
}


text:
* [FEA] Bump node deps
* [FIX] Use localizer methods programatically (without DOM)
* [FIX] Release package-lock.json
* [FIX] Add git-flow and release bumps support (releasing)


text:
package org.olat.course.groupsandrights.ui;

import org.olat.core.gui.translator.Translator;
import org.olat.course.groupsandrights.CourseGroupManager;
import org.olat.group.context.BGContext;

/**
 * Description:<BR/>
 * TODO: Class Description for DefaultContextTranslationHelper Initial Date: Mar 10, 2005
 *
 * @author gnaegi
 */
public class DefaultContextTranslationHelper {

	/**
	 * Returns a nicly translated name for the default context. If it is not a default context, nothing will be done and the contexts name will be returned
	 *
	 * @param context
	 * @param trans
	 * @return String
	 */
	public static String translateIfDefaultContextName(final BGContext context, final Translator trans) {
		String name = context.getName();
		if (name.indexOf(CourseGroupManager.DEFAULT_NAME_LC_PREFIX) == 0) {
			name = trans.translate("default.context") + " " + name.substring(CourseGroupManager.DEFAULT_NAME_LC_PREFIX.length());
		} else if (name.indexOf(CourseGroupManager.DEFAULT_NAME_RC_PREFIX) == 0) {
			name = trans.translate("default.context") + " " + name.substring(CourseGroupManager.DEFAULT_NAME_RC_PREFIX.length());
		}
		return name;
	}

}


text:
             Loading data ...

             There is a problem during fetching the data. Please try again later.

                <input class="search-query" ng-model="keyQuery" placeholder="search apps" />
                <button class="btn btn-primary" ng-click="queryUpdate()">Search</button>

                 Page Size

                    <input class="span3" ng-model="shownResult"/>
                    <button class="btn btn-success" ng-click="searchResults()">Change</button>

                Total Retrieved : {{ searchCount }}
                    out of {{ searchTotalCount}} total records

                        « Prev

                        {{ value }}

= totalPages}"
                    ng-click="nextPage()">

                        Next »

                        Load More

            Warning! Only 5 Applications can be Added, Try to remove existing application to continue

                Logo

                        App Name

                        Score

                        Price

                    Action
                    Loading

                        <input class="span8" id="localquery" ng-model="query"
                            placeholder="Filter Apps by Title and Description"
                            ng-change="searchResults()"/>

                    <button class="btn btn-primary"
                        data-toggle="collapse"
                        data-target="#description{{index}}"
                        ng-show="data.description != undefined">

                    </button>

                        {{ data.title }}

                            {{ data.description }}

                 {{ data.applause_score }}
                 {{ data.price }}

                    <button ng-show="isAppExists(data.app_id)"
                        class="btn btn-danger"
                        ng-click="removeApp(data.app_id)"
                        >
                         Remove
                    </button>
                    <button type="button" ng-hide="(isAppExists(data.app_id) || isAppAdding(data.app_id))"
                        class="btn btn-success"
                        ng-click="addApp(data.app_id)"
                        ng-disabled="!allowToAddApp(data.app_id)"
                        >
                        Add
                    </button>
                    <button type="button" ng-show="isAppAdding(data.app_id)"
                        class="btn btn-success"
                        disabled
                        >
                        Adding
                    </button>

                        « Prev

                        {{ value }}

= totalPages}"
                    ng-click="nextPage()">

                        Next »

                        Load More


text:
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Anima2D
{
	public class BlendShapeEditor : WindowEditorTool
	{
		public SpriteMeshCache spriteMeshCache;

		protected override string GetHeader() { return "Blendshapes"; }

		float windowHeight {
			get {
				return 80f;
			}
		}

		public BlendShapeEditor()
		{
			windowRect = new Rect(5f, 5f, 250, 45);
		}

		public override void OnWindowGUI(Rect viewRect)
		{
			windowRect.position = new Vector2(0f, -15f);

			base.OnWindowGUI(viewRect);
		}

		protected override void DoWindow(int windowId)
		{
			if(!spriteMeshCache)
			{
				//Debug.Log("No SpriteMeshCache");
				return;
			}

			if(!spriteMeshCache)
			{
				//Debug.Log("No SpriteMeshCache");
				return;
			}

			if(spriteMeshCache.blendshapes == null)
			{
				//Debug.Log("spriteMeshCache.blendshapes == null");
				return;
			}

			EditorGUIUtility.labelWidth = 50f;

			EditorGUILayout.BeginVertical();

			EditorGUILayout.BeginHorizontal();

			EditorGUI.BeginChangeCheck();

			int blendshapeIndex = spriteMeshCache.blendshapes.IndexOf(spriteMeshCache.selectedBlendshape);

			blendshapeIndex = EditorGUILayout.Popup(blendshapeIndex,GetBlendshapeNames(),GUILayout.Width(100f));

			if(EditorGUI.EndChangeCheck())
			{
				spriteMeshCache.RegisterUndo("select blendshape");
				spriteMeshCache.selectedBlendshape = spriteMeshCache.blendshapes[blendshapeIndex];
			}

			EditorGUILayout.Space();

			if(GUILayout.Button(new GUIContent("New", "Create a blend shape"),EditorStyles.miniButtonLeft,GUILayout.Width(50f)))
			{
				CreateBlendshape();
			}

			EditorGUI.BeginDisabledGroup(spriteMeshCache.selectedBlendshape == null);

			if(GUILayout.Button(new GUIContent("Delete", "Delete blend shape"),EditorStyles.miniButtonRight,GUILayout.Width(50f)))
			{
				DeleteBlendshape();
			}

			EditorGUI.EndDisabledGroup();

			EditorGUILayout.Space();

			EditorGUIUtility.fieldWidth = 35f;
			EditorGUIUtility.labelWidth = 1f;

			EditorGUI.BeginDisabledGroup(spriteMeshCache.selectedBlendshapeFrame == null);

			EditorGUILayout.LabelField("Frame:");

			if(GUILayout.Button(new GUIContent("Delete", "Delete frame"),EditorStyles.miniButtonLeft, GUILayout.Width(50f)))
			{
				DeleteFrame();
			}

			if(GUILayout.Button(new GUIContent("Reset", "Reset vertices"),EditorStyles.miniButtonRight, GUILayout.Width(50f)))
			{
				ResetVertices();
			}

			EditorGUI.EndDisabledGroup();

			GUILayout.Space(1f);

			EditorGUILayout.EndHorizontal();

			EditorGUILayout.EndVertical();
		}

		void CreateBlendshape()
		{
			if(spriteMeshCache)
			{
				BlendShape blendShape = spriteMeshCache.CreateBlendshape("New BlendShape", "Create BlendShape");

				spriteMeshCache.selectedBlendshape = blendShape;

				spriteMeshCache.CreateBlendShapeFrame(blendShape, 100f, "Create BlendShape");

				spriteMeshCache.blendShapeWeight = 100f;
			}
		}

		void DeleteBlendshape()
		{
			if(spriteMeshCache)
			{
				spriteMeshCache.DeleteBlendShape(spriteMeshCache.selectedBlendshape, "Delete BlendShape");
			}
		}

		void ResetVertices()
		{
			if(spriteMeshCache)
			{
				if(spriteMeshCache.selection.Count > 0)
				{
					spriteMeshCache.ResetVertices(spriteMeshCache.selectedNodes, "Reset vertices");
				}else{
					spriteMeshCache.ResetVertices(spriteMeshCache.nodes, "Reset vertices");
				}
			}
		}

		void DeleteFrame()
		{
			if(spriteMeshCache && spriteMeshCache.selectedBlendshapeFrame)
			{
				spriteMeshCache.DeleteBlendShapeFrame(spriteMeshCache.selectedBlendshape,
														spriteMeshCache.selectedBlendshapeFrame,
														"Delete frame");
			}
		}

		string[] GetBlendshapeNames()
		{
			if(spriteMeshCache && spriteMeshCache.blendshapes != null)
			{
				int i = 0;

				return spriteMeshCache.blendshapes.ConvertAll( b => (i++) + "  " + b.name).ToArray();
			}

			return new string[0];
		}
	}
}


text:
/**
 * @file Various information of the bot.
 * @author Ovyerus
 */

const fs = require('fs');
const path = require('path');
var version;

try {
    version = JSON.parse(fs.readFileSync(path.resolve(`${mainDir}`, '../', './package.json'))).version;
} catch(_) {
    version = JSON.parse(fs.readFileSync(path.resolve(`${mainDir}`, './package.json'))).version;
}

exports.commands = [
    'info'
];

exports.info = {
    desc: 'Information about the bot.',
    async main(bot, ctx) {
        let roleColour = ctx.guildBot.roles.sort((a, b) => ctx.guild.roles.get(b).position - ctx.guild.roles.get(a).position)[0];
        roleColour = roleColour ? ctx.guild.roles.get(roleColour).color : 0;

        await ctx.createMessage({embed: {
            title: `${bot.user.username}'s Info`,
            description: `[${bot.localeManager.t('info-source')}](https://github.com/ClarityMoe/Clara) | [${bot.localeManager.t('info-supportServer')}](https://discord.gg/rmMTZue)`,
            thumbnail: {url: bot.user.avatarURL},
            footer: {text: 'info-footer'},
            color: roleColour,
            fields: [
                {
                    name: 'info-guilds',
                    value: bot.guilds.size,
                    inline: true
                },
                {
                    name: 'info-users',
                    value: bot.users.size,
                    inline: true
                },
                {
                    name: 'info-uptime',
                    value: utils.msToTime(bot.uptime),
                    inline: true
                },
                {
                    name: 'info-shards',
                    value: bot.shards.size,
                    inline: true
                },
                {
                    name: 'info-mem',
                    value: utils.genBytes(process.memoryUsage().rss),
                    inline: true
                },
                {
                    name: 'info-version',
                    value: version, inline:
                    true
                }
            ]
        }}, null, 'channel', {name: bot.user.username});
    }
};


text:
from datetime import timedelta, datetime
import logging
from random import choice
from string import ascii_letters, digits

from pymongo import MongoClient

class Moth(object):
    '''
    :class:`Moth` requires the credentials to log in to MongoDB.
    '''
    def __init__(self, database='moth', host='localhost', port=27017,
                 user=None, pwd=None):
        '''
        Moth uses a mongo back-end (although other data stores may be added
        later) __init__ creates a mongo connection with the passed credentials.
        '''
        if user and pwd:
            connection_string = 'mongodb://%s:%s@%s:%s' % \
                                (user, pwd, host, port)
            self.db = MongoClient(connection_string)[database]
        else:
            self.db = MongoClient(host, port)[database]

    def create_token(self, email, ip=None, expire=None, token_size=64,
                     retval=None):
        '''
        Generate a token of a given length, tied to email address, and store it.
        Optionally store IP address, expiration (in days), and retval (see
        set_retval for additional information on this).
        Return the token
        '''
        token = ''.join(
            choice(ascii_letters + digits) for x in range(token_size)
        )

        payload = {'email': email.lower(), 'token': token}
        if ip: payload.update(ip=ip)
        if expire:
            expire = (datetime.now() + timedelta(days=expire)).strftime('%s')
            payload.update(expire=expire)

        self.db.tokens.insert(payload)

        if retval:
            self.set_retval(email, retval)

        return token

    def auth_token(self, email, token, ip=None):
        '''
        Return True if email address and token match. If IP exists, also verify
        that. If expiration was set when ``create_token`` was called, verify
        that the token hasn't expired.  If for any reason the token is not
        valid, remove it.
        '''
        criteria = {'email': email.lower(), 'token': token}
        if ip: criteria.update(ip=ip)

        data = self.db.tokens.find_one(criteria)
        if not data: return False

        token_ip = data.get('ip', None)
        if token_ip is not None and token_ip != ip:
            self.remove_token(token, email)
            return False

        token_expire = data.get('expire', None)
        if token_expire and token_expire < datetime.now().strftime('%s'):
            self.remove_token(token, email)
            return False

        return self.fetch_retval(email)

    def remove_user(self, email):
        '''
        Remove all user data from Moth.
        '''
        self.db.tokens.remove({'email': email.lower()})
        self.db.retvals.remove({'email': email.lower()})

    def remove_token(self, email, token):
        '''
        Remove token from Moth.
        '''
        return self.db.tokens.remove({'email': email.lower(), 'token': token})

    def set_retval(self, email, retval):
        '''
        Store retval associated with the email address.
        When auth_token is called, if the authentication was successful, and a
        retval exists, it will be returned by the ``auth_token`` call. If retval
        does not exist, auth_token returns True.
        '''
        return self.db.retvals.update({'email': email.lower()},
                                      {'email': email.lower(),
                                       'retval': retval},
                                      upsert=True)

    def fetch_retval(self, email):
        '''
        If retval exists, return it.
        If it doesn't, return True.
        '''
        retval = self.db.retvals.find_one({'email': email.lower()})
        if retval is None:
            return True
        return retval.get('retval', True)


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.datafactory.models;

import com.azure.resourcemanager.datafactory.fluent.models.TriggerQueryResponseInner;
import java.util.List;

/** An immutable client-side representation of TriggerQueryResponse. */
public interface TriggerQueryResponse {
    /**
     * Gets the value property: List of triggers.
     *
     * @return the value value.
     */
    List<TriggerResource> value();

    /**
     * Gets the continuationToken property: The continuation token for getting the next page of results, if any
     * remaining results exist, null otherwise.
     *
     * @return the continuationToken value.
     */
    String continuationToken();

    /**
     * Gets the inner com.azure.resourcemanager.datafactory.fluent.models.TriggerQueryResponseInner object.
     *
     * @return the inner object.
     */
    TriggerQueryResponseInner innerModel();
}


text:
import datetime

from .settings import is_development
import json

def info(msg):
    print("[tabnine] {} | {}".format(_time(), msg))

def debug(msg, if_development=True):
    if if_development and is_development():
        info(msg)

def jsonstr(obj):
    debug(json.dumps(obj, indent=2))

def _time():
    return datetime.datetime.now().strftime("%m/%d/%y %H:%M:%S.%f")[:-3]


text:
package io.reflectoring.argumentresolver;

import lombok.Value;

@Value
class GitRepositoryId {

  private final long value;

}


text:
package com.opencsv;

import javax.xml.bind.DatatypeConverter;
import java.io.Closeable;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * Created by Tyler on 30/12/2016.
 */
public class ResultSetHelperService implements Closeable {
    // note: we want to maintain compatibility with Java 5 VM's
    // These types don't exist in Java 5
    public static int RESULT_FETCH_SIZE = 10000;
    public static int MAX_FETCH_ROWS = -1;
    public static boolean IS_TRIM = false;
    public static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    public static String DEFAULT_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
    public int columnCount;
    public String[] columnNames;
    public String[] columnTypes;
    public String[] columnClassName;
    public int[] columnTypesI;
    public Object[] rowObject;
    public long cost = 0;
    private SimpleDateFormat dateFormat;
    private SimpleDateFormat timeFormat;
    private SimpleDateFormat TimeTZFormat1;
    private DateTimeFormatter timeTZFormat;
    private ResultSet rs;
    private Object[] EOF = new Object[1];
    private ArrayBlockingQueue<Object[]> queue;
    private boolean isFinished = false;
    private static volatile boolean isAborted = false;

    /**
     * Default Constructor.
     */
    public ResultSetHelperService(ResultSet res, int fetchSize) throws SQLException {
        long sec = System.nanoTime();
        rs = res;
        rs.setFetchSize(fetchSize);

        RESULT_FETCH_SIZE = fetchSize;
        isAborted = false;
        try {
            rs.setFetchDirection(ResultSet.FETCH_FORWARD);
        } catch (Exception e) {
        }
        ResultSetMetaData metadata = rs.getMetaData();
        columnCount = metadata.getColumnCount();
        columnNames = new String[columnCount];
        columnTypes = new String[columnCount];
        columnClassName = new String[columnCount];
        columnTypesI = new int[columnCount];
        for (int i = 0; i < metadata.getColumnCount(); i++) {
            int type = metadata.getColumnType(i + 1);
            String value;
            switch (type) {
                case Types.JAVA_OBJECT:
                    value = "object";
                    break;
                case Types.BIT:
                case Types.BOOLEAN:
                    value = "boolean";
                    break;
                case Types.DECIMAL:
                case Types.DOUBLE:
                case Types.FLOAT:
                case Types.REAL:
                case Types.NUMERIC:
                    value = "double";
                    break;
                case Types.BIGINT:
                    value = "long";
                    break;
//               case Types.BIT:
                case Types.INTEGER:
                case Types.TINYINT:
                case Types.SMALLINT:
                    value = "int";
                    break;
                case Types.TIME:
                    value = "date";
                    break;
                case Types.DATE:
                    value = "date";
                    break;
                case Types.TIMESTAMP:
                case -100:
                    value = "timestamp";
                    break;
                case -101:
                case -102:
                    //case Types.TIME_WITH_TIMEZONE:
                    //case Types.TIMESTAMP_WITH_TIMEZONE:
                    value = "timestamptz";
                    break;
                case Types.BINARY:
                case Types.VARBINARY:
                case Types.LONGVARBINARY:
                    value = "raw";
                    break;
                case Types.CLOB:
                case Types.NCLOB:
                    value = "clob";
                    break;
                case Types.BLOB:
                    value = "blob";
                    break;
                case Types.SQLXML:
                    value = "xml";
                    break;
                case Types.LONGVARCHAR:
                case Types.LONGNVARCHAR:
                    value = "longtext";
                    break;
                default:
                    value = "string";
            }
            columnTypesI[i] = type;
            columnTypes[i] = value.intern();
            final String name=metadata.getColumnName(i + 1);
            columnNames[i] = (name==null?"":name).intern();
        }
        cost += System.nanoTime() - sec;
    }

    public static void abort() {
        isAborted = true;
    }

    public ResultSetHelperService(ResultSet res) throws SQLException {
        this(res, RESULT_FETCH_SIZE);
    }

    /**
     * Get all the column values from the result set.
     *
     * @return - String array containing all the column values.
     * @throws SQLException - thrown by the result set.
     * @throws IOException  - thrown by the result set.
     */
    public Object[] getColumnValues() throws SQLException, IOException {
        return this.getColumnValues(IS_TRIM, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT);
    }

    /**
     * Get all the column values from the result set.
     *
     * @param trim - values should have white spaces trimmed.
     * @return - String array containing all the column values.
     * @throws SQLException - thrown by the result set.
     * @throws IOException  - thrown by the result set.
     */
    public Object[] getColumnValues(boolean trim) throws SQLException, IOException {
        return this.getColumnValues(trim, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT);
    }

    /**
     * Get all the column values from the result set.
     *
     * @param trim             - values should have white spaces trimmed.
     * @param dateFormatString - format String for dates.
     * @param timeFormatString - format String for timestamps.
     * @return - String array containing all the column values.
     * @throws SQLException - thrown by the result set.
     * @throws IOException  - thrown by the result set.
     */
    public Object[] getColumnValues(boolean trim, String dateFormatString, String timeFormatString) throws SQLException, IOException {
        long sec = System.nanoTime();
        if (isAborted) {
            if (rs != null) rs.close();
            throw new IOException("Processing is aborted!");
        }
        if (rs == null || rs.isClosed() || !rs.next()) {
            if (rs != null) rs.close();
            cost += System.nanoTime() - sec;
            isFinished = true;
            return null;
        }
        if (rowObject == null) rowObject = new Object[columnCount];
        Object o = null;
        boolean isFetched;
        for (int i = 0; i < columnCount; i++) {
            isFetched = false;
            if (columnClassName[i] == null) {
                try {
                    o = rs.getObject(i + 1);
                } catch (SQLException e) {
                    o = null;
                }
                if (o != null) columnClassName[i] = o.getClass().getName();
                isFetched = true;
            }
            switch (columnTypes[i]) {
                case "timestamptz":
                    try {
                        o = rs.getObject(i + 1, ZonedDateTime.class);
                    } catch (AbstractMethodError ex2) {
                        o = rs.getTimestamp(i + 1);
                    } catch (Exception ex) {
                        try {
                            o = rs.getObject(i + 1, OffsetDateTime.class);
                        } catch (Exception ex1) {
                            o = rs.getTimestamp(i + 1);
                        }
                    }
                    break;
                case "timestamp":
                    o = rs.getTimestamp(i + 1);
                    break;
                case "raw":
                    o = rs.getString(i + 1);
                    break;
                case "blob":
                    Blob bl = rs.getBlob(i + 1);
                    if (bl != null) {
                        o = DatatypeConverter.printHexBinary(bl.getBytes(1, (int) bl.length()));
                        try {
                            bl.free();
                        } catch (Exception e) {
                        }
                    } else o = null;
                    break;
                case "clob":
                    Clob c = rs.getClob(i + 1);
                    if (c != null) {
                        o = c.getSubString(1, (int) c.length());
                        try {
                            c.free();
                        } catch (Exception e) {
                        }
                    } else o = null;
                    break;
                case "xml":
                    SQLXML x = rs.getSQLXML(i + 1);
                    try {
                        if (x != null) o = x.getString();
                        else o = null;
                    } catch (Exception e) {
                        o = isFetched ? o : rs.getObject(i + 1);
                    }
                    break;
                default:
                    try {
                        o = isFetched ? o : rs.getObject(i + 1);
                    } catch (SQLException e) {
                        o = null;
                    }
            }
            if (o != null && rs.wasNull()) o = null;
            if (queue == null) rowObject[i] = getColumnValue(o, i, trim, dateFormatString, timeFormatString);
            else rowObject[i] = o;
        }
        cost += System.nanoTime() - sec;
        return rowObject;
    }

    @Override
    public void close() {
        try {
            if (rs != null && !rs.isClosed()) rs.close();
        } catch (Exception e) {
        }
        queue = null;
    }

    /**
     * changes an object to a String.
     *
     * @param obj - Object to format.
     * @return - String value of an object or empty string if the object is null.
     */
    protected String handleObject(Object obj) {
        return obj == null ? "" : String.valueOf(obj);
    }

    protected String handleDate(Date date, String dateFormatString) {
        if (dateFormat == null) {
            DEFAULT_DATE_FORMAT = dateFormatString;
            dateFormat = new SimpleDateFormat(dateFormatString);
        }
        return date == null ? null : dateFormat.format(date);
    }

    protected String handleTimestamp(Timestamp timestamp, String timestampFormatString) {
        String result = null;
        if (timeFormat == null) {
            DEFAULT_TIMESTAMP_FORMAT = timestampFormatString;
            timeFormat = new SimpleDateFormat(timestampFormatString);
        }
        if (timestamp != null) {
            result = timeFormat.format(timestamp);
            if (result.endsWith(".0")) result = result.substring(0, result.length() - 2);
            else if (result.endsWith(".000")) result = result.substring(0, result.length() - 4);
        }
        return result;
    }

    protected String handleTimestampTZ(Object timestamp, String timestampFormatString) {
        if (timeTZFormat == null) {
            timeTZFormat = DateTimeFormatter.ofPattern(timestampFormatString + " X");
            TimeTZFormat1 = new SimpleDateFormat(timestampFormatString + " X");
        }
        if (timestamp == null) return null;
        if (timestamp instanceof OffsetDateTime) return ((OffsetDateTime) timestamp).format(timeTZFormat);
        else if (timestamp instanceof Timestamp) return TimeTZFormat1.format((Timestamp) timestamp);
        return ((ZonedDateTime) timestamp).format(timeTZFormat);
    }

    private Object getColumnValue(Object o, int colIndex, boolean trim, String dateFormatString, String timestampFormatString) throws SQLException, IOException {
        if (o == null) return null;
        String str;
        final double d;
        switch (columnTypes[colIndex]) {
            case "object":
                str = handleObject(o);
                break;
            case "boolean":
                return o;
            case "int":
                return ((Number) o).intValue();
            case "double":
            case "long":
                str = o.getClass().getSimpleName();
                if (str.equals(columnTypes[colIndex])) str = Character.toUpperCase(str.charAt(0)) + str.substring(1);
                columnTypes[colIndex] = str;
                return getColumnValue(o, colIndex, trim, dateFormatString, timestampFormatString);
            case "Double":
                d = ((Number) o).doubleValue();
                return d == (long) d ? (long) d : d;
            case "Float":
                return Double.valueOf(o.toString());
            case "Integer":
                return ((Number) o).intValue();
            case "Long":
                return ((Number) o).longValue();
            case "BigInteger":
                d = ((Number) o).doubleValue();
                if (o.toString().equals(new BigInteger(String.valueOf((long) d)))) return (long) d;
                return o;
            case "BigDecimal":
                d = ((Number) o).doubleValue();
                final long l = (long) d;
                if (d == l && o.toString().equals(BigInteger.valueOf(l))) return l;
                if (o.toString().equals(BigDecimal.valueOf(d).toString())) return d;
                return o.toString();
            case "date":
            case "time":
                str = handleDate((Date) o, dateFormatString);
                break;
            case "timestamp":
                try {
                    str = handleTimestamp((Timestamp) o, timestampFormatString);
                    if (columnClassName[colIndex].startsWith("oracle.sql.DATE")) {
                        int pos = str.lastIndexOf('.');
                        if (pos > 0) str = str.substring(0, pos - 1);
                    }
                } catch (Exception e) {
                    System.out.println(o + ":" + colIndex + ":" + columnClassName[colIndex] + ":" + columnNames[colIndex]);
                    throw e;
                }
                break;
            case "timestamptz":
                str = handleTimestampTZ(o, timestampFormatString);
                break;
            case "longraw":
                str = DatatypeConverter.printHexBinary((byte[]) o);
                break;
            default:
                if (o instanceof Number) {
                    d = ((Number) o).doubleValue();
                    return d == (long) d ? (long) d : d;
                }
                str = o.toString();
        }
        return trim ? str.trim() : str;
    }

    private volatile Exception exception = null;

    public void startAsyncFetch(final RowCallback callback, final boolean trim, final String dateFormatString, final String timeFormatString, int fetchRows) throws Exception {
        if (fetchRows == -1) queue = new ArrayBlockingQueue<>(RESULT_FETCH_SIZE * 2 + 10);
        else if (fetchRows > 0) {
            int size = Math.max(256, Math.min(fetchRows, RESULT_FETCH_SIZE));
            rs.getStatement().setMaxRows(fetchRows);
            if (size >= fetchRows / 2 && size < fetchRows) rs.setFetchSize(fetchRows / 2 + 1);
            else rs.setFetchSize(size);
            queue = new ArrayBlockingQueue<>(rs.getFetchSize() * 2 + 10);
        } else queue = new ArrayBlockingQueue<>(256);
        exception = null;
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (queue != null && !isFinished && (rowObject = new Object[columnCount]) != null)
                        queue.put(getColumnValues() == null ? EOF : rowObject);
                } catch (NullPointerException e0) {
                } catch (Exception e) {
                    try {
                        if (queue != null) queue.put(EOF);
                    } catch (Exception e1) {
                    }
                    exception = e;
                }
            }
        });
        t.setDaemon(true);
        t.start();

        Object[] values;
        int count = 0;
        while ((values = queue.take()) != EOF && (fetchRows < 0 || ++count < fetchRows)) {
            for (int i = 0; i < columnCount; i++)
                values[i] = getColumnValue(values[i], i, trim, dateFormatString, timeFormatString);
            callback.execute(values);
        }
        queue = null;
        t.join();
        if (exception != null) throw exception;
    }

    public void startAsyncFetch(final RowCallback c, boolean trim) throws Exception {
        startAsyncFetch(c, trim, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT, MAX_FETCH_ROWS);
    }

    public void startAsyncFetch(final RowCallback c) throws Exception {
        startAsyncFetch(c, IS_TRIM);
    }

    public Object[][] fetchRowsAsync(int rows) throws Exception {
        final ArrayList<Object[]> ary = new ArrayList();
        //ary.add(columnNames);
        startAsyncFetch(row -> ary.add(row.clone()), false, DEFAULT_DATE_FORMAT, DEFAULT_TIMESTAMP_FORMAT, rows);
        return ary.toArray(new Object[][]{});
    }

    public Object[][] fetchRows(int rows) throws Exception {
        queue = null;
        final ArrayList<Object[]> ary = new ArrayList();
        Object[] row;
        int counter = 0;
        if (rows > 0) rs.setFetchSize(rows <= 1000 ? rows : rows / 2);
        while (rows < 0 || ++counter <= rows) {
            row = getColumnValues();
            if (row == null) break;
            ary.add(row.clone());
        }
        return ary.toArray(new Object[][]{});
    }
}


text:
package com.hackaton.md3;

import static org.fest.assertions.Assertions.assertThat;
import io.dropwizard.testing.junit.DropwizardAppRule;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;

import com.coko.server.mdk3.App;
import com.coko.server.mdk3.Mdk3Configuration;
import com.coko.server.mdk3.representations.DataKTP;

//import com.dwbook.phonebook.representations.Contact;

public class ApplicationTest {
	private Client client;
	private DataKTP dataKTPForTest = new DataKTP();

	@ClassRule
	public static final DropwizardAppRule<Mdk3Configuration> RULE = new DropwizardAppRule<Mdk3Configuration>(App.class, "config.yaml");

	@Before
	public void setUp() {
		client = ClientBuilder.newClient();
		// Set the credentials to be used by the client
		HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("user", "superSecretPassword");
		client.register(feature);
	}

	@Test
	public void createAndRetrieveContact() {
		// Create a new contact by performing the appropriate http request (POST)
		WebTarget target = client.target("http://localhost:8080/eKTPModule");
		Response response = target.request().post(Entity.entity(dataKTPForTest, MediaType.APPLICATION_JSON));

		// Check that the response has the appropriate response code (201)
		assertThat(response.getStatus()).isEqualTo(201);
		// Retrieve the newly created contact
		String newContactURL = (String) response.getHeaders().get("Location").get(0);
		DataKTP contact = client.target(newContactURL).request().get(DataKTP.class);

		// Check that it has the same properties as the initial one
		assertThat(contact.getFirstName()).isEqualTo(dataKTPForTest.getFirstName());
		assertThat(contact.getLastName()).isEqualTo(dataKTPForTest.getLastName());
		assertThat(contact.getPhone()).isEqualTo(dataKTPForTest.getPhone());
	}
}


text:
import os
import sys

import alabaster

sys.path.insert(0, os.path.abspath('..'))
import guardrail

extensions = [
    'sphinx.ext.todo',
    'sphinx.ext.autodoc',
    'sphinx.ext.viewcode',
    'alabaster',
]

html_theme = 'alabaster'
html_static_path = ['_static']
html_theme_path = [alabaster.get_path()]

html_sidebars = {
    '**': [
        'about.html', 'navigation.html', 'searchbox.html', 'donate.html',
    ],
}
html_theme_options = {
    'github_banner': True,
    'travis_button': True,
    'github_user': 'jmcarp',
    'github_repo': 'guardrail',
}

templates_path = ['_templates']

source_suffix = '.rst'

master_doc = 'index'

project = 'guardrail'
copyright = '2014-2015'
version = release = guardrail.__version__
language = 'en'

exclude_patterns = ['_build']

default_role = 'py:obj'

autodoc_member_order = 'bysource'


text:
require 'rubygems'
require 'open-uri'
require 'tempfile'
require 'zip'
require 'csv'
require 'curses'
require 'activerecord-import'
require 'ken_all/visualizer'
require 'ken_all/engine'
require 'ken_all/import'
require 'ken_all/merge_box'
require 'ken_all/post'


text:
package models

import java.util.UUID
import org.joda.time.{DateTime, LocalDate, LocalTime}
import play.api.libs.functional.syntax.{unlift, _}
import play.api.libs.json.{JsPath, Json, Reads, Writes}
import utils.date.DateTimeJsonFormatter._

trait ReportCardRescheduledLike extends UniqueEntity

case class ReportCardRescheduled(
  date: LocalDate,
  start: LocalTime,
  end: LocalTime,
  room: UUID,
  reason: Option[String] = None,
  lastModified: DateTime,
  id: UUID = UUID.randomUUID
) extends ReportCardRescheduledLike

case class ReportCardRescheduledProtocol(
  reportCardEntry: UUID,
  date: LocalDate,
  start: LocalTime,
  end: LocalTime,
  room: UUID,
  reason: Option[String] = None
)

case class ReportCardRescheduledAtom(date: LocalDate,
  start: LocalTime,
  end: LocalTime,
  room: Room,
  reason: Option[String],
  lastModified: DateTime,
  id: UUID
) extends ReportCardRescheduledLike

object ReportCardRescheduledLike {

  implicit val writes: Writes[ReportCardRescheduledLike] = {
    case normal: ReportCardRescheduled => Json.toJson(normal)(ReportCardRescheduled.writes)
    case atom: ReportCardRescheduledAtom => Json.toJson(atom)(ReportCardRescheduledAtom.writes)
  }
}

object ReportCardRescheduled {
  implicit val writes: Writes[ReportCardRescheduled] = Json.writes[ReportCardRescheduled]
}

object ReportCardRescheduledProtocol {
  implicit val reads: Reads[ReportCardRescheduledProtocol] = Json.reads[ReportCardRescheduledProtocol]
}

object ReportCardRescheduledAtom {

  implicit val writes: Writes[ReportCardRescheduledAtom] = (
    (JsPath \ "date").write[LocalDate] and
      (JsPath \ "start").write[LocalTime] and
      (JsPath \ "end").write[LocalTime] and
      (JsPath \ "room").write[Room](Room.writes) and
      (JsPath \ "reason").writeNullable[String] and
      (JsPath \ "lastModified").write[DateTime] and
      (JsPath \ "id").write[UUID]
    ) (unlift(ReportCardRescheduledAtom.unapply))
}


text:
title: Great Books
layout: photospage
permalink: /books/
tag: images/books
---