text:
class Unbuffered(object):
    def __init__(self, stream):
        self.stream = stream
    def write(self, data):
        self.stream.write(data)
        self.stream.flush()
    def __getattr__(self, attr):
        return getattr(self.stream, attr)

import sys
sys.stdout = Unbuffered(sys.stdout)

from sklearn.base import BaseEstimator
import numpy
import sklearn.metrics
from sklearn.linear_model import LogisticRegression as LR
import nlopt
import scipy.stats

class CPLELearningModel(BaseEstimator):
    """
    Contrastive Pessimistic Likelihood Estimation framework for semi-supervised
    learning, based on (Loog, 2015). This implementation contains two
    significant differences to (Loog, 2015):
    - the discriminative likelihood p(y|X), instead of the generative
    likelihood p(X), is used for optimization
    - apart from `pessimism' (the assumption that the true labels of the
    unlabeled instances are as adversarial to the likelihood as possible), the
    optimization objective also tries to increase the likelihood on the labeled
    examples

    This class takes a base model (any scikit learn estimator),
    trains it on the labeled examples, and then uses global optimization to
    find (soft) label hypotheses for the unlabeled examples in a pessimistic
    fashion (such that the model log likelihood on the unlabeled data is as
    small as possible, but the log likelihood on the labeled data is as high
    as possible)

    See Loog, Marco. "Contrastive Pessimistic Likelihood Estimation for
    Semi-Supervised Classification." arXiv preprint arXiv:1503.00269 (2015).
    http://arxiv.org/pdf/1503.00269

    Attributes
    ----------
    basemodel : BaseEstimator instance
        Base classifier to be trained on the partially supervised data

    pessimistic : boolean, optional (default=True)
        Whether the label hypotheses for the unlabeled instances should be
        pessimistic (i.e. minimize log likelihood) or optimistic (i.e.
        maximize log likelihood).
        Pessimistic label hypotheses ensure safety (i.e. the semi-supervised
        solution will not be worse than a model trained on the purely
        supervised instances)

    predict_from_probabilities : boolean, optional (default=False)
        The prediction is calculated from the probabilities if this is True
        (1 if more likely than the mean predicted probability or 0 otherwise).
        If it is false, the normal base model predictions are used.
        This only affects the predict function. Warning: only set to true if
        predict will be called with a substantial number of data points

    use_sample_weighting : boolean, optional (default=True)
        Whether to use sample weights (soft labels) for the unlabeled instances.
        Setting this to False allows the use of base classifiers which do not
        support sample weights (but might slow down the optimization)

    max_iter : int, optional (default=3000)
        Maximum number of iterations

    verbose : int, optional (default=1)
        Enable verbose output (1 shows progress, 2 shows the detailed log
        likelihood at every iteration).

    """

    def __init__(self, basemodel, pessimistic=True, predict_from_probabilities = False, use_sample_weighting = True, max_iter=3000, verbose = 1):
        self.model = basemodel
        self.pessimistic = pessimistic
        self.predict_from_probabilities = predict_from_probabilities
        self.use_sample_weighting = use_sample_weighting
        self.max_iter = max_iter
        self.verbose = verbose

        self.it = 0 # iteration counter
        self.noimprovementsince = 0 # log likelihood hasn't improved since this number of iterations
        self.maxnoimprovementsince = 3 # threshold for iterations without improvements (convergence is assumed when this is reached)

        self.buffersize = 200
        # buffer for the last few discriminative likelihoods (used to check for convergence)
        self.lastdls = [0]*self.buffersize

        # best discriminative likelihood and corresponding soft labels; updated during training
        self.bestdl = numpy.infty
        self.bestlbls = []

        # unique id
        self.id = str(unichr(numpy.random.randint(26)+97))+str(unichr(numpy.random.randint(26)+97))

    def discriminative_likelihood(self, model, labeledData, labeledy = None, unlabeledData = None, unlabeledWeights = None, unlabeledlambda = 1, gradient=[], alpha = 0.01):
        unlabeledy = (unlabeledWeights[:, 0]<0.5)*1
        uweights = numpy.copy(unlabeledWeights[:, 0]) # large prob. for k=0 instances, small prob. for k=1 instances
        uweights[unlabeledy==1] = 1-uweights[unlabeledy==1] # subtract from 1 for k=1 instances to reflect confidence
        weights = numpy.hstack((numpy.ones(len(labeledy)), uweights))
        labels = numpy.hstack((labeledy, unlabeledy))

        # fit model on supervised data
        if self.use_sample_weighting:
            model.fit(numpy.vstack((labeledData, unlabeledData)), labels, sample_weight=weights)
        else:
            model.fit(numpy.vstack((labeledData, unlabeledData)), labels)

        # probability of labeled data
        P = model.predict_proba(labeledData)

        try:
            # labeled discriminative log likelihood
            labeledDL = -sklearn.metrics.log_loss(labeledy, P)
        except Exception as e:
            print(e)
            P = model.predict_proba(labeledData)

        # probability of unlabeled data
        unlabeledP = model.predict_proba(unlabeledData)

        try:
            # unlabeled discriminative log likelihood
            eps = 1e-15
            unlabeledP = numpy.clip(unlabeledP, eps, 1 - eps)
            unlabeledDL = numpy.average((unlabeledWeights*numpy.vstack((1-unlabeledy, unlabeledy)).T*numpy.log(unlabeledP)).sum(axis=1))
        except Exception as e:
            print(e)
            unlabeledP = model.predict_proba(unlabeledData)

        if self.pessimistic:
            # pessimistic: minimize the difference between unlabeled and labeled discriminative likelihood (assume worst case for unknown true labels)
            dl = unlabeledlambda * unlabeledDL - labeledDL
        else:
            # optimistic: minimize negative total discriminative likelihood (i.e. maximize likelihood)
            dl = - unlabeledlambda * unlabeledDL - labeledDL

        return dl

    def discriminative_likelihood_objective(self, model, labeledData, labeledy = None, unlabeledData = None, unlabeledWeights = None, unlabeledlambda = 1, gradient=[], alpha = 0.01):
        if self.it == 0:
            self.lastdls = [0]*self.buffersize

        dl = self.discriminative_likelihood(model, labeledData, labeledy, unlabeledData, unlabeledWeights, unlabeledlambda, gradient, alpha)

        self.it += 1
        self.lastdls[numpy.mod(self.it, len(self.lastdls))] = dl

        if numpy.mod(self.it, self.buffersize) == 0: # or True:
            improvement = numpy.mean((self.lastdls[(len(self.lastdls)/2):])) - numpy.mean((self.lastdls[:(len(self.lastdls)/2)]))
            # ttest - test for hypothesis that the likelihoods have not changed (i.e. there has been no improvement, and we are close to convergence)
            _, prob = scipy.stats.ttest_ind(self.lastdls[(len(self.lastdls)/2):], self.lastdls[:(len(self.lastdls)/2)])

            # if improvement is not certain accoring to t-test...
            noimprovement = prob > 0.1 and numpy.mean(self.lastdls[(len(self.lastdls)/2):]) < numpy.mean(self.lastdls[:(len(self.lastdls)/2)])
            if noimprovement:
                self.noimprovementsince += 1
                if self.noimprovementsince >= self.maxnoimprovementsince:
                    # no improvement since a while - converged; exit
                    self.noimprovementsince = 0
                    raise Exception(" converged.") # we need to raise an exception to get NLopt to stop before exceeding the iteration budget
            else:
                self.noimprovementsince = 0

            if self.verbose == 2:
                print(self.id,self.it, dl, numpy.mean(self.lastdls), improvement, round(prob, 3), (prob < 0.1))
            elif self.verbose:
                sys.stdout.write(('.' if self.pessimistic else '.') if not noimprovement else 'n')

        if dl < self.bestdl:
            self.bestdl = dl
            self.bestlbls = numpy.copy(unlabeledWeights[:, 0])

        return dl

    def fit(self, X, y): # -1 for unlabeled
        unlabeledX = X[y==-1, :]
        labeledX = X[y!=-1, :]
        labeledy = y[y!=-1]

        M = unlabeledX.shape[0]

        # train on labeled data
        self.model.fit(labeledX, labeledy)

        unlabeledy = self.predict(unlabeledX)

        #re-train, labeling unlabeled instances pessimistically

        # pessimistic soft labels ('weights') q for unlabelled points, q=P(k=0|Xu)
        f = lambda softlabels, grad=[]: self.discriminative_likelihood_objective(self.model, labeledX, labeledy=labeledy, unlabeledData=unlabeledX, unlabeledWeights=numpy.vstack((softlabels, 1-softlabels)).T, gradient=grad) #- supLL
        lblinit = numpy.random.random(len(unlabeledy))

        try:
            self.it = 0
            opt = nlopt.opt(nlopt.GN_DIRECT_L_RAND, M)
            opt.set_lower_bounds(numpy.zeros(M))
            opt.set_upper_bounds(numpy.ones(M))
            opt.set_min_objective(f)
            opt.set_maxeval(self.max_iter)
            self.bestsoftlbl = opt.optimize(lblinit)
            print(" max_iter exceeded.")
        except Exception as e:
            print(e)
            self.bestsoftlbl = self.bestlbls

        if numpy.any(self.bestsoftlbl != self.bestlbls):
            self.bestsoftlbl = self.bestlbls
        ll = f(self.bestsoftlbl)

        unlabeledy = (self.bestsoftlbl<0.5)*1
        uweights = numpy.copy(self.bestsoftlbl) # large prob. for k=0 instances, small prob. for k=1 instances
        uweights[unlabeledy==1] = 1-uweights[unlabeledy==1] # subtract from 1 for k=1 instances to reflect confidence
        weights = numpy.hstack((numpy.ones(len(labeledy)), uweights))
        labels = numpy.hstack((labeledy, unlabeledy))
        if self.use_sample_weighting:
            self.model.fit(numpy.vstack((labeledX, unlabeledX)), labels, sample_weight=weights)
        else:
            self.model.fit(numpy.vstack((labeledX, unlabeledX)), labels)

        if self.verbose > 1:
            print("number of non-one soft labels: ", numpy.sum(self.bestsoftlbl != 1), ", balance:", numpy.sum(self.bestsoftlbl<0.5), " / ", len(self.bestsoftlbl))
            print("current likelihood: ", ll)

        if not getattr(self.model, "predict_proba", None):
            # Platt scaling
            self.plattlr = LR()
            preds = self.model.predict(labeledX)
            self.plattlr.fit( preds.reshape( -1, 1 ), labeledy )

        return self

    def predict_proba(self, X):
        """Compute probabilities of possible outcomes for samples in X.

        The model need to have probability information computed at training
        time: fit with attribute `probability` set to True.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]

        Returns
        -------
        T : array-like, shape = [n_samples, n_classes]
            Returns the probability of the sample for each class in
            the model. The columns correspond to the classes in sorted
            order, as they appear in the attribute `classes_`.
        """

        if getattr(self.model, "predict_proba", None):
            return self.model.predict_proba(X)
        else:
            preds = self.model.predict(X)
            return self.plattlr.predict_proba(preds.reshape( -1, 1 ))

    def predict(self, X):
        """Perform classification on samples in X.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]

        Returns
        -------
        y_pred : array, shape = [n_samples]
            Class labels for samples in X.
        """

        if self.predict_from_probabilities:
            P = self.predict_proba(X)
            return (P[:, 0]<numpy.average(P[:, 0]))
        else:
            return self.model.predict(X)

    def score(self, X, y, sample_weight=None):
        return sklearn.metrics.accuracy_score(y, self.predict(X), sample_weight=sample_weight)


