text:
// S. Farsiu , D. Robinson, M. Elad, P. Milanfar. Fast and robust multiframe super resolution.
// Dennis Mitzel, Thomas Pock, Thomas Schoenemann, Daniel Cremers. Video Super Resolution using Duality Based TV-L1 Optical Flow.

#include "precomp.hpp"

using namespace std;
using namespace cv;
using namespace cv::gpu;
using namespace cv::superres;
using namespace cv::superres::detail;

#if !defined(HAVE_CUDA) || !defined(HAVE_OPENCV_GPU)

Ptr<SuperResolution> cv::superres::createSuperResolution_BTVL1_GPU()
{
    CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform");
    return Ptr<SuperResolution>();
}

#else // HAVE_CUDA

namespace btv_l1_device
{
    void buildMotionMaps(PtrStepSzf forwardMotionX, PtrStepSzf forwardMotionY,
                         PtrStepSzf backwardMotionX, PtrStepSzf bacwardMotionY,
                         PtrStepSzf forwardMapX, PtrStepSzf forwardMapY,
                         PtrStepSzf backwardMapX, PtrStepSzf backwardMapY);

    template <int cn>
    void upscale(const PtrStepSzb src, PtrStepSzb dst, int scale, cudaStream_t stream);

    void diffSign(PtrStepSzf src1, PtrStepSzf src2, PtrStepSzf dst, cudaStream_t stream);

    void loadBtvWeights(const float* weights, size_t count);
    template <int cn> void calcBtvRegularization(PtrStepSzb src, PtrStepSzb dst, int ksize);
}

namespace
{
    void calcRelativeMotions(const vector<pair<GpuMat, GpuMat> >& forwardMotions, const vector<pair<GpuMat, GpuMat> >& backwardMotions,
                             vector<pair<GpuMat, GpuMat> >& relForwardMotions, vector<pair<GpuMat, GpuMat> >& relBackwardMotions,
                             int baseIdx, Size size)
    {
        const int count = static_cast<int>(forwardMotions.size());

        relForwardMotions.resize(count);
        relForwardMotions[baseIdx].first.create(size, CV_32FC1);
        relForwardMotions[baseIdx].first.setTo(Scalar::all(0));
        relForwardMotions[baseIdx].second.create(size, CV_32FC1);
        relForwardMotions[baseIdx].second.setTo(Scalar::all(0));

        relBackwardMotions.resize(count);
        relBackwardMotions[baseIdx].first.create(size, CV_32FC1);
        relBackwardMotions[baseIdx].first.setTo(Scalar::all(0));
        relBackwardMotions[baseIdx].second.create(size, CV_32FC1);
        relBackwardMotions[baseIdx].second.setTo(Scalar::all(0));

        for (int i = baseIdx - 1; i >= 0; --i)
        {
            gpu::add(relForwardMotions[i + 1].first, forwardMotions[i].first, relForwardMotions[i].first);
            gpu::add(relForwardMotions[i + 1].second, forwardMotions[i].second, relForwardMotions[i].second);

            gpu::add(relBackwardMotions[i + 1].first, backwardMotions[i + 1].first, relBackwardMotions[i].first);
            gpu::add(relBackwardMotions[i + 1].second, backwardMotions[i + 1].second, relBackwardMotions[i].second);
        }

        for (int i = baseIdx + 1; i < count; ++i)
        {
            gpu::add(relForwardMotions[i - 1].first, backwardMotions[i].first, relForwardMotions[i].first);
            gpu::add(relForwardMotions[i - 1].second, backwardMotions[i].second, relForwardMotions[i].second);

            gpu::add(relBackwardMotions[i - 1].first, forwardMotions[i - 1].first, relBackwardMotions[i].first);
            gpu::add(relBackwardMotions[i - 1].second, forwardMotions[i - 1].second, relBackwardMotions[i].second);
        }
    }

    void upscaleMotions(const vector<pair<GpuMat, GpuMat> >& lowResMotions, vector<pair<GpuMat, GpuMat> >& highResMotions, int scale)
    {
        highResMotions.resize(lowResMotions.size());

        for (size_t i = 0; i < lowResMotions.size(); ++i)
        {
            gpu::resize(lowResMotions[i].first, highResMotions[i].first, Size(), scale, scale, INTER_CUBIC);
            gpu::resize(lowResMotions[i].second, highResMotions[i].second, Size(), scale, scale, INTER_CUBIC);

            gpu::multiply(highResMotions[i].first, Scalar::all(scale), highResMotions[i].first);
            gpu::multiply(highResMotions[i].second, Scalar::all(scale), highResMotions[i].second);
        }
    }

    void buildMotionMaps(const pair<GpuMat, GpuMat>& forwardMotion, const pair<GpuMat, GpuMat>& backwardMotion,
                         pair<GpuMat, GpuMat>& forwardMap, pair<GpuMat, GpuMat>& backwardMap)
    {
        forwardMap.first.create(forwardMotion.first.size(), CV_32FC1);
        forwardMap.second.create(forwardMotion.first.size(), CV_32FC1);

        backwardMap.first.create(forwardMotion.first.size(), CV_32FC1);
        backwardMap.second.create(forwardMotion.first.size(), CV_32FC1);

        btv_l1_device::buildMotionMaps(forwardMotion.first, forwardMotion.second,
                                       backwardMotion.first, backwardMotion.second,
                                       forwardMap.first, forwardMap.second,
                                       backwardMap.first, backwardMap.second);
    }

    void upscale(const GpuMat& src, GpuMat& dst, int scale, Stream& stream)
    {
        typedef void (*func_t)(const PtrStepSzb src, PtrStepSzb dst, int scale, cudaStream_t stream);
        static const func_t funcs[] =
        {
            0, btv_l1_device::upscale<1>, 0, btv_l1_device::upscale<3>, btv_l1_device::upscale<4>
        };

        CV_Assert( src.channels() == 1 || src.channels() == 3 || src.channels() == 4 );

        dst.create(src.rows * scale, src.cols * scale, src.type());
        dst.setTo(Scalar::all(0));

        const func_t func = funcs[src.channels()];

        func(src, dst, scale, StreamAccessor::getStream(stream));
    }

    void diffSign(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream)
    {
        dst.create(src1.size(), src1.type());

        btv_l1_device::diffSign(src1.reshape(1), src2.reshape(1), dst.reshape(1), StreamAccessor::getStream(stream));
    }

    void calcBtvWeights(int btvKernelSize, double alpha, vector<float>& btvWeights)
    {
        const size_t size = btvKernelSize * btvKernelSize;

        btvWeights.resize(size);

        const int ksize = (btvKernelSize - 1) / 2;
        const float alpha_f = static_cast<float>(alpha);

        for (int m = 0, ind = 0; m <= ksize; ++m)
        {
            for (int l = ksize; l + m >= 0; --l, ++ind)
                btvWeights[ind] = pow(alpha_f, std::abs(m) + std::abs(l));
        }

        btv_l1_device::loadBtvWeights(&btvWeights[0], size);
    }

    void calcBtvRegularization(const GpuMat& src, GpuMat& dst, int btvKernelSize)
    {
        typedef void (*func_t)(PtrStepSzb src, PtrStepSzb dst, int ksize);
        static const func_t funcs[] =
        {
            0,
            btv_l1_device::calcBtvRegularization<1>,
            0,
            btv_l1_device::calcBtvRegularization<3>,
            btv_l1_device::calcBtvRegularization<4>
        };

        dst.create(src.size(), src.type());
        dst.setTo(Scalar::all(0));

        const int ksize = (btvKernelSize - 1) / 2;

        funcs[src.channels()](src, dst, ksize);
    }

    class BTVL1_GPU_Base
    {
    public:
        BTVL1_GPU_Base();

        void process(const vector<GpuMat>& src, GpuMat& dst,
                     const vector<pair<GpuMat, GpuMat> >& forwardMotions, const vector<pair<GpuMat, GpuMat> >& backwardMotions,
                     int baseIdx);

        void collectGarbage();

    protected:
        int scale_;
        int iterations_;
        double lambda_;
        double tau_;
        double alpha_;
        int btvKernelSize_;
        int blurKernelSize_;
        double blurSigma_;
        Ptr<DenseOpticalFlowExt> opticalFlow_;

    private:
        vector<Ptr<FilterEngine_GPU> > filters_;
        int curBlurKernelSize_;
        double curBlurSigma_;
        int curSrcType_;

        vector<float> btvWeights_;
        int curBtvKernelSize_;
        double curAlpha_;

        vector<pair<GpuMat, GpuMat> > lowResForwardMotions_;
        vector<pair<GpuMat, GpuMat> > lowResBackwardMotions_;

        vector<pair<GpuMat, GpuMat> > highResForwardMotions_;
        vector<pair<GpuMat, GpuMat> > highResBackwardMotions_;

        vector<pair<GpuMat, GpuMat> > forwardMaps_;
        vector<pair<GpuMat, GpuMat> > backwardMaps_;

        GpuMat highRes_;

        vector<Stream> streams_;
        vector<GpuMat> diffTerms_;
        vector<GpuMat> a_, b_, c_;
        GpuMat regTerm_;
    };

    BTVL1_GPU_Base::BTVL1_GPU_Base()
    {
        scale_ = 4;
        iterations_ = 180;
        lambda_ = 0.03;
        tau_ = 1.3;
        alpha_ = 0.7;
        btvKernelSize_ = 7;
        blurKernelSize_ = 5;
        blurSigma_ = 0.0;
        opticalFlow_ = createOptFlow_Farneback_GPU();

        curBlurKernelSize_ = -1;
        curBlurSigma_ = -1.0;
        curSrcType_ = -1;

        curBtvKernelSize_ = -1;
        curAlpha_ = -1.0;
    }

