text:
    Стабільнисть: 4 - API Зафіксовано

<!--type=module-->

Many objects in io.js emit events: a `net.Server` emits an event each time a peer connects to it, a `fs.readStream` emits an event when the file is opened. All objects which emit events are instances of `events.EventEmitter`. You can access this module by doing: `require("events");`

Typically, event names are represented by a camel-cased string, however, there aren't any strict restrictions on that, as any string will be accepted.

Functions can then be attached to objects, to be executed when an event is emitted. These functions are called *listeners*. Inside a listener function, `this` refers to the `EventEmitter` that the listener was attached to.

## Class: events.EventEmitter

To access the EventEmitter class, `require('events').EventEmitter`.

When an `EventEmitter` instance experiences an error, the typical action is to emit an `'error'` event. Error events are treated as a special case in io.js. If there is no listener for it, then the default action is to print a stack trace and exit the program.

All EventEmitters emit the event `'newListener'` when new listeners are added and `'removeListener'` when a listener is removed.

### emitter.addListener(event, listener)

### emitter.on(event, listener)

Adds a listener to the end of the listeners array for the specified `event`. No checks are made to see if the `listener` has already been added. Multiple calls passing the same combination of `event` and `listener` will result in the `listener` being added multiple times.

    server.on('connection', function (stream) {
      console.log('someone connected!');
    });

Returns emitter, so calls can be chained.

### emitter.once(event, listener)

Adds a **one time** listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.

    server.once('connection', function (stream) {
      console.log('Ah, we have our first user!');
    });

Returns emitter, so calls can be chained.

### emitter.removeListener(event, listener)

Remove a listener from the listener array for the specified event. **Caution**: changes array indices in the listener array behind the listener.

    var callback = function(stream) {
      console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);

`removeListener` will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified `event`, then `removeListener` must be called multiple times to remove each instance.

Returns emitter, so calls can be chained.

### emitter.removeAllListeners([event])

Removes all listeners, or those of the specified event. It's not a good idea to remove listeners that were added elsewhere in the code, especially when it's on an emitter that you didn't create (e.g. sockets or file streams).

Returns emitter, so calls can be chained.

### emitter.setMaxListeners(n)

By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited.

Returns emitter, so calls can be chained.

### emitter.getMaxListeners()

Returns the current max listener value for the emitter which is either set by `emitter.setMaxListeners(n)` or defaults to `EventEmitter.defaultMaxListeners`.

This can be useful to increment/decrement max listeners to avoid the warning while not being irresponsible and setting a too big number.

    emitter.setMaxListeners(emitter.getMaxListeners() + 1);
    emitter.once('event', function () {
      // do stuff
      emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
    });

### EventEmitter.defaultMaxListeners

`emitter.setMaxListeners(n)` sets the maximum on a per-instance basis. This class property lets you set it for *all* `EventEmitter` instances, current and future, effective immediately. Use with care.

Note that `emitter.setMaxListeners(n)` still has precedence over `EventEmitter.defaultMaxListeners`.

### emitter.listeners(event)