text:
/**
 * \file rtcpscheduler.h
 */

#ifndef RTCPSCHEDULER_H

#define RTCPSCHEDULER_H

#include "rtpconfig.h"
#include "rtptimeutilities.h"
#include "rtprandom.h"

namespace jrtplib
{

class RTCPCompoundPacket;
class RTPPacket;
class RTPSources;

/** Describes parameters used by the RTCPScheduler class. */
class RTCPSchedulerParams
{
public:
	RTCPSchedulerParams();
	~RTCPSchedulerParams();

	/** Sets the RTCP bandwidth to be used to \c bw (in bytes per second). */
	int SetRTCPBandwidth(double bw);

	/** Returns the used RTCP bandwidth in bytes per second (default is 1000). */
	double GetRTCPBandwidth() const							{ return bandwidth; }

	/** Sets the fraction of the RTCP bandwidth reserved for senders to \c fraction. */
	int SetSenderBandwidthFraction(double fraction);

	/** Returns the fraction of the RTCP bandwidth reserved for senders (default is 25%). */
	double GetSenderBandwidthFraction() const					{ return senderfraction; }

	/** Sets the minimum (deterministic) interval between RTCP compound packets to \c t. */
	int SetMinimumTransmissionInterval(const RTPTime &t);

	/** Returns the minimum RTCP transmission interval (default is 5 seconds). */
	RTPTime GetMinimumTransmissionInterval() const					{ return mininterval; }

	/** If \c usehalf is \c true, only use half the minimum interval before sending the first RTCP compound packet. */
	void SetUseHalfAtStartup(bool usehalf)						{ usehalfatstartup = usehalf; }

	/** Returns \c true if only half the minimum interval should be used before sending the first RTCP compound packet
	 *  (defualt is \c true).
	 */
	bool GetUseHalfAtStartup() const						{ return usehalfatstartup; }

	/** If \c v is \c true, the scheduler will schedule a BYE packet to be sent immediately if allowed. */
	void SetRequestImmediateBYE(bool v)						{ immediatebye = v; }

	/** Returns if the scheduler will schedule a BYE packet to be sent immediately if allowed
	 *  (default is \c true).
	 */
	bool GetRequestImmediateBYE() const						{ return immediatebye; }
private:
	double bandwidth;
	double senderfraction;
	RTPTime mininterval;
	bool usehalfatstartup;
	bool immediatebye;
};

/** This class determines when RTCP compound packets should be sent. */
class RTCPScheduler
{
public:
	/** Creates an instance which will use the source table RTPSources to determine when RTCP compound
	 *  packets should be scheduled.
	 *  Creates an instance which will use the source table RTPSources to determine when RTCP compound
	 *  packets should be scheduled. Note that for correct operation the \c sources instance should have information
	 *  about the own SSRC (added by RTPSources::CreateOwnSSRC). You must also supply a random number
	 *  generator \c rtprand which will be used for adding randomness to the RTCP intervals.
	 */
	RTCPScheduler(RTPSources &sources, RTPRandom &rtprand);
	~RTCPScheduler();

	/** Resets the scheduler. */
	void Reset();

	/** Sets the scheduler parameters to be used to \c params. */
	void SetParameters(const RTCPSchedulerParams &params)						{ schedparams = params; }

	/** Returns the currently used scheduler parameters. */
	RTCPSchedulerParams GetParameters() const							{ return schedparams; }

	/** Sets the header overhead from underlying protocols (for example UDP and IP) to \c numbytes. */
	void SetHeaderOverhead(size_t numbytes)								{ headeroverhead = numbytes; }

	/** Returns the currently used header overhead. */
	size_t GetHeaderOverhead() const								{ return headeroverhead; }

	/** For each incoming RTCP compound packet, this function has to be called for the scheduler to work correctly. */
	void AnalyseIncoming(RTCPCompoundPacket &rtcpcomppack);

	/** For each outgoing RTCP compound packet, this function has to be called for the scheduler to work correctly. */
	void AnalyseOutgoing(RTCPCompoundPacket &rtcpcomppack);

	/** This function has to be called each time a member times out or sends a BYE packet. */
	void ActiveMemberDecrease();

	/** Asks the scheduler to schedule an RTCP compound packet containing a BYE packetl; the compound packet
	 *  has size \c packetsize.
	 */
	void ScheduleBYEPacket(size_t packetsize);

	/**	Returns the delay after which an RTCP compound will possibly have to be sent.
	 *  Returns the delay after which an RTCP compound will possibly have to be sent. The IsTime member function
	 *  should be called afterwards to make sure that it actually is time to send an RTCP compound packet.
	 */
	RTPTime GetTransmissionDelay();

	/** This function returns \c true if it's time to send an RTCP compound packet and \c false otherwise.
	 *  This function returns \c true if it's time to send an RTCP compound packet and \c false otherwise.
	 *  If the function returns \c true, it will also have calculated the next time at which a packet should
	 *  be sent, so if it is called again right away, it will return \c false.
	 */
	bool IsTime();

	/** Calculates the deterministic interval at this time.
	 *  Calculates the deterministic interval at this time. This is used - in combination with a certain multiplier -
	 *  to time out members, senders etc.
	 */
	RTPTime CalculateDeterministicInterval(bool sender = false);
private:
	void CalculateNextRTCPTime();
	void PerformReverseReconsideration();
	RTPTime CalculateBYETransmissionInterval();
	RTPTime CalculateTransmissionInterval(bool sender);

	RTPSources &sources;
	RTCPSchedulerParams schedparams;
	size_t headeroverhead;
	size_t avgrtcppacksize;
	bool hassentrtcp;
	bool firstcall;
	RTPTime nextrtcptime;
	RTPTime prevrtcptime;
	int pmembers;

	// for BYE packet scheduling
	bool byescheduled;
	int byemembers,pbyemembers;
	size_t avgbyepacketsize;
	bool sendbyenow;

	RTPRandom &rtprand;
};

} // end namespace

#endif // RTCPSCHEDULER_H

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cladina evansii f. evansii

### Remarks
null


text:
* HasFieldsWithSameValues failed to properly compare when the expected value contained duplicate string.
More generally, instances where only checked once for equality; any subsequent check was assumed to be succesful.
This could lead to false positive (i.e. checks succeeded when it should have failed).
This regression was introduced by V 2.2.0 in 02/2018. Sorry about that.

### GitHub Issues
* #331

## V 2.7.0
### New checks
* You can use *IsCloseTo* on **DateTime** and **DateTimeOffset** to check if a given date is close to a reference one.
* You can provide your own equality comparer (as an implementation of *IEqualityComparer*) when using *IsEqualTo*.

      Check.That(sut).IsEqualTo(expected, new MyEqualityComparer());

### Improvements
* *Check.That(IEnumerable).IsEquivalent(...)* now uses default logic for equality check.
* Significantly improved error messages for enumeration and dictionary equality comparison.
* Restore **typed** *IsEqualTo* check. It should ensure smoother experience with autocompletion logic. Non typed version
(using Object as a parameter) is still available.
* You can use **WhichMember** to perform checks on any member of an exception.

      Check.ThatCode(() => {...}).Throws<ArgumentException>().
        WhichMember( x=> x.ParamName).IsEqualTo(myArg);

### Fixes
* the Not operator no longer erases the custom message set using WithCustomMessage
* Check.That(IDictionary).IsEquivalent now fails as expected when the _sut_ has entries that do not exist in the expected dictionary.
* IsEquivalent now performs deep equivalence. For example, it supports Dictionaries of Dictionaries
* Enum properties are properly considered when using *Considering*.
* Enumeration of *KeyValue* pairs are no longer treated as dictionaries but as enumeration. This behavior was a hack
to support custom *IDictionary<K,V>* implementations. Detection logic has been improved so this is no longer necessary.
* *Check.That(IEnumerable).IsInDescendingOrder* no longer requires items to implement IComparable

### GitHub Issues
* #306, #312, #313, #314, #315, #317
__________________
## V 2.6.0

### New feature
* NFluent now supports assumption through Assuming entry point. For example you express it as :Assume.That(sut).IsEqualTo(expected); in a nutshell
you type Assuming instead of Check. All checks are available. Note that actual support depends on the underlying testing framework. As of now
it is supported for NUnit and MsTest
* NFluent now supports DateTimeOffset type with the same checks than for DateTime. These checks fails
if the offsets are different. The IsSameUtcInstant cheks perform a comparison integrating the offset.

### New checks
* You can use WhoseSize() to check the size of an enumeration. It is used as an extension keyword, as in:
Check.That(enum).WhoseSize().IsEqualTo(3)

### Improvements
* When using the Equals method, NFluent now uses expected.Equals(actual) instead of actual.Equals(expected).
This should have limited impact.
* Actual and expected value naming has been redesigned to improve naming accuracy. Impact vary depending on checks and types.
* Comparison of enumeration now provides details regarding the differences. You can control
how many differences are reported using the property **ExtensionsCommonHelpers.CountOfLineOfDetails**.
* Cleaned up the reporting of array fields when using Considering. The superfluous dot (as in _field.[index]_)
has been removed.
* Improved implementation for Equals when using Considering. You should use IsEqualTo when checking for
* equality, but we also provide an implementation of Equals as a failsafe.

### Fixes
* Fix issue with `IEnumerable<object>` and Contains(Exactly), IsEqualTo, IsEquivalentTo.
* Several error messages have been improved due to fix on check helpers.
* NotSupportedException when using ContainsExactly on strings.
* Fix issue with single dimension arrays and field based checks where the LAST item of the array
* was not evaluated during the check (issue found thanks to mutation test)
* Comparing Array with considering was no different than when using IsEqualTo. This has been fixed.
Therefore error messages are now in line with what was expected

### Extensibility
Foreword: several breaking changes have been introduced that may trigger build error in your custom extensions if you have made any.
Methods and types have been renamed, so your code will have to refer the new names. IF YOU ENCOUNTER ISSUES AND NEED ASSISTANCE, please open an issue, we will assist you ASAP.
* All lambda/code specific interfaces (ICodeCheck<T>...) and classes have been removed. NFluent now uses the standard interfaces and types (i.e. Check<T>)
* ICheckLogic.DefineExpectedValues now expects an generic IEnumerable<T> instead of a plain IEnumerable
* you can use ICheckLogic.DefinePossibleTypes if you need to have a list of possible types for the sut (displayed in the error message)
* improved naming: ICheckLogic.DefineExpectedValues has been renamed DefinePossibleValues
* checks helper (ICheckLogic) now correctly reports the fundamental error instead of a detail error. In previous version, the error messages could focus on details, e.g. report the
exception's message when the issue is the exception's type.
* add a flag (boolean) to BuildCheckLinkWhich method (allows to provide subitem check) that allows to speciyf sub item is available.

### GitHub Issues
* #225, #291, #292, #295, #296, #297, #299, #302

## V 2.5.0
### Main feature
* **CaptureConsole class** mocks the system console. Using it you can inject/simulate
user input (with **Input** and **InputLine** methods) and read/review what the code has put on the
console (with the **Output** property). The class is disposable: nnormal behavior
is restored on Dispose.
Example

      using (var console = new CaptureConsole)
      {
          console.InputLine("12+13");
          // the code I need to check (a calculator here)
          Calculator.Process();
          // perform the check
          Check.That(console.Output).IsEqualTo("25");
       }