    void BTVL1_GPU_Base::process(const vector<GpuMat>& src, GpuMat& dst,
                                 const vector<pair<GpuMat, GpuMat> >& forwardMotions, const vector<pair<GpuMat, GpuMat> >& backwardMotions,
                                 int baseIdx)
    {
        CV_Assert( scale_ > 1 );
        CV_Assert( iterations_ > 0 );
        CV_Assert( tau_ > 0.0 );
        CV_Assert( alpha_ > 0.0 );
        CV_Assert( btvKernelSize_ > 0 && btvKernelSize_ <= 16 );
        CV_Assert( blurKernelSize_ > 0 );
        CV_Assert( blurSigma_ >= 0.0 );

        // update blur filter and btv weights

        if (filters_.size() != src.size() || blurKernelSize_ != curBlurKernelSize_ || blurSigma_ != curBlurSigma_ || src[0].type() != curSrcType_)
        {
            filters_.resize(src.size());
            for (size_t i = 0; i < src.size(); ++i)
                filters_[i] = createGaussianFilter_GPU(src[0].type(), Size(blurKernelSize_, blurKernelSize_), blurSigma_);
            curBlurKernelSize_ = blurKernelSize_;
            curBlurSigma_ = blurSigma_;
            curSrcType_ = src[0].type();
        }

        if (btvWeights_.empty() || btvKernelSize_ != curBtvKernelSize_ || alpha_ != curAlpha_)
        {
            calcBtvWeights(btvKernelSize_, alpha_, btvWeights_);
            curBtvKernelSize_ = btvKernelSize_;
            curAlpha_ = alpha_;
        }

        // calc motions between input frames

        calcRelativeMotions(forwardMotions, backwardMotions, lowResForwardMotions_, lowResBackwardMotions_, baseIdx, src[0].size());

        upscaleMotions(lowResForwardMotions_, highResForwardMotions_, scale_);
        upscaleMotions(lowResBackwardMotions_, highResBackwardMotions_, scale_);

        forwardMaps_.resize(highResForwardMotions_.size());
        backwardMaps_.resize(highResForwardMotions_.size());
        for (size_t i = 0; i < highResForwardMotions_.size(); ++i)
            buildMotionMaps(highResForwardMotions_[i], highResBackwardMotions_[i], forwardMaps_[i], backwardMaps_[i]);

        // initial estimation

        const Size lowResSize = src[0].size();
        const Size highResSize(lowResSize.width * scale_, lowResSize.height * scale_);

        gpu::resize(src[baseIdx], highRes_, highResSize, 0, 0, INTER_CUBIC);

        // iterations

        streams_.resize(src.size());
        diffTerms_.resize(src.size());
        a_.resize(src.size());
        b_.resize(src.size());
        c_.resize(src.size());

        for (int i = 0; i < iterations_; ++i)
        {
            for (size_t k = 0; k < src.size(); ++k)
            {
                // a = M * Ih
                gpu::remap(highRes_, a_[k], backwardMaps_[k].first, backwardMaps_[k].second, INTER_NEAREST, BORDER_REPLICATE, Scalar(), streams_[k]);
                // b = HM * Ih
                filters_[k]->apply(a_[k], b_[k], Rect(0,0,-1,-1), streams_[k]);
                // c = DHF * Ih
                gpu::resize(b_[k], c_[k], lowResSize, 0, 0, INTER_NEAREST, streams_[k]);

                diffSign(src[k], c_[k], c_[k], streams_[k]);

                // a = Dt * diff
                upscale(c_[k], a_[k], scale_, streams_[k]);
                // b = HtDt * diff
                filters_[k]->apply(a_[k], b_[k], Rect(0,0,-1,-1), streams_[k]);
                // diffTerm = MtHtDt * diff
                gpu::remap(b_[k], diffTerms_[k], forwardMaps_[k].first, forwardMaps_[k].second, INTER_NEAREST, BORDER_REPLICATE, Scalar(), streams_[k]);
            }

            if (lambda_ > 0)
            {
                calcBtvRegularization(highRes_, regTerm_, btvKernelSize_);
                gpu::addWeighted(highRes_, 1.0, regTerm_, -tau_ * lambda_, 0.0, highRes_);
            }

            for (size_t k = 0; k < src.size(); ++k)
            {
                streams_[k].waitForCompletion();
                gpu::addWeighted(highRes_, 1.0, diffTerms_[k], tau_, 0.0, highRes_);
            }
        }

        Rect inner(btvKernelSize_, btvKernelSize_, highRes_.cols - 2 * btvKernelSize_, highRes_.rows - 2 * btvKernelSize_);
        highRes_(inner).copyTo(dst);
    }

    void BTVL1_GPU_Base::collectGarbage()
    {
        filters_.clear();

        lowResForwardMotions_.clear();
        lowResBackwardMotions_.clear();

        highResForwardMotions_.clear();
        highResBackwardMotions_.clear();

        forwardMaps_.clear();
        backwardMaps_.clear();

        highRes_.release();

        diffTerms_.clear();
        a_.clear();
        b_.clear();
        c_.clear();
        regTerm_.release();
    }

////////////////////////////////////////////////////////////

    class BTVL1_GPU : public SuperResolution, private BTVL1_GPU_Base
    {
    public:
        AlgorithmInfo* info() const;

        BTVL1_GPU();

        void collectGarbage();

    protected:
        void initImpl(Ptr<FrameSource>& frameSource);
        void processImpl(Ptr<FrameSource>& frameSource, OutputArray output);

    private:
        int temporalAreaRadius_;

        void readNextFrame(Ptr<FrameSource>& frameSource);
        void processFrame(int idx);

        GpuMat curFrame_;
        GpuMat prevFrame_;

        vector<GpuMat> frames_;
        vector<pair<GpuMat, GpuMat> > forwardMotions_;
        vector<pair<GpuMat, GpuMat> > backwardMotions_;
        vector<GpuMat> outputs_;

        int storePos_;
        int procPos_;
        int outPos_;

        vector<GpuMat> srcFrames_;
        vector<pair<GpuMat, GpuMat> > srcForwardMotions_;
        vector<pair<GpuMat, GpuMat> > srcBackwardMotions_;
        GpuMat finalOutput_;
    };

    CV_INIT_ALGORITHM(BTVL1_GPU, "SuperResolution.BTVL1_GPU",
                      obj.info()->addParam(obj, "scale", obj.scale_, false, 0, 0, "Scale factor.");
                      obj.info()->addParam(obj, "iterations", obj.iterations_, false, 0, 0, "Iteration count.");
                      obj.info()->addParam(obj, "tau", obj.tau_, false, 0, 0, "Asymptotic value of steepest descent method.");
                      obj.info()->addParam(obj, "lambda", obj.lambda_, false, 0, 0, "Weight parameter to balance data term and smoothness term.");
                      obj.info()->addParam(obj, "alpha", obj.alpha_, false, 0, 0, "Parameter of spacial distribution in Bilateral-TV.");
                      obj.info()->addParam(obj, "btvKernelSize", obj.btvKernelSize_, false, 0, 0, "Kernel size of Bilateral-TV filter.");
                      obj.info()->addParam(obj, "blurKernelSize", obj.blurKernelSize_, false, 0, 0, "Gaussian blur kernel size.");
                      obj.info()->addParam(obj, "blurSigma", obj.blurSigma_, false, 0, 0, "Gaussian blur sigma.");
                      obj.info()->addParam(obj, "temporalAreaRadius", obj.temporalAreaRadius_, false, 0, 0, "Radius of the temporal search area.");
                      obj.info()->addParam<DenseOpticalFlowExt>(obj, "opticalFlow", obj.opticalFlow_, false, 0, 0, "Dense optical flow algorithm."));

    BTVL1_GPU::BTVL1_GPU()
    {
        temporalAreaRadius_ = 4;
    }

    void BTVL1_GPU::collectGarbage()
    {
        curFrame_.release();
        prevFrame_.release();

        frames_.clear();
        forwardMotions_.clear();
        backwardMotions_.clear();
        outputs_.clear();

        srcFrames_.clear();
        srcForwardMotions_.clear();
        srcBackwardMotions_.clear();
        finalOutput_.release();

        SuperResolution::collectGarbage();
        BTVL1_GPU_Base::collectGarbage();
    }

    void BTVL1_GPU::initImpl(Ptr<FrameSource>& frameSource)
    {
        const int cacheSize = 2 * temporalAreaRadius_ + 1;

        frames_.resize(cacheSize);
        forwardMotions_.resize(cacheSize);
        backwardMotions_.resize(cacheSize);
        outputs_.resize(cacheSize);

        storePos_ = -1;

        for (int t = -temporalAreaRadius_; t <= temporalAreaRadius_; ++t)
            readNextFrame(frameSource);

        for (int i = 0; i <= temporalAreaRadius_; ++i)
            processFrame(i);

        procPos_ = temporalAreaRadius_;
        outPos_ = -1;
    }

    void BTVL1_GPU::processImpl(Ptr<FrameSource>& frameSource, OutputArray _output)
    {
        if (outPos_ >= storePos_)
        {
            _output.release();
            return;
        }

        readNextFrame(frameSource);

        if (procPos_ < storePos_)
        {
            ++procPos_;
            processFrame(procPos_);
        }

        ++outPos_;
        const GpuMat& curOutput = at(outPos_, outputs_);

        if (_output.kind() == _InputArray::GPU_MAT)
            curOutput.convertTo(_output.getGpuMatRef(), CV_8U);
        else
        {
            curOutput.convertTo(finalOutput_, CV_8U);
            arrCopy(finalOutput_, _output);
        }
    }

    void BTVL1_GPU::readNextFrame(Ptr<FrameSource>& frameSource)
    {
        frameSource->nextFrame(curFrame_);

        if (curFrame_.empty())
            return;

        ++storePos_;
        curFrame_.convertTo(at(storePos_, frames_), CV_32F);

        if (storePos_ > 0)
        {
            pair<GpuMat, GpuMat>& forwardMotion = at(storePos_ - 1, forwardMotions_);
            pair<GpuMat, GpuMat>& backwardMotion = at(storePos_, backwardMotions_);

            opticalFlow_->calc(prevFrame_, curFrame_, forwardMotion.first, forwardMotion.second);
            opticalFlow_->calc(curFrame_, prevFrame_, backwardMotion.first, backwardMotion.second);
        }

        curFrame_.copyTo(prevFrame_);
    }

    void BTVL1_GPU::processFrame(int idx)
    {
        const int startIdx = max(idx - temporalAreaRadius_, 0);
        const int procIdx = idx;
        const int endIdx = min(startIdx + 2 * temporalAreaRadius_, storePos_);

        const int count = endIdx - startIdx + 1;

        srcFrames_.resize(count);
        srcForwardMotions_.resize(count);
        srcBackwardMotions_.resize(count);

        int baseIdx = -1;

        for (int i = startIdx, k = 0; i <= endIdx; ++i, ++k)
        {
            if (i == procIdx)
                baseIdx = k;

            srcFrames_[k] = at(i, frames_);

            if (i < endIdx)
                srcForwardMotions_[k] = at(i, forwardMotions_);
            if (i > startIdx)
                srcBackwardMotions_[k] = at(i, backwardMotions_);
        }

        process(srcFrames_, at(idx, outputs_), srcForwardMotions_, srcBackwardMotions_, baseIdx);
    }
}

Ptr<SuperResolution> cv::superres::createSuperResolution_BTVL1_GPU()
{
    return new BTVL1_GPU;
}

#endif // HAVE_CUDA


text:
# Billing

> see https://aka.ms/autorest

This is the AutoRest configuration file for Billing.