Returns an array of listeners for the specified event.

    server.on('connection', function (stream) {
      console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]

### emitter.emit(event\[, arg1\]\[, arg2\][, ...])

Execute each of the listeners in order with the supplied arguments.

Returns `true` if event had listeners, `false` otherwise.

### Class Method: EventEmitter.listenerCount(emitter, event)

Return the number of listeners for a given event.

### Event: 'newListener'

  * `event` {String} The event name
  * `listener` {Function} The event handler function

This event is emitted *before* a listener is added. When this event is triggered, the listener has not been added to the array of listeners for the `event`. Any listeners added to the event `name` in the newListener event callback will be added *before* the listener that is in the process of being added.

### Event: 'removeListener'

  * `event` {String} The event name
  * `listener` {Function} The event handler function

This event is emitted *after* a listener is removed. When this event is triggered, the listener has been removed from the array of listeners for the `event`.


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.
// Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland.

// This file was modified by Oracle on 2014.
// Modifications copyright (c) 2014, Oracle and/or its affiliates.

// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_GEOMETRIES_POINT_HPP
#define BOOST_GEOMETRY_GEOMETRIES_POINT_HPP

#include <cstddef>

#include <boost/mpl/int.hpp>
#include <boost/static_assert.hpp>

#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/coordinate_type.hpp>
#include <boost/geometry/core/coordinate_system.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>

namespace boost { namespace geometry
{

// Silence warning C4127: conditional expression is constant
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4127)
#endif

namespace model
{

namespace detail
{

template <std::size_t DimensionCount, std::size_t Index>
struct array_assign
{
    template <typename T>
    static inline void apply(T values[], T const& value)
    {
        values[Index] = value;
    }
};

// Specialization avoiding assigning element [2] for only 2 dimensions
template <> struct array_assign<2, 2>
{
    template <typename T> static inline void apply(T [], T const& ) {}
};

// Specialization avoiding assigning elements for (rarely used) points in 1 dim
template <> struct array_assign<1, 1>
{
    template <typename T> static inline void apply(T [], T const& ) {}
};

template <> struct array_assign<1, 2>
{
    template <typename T> static inline void apply(T [], T const& ) {}
};

}
/*!
\brief Basic point class, having coordinates defined in a neutral way
\details Defines a neutral point class, fulfilling the Point Concept.
    Library users can use this point class, or use their own point classes.
    This point class is used in most of the samples and tests of Boost.Geometry
    This point class is used occasionally within the library, where a temporary
    point class is necessary.
\ingroup geometries
\tparam CoordinateType \tparam_numeric
\tparam DimensionCount number of coordinates, usually 2 or 3
\tparam CoordinateSystem coordinate system, for example cs::cartesian

\qbk{[include reference/geometries/point.qbk]}
\qbk{before.synopsis, [heading Model of]}
\qbk{before.synopsis, [link geometry.reference.concepts.concept_point Point Concept]}

*/
template
<
    typename CoordinateType,
    std::size_t DimensionCount,
    typename CoordinateSystem
>
class point
{
private:
    // The following enum is used to fully instantiate the
    // CoordinateSystem class and check the correctness of the units
    // passed for non-Cartesian coordinate systems.
    enum { cs_check = sizeof(CoordinateSystem) };

public:

    /// @brief Default constructor, no initialization
    inline point()
    {
        BOOST_STATIC_ASSERT(DimensionCount >= 1);
    }

    /// @brief Constructor to set one value
    explicit inline point(CoordinateType const& v0)
    {
        detail::array_assign<DimensionCount, 0>::apply(m_values, v0);
        detail::array_assign<DimensionCount, 1>::apply(m_values, CoordinateType());
        detail::array_assign<DimensionCount, 2>::apply(m_values, CoordinateType());
    }

    /// @brief Constructor to set two values
    inline point(CoordinateType const& v0, CoordinateType const& v1)
    {
        detail::array_assign<DimensionCount, 0>::apply(m_values, v0);
        detail::array_assign<DimensionCount, 1>::apply(m_values, v1);
        detail::array_assign<DimensionCount, 2>::apply(m_values, CoordinateType());
    }

    /// @brief Constructor to set three values
    inline point(CoordinateType const& v0, CoordinateType const& v1,
            CoordinateType const& v2)
    {
        detail::array_assign<DimensionCount, 0>::apply(m_values, v0);
        detail::array_assign<DimensionCount, 1>::apply(m_values, v1);
        detail::array_assign<DimensionCount, 2>::apply(m_values, v2);
    }

    /// @brief Get a coordinate
    /// @tparam K coordinate to get
    /// @return the coordinate
    template <std::size_t K>
    inline CoordinateType const& get() const
    {
        BOOST_STATIC_ASSERT(K < DimensionCount);
        return m_values[K];
    }

    /// @brief Set a coordinate
    /// @tparam K coordinate to set
    /// @param value value to set
    template <std::size_t K>
    inline void set(CoordinateType const& value)
    {
        BOOST_STATIC_ASSERT(K < DimensionCount);
        m_values[K] = value;
    }

private:

    CoordinateType m_values[DimensionCount];
};

} // namespace model

// Adapt the point to the concept
#ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS
namespace traits
{
template
<
    typename CoordinateType,
    std::size_t DimensionCount,
    typename CoordinateSystem
>
struct tag<model::point<CoordinateType, DimensionCount, CoordinateSystem> >
{
    typedef point_tag type;
};

template
<
    typename CoordinateType,
    std::size_t DimensionCount,
    typename CoordinateSystem
>
struct coordinate_type<model::point<CoordinateType, DimensionCount, CoordinateSystem> >
{
    typedef CoordinateType type;
};

template
<
    typename CoordinateType,
    std::size_t DimensionCount,
    typename CoordinateSystem
>
struct coordinate_system<model::point<CoordinateType, DimensionCount, CoordinateSystem> >
{
    typedef CoordinateSystem type;
};

template
<
    typename CoordinateType,
    std::size_t DimensionCount,
    typename CoordinateSystem
>
struct dimension<model::point<CoordinateType, DimensionCount, CoordinateSystem> >
    : boost::mpl::int_<DimensionCount>
{};

template
<
    typename CoordinateType,
    std::size_t DimensionCount,
    typename CoordinateSystem,
    std::size_t Dimension
>
struct access<model::point<CoordinateType, DimensionCount, CoordinateSystem>, Dimension>
{
    static inline CoordinateType get(
        model::point<CoordinateType, DimensionCount, CoordinateSystem> const& p)
    {
        return p.template get<Dimension>();
    }

    static inline void set(
        model::point<CoordinateType, DimensionCount, CoordinateSystem>& p,
        CoordinateType const& value)
    {
        p.template set<Dimension>(value);
    }
};

} // namespace traits
#endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS

#if defined(_MSC_VER)
#pragma warning(pop)
#endif

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_GEOMETRIES_POINT_HPP

redpajama_set_name: RedPajamaGithub


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

namespace B2API
{
    /// <summary>
    /// Default values for parameters
    /// </summary>
    internal static class Defaults
    {
        #region Public Fields

        public const string APIVersionPath = @"b2api/v1";
        public const string AuthorizeAccountURLPrefix = @"https://api.backblaze.com";
        public const int MaxFileCount = 1000;
        public const int MaxRequestRetries = 5;
        public const int RequestTimeoutMillis = 10 * 1000;
        public const int TransferTimeoutMillis = 10 * 60 * 60 * 1000;

        #endregion Public Fields
    }
}


text:
void led_init(void);
void led_set(void);
void led_clear(void);
void led_toggle(void);

#endif


text:
package api

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"

	"github.com/tsuru/config"
	_ "github.com/tsuru/tsuru/router/routertest"
	"gopkg.in/check.v1"
)

func (s *S) TestInfo(c *check.C) {
	config.Set("autoscale", true)
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("GET", "/info", nil)
	c.Assert(err, check.IsNil)
	m := RunServer(true)
	m.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	c.Assert(recorder.Header().Get("Content-Type"), check.Equals, "application/json")
	expected := map[string]interface{}{
		"autoscale": true,
		"version":   Version,
	}
	var info map[string]interface{}
	err = json.Unmarshal(recorder.Body.Bytes(), &info)
	c.Assert(err, check.IsNil)
	c.Assert(info, check.DeepEquals, expected)
}


text:
package pet.hp;

public abstract class Gametype {
	public abstract String[] getStreetNames(Game.Type gametype);
}


text:
using System.Collections.Generic;
using System.IO;
using Usbacc.Core.Converter;
using Usbacc.Core.Domain;
using Usbacc.Core.Repository;

namespace Usbacc.Core.Import
{
    public class UsbRecordImport
    {
        public void Import(string filePath)
        {
            var reportConverter = new UsbDeviewConverter();
            var report = new Report
            {
                ReportName = Path.GetFileNameWithoutExtension(filePath),
                CreationDateTime = File.GetLastWriteTime(filePath)
            };

            var usbDevices = reportConverter.Convert(filePath);
            foreach (var usbDevice in usbDevices)
                usbDevice.Report = report;

            report.UsbRecords = usbDevices;

            var reportRepository = new Repository<Report>();
            reportRepository.Save(report);

            var usbDeviceRepository = new Repository<UsbRecord>();
            usbDeviceRepository.Save(usbDevices);
        }

        public void Import(IList<string> filesPath)
        {
            foreach (var filePath in filesPath)
                Import(filePath);
        }
    }
}


text:
// Strong Hold BOB 2016 Commands (Arm Stop)

package org.usfirst.frc319.commands.arm;

import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc319.Robot;

/**
 *
 */
public class ArmStop extends Command {

    public ArmStop() {

        requires(Robot.arm);

    }

    protected void initialize() {
    }

    protected void execute() {

    	Robot.arm.armStop();
    }

    protected boolean isFinished() {
        return true;
    }

    protected void end() {
    }

    protected void interrupted() {
    }

}


text:
CXXFLAGS = -O2 $(DEBUGFLAGS) -fmessage-length=0 -std=c++0x
LDFLAGS = -L../../lib/ -lboost_iostreams

# KMajority
CXXFLAGS += -I../../KMajorityLib/include
LDFLAGS += -lkmajority

# HCTreeLib
CXXFLAGS += -I../include
LDFLAGS += -lhctree

# Common
CXXFLAGS += -I../../Common/include/
LDFLAGS += -lcommon

# OpenCV
CXXFLAGS += `pkg-config opencv --cflags`
LDFLAGS += `pkg-config opencv --libs`

# GoogleTest
CXXFLAGS += -Wextra -pthread
LDFLAGS += -L/home/andresf/workspace-cpp/gtest-1.7.0/make
LDFLAGS += -lgtest_main -lpthread

SOURCES = $(wildcard *.cpp)
OBJECTS = $(SOURCES:.cpp=.o)
EXECUTABLES = $(OBJECTS:.o=)

all: $(EXECUTABLES)

$(EXECUTABLES): $(OBJECTS)
	$(CXX) $(CXXFLAGS) $@.o $(LDFLAGS) -o $@

.cpp.o:
	$(CXX) $(CXXFLAGS) -c $< -o $@

clean:
	rm -rf $(OBJECTS) $(EXECUTABLES) test_tree.yaml.gz *~


text:
package eu.amidst.core.exponentialfamily;

import eu.amidst.core.distribution.UnivariateDistribution;
import eu.amidst.core.utils.ArrayVector;
import eu.amidst.core.utils.Utils;
import eu.amidst.core.utils.Vector;
import eu.amidst.core.variables.Variable;
import org.apache.commons.math3.special.Gamma;

import java.util.ArrayList;
import java.util.Random;

/**
 *
 * This class extends the abstract class {@link EF_UnivariateDistribution} and defines an inverse Gamma distribution in exponential family canonical form.
 *
 *
 For further details about how exponential family models are considered in this toolbox take a look at the following paper:
 *  Representation, Inference and Learning of Bayesian Networks as Conjugate Exponential Family Models. Technical Report.
 * (pdf)

 */
public class EF_InverseGamma extends EF_UnivariateDistribution {

    public static final int LOGX = 0;
    public static final int INVX = 1;
    public static final double DELTA = 0.0001;

    /**
     * Creates a new EF_InverseGamma distribution for a given {@link Variable} object.
     * @param var1 a {@link Variable} object.
     */
    public EF_InverseGamma(Variable var1) {

        if (!var1.isInverseGammaParameter())
            throw new IllegalArgumentException("The variable is not Inverse Gamma parameter");

        this.parents = new ArrayList();

        this.var = var1;
        this.naturalParameters = this.createZeroNaturalParameters();
        this.momentParameters = this.createZeroMomentParameters();

        this.naturalParameters.set(0, -2.1); //alpha = 1.1
        this.naturalParameters.set(1, -1);   //beta = 1
        this.setNaturalParameters(naturalParameters);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double computeLogBaseMeasure(double val) {
        return 0;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SufficientStatistics getSufficientStatistics(double val) {
        SufficientStatistics vec = this.createZeroSufficientStatistics();
        vec.set(LOGX, Math.log(val));
        vec.set(INVX, 1.0 / val);
        return vec;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public EF_UnivariateDistribution deepCopy(Variable var) {
        EF_InverseGamma copy = new EF_InverseGamma(var);
        copy.getNaturalParameters().copy(this.getNaturalParameters());
        copy.getMomentParameters().copy(this.getMomentParameters());

        return copy;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public EF_UnivariateDistribution randomInitialization(Random random) {
        double alpha = random.nextGaussian() * 2 + 1;
        double beta = random.nextDouble() * 1 + 0.1;

        this.getNaturalParameters().set(0, -alpha - 1);
        this.getNaturalParameters().set(1, -beta);
        this.fixNumericalInstability();
        this.updateMomentFromNaturalParameters();

        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <E extends UnivariateDistribution> E toUnivariateDistribution() {
        throw new UnsupportedOperationException("Inverse Gamma is not included yet in the Distributions package.");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void updateNaturalFromMomentParameters() {
        double m0 = this.getMomentParameters().get(0);
        double m1 = this.getMomentParameters().get(1);
        // Coordinate ascent until convergence
        double newalpha = 2.0, alpha = 0.0;
        double newbeta = 2.0, beta = 0.0;
        while (Math.abs(newalpha - alpha) > DELTA || Math.abs(newbeta - beta) > DELTA) {
            alpha = newalpha; beta = newbeta;
            newalpha = Utils.invDigamma(Math.log(beta) - m0);
            newbeta = newalpha / m1;
        }
        this.naturalParameters.set(0, newalpha);
        this.naturalParameters.set(1, newbeta);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void updateMomentFromNaturalParameters() {
        double alpha = -this.naturalParameters.get(0) - 1;
        double beta = -this.naturalParameters.get(1);
        this.momentParameters.set(0, Math.log(beta) - Gamma.digamma(alpha));
        this.momentParameters.set(1, alpha / beta);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int sizeOfSufficientStatistics() {
        return 2;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double computeLogNormalizer() {
        double alpha = -this.naturalParameters.get(0) - 1;
        double beta = -this.naturalParameters.get(1);
        return Gamma.logGamma(alpha) - alpha * Math.log(beta);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Vector createZeroVector() {
        return new ArrayVector(2);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Vector getExpectedParameters() {
        //if ((-this.naturalParameters.get(0)-2)<=0){
        //    throw new UnsupportedOperationException("The expected value is negative, so we do not have a valid inverse gamma distributions ");
        //}
        Vector vec = new ArrayVector(1);
        vec.set(0, -this.naturalParameters.get(1)/(-this.naturalParameters.get(0)-1));
        return vec;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void fixNumericalInstability() {

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SufficientStatistics createInitSufficientStatistics() {

        ArrayVector vector = new ArrayVector(this.sizeOfSufficientStatistics());

        double alpha = 1.0;
        double beta = 1.0;
        vector.set(0, Math.log(beta) - Gamma.digamma(alpha));
        vector.set(1, alpha / beta);

        return vector;
    }

}


text:
<?php

namespace Assely\Posttype;

use Exception;

class PosttypeException extends Exception
{
    //
}


text:
namespace llvm {
#include "AMDGPUPTNote.h"

class DataLayout;
class Function;
class MCELFStreamer;
class MCSymbol;
class MDNode;
class Module;
class Type;

class AMDGPUTargetStreamer : public MCTargetStreamer {
  AMDGPUPALMetadata PALMetadata;

protected:
  MCContext &getContext() const { return Streamer.getContext(); }

public:
  AMDGPUTargetStreamer(MCStreamer &S) : MCTargetStreamer(S) {}

  AMDGPUPALMetadata *getPALMetadata() { return &PALMetadata; }

  virtual void EmitDirectiveAMDGCNTarget(StringRef Target) = 0;

  virtual void EmitDirectiveHSACodeObjectVersion(uint32_t Major,
                                                 uint32_t Minor) = 0;

  virtual void EmitDirectiveHSACodeObjectISA(uint32_t Major, uint32_t Minor,
                                             uint32_t Stepping,
                                             StringRef VendorName,
                                             StringRef ArchName) = 0;

  virtual void EmitAMDKernelCodeT(const amd_kernel_code_t &Header) = 0;

  virtual void EmitAMDGPUSymbolType(StringRef SymbolName, unsigned Type) = 0;

  /// \returns True on success, false on failure.
  virtual bool EmitISAVersion(StringRef IsaVersionString) = 0;

  /// \returns True on success, false on failure.
  virtual bool EmitHSAMetadataV2(StringRef HSAMetadataString);

  /// \returns True on success, false on failure.
  virtual bool EmitHSAMetadataV3(StringRef HSAMetadataString);

  /// Emit HSA Metadata
  ///
  /// When \p Strict is true, known metadata elements must already be
  /// well-typed. When \p Strict is false, known types are inferred and
  /// the \p HSAMetadata structure is updated with the correct types.
  ///
  /// \returns True on success, false on failure.
  virtual bool EmitHSAMetadata(msgpack::Document &HSAMetadata, bool Strict) = 0;

  /// \returns True on success, false on failure.
  virtual bool EmitHSAMetadata(const AMDGPU::HSAMD::Metadata &HSAMetadata) = 0;

  /// \returns True on success, false on failure.
  virtual bool EmitCodeEnd() = 0;

  virtual void EmitAmdhsaKernelDescriptor(
      const MCSubtargetInfo &STI, StringRef KernelName,
      const amdhsa::kernel_descriptor_t &KernelDescriptor, uint64_t NextVGPR,
      uint64_t NextSGPR, bool ReserveVCC, bool ReserveFlatScr,
      bool ReserveXNACK) = 0;

  static StringRef getArchNameFromElfMach(unsigned ElfMach);
  static unsigned getElfMach(StringRef GPU);
};

class AMDGPUTargetAsmStreamer final : public AMDGPUTargetStreamer {
  formatted_raw_ostream &OS;
public:
  AMDGPUTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS);

  void finish() override;

  void EmitDirectiveAMDGCNTarget(StringRef Target) override;

  void EmitDirectiveHSACodeObjectVersion(uint32_t Major,
                                         uint32_t Minor) override;

  void EmitDirectiveHSACodeObjectISA(uint32_t Major, uint32_t Minor,
                                     uint32_t Stepping, StringRef VendorName,
                                     StringRef ArchName) override;

  void EmitAMDKernelCodeT(const amd_kernel_code_t &Header) override;

  void EmitAMDGPUSymbolType(StringRef SymbolName, unsigned Type) override;

  /// \returns True on success, false on failure.
  bool EmitISAVersion(StringRef IsaVersionString) override;

  /// \returns True on success, false on failure.
  bool EmitHSAMetadata(msgpack::Document &HSAMetadata, bool Strict) override;

  /// \returns True on success, false on failure.
  bool EmitHSAMetadata(const AMDGPU::HSAMD::Metadata &HSAMetadata) override;

  /// \returns True on success, false on failure.
  bool EmitCodeEnd() override;

  void EmitAmdhsaKernelDescriptor(
      const MCSubtargetInfo &STI, StringRef KernelName,
      const amdhsa::kernel_descriptor_t &KernelDescriptor, uint64_t NextVGPR,
      uint64_t NextSGPR, bool ReserveVCC, bool ReserveFlatScr,
      bool ReserveXNACK) override;
};

class AMDGPUTargetELFStreamer final : public AMDGPUTargetStreamer {
  MCStreamer &Streamer;

  void EmitNote(StringRef Name, const MCExpr *DescSize, unsigned NoteType,
                function_ref<void(MCELFStreamer &)> EmitDesc);

public:
  AMDGPUTargetELFStreamer(MCStreamer &S, const MCSubtargetInfo &STI);

  MCELFStreamer &getStreamer();

  void finish() override;

  void EmitDirectiveAMDGCNTarget(StringRef Target) override;

  void EmitDirectiveHSACodeObjectVersion(uint32_t Major,
                                         uint32_t Minor) override;

  void EmitDirectiveHSACodeObjectISA(uint32_t Major, uint32_t Minor,
                                     uint32_t Stepping, StringRef VendorName,
                                     StringRef ArchName) override;

  void EmitAMDKernelCodeT(const amd_kernel_code_t &Header) override;

  void EmitAMDGPUSymbolType(StringRef SymbolName, unsigned Type) override;

  /// \returns True on success, false on failure.
  bool EmitISAVersion(StringRef IsaVersionString) override;

  /// \returns True on success, false on failure.
  bool EmitHSAMetadata(msgpack::Document &HSAMetadata, bool Strict) override;

  /// \returns True on success, false on failure.
  bool EmitHSAMetadata(const AMDGPU::HSAMD::Metadata &HSAMetadata) override;

  /// \returns True on success, false on failure.
  bool EmitCodeEnd() override;

  void EmitAmdhsaKernelDescriptor(
      const MCSubtargetInfo &STI, StringRef KernelName,
      const amdhsa::kernel_descriptor_t &KernelDescriptor, uint64_t NextVGPR,
      uint64_t NextSGPR, bool ReserveVCC, bool ReserveFlatScr,
      bool ReserveXNACK) override;
};

}
#endif


text:
package com.Wsdl2Code.WebServices.PredictionsService;

//------------------------------------------------------------------------------
// <wsdl2code-generated>
//    This code was generated by http://www.wsdl2code.com version  2.6
//
// Date Of Creation: 10/19/2017 10:20:46 PM
//    Please dont change this code, regeneration will override your changes
//</wsdl2code-generated>
//
//------------------------------------------------------------------------------
//
//This source code was auto-generated by Wsdl2Code  Version
//

import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;

import java.util.Hashtable;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;

public class StringBoundary implements KvmSerializable {

    public String max;
    public String min;

    public StringBoundary() {
    }

    public StringBoundary(SoapObject soapObject) {
        if (soapObject == null)
            return;
        if (soapObject.hasProperty("max")) {
            Object obj = soapObject.getProperty("max");
            if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
                SoapPrimitive j = (SoapPrimitive) obj;
                max = j.toString();
            } else if (obj != null && obj instanceof String) {
                max = (String) obj;
            }
        }
        if (soapObject.hasProperty("min")) {
            Object obj = soapObject.getProperty("min");
            if (obj != null && obj.getClass().equals(SoapPrimitive.class)) {
                SoapPrimitive j = (SoapPrimitive) obj;
                min = j.toString();
            } else if (obj != null && obj instanceof String) {
                min = (String) obj;
            }
        }
    }

    @Override
    public Object getProperty(int arg0) {
        switch (arg0) {
            case 0:
                return max;
            case 1:
                return min;
        }
        return null;
    }

    @Override
    public int getPropertyCount() {
        return 2;
    }

    @Override
    public void getPropertyInfo(int index, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info) {
        switch (index) {
            case 0:
                info.type = PropertyInfo.STRING_CLASS;
                info.name = "max";
                break;
            case 1:
                info.type = PropertyInfo.STRING_CLASS;
                info.name = "min";
                break;
        }
    }

    //    @Override
    public String getInnerText() {
        return null;
    }

    //    @Override
    public void setInnerText(String s) {
    }

    @Override
    public void setProperty(int arg0, Object arg1) {
    }

}


text:
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace Microsoft.Msagl.DebugHelpers {
#if REPORTING
    /// <summary>
    /// support for native method calls
    /// </summary>
    public class Timer {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass"), DllImport("Kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool QueryPerformanceFrequency(out long lpFrequency);
        private long startTime;
        private long stopTime;
        private long freq;
        /// <summary>
        /// ctor
        /// </summary>
        public Timer() {
            if (QueryPerformanceFrequency(out freq) == false) {
                throw new Win32Exception(); // timer not supanchored
            }
        }
        /// <summary>
        /// Start the timer
        /// </summary>
        /// <returns>long - tick count</returns>
        public long Start() {
            QueryPerformanceCounter(out startTime);
            return startTime;
        }
        /// <summary>
        /// Stop timer
        /// </summary>
        /// <returns>long - tick count</returns>
        public long Stop() {
            QueryPerformanceCounter(out stopTime);
            return stopTime;
        }
        /// <summary>
        /// Return the duration of the timer in seconds.
        /// </summary>
        /// <returns>double - duration</returns>
        public double Duration {
            get {
                return (double)(stopTime - startTime) / (double)freq;
            }
        }
        /// <summary>
        /// Frequency of timer (no counts in one second on this machine)
        /// </summary>
        ///<returns>long - Frequency</returns>
        public long Frequency {
            get {
                QueryPerformanceFrequency(out freq);
                return freq;
            }
        }
    }
#endif
}


text:
namespace Patchwork.Engine.Utility {
	/// <summary>
	///     A member's accessibility level, such as public, private, etc.
	/// </summary>
	public enum Accessibility {
		Private,
		Protected,
		Internal,
		ProtectedInternal,
		Public,
		Other
	}
}


text:
namespace ppapi {

class TrackedCallback;

namespace proxy {

class ResourceMessageReplyParams;

class PPAPI_PROXY_EXPORT ExtCrxFileSystemPrivateResource
    : public PluginResource,
      public thunk::PPB_Ext_CrxFileSystem_Private_API {
 public:
  ExtCrxFileSystemPrivateResource(Connection connection, PP_Instance instance);
  virtual ~ExtCrxFileSystemPrivateResource();

  // Resource overrides.
  virtual thunk::PPB_Ext_CrxFileSystem_Private_API*
      AsPPB_Ext_CrxFileSystem_Private_API() OVERRIDE;

  // PPB_Ext_CrxFileSystem_Private_API implementation.
  virtual int32_t Open(PP_Instance instance,
                       PP_Resource* file_system_resource,
                       scoped_refptr<TrackedCallback> callback) OVERRIDE;

 private:
  void OnBrowserOpenComplete(PP_Resource* file_system_resource,
                             scoped_refptr<TrackedCallback> callback,
                             const ResourceMessageReplyParams& params,
                             const std::string& fsid);

  bool called_open_;

  DISALLOW_COPY_AND_ASSIGN(ExtCrxFileSystemPrivateResource);
};

}  // namespace proxy
}  // namespace ppapi

#endif  // PPAPI_PROXY_EXT_CRX_FILE_SYSTEM_PRIVATE_RESOURCE_H_


text:
package com.netflix.spinnaker.orca.clouddriver.pipeline.launchconfigurations;

import com.netflix.spinnaker.orca.api.pipeline.graph.StageDefinitionBuilder;
import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode;
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution;
import com.netflix.spinnaker.orca.clouddriver.tasks.MonitorKatoTask;
import com.netflix.spinnaker.orca.clouddriver.tasks.launchconfigurations.DeleteLaunchConfigurationTask;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.validation.constraints.NotNull;
import lombok.Data;
import org.springframework.stereotype.Component;

@Component
public class DeleteLaunchConfigurationStage implements StageDefinitionBuilder {
  @Override
  public void taskGraph(@Nonnull StageExecution stage, @Nonnull @NotNull TaskNode.Builder builder) {
    builder
        .withTask("deleteLaunchConfiguration", DeleteLaunchConfigurationTask.class)
        .withTask("monitorDeleteSnapshot", MonitorKatoTask.class);
  }

  @Data
  public static class DeleteLaunchConfigurationRequest {
    private String credentials;
    private String cloudProvider;
    private String region;
    private Set<String> launchConfigurationNames;
  }
}


text:
package com.savoirtech.hecate.migrator;

import com.datastax.driver.core.Session;

public interface SchemaMigrationMetadataRepository {
//----------------------------------------------------------------------------------------------------------------------
// Other Methods
//----------------------------------------------------------------------------------------------------------------------

    void create(SchemaMigrationMetadata metadata);
    SchemaMigrationMetadata retrieve(String id);
    void update(SchemaMigrationMetadata metadata);
    Session getSession();
}


text:
package com.nortal.petit.converter.util;

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.jdbc.core.RowMapper;

import com.nortal.petit.converter.columnreader.ColumnReader;
import com.nortal.petit.converter.columnreader.StandardStrategies;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * RowMapper for generic Pair. Note that we need to provide Class arguments
 * since generic type information is nowhere to be found at runtime and we
 * cannot decide which method to invoke. Wait for runtime generics in Java! %)
 * Watch for default values ('key', 'value') for field names and (String,
 * String) for field classes.
 *
 * @author Aleksei Lissitsin <aleksei.lissitsin@webmedia.ee>
 */
public class PairRowMapper<T, K> implements RowMapper<Pair<T, K>> {
    private final ColumnPosition keyField;
    private final ColumnPosition valueField;
    private final ColumnReader<T> keyType;
    private final ColumnReader<K> valueType;

    public PairRowMapper() {
        this("key", "value");
    }

    @SuppressWarnings("unchecked")
    public PairRowMapper(String keyField, String valueField) {
        this(keyField, valueField, (Class<T>)String.class, (Class<K>)String.class);
    }

    public PairRowMapper(Class<T> keyClass, Class<K> valueClass) {
        this("key", "value", keyClass, valueClass);
    }

    @SuppressWarnings("unchecked")
    public PairRowMapper(String keyField, String valueField, Class<T> keyClass, Class<K> valueClass) {
        this.keyField = new ColumnPosition(keyField);
        this.valueField = new ColumnPosition(valueField);
        this.keyType = (ColumnReader<T>) StandardStrategies.instance.get(keyClass);
        this.valueType = (ColumnReader<K>) StandardStrategies.instance.get(valueClass);
    }

    public Pair<T, K> mapRow(ResultSet rs, int arg1) throws SQLException {
        T key = keyType.getColumnValue(rs, keyField.getIndex(rs));
        K value = valueType.getColumnValue(rs, valueField.getIndex(rs));
        return Pair.of(key, value);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>TreeExpansionEvent (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="javax.swing.event.TreeExpansionEvent class">
<meta name="keywords" content="path">
<meta name="keywords" content="getPath()">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.swing.event

Class TreeExpansionEvent

java.lang.Object

java.util.EventObject

javax.swing.event.TreeExpansionEvent

All Implemented Interfaces:

Serializable

public class TreeExpansionEvent
extends EventObject

An event used to identify a single path in a tree.  The source
 returned by getSource will be an instance of JTree.

 For further documentation and examples see
 the following sections in The Java Tutorial:
 How to Write a Tree Expansion Listener and
 How to Write a Tree-Will-Expand Listener.

 Warning:
 Serialized objects of this class will not be compatible with
 future Swing releases. The current serialization support is
 appropriate for short term storage or RMI between applications running
 the same version of Swing.  As of 1.4, support for long term storage
 of all JavaBeans™
 has been added to the java.beans package.
 Please see XMLEncoder.

Field Summary

Fields

Modifier and Type
Field and Description

protected TreePath
path

Path to the value this event represents.

Fields inherited from class java.util.EventObject

source

Constructor Summary

Constructors

Constructor and Description

TreeExpansionEvent(Object source,
                  TreePath path)

Constructs a TreeExpansionEvent object.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

TreePath
getPath()

Returns the path to the value that has been expanded/collapsed.

Methods inherited from class java.util.EventObject

getSource, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

path

protected TreePath path

Path to the value this event represents.

Constructor Detail

TreeExpansionEvent

public TreeExpansionEvent(Object source,
                          TreePath path)

Constructs a TreeExpansionEvent object.

Parameters:

source - the Object that originated the event
                (typically this)

path - a TreePath object identifying the newly expanded
                node

Method Detail

getPath

public TreePath getPath()

Returns the path to the value that has been expanded/collapsed.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
import chai from 'chai'
import sinon from 'sinon'
import sinonChai from 'sinon-chai'
const {
  expect
} = chai
chai.use(sinonChai)

import runtime from '../../../runtime'
import frameworks from '../../../frameworks'
import defaultConfig from '../../../frameworks/legacy/config'

const { init, config } = runtime
config.frameworks = frameworks
runtime.setNativeConsole()

import Vm from '../../../frameworks/legacy/vm'
import { clearModules, getModule } from '../../../frameworks/legacy/app/register'

const framework = init(config)

function clearRefs (json) {
  delete json.ref
  if (json.children) {
    json.children.forEach(clearRefs)
  }
}

describe('framework entry', () => {
  const oriCallNative = global.callNative
  const oriCallAddElement = global.callAddElement
  const callNativeSpy = sinon.spy()
  const callAddElementSpy = sinon.spy()
  const instanceId = Date.now() + ''

  before(() => {
    global.callNative = (id, tasks, callbackId) => {
      callNativeSpy(id, tasks, callbackId)
      /* istanbul ignore if */
      if (callbackId !== '-1') {
        framework.callJS(id, [{
          method: 'callback',
          args: [callbackId, null, true]
        }])
      }
    }
    config.Document.handler = global.callNative
    global.callAddElement = (name, id, ref, json, index, callbackId) => {
      callAddElementSpy(name, ref, json, index, callbackId)
      /* istanbul ignore if */
      if (callbackId !== '-1') {
        framework.callJS(id, [{
          method: 'callback',
          args: [callbackId, null, true]
        }])
      }
    }
  })

  afterEach(() => {
    callNativeSpy.reset()
    callAddElementSpy.reset()
  })

  after(() => {
    config.Document.handler = function () {}
    global.callNative = oriCallNative
    global.callAddElement = oriCallAddElement
  })

  describe('createInstance', () => {
    it('a simple bundle', () => {
      const code = `
        define('@weex-component/main',
          function(require, exports, module) {
            module.exports = {
              data: function() {
                return {
                  text: 'Hello World',
                  showText: true
                };
              }
            }

            ;module.exports.style = {}

            ;module.exports.template = {
              'type': 'container',
              'children': [{
                'type': 'text',
                'shown': function() {
                  return this.showText
                },
                'attr': {
                  'value': function() {
                    return this.text
                  }
                }
              }]
            }
          }
        )

        bootstrap('@weex-component/main')
      `
      framework.createInstance(instanceId, code)

      expect(callNativeSpy.callCount).to.be.equal(2)
      expect(callAddElementSpy.callCount).to.be.equal(1)

      expect(callNativeSpy.firstCall.args[0]).to.be.equal(instanceId)
      expect(callNativeSpy.firstCall.args[1]).to.deep.equal([{
        module: 'dom',
        method: 'createBody',
        args: [{
          ref: '_root',
          type: 'container',
          attr: {},
          style: {}
        }]
      }])
      // expect(callNativeSpy.firstCall.args[2]).to.not.equal('-1')

      expect(callAddElementSpy.firstCall.args[0]).to.be.equal(instanceId)
      delete callAddElementSpy.firstCall.args[1].ref
      expect(callAddElementSpy.firstCall.args[1]).to.deep.equal({
        type: 'text',
        attr: { value: 'Hello World' },
        style: {}
      })

      // expect(callNativeSpy.secondCall.args[2]).to.not.equal('-1')

      expect(callNativeSpy.secondCall.args[0]).to.be.equal(instanceId)
      expect(callNativeSpy.secondCall.args[1]).to.deep.equal([{
        module: 'dom',
        method: 'createFinish',
        args: []
      }])
      // expect(callNativeSpy.thirdCall.args[2]).to.not.equal('-1')
    })

    it('with a exist instanceId', () => {
      const code = ''
      const result = framework.createInstance(instanceId, code)
      expect(result).to.be.an.instanceof(Error)
    })

    it('js bundle format version checker', function () {
      const weexFramework = frameworks.Weex
      frameworks.Weex = {
        init: function () {},
        createInstance: sinon.spy()
      }
      frameworks.xxx = {
        init: function () {},
        createInstance: sinon.spy()
      }
      frameworks.yyy = {
        init: function () {},
        createInstance: sinon.spy()
      }

      // test framework xxx
      let code = `// {"framework":"xxx","version":"0.3.1"}
      'This is a piece of JavaScript from a third-party Framework...'`
      framework.createInstance(instanceId + '~', code)
      expect(frameworks.xxx.createInstance.callCount).equal(1)
      expect(frameworks.yyy.createInstance.callCount).equal(0)
      expect(frameworks.Weex.createInstance.callCount).equal(0)
      expect(frameworks.xxx.createInstance.firstCall.args).eql([
        instanceId + '~',
        code,
        { bundleVersion: '0.3.1', env: {}},
        undefined
      ])

      // also support spaces in JSON string
      // also ignore spaces between double-slash and JSON string
      code = `//{ "framework":"xxx" }
      'This is a piece of JavaScript from a third-party Framework...'`
      framework.createInstance(instanceId + '~~', code)
      expect(frameworks.xxx.createInstance.callCount).equal(2)
      expect(frameworks.yyy.createInstance.callCount).equal(0)
      expect(frameworks.Weex.createInstance.callCount).equal(0)

      // also support non-strict JSON format
      code = `// {framework:"xxx",'version':"0.3.1"}
      'This is a piece of JavaScript from a third-party Framework...'`
      framework.createInstance(instanceId + '~~~', code)
      expect(frameworks.xxx.createInstance.callCount).equal(2)
      expect(frameworks.yyy.createInstance.callCount).equal(0)
      expect(frameworks.Weex.createInstance.callCount).equal(1)
      expect(frameworks.Weex.createInstance.firstCall.args).eql([
        instanceId + '~~~',
        code,
        { bundleVersion: undefined, env: {}},
        undefined
      ])

      // test framework yyy
      /* eslint-disable */
      code = `

        // {"framework":"yyy"}

'JS Bundle with space and empty lines behind'` // modified from real generated code from tb
      /* eslint-enable */
      framework.createInstance(instanceId + '~~~~', code)
      expect(frameworks.xxx.createInstance.callCount).equal(2)
      expect(frameworks.yyy.createInstance.callCount).equal(1)
      expect(frameworks.Weex.createInstance.callCount).equal(1)
      expect(frameworks.yyy.createInstance.firstCall.args).eql([
        instanceId + '~~~~',
        code,
        { bundleVersion: undefined, env: {}},
        undefined
      ])

      // test framework Weex (wrong format at the middle)
      code = `'Some JS bundle code here ... // {"framework":"xxx"}\n ... end.'`
      framework.createInstance(instanceId + '~~~~~', code)
      expect(frameworks.xxx.createInstance.callCount).equal(2)
      expect(frameworks.yyy.createInstance.callCount).equal(1)
      expect(frameworks.Weex.createInstance.callCount).equal(2)
      expect(frameworks.Weex.createInstance.secondCall.args).eql([
        instanceId + '~~~~~',
        code,
        { bundleVersion: undefined, env: {}},
        undefined
      ])

      // test framework Weex (without any JSON string in comment)
      code = `'Some JS bundle code here'`
      framework.createInstance(instanceId + '~~~~~~', code)
      expect(frameworks.xxx.createInstance.callCount).equal(2)
      expect(frameworks.yyy.createInstance.callCount).equal(1)
      expect(frameworks.Weex.createInstance.callCount).equal(3)
      expect(frameworks.Weex.createInstance.thirdCall.args).eql([
        instanceId + '~~~~~~',
        code,
        { bundleVersion: undefined, env: {}},
        undefined
      ])

      // revert frameworks
      delete frameworks.xxx
      delete frameworks.yyy
      frameworks.Weex = weexFramework
    })
  })

  describe('getRoot', () => {
    it('with a exist instanceId', () => {
      const json = framework.getRoot(instanceId)
      expect(json.ref).eql('_root')
      clearRefs(json)
      const expectJSON = {
        type: 'container',
        attr: {},
        style: {},
        children: [{
          type: 'text',
          attr: {
            value: 'Hello World'
          },
          style: {}
        }]
      }
      expect(json).to.be.deep.equal(expectJSON)
    })

    it('with a non-exist instanceId', () => {
      const result = framework.getRoot('123')
      expect(result).to.be.an.instanceof(Error)
    })
  })

  describe('callJS', () => {
    it('fireEvent with no params', () => {
      framework.callJS()
    })

    it('fireEvent with a exist instanceId', () => {
      framework.callJS(instanceId, [{
        method: 'fireEvent',
        args: []
      }])
    })

    it('callback with a exist instanceId', () => {
      framework.callJS(instanceId, [{
        method: 'callback',
        args: []
      }])
    })

    it('with a non-exist instanceId', () => {
      const result = framework.callJS('123', [{
        method: 'fireEvent',
        args: []
      }])
      expect(result).to.be.an.instanceof(Error)
    })

    it('with a non-array tasks', () => {
      const result = framework.callJS(instanceId, {
        method: 'fireEvent',
        args: []
      })
      expect(result).to.be.an.instanceof(Error)
    })
  })

  describe('refreshInstance', () => {
    it('modify showText to false', () => {
      const json = framework.getRoot(instanceId)
      const textRef = json.children[0].ref
      framework.refreshInstance(instanceId, { showText: false })
      expect(callNativeSpy.callCount).to.be.equal(2)

      expect(callNativeSpy.firstCall.args[0]).to.be.equal(instanceId)
      expect(callNativeSpy.firstCall.args[1]).to.deep.equal([{
        module: 'dom',
        method: 'removeElement',
        args: [textRef]
      }])
      expect(callNativeSpy.firstCall.args[2]).to.be.equal('-1')

      expect(callNativeSpy.secondCall.args[0]).to.be.equal(instanceId)
      expect(callNativeSpy.secondCall.args[1]).to.deep.equal([{
        module: 'dom',
        method: 'refreshFinish',
        args: []
      }])
      expect(callNativeSpy.secondCall.args[2]).to.be.equal('-1')
    })

    it('with a non-exist instanceId', () => {
      const result = framework.refreshInstance('123', {})
      expect(result).to.be.an.instanceof(Error)
    })
  })

  describe('destroyInstance', () => {
    it('with no params', () => {
      framework.destroyInstance()
    })

    it('with a exist instanceId', () => {
      const result = framework.destroyInstance(instanceId)
      expect(result[instanceId]).to.be.undefined
    })

    it('with a non-exist instanceId', () => {
      const result = framework.destroyInstance('123')
      expect(result).to.be.an.instanceof(Error)
    })
  })

  describe('registerComponents', () => {
    it('with old format', () => {
      framework.registerComponents(['a', 'b', 'c'])
      expect(defaultConfig.nativeComponentMap).to.contain.keys('a', 'b', 'c')
    })

    it('with new format', () => {
      framework.registerComponents([{
        type: 'd',
        append: 'tree'
      }])
      expect(defaultConfig.nativeComponentMap).to.contain.keys('d')
      expect(defaultConfig.nativeComponentMap['d']).to.be.deep.equal({
        type: 'd',
        append: 'tree'
      })
    })

    it('with non-array', () => {
      framework.registerComponents({
        type: 'e'
      })
      expect(defaultConfig.nativeComponentMap).not.contain.keys('e')
    })
  })

  describe('register modules', () => {
    it('with object of modules', () => {
      clearModules()
      const modules = {
        a: [{
          name: 'b',
          args: ['string']
        }]
      }

      framework.registerModules(modules)
      expect(getModule('b')).an.object
      clearModules()
    })
  })

  describe('register methods', () => {
    it('with object of methods', () => {
      const methods = {
        a: sinon.spy()
      }

      framework.registerMethods(methods)
      expect(Vm.prototype.a).a.function
      delete Vm.prototype.a
    })
  })
})

describe('config', () => {
  it('config is an object', () => {
    init({})
  })
})

describe.skip('freeze the prototypes of vdom', function () {
  const { Document, Element, Comment, Listener } = config

  before(() => {
    runtime.freezePrototype()
  })

  it('Document.prototype', () => {
    expect(Document.prototype).to.be.frozen
  })

  it('Element & Element.prototype', () => {
    expect(Element).to.be.frozen
    expect(Element.prototype).to.be.frozen
  })

  it('Comment & Comment.prototype', () => {
    expect(Comment).to.be.frozen
    expect(Comment.prototype).to.be.frozen
  })

  it('Listener & Listener.prototype', () => {
    expect(Listener).to.be.frozen
    expect(Listener.prototype).to.be.frozen
  })
})


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>colour.adaptation.cie1994 Module — Colour 0.3.3 documentation</title>

    <link rel="stylesheet" href="_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootswatch-3.1.0/colour/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="_static/styles.css" type="text/css" />

    <link rel="top" title="Colour 0.3.3 documentation" href="index.html" />
    <link rel="up" title="colour.adaptation Package" href="colour.adaptation.html" />
    <link rel="next" title="colour.adaptation.cmccat2000 Module" href="colour.adaptation.cmccat2000.html" />
    <link rel="prev" title="colour.adaptation.dataset.cat Module" href="colour.adaptation.dataset.cat.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          Colour 0.3

colour-science.org

                   Documentation

                           API Reference

                           IPython Notebooks

                           Features

                           Contributing

    « colour.adaptatio...

    colour.adaptatio... »

<form class="navbar-form navbar-right" action="search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

colour.adaptation.cie1994 Module¶

CIE 1994 Chromatic Adaptation Model¶

Defines CIE 1994 chromatic adaptation model objects:

<tt class="xref py py-func docutils literal">chromatic_adaptation_CIE1994()</tt>

See also

CIE 1994 Chromatic Adaptation Model IPython Notebook

References

<colgroup><col class="label" /><col /></colgroup>

[1]	CIE TC 1-32. (1994). CIE 109-1994 A Method of Predicting Corresponding
Colours under Different Chromatic and Illuminance Adaptations
(pp. 1–18). ISBN:978-3-900734-51-0

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">CIE1994_XYZ_TO_RGB_MATRIX</tt> = array([[ 0.40024,  0.7076 , -0.08081],        [-0.2263 ,  1.16532,  0.0457 ],        [ 0.     ,  0.     ,  0.91822]])¶

CIE 1994 colour appearance model CIE XYZ colourspace to cone
responses matrix.

CIE1994_XYZ_TO_RGB_MATRIX : array_like, (3, 3)

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">CIE1994_RGB_TO_XYZ_MATRIX</tt> = array([[  1.85993639e+00,  -1.12938162e+00,   2.19897410e-01],        [  3.61191436e-01,   6.38812463e-01,  -6.37059684e-06],        [  0.00000000e+00,   0.00000000e+00,   1.08906362e+00]])¶

CIE 1994 colour appearance model cone responses to CIE XYZ colourspace
matrix.

CIE1994_RGB_TO_XYZ_MATRIX : array_like, (3, 3)

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">chromatic_adaptation_CIE1994</tt><big>(</big>XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2, n=1<big>)</big>[source]¶

Adapts given CIE XYZ_1 colourspace stimulus from test viewing conditions
to reference viewing conditions using CIE 1994 chromatic adaptation
model.

<col class="field-name" />
<col class="field-body" />

Parameters:

XYZ (array_like, (3,)) – CIE XYZ colourspace matrix of test sample / stimulus in domain
[0, 100].

xy_o1 (array_like, (2,)) – Chromaticity coordinates \(x_{o1}\) and \(y_{o1}\) of test
illuminant and background.

xy_o2 (array_like, (2,)) – Chromaticity coordinates \(x_{o2}\) and \(y_{o2}\) of reference
illuminant and background.

Y_o (numeric) – Luminance factor \(Y_o\) of achromatic background as percentage in
domain [18, 100].

E_o1 (numeric) – Test illuminance \(E_{o1}\) in \(cd/m^2\).

E_o2 (numeric) – Reference illuminance \(E_{o2}\) in \(cd/m^2\).

n (numeric, optional) – Noise component in fundamental primary system.

Returns:
Adapted CIE XYZ_2 colourspace test stimulus.

Return type:
ndarray, (3,)

Warning

The input domain of that definition is non standard!

Notes

Input CIE XYZ_1 colourspace matrix is in domain [0, 100].

Output CIE XYZ_2 colourspace matrix is in domain [0, 100].

Examples

>>> XYZ_1 = np.array([28.0, 21.26, 5.27])
>>> xy_o1 = (0.4476, 0.4074)
>>> xy_o2 = (0.3127, 0.3290)
>>> Y_o = 20
>>> E_o1 = 1000
>>> E_o2 = 1000
>>> chromatic_adaptation_CIE1994(XYZ_1, xy_o1, xy_o2, Y_o, E_o1, E_o2)
array([ 24.0337952...,  21.1562121...,  17.6430119...])

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">XYZ_to_RGB_cie1994</tt><big>(</big>XYZ<big>)</big>[source]¶

Converts from CIE XYZ colourspace to cone responses.

<col class="field-name" />
<col class="field-body" />

Parameters:	XYZ (array_like, (3,)) – CIE XYZ colourspace matrix.

Returns:	Cone responses.

Return type:	ndarray, (3,)

Examples

>>> XYZ = np.array([28.0, 21.26, 5.27])
>>> XYZ_to_RGB_cie1994(XYZ)
array([ 25.8244273...,  18.6791422...,   4.8390194...])

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">RGB_to_XYZ_cie1994</tt><big>(</big>RGB<big>)</big>[source]¶

Converts from cone responses to CIE XYZ colourspace.

<col class="field-name" />
<col class="field-body" />

Parameters:	RGB (array_like, (3,)) – Cone responses.

Returns:	CIE XYZ colourspace matrix.

Return type:	ndarray, (3,)

Examples

>>> RGB = np.array([25.8244273, 18.6791422, 4.8390194])
>>> RGB_to_XYZ_cie1994(RGB)
array([ 28.  ,  21.26,   5.27])

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">intermediate_values</tt><big>(</big>xy_o<big>)</big>[source]¶

Returns the intermediate values \(\xi\), \(\eta\), \(\zeta\).

<col class="field-name" />
<col class="field-body" />

Parameters:	xy_o (array_like, (2,)) – Chromaticity coordinates \(x_o\) and \(y_o\) of whitepoint.

Returns:	Intermediate values \(\xi\), \(\eta\), \(\zeta\).

Return type:	ndarray, (3,)

Examples

>>> xy_o = (0.4476, 0.4074)
>>> intermediate_values(xy_o)
array([ 1.1185719...,  0.9329553...,  0.3268087...])

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">effective_adapting_responses</tt><big>(</big>Y_o, E_o, xez<big>)</big>[source]¶

Derives the effective adapting responses in the fundamental primary system
of the test or reference field.

<col class="field-name" />
<col class="field-body" />

Parameters:

Y_o (numeric) – Luminance factor \(Y_o\) of achromatic background as percentage in
domain [18, 100].

E_o (numeric) – Test or reference illuminance \(E_{o}\) in lux.

xez (ndarray, (3,)) – Intermediate values \(\xi\), \(\eta\), \(\zeta\).

Returns:
Effective adapting responses.

Return type:
ndarray, (3,)

Examples

>>> Y_o = 20
>>> E_o = 1000
>>> xez = np.array([1.11857195, 0.9329553, 0.32680879])
>>> effective_adapting_responses(Y_o, E_o, xez)
array([ 71.2105020...,  59.3937790...,  20.8052937...])

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">beta_1</tt><big>(</big>x<big>)</big>[source]¶

Computes the exponent \(\beta_1\) for the middle and long-wavelength
sensitive cones.

<col class="field-name" />
<col class="field-body" />

Parameters:	x (numeric) – Middle and long-wavelength sensitive cone response.

Returns:	Exponent \(\beta_1\).

Return type:	numeric

Examples

>>> beta_1(318.323316315)
4.6106222...

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">beta_2</tt><big>(</big>x<big>)</big>[source]¶

Computes the exponent \(\beta_2\) for the short-wavelength sensitive
cones.

<col class="field-name" />
<col class="field-body" />

Parameters:	x (numeric) – Short-wavelength sensitive cone response.

Returns:	Exponent \(\beta_2\).

Return type:	numeric

Examples

>>> beta_2(318.323316315)
4.6522416...

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">exponential_factors</tt><big>(</big>RGB_o<big>)</big>[source]¶

Returns the chromatic adaptation exponential factors \(\beta_1(R_o)\),
\(\beta_1(G_o)\) and \(\beta_2(B_o)\) of given cone responses.

<col class="field-name" />
<col class="field-body" />

Parameters:	RGB_o (ndarray, (3,)) – Cone responses.

Returns:	Chromatic adaptation exponential factors \(\beta_1(R_o)\),
\(\beta_1(G_o)\) and \(\beta_2(B_o)\).

Return type:	ndarray, (3,)

Examples

>>> RGB_o = np.array([318.32331631, 318.30352317, 318.23283482])
>>> exponential_factors(RGB_o)
array([ 4.6106222...,  4.6105892...,  4.6520698...])

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">K_coefficient</tt><big>(</big>Y_o, xez_1, xez_2, bRGB_o1, bRGB_o2, n=1<big>)</big>[source]¶

Computes the coefficient \(K\) for correcting the difference between
the test and references illuminances.

<col class="field-name" />
<col class="field-body" />

Parameters:

Y_o (numeric) – Luminance factor \(Y_o\) of achromatic background as percentage in
domain [18, 100].

xez_1 (ndarray, (3,)) – Intermediate values \(\xi_1\), \(\eta_1\), \(\zeta_1\) for
the test illuminant and background.

xez_2 (ndarray, (3,)) – Intermediate values \(\xi_2\), \(\eta_2\), \(\zeta_2\) for
the reference illuminant and background.

bRGB_o1 (ndarray, (3,)) – Chromatic adaptation exponential factors \(\beta_1(R_{o1})\),
\(\beta_1(G_{o1})\) and \(\beta_2(B_{o1})\) of test sample.

bRGB_o2 (ndarray, (3,)) – Chromatic adaptation exponential factors \(\beta_1(R_{o2})\),
\(\beta_1(G_{o2})\) and \(\beta_2(B_{o2})\) of reference
sample.

n (numeric, optional) – Noise component in fundamental primary system.

Returns:
Coefficient \(K\).

Return type:
numeric

Examples

>>> Y_o = 20
>>> xez_1 = np.array([1.11857195, 0.9329553, 0.32680879])
>>> xez_2 = np.array([1.00000372, 1.00000176, 0.99999461])
>>> bRGB_o1 = np.array([3.74852518, 3.63920879, 2.78924811])
>>> bRGB_o2 = np.array([3.68102374, 3.68102256, 3.56557351])
>>> K_coefficient(Y_o, xez_1, xez_2, bRGB_o1, bRGB_o2)
1.0

<tt class="descclassname">colour.adaptation.cie1994.</tt><tt class="descname">corresponding_colour</tt><big>(</big>RGB_1, Y_o, xez_1, xez_2, bRGB_o1, bRGB_o2, K, n=1<big>)</big>[source]¶

Computes the corresponding colour cone responses of given test sample cone
responses \(RGB_1\).

<col class="field-name" />
<col class="field-body" />

Parameters:

RGB_1 (ndarray, (3,)) – Test sample cone responses \(RGB_1\).

Y_o (numeric) – Luminance factor \(Y_o\) of achromatic background as percentage in
domain [18, 100].

xez_1 (ndarray, (3,)) – Intermediate values \(\xi_1\), \(\eta_1\), \(\zeta_1\) for
the test illuminant and background.

xez_2 (ndarray, (3,)) – Intermediate values \(\xi_2\), \(\eta_2\), \(\zeta_2\) for
the reference illuminant and background.

bRGB_o1 (ndarray, (3,)) – Chromatic adaptation exponential factors \(\beta_1(R_{o1})\),
\(\beta_1(G_{o1})\) and \(\beta_2(B_{o1})\) of test sample.

bRGB_o2 (ndarray, (3,)) – Chromatic adaptation exponential factors \(\beta_1(R_{o2})\),
\(\beta_1(G_{o2})\) and \(\beta_2(B_{o2})\) of reference
sample.

K (numeric) – Coefficient \(K\).

n (numeric, optional) – Noise component in fundamental primary system.

Returns:
Corresponding colour cone responses of given test sample cone
responses.

Return type:
ndarray, (3,)

Examples

>>> RGB_1 = np.array([25.8244273, 18.6791422, 4.8390194])
>>> Y_o = 20
>>> xez_1 = np.array([1.11857195, 0.9329553, 0.32680879])
>>> xez_2 = np.array([1.00000372, 1.00000176, 0.99999461])
>>> bRGB_o1 = np.array([3.74852518, 3.63920879, 2.78924811])
>>> bRGB_o2 = np.array([3.68102374, 3.68102256, 3.56557351])
>>> K = 1.0
>>> corresponding_colour(RGB_1, Y_o, xez_1, xez_2, bRGB_o1, bRGB_o2, K)
array([ 23.1636901...,  20.0211948...,  16.2001664...])

      Back to top

        © Copyright 2013 - 2014, Colour Developers.

      Created using Sphinx 1.2.2.


text:
using System;
using System.Collections.Generic;
using System.Threading;

using ICities;
using ColossalFramework;
using ColossalFramework.Math;
using ColossalFramework.Plugins;
using ColossalFramework.UI;
using UnityEngine;

namespace EnhancedHearseAI
{
    public class Dispatcher : ThreadingExtensionBase
    {
        private Settings _settings;
        private Helper _helper;

        private string _collecting = ColossalFramework.Globalization.Locale.Get("VEHICLE_STATUS_HEARSE_COLLECT");

        private bool _initialized;
        private bool _baselined;
        private bool _terminated;

        private Dictionary<ushort, Cemetery> _cemeteries;
        private Dictionary<ushort, Claimant> _master;
        private HashSet<ushort> _stopped;

        protected bool IsOverwatched()
        {
            #if DEBUG

            return true;

            #else

            foreach (var plugin in PluginManager.instance.GetPluginsInfo())
            {
                if (plugin.publishedFileID.AsUInt64 == 421028969)
                    return true;
            }

            return false;

            #endif
        }

        public override void OnCreated(IThreading threading)
        {
            _settings = Settings.Instance;
            _helper = Helper.Instance;

            _initialized = false;
            _baselined = false;
            _terminated = false;

            base.OnCreated(threading);
        }

        public override void OnBeforeSimulationTick()
        {
            if (_terminated) return;

            if (!_helper.GameLoaded)
            {
                _initialized = false;
                _baselined = false;
                return;
            }

            base.OnBeforeSimulationTick();
        }

        public override void OnUpdate(float realTimeDelta, float simulationTimeDelta)
        {
            if (_terminated) return;

            if (!_helper.GameLoaded) return;

            try
            {
                if (!_initialized)
                {
                    if (!IsOverwatched())
                    {
                        _helper.NotifyPlayer("Skylines Overwatch not found. Terminating...");
                        _terminated = true;

                        return;
                    }

                    SkylinesOverwatch.Settings.Instance.Enable.BuildingMonitor = true;
                    SkylinesOverwatch.Settings.Instance.Enable.VehicleMonitor = true;

                    _cemeteries = new Dictionary<ushort, Cemetery>();
                    _master = new Dictionary<ushort, Claimant>();
                    _stopped = new HashSet<ushort>();

                    _initialized = true;

                    _helper.NotifyPlayer("Initialized");
                }
                else if (!_baselined)
                {
                    CreateBaseline();
                }
                else
                {
                    ProcessNewCemeteries();
                    ProcessRemovedCemeteries();

                    ProcessNewPickups();

                    UpdateHearses();

                    /*
                    if (SimulationManager.instance.SimulationPaused)
                    {
                        foreach (ushort id in _master.Keys)
                        {
                            string name = Singleton<BuildingManager>.instance.GetBuildingName(id, new InstanceID { Building = id });

                            if (!name.Contains("##"))
                                continue;

                            _helper.NotifyPlayer(String.Format("{0} ({1}) {2}/{3}", _master[id].Hearse, Math.Sqrt(_master[id].Distance), _master[id].IsValid, _master[id].IsChallengable));
                        }
                    }
                    */
                }
            }
            catch (Exception e)
            {
                string error = String.Format("Failed to {0}\r\n", !_initialized ? "initialize" : "update");
                error += String.Format("Error: {0}\r\n", e.Message);
                error += "\r\n";
                error += "==== STACK TRACE ====\r\n";
                error += e.StackTrace;

                _helper.Log(error);

                if (!_initialized)
                    _terminated = true;
            }

            base.OnUpdate(realTimeDelta, simulationTimeDelta);
        }

        public override void OnReleased()
        {
            _initialized = false;
            _baselined = false;
            _terminated = false;

            base.OnReleased();
        }

        private void CreateBaseline()
        {
            SkylinesOverwatch.Data data = SkylinesOverwatch.Data.Instance;

            foreach (ushort id in data.Cemeteries)
                _cemeteries.Add(id, new Cemetery(id, ref _master));

            foreach (ushort pickup in data.BuildingsWithDead)
            {
                foreach (ushort id in _cemeteries.Keys)
                    _cemeteries[id].AddPickup(pickup);
            }

            _baselined = true;
        }

        private void ProcessNewCemeteries()
        {
            SkylinesOverwatch.Data data = SkylinesOverwatch.Data.Instance;

            foreach (ushort x in data.BuildingsUpdated)
            {
                if (!data.IsCemetery(x))
                    continue;

                if (_cemeteries.ContainsKey(x))
                    continue;

                _cemeteries.Add(x, new Cemetery(x, ref _master));

                foreach (ushort pickup in data.BuildingsWithDead)
                    _cemeteries[x].AddPickup(pickup);
            }
        }

        private void ProcessRemovedCemeteries()
        {
            SkylinesOverwatch.Data data = SkylinesOverwatch.Data.Instance;

            foreach (ushort id in data.BuildingsRemoved)
                _cemeteries.Remove(id);
        }

        private void ProcessNewPickups()
        {
            SkylinesOverwatch.Data data = SkylinesOverwatch.Data.Instance;

            foreach (ushort pickup in data.BuildingsUpdated)
            {
                foreach (ushort id in _cemeteries.Keys)
                {
                    if (data.IsBuildingWithDead(pickup))
                        _cemeteries[id].AddPickup(pickup);
                    else
                        _cemeteries[id].AddCheckup(pickup);
                }
            }
        }

        private void UpdateHearses()
        {
            SkylinesOverwatch.Data data = SkylinesOverwatch.Data.Instance;
            Vehicle[] vehicles = Singleton<VehicleManager>.instance.m_vehicles.m_buffer;
            InstanceID instanceID = new InstanceID();

            foreach (ushort id in data.VehiclesUpdated)
            {
                if (!data.IsHearse(id))
                    continue;

                Vehicle v = vehicles[id];

                /*
                 * If a hearse is loading corpse, we will remove it from the vehicle grid,
                 * so other cars can pass it and more than one hearse can service a building.
                 * It doesn't really make sense that only one hearse can be at a high rise
                 * at a time.
                 */
                if (v.m_flags.IsFlagSet(Vehicle.Flags.Stopped))
                {
                    if (!_stopped.Contains(id))
                    {
                        Singleton<VehicleManager>.instance.RemoveFromGrid(id, ref vehicles[id], false);
                        _stopped.Add(id);
                    }

                    continue;
                }
                else
                    _stopped.Remove(id);

                if (!_cemeteries.ContainsKey(v.m_sourceBuilding))
                    continue;

                if (v.Info.m_vehicleAI.GetLocalizedStatus(id, ref v, out instanceID) != _collecting)
                    continue;

                ushort target = _cemeteries[v.m_sourceBuilding].AssignTarget(id);

                if (target != 0 && target != v.m_targetBuilding)
                    v.Info.m_vehicleAI.SetTarget(id, ref vehicles[id], target);
            }
        }
    }
}


text:
$outputPath = "$PSScriptRoot\Distr"

Import-Module "$PSScriptRoot\Scripts\BuildHelpers.psm1"

Initialize-BuildVariables
Invoke-NugetRestore "$PSScriptRoot\DBVer.sln"

Invoke-SolutionBuild "$PSScriptRoot\DBVer.sln" 'Release'

if (Test-Path $outputPath)
{
    Remove-Item -recurse -force $outputPath
}

New-Item $outputPath -ItemType directory

$nugetExePath = "$PSScriptRoot\Scripts\nuget.exe"
$packagesPath = "$PSScriptRoot\packages"
&$nugetExePath install ILMerge -Version '2.14.1208' -OutputDirectory $packagesPath

$releasePath = "$PSScriptRoot\bin\Release"
$ilMergePath = $packagesPath + '\ilmerge.2.14.1208\tools\ILMerge.exe'

&$ilMergePath "/out:${outputPath}\DBVer.exe" "$releasePath\DBVer.exe" "$releasePath\*.dll" '/wildcards'

Copy-Item "$releasePath\DBVer.exe.config" $outputPath

&"${env:ProgramFiles}\7-Zip\7z.exe" a "$outputPath\DBVer0.0.0.zip" "$outputPath\*"

"`nhttps://github.com/dermeister0/DBVer/releases"


text:
using NUnit.Framework;
using System;
using System.IO;

namespace MonoTests.System.IO
{
	[TestFixture]
	public class FileSystemWatcherTest : Assertion
	{
		[Test]
		public void CheckDefaults ()
		{
			FileSystemWatcher fw = new FileSystemWatcher ();
			AssertEquals ("#01", fw.EnableRaisingEvents, false);
			AssertEquals ("#02", fw.Filter, "*.*");
			AssertEquals ("#03", fw.IncludeSubdirectories, false);
			AssertEquals ("#04", fw.InternalBufferSize, 8192);
			AssertEquals ("#05", fw.NotifyFilter, NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite);
			AssertEquals ("#06", fw.Path, "");
		}

		[Test]
		[ExpectedException (typeof (ArgumentNullException))]
		public void CheckCtor1 ()
		{
			FileSystemWatcher fw = new FileSystemWatcher (null);
		}

		[Test]
		[ExpectedException (typeof (ArgumentException))]
		public void CheckCtor2 ()
		{
			FileSystemWatcher fw = new FileSystemWatcher ("");
		}

		[Test]
		[ExpectedException (typeof (ArgumentException))]
		public void CheckCtor3 ()
		{
			FileSystemWatcher fw = new FileSystemWatcher ("notexistsblahblah");
		}

		[Test]
		[ExpectedException (typeof (ArgumentNullException))]
		public void CheckCtor4 ()
		{
			FileSystemWatcher fw = new FileSystemWatcher (Path.GetTempPath (), null);
		}

		[Test]
		// Doesn't throw here :-?
		// [ExpectedException (typeof (ArgumentException))]
		public void CheckCtor5 ()
		{
			FileSystemWatcher fw = new FileSystemWatcher (Path.GetTempPath (), "invalidpath|");
			fw = new FileSystemWatcher (Path.GetTempPath (), "*");
		}

		[Test]
		// ...But here it does...
		[ExpectedException (typeof (ArgumentException))]
		public void CheckInvalidPath ()
		{
			FileSystemWatcher fw = new FileSystemWatcher (Path.GetTempPath (), "invalidpath|");
			fw.Path = "invalidpath|";
		}

		[Test]
		// ...and here too
		[ExpectedException (typeof (ArgumentException))]
		public void CheckPathWildcard ()
		{
			FileSystemWatcher fw = new FileSystemWatcher (Path.GetTempPath (), "*");
			fw.Path = "*";
		}
	}
}


text:
package p2p

import (
	"crypto/ecdsa"
	"errors"
	"math/rand"
	"net"
	"reflect"
	"testing"
	"time"

	"github.com/ethereum/go-ethereum/log"
	"github.com/fractalplatform/fractal/crypto"
	"github.com/fractalplatform/fractal/p2p/enode"
	"github.com/fractalplatform/fractal/p2p/enr"
	"golang.org/x/crypto/sha3"
)

// func init() {
// 	log.Root().SetHandler(log.LvlFilterHandler(log.LvlTrace, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))
// }

type testTransport struct {
	rpub *ecdsa.PublicKey
	*rlpx

	closeErr error
}

func newTestTransport(rpub *ecdsa.PublicKey, fd net.Conn) transport {
	wrapped := newRLPX(fd, 0).(*rlpx)
	wrapped.rw = newRLPXFrameRW(fd, secrets{
		MAC:        zero16,
		AES:        zero16,
		IngressMAC: sha3.NewLegacyKeccak256(),
		EgressMAC:  sha3.NewLegacyKeccak256(),
	})
	return &testTransport{rpub: rpub, rlpx: wrapped}
}

func (c *testTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *ecdsa.PublicKey) (*ecdsa.PublicKey, error) {
	return c.rpub, nil
}

func (c *testTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) {
	pubkey := crypto.FromECDSAPub(c.rpub)[1:]
	return &protoHandshake{ID: pubkey, Name: "test"}, nil
}

func (c *testTransport) close(err error) {
	c.rlpx.fd.Close()
	c.closeErr = err
}

func startTestServer(t *testing.T, remoteKey *ecdsa.PublicKey, pf func(*Peer)) *Server {
	config := &Config{
		Name:       "test",
		MaxPeers:   10,
		ListenAddr: "127.0.0.1:0",
		PrivateKey: newkey(),
	}
	server := &Server{
		Config:       config,
		newPeerHook:  pf,
		newTransport: func(fd net.Conn, _ uint64) transport { return newTestTransport(remoteKey, fd) },
	}
	if err := server.Start(); err != nil {
		t.Fatalf("Could not start server: %v", err)
	}
	return server
}

func TestServerListen(t *testing.T) {
	// start the test server
	connected := make(chan *Peer)
	remid := &newkey().PublicKey
	srv := startTestServer(t, remid, func(p *Peer) {
		if p.ID() != enode.PubkeyToIDV4(remid) {
			t.Error("peer func called with wrong node id")
		}
		connected <- p
	})
	defer close(connected)
	defer srv.Stop()

	// dial the test server
	conn, err := net.DialTimeout("tcp", srv.ListenAddr, 5*time.Second)
	if err != nil {
		t.Fatalf("could not dial: %v", err)
	}
	defer conn.Close()

	select {
	case peer := <-connected:
		if peer.LocalAddr().String() != conn.RemoteAddr().String() {
			t.Errorf("peer started with wrong conn: got %v, want %v",
				peer.LocalAddr(), conn.RemoteAddr())
		}
		peers := srv.Peers()
		if !reflect.DeepEqual(peers, []*Peer{peer}) {
			t.Errorf("Peers mismatch: got %v, want %v", peers, []*Peer{peer})
		}
	case <-time.After(1 * time.Second):
		t.Error("server did not accept within one second")
	}
}

func TestServerDial(t *testing.T) {
	// run a one-shot TCP server to handle the connection.
	listener, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("could not setup listener: %v", err)
	}
	defer listener.Close()
	accepted := make(chan net.Conn)
	go func() {
		conn, err := listener.Accept()
		if err != nil {
			t.Error("accept error:", err)
			return
		}
		accepted <- conn
	}()

	// start the server
	connected := make(chan *Peer)
	remid := &newkey().PublicKey
	srv := startTestServer(t, remid, func(p *Peer) { connected <- p })
	defer close(connected)
	defer srv.Stop()

	// tell the server to connect
	tcpAddr := listener.Addr().(*net.TCPAddr)
	node := enode.NewV4(remid, tcpAddr.IP, tcpAddr.Port, 0)
	srv.AddPeer(node)

	select {
	case conn := <-accepted:
		defer conn.Close()

		select {
		case peer := <-connected:
			if peer.ID() != enode.PubkeyToIDV4(remid) {
				t.Errorf("peer has wrong id")
			}
			if peer.Name() != "test" {
				t.Errorf("peer has wrong name")
			}
			if peer.RemoteAddr().String() != conn.LocalAddr().String() {
				t.Errorf("peer started with wrong conn: got %v, want %v",
					peer.RemoteAddr(), conn.LocalAddr())
			}
			peers := srv.Peers()
			if !reflect.DeepEqual(peers, []*Peer{peer}) {
				t.Errorf("Peers mismatch: got %v, want %v", peers, []*Peer{peer})
			}

			// Test AddTrustedPeer/RemoveTrustedPeer and changing Trusted flags
			// Particularly for race conditions on changing the flag state.
			if peer := srv.Peers()[0]; peer.Info().Network.Trusted {
				t.Errorf("peer is trusted prematurely: %v", peer)
			}
			done := make(chan bool)
			go func() {
				srv.AddTrustedPeer(node)
				if peer := srv.Peers()[0]; !peer.Info().Network.Trusted {
					t.Errorf("peer is not trusted after AddTrustedPeer: %v", peer)
				}
				srv.RemoveTrustedPeer(node)
				if peer := srv.Peers()[0]; peer.Info().Network.Trusted {
					t.Errorf("peer is trusted after RemoveTrustedPeer: %v", peer)
				}
				done <- true
			}()
			// Trigger potential race conditions
			peer = srv.Peers()[0]
			_ = peer.Inbound()
			_ = peer.Info()
			<-done
		case <-time.After(1 * time.Second):
			t.Error("server did not launch peer within one second")
		}

	case <-time.After(1 * time.Second):
		t.Error("server did not connect within one second")
	}
}

// This test checks that tasks generated by dialstate are
// actually executed and taskdone is called for them.
func TestServerTaskScheduling(t *testing.T) {
	var (
		done           = make(chan *testTask)
		quit, returned = make(chan struct{}), make(chan struct{})
		tc             = 0
		tg             = taskgen{
			newFunc: func(running int, peers map[enode.ID]*Peer) []task {
				tc++
				return []task{&testTask{index: tc - 1}}
			},
			doneFunc: func(t task) {
				select {
				case done <- t.(*testTask):
				case <-quit:
				}
			},
		}
	)

	// The Server in this test isn't actually running
	// because we're only interested in what run does.
	srv := &Server{
		Config:  &Config{MaxPeers: 10},
		quit:    make(chan struct{}),
		ntab:    fakeTable{},
		running: true,
		log:     log.New(),
	}
	srv.loopWG.Add(1)
	go func() {
		srv.run(tg)
		close(returned)
	}()

	var gotdone []*testTask
	for i := 0; i < 100; i++ {
		gotdone = append(gotdone, <-done)
	}
	for i, task := range gotdone {
		if task.index != i {
			t.Errorf("task %d has wrong index, got %d", i, task.index)
			break
		}
		if !task.called {
			t.Errorf("task %d was not called", i)
			break
		}
	}

	close(quit)
	srv.Stop()
	select {
	case <-returned:
	case <-time.After(500 * time.Millisecond):
		t.Error("Server.run did not return within 500ms")
	}
}

// This test checks that Server doesn't drop tasks,
// even if newTasks returns more than the maximum number of tasks.
func TestServerManyTasks(t *testing.T) {
	alltasks := make([]task, 300)
	for i := range alltasks {
		alltasks[i] = &testTask{index: i}
	}

	var (
		srv = &Server{
			Config:  &Config{},
			quit:    make(chan struct{}),
			ntab:    fakeTable{},
			running: true,
			log:     log.New(),
		}
		done       = make(chan *testTask)
		start, end = 0, 0
	)
	defer srv.Stop()
	srv.loopWG.Add(1)
	go srv.run(taskgen{
		newFunc: func(running int, peers map[enode.ID]*Peer) []task {
			start, end = end, end+maxActiveDialTasks+10
			if end > len(alltasks) {
				end = len(alltasks)
			}
			return alltasks[start:end]
		},
		doneFunc: func(tt task) {
			done <- tt.(*testTask)
		},
	})

	doneset := make(map[int]bool)
	timeout := time.After(2 * time.Second)
	for len(doneset) < len(alltasks) {
		select {
		case tt := <-done:
			if doneset[tt.index] {
				t.Errorf("task %d got done more than once", tt.index)
			} else {
				doneset[tt.index] = true
			}
		case <-timeout:
			t.Errorf("%d of %d tasks got done within 2s", len(doneset), len(alltasks))
			for i := 0; i < len(alltasks); i++ {
				if !doneset[i] {
					t.Logf("task %d not done", i)
				}
			}
			return
		}
	}
}

type taskgen struct {
	newFunc  func(running int, peers map[enode.ID]*Peer) []task
	doneFunc func(task)
}

func (tg taskgen) newTasks(running int, peers map[enode.ID]*Peer, now time.Time) []task {
	return tg.newFunc(running, peers)
}
func (tg taskgen) taskDone(t task, now time.Time) {
	tg.doneFunc(t)
}
func (tg taskgen) addStatic(*enode.Node) {
}
func (tg taskgen) removeStatic(*enode.Node) {
}

type testTask struct {
	index  int
	called bool
}

func (t *testTask) Do(srv *Server) {
	t.called = true
}

func TestServerBadNodes(t *testing.T) {
	badNode := newkey()
	badID := enode.PubkeyToIDV4(&badNode.PublicKey)
	srv := &Server{
		Config: &Config{
			PrivateKey: newkey(),
			MaxPeers:   10,
			NoDial:     true,
		},
	}
	if err := srv.Start(); err != nil {
		t.Fatalf("could not start: %v", err)
	}
	defer srv.Stop()
	newconn := func(id enode.ID) *conn {
		fd, _ := net.Pipe()
		tx := newTestTransport(&badNode.PublicKey, fd)
		node := enode.SignNull(new(enr.Record), id)
		return &conn{fd: fd, transport: tx, flags: inboundConn, node: node, cont: make(chan error)}
	}

	c := newconn(badID)
	if err := srv.checkpoint(c, srv.posthandshake); err != nil {
		t.Fatal("wrong error for posthandshake:", err)
	}

	c = newconn(badID)
	srv.AddBadNode(c.node, nil)
	if err := srv.checkpoint(c, srv.posthandshake); err != DiscBadNode {
		t.Fatal("wrong error for posthandshake:", err)
	}

	c = newconn(badID)
	srv.AddTrustedPeer(c.node)
	if err := srv.checkpoint(c, srv.posthandshake); err != nil {
		t.Fatal("wrong error for posthandshake:", err)
	}

	c = newconn(badID)
	srv.RemoveBadNode(c.node)
	srv.RemoveTrustedPeer(c.node)
	endtime := time.Now().Add(time.Second)
	srv.AddBadNode(c.node, &endtime)
	if err := srv.checkpoint(c, srv.posthandshake); err != DiscBadNode {
		t.Fatal("wrong error for posthandshake:", err)
	}

	time.Sleep(2 * time.Second)
	c = newconn(badID)
	if err := srv.checkpoint(c, srv.posthandshake); err != nil {
		t.Fatal("wrong error for posthandshake:", err)
	}
}

// This test checks that connections are disconnected
// just after the encryption handshake when the server is
// at capacity. Trusted connections should still be accepted.
func TestServerAtCap(t *testing.T) {
	trustedNode := newkey()
	trustedID := enode.PubkeyToIDV4(&trustedNode.PublicKey)
	srv := &Server{
		Config: &Config{
			PrivateKey:   newkey(),
			MaxPeers:     10,
			NoDial:       true,
			TrustedNodes: []*enode.Node{newNode(trustedID, nil)},
		},
	}
	if err := srv.Start(); err != nil {
		t.Fatalf("could not start: %v", err)
	}
	defer srv.Stop()

	newconn := func(id enode.ID) *conn {
		fd, _ := net.Pipe()
		tx := newTestTransport(&trustedNode.PublicKey, fd)
		node := enode.SignNull(new(enr.Record), id)
		return &conn{fd: fd, transport: tx, flags: inboundConn, node: node, cont: make(chan error)}
	}

	// Inject a few connections to fill up the peer set.
	for i := 0; i < 10; i++ {
		c := newconn(randomID())
		if err := srv.checkpoint(c, srv.addpeer); err != nil {
			t.Fatalf("could not add conn %d: %v", i, err)
		}
	}
	// Try inserting a non-trusted connection.
	anotherID := randomID()
	c := newconn(anotherID)
	if err := srv.checkpoint(c, srv.posthandshake); err != DiscTooManyPeers {
		t.Error("wrong error for insert:", err)
	}
	// Try inserting a trusted connection.
	c = newconn(trustedID)
	if err := srv.checkpoint(c, srv.posthandshake); err != nil {
		t.Error("unexpected error for trusted conn @posthandshake:", err)
	}
	if !c.is(trustedConn) {
		t.Error("Server did not set trusted flag")
	}

	// Remove from trusted set and try again
	srv.RemoveTrustedPeer(newNode(trustedID, nil))
	c = newconn(trustedID)
	if err := srv.checkpoint(c, srv.posthandshake); err != DiscTooManyPeers {
		t.Error("wrong error for insert:", err)
	}

	// Add anotherID to trusted set and try again
	srv.AddTrustedPeer(newNode(anotherID, nil))
	c = newconn(anotherID)
	if err := srv.checkpoint(c, srv.posthandshake); err != nil {
		t.Error("unexpected error for trusted conn @posthandshake:", err)
	}
	if !c.is(trustedConn) {
		t.Error("Server did not set trusted flag")
	}
}

func TestServerPeerLimits(t *testing.T) {
	srvkey := newkey()
	clientkey := newkey()
	clientnode := enode.NewV4(&clientkey.PublicKey, nil, 0, 0)

	var tp = &setupTransport{
		pubkey: &clientkey.PublicKey,
		phs: protoHandshake{
			ID: crypto.FromECDSAPub(&clientkey.PublicKey)[1:],
			// Force "DiscUselessPeer" due to unmatching caps
			// Caps: []Cap{discard.cap()},
		},
	}

	srv := &Server{
		Config: &Config{
			PrivateKey: srvkey,
			MaxPeers:   0,
			NoDial:     true,
			Protocols:  []Protocol{discard},
		},
		newTransport: func(fd net.Conn, _ uint64) transport { return tp },
		log:          log.New(),
	}
	if err := srv.Start(); err != nil {
		t.Fatalf("couldn't start server: %v", err)
	}
	defer srv.Stop()

	// Check that server is full (MaxPeers=0)
	flags := dynDialedConn
	dialDest := clientnode
	conn, _ := net.Pipe()
	srv.SetupConn(conn, flags, dialDest)
	if tp.closeErr != DiscTooManyPeers {
		t.Errorf("unexpected close error: %q", tp.closeErr)
	}
	conn.Close()

	srv.AddTrustedPeer(clientnode)

	// Check that server allows a trusted peer despite being full.
	conn, _ = net.Pipe()
	srv.SetupConn(conn, flags, dialDest)
	if tp.closeErr == DiscTooManyPeers {
		t.Errorf("failed to bypass MaxPeers with trusted node: %q", tp.closeErr)
	}

	if tp.closeErr != DiscUselessPeer {
		t.Errorf("unexpected close error: %q", tp.closeErr)
	}
	conn.Close()

	srv.RemoveTrustedPeer(clientnode)

	// Check that server is full again.
	conn, _ = net.Pipe()
	srv.SetupConn(conn, flags, dialDest)
	if tp.closeErr != DiscTooManyPeers {
		t.Errorf("unexpected close error: %q", tp.closeErr)
	}
	conn.Close()
}

func TestServerSetupConn(t *testing.T) {
	var (
		clientkey, srvkey = newkey(), newkey()
		clientpub         = &clientkey.PublicKey
		srvpub            = &srvkey.PublicKey
	)
	tests := []struct {
		dontstart bool
		tt        *setupTransport
		flags     connFlag
		dialDest  *enode.Node

		wantCloseErr error
		wantCalls    string
	}{
		{
			dontstart:    true,
			tt:           &setupTransport{pubkey: clientpub},
			wantCalls:    "close,",
			wantCloseErr: errServerStopped,
		},
		{
			tt:           &setupTransport{pubkey: clientpub, encHandshakeErr: errors.New("read error")},
			flags:        inboundConn,
			wantCalls:    "doEncHandshake,close,",
			wantCloseErr: errors.New("read error"),
		},
		{
			tt:           &setupTransport{pubkey: clientpub},
			dialDest:     enode.NewV4(&newkey().PublicKey, nil, 0, 0),
			flags:        dynDialedConn,
			wantCalls:    "doEncHandshake,close,",
			wantCloseErr: DiscUnexpectedIdentity,
		},
		{
			tt:           &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: randomID().Bytes()}},
			dialDest:     enode.NewV4(clientpub, nil, 0, 0),
			flags:        dynDialedConn,
			wantCalls:    "doEncHandshake,doProtoHandshake,close,",
			wantCloseErr: DiscUnexpectedIdentity,
		},
		{
			tt:           &setupTransport{pubkey: clientpub, protoHandshakeErr: errors.New("foo")},
			dialDest:     enode.NewV4(clientpub, nil, 0, 0),
			flags:        dynDialedConn,
			wantCalls:    "doEncHandshake,doProtoHandshake,close,",
			wantCloseErr: errors.New("foo"),
		},
		{
			tt:           &setupTransport{pubkey: srvpub, phs: protoHandshake{ID: crypto.FromECDSAPub(srvpub)[1:]}},
			flags:        inboundConn,
			wantCalls:    "doEncHandshake,close,",
			wantCloseErr: DiscSelf,
		},
		{
			tt:           &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: crypto.FromECDSAPub(clientpub)[1:]}},
			flags:        inboundConn,
			wantCalls:    "doEncHandshake,doProtoHandshake,close,",
			wantCloseErr: DiscUselessPeer,
		},
	}

	for i, test := range tests {
		srv := &Server{
			Config: &Config{
				PrivateKey: srvkey,
				MaxPeers:   10,
				NoDial:     true,
				Protocols:  []Protocol{discard},
			},
			newTransport: func(fd net.Conn, _ uint64) transport { return test.tt },
			log:          log.New(),
		}
		if !test.dontstart {
			if err := srv.Start(); err != nil {
				t.Fatalf("couldn't start server: %v", err)
			}
		}
		p1, _ := net.Pipe()
		srv.SetupConn(p1, test.flags, test.dialDest)
		if !reflect.DeepEqual(test.tt.closeErr, test.wantCloseErr) {
			t.Errorf("test %d: close error mismatch: got %q, want %q", i, test.tt.closeErr, test.wantCloseErr)
		}
		if test.tt.calls != test.wantCalls {
			t.Errorf("test %d: calls mismatch: got %q, want %q", i, test.tt.calls, test.wantCalls)
		}
	}
}

type setupTransport struct {
	pubkey            *ecdsa.PublicKey
	encHandshakeErr   error
	phs               protoHandshake
	protoHandshakeErr error

	calls    string
	closeErr error
}

func (c *setupTransport) doEncHandshake(prv *ecdsa.PrivateKey, dialDest *ecdsa.PublicKey) (*ecdsa.PublicKey, error) {
	c.calls += "doEncHandshake,"
	return c.pubkey, c.encHandshakeErr
}

func (c *setupTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) {
	c.calls += "doProtoHandshake,"
	if c.protoHandshakeErr != nil {
		return nil, c.protoHandshakeErr
	}
	return &c.phs, nil
}
func (c *setupTransport) close(err error) {
	c.calls += "close,"
	c.closeErr = err
}

// setupConn shouldn't write to/read from the connection.
func (c *setupTransport) WriteMsg(Msg) error {
	panic("WriteMsg called on setupTransport")
}
func (c *setupTransport) ReadMsg() (Msg, error) {
	panic("ReadMsg called on setupTransport")
}

func newkey() *ecdsa.PrivateKey {
	key, err := crypto.GenerateKey()
	if err != nil {
		panic("couldn't generate key: " + err.Error())
	}
	return key
}

func randomID() (id enode.ID) {
	for i := range id {
		id[i] = byte(rand.Intn(255))
	}
	return id
}


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

namespace Logging.Services
{
	public abstract class ThreadedLogger : IDisposable
	{
		private readonly Task consumerTask;
		protected readonly LogLevel loggerLogLevel;

		private bool _isPolling;
		protected bool isPolling
		{
			get { return _isPolling; }
			private set { _isPolling = value; }
		}

		public ThreadedLogger(LogLevel level)
		{
			loggerLogLevel = level;
			isPolling = true;
			consumerTask = Task.Factory.StartNew(MessageConsumerLoop, TaskCreationOptions.LongRunning); //Creates a long running task to consumer the messages supplied to the logger. Not promised to be a new thread but it is suppose to be.
		}

		private void MessageConsumerLoop()
		{
			while(isPolling)
			{
				TryConsumeMessage(); // We don't need to check if this is returning true or false.
			}
		}

		protected abstract bool TryConsumeMessage();

		public virtual void Dispose()
		{
			isPolling = false;
			//Cannot dispose task. No way to coordinate it. Let GC handle it.
		}
	}
}


text:
import unittest

from profitbricks.client import ProfitBricksService

from .helpers import configuration

class TestContractResources(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.client = ProfitBricksService(
            username=configuration.USERNAME,
            password=configuration.PASSWORD,
            headers=configuration.HEADERS)

    def test_list_contract_resources(self):
        contracts = self.client.list_contracts()

        self.assertEqual(contracts['type'], 'contract')
        self.assertIsInstance(contracts['properties']['contractNumber'], int)

if __name__ == '__main__':
    unittest.main()


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace XPump.SubForm
{
    public partial class DialogSimpleSearch : Form
    {
        public string keyword = string.Empty;
        private CultureInfo c_info = CultureInfo.GetCultureInfo("th-TH");

        public DialogSimpleSearch(CultureInfo c_info = null)
        {
            if(c_info != null)
            {
                this.c_info = c_info;
            }
            Thread.CurrentThread.CurrentUICulture = this.c_info;
            InitializeComponent();
        }

        public DialogSimpleSearch(string search_label, string initial_keyword, CultureInfo c_info = null)
            : this(c_info)
        {
            this.lblSearchLabel.Text = search_label;
            this.txtKeyword.Text = initial_keyword;
        }

        private void txtKeyword_TextChanged(object sender, EventArgs e)
        {
            this.keyword = ((TextBox)sender).Text;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if(keyData == Keys.Enter && this.txtKeyword.Focused)
            {
                this.btnOK.PerformClick();
                return true;
            }

            if(keyData == Keys.Escape)
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }
    }
}


text:
import sys
import os
import unittest

DIR_CURRENT = os.path.abspath(os.path.dirname(__file__))
DIR_PARENT = os.path.dirname(DIR_CURRENT)

sys.path.insert(0, DIR_PARENT)

tests_loader = unittest.TestLoader()
test_suit = tests_loader.discover(DIR_CURRENT)
unittest.TextTestRunner().run(test_suit)