### New checks
* Console related checks (see above)

### Improvements
* Stabilize Assembly Version to reduce friction induced by strong naming (assembly version is still V2.4.0)
* Align to Microsoft guidelines for OSS libraries (https://docs.microsoft.com/en-us/dotnet/standard/library-guidance/)
* HasAvalue() and HasNoValue() are available on all nullable types
* Add support for WithCustomMessage for dynamics.
* Revised signature for enumerable checks to reduce type erasure (loss of type information when chaining checks). Regression tests have been added regarding non generic IEnumerable support, but as the changes
are significant, please revert to us if you face issues.
* Fixes reporting of end of line markers: only carriage return chars were reported.
* Changed error text for missing or extra lines in string to make it clearer.
* IsEqualTo provides more details for IEnumerable (make sure first different item is visible).
* Number of items in expected value was often not reported in error messages.

### Fixes
* Fix false positive with TimeSpan due linked to precision loss. It concerns: IsEqualTo(TimeSpan), IsLessThan(TimeSpan), IsGreaterThan(TimeSpan)
* Fix random FileNotFound exceptions on the first failing assertion while using XUnit in some specific setup.
* Error message for Check.ThatCode().LastsLessThan did not report the actual time.
* Error message for Not.ThrowsAny() was wrong.
* Hashtable not properly reported in error messages.
* Fixed error messages for negated checks on dynamics.
* Fix false positive for IsNotZero (and IsZero) for decimal that are close to 0 (<.5).
* IsEquivalentTo now supports dictionary types.
* IsEqualTo now supports dictionary types. Error message hints to use IsEquivalentTo when relevant.

### GitHub Issues
* #269, #274, #270, #275, #276, #280, #283, #184, #284, #286, #290
---------------
# V 2.4.0
### Main feature: Custom explicit error message
You can now provides explicit error messages for each check, thanks to **WithCustomMessage**. E.g:
Check.WithCustomMessage("Ticket must be valid at this stage").That(ticket.Status).IsEqualTo(Status.Valid);
This feature has often been requested  and we are happy to finaly deliver it, but please keep on
naming your test methods properly.
Custom error messages are not avaible for dynamic types.

### New checks
* IsInAscendingOrder: checks if an IEnumerable is sorted in ascending orders, it accepts an optional comparer instance
* IsInDescendingOrder:  checks if an IEnumerable is sorted in descending orders, it accepts an optional comparer instance
* IsSubSetOf: checks if an IEnumerable is a subset of another collection.
* IsInstanceOf<Type>(): now supports the Which() keyword so you may use checks specific to the asserted type.

### Improvements
* Truncation default length for message is now 20Ko as an experiment. Please bring feedback. You can still adjust
* default truncation with the Check.StringTruncationLength property
* Multidimensional arrays are properly reported in error messages, respecting index structure.
* Sourcelink (Net Core 2.1+ and Net Standard 2.0): you can debug through NFluent code using Sourcelink on Core 2.1 projects

### Fixes
* As now works with Not (and vice versa).
* Exception when using HasElementThatMatches or ContainsOnlyElementsThatMatch on arrays, and possibly
other enumerable types.
* Exception when using multidimensional arrays (such as  int[2,5]) with Considering/HasFiedsWithSameValueAs.
* false Negative when comparing multidimensionnal arrays, e.g.: int[3,5] was equal to int[5,3] and with int[15].
* Exception when reporting strings containing braces.
### GitHub Issues
* #255, #38, #166, #258, #259, #260, #261, #262, #264, #265
---------------
## V 2.3.1
### Fixes
* NullReferenceException on failed check using xUnit and NetCore
### GitHub Issues
* #251
---------------
## V 2.3.0
### Main feature: redesigned extensibility
One of the fundamental features of NFluent is that you can add your own checks.
Articles explained how to do that, but syntax was still too cumbersome
for our taste. This version brings major improvements detailed here:

* Simplified support for creating custom checks thanks to new helper methods
and classes (see https://github.com/tpierrain/NFluent/wiki/Extensibility)
* Customisation of error reporting: by default, any check failure is reported
by raising an exception. You can now provide your own reporting system. You need to provide an implementation
of IErrorReporter interface, and specify you want to use it by setting the Check.Reporter interface.

### Other New features(s)
* IsNullOrWhiteSpace: checks if a string is null, empty or contains only white space(s).
* IReadOnlyDictionary (_Net 4.5+_)
  * ContainsKey, ContainsValue, ContainsPair are supported.
* async method/delegates
  * Check.ThatCode now supports _async_ methods/delegates transparently.
* Check expression now provides the result as a string. I.e Check.That(true).IsTrue().ToString() returns "Success".
* New check: IsDefaultValue, which fails if the sut is not the default value for its type: null for ref types, 0 for value types.
* New check: ContainsNoDuplicateItem for enumerable, that fails if it contains a dupe.
* New check: IsEquivalentTo for enumerable, that checks if its contents match an expected content, disregarding order.
* New check: DoesNotContainNull for enumerable, that fails if an entry is null.
* New check: IsAnInstanceOfOneOf that checks if the sut is of one of expected types.
* New check: IsNotAnInstanceOfThese that checks if the sut type is different from a list of forbidden types.
* New check: DueToAnyFrom(...) that checks that an exception has been triggered by another exception from a list of possible types.

### Fixes
 * Check.ThatCode(...).Not.Throws\<T\>() may throw an InvalidCastException when thrown exception is not T.
 * Extension checks to Throw\<\>, ThrowType or ThrowAny raise an exception when used with Not as it does not make sense.
 * Which() raises an exception when used on a negated check (Not).
 * Fix exception when using Considering and indexed properties.
 * Fix loss of type when using Contains and ContainsExactly. This restores fluentness for IEnumerable<T> types.
 Fixed error messages for double (and float) equality check that reported checked value in place of the expected one.
 * Fixed error messages for Check.That(TimeSpan).IsGreaterThan
 * False positive whith Considering() or HasFieldsWithSameValues when haing ints and enum attributes with the same value.

### Changes
* Improved error messages
  * ContainsOnlyElementsThatMatch: now provides the index and value of the first failing value.
  * IsOnlyMadeOf: improved error messages
  * DateTime checks: revamped all messages
  * Enum: error message on enum types now use 'enum' instead of 'value'.
  * IsInstanceOf: be more specific regarding types
  * Considering()...IsNull/IsNotNull: error messages specify member triggering the failure.
* Breaking
  * Added automatic conversion between decimal and other numerical types. Check.That(100M).IsEqualTo(100) no longer fails.
  * Removed Failure method from IChecker interface

### GitHub Issues
* #228, #227, #222, #223, #217, #230, #232,
* #236, #238, #242, #243, #244, #245, #246,
* #231, #247, #161, #249
---------------
# V 2.2.0
Flexible property and field based comparison is now available. Examples:
* Check.That(sut)**.Considering().Public.Properties**.IsEqualTo(expected);
* Check.That(sut)**.Considering().Public.Fields.And.Public.Properties**.IsEqualTo(expected);
* Check.That(sut)**.Considering().Public.Fields.Excluding("coordX", "child.address")**.IsEqualTo(expected);
Syntax is:
* Check.That(sut)**.Considering().(Public|NonPublic|All).(Fields.Properties)[.And.(Public|NonPublic|All).(Fields.Properties)][Excluding("fielda", "sub.fieldb")]**.IsEqualTo(expected);
* **Considering()** is supported by: _IsEqualTo(), IsNotEqualTo(), AsSameValueAs(), HasDifferentValueThan(), IsInstanceOf\<type\>()_ [checks if fields/properties are present],
_IsNotInstanceOf\<type\>()_,  _HasSameValueAs()_, _IsSameReferenceAs(), _IsDistinctFrom()_, _HasDifferentValueThan()_

### New feature(s)
* **Object**
  * New check **IsInstanceOfType(Type type)** which is equivalent to *IsInstanceOf\<type\>()*, in a non generic form for parameteriSed tests.
  * New check **IsNoInstanceOfType(Type type)** which is equivalent to *IsNotInstanceOf\<type\>()*, in a non generic form for parameteriSed tests.
  * New check **InheritsFromType(Type type)** which is equivalent to *InheritsFrom\<type\>()*, in a non generic form for parameterised tests.
* **Enum**
  - New check **HasFlag(xxx)** that checks if a flag is present in an enum value.
* **Code**
  * New check **ThrowsType(Type type)** which is equivalent to *Throws\<type\>*, in a non generic form for parameterised tests.

### Changes
* Improved error messages for missing fields(and properties) for reflection based checks.

### Fixes
* Fix issue with overloaded member/properties for HasFieldswithSameValues(...) (#219)

### GitHub Issues
* #219, #218, #216, #215, #214, #121
---------------
# V 2.1.1
Bug fix(es):
* fix issue #215: null reference exception triggered by HasFields... on null interface fields.
--------------
# V 2.1.0
New feature(s):
* Enumerable:
  * Breaking change: equality for Enumerable is now content based (instead of reference based). See issue #209. You can revert adding: Check.EqualMode = EqualityMode.Equals in your test set up code
  * New check ContainsOnlyElementsThatMatch which checks that all items verify a given predicate.
* New Check: IsOneOf checks if the value belongs to a list of authorised value. Check.That(sut).IsOneOf(a, b, c, ...) fails if _sut_ is different from all valid values
* Improved error messages for IsEqualTo() on floating point types. Difference is displayed when small, suggestion to use IsCloseTo when difference is really small (#205).
* Initial support for dynamics (issue #85):
  * Entry point is: Check.ThatDynamic()
  * Available checks are: IsNotNull(), IsEqualTo(...), IsSameReferenceAs(...)
  * And keyword is available
  * Not keyword is available
* You can specify the maximum size (before truncate) for strings in error messages using **Check.StringTruncationLength** property
Bug Fixe(s):
* Fixed support of array types for HasFielsWithSameValues (issue #200)
* Fixed some stack overflow exceptions (issue #210).
* Fixed confusing examples about array item related checks in the readme
--------------
# V 2.00
New feature(s):
* Support for NetStandard > 1.3
* Support for Net.Core > 1.0
* Compatible for Net > 2.0
* Built for: 2.0, 3.0, 3.5, 4.0, 4.5, NetStandard 1.3
* All: introduce: HasSameValueAs(x) that perform comparison using 'operator==' instead of 'Equals'.
* All: introduce: HasAValueDifferentFrom(x) that perform comparison using 'operator!=' instead of '!Equals'.
* Streams: introduce HasSameSequenceOfBytesAs() check.
* Numbers: introduce IsPositiveOrZero() check.
* Numbers: introduce IsNegativeOrZero() check.
* FloatingNumbers (float, double): introduce IsCloseTo(expected, within) check for estimated value.
* Exception: introduce the DueTo<InnerException> as an extension to Throws<Exception>. It verifies that the checked exception was triggered by a specific exception. This is done by scanning the 'innerException' chain until the expected type is identified. Further checking is done on the inner exception.
* Exception: introduce WithProperties( expression, expectedValue) to check the value of any exception members, thanks to a selector expression.
* IEnumerable: introduce HasElementAt(int index) which checks for an item as a specific index. Furthermore, this item can be checked as well thanks to 'Which'. E.g: Check.That(_collection).HasElementAt(3).Which.IsEqualTo("foo").
* IEnumerable: introduce HasFirstElement() which checks for the first item. Furthermore, this item can be checked as well thanks to 'Which'. E.g: Check.That(_collection).HasFirstElement().Which.IsEqualTo("foo").
* IEnumerable: introduce HasLastElement() which checks for the last item. Furthermore, this item can be checked as well thanks to 'Which'. E.g: Check.That(_collection).HasLastElement().Which.IsEqualTo("foo").
* IEnumerable: introduce HasOneElementOnly() which checks for the first and single item. Furthermore, this item can be checked as well thanks to 'Which'. E.g: Check.That(_collection).HasOneElementOnly().Which.IsEqualTo("foo").
* IEnumerable: introduce HasElementThatMatches( bool predicate()) which checks that an enumerable has at least on item matching the given predicate. You can use 'Which' to check further this item. E.g.: Check.That(_collection).HasItemThatMatches((_) => _.StartWith("foo")).Which.IsEqualTo("foobar").
* IDictionary<K,V>: now explicitly supported.
* IDictionary<K,V>: introduce ContainsEntry<K, V>(K key, V value) which checks that a dictionary contains a specific value for a given key.
* Hashtable: now explicitly supported.

Change(s):
* IEnumerable: improved description within error messages: partial dump around first difference for large sets
* IDictionnary: no longer supported. Hashtable is supported instead
* Numbers: introduce IsStrictlyPositive() as a substitute for IsPositive() which is now obsolete.
* Numbers: introduce IsStrictlyNegative() as a substitute for IsNegative() which is now obsolete.
* Numbers: introduce IsStrictlyGreaterThan() as a substitute for IsGreaterThan() which is now obsolete.
* Numbers: introduce IsStrictlyLessThan() as a substitute for IsLessThan() which is now obsolete.
* Floating Numbers: introduce IsCloseTo() to check if a number is close to another one.
* Check.ThatCode(...).Throws<T>() now requires T to be an exception. This restriction ensures only Exceptions are proposed in autocompletion.
* Improve error messages (consistency and relevance).
* Strings: generate specific error message using IsEqualTo() when the actual string is empty
* Strings: generate specific error message using IsEqualTo() when the expected string is empty
* Strings: provides part of string where first difference occurs even when strings have different lengths
* Objects: IsSameReferenceAs supersede IsSameReferenceThan (now flagged as obsolete)
* Objects: Dump hashcodes only when NFluent cannot highlight difference.
* Check.That(Action) can no longer be used (error, obsolete)
* Check.That(Func<T>) can no longer be used (error, obsolete)
* Simplify the way you can extend NFluent by adding your own checks. Now, you can call: var checker = ExtensibilityHelper.ExtractChecker(check);
  at the beginning of your check extension method, and then rely on its ExecuteCheck() or BuildMessage() helper methods to do the job. Note: the Checker is part of the NFluent.Extensibility namespace.
* Reviewing of public elements: Some classes are no longer public. They should never have been in the first case.
* Signature of ILambdaExceptionCheck has been updated to refer the checked exception type (instead of RunTrace). This is a breaking change for edge cases, that will impact your extension method on exceptions, if any; it can also impact your tests if you use the explicit signature.

Bug Fixe(s):
* Fix the inversion between expected and actual error message for the .WithMessage checks on exception.
* Fix the issue with null value on Check.That(...).IsBefore(...)
* HasFieldsWithSameValues now recurse along the hierarchy class (Fix for #141)
* Fix stack overflow triggered by HasFieldsWithSameValues() on object with reference loop (#148)
* Properly escaped strings when generating error messages.
* GitHub issues: #124, #133, #141, #148, #153, #154, #156, #159, #164, #165, #167, #174, #177, #178, #179, #187
--------------
# V 1.3.1
New feature(s):
* Now, supports .NET Tasks and Async methods/lambdas/functions thanks to a new Check.ThatAsyncCode()  statement.

Change(s):
* Error messages with double and float are now displayed with InvariantCulture.
* Improved error messages for HasFieldWithSameValue to deal when ToString gives the same text for actual and expected.
* Slightly changed error messages for exceptions to improve consistency.

Bug Fixe(s):
* There was an inversion between expected and actual error message for the .WithMessage checks on exception. This is fixed.
--------------
# V 1.2.0
New feature(s):
* Adds IsSetWithin check for EventWaitHandle types (ex. Manual or AutoResetEvent)
* Adds IsOneOfThese() check for string.
* NFluent is now also available as a Portable Class Library (Profile: portable-net45+sl5+netcore45+MonoAndroid1+MonoTouch1)
* Adds IsNaN() check for double and float.
* Adds IsFinite() check for double and float.

Change(s):
* Renames the Properties extension method on IEnumerable to Extracting. Properties is still there, but marked as obsolete.
* Improves error messages for IsInstanceOf checks.
* IsNull, IsNotNull, IsSameReferenceThan, IsDistinctFrom, HasFieldsWithSameValues and HasNotFieldsWithSameValues are now able to conserve the checked typed (instead of loosing it by converting it into a object).
* InheritsFrom does not return a linkable check anymore (but void).

Bug Fixe(s):
* Fixes a null ref exception for Contains on null
* Fixes a null ref exception for HasFieldsWithSameValues
* Fixes Invalid exceptions on strings with curly braces
--------------
# V 1.1.0
New feature(s):
* Now supports IsNull() and IsNotNull() checks for nullable (thanks to Mendel Monteiro Beckerman for that).
* Check.ThatCode(...): New entry point for checks on code (Action and Func<T>). It supersedes the equivalent Check.That signature.

Change(s):
* Improves error messages for string comparisons (e.g. visually indicates the presence of tab char with <<tab>>, or distinguish <<CFLF>> and <<LF>>, properly handles long strings, ...)
* Check.That(Func<T>) and Check.That(Action) are now obsolete.
* The HasFieldsEqualToThose() check is now obsolete and should be replaced by HasFieldsWithSameValues() which now support anonymous classes as expected parameter.
* The HasFieldsNotEqualToThose() check is now obsolete and should be replaced by HasNotFieldsWithSameValues()
* Simplification of extensibility
* We are so proud of this 1.1 version of NFluent; we decided to sign it.
--------------
# V 1.0.0
New feature(s):
* NFluent is now also shipped with its .NET 4.0 version (to support dynamic for extensibility)
* Adds recursion to the HasFieldsEqualToThose() check on object

Change(s):
* You can now easily link your own checks by using the And operator thanks to the IChecker.ReturnValueForLinkage property.

Bug Fixe(s):
* IsAfter() check was throwing an exception when the givenValue type (considered as a IComparable instead of a number)  was not the same as the checked value.
-------------
# V 0.11
New feature(s):
* Introduces a mechanism for anyone to easily extend NFluent with his own checks (see. ExtensibilityHelper)
* Adds recursion to the HasFieldsEqualToThose() check on object
--------------
# V 0.10
New feature(s):
* Adds IsNull() and IsNotNull() checks.

Change(s):
* Now, Check.That(4L).IsEqualTo(4) passes instead of throwing that types are different.
-------------
# V 0.9
New feature(s):
* Add the support of char
* Add the IsAfter() check to the IComparable instances
* Adds comparison checks to all the numeric types

Change(s):
* Hides the ForkInstance() method from the IntelliSense

Bug Fixe(s):
* Fixes a bad behaviour of the HasFieldsEqualThose() check against auto property null backing fields.
# V 0.8
New features:
* Now, the Equals() method of the ICheck<T> instances is a real fluent check method (instead of the default object.Equals() one).
* New extensible syntax for Check.That(IEnumerable xxx).Contains(...) that permits to add suffixes narrowing the conditions (e.g.: Check.That(IEnumerable xxx).Contains(...).InThatOrder()). Possible suffixes are (Only, Once or InThatOrder)
* Adds check methods for IDictionary
* Adds more check methods to the IEnumerable (e.g. IsNullOrEmpty)

Changes:
* New error message structure that clearly states what is wrong.
* Renames the ContainsOnly() method to IsOnlyMadeOf().
* Replaces IFluentAssertion by ICheck; and IChainableFluentAssertion by ICheckLink so that it improves the IntelliSense experience.


text:
package gcm

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
	"time"

	"github.com/dialogs/dialog-push-service/pkg/provider"
	"github.com/pkg/errors"
)

const ErrorCodeFailedToReadResponse = "FailedToReadResponse"

// Client (legacy/gcm)
// https://firebase.google.com/docs/cloud-messaging/http-server-ref
// Legacy FCM/GCM API (https://firebase.google.com/docs/cloud-messaging/migrate-v1):
// 1. copy server key from: https://console.firebase.google.com/project/_/settings/cloudmessaging/
// 2. add to request header: Authorization:key=<server key>
type Client struct {
	client *http.Client

	// count send retries
	retries int

	// authorization key:
	// https://firebase.google.com/docs/cloud-messaging/migrate-v1#before_2
	headerAuthorization string

	sandbox bool
}

func New(key []byte, isSandbox bool, retries int, timeout time.Duration) (*Client, error) {

	if timeout <= 0 {
		timeout = time.Second * 10
	}

	return &Client{
		headerAuthorization: "key=" + string(key),
		retries:             retries,
		sandbox:             isSandbox,
		client: &http.Client{
			Timeout: timeout,
		},
	}, nil
}

func (c *Client) Sandbox() bool {
	return c.sandbox
}

func (c *Client) Send(ctx context.Context, message *Request) (retval *Response, err error) {

	req, err := c.newRequest(ctx)
	if err != nil {
		return nil, err
	}

	if c.sandbox && message != nil {
		message.DryRun = true
	}

	fnSend := func() (int, error) {
		retval, err = c.send(ctx, req, message)
		if err != nil {
			return 0, err
		}

		return retval.StatusCode, err
	}

	err = provider.SendWithRetry(c.retries, fnSend)
	if err != nil {
		return nil, err
	}

	return retval, nil
}

func (c *Client) send(ctx context.Context, req *http.Request, message *Request) (*Response, error) {

	pipe := provider.NewPipe(func(w io.Writer) error {
		// message format:
		// https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream-http-messages-json
		return json.NewEncoder(w).Encode(message)
	})
	defer pipe.Close()

	req.Body = pipe

	res, err := c.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	retval := &Response{
		StatusCode: res.StatusCode,
	}

	// https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes
	if res.StatusCode == 200 || res.StatusCode == 400 {
		if err := provider.DecodeJSONResponse(res.Body, retval); err != nil {
			outInfo, errEncode := provider.JSONWithoutSecrets(message)
			if errEncode != nil {
				outInfo = []byte(errEncode.Error())
			}
			return nil, errors.Wrap(err, "invalid gcm response: source: "+string(outInfo))
		}
	}

	return retval, nil
}

func (c *Client) newRequest(ctx context.Context) (*http.Request, error) {

	req, err := http.NewRequest(http.MethodPost, "https://fcm.googleapis.com/fcm/send", nil)
	if err != nil {
		return nil, err
	}

	// token format:
	// https://firebase.google.com/docs/cloud-messaging/migrate-v1#before_2
	req.Header.Set("Authorization", c.headerAuthorization)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Content-Length", "-1")
	req = req.WithContext(ctx)

	return req, nil
}


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

/**
 * A header for declaring various things that binding implementation headers
 * might need.  The idea is to make binding implementation headers safe to
 * include anywhere without running into include hell like we do with
 * BindingUtils.h
 */
#ifndef mozilla_dom_BindingDeclarations_h__
#define mozilla_dom_BindingDeclarations_h__

#include "nsStringGlue.h"
#include "js/Value.h"
#include "js/RootingAPI.h"
#include "mozilla/Maybe.h"
#include "nsCOMPtr.h"
#include "nsTArray.h"
#include "nsAutoPtr.h" // for nsRefPtr member variables
#include "mozilla/dom/DOMString.h"
#include "mozilla/dom/OwningNonNull.h"

class nsWrapperCache;

namespace mozilla {
namespace dom {

// Struct that serves as a base class for all dictionaries.  Particularly useful
// so we can use IsBaseOf to detect dictionary template arguments.
struct DictionaryBase
{
protected:
  bool ParseJSON(JSContext* aCx, const nsAString& aJSON,
                 JS::MutableHandle<JS::Value> aVal);

  bool StringifyToJSON(JSContext* aCx,
                       JS::MutableHandle<JS::Value> aValue,
                       nsAString& aJSON) const;

  // Struct used as a way to force a dictionary constructor to not init the
  // dictionary (via constructing from a pointer to this class).  We're putting
  // it here so that all the dictionaries will have access to it, but outside
  // code will not.
  struct FastDictionaryInitializer {
  };

private:
  // aString is expected to actually be an nsAString*.  Should only be
  // called from StringifyToJSON.
  static bool AppendJSONToString(const char16_t* aJSONData,
                                 uint32_t aDataLength, void* aString);
};

// Struct that serves as a base class for all typed arrays and array buffers and
// array buffer views.  Particularly useful so we can use IsBaseOf to detect
// typed array/buffer/view template arguments.
struct AllTypedArraysBase {
};

// Struct that serves as a base class for all owning unions.
// Particularly useful so we can use IsBaseOf to detect owning union
// template arguments.
struct AllOwningUnionBase {
};

struct EnumEntry {
  const char* value;
  size_t length;
};

class MOZ_STACK_CLASS GlobalObject
{
public:
  GlobalObject(JSContext* aCx, JSObject* aObject);

  JSObject* Get() const
  {
    return mGlobalJSObject;
  }

  nsISupports* GetAsSupports() const;

  // The context that this returns is not guaranteed to be in the compartment of
  // the object returned from Get(), in fact it's generally in the caller's
  // compartment.
  JSContext* Context() const
  {
    return mCx;
  }

  bool Failed() const
  {
    return !Get();
  }

protected:
  JS::Rooted<JSObject*> mGlobalJSObject;
  JSContext* mCx;
  mutable nsISupports* MOZ_UNSAFE_REF("Valid because GlobalObject is a stack "
                                      "class, and mGlobalObject points to the "
                                      "global, so it won't be destroyed as long "
                                      "as GlobalObject lives on the stack") mGlobalObject;
};

// Class for representing optional arguments.
template<typename T, typename InternalType>
class Optional_base
{
public:
  Optional_base()
  {}

  explicit Optional_base(const T& aValue)
  {
    mImpl.emplace(aValue);
  }

  template<typename T1, typename T2>
  explicit Optional_base(const T1& aValue1, const T2& aValue2)
  {
    mImpl.emplace(aValue1, aValue2);
  }

  bool WasPassed() const
  {
    return mImpl.isSome();
  }

  // Return InternalType here so we can work with it usefully.
  InternalType& Construct()
  {
    mImpl.emplace();
    return *mImpl;
  }

  template <class T1>
  InternalType& Construct(const T1 &t1)
  {
    mImpl.emplace(t1);
    return *mImpl;
  }

  template <class T1, class T2>
  InternalType& Construct(const T1 &t1, const T2 &t2)
  {
    mImpl.emplace(t1, t2);
    return *mImpl;
  }

  void Reset()
  {
    mImpl.reset();
  }

  const T& Value() const
  {
    return *mImpl;
  }

  // Return InternalType here so we can work with it usefully.
  InternalType& Value()
  {
    return *mImpl;
  }

  // And an explicit way to get the InternalType even if we're const.
  const InternalType& InternalValue() const
  {
    return *mImpl;
  }

  // If we ever decide to add conversion operators for optional arrays
  // like the ones Nullable has, we'll need to ensure that Maybe<> has
  // the boolean before the actual data.

private:
  // Forbid copy-construction and assignment
  Optional_base(const Optional_base& other) = delete;
  const Optional_base &operator=(const Optional_base &other) = delete;

protected:
  Maybe<InternalType> mImpl;
};

template<typename T>
class Optional : public Optional_base<T, T>
{
public:
  Optional() :
    Optional_base<T, T>()
  {}

  explicit Optional(const T& aValue) :
    Optional_base<T, T>(aValue)
  {}
};

template<typename T>
class Optional<JS::Handle<T> > :
  public Optional_base<JS::Handle<T>, JS::Rooted<T> >
{
public:
  Optional() :
    Optional_base<JS::Handle<T>, JS::Rooted<T> >()
  {}

  explicit Optional(JSContext* cx) :
    Optional_base<JS::Handle<T>, JS::Rooted<T> >()
  {
    this->Construct(cx);
  }

  Optional(JSContext* cx, const T& aValue) :
    Optional_base<JS::Handle<T>, JS::Rooted<T> >(cx, aValue)
  {}

  // Override the const Value() to return the right thing so we're not
  // returning references to temporaries.
  JS::Handle<T> Value() const
  {
    return *this->mImpl;
  }

  // And we have to override the non-const one too, since we're
  // shadowing the one on the superclass.
  JS::Rooted<T>& Value()
  {
    return *this->mImpl;
  }
};

// A specialization of Optional for JSObject* to make sure that when someone
// calls Construct() on it we will pre-initialized the JSObject* to nullptr so
// it can be traced safely.
template<>
class Optional<JSObject*> : public Optional_base<JSObject*, JSObject*>
{
public:
  Optional() :
    Optional_base<JSObject*, JSObject*>()
  {}

  explicit Optional(JSObject* aValue) :
    Optional_base<JSObject*, JSObject*>(aValue)
  {}

  // Don't allow us to have an uninitialized JSObject*
  JSObject*& Construct()
  {
    // The Android compiler sucks and thinks we're trying to construct
    // a JSObject* from an int if we don't cast here.  :(
    return Optional_base<JSObject*, JSObject*>::Construct(
      static_cast<JSObject*>(nullptr));
  }

  template <class T1>
  JSObject*& Construct(const T1& t1)
  {
    return Optional_base<JSObject*, JSObject*>::Construct(t1);
  }
};

// A specialization of Optional for JS::Value to make sure no one ever uses it.
template<>
class Optional<JS::Value>
{
private:
  Optional() = delete;

  explicit Optional(JS::Value aValue) = delete;
};

// A specialization of Optional for NonNull that lets us get a T& from Value()
template<typename U> class NonNull;
template<typename T>
class Optional<NonNull<T> > : public Optional_base<T, NonNull<T> >
{
public:
  // We want our Value to actually return a non-const reference, even
  // if we're const.  At least for things that are normally pointer
  // types...
  T& Value() const
  {
    return *this->mImpl->get();
  }

  // And we have to override the non-const one too, since we're
  // shadowing the one on the superclass.
  NonNull<T>& Value()
  {
    return *this->mImpl;
  }
};

// A specialization of Optional for OwningNonNull that lets us get a
// T& from Value()
template<typename T>
class Optional<OwningNonNull<T> > : public Optional_base<T, OwningNonNull<T> >
{
public:
  // We want our Value to actually return a non-const reference, even
  // if we're const.  At least for things that are normally pointer
  // types...
  T& Value() const
  {
    return *this->mImpl->get();
  }

  // And we have to override the non-const one too, since we're
  // shadowing the one on the superclass.
  OwningNonNull<T>& Value()
  {
    return *this->mImpl;
  }
};

// Specialization for strings.
// XXXbz we can't pull in FakeString here, because it depends on internal
// strings.  So we just have to forward-declare it and reimplement its
// ToAStringPtr.

namespace binding_detail {
struct FakeString;
} // namespace binding_detail

template<>
class Optional<nsAString>
{
public:
  Optional() : mPassed(false) {}

  bool WasPassed() const
  {
    return mPassed;
  }

  void operator=(const nsAString* str)
  {
    MOZ_ASSERT(str);
    mStr = str;
    mPassed = true;
  }

  // If this code ever goes away, remove the comment pointing to it in the
  // FakeString class in BindingUtils.h.
  void operator=(const binding_detail::FakeString* str)
  {
    MOZ_ASSERT(str);
    mStr = reinterpret_cast<const nsString*>(str);
    mPassed = true;
  }

  const nsAString& Value() const
  {
    MOZ_ASSERT(WasPassed());
    return *mStr;
  }

private:
  // Forbid copy-construction and assignment
  Optional(const Optional& other) = delete;
  const Optional &operator=(const Optional &other) = delete;

  bool mPassed;
  const nsAString* mStr;
};

template<class T>
class NonNull
{
public:
  NonNull()
#ifdef DEBUG
    : inited(false)
#endif
  {}

  // This is no worse than get() in terms of const handling.
  operator T&() const {
    MOZ_ASSERT(inited);
    MOZ_ASSERT(ptr, "NonNull<T> was set to null");
    return *ptr;
  }

  operator T*() const {
    MOZ_ASSERT(inited);
    MOZ_ASSERT(ptr, "NonNull<T> was set to null");
    return ptr;
  }

  void operator=(T* t) {
    ptr = t;
    MOZ_ASSERT(ptr);
#ifdef DEBUG
    inited = true;
#endif
  }

  template<typename U>
  void operator=(U* t) {
    ptr = t->ToAStringPtr();
    MOZ_ASSERT(ptr);
#ifdef DEBUG
    inited = true;
#endif
  }

  T** Slot() {
#ifdef DEBUG
    inited = true;
#endif
    return &ptr;
  }

  T* Ptr() {
    MOZ_ASSERT(inited);
    MOZ_ASSERT(ptr, "NonNull<T> was set to null");
    return ptr;
  }

  // Make us work with smart-ptr helpers that expect a get()
  T* get() const {
    MOZ_ASSERT(inited);
    MOZ_ASSERT(ptr);
    return ptr;
  }

protected:
  T* ptr;
#ifdef DEBUG
  bool inited;
#endif
};

// Class for representing sequences in arguments.  We use a non-auto array
// because that allows us to use sequences of sequences and the like.  This
// needs to be fallible because web content controls the length of the array,
// and can easily try to create very large lengths.
template<typename T>
class Sequence : public FallibleTArray<T>
{
public:
  Sequence() : FallibleTArray<T>()
  {}
};

inline nsWrapperCache*
GetWrapperCache(nsWrapperCache* cache)
{
  return cache;
}

inline nsWrapperCache*
GetWrapperCache(void* p)
{
  return nullptr;
}

// Helper template for smart pointers to resolve ambiguity between
// GetWrappeCache(void*) and GetWrapperCache(const ParentObject&).
template <template <typename> class SmartPtr, typename T>
inline nsWrapperCache*
GetWrapperCache(const SmartPtr<T>& aObject)
{
  return GetWrapperCache(aObject.get());
}

struct MOZ_STACK_CLASS ParentObject {
  template<class T>
  ParentObject(T* aObject) :
    mObject(aObject),
    mWrapperCache(GetWrapperCache(aObject)),
    mUseXBLScope(false)
  {}

  template<class T, template<typename> class SmartPtr>
  ParentObject(const SmartPtr<T>& aObject) :
    mObject(aObject.get()),
    mWrapperCache(GetWrapperCache(aObject.get())),
    mUseXBLScope(false)
  {}

  ParentObject(nsISupports* aObject, nsWrapperCache* aCache) :
    mObject(aObject),
    mWrapperCache(aCache),
    mUseXBLScope(false)
  {}

  // We don't want to make this an nsCOMPtr because of performance reasons, but
  // it's safe because ParentObject is a stack class.
  nsISupports* const MOZ_NON_OWNING_REF mObject;
  nsWrapperCache* const mWrapperCache;
  bool mUseXBLScope;
};

} // namespace dom
} // namespace mozilla

#endif // mozilla_dom_BindingDeclarations_h__


text:
layout: page
title: ec-Ecuador
---
{% include postbycat key="ec" %}


text:
module ActiveRecordPGTasks
  def drop
    establish_master_connection
    connection.select_all <<-SQL.squish
      SELECT pg_terminate_backend(pg_stat_activity.pid)
      FROM pg_stat_activity
      WHERE datname='#{configuration['database']}' AND state='idle';
    SQL
    connection.drop_database configuration["database"]
  end
end

ActiveRecord::Tasks::PostgreSQLDatabaseTasks.prepend(ActiveRecordPGTasks)


text:
package main

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestUnIndexError(t *testing.T) {
	assert.NotNil(t, unIndex(""))
}

func TestGetIndexError(t *testing.T) {
	idx, err := getIndex("")
	assert.Nil(t, idx)
	assert.NotNil(t, err)
}

func TestGetIndexNoteError(t *testing.T) {
	assert.NotNil(t, indexNote(Note{UID: ""}))
}

func TestReIndex(t *testing.T) {
	mock := setup(t)
	defer tearDown(mock)
	createTestNote(mock, "")
	assert.Nil(t, reIndex(mock.db))
}


text:
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.dataStorage.database;

import gov.nih.nci.caarray.application.fileaccess.TemporaryFileCache;
import gov.nih.nci.caarray.dataStorage.spi.DataStorage;
import gov.nih.nci.caarray.dataStorage.spi.StorageUnitOfWork;

import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import com.google.inject.multibindings.MapBinder;
import com.google.inject.multibindings.Multibinder;
import com.google.inject.name.Names;

/**
 * Guice module for the database-based data storage plugin.
 *
 * @author dkokotov
 */
public class DatabaseStorageModule extends AbstractModule {

    /**
     * {@inheritDoc}
     */
    @Override
    protected void configure() {
        final MapBinder<String, DataStorage> mapBinder = MapBinder.newMapBinder(binder(), String.class,
                DataStorage.class);
        mapBinder.addBinding(DatabaseMultipartBlobDataStorage.SCHEME).to(DatabaseMultipartBlobDataStorage.class);

        final Multibinder<StorageUnitOfWork> unitBinder = Multibinder.newSetBinder(binder(), StorageUnitOfWork.class);
        bind(DatabaseStorageUnitOfWork.class).in(Singleton.class);
        unitBinder.addBinding().to(DatabaseStorageUnitOfWork.class);

        bind(TemporaryFileCache.class).annotatedWith(Names.named("dbMultipartStorageTempCache")).toProvider(
                DatabaseStorageUnitOfWork.class);
    }
}


text:
"""
Script that trains progressive multitask models on HOPV dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals

import os
import shutil
import numpy as np
import deepchem as dc
from deepchem.molnet import load_hopv

# Only for debug!
np.random.seed(123)

# Load HOPV dataset
n_features = 1024
hopv_tasks, hopv_datasets, transformers = load_hopv()
train_dataset, valid_dataset, test_dataset = hopv_datasets

# Fit models
metric = [
    dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"),
    dc.metrics.Metric(
        dc.metrics.mean_absolute_error, np.mean, mode="regression")
]

model = dc.models.ProgressiveMultitaskRegressor(
    len(hopv_tasks),
    n_features,
    layer_sizes=[1000],
    dropouts=[.25],
    learning_rate=0.001,
    batch_size=50)

# Fit trained model
model.fit(train_dataset, nb_epoch=25)

print("Evaluating model")
train_scores = model.evaluate(train_dataset, metric, transformers)
valid_scores = model.evaluate(valid_dataset, metric, transformers)

print("Train scores")
print(train_scores)

print("Validation scores")
print(valid_scores)


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInitf666168e7a491cc40ebebd55a28299b2::getLoader();


text:
module.exports = function(karma) {
  var common = require('../../tools/test/karma-common.conf.js');

  karma.set(common.mixin_common_opts(karma, {
    // base path, that will be used to resolve files and exclude
    basePath: '../../',

    // list of files / patterns to load in the browser
    files: [
      'tools/test/mocha-htmltest.js',
      'CustomElements/conf/mocha.conf.js',
      'CustomElements/../tools/test/chai/chai.js',
      'CustomElements/custom-elements.js',
      'CustomElements/test/js/*.js',
      {pattern: 'CustomElements/src/*', included: false},
      {pattern: 'CustomElements/test/html/*.html', included: false},
      {pattern: 'MutationObservers/*.js', included: false},
      {pattern: 'WeakMap/*.js', included: false},
      {pattern: 'tools/**/*.js', included: false}
    ]
  }));
};


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { LegendDataQualityComponent } from './legend-data-quality.component';

describe('LegendDataQualityComponent', () => {
  let component: LegendDataQualityComponent;
  let fixture: ComponentFixture<LegendDataQualityComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LegendDataQualityComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LegendDataQualityComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxNtfsDb extends BxBaseModNotificationsDb
{
    protected $_sTableEvt2Usr;

    /*
     * Constructor.
     */
    function __construct(&$oConfig)
    {
        parent::__construct($oConfig);
        $this->_sTableEvt2Usr = $this->_sPrefix . 'events2users';
    }

    public function markAsRead($iUserId, $iEventId)
    {
    	$sSql = $this->prepare("REPLACE `" . $this->_sTableEvt2Usr . "` SET `user_id`=?, `event_id`=?", $iUserId, $iEventId);
    	return (int)$this->query($sSql) > 0;
    }

	protected function _getSqlPartsEventsList($aParams)
	{
		$sJoinClause = $sWhereClause = "";

		if(isset($aParams['active']))
			$sWhereClause .= $this->prepareAsString("AND `{$this->_sTable}`.`active`=? ", (int)$aParams['active']);

		//--- Apply modules or handlers filter
		$sWhereModuleFilter = '';
		if(!empty($aParams['modules']) && is_array($aParams['modules']))
			$sWhereModuleFilter = "AND `" . $this->_sTable . "`.`type` IN (" . $this->implode_escape($aParams['modules']) . ") ";

		if($sWhereModuleFilter == '') {
			$aHidden = $this->_oConfig->getHandlersHidden();
			$sWhereModuleFilter = !empty($aHidden) && is_array($aHidden) ? "AND `" . $this->_sTableHandlers . "`.`id` NOT IN (" . $this->implode_escape($aHidden) . ") " : "";
		}

		if($sWhereModuleFilter != '')
			$sWhereClause .= $sWhereModuleFilter;

		//--- Check flag 'New'
		if(!empty($aParams['new']) && !empty($aParams['owner_id'])) {
			$sSql = $this->prepare("SELECT `event_id` FROM `" . $this->_sTableEvt2Usr . "` WHERE `user_id`=? LIMIT 1", (int)$aParams['owner_id']);
			$iId = (int)$this->getOne($sSql);

			$sWhereClause .= $this->prepareAsString("AND `{$this->_sTable}`.`id`>? ", $iId);
		}

		//--- Apply privacy filter
		$aPrivacy = array(BX_DOL_PG_ALL);
		if(isLogged())
			$aPrivacy[] = BX_DOL_PG_MEMBERS;

		$oPrivacy = BxDolPrivacy::getObjectInstance($this->_oConfig->getObject('privacy_view'));
		$aQueryParts = $oPrivacy->getContentByGroupAsSQLPart($aPrivacy);
		$sWhereClause .= $aQueryParts['where'] . " ";

		//--- Check type
		if(!empty($aParams['owner_id']))
			switch($aParams['type']) {
				case BX_BASE_MOD_NTFS_TYPE_OWNER:
					$sWhereClause .= $this->prepareAsString("AND `{$this->_sTable}`.`owner_id`=? ", $aParams['owner_id']);
					break;

				case BX_BASE_MOD_NTFS_TYPE_OBJECT_OWNER:
					$sWhereClause .= $this->prepareAsString("AND `{$this->_sTable}`.`owner_id`<>`{$this->_sTable}`.`object_owner_id` AND `{$this->_sTable}`.`object_owner_id`=? ", $aParams['owner_id']);
					break;

				case BX_BASE_MOD_NTFS_TYPE_CONNECTIONS:
					$oConnection = BxDolConnection::getObjectInstance($this->_oConfig->getObject('conn_subscriptions'));

					$aQueryParts = $oConnection->getConnectedContentAsSQLParts($this->_sPrefix . "events", 'owner_id', $aParams['owner_id']);
					$sJoinClause .= ' ' . $aQueryParts['join'];
					break;
			}

		return array($sJoinClause, $sWhereClause);
	}
}

/** @} */


text:
package internet

import (
	"github.com/sacloud/libsacloud/v2/helper/validate"
	"github.com/sacloud/libsacloud/v2/sacloud/types"
)

type EnableIPv6Request struct {
	Zone string   `request:"-" validate:"required"`
	ID   types.ID `request:"-" validate:"required"`
}

func (req *EnableIPv6Request) Validate() error {
	return validate.Struct(req)
}


text:
package fi.csc.microarray.client.serverfiles;

import java.awt.Component;
import java.awt.Container;

import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFileChooser;

public class ServerFileUtils {

	public static void hideJFileChooserButtons(JFileChooser sessionFileChooser) {
		// stupid graphical buttons do not seem to have anything better than tooltip for identification
		hideChildButtonsWithTooltip(sessionFileChooser, "Sessions at server");
		hideChildButtonsWithTooltip(sessionFileChooser, "Up One Level");
		hideChildButtonsWithTooltip(sessionFileChooser, "Remote sessions");
		hideChildButtonsWithTooltip(sessionFileChooser, "Create New Folder");
		hideChildButtonsWithTooltip(sessionFileChooser, "List");
		hideChildButtonsWithTooltip(sessionFileChooser, "Details");
	}

	/**
	 * Find button by tooltip
	 *
	 * @param parent
	 * @param tooltip
	 */
	private static void hideChildButtonsWithTooltip(Container parent, String tooltip) {

		for (Component component : parent.getComponents()) {
			if (component instanceof AbstractButton && tooltip.equals(((AbstractButton)component).getToolTipText())) {
				component.setVisible(false); // hide this
			} else if (component instanceof Container ){
				hideChildButtonsWithTooltip((Container)component, tooltip);
			}
		}

	}

	/**
	 * Find button by text
	 *
	 * @param c
	 * @param text
	 * @return
	 */
	private static JButton lookupButton(Container c, String text) {
	    JButton button = null;
	    for (Component comp : c.getComponents()) {
	        if (comp == null) {
	            continue;
	        }
	        if (comp instanceof JButton && (button = (JButton) comp).getText() != null && button.getText().equals(text)) {
	            return button;
	        } else if (comp instanceof Container) {
	            if ((button = lookupButton((Container) comp, text)) != null) {
	                return button;
	            }
	        }
	    }
	    return button;
	}

	public static void addButton(JFileChooser fileChooser) {
		// this will initialize the button and its parent component
		fileChooser.setApproveButtonText("approveButton");
		JButton button = lookupButton(fileChooser, "approveButton");
		// reset approve button text
		fileChooser.setApproveButtonText(null);
		// add a new button
		button.getParent().add(new JButton("Save"), 0);
	}

	public static void hideApproveButton(JFileChooser fileChooser) {
		// this will initialize the button and its parent component
		fileChooser.setApproveButtonText("approveButton");
		JButton button = lookupButton(fileChooser, "approveButton");
		// reset approve button text
		fileChooser.setApproveButtonText(null);
		// hide it
		button.setVisible(false);
	}

	public static void setCancelButtonText(JFileChooser fileChooser, String text) {
		JButton button = lookupButton(fileChooser, "Cancel");
		if (button != null) {
			button.setText(text);
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="10"
        android:useLevel="false" >

    <gradient
        android:centerColor="#ffffff"
        android:centerY="0.5"
        android:endColor="#4caf50"
        android:startColor="#c8e6c9"
        android:type="sweep"
        android:useLevel="false" />

    </shape>

</rotate>


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.typeFromAST = typeFromAST;

var _invariant = require('../jsutils/invariant');

var _invariant2 = _interopRequireDefault(_invariant);

var _kinds = require('../language/kinds');

var _definition = require('../type/definition');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function typeFromAST(schema, typeNode) {
  var innerType = void 0;
  if (typeNode.kind === _kinds.LIST_TYPE) {
    innerType = typeFromAST(schema, typeNode.type);
    return innerType && new _definition.GraphQLList(innerType);
  }
  if (typeNode.kind === _kinds.NON_NULL_TYPE) {
    innerType = typeFromAST(schema, typeNode.type);
    return innerType && new _definition.GraphQLNonNull(innerType);
  }
  (0, _invariant2.default)(typeNode.kind === _kinds.NAMED_TYPE, 'Must be a named type.');
  return schema.getType(typeNode.name.value);
}


text:
package rctrl

import (
	"github.com/scionproto/scion/go/border/rctx"
	"github.com/scionproto/scion/go/border/rpkt"
	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/ctrl"
	"github.com/scionproto/scion/go/lib/ctrl/path_mgmt"
	"github.com/scionproto/scion/go/lib/log"
	"github.com/scionproto/scion/go/lib/snet"
)

// RevInfoFwd takes RevInfos, and forwards them to the local Beacon Service
// (BS) and Path Service (PS).
func revInfoFwd(revInfoQ chan rpkt.RawSRevCallbackArgs) {
	// Run forever.
	for args := range revInfoQ {
		revInfo, err := args.SignedRevInfo.RevInfo()
		if err != nil {
			logger.Error("Error getting RevInfo from SignedRevInfo", "err", err)
		}
		logger.Debug("Forwarding revocation", "revInfo", revInfo.String(), "targets", args.Addrs)
		for _, svcAddr := range args.Addrs {
			fwdRevInfo(args.SignedRevInfo, svcAddr)
		}
	}
}

// fwdRevInfo forwards RevInfo payloads to a designated local host.
func fwdRevInfo(sRevInfo *path_mgmt.SignedRevInfo, dstHost addr.HostSVC) {
	ctx := rctx.Get()
	cpld, err := ctrl.NewPathMgmtPld(sRevInfo, nil, nil)
	if err != nil {
		log.Error("Error generating RevInfo Ctrl payload", "err", err)
		return
	}
	scpld, err := cpld.SignedPld(ctrl.NullSigner)
	if err != nil {
		log.Error("Error generating RevInfo signed Ctrl payload", "err", err)
		return
	}
	pld, err := scpld.PackPld()
	if err != nil {
		logger.Error("Writing RevInfo signed Ctrl payload", "err", err)
		return
	}
	dst := &snet.Addr{
		IA:   ia,
		Host: &addr.AppAddr{L3: dstHost, L4: addr.NewL4UDPInfo(0)},
	}
	dst.NextHop, err = ctx.ResolveSVCAny(dstHost)
	if err != nil {
		logger.Error("Resolving SVC anycast", "err", err, "addr", dst)
		return
	}
	if _, err := snetConn.WriteToSCION(pld, dst); err != nil {
		logger.Error("Writing RevInfo", "dst", dst, "err", err)
	}
	logger.Debug("Sent RevInfo", "dst", dst, "overlayDst", dst.NextHop)
}


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

{% block title %}Aggregates for Project {{ project.name }}{% endblock title %}

{% block content %}

Add an Aggregate for Project {{ project.name }}

		{% if aggregate_list.count %}
			{% with "project/agg_add_actions.html" as action_template %}
				{% include "aggregate/list_table.html" %}
			{% endwith %}
		{% else %}
			Either this project has all aggregates or there are no aggregates
			installed at this Expedient. Sorry, no aggregates to add.
		{% endif %}

		<input type="button" value="Done"
		onclick="document.location='{% url project_detail project.id %}'" />

{% endblock content %}


text:
PLATFORM = $(shell uname)

PROJECT_NAME=NESasm
PROJECT_TAG?=nesasm

PYTHON_MODULES=nesasm

NESASM_C_PATH=tools/nesasm
NESASM_C_MAKE=${NESASM_C_PATH}/Makefile
NESASM_C_BIN=${NESASM_C_PATH}/bin/nesasm

WGET = wget -q

OK=\033[32m[OK]\033[39m
FAIL=\033[31m[FAIL]\033[39m
CHECK=@if [ $$? -eq 0 ]; then echo "${OK}"; else echo "${FAIL}" ; fi

default: python.mk github.mk
	@$(MAKE) -C . test

ifeq "true" "${shell test -f python.mk && echo true}"
include python.mk
endif

ifeq "true" "${shell test -f github.mk && echo true}"
include github.mk
endif

python.mk:
	@${WGET} https://raw.githubusercontent.com/gutomaia/makery/master/python.mk && \
		touch $@

github.mk:
	@${WGET} https://raw.githubusercontent.com/gutomaia/makery/master/github.mk && \
		touch $@

clean: python_clean

purge: python_purge
	@rm -rf python.mk github.mk
	@rm -rf tools
	@rm -rf .tox

build: python_build

test: python_build ${REQUIREMENTS_TEST} ${CHECKPOINT_DIR}/.python_develop
	${VIRTUALENV} nosetests --processes=2

${NESASM_C_MAKE}:
	mkdir -p tools
	cd tools && git clone https://github.com/toastynerd/nesasm.git

${NESASM_C_BIN}: ${NESASM_C_MAKE}
	@$(MAKE) -C ${NESASM_C_PATH}

tools: ${NESASM_C_BIN}

ci: build ${REQUIREMENTS_TEST} ${CHECKPOINT_DIR}/.python_develop tools
	${VIRTUALENV} CI=1 nosetests -v --with-timer --timer-top-n 0 --with-coverage --cover-xml --cover-package=${PYTHON_MODULES} ${PYTHON_MODULES}

pep8: ${REQUIREMENTS_TEST}
	${VIRTUALENV} pep8 --statistics -qq nesasm | sort -rn || echo ''

todo:
	${VIRTUALENV} pep8 --first nesasm
	find nesasm -type f | xargs -I [] grep -H TODO []

search:
	find nesasm -regex .*\.py$ | xargs -I [] egrep -H -n 'print|ipdb' [] || echo ''

tdd:
	${VIRTUALENV} tdaemon --ignore-dirs="build,dist,bin,site,nesasm.egg-info,venv,.tox" --custom-args="-e image_test.py --with-notify --no-start-message"

tox: ${REQUIREMENTS_TEST}
	${VIRTUALENV} tox

${HOME}/.pypirc:
	@echo "[distutils]" >> $@
	@echo "index-servers = pypi" >> $@
	@echo "" >> $@
	@echo "[pypi]" >> $@
	@echo "username = ${PYPI_USERNAME}" >> $@
	@echo "password = ${PYPI_PASSWORD}" >> $@
	@touch $@

dist: python_egg python_wheel

register:
	${VIRTUALENV} python setup.py register -r pypi

distribute: dist ${HOME}/.pypirc
	${VIRTUALENV} python setup.py bdist_egg bdist_wheel upload -r pypi

.PHONY: install clean report dist register distribute ghpages


text:
.class Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;
.super Landroid/graphics/drawable/Drawable$ConstantState;
.source "AnimatedVectorDrawableCompat.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "AnimatedVectorDrawableCompatState"
.end annotation

# instance fields
.field mAnimatorSet:Landroid/animation/AnimatorSet;

.field private mAnimators:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Landroid/animation/Animator;",
            ">;"
        }
    .end annotation
.end field

.field mChangingConfigurations:I

.field mTargetNameMap:Landroid/support/v4/util/ArrayMap;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/support/v4/util/ArrayMap",
            "<",
            "Landroid/animation/Animator;",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation
.end field

.field mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

# direct methods
.method static synthetic -get0(Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;)Ljava/util/ArrayList;
    .locals 1

    iget-object v0, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimators:Ljava/util/ArrayList;

    return-object v0
.end method

.method static synthetic -set0(Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;Ljava/util/ArrayList;)Ljava/util/ArrayList;
    .locals 0

    iput-object p1, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimators:Ljava/util/ArrayList;

    return-object p1
.end method

.method public constructor <init>(Landroid/content/Context;Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;Landroid/graphics/drawable/Drawable$Callback;Landroid/content/res/Resources;)V
    .locals 9

    invoke-direct {p0}, Landroid/graphics/drawable/Drawable$ConstantState;-><init>()V

    if-eqz p2, :cond_3

    iget v7, p2, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mChangingConfigurations:I

    iput v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mChangingConfigurations:I

    iget-object v7, p2, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    if-eqz v7, :cond_0

    iget-object v7, p2, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    invoke-virtual {v7}, Landroid/support/graphics/drawable/VectorDrawableCompat;->getConstantState()Landroid/graphics/drawable/Drawable$ConstantState;

    move-result-object v2

    if-eqz p4, :cond_1

    invoke-virtual {v2, p4}, Landroid/graphics/drawable/Drawable$ConstantState;->newDrawable(Landroid/content/res/Resources;)Landroid/graphics/drawable/Drawable;

    move-result-object v7

    check-cast v7, Landroid/support/graphics/drawable/VectorDrawableCompat;

    iput-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    :goto_0
    iget-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    invoke-virtual {v7}, Landroid/support/graphics/drawable/VectorDrawableCompat;->mutate()Landroid/graphics/drawable/Drawable;

    move-result-object v7

    check-cast v7, Landroid/support/graphics/drawable/VectorDrawableCompat;

    iput-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    iget-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    invoke-virtual {v7, p3}, Landroid/support/graphics/drawable/VectorDrawableCompat;->setCallback(Landroid/graphics/drawable/Drawable$Callback;)V

    iget-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    iget-object v8, p2, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    invoke-virtual {v8}, Landroid/support/graphics/drawable/VectorDrawableCompat;->getBounds()Landroid/graphics/Rect;

    move-result-object v8

    invoke-virtual {v7, v8}, Landroid/support/graphics/drawable/VectorDrawableCompat;->setBounds(Landroid/graphics/Rect;)V

    iget-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    const/4 v8, 0x0

    invoke-virtual {v7, v8}, Landroid/support/graphics/drawable/VectorDrawableCompat;->setAllowCaching(Z)V

    :cond_0
    iget-object v7, p2, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimators:Ljava/util/ArrayList;

    if-eqz v7, :cond_3

    iget-object v7, p2, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimators:Ljava/util/ArrayList;

    invoke-virtual {v7}, Ljava/util/ArrayList;->size()I

    move-result v4

    new-instance v7, Ljava/util/ArrayList;

    invoke-direct {v7, v4}, Ljava/util/ArrayList;-><init>(I)V

    iput-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimators:Ljava/util/ArrayList;

    new-instance v7, Landroid/support/v4/util/ArrayMap;

    invoke-direct {v7, v4}, Landroid/support/v4/util/ArrayMap;-><init>(I)V

    iput-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mTargetNameMap:Landroid/support/v4/util/ArrayMap;

    const/4 v3, 0x0

    :goto_1
    if-ge v3, v4, :cond_2

    iget-object v7, p2, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimators:Ljava/util/ArrayList;

    invoke-virtual {v7, v3}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/animation/Animator;

    invoke-virtual {v0}, Landroid/animation/Animator;->clone()Landroid/animation/Animator;

    move-result-object v1

    iget-object v7, p2, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mTargetNameMap:Landroid/support/v4/util/ArrayMap;

    invoke-virtual {v7, v0}, Landroid/support/v4/util/ArrayMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v5

    check-cast v5, Ljava/lang/String;

    iget-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    invoke-virtual {v7, v5}, Landroid/support/graphics/drawable/VectorDrawableCompat;->getTargetByName(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v6

    invoke-virtual {v1, v6}, Landroid/animation/Animator;->setTarget(Ljava/lang/Object;)V

    iget-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimators:Ljava/util/ArrayList;

    invoke-virtual {v7, v1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z

    iget-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mTargetNameMap:Landroid/support/v4/util/ArrayMap;

    invoke-virtual {v7, v1, v5}, Landroid/support/v4/util/ArrayMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    add-int/lit8 v3, v3, 0x1

    goto :goto_1

    :cond_1
    invoke-virtual {v2}, Landroid/graphics/drawable/Drawable$ConstantState;->newDrawable()Landroid/graphics/drawable/Drawable;

    move-result-object v7

    check-cast v7, Landroid/support/graphics/drawable/VectorDrawableCompat;

    iput-object v7, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mVectorDrawable:Landroid/support/graphics/drawable/VectorDrawableCompat;

    goto :goto_0

    :cond_2
    invoke-virtual {p0}, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->setupAnimatorSet()V

    :cond_3
    return-void
.end method

# virtual methods
.method public getChangingConfigurations()I
    .locals 1

    iget v0, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mChangingConfigurations:I

    return v0
.end method

.method public newDrawable()Landroid/graphics/drawable/Drawable;
    .locals 2

    new-instance v0, Ljava/lang/IllegalStateException;

    const-string/jumbo v1, "No constant state support for SDK < 24."

    invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V

    throw v0
.end method

.method public newDrawable(Landroid/content/res/Resources;)Landroid/graphics/drawable/Drawable;
    .locals 2

    new-instance v0, Ljava/lang/IllegalStateException;

    const-string/jumbo v1, "No constant state support for SDK < 24."

    invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V

    throw v0
.end method

.method public setupAnimatorSet()V
    .locals 2

    iget-object v0, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimatorSet:Landroid/animation/AnimatorSet;

    if-nez v0, :cond_0

    new-instance v0, Landroid/animation/AnimatorSet;

    invoke-direct {v0}, Landroid/animation/AnimatorSet;-><init>()V

    iput-object v0, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimatorSet:Landroid/animation/AnimatorSet;

    :cond_0
    iget-object v0, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimatorSet:Landroid/animation/AnimatorSet;

    iget-object v1, p0, Landroid/support/graphics/drawable/AnimatedVectorDrawableCompat$AnimatedVectorDrawableCompatState;->mAnimators:Ljava/util/ArrayList;

    invoke-virtual {v0, v1}, Landroid/animation/AnimatorSet;->playTogether(Ljava/util/Collection;)V

    return-void
.end method


text:
class NodeChildrenMenuLayer : public PerformBasicLayer
{
public:
    NodeChildrenMenuLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0);
    virtual void showCurrentTest();
};

class NodeChildrenMainScene : public CCScene
{
public:
    virtual void initWithQuantityOfNodes(unsigned int nNodes);
    virtual std::string title();
    virtual std::string subtitle();
    virtual void updateQuantityOfNodes() = 0;

    void onDecrease(CCObject* pSender);
    void onIncrease(CCObject* pSender);
    void updateQuantityLabel();

    int getQuantityOfNodes() { return quantityOfNodes; }

protected:
    int    lastRenderedCount;
    int    quantityOfNodes;
    int    currentQuantityOfNodes;
};

class IterateSpriteSheet : public NodeChildrenMainScene
{
public:
    ~IterateSpriteSheet();
    virtual void updateQuantityOfNodes();
    virtual void initWithQuantityOfNodes(unsigned int nNodes);
    virtual void update(float dt) = 0;
    virtual std::string profilerName();

protected:
    CCSpriteBatchNode    *batchNode;

#if CC_ENABLE_PROFILERS
    CCProfilingTimer    *_profilingTimer;
#endif
};

class IterateSpriteSheetFastEnum : public IterateSpriteSheet
{
public:
    virtual void update(float dt);

    virtual std::string title();
    virtual std::string subtitle();
    virtual std::string profilerName();
};

class IterateSpriteSheetCArray : public IterateSpriteSheet
{
public:
    virtual void update(float dt);

    virtual std::string title();
    virtual std::string subtitle();
    virtual std::string profilerName();
};

class AddRemoveSpriteSheet : public NodeChildrenMainScene
{
public:
    ~AddRemoveSpriteSheet();
    virtual void updateQuantityOfNodes();
    virtual void initWithQuantityOfNodes(unsigned int nNodes);
    virtual void update(float dt) = 0;
    virtual std::string profilerName();

protected:
    CCSpriteBatchNode    *batchNode;

#if CC_ENABLE_PROFILERS
    CCProfilingTimer* _profilingTimer;
#endif
};

class AddSpriteSheet : public AddRemoveSpriteSheet
{
public:
    virtual void update(float dt);

    virtual std::string title();
    virtual std::string subtitle();
    virtual std::string profilerName();
};

class RemoveSpriteSheet : public AddRemoveSpriteSheet
{
public:
    virtual void update(float dt);

    virtual std::string title();
    virtual std::string subtitle();
    virtual std::string profilerName();
};

class ReorderSpriteSheet : public AddRemoveSpriteSheet
{
public:
    virtual void update(float dt);

    virtual std::string title();
    virtual std::string subtitle();
    virtual std::string profilerName();
};

void runNodeChildrenTest();

#endif // __PERFORMANCE_NODE_CHILDREN_TEST_H__


text:
import org.apache.spark.SparkContext._
import org.apache.spark.mllib.clustering.HierarchicalClustering
import org.apache.spark.mllib.linalg.{Vector, Vectors}
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
import org.uncommons.maths.random.XORShiftRNG

object AccuracyTestApp {

  def main(args: Array[String]) {
    val master = args(0)
    val maxCores = args(1)
    val numClusters = args(2).toInt
    val dimension = args(3).toInt
    val numPartitions = args(4).toInt

    val appName = s"${this.getClass().getSimpleName},maxCores,${maxCores},dim:${dimension},"
    val conf = new SparkConf()
        .setAppName(appName)
        .setMaster(master)
        .set("spark.cores.max", maxCores)
    val sc = new SparkContext(conf)

    val labeledData = generateData(sc, numPartitions, numClusters, dimension)
    labeledData.cache
    val model = HierarchicalClustering.train(labeledData.map(_._2), numClusters)
    val result = model.predict(labeledData.map(_._2)).map(_.swap)
    val joinedData = labeledData.zipWithIndex().map(_.swap).join(result.zipWithIndex().map(_.swap))

    val weightedTotalVariance = model.getClusters()
        .map(c => c.getDataSize().get * c.getVariance().get).sum
    val meanVariance = weightedTotalVariance / labeledData.count()

    val clusters = model.getClusters()
    sc.broadcast(clusters)
    val result1 = result.map { case (vector, closestIdx) => (closestIdx, 1)}.reduceByKey(_ + _)
        .map(_.swap).sortByKey().collect().map { case (count, closestIdx) =>
      val closestCluster = clusters(closestIdx)
      val vector = closestCluster.center
      s"  Count: ${count}, Depth: ${closestCluster.getDepth()}, Variance: ${closestCluster.getVariance().get}, Seed Vector: ${vector.toArray.take(3).mkString(",")}..."
    }

    //    val seedVectors = labeledData.map { case (seed, v, sv) => seed}.distinct().collect().sorted
    //    val result2 = seedVectors.map { seed =>
    //      val rdd = labeledData.filter { case (s, v, sv) => seed == s}.map { case (s, v, sv) => v}
    //      val cluster = ClusterTree.fromRDD(rdd)
    //      cluster.updateStats()
    //      s"  Count: ${cluster.getDataSize()}, Depth: ${cluster.depth()}, Variance: ${cluster.getVariance().get}, Seed Vector: ${cluster.center.toArray.take(3).mkString(",")}..."
    //    }

    val result3 = labeledData.map { case (seed, vector, seedVector) => (seedVector, 1)}.reduceByKey(_ + _)
        .map(_.swap).sortByKey().collect().map { case (count, vector) =>
      s"  Count: ${count}, Seed Vector: ${vector.toArray.take(3).mkString(",")}..."
    }

    // show the result
    println(s"==== Experiment Result ====")
    println(s"Total Rows: ${labeledData.count()}")
    println(s"Given # Clusters: ${numClusters}")
    println(s"Result Clusters: ${model.getClusters().size}")
    println(s"Dimension: ${dimension}")
    println(s"Train Time: ${model.trainTime} [msec]")
    println(s"Predict Time: ${model.predictTime} [msec]")

    println(s"Mean Standard Deviation: ${Math.sqrt(meanVariance)}")
    println(s"== Result Vectors and Their Rows: ")
    result1.foreach(println)
    //    println(s"== Original Vectors:")
    //    result2.foreach(println)
    println(s"== Seed Vectors and Their Rows: ")
    result3.foreach(println)

    val nodes = model.clusterTree.toSeq().sortWith { case (n1, n2) => n1.getDepth() < n2.getDepth()}
    nodes.foreach { node =>
      println(s"hashCode:${node.hashCode()}, " +
          s"Depth:${node.getDepth()}, " +
          s"Count:${node.getDataSize()}, " +
          s"Variance:${node.getVariance()}, " +
          s"Children:${node.getChildren().map(_.hashCode())}" +
          s"isVisited:${node.isVisited}" +
          s"Center:${node.center}"
      )
    }
  }

  def generateData(sc: SparkContext,
    numPartitions: Int,
    numClusters: Int,
    dim: Int): RDD[(Int, Vector, Vector)] = {

    val random = new XORShiftRNG()
    sc.broadcast(random)
    sc.parallelize(generateSeedSeq(numClusters), numPartitions).map { seed =>
      val seedArray = (1 to dim).map(j => seed.toDouble).toArray
      val seedVector = Vectors.dense(seedArray)
      val vector = Vectors.dense(seedArray.map(elm => elm + 0.01 * random.nextGaussian()))
      (seed, vector, seedVector)
    }
  }

  def generateSeedSeq(n: Int): Seq[Int] = {
    val seed = 10 * n
    val times = 1000
    n match {
      case 1 => (1 to n * times).map(i => seed).toSeq
      case _ => generateSeedSeq(n - 1) ++ (1 to n * times).map(i => seed).toSeq
    }
  }
}