---
## Getting Started
To build the SDK for Billing, simply [Install AutoRest](https://aka.ms/autorest/install) and in this folder, run:

> `autorest`

To see additional help and options, run:

> `autorest --help`
---

## Configuration

### Basic Information
These are the global settings for the Billing API.

``` yaml
openapi-type: arm
tag: package-2020-05
```

### Tag: package-2020-05

These settings apply only when `--tag=package-2020-05` is specified on the command line.

``` yaml $(tag) == 'package-2020-05'
input-file:
- Microsoft.Billing/stable/2020-05-01/billing.json
```

### Tag: package-2019-10-preview

These settings apply only when `--tag=package-2019-10-preview` is specified on the command line.

``` yaml $(tag) == 'package-2019-10-preview'
input-file:
- Microsoft.Billing/preview/2019-10-01-preview/billing.json
```

### Tag: package-2018-11-preview

These settings apply only when `--tag=package-2018-11-preview` is specified on the command line.

``` yaml $(tag) == 'package-2018-11-preview'
input-file:
- Microsoft.Billing/preview/2018-11-01-preview/billing.json
```

### Tag: package-2018-03-preview

These settings apply only when `--tag=package-2018-03-preview` is specified on the command line.

``` yaml $(tag) == 'package-2018-03-preview'
input-file:
- Microsoft.Billing/preview/2018-03-01-preview/billing.json
```

### Tag: package-2017-04-preview

These settings apply only when `--tag=package-2017-04-preview` is specified on the command line.

``` yaml $(tag) == 'package-2017-04-preview'
input-file:
- Microsoft.Billing/preview/2017-04-24-preview/billing.json
```

### Tag: package-2017-02-preview

These settings apply only when `--tag=package-2017-02-preview` is specified on the command line.

``` yaml $(tag) == 'package-2017-02-preview'
input-file:
- Microsoft.Billing/preview/2017-02-27-preview/billing.json
```

---
# Code Generation

## Swagger to SDK

This section describes what SDK should be generated by the automatic system.
This is not used by Autorest itself.

``` yaml $(swagger-to-sdk)
swagger-to-sdk:
  - repo: azure-sdk-for-net
  - repo: azure-sdk-for-python
  - repo: azure-sdk-for-java
  - repo: azure-sdk-for-go
  - repo: azure-sdk-for-js
  - repo: azure-sdk-for-node
  - repo: azure-sdk-for-ruby
    after_scripts:
      - bundle install && rake arm:regen_all_profiles['azure_mgmt_billing']
```

## C#

These settings apply only when `--csharp` is specified on the command line.
Please also specify `--csharp-sdks-folder=<path to "SDKs" directory of your azure-sdk-for-net clone>`.

``` yaml $(csharp)
csharp:
  azure-arm: true
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: Microsoft.Azure.Management.Billing
  output-folder: $(csharp-sdks-folder)/billing/Microsoft.Azure.Management.Billing/src/Generated
  clear-output-folder: true
```

## Go

See configuration in [readme.go.md](./readme.go.md)

## Java

These settings apply only when `--java` is specified on the command line.
Please also specify `--azure-libraries-for-java-folder=<path to the root directory of your azure-libraries-for-java clone>`.

``` yaml $(java)
azure-arm: true
fluent: true
namespace: com.microsoft.azure.management.billing
license-header: MICROSOFT_MIT_NO_CODEGEN
payload-flattening-threshold: 1
output-folder: $(azure-libraries-for-java-folder)/azure-mgmt-billing
```

### Java multi-api

``` yaml $(java) && $(multiapi)
batch:
  - tag: package-2020-05
  - tag: package-2019-10-preview
  - tag: package-2018-11-preview
  - tag: package-2018-03-preview
  - tag: package-2017-04-preview
  - tag: package-2017-02-preview
```

### Tag: package-2020-05 and java

These settings apply only when `--tag=package-2020-05 --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2020-05' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.billing.v2020_05_01
  output-folder: $(azure-libraries-for-java-folder)/sdk/billing/mgmt-v2020_05_01
regenerate-manager: true
generate-interface: true
```

### Tag: package-2019-10-preview and java

These settings apply only when `--tag=package-2019-10-preview --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2019-10-preview' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.billing.v2019_10_01_preview
  output-folder: $(azure-libraries-for-java-folder)/sdk/billing/mgmt-v2019_10_01_preview
regenerate-manager: true
generate-interface: true
```

### Tag: package-2018-11-preview and java

These settings apply only when `--tag=package-2018-11-preview --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2018-11-preview' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.billing.v2018_11_01_preview
  output-folder: $(azure-libraries-for-java-folder)/sdk/billing/mgmt-v2018_11_01_preview
regenerate-manager: true
generate-interface: true
```

### Tag: package-2018-03-preview and java

These settings apply only when `--tag=package-2018-03-preview --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2018-03-preview' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.billing.v2018_03_01_preview
  output-folder: $(azure-libraries-for-java-folder)/sdk/billing/mgmt-v2018_03_01_preview
regenerate-manager: true
generate-interface: true
```

### Tag: package-2017-04-preview and java

These settings apply only when `--tag=package-2017-04-preview --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-04-preview' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.billing.v2017_04_24_preview
  output-folder: $(azure-libraries-for-java-folder)/sdk/billing/mgmt-v2017_04_24_preview
regenerate-manager: true
generate-interface: true
```

### Tag: package-2017-02-preview and java

These settings apply only when `--tag=package-2017-02-preview --java` is specified on the command line.
Please also specify `--azure-libraries-for-java=<path to the root directory of your azure-sdk-for-java clone>`.

``` yaml $(tag) == 'package-2017-02-preview' && $(java) && $(multiapi)
java:
  namespace: com.microsoft.azure.management.billing.v2017_02_27_preview
  output-folder: $(azure-libraries-for-java-folder)/sdk/billing/mgmt-v2017_02_27_preview
regenerate-manager: true
generate-interface: true
```

## Multi-API/Profile support for AutoRest v3 generators

AutoRest V3 generators require the use of `--tag=all-api-versions` to select api files.

This block is updated by an automatic script. Edits may be lost!

``` yaml $(tag) == 'all-api-versions' /* autogenerated */
# include the azure profile definitions from the standard location
require: $(this-folder)/../../../profiles/readme.md

# all the input files across all versions
input-file:
  - $(this-folder)/Microsoft.Billing/stable/2020-05-01/billing.json
  - $(this-folder)/Microsoft.Billing/preview/2019-10-01-preview/billing.json
  - $(this-folder)/Microsoft.Billing/preview/2018-11-01-preview/billing.json
  - $(this-folder)/Microsoft.Billing/preview/2018-03-01-preview/billing.json
  - $(this-folder)/Microsoft.Billing/preview/2017-04-24-preview/billing.json
  - $(this-folder)/Microsoft.Billing/preview/2017-02-27-preview/billing.json

```

If there are files that should not be in the `all-api-versions` set,
uncomment the  `exclude-file` section below and add the file paths.

``` yaml $(tag) == 'all-api-versions'
#exclude-file:
#  - $(this-folder)/Microsoft.Example/stable/2010-01-01/somefile.json
```

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe GitlabShellWorker do
  let(:worker) { described_class.new }

  describe '#perform with add_key' do
    it 'calls add_key on Gitlab::Shell' do
      expect_any_instance_of(Gitlab::Shell).to receive(:add_key).with('foo', 'bar')
      worker.perform(:add_key, 'foo', 'bar')
    end
  end
end


text:
<?php
/**
 * <select> <option></option> </select>
 * @author m.augustynowicz
 * @author m.jutkiewicz (fix for multiple select box)
 *
 * (params passed as local variables)
 * @param string $id uniqe id
 * @param array $values REQUIRED!
 * @param string $empty_value_label if given, adds extra, empty value at the beginning
 * @param array $attrs
 * @param boolean $disabled
 * @param string $class
 * @param boolean $err_handling add div.field error, bind events (if $ajax)
 * @param string $name_suffix e.g. "[en]" (note that name has to have
 *        arrayish value, use at your own risk)
 * @param string $name_suffix e.g. "[42][]" (note that name has to have
 *        arrayish value, use at your own risk)
 */
if(!$____local_variables['values'])
{
    g()->debug->addInfo(null, 'No values passed to FSelect (%s, %s::%s)', $this->path(), $ident, $input);
}
extract(array_merge(array(
    'id' => null,
    'values' => array(),
    'empty_value_label' => null,
    'attrs' => array(),
    'disabled' => false,
    'class' => '', // overrides attrs[class] !
    'err_handling' => true,
    'name_prefix' => '',
    'name_suffix' => ''
), (array)$____local_variables));
if($disabled)
    $attrs['disabled'] = 'disabled';
@$attrs['class'] .= ' hg ' . $class;
$attrs['id'] = $id;
$attrs['name'] = $ident . $name_prefix . '[' . $input . ']' . $name_suffix;

$attrs_html = $f->xmlAttr($attrs);
if(isset($select_array))
{
    g()->debug->addInfo('deprecated select_array', '$select_array variable has been assigned, but FSelect now accepts only local variable $values');
}
?>

<select <?= $attrs_html; ?>>
    <?php
    if($empty_value_label !== null)
    {
    ?>
    <option class="empty" value=""><?=$empty_value_label?></option>
    <?php
    }
    foreach($values as $value => $name)
    {
    ?>
    <option value="<?= $value; ?>"
	<?
        if(isset($data) && !is_array($data))
        {
            if((string)$value === (string)$data)
                echo 'selected="selected"';
        }
        else
        {
            if((string)$value === (string)@$data[$value])
                echo 'selected="selected"';
        }
    ?>><?= $name; ?></option>
    <?php
    }
    ?>
</select>

<?php
$t->inc('Forms/errors', compact('id', 'ajax', 'err_handling', 'errors'));
return $attrs;


text:
package com.github.jlgrock.javascriptframework.jsdependency;

import java.io.File;
import java.io.IOException;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;

import com.github.jlgrock.javascriptframework.mavenutils.io.DirectoryIO;
import com.github.jlgrock.javascriptframework.mavenutils.io.ResourceIO;
import com.github.jlgrock.javascriptframework.mavenutils.io.ZipUtils;
import com.github.jlgrock.javascriptframework.mavenutils.logging.MojoLogAppender;
import com.github.jlgrock.javascriptframework.mavenutils.mavenobjects.ArtifactExtractor;
import com.github.jlgrock.javascriptframework.mavenutils.mavenobjects.JsarRelativeLocations;
import com.github.jlgrock.javascriptframework.mavenutils.mavenobjects.PackagingType;
import com.github.jlgrock.javascriptframework.mavenutils.mavenobjects.ScopeType;

/**
 * The Abstract instance of all of the dependecy mojo implementations. This
 * gives common functions for retrieving dependencies for each different type.
 *
 */
public abstract class AbstractDependencyMojo extends AbstractMojo {

	/**
	 * The name of the current closure library - this is updated regularly.
	 */
	public static final String CLOSURE_LIBRARY_NAME = "closure-library-99cd91";

	/**
	 * @return the current maven project
	 */
	public abstract MavenProject getProject();

	/**
	 * If you are using a local version of the library, you can skip the google
	 * library extraction.
	 *
	 * @parameter default-value="false"
	 */
	private boolean skipGoogleExtraction;

	/**
	 * @return the skipExtraction
	 */
	public final boolean isSkipGoogleExtraction() {
		return skipGoogleExtraction;
	}

	/**
	 * The Logger.
	 */
	private static final Logger LOGGER = Logger
			.getLogger(AbstractDependencyMojo.class);

	/**
	 * The default directory to extract dependency files marked with classifier
	 * of "external". This likely shouldn't be changed unless there is a
	 * conflict with another plugin.
	 *
	 * @parameter default-value=
	 *            "${project.build.directory}${file.separator}javascriptFramework"
	 */
	private File closureExtractLibDirectory;

	/**
	 * @return the closureExtractLibDirectory
	 */
	public final File getClosureExtractLibDirectory() {
		return closureExtractLibDirectory;
	}

	@Override
	public final void execute() throws MojoExecutionException,
			MojoFailureException {
		MojoLogAppender.beginLogging(this);
		try {
			LOGGER.info("Creating output directory at location \""
					+ getFrameworkTargetDirectory().getAbsolutePath() + "\".");
			DirectoryIO
					.createDir(getFrameworkTargetDirectory().getParentFile());

			extractDependencies();

		} catch (Exception e) {
			throw new MojoExecutionException(
					"Unable to access artifact dependency object: "
							+ e.getMessage());
		} finally {
			MojoLogAppender.endLogging();
		}
	}

	/**
	 * Extract the dependencies from the jsar to the appropriate location(s).
	 *
	 * @throws IOException
	 *             if there is a problem reading the artifact
	 * @throws MojoFailureException
	 *             from any Mojo API specific calls
	 * @throws MojoExecutionException
	 *             from any Mojo API specific calls
	 */
	protected abstract void extractDependencies() throws IOException,
			MojoFailureException, MojoExecutionException;

	/**
	 * Extracts the closure library and renames it to a standard so that it can be referenced
	 * at a later point.
	 * @throws IOException if there is a problem reading the artifact
	 */
	protected final void extractAndRenameLibrary() throws IOException {
		String zipName = AbstractDependencyMojo.CLOSURE_LIBRARY_NAME + ".zip";
		File libFile = new File(getFrameworkTargetDirectory(), AbstractDependencyMojo.CLOSURE_LIBRARY_NAME);
		File stdFile = new File(getFrameworkTargetDirectory(), "closure-library");

		LOGGER.info("Extracting google closure library to location \""
				+ getFrameworkTargetDirectory().getAbsolutePath() + "\"");
		FileUtils.deleteDirectory(libFile);
		FileUtils.deleteDirectory(stdFile);

		ZipUtils.unzip(
				ResourceIO.getResourceAsZipStream(zipName),
				getFrameworkTargetDirectory());
		FileUtils.rename(libFile, stdFile);
	}

	/**
	 * Extract the interns (assert/debug) files from the package.
	 *
	 * @param extractAssert
	 *            whether to extract assert files
	 * @throws IOException
	 *             if unable to write files
	 * @throws MojoFailureException
	 *             from any Mojo API specific calls
	 * @throws MojoExecutionException
	 *             from any Mojo API specific calls
	 */
	protected final void extractInterns(final boolean extractAssert) throws IOException,
			MojoFailureException, MojoExecutionException {

		@SuppressWarnings("unchecked")
		Set<Artifact> artifactSet = (Set<Artifact>) getProject().getArtifacts();
		ArtifactExtractor extractJSArtifacts = new ArtifactExtractor(
				artifactSet);

		// extract internal assert dependencies
		if (extractAssert) {
			File assertLocation = JsarRelativeLocations
					.getInternsAssertLocation(getFrameworkTargetDirectory());
			LOGGER.info("Extracting internal assert dependencies to location \""
					+ assertLocation.getAbsolutePath()
					+ File.separator
					+ JsarRelativeLocations.JSAR_ASSERTION_SOURCE_LOCATION
					+ "\"");
			extractJSArtifacts.extract(
					JsarRelativeLocations.JSAR_ASSERTION_SOURCE_LOCATION + "/",
					PackagingType.JSAR, ScopeType.COMPILE, assertLocation);
		}

		// extract internal debug dependencies
		File debugLocation = JsarRelativeLocations
				.getInternsDebugLocation(getFrameworkTargetDirectory());
		LOGGER.info("Extracting internal debug dependencies to location \""

		+ debugLocation.getAbsolutePath() + File.separator
				+ JsarRelativeLocations.JSAR_PROCESSED_SOURCE_LOCATION
				+ "\"");
		extractJSArtifacts.extract(
				JsarRelativeLocations.JSAR_PROCESSED_SOURCE_LOCATION + "/",
				PackagingType.JSAR, ScopeType.COMPILE, debugLocation);
	}

	/**
	 * Extract the externs from the package.
	 *
	 * @param artifactSet
	 *            the set to extract
	 * @throws IOException
	 *             if unable to write files
	 * @throws MojoFailureException
	 *             from any Mojo API specific calls
	 * @throws MojoExecutionException
	 *             from any Mojo API specific calls
	 */
	protected final void extractExterns(final Set<Artifact> artifactSet)
			throws IOException, MojoFailureException, MojoExecutionException {
		ArtifactExtractor extractJSArtifacts = new ArtifactExtractor(
				artifactSet);
		File location = JsarRelativeLocations
				.getExternsLocation(getFrameworkTargetDirectory());

		// extract extern files
		LOGGER.info("Extracting external dependencies to location \""
				+ location.getAbsolutePath() + "\"");
		extractJSArtifacts.extract(JsarRelativeLocations.JSAR_EXTERN_LOCATION
				+ "/", PackagingType.JSAR, ScopeType.COMPILE, location);
	}

	/**
	 * @return frameworkTargetDirectory
	 */
	public abstract File getFrameworkTargetDirectory();
}


text:
/**
 * Internal events passed between components
 */
package com.cisco.qte.jdtn.events;


text:
import 'mocha';
import { Calendar, CalendarEvent } from '../calendar';

describe('Calendar', () => {
    beforeEach(() => {

    });
});

describe('CalendarEvent', () => {

});


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

internal static partial class Interop
{
    internal static partial class OpenSsl
    {
        private static Version s_opensslVersion;

        [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_OpenSslVersionNumber")]
        internal static extern uint OpenSslVersionNumber();

        internal static Version OpenSslVersion
        {
            get
            {
                if (s_opensslVersion == null)
                {
                    uint versionNumber = OpenSslVersionNumber();
                    s_opensslVersion = new Version((int)(versionNumber >> 28), (int)((versionNumber >> 20) & 0xff), (int)((versionNumber >> 12) & 0xff));
                }

                return s_opensslVersion;
            }
        }
    }
}


text:
/**
 *
 */
package com.kancolle.server.model.po.furniture;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.kancolle.server.utils.jackson.NumericBooleanSerializer;
import org.apache.ibatis.type.Alias;

import java.io.Serializable;

/**
 * @author J.K.SAGE
 * @Date 2015年6月10日
 */
@JsonPropertyOrder(value = {
        "furnitureId", "type", "no", "title",
        "description", "rarity", "price", "saleFlag",
        "season"
})
@Alias("Furniture")
public class Furniture implements Serializable {

    private static final long serialVersionUID = -6302293499953139928L;

    @JsonProperty(value = "api_id")
    @JSONField(ordinal = 1, name = "api_id")
    private int furnitureId;

    @JsonProperty(value = "api_type")
    @JSONField(ordinal = 2, name = "api_type")
    private int type;

    @JsonProperty(value = "api_no")
    @JSONField(ordinal = 3, name = "api_no")
    private int no;

    @JsonProperty(value = "api_title")
    @JSONField(ordinal = 4, name = "api_title")
    private String title;

    @JsonProperty(value = "api_description")
    @JSONField(ordinal = 5, name = "api_description")
    private String description;

    @JsonProperty(value = "api_rarity")
    @JSONField(ordinal = 6, name = "api_rarity")
    private int rarity;

    @JsonProperty(value = "api_price")
    @JSONField(ordinal = 7, name = "api_price")
    private int price;

    @JsonProperty(value = "api_saleflg")
    @JsonSerialize(using = NumericBooleanSerializer.class)
    private boolean saleFlag;

    @JsonProperty(value = "api_season")
    @JSONField(ordinal = 9, name = "api_season")
    private int season;

    public int getFurnitureId() {
        return furnitureId;
    }

    public void setFurnitureId(int furnitureId) {
        this.furnitureId = furnitureId;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getRarity() {
        return rarity;
    }

    public void setRarity(int rarity) {
        this.rarity = rarity;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public boolean isSaleFlag() {
        return saleFlag;
    }

    public void setSaleFlag(boolean saleFlag) {
        this.saleFlag = saleFlag;
    }

    public int getSeason() {
        return season;
    }

    public void setSeason(int season) {
        this.season = season;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + furnitureId;
        result = prime * result + no;
        result = prime * result + price;
        result = prime * result + rarity;
        result = prime * result + (saleFlag ? 1231 : 1237);
        result = prime * result + season;
        result = prime * result + type;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Furniture other = (Furniture) obj;
        if (furnitureId != other.furnitureId)
            return false;
        if (no != other.no)
            return false;
        if (price != other.price)
            return false;
        if (rarity != other.rarity)
            return false;
        if (saleFlag != other.saleFlag)
            return false;
        if (season != other.season)
            return false;
        if (type != other.type)
            return false;
        return true;
    }

    @Override
    public String toString() {
        return String.format("Furniture [title=%s]", title);
    }
}


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

namespace Sunfish
{
    public partial class TagListView : ListView, INotifyPropertyChanged
    {
        public TagListView()
        {
            InitializeComponent();
        }

        public new View View
        {
            get { return base.View; }
            set
            {
                if (base.View != value)
                {
                    base.View = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(View)));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}


text:
package org.apache.abdera.parser.stax;

import java.util.List;

import javax.xml.namespace.QName;

import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Collection;
import org.apache.abdera.model.Service;
import org.apache.abdera.model.Workspace;
import org.apache.abdera.util.Constants;
import org.apache.axiom.om.OMContainer;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMXMLParserWrapper;

public class FOMService
  extends FOMExtensibleElement
  implements Service {

  private static final long serialVersionUID = 7982751563668891240L;

  public FOMService() {
    super(Constants.SERVICE, new FOMDocument(), (OMFactory)Factory.INSTANCE);
  }

  public FOMService(
    String name,
    OMNamespace namespace,
    OMContainer parent,
    OMFactory factory)
      throws OMException {
    super(name, namespace, parent, factory);
  }

  public FOMService(
    QName qname,
    OMContainer parent,
    OMFactory factory) {
      super(qname, parent, factory);
  }

  public FOMService(
    QName qname,
    OMContainer parent,
    OMFactory factory,
    OMXMLParserWrapper builder) {
      super(qname, parent, factory, builder);
  }

  public FOMService(
    OMContainer parent,
    OMFactory factory)
      throws OMException {
    super(SERVICE, parent, factory);
  }

  public FOMService(
    OMContainer parent,
    OMFactory factory,
    OMXMLParserWrapper builder)
      throws OMException {
    super(SERVICE, parent, factory, builder);
  }

  public List<Workspace> getWorkspaces() {
    return _getChildrenAsSet(WORKSPACE);
  }

  public Workspace getWorkspace(String title) {
    List<Workspace> workspaces = getWorkspaces();
    Workspace workspace = null;
    for (Workspace w : workspaces) {
      if (w.getTitle().equals(title)) {
        workspace = w;
        break;
      }
    }
    return workspace;
  }

  public void addWorkspace(Workspace workspace) {
    addChild((OMElement) workspace);
  }

  public Workspace addWorkspace(String title) {
    FOMFactory fomfactory = (FOMFactory) factory;
    Workspace workspace = fomfactory.newWorkspace(this);
    workspace.setTitle(title);
    return workspace;
  }

  public Collection getCollection(String workspace, String collection) {
    Collection col = null;
    Workspace w = getWorkspace(workspace);
    if (w != null) {
      col = w.getCollection(collection);
    }
    return col;
  }

}


text:
// ReSharper disable All

namespace OpenTl.Schema.Account
{
	using System;
	using System.Collections;
	using System.Text;

	using OpenTl.Schema;
	using OpenTl.Schema.Serialization.Attributes;

	[Serialize(0xecba39db)]
    public sealed class RequestVerifyEmail : IRequest<bool>
    {
       /// Binary representation for the 'Email' property
       [SerializationOrder(0)]
       public byte[] EmailAsBinary { get => _EmailAsBinary; set { _Email = Encoding.UTF8.GetString(value); _EmailAsBinary = value; }}
       private byte[] _EmailAsBinary;
       private string _Email;
       public string Email { get => _Email; set { EmailAsBinary = Encoding.UTF8.GetBytes(value); _Email = value; }}

       /// Binary representation for the 'Code' property
       [SerializationOrder(1)]
       public byte[] CodeAsBinary { get => _CodeAsBinary; set { _Code = Encoding.UTF8.GetString(value); _CodeAsBinary = value; }}
       private byte[] _CodeAsBinary;
       private string _Code;
       public string Code { get => _Code; set { CodeAsBinary = Encoding.UTF8.GetBytes(value); _Code = value; }}

    }
}


text:
import {Emitter} from './Emitter'
import {Destroy} from './Destroy'
import {Data} from './Data'

export function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        })
    });
}

export class Entity implements Emitter, Destroy, Data {
    private _id: string
    protected _saveData: Object
    protected _tempData: Object
    constructor(id) {
        this._id = id;
    }
    get id() {
        return this._id
    }
    toJSON() {
        return this._saveData;
    }
    clone() {
        var data = this.toJSON()
        return new Entity(data)
    }
    // emitter
    events = {}
    emit: (type: string, ...arg: any[]) => void
    on: () => void
    off: () => void
    once: () => void
    // disposeable
    isDestroy = false
    destroy: () => void
    // save
    saveData = {}
    tempData = {}
    save: () => boolean
    load: () => boolean
    setValue: (key: string, value: any) => void
    getValue: (key: string) => any
    setTempValue: (key: string, value: any) => void
    getTempValue: (key: string) => any
}

applyMixins(Entity, [Emitter, Destroy, Data])


text:
using System.Collections.Generic;

namespace Microsoft.SourceBrowser.SourceIndexServer
{
    public class SymbolKindText
    {
        public const string Assembly = "assembly";
        public const string Type = "type";
        public const string Class = "class";
        public const string Struct = "struct";
        public const string Interface = "interface";
        public const string Enum = "enum";
        public const string Delegate = "delegate";
        public const string Method = "method";
        public const string Property = "property";
        public const string Event = "event";
        public const string Field = "field";
        public const string File = "file";
        public const string MSBuildProperty = "MSBuildProperty";
        public const string MSBuildItem = "MSBuildItem";
        public const string MSBuildTarget = "MSBuildTarget";
        public const string MSBuildTask = "MSBuildTask";
        public const string Default = "symbol";

        public static readonly string[] Kinds =
        {
            Assembly,
            Type,
            Class,
            Struct,
            Interface,
            Enum,
            Delegate,
            Method,
            Property,
            Event,
            Field,
            File,
            MSBuildProperty,
            MSBuildItem,
            MSBuildTarget,
            MSBuildTask,
        };
        private static readonly HashSet<string> hashtable = new HashSet<string>(Kinds);

        public static ushort Rank(string kind)
        {
            switch (kind)
            {
                case Class:
                case Struct:
                case Interface:
                case Enum:
                case Delegate:
                    return 1;
                case Field:
                    return 3;
                case File:
                    return 4;
                default:
                    return 2;
            }
        }

        public static bool IsKnown(string term)
        {
            return hashtable.Contains(term);
        }

        public static bool IsType(string kind)
        {
            return
                kind == Class ||
                kind == Struct ||
                kind == Interface ||
                kind == Enum ||
                kind == Delegate;
        }
    }
}


text:
package org.visallo.webster.parameterProviders;

import org.visallo.webster.ParameterValueConverter;
import org.visallo.webster.WebsterException;
import org.visallo.webster.annotations.Required;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class RequiredParameterProviderFactory<T> extends ValueParameterProviderFactory<T> {
    @Override
    public boolean isHandled(Method handleMethod, Class<? extends T> parameterType, Annotation[] parameterAnnotations) {
        return getRequiredAnnotation(parameterAnnotations) != null;
    }

    @Override
    public ParameterProvider<T> createParameterProvider(Method handleMethod, Class<?> parameterType, Annotation[] parameterAnnotations) {
        Required requiredAnnotation = getRequiredAnnotation(parameterAnnotations);
        if (requiredAnnotation == null) {
            throw new WebsterException("Could not find required annotation");
        }
        ParameterValueConverter parameterValueConverter = createParameterValueConverter(requiredAnnotation.parameterValueConverter());
        return new RequiredParameterProvider<>(parameterType, requiredAnnotation, parameterValueConverter);
    }

    private static Required getRequiredAnnotation(Annotation[] annotations) {
        for (Annotation annotation : annotations) {
            if (annotation instanceof Required) {
                return (Required) annotation;
            }
        }
        return null;
    }
}


text:
require 'spec_helper'
require 'scorm2004/sequencing/global_state_information'

describe Scorm2004::Sequencing::GlobalStateInformation do
  subject do
    obj = Object.new.extend(Scorm2004::Sequencing::GlobalStateInformation)
    obj.instance_variable_set(:@state, {})
    obj
  end

  describe 'defaults' do
    its(:current_activity) { should be_nil }
    its(:suspended_activity) { should be_nil }
  end

  describe 'example' do
    before do
      state = {
        'global_state_information' => {
          'current_activity' => 'foo',
          'suspended_activity' => 'bar'
        }
      }
      subject.instance_variable_set(:@state, state)
    end

    its(:current_activity) { should == 'foo' }
    its(:suspended_activity) { should == 'bar'}

    describe '#current_activity=' do
      it 'sets Current Activity' do
        expect {
          subject.current_activity = 'baz'
        }.to change {
          subject.current_activity
        }.from('foo').to('baz')
      end
    end

    describe '#suspended_activity=' do
      it 'sets Suspended Activity' do
        expect {
          subject.suspended_activity = 'baz'
        }.to change {
          subject.suspended_activity
        }.from('bar').to('baz')
      end
    end
  end
end


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/dialogflow/cx/v3beta1/page.proto

package com.google.cloud.dialogflow.cx.v3beta1;

public interface ListPagesRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.cx.v3beta1.ListPagesRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The flow to list all pages for.
   * Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
   * ID>/flows/<Flow ID>`.
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The parent.
   */
  java.lang.String getParent();
  /**
   *
   *
   *

   * Required. The flow to list all pages for.
   * Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
   * ID>/flows/<Flow ID>`.
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for parent.
   */
  com.google.protobuf.ByteString getParentBytes();

  /**
   *
   *
   *

   * The language to list pages for. The following fields are language
   * dependent:
   * *  `Page.entry_fulfillment.messages`
   * *  `Page.entry_fulfillment.conditional_cases`
   * *  `Page.event_handlers.trigger_fulfillment.messages`
   * *  `Page.event_handlers.trigger_fulfillment.conditional_cases`
   * *  `Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`
   * *
   * `Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`
   * *  `Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`
   * *
   * `Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`
   * *  `Page.transition_routes.trigger_fulfillment.messages`
   * *  `Page.transition_routes.trigger_fulfillment.conditional_cases`
   * If not specified, the agent's default language is used.
   * [Many
   * languages](https://cloud.google.com/dialogflow/cx/docs/reference/language)
   * are supported.
   * Note: languages must be enabled in the agent before they can be used.
   *

   *
   * string language_code = 2;
   *
   * @return The languageCode.
   */
  java.lang.String getLanguageCode();
  /**
   *
   *
   *

   * The language to list pages for. The following fields are language
   * dependent:
   * *  `Page.entry_fulfillment.messages`
   * *  `Page.entry_fulfillment.conditional_cases`
   * *  `Page.event_handlers.trigger_fulfillment.messages`
   * *  `Page.event_handlers.trigger_fulfillment.conditional_cases`
   * *  `Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages`
   * *
   * `Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases`
   * *  `Page.form.parameters.fill_behavior.reprompt_event_handlers.messages`
   * *
   * `Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases`
   * *  `Page.transition_routes.trigger_fulfillment.messages`
   * *  `Page.transition_routes.trigger_fulfillment.conditional_cases`
   * If not specified, the agent's default language is used.
   * [Many
   * languages](https://cloud.google.com/dialogflow/cx/docs/reference/language)
   * are supported.
   * Note: languages must be enabled in the agent before they can be used.
   *

   *
   * string language_code = 2;
   *
   * @return The bytes for languageCode.
   */
  com.google.protobuf.ByteString getLanguageCodeBytes();

  /**
   *
   *
   *

   * The maximum number of items to return in a single page. By default 100 and
   * at most 1000.
   *

   *
   * int32 page_size = 3;
   *
   * @return The pageSize.
   */
  int getPageSize();

  /**
   *
   *
   *

   * The next_page_token value returned from a previous list request.
   *

   *
   * string page_token = 4;
   *
   * @return The pageToken.
   */
  java.lang.String getPageToken();
  /**
   *
   *
   *

   * The next_page_token value returned from a previous list request.
   *

   *
   * string page_token = 4;
   *
   * @return The bytes for pageToken.
   */
  com.google.protobuf.ByteString getPageTokenBytes();
}


text:
var asyncplify = require('../dist/asyncplify');
var should = require('should');
var tests = require('asyncplify-tests');

describe('fromArray', function () {
    asyncplify
        .fromArray([0, 1])
        .pipe(tests.itShouldClose())
        .pipe(tests.itShouldEndSync())
        .pipe(tests.itShouldEmitValues([0, 1]));

    asyncplify
        .fromArray([])
        .pipe(tests.itShouldEmitValues([]));
});


text:
from django.views.generic import (TemplateView, ListView, DetailView, View, CreateView, UpdateView, DeleteView)
from django.core.exceptions import PermissionDenied

class HelpDeskView(View):
    """
    An abstraction of the basic view
    """

class HelpDeskTemplateView(TemplateView):
    """
    As defined by
    http://docs.djangoproject.com/en/dev/topics/class-based-views/
    Stuff defined here (A.K.A this is a documentation proxy for the above
    link):
    ---------------------------------------------------------------------
    self.template_name : Name of the template to use for rendering
    self.get_context_data(): Returns the context {} to render the template with
    self.get(request, *args, **kwargs): called for GET methods
    """

class HelpDeskListView(ListView):
    """
    This is just to abstract the "Django version switching magic happening up
    there
    """

class HelpDeskDetailView(DetailView):
    pass

class HelpDeskCreateView(CreateView):
    pass

class HelpDeskUpdateView(UpdateView):
    pass

class HelpDeskDeleteView(DeleteView):
    pass

class HelpDeskStaffView(object):

    def dispatch(self, request, *args, **kwargs):

        if request.user.is_staff is False:
            # ToDo
            # return HttpResponseRedirect
            raise PermissionDenied()
        return super(HelpDeskStaffView, self).dispatch(request, *args, **kwargs)

class HelpDeskSuperuserView(object):

    def dispatch(self, request, *args, **kwargs):

        if request.user.is_superuser is False:
            # ToDo
            # return HttpResponseRedirect
            raise PermissionDenied()
        return super(HelpDeskSuperuserView, self).dispatch(request, *args, **kwargs)

from pure_pagination.paginator import Paginator

class HelpDeskPaginationMixin(object):
    """
    Mixin for generic class-based views (e.g. django.views.generic.ListView)
    """
    # Replace the default django.core paginator by pure_pagination.Paginator
    paginator_class = Paginator

    def get_paginator(self, queryset, per_page, orphans=0, allow_empty_first_page=True):
        # Pass the request object to the paginator to keep the parameters in the url querystring ("?page=2&old_param=...")
        request = self.request
        return self.paginator_class(queryset, per_page, orphans=orphans, allow_empty_first_page=allow_empty_first_page, request=request)


text:
package org.apache.hadoop.oncrpc;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A simple TCP based RPC client handler used by {@link SimpleTcpServer}.
 */
public class SimpleTcpClientHandler extends SimpleChannelHandler {
  public static final Logger LOG =
      LoggerFactory.getLogger(SimpleTcpClient.class);
  protected final XDR request;

  public SimpleTcpClientHandler(XDR request) {
    this.request = request;
  }

  @Override
  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
    // Send the request
    if (LOG.isDebugEnabled()) {
      LOG.debug("sending PRC request");
    }
    ChannelBuffer outBuf = XDR.writeMessageTcp(request, true);
    e.getChannel().write(outBuf);
  }

  /**
   * Shutdown connection by default. Subclass can override this method to do
   * more interaction with the server.
   */
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    e.getChannel().close();
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
    LOG.warn("Unexpected exception from downstream: ", e.getCause());
    e.getChannel().close();
  }
}


text:
// Datasheet: https://cdn.sparkfun.com/assets/learn_tutorials/3/2/1/Avago-APDS-9960-datasheet.pdf
const Emitter = require('events').EventEmitter;
const util    = require('util');

const I2C_ADDR = 0x39; // Sensor's hardwired I2C address (p.8)
const DEVICE_ID = 0xAB; // The device will report this ID (p.25)

// Register addresses; only those used by plugin included
const REGISTERS = {
  ENABLE   : 0x80, // Enable different sensors/features (p.20)
  WTIME    : 0x83, // Wait time config value (p.21)
  PPULSE   : 0x8E, // Proximity pulse count and length (p.23)
  CONFIG2  : 0x90, // Second configuration register (p.24), for LED boost
  DEVICE_ID: 0x92, // Contains device ID (0xAB) (p.25)
  GPENTH   : 0xA0, // Entry proximity threshold for gestures (p.27)
  GEXTH    : 0xA1, // Exit proximity threshold for gestures (p.28)
  GCONF1   : 0xA2, // Gesture config 1: gesture detection masking (p.28)
  GCONF2   : 0xA3, // G config 2: gain, LED drive, gesture wait time (p.29)
  GOFFSET_U: 0xA4, // Gesture offset (up) (p.30)
  GOFFSET_D: 0xA5, // Gesture offset (down) (p.30)
  GPULSE   : 0xA6, // Gesture Pulse count and length (p.31)
  GOFFSET_L: 0xA7, // Gesture offset (left) (p.30)
  GOFFSET_R: 0xA9, // Gesture offset (right) (p.31)
  GCONF4   : 0xAB, // Gesture config 4: interrupts, mode enable (p.32)
  GFLVL    : 0xAE, // Gesture FIFO level: # of datasets in FIFO (p.32)
  GSTATUS  : 0xAF, // Gesture status; bit 0 indicates available data (p.33)
  GFIFO_U  : 0xFC, // 1st FIFO register in (RAM)—read data from here (p.33)
};

const FLAGS = {
  GFIFOTH  : 0b10000000, /* FIFO threshold: trigger interrupt after
                            4 datasets in FIFO (GCONF1 <7:6> p.28) */
  GGAIN    : 0b01000000, /* Gesture gain control:
                            4x (GCONF2 <6:5> p.29) */
  GLDRIVE  : 0b00000000, /* Gesture LED drive strength:
                          * 100mA (GCONF2 <4:3> p.29) */
  GWTIME   : 0b00000001, /* Gesture wait time:
                            2.8ms (GCONF2 <2:0> p.29) */
  GPLEN    : 0b11000000, /* Gesture pulse length:
                            32µs (GPULSE <7 :6> p.31) */
  GPULSE   : 0b00001001, /* Gesture pulse count:
                            10 (9 + 1) (GPULSE <5:0> p.31) */
  GVALID   : 0b00000001, /* GSTATUS register value
                            indicates valid data if 0th bit is 1 */
  PPLEN    : 0b10000000, /* Proximity pulse length:
                            16µs (PPULSE <7 :6> p.23) */
  PPULSE   : 0b10001001, /* Proximity pulse count:
                            10 (9 + 1) (PPULSE <5:0> p.23) */
  LED_BOOST: 0b00110000, /* LED drive boost:
                            300% (CONFIG2 <5:4> p.24) */
  GIEN     : 0b00000010, /* Gesture interrupt enable:
                            yes (GCONF4 <1> p.32) */
  GMODE    : 0b00000001, /* Gesture mode:
                            yes! (GCONF4 <0> p.32) */
  ENABLE   : 0b01001101, /* Enable features:
                            Gesture, Wait, Proximity, Power on
                            (ENABLE, p.20) */
};

// During setup, (value) is written to each register (key)
const SETUP_DEFAULTS = {
  ENABLE   : 0x00,          /* Disable all things,
                              effectively turning the chip off (p. 20) */
  GPENTH   : 40,            // Entry proximity threshold
  GEXTH    : 30,            // Exit proximity threshold
  GCONF1   : FLAGS.GFIFOTH, // FIFO interrupt threshold
  GCONF2   : FLAGS.GGAIN | FLAGS.GLDRIVE | FLAGS.GWTIME, // Gesture gain, LED drive, wait time
  GOFFSET_U: 0x00,          // no offset
  GOFFSET_D: 0x00,          // no offset
  GOFFSET_L: 0x00,          // no offset
  GOFFSET_R: 0x00,          // no offset
  GPULSE   : FLAGS.GPLEN | FLAGS.GPULSE // pulse count and length,
};

// During enable, each (value) is written to register (key)
const ENABLE_VALUES = {
  WTIME  : 0xFF,                       /* Wait time between cycles in
                                          low-power mode: 2.78ms (p. 21) */
  PPULSE : FLAGS.PPLEN | FLAGS.PPULSE, // Proximity pulse length and count
  CONFIG2: FLAGS.LED_BOOST,
  GCONF4 : FLAGS.GIEN | FLAGS.GMODE,
  ENABLE : FLAGS.ENABLE
};

// For processing read data
const GESTURE_THRESHOLD_OUT = 30;
const GESTURE_SENSITIVITY = 10;

module.exports = function (five) {
  return (function () {
    /**
     * @param {Object} opts Options: pin, address
     * pin denotes interrupt pin connection
     *
     * Sample initialization:
     * new APDS9960('A2');
     * new APDS9960({ pin: 'A2'});
     *
     */
    function APDS9960 (opts) {
      if (!(this instanceof APDS9960)) {
        return new APDS9960(opts);
      }
      five.Board.Component.call(this, opts = five.Board.Options(opts));
      this.interruptState = 1; // Interrupt is active LOW
      opts.address        = opts.address || I2C_ADDR;
      this.address        = opts.address;
      this.io.i2cConfig(opts); // Get I2C comms started for the device

      this.io.i2cReadOnce(this.address, REGISTERS.DEVICE_ID, 1, data => {
        if (data[0] !== DEVICE_ID) { // DEVICE_ID register should return 0xAB
          throw new Error('Unable to establish connection with APDS9960');
        }
      });
      this.resetGesture();
      this.setup(this.enable);
    }

    util.inherits(APDS9960, Emitter);

    APDS9960.prototype.resetGesture = function () {
      this.gestureData = {
        raw: [],
        deltas: {},
        movements: { // A gesture can have movements along more than one axis
          vertical  : false,
          horizontal: false,
          up        : false,
          down      : false,
          left      : false,
          right     : false
        },
        valid: false, // Was gesture decoding successful?
        direction: undefined
      };
    };

    APDS9960.prototype.setup = function (callback) {
      for (var rKey in SETUP_DEFAULTS) {
        this.io.i2cWrite(this.address,
          REGISTERS[rKey], [SETUP_DEFAULTS[rKey]]);
      }
      if (typeof callback === 'function') {
        callback.call(this);
      }
    };

    APDS9960.prototype.enable = function () {
      // Set up interrupt handling
      this.io.pinMode(this.pin, this.io.MODES.INPUT);
      // Interrupts from device are active LOW—when pin goes LOW we should act
      this.io.digitalRead(this.pin, data => {
        if (data !== this.interruptState && data === 0) {
          this.readGesture();
        }
        this.interruptState = data;
      });
      for (var rKey in ENABLE_VALUES) {
        this.io.i2cWrite(this.address,
          REGISTERS[rKey], [ENABLE_VALUES[rKey]]);
      }
    };

    APDS9960.prototype.readGesture = function () {
      // GSTATUS value determines whether valid data is available (p.33)
      this.io.i2cReadOnce(this.address, REGISTERS.GSTATUS, 1, status => {
        if (status & FLAGS.GVALID === FLAGS.GVALID) {
          // There should be valid data in the FIFO
          // GFLVL will report how many datasets are in the FIFO (p.32)
          this.io.i2cReadOnce(this.address, REGISTERS.GFLVL, 1, fifoLevel => {
            // Read the number of 4-byte samples indicated by sampleCount
            // And split them out into their directional components
            this.io.i2cReadOnce(this.address,
              REGISTERS.GFIFO_U, (fifoLevel * 4), rawData => {
                for (var i = 0; i < rawData.length; i += 4) {
                  this.gestureData.raw.push({
                    up   : rawData[i],
                    down : rawData[i + 1],
                    left : rawData[i + 2],
                    right: rawData[i + 3]
                  });
                }
                return this.readGesture(); // Keep reading data...
              });
          });
        } else { // No (more) data to gather about this gesture
          this.processGesture();
          this.decodeGesture();
          this.resetGesture();
        }
      });
    };

    APDS9960.prototype.processGesture = function () {
      const raw = this.gestureData.raw;
      const directionDelta = function (el1, el2, dir1, dir2) {
        var el2r = ((el2[dir1] - el2[dir2]) * 100) / (el2[dir1] + el2[dir2]);
        var el1r = ((el1[dir1] - el1[dir2]) * 100) / (el1[dir1] + el1[dir2]);
        return el2r - el1r;
      };
      const exceedsThreshold = raw.filter(sample => {
        return (sample.up > GESTURE_THRESHOLD_OUT &&
                sample.down > GESTURE_THRESHOLD_OUT &&
                sample.left > GESTURE_THRESHOLD_OUT &&
                sample.right > GESTURE_THRESHOLD_OUT);
      });
      if (!exceedsThreshold.length || raw.length < 4) {
        // If not enough data or none exceed threshold, nothing to do
        // This will result in gesture data being ignored and discarded
        return false;
      }

      const first = exceedsThreshold[0];
      const last = exceedsThreshold[exceedsThreshold.length - 1];
      const deltas = {
        upDown: directionDelta(first, last, 'up', 'down'),
        leftRight: directionDelta(first, last, 'left', 'right')
      };
      this.gestureData.deltas = deltas;
    };

    APDS9960.prototype.decodeGesture = function () {
      const deltas = this.gestureData.deltas;
      const verticalMotion = Math.abs(deltas.upDown);
      const horizontalMotion = Math.abs(deltas.leftRight);
      if (verticalMotion > GESTURE_SENSITIVITY) {
        this.gestureData.valid = true;
        this.gestureData.movements.vertical = true;
        this.gestureData.movements.up = (deltas.upDown >= 0);
        this.gestureData.movements.down = (deltas.upDown < 0);
      }
      if (horizontalMotion > GESTURE_SENSITIVITY) {
        this.gestureData.valid = true;
        this.gestureData.movements.horizontal = true;
        this.gestureData.movements.left = (deltas.leftRight >= 0);
        this.gestureData.movements.right = (deltas.leftRight < 0);
      }
      if (this.gestureData.valid) {
        if (verticalMotion > horizontalMotion) {
          this.gestureData.direction = (this.gestureData.movements.up) ?
            'up' : 'down';
        } else {
          this.gestureData.direction = (this.gestureData.movements.left) ?
          'left' : 'right';
        }
      }
      // Emit a directional event if there is a direction
      if (this.gestureData.direction) {
        this.emit(this.gestureData.direction, this.gestureData);
      }
      // Always emit a generic gesture event, even if decoding failed
      this.emit('gesture', this.gestureData);
    };

    return APDS9960;
  }());
};


text:
function hello()
	return "Hello i am Lua"
end

function hello2()
	return "Hello i am Lua [2]"
end

function hello3(arg1)
	return "Hello i am a Lua function with 1 arg "..arg1
end

function hello4(arg1, arg2)
	return "Hello i am a Lua function with 2 args "..arg1.." "..arg2
end

uwsgi.register_rpc("hello", hello)
uwsgi.register_rpc("hello2", hello2)
uwsgi.register_rpc("hello3", hello3)
uwsgi.register_rpc("hello4", hello4)


text:
package com.thinkgem.jeesite.modules.sys.dao;

import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.thinkgem.jeesite.common.persistence.BaseDao;
import com.thinkgem.jeesite.common.persistence.BaseDaoImpl;
import com.thinkgem.jeesite.modules.sys.entity.Menu;

/**
 * 菜单DAO接口
 * @author ThinkGem
 * @version 2013-01-15
 */
public interface MenuDao extends MenuDaoCustom, CrudRepository<Menu, Long> {

	@Query("from Menu  where is_top=0 order by id asc")
	public List<Menu> findAllList();

}

/**
 * DAO自定义接口
 * @author ThinkGem
 */
interface MenuDaoCustom extends BaseDao<Menu> {

}

/**
 * DAO自定义接口实现
 * @author ThinkGem
 */
@Repository
class MenuDaoImpl extends BaseDaoImpl<Menu> implements MenuDaoCustom {

}


text:
from django.conf.urls import patterns, url

urlpatterns = patterns('ajax_upload.views',
    url(r'^$', 'upload', name='ajax-upload'),
)


text:
package org.apache.jackrabbit.oak.plugins.document;

import java.util.List;

import com.google.common.collect.Lists;

import org.apache.jackrabbit.oak.plugins.document.util.Utils;
import org.junit.Test;

import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES;
import static org.apache.jackrabbit.oak.plugins.document.util.Utils.getIdFromPath;
import static org.apache.jackrabbit.oak.plugins.document.util.Utils.getKeyLowerLimit;
import static org.apache.jackrabbit.oak.plugins.document.util.Utils.getKeyUpperLimit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class ConcurrentQueryAndInvalidateIT extends AbstractMultiDocumentStoreTest {

    public ConcurrentQueryAndInvalidateIT(DocumentStoreFixture dsf) {
        super(dsf);
    }

    protected static final int NUM_NODES = 50;

    private volatile long counter;

    @Test
    public void cacheUpdateInvalidateWithIDs() throws Exception {
        cacheUpdate(new Invalidate() {
            @Override
            public void perform(DocumentStore store, Iterable<String> ids) {
                store.invalidateCache(ids);
            }
        });
    }

    @Test
    public void cacheUpdateInvalidateAll() throws Exception {
        cacheUpdate(new Invalidate() {
            @Override
            public void perform(DocumentStore store, Iterable<String> ids) {
                store.invalidateCache();
            }
        });
    }

    @Test
    public void cacheUpdateInvalidateIndividual() throws Exception {
        cacheUpdate(new Invalidate() {
            @Override
            public void perform(DocumentStore store, Iterable<String> ids) {
                for (String id : ids) {
                    store.invalidateCache(NODES, id);
                }
            }
        });
    }

    private void cacheUpdate(final Invalidate inv) throws Exception {
        Revision r = newRevision();
        List<UpdateOp> ops = Lists.newArrayList();
        List<String> ids = Lists.newArrayList();
        for (int i = 0; i < NUM_NODES; i++) {
            String id = Utils.getIdFromPath("/node-" + i);
            ids.add(id);
            UpdateOp op = new UpdateOp(id, true);
            op.set(Document.ID, id);
            NodeDocument.setLastRev(op, r);
            ops.add(op);
            removeMe.add(id);
        }
        ds1.remove(NODES, ids);
        ds1.create(NODES, ops);

        for (int i = 0; i < 200; i++) {
            Thread q = new Thread(new Runnable() {
                @Override
                public void run() {
                    // query docs on ds1
                    queryDocuments();
                }
            });
            Thread u = new Thread(new Runnable() {
                @Override
                public void run() {
                    // update docs on ds2
                    Iterable<String> ids = updateDocuments();
                    // invalidate docs on ds1
                    inv.perform(ds1, ids);
                }
            });
            q.start();
            u.start();
            q.join();
            u.join();
            for (int j = 0; j < NUM_NODES; j++) {
                NodeDocument doc = ds1.find(NODES, Utils.getIdFromPath("/node-" + j));
                assertNotNull(doc);
                assertEquals("Unexpected revision timestamp for " + doc.getId(),
                        counter, doc.getLastRev().get(1).getTimestamp());
            }
        }
    }

    private Revision newRevision() {
        return new Revision(++counter, 0, 1);
    }

    private void queryDocuments() {
        ds1.query(NODES, getKeyLowerLimit("/"), getKeyUpperLimit("/"), 100);
    }

    private Iterable<String> updateDocuments() {
        List<String> ids = Lists.newArrayList();
        for (int i = 0; i < NUM_NODES; i++) {
            ids.add(getIdFromPath("/node-" + i));
        }
        UpdateOp op = new UpdateOp("foo", false);
        NodeDocument.setLastRev(op, newRevision());
        ds2.update(NODES, ids, op);
        return ids;
    }

    private interface Invalidate {
        void perform(DocumentStore store, Iterable<String> ids);
    }
}


text:
define(function (require) {
    return require('fcui/main').alias('FcTab', require('esui/Tab'));
});


text:
package com.axway.ats.agent.core.ant.component.agenttest;

import org.apache.log4j.Logger;

import com.axway.ats.agent.core.ant.component.agenttest.SecondActionClass;
import com.axway.ats.agent.core.model.Action;
import com.axway.ats.agent.core.model.Parameter;
import com.axway.ats.core.validation.ValidationType;

public class SecondActionClass {

    public static int ACTION_VALUE = 0;

    @Action(name = "action 2")
    public void action1( @Parameter(name = "value") int value ) {

        ACTION_VALUE = value;
        Logger.getLogger( SecondActionClass.class ).info( ( Object ) "Method action 1 has been executed" );
    }

    @Action(name = "action checked exception")
    public void actionCheckedException() throws Exception {

        throw new Exception( "Message - checked exception " );
    }

    @Action(name = "action unchecked exception")
    public void actionUncheckedException() {

        throw new RuntimeException( "Message - unchecked exception " );
    }

    @Action(name = "Create User")
    public void createUser( @Parameter(name = "emailAddress", validation = ValidationType.STRING_EMAIL_ADDRESS) String emailAddress ) {

        throw new RuntimeException( "Message - unchecked exception " );
    }
}


text:
<?php

/**
 * Global Configuration Override
 *
 * You can use this file for overriding configuration values from modules, etc.
 * You would place values in here that are agnostic to the environment and not
 * sensitive to security.
 *
 * @NOTE: In practice, this file will typically be INCLUDED in your source
 * control, so do not include passwords or other sensitive information in this
 * file.
 */
return array(
    'db' => array(
        //this is for primary adapter....
        'driver' => 'Pdo',
        'dsn' => 'mysql:dbname=techquer;host=localhost',
        'username' => 'root',
        'password' => 'tech',
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
        ),
        //other adapter when it needed...
        /*'adapters' => array(
            'otherdb' => array(
                'driver' => 'Pdo',
                'dsn' => 'mysql:dbname=mylandho_foreclosure;host=10.1.190.245',
                'username' => 'SREMON',
                'password' => 'nDCSr4M0n1t0r',
                'driver_options' => array(
                    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
                ),
            )
        ),*/
    ),
    'service_manager' => array(
        // for primary db adapter that called
        // by $sm->get('Zend\Db\Adapter\Adapter')
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
        // to allow other adapter to be called by
        // $sm->get('db1') or $sm->get('db2') based on the adapters config.
        'abstract_factories' => array(
            'Zend\Db\Adapter\AdapterAbstractServiceFactory',
        ),
    ),
    'module_layouts' => array(
        'Portal' => 'layout/layout.phtml',
    ),
);


text:
//
//  SMSQLiteMigration.h
//  SMSQLiteMigration
//
//  Created by hyman on 2016/11/27.
//  Copyright © 2016年 hyman. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "FMDatabase.h"

/**
 *  According to the different reference database and local database, upgrade the differences
 *
 *  Supports:
 *
 *  1,Add new field(the new field of constraint only support: PK, DefaultValue, NOT NULL)
 *  2,Add new table, Delete table, Rename table
 *  3,Upate index
 *
 *  @note
 *  1,Rename table must be in accordance with the following format to rename the table name:oldTableName_to_newTableName
 *
 *  (Migration, when recognition to the format of the table name, will extract the oldTableName and newTableName, and then judge whether the oldTableName exists in oldDB, if any, is renamed as newTableName;Otherwise, the oldTableName_to_newTableName will be treated as an ordinary table name)
 *
 *  2,Does not support this case: foreign key constraints exist in the database
 *
 */
@interface SMSQLiteMigration : NSObject

/**
 the version of db

 @param db db

 @return the version of db. if error, return NSNotFound
 */
+ (NSInteger)versionForDB:(FMDatabase *)db;

/**
 set the db version

 @param version the new version
 @param db db
 */
+ (BOOL)setVersion:(NSInteger)version forDB:(FMDatabase *)db;

/**
 According to the reference database, migrate the old database.After successful migration, update oldDB version number into a new version number

 According to the different reference database and local database, upgrade the differences

 @param localDB      need to migration
 @param referDB      reference database
 @param newVersion   the new version
 */
+ (BOOL)migrateLocalDB:(FMDatabase *)localDB referDB:(FMDatabase *)referDB toVersion:(NSInteger)newVersion;

/**
 Copy of the specified table data from origin DB to target DB

 @param tableNames   need to copy
 @param originDB     the database where the table to be copied resides
 @param targetDB     the database where the table need to copy to

 @note
 If the corresponding table does not exist in targetDB, the method will copy the corresponding table to targetDB.
 Otherwise, only copy the field datas that also exists in the targetDB table
 */
+ (BOOL)copyDataInTables:(NSArray<NSString *> *)tableNames fromDB:(FMDatabase *)originDB toDB:(FMDatabase *)targetDB;

@end


text:
from lxml.etree import Element
from ..stanzas import XML_LANG
from ..utils import stripNsFromTag
from ..errors import XmppError

NS_URI = "urn:ietf:params:xml:ns:xmpp-sasl"

class SaslError(XmppError):
    '''
    Conditions: aborted, account-disabled, credentials-expired,
                encryption-required, incorrect-encoding, invalid-authzid,
                invalid-mechanism, mechanism-too-weak, not-authorized,
                temporary-auth-failure
    '''
    def __init__(self, cond=None, text=None, lang=None, xml=None):
        self.cond = cond
        self.text = text
        self.lang = lang

        if xml is not None:
            # 'xml' overrided and keyword args
            if xml.tag != "{%s}failure" % NS_URI:
                raise ValueError("'xml' is not a SASL error element")
            for child in list(xml):
                if child.tag == "text":
                    self.text = child.text
                    try:
                        self.lang = child.attrib[XML_LANG]
                    except KeyError:
                        pass
                else:
                    self.cond = stripNsFromTag(child.tag, NS_URI)

        if not self.cond:
            raise ValueError("Error condition 'cond' required")

    @property
    def xml(self):
        nsmap = {None: NS_URI}

        e = Element("{%s}failure" % NS_URI, nsmap=nsmap)
        e.append(Element("{%s}%s" % (NS_URI, self.cond), nsmap=nsmap))
        if self.text:
            txt = Element("{%s}text" % NS_URI, nsmap=nsmap)
            if self.lang:
                txt.attrib[XML_LANG] = self.lang
            txt.text = self.text
            e.append(txt)

        return e


text:
package cz.metacentrum.perun.controller.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;

import cz.metacentrum.perun.controller.model.ServiceForGUI;
import cz.metacentrum.perun.controller.service.GeneralServiceManager;
import cz.metacentrum.perun.core.api.AuthzResolver;
import cz.metacentrum.perun.core.api.Facility;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.Role;
import cz.metacentrum.perun.core.api.Service;
import cz.metacentrum.perun.core.api.ServicesManager;
import cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.PrivilegeException;
import cz.metacentrum.perun.core.api.exceptions.RelationExistsException;
import cz.metacentrum.perun.core.api.exceptions.ServiceAlreadyBannedException;
import cz.metacentrum.perun.core.api.exceptions.ServiceAlreadyRemovedException;
import cz.metacentrum.perun.core.api.exceptions.ServiceExistsException;
import cz.metacentrum.perun.core.api.exceptions.ServiceNotExistsException;
import cz.metacentrum.perun.taskslib.dao.ExecServiceDao;
import cz.metacentrum.perun.taskslib.dao.ExecServiceDenialDao;
import cz.metacentrum.perun.taskslib.dao.ExecServiceDependencyDao;
import cz.metacentrum.perun.taskslib.model.ExecService;
import cz.metacentrum.perun.taskslib.model.ExecService.ExecServiceType;

/**
 * @author Michal Karm Babacek
 */
@Transactional
@org.springframework.stereotype.Service(value = "generalServiceManager")
public class GeneralServiceManagerImpl implements GeneralServiceManager {

	private final static Logger log = LoggerFactory.getLogger(GeneralServiceManagerImpl.class);
	// Beginning of the auditer message which triggers service propagation
	public final static String FORCE_PROPAGATION = "force propagation: ";
	public final static String FREE_ALL_DEN = "free all denials: ";
	public final static String FREE_DEN_OF_EXECSERVICE = "free denial: ";
	public final static String BAN_SERVICE = "ban :";

	@Autowired
	private ExecServiceDao execServiceDao;
	@Autowired
	private ExecServiceDenialDao execServiceDenialDao;
	@Autowired
	private ExecServiceDependencyDao execServiceDependencyDao;
	@Autowired
	private ServicesManager servicesManager;

	@Override
	public List<ExecService> listExecServices(PerunSession perunSession) throws ServiceNotExistsException, InternalErrorException, PrivilegeException {
		return execServiceDao.listExecServices();
	}

	@Override
	public List<ExecService> listExecServices(PerunSession perunSession, int serviceId) throws ServiceNotExistsException, InternalErrorException, PrivilegeException {
		return execServiceDao.listExecServices(serviceId);
	}

	@Override
	public int countExecServices() {
		return execServiceDao.countExecServices();
	}

	@Override
	public ExecService getExecService(PerunSession perunSession, int execServiceId) throws InternalErrorException {
		return execServiceDao.getExecService(execServiceId);
	}

	@Override
	public int insertExecService(PerunSession perunSession, ExecService execService) throws InternalErrorException, PrivilegeException, ServiceExistsException {
		Service service = null;
		try {
			service = servicesManager.getServiceByName(perunSession, execService.getService().getName());
		} catch (ServiceNotExistsException e) {
			service = servicesManager.createService(perunSession, execService.getService());
		}
		execService.setService(service);
		return execServiceDao.insertExecService(execService);
	}

	@Override
	public void updateExecService(PerunSession perunSession, ExecService execService) throws ServiceNotExistsException, InternalErrorException, PrivilegeException {
		servicesManager.updateService(perunSession, execService.getService());
		execServiceDao.updateExecService(execService);
	}

	@Override
	public void deleteExecService(ExecService execService) {
		execServiceDao.deleteExecService(execService.getId());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void banExecServiceOnFacility(PerunSession sess, ExecService execService, Facility facility) throws InternalErrorException, ServiceAlreadyBannedException {
		try {
			execServiceDenialDao.banExecServiceOnFacility(execService.getId(), facility.getId());
		} catch (DuplicateKeyException ex) {
			throw new ServiceAlreadyBannedException(execService.getService(), facility);
		}
		sess.getPerun().getAuditer().log(sess, "{} {} on {}", BAN_SERVICE, execService, facility);
	}

	@Override
	public void banExecServiceOnDestination(PerunSession sess, ExecService execService, int destinationId) throws InternalErrorException {
		execServiceDenialDao.banExecServiceOnDestination(execService.getId(), destinationId);
		sess.getPerun().getAuditer().log(sess, "{} {} on {}", BAN_SERVICE, execService, destinationId);
	}

	@Override
	public List<ExecService> listDenialsForFacility(PerunSession perunSession, Facility facility) throws InternalErrorException {
		return execServiceDenialDao.listDenialsForFacility(facility.getId());
	}

	@Override
	public List<ExecService> listDenialsForDestination(PerunSession perunSession, int destinationId) throws InternalErrorException {
		return execServiceDenialDao.listDenialsForDestination(destinationId);
	}

	@Override
	public boolean isExecServiceDeniedOnFacility(ExecService execService, Facility facility) {
		return execServiceDenialDao.isExecServiceDeniedOnFacility(execService.getId(), facility.getId());
	}

	@Override
	public boolean isExecServiceDeniedOnDestination(ExecService execService, int destinationId) {
		return execServiceDenialDao.isExecServiceDeniedOnDestination(execService.getId(), destinationId);
	}
	@Override
	public void freeAllDenialsOnFacility(PerunSession sess, Facility facility) throws InternalErrorException{
		execServiceDenialDao.freeAllDenialsOnFacility(facility.getId());
		sess.getPerun().getAuditer().log(sess, "{} on {}" ,FREE_ALL_DEN, facility);
	}

	@Override
	public void freeAllDenialsOnDestination(PerunSession sess, int destinationId) throws InternalErrorException {
		execServiceDenialDao.freeAllDenialsOnDestination(destinationId);
		sess.getPerun().getAuditer().log(sess, "{} on {}", FREE_ALL_DEN, destinationId);
	}

	@Override
	public void freeDenialOfExecServiceOnFacility(PerunSession sess, ExecService execService, Facility facility) throws InternalErrorException {
		execServiceDenialDao.freeDenialOfExecServiceOnFacility(execService.getId(), facility.getId());
		sess.getPerun().getAuditer().log(sess, "{} {} on {}", FREE_DEN_OF_EXECSERVICE, execService, facility);
	}

	@Override
	public void freeDenialOfExecServiceOnDestination(PerunSession sess, ExecService execService, int destinationId) throws InternalErrorException {
		execServiceDenialDao.freeDenialOfExecServiceOnDestination(execService.getId(), destinationId);
		sess.getPerun().getAuditer().log(sess, "{} {} on {}", FREE_DEN_OF_EXECSERVICE, execService, destinationId);
	}

	@Override
	public void createDependency(ExecService dependantExecService, ExecService execService) {
		execServiceDependencyDao.createDependency(dependantExecService.getId(), execService.getId());
	}

	@Override
	public void removeDependency(ExecService dependantExecService, ExecService execService) {
		execServiceDependencyDao.removeDependency(dependantExecService.getId(), execService.getId());
	}

	@Override
	public boolean isThereDependency(ExecService dependantExecService, ExecService execService) {
		return execServiceDependencyDao.isThereDependency(dependantExecService.getId(), execService.getId());
	}

	@Override
	public List<ExecService> listExecServicesDependingOn(PerunSession perunSession, ExecService execService) throws InternalErrorException {
		return execServiceDependencyDao.listExecServicesDependingOn(execService.getId());
	}

	@Override
	public List<ExecService> listExecServicesThisExecServiceDependsOn(PerunSession perunSession, ExecService dependantExecService) throws InternalErrorException {
		return execServiceDependencyDao.listExecServicesThisExecServiceDependsOn(dependantExecService.getId());
	}

	@Override
	public List<ExecService> listExecServicesThisExecServiceDependsOn(PerunSession perunSession, ExecService dependantExecService, ExecServiceType execServiceType) throws InternalErrorException {
		return execServiceDependencyDao.listExecServicesThisExecServiceDependsOn(dependantExecService.getId(), execServiceType);
	}

	@Override
	public boolean forceServicePropagation(PerunSession sess, Facility facility, Service service) throws ServiceNotExistsException, FacilityNotExistsException, InternalErrorException, PrivilegeException {
		List<ExecService> listOfExecServices = listExecServices(sess, service.getId());
		for(ExecService es: listOfExecServices) {
			//Global
			if(!es.isEnabled()) return false;
			//Local
			if(execServiceDenialDao.isExecServiceDeniedOnFacility(es.getId(), facility.getId())) return false;
		}
		//Call log method out of transaction
		sess.getPerun().getAuditer().log(sess, FORCE_PROPAGATION + "On {} and {}", facility, service);
		return true;
	}

	@Override
	public boolean forceServicePropagation(PerunSession sess, Service service) throws ServiceNotExistsException, InternalErrorException, PrivilegeException {
		List<ExecService> listOfExecServices = listExecServices(sess, service.getId());
		for(ExecService es: listOfExecServices) {
			//Global
			if(!es.isEnabled()) return false;
		}
		//Call log method out of transaction
		sess.getPerun().getAuditer().log(sess, FORCE_PROPAGATION + "On {} ", service);
		return true;
	}

	@Override
	public void deleteService(PerunSession perunSession, Service service) throws InternalErrorException, ServiceNotExistsException, PrivilegeException, RelationExistsException, ServiceAlreadyRemovedException {
		execServiceDao.deleteAllExecServicesByService(service.getId());
		servicesManager.deleteService(perunSession, service);
	}

	@Override
	public List<Service> listServices(PerunSession perunSession) throws InternalErrorException, PrivilegeException {
		return servicesManager.getServices(perunSession);
	}

	@Override
	public Service getService(PerunSession perunSession, int serviceId) throws ServiceNotExistsException, InternalErrorException, PrivilegeException {
		return servicesManager.getServiceById(perunSession, serviceId);
	}

	@Override
	public List<ServiceForGUI> getFacilityAssignedServicesForGUI(PerunSession perunSession, Facility facility) throws PrivilegeException, FacilityNotExistsException, InternalErrorException {

		// result list
		List<ServiceForGUI> result = new ArrayList<ServiceForGUI>();
		// get assigned services
		List<Service> services = getServicesManager().getAssignedServices(perunSession, facility);
		for (Service service : services){
			// flag
			boolean allowed = true;
			// new ServiceForGUI
			ServiceForGUI newService = new ServiceForGUI(service);
			// get their exec services
			List<ExecService> execs = execServiceDao.listExecServices(service.getId());
			for (ExecService exec : execs){
				// if generate
				if (exec.getExecServiceType().equals(ExecService.ExecServiceType.GENERATE)){
					if (execServiceDenialDao.isExecServiceDeniedOnFacility(exec.getId(), facility.getId()) == true) {
						newService.setGenAllowedOnFacility(false);
						allowed = false;
					} else {
						newService.setGenAllowedOnFacility(true);
					}
					newService.setGenExecService(exec);
				} else {
					// if send
					if (execServiceDenialDao.isExecServiceDeniedOnFacility(exec.getId(), facility.getId()) == true) {
						newService.setSendAllowedOnFacility(false);
						allowed = false;
					} else {
						newService.setSendAllowedOnFacility(true);
					}
					newService.setSendExecService(exec);
				}
			}
			newService.setAllowedOnFacility(allowed);
			result.add(newService);
		}

		return result;

	}

	public ExecServiceDao getExecServiceDao() {
		return execServiceDao;
	}

	public void setExecServiceDao(ExecServiceDao execServiceDao) {
		this.execServiceDao = execServiceDao;
	}

	public ExecServiceDenialDao getExecServiceDenialDao() {
		return execServiceDenialDao;
	}

	public void setExecServiceDenialDao(ExecServiceDenialDao execServiceDenialDao) {
		this.execServiceDenialDao = execServiceDenialDao;
	}

	public ExecServiceDependencyDao getExecServiceDependencyDao() {
		return execServiceDependencyDao;
	}

	public void setExecServiceDependencyDao(ExecServiceDependencyDao execServiceDependencyDao) {
		this.execServiceDependencyDao = execServiceDependencyDao;
	}

	public void setServicesManager(ServicesManager servicesManager) {
		this.servicesManager = servicesManager;
	}

	public ServicesManager getServicesManager() {
		return servicesManager;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Service createCompleteService(PerunSession perunSession, String serviceName, String scriptPath, int defaultDelay, boolean enabled) throws InternalErrorException, PrivilegeException, ServiceExistsException {

		if (!AuthzResolver.isAuthorized(perunSession, Role.PERUNADMIN)) {
			throw new PrivilegeException(perunSession, "createCompleteService");
		}

		Service service = null;

		try {
			service = servicesManager.getServiceByName(perunSession, serviceName);
			if (service != null) {
				throw new ServiceExistsException(service);
			}
		} catch (ServiceNotExistsException e) {
			service = new Service();
			service.setName(serviceName);
			service = servicesManager.createService(perunSession, service);
		}

		ExecService genExecService = new ExecService();
		genExecService.setService(service);
		genExecService.setDefaultDelay(defaultDelay);
		genExecService.setEnabled(enabled);
		genExecService.setScript(scriptPath);
		genExecService.setExecServiceType(ExecServiceType.GENERATE);
		genExecService.setId(execServiceDao.insertExecService(genExecService));

		ExecService sendExecService = new ExecService();
		sendExecService.setService(service);
		sendExecService.setDefaultDelay(defaultDelay);
		sendExecService.setEnabled(enabled);
		sendExecService.setScript(scriptPath);
		sendExecService.setExecServiceType(ExecServiceType.SEND);
		sendExecService.setId(execServiceDao.insertExecService(sendExecService));

		this.createDependency(sendExecService, genExecService);

		return service;

	}
}