text:
<?php

class assignments_util {
    public static function CopyAssignmentStructure($asg_id,$user_id,$now)
    {
        $sql = "INSERT into assignments (quiz_id, org_quiz_id,asg_image,paused,added_date,
                          inserted_by,inserted_date,results_mode,
                          quiz_time,show_results, pass_score,quiz_type,
                          status , allow_review,qst_order,answer_order,affect_changes,
                          limited, send_results,accept_new_users,assignment_name,asg_quiz_type,
                          branch_id,allow_change_prev,show_success_msg,
                          is_random,random_qst_count,variants, show_intro, intro_text,show_point_info,
                          results_template_id,cert_name, cert_enabled, asg_cat_id,mails_copy,
                          fb_users_list,fb_share,fb_allow_comments,short_desc,
                          v_start_time,v_end_time,calc_mode,ans_calc_mode)

                SELECT null, null,null,0,'$now',
                                          $user_id,'$now',results_mode,
                                          quiz_time,show_results, pass_score,quiz_type,
                                          0 , allow_review,qst_order,answer_order,affect_changes,
                                          limited, send_results,accept_new_users,assignment_name,asg_quiz_type,
                                          branch_id,allow_change_prev,show_success_msg,
                                          is_random,random_qst_count,variants, show_intro, intro_text,show_point_info,
                                          results_template_id,cert_name, cert_enabled, asg_cat_id,mails_copy,
                                          fb_users_list,fb_share,fb_allow_comments,short_desc,
                                          v_start_time,v_end_time,calc_mode,ans_calc_mode
                FROM assignments
                WHERE id = $asg_id";
        return $sql;
    }
}

?>


text:
start=`date +%s.%N`
mkdir multigpu-trained
CUDA_VISIBLE_DEVICES=$deviceId python fcn5_mnist.py  --batch_size=$batch_size --epochs=$epochs --device_id=$deviceId
end=`date +%s.%N`
runtime=$( echo "$end - $start" | bc -l )
echo "finished with execute time: ${runtime}"
rm -rf multigpu-trained

redpajama_set_name: RedPajamaGithub


text:
package generated.zcsclient.account;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import generated.zcsclient.zm.testShareInfo;

/**
 *
Java class for getShareInfoResponse complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="getShareInfoResponse">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="share" type="{urn:zimbra}shareInfo" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getShareInfoResponse", propOrder = {
    "share"
})
public class testGetShareInfoResponse {

    protected List<testShareInfo> share;

    /**
     * Gets the value of the share property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the share property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getShare().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link testShareInfo }
     *
     *
     */
    public List<testShareInfo> getShare() {
        if (share == null) {
            share = new ArrayList<testShareInfo>();
        }
        return this.share;
    }

}


text:
package com.thanksmister.iot.mqtt.alarmpanel.ui.controls;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * https://stackoverflow.com/questions/31000076/how-to-make-swipe-disable-in-a-view-pager-in-android
 */
public class CustomViewPager extends ViewPager {

    private boolean enabled;

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.enabled = true;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return this.enabled && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return this.enabled && super.onInterceptTouchEvent(event);
    }

    public void setPagingEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}


text:
import { Component } from '@angular/core';

import { AppState } from '../app.service';
import { Title } from './title';
import { XLarge } from './x-large';
import { UserService } from '../shared/services/user/user.service';

import { AlertComponent } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
  // The selector is what angular internally uses
  // for `document.querySelectorAll(selector)` in our index.html
  // where, in this case, selector is the string 'home'
  selector: 'home',  // <home></home>
  // We need to tell Angular's Dependency Injection which providers are in our app.
  providers: [
    Title,
    AlertComponent
  ],

  // Our list of styles in our component. We may add more to compose many styles together
  styleUrls: [ './home.component.scss' ],
  // Every Angular template is first compiled by the browser before Angular runs it's compiler
  templateUrl: './home.component.html'
})
export class HomeComponent {
  // Set our default values
  localState = { value: '' };
  slideToggleModel = true;

  // TypeScript public modifiers
  constructor(
    public appState: AppState,
    public title: Title,
    private userService: UserService
    ) {

  }

  ngOnInit() {
    console.log('hello `Home` component');
    // this.title.getData().subscribe(data => this.data = data);
  }

  submitState(value: string) {
    console.log('submitState', value);
    this.appState.set('value', value);
    this.localState.value = '';
  }

  sendData() {
    this.userService.sendData();
  }

   sendDataWrong() {
    this.userService.sendDataWrong();
  }
}


text:
package gxui

import test "github.com/google/gxui/testing"
import (
	"strings"
	"testing"
)

func calcScore(str, partial string) int {
	return flaScore(str, strings.ToLower(str), partial, strings.ToLower(partial))
}

func TestFilteredListAdapterScore(t *testing.T) {
	test.AssertEquals(t, (3*3)+(2*2+1)+(3*3+1), calcScore("a_Mix_Of_Words", "mixOfrds"))
}


text:
var gulp = require( 'gulp' );
var shell = require( 'gulp-shell' );

gulp.task(
	'fontcustom',
	shell.task([
		'bundle exec fontcustom compile'
	])
);


text:
/**
 * Created by aksalj on 6/17/16.
 */
"use strict";
let chai = require('chai');
let expect = chai.expect;

const PesaJs = require('../index');
const service = new PesaJs.LipaNaMpesa(require("../.test.local.json"));

const cart = {
    transaction: "54fgftgh",
    ref: "ytrytfytf",
    account: "254709998888",
    amount: 8765,
    callbackUrl: "http://awesome-store.co.ke/ipn",
    details: "Additional transaction details if any"
};

describe("PaymentService", function () {

    describe("request payment", function () {

        it("checks cart params", function (done) {
            service.requestPayment()
                .then((data) => {
                    data.should.not.exist();
                    done();
                })
                .catch((err) => {
                    expect(err).to.be.not.equal(null);
                    done();
                });
        });

        it("submits payment request", function (done) {
            service.requestPayment(cart)
                .then((data) => {
                    data.should.exist();
                    done();
                })
                .catch((err) => {
                    expect(err).to.be.equal(null); // grr really?
                    done();
                });
        });

    });

    describe("confirm payment", function () {
        it("checks params", function (done) {
            service.confirmPayment()
                .then((data) => {
                    data.should.exist();
                    done();
                })
                .catch((err) => {
                    expect(err).to.be.equal(null);
                });
        });
    });

    describe("check payment status", function () {
        it("checks params", function (done) {
            service.getPaymentStatus()
                .then((data) => {
                    data.should.exist();
                    done();
                })
                .catch((err) => {
                    expect(err).to.be.equal(null);
                });
        });
    });

});


text:
using Econometrics, Distributions, LinearAlgebra, Random

function GIVmoments(theta, y, x, inst)
	e = y - x*theta
	ms = e.*inst
end

function main()
# do the Monte Carlo
n = 100
sig = 1
reps = 1000
results = zeros(reps,3)
ystar = zeros(n)
for rep = 1:reps
	x = randn(n) # an exogenous regressor
	e = randn(n) # the error term
	# generate the dep var
	for t = 2:n
	  ystar[t] = 0.0 + 0.9*ystar[t-1] + 1.0*x[t] + e[t]
	end
    # add measurement error
	y = ystar + sig*randn(n)
	# now do GMM, using the data with meas. error in both dep. var. and regressor
	data = [y lag(y,1) x lags(x,2)];
    data = data[3:end,:] # drop first obsns, missing due to lags
    y = data[:,1]
    ylag = data[:,2]
    x = data[:,3]
    xlags = data[:,4:end]
    regressors = [ones(size(y)) ylag x]
	instruments = [ones(size(y)) x xlags]
    xhat = instruments*(instruments\regressors)
    thetahat = xhat\y
    ms = GIVmoments(thetahat, y, regressors, instruments)
    weight = inv(cov(ms))
    moments = theta-> GIVmoments(theta, y, regressors, instruments)
	junk, objvalue, junk, junk, junk = gmm(moments, thetahat, weight)
   	objvalue = size(y,1)*objvalue
	df = size(ms,2) - size(thetahat,1)
	reject = objvalue .> quantile.(Ref(Chisq(df)),[0.9 0.95 0.99]) # does the test reject at these signif levels?
    results[rep,:] = reject
end
cnames = ["10%", "5%", "1%"]
println("rejection frequencies, nominal 10% 5% and 1%:")
prettyprint(mean(results,dims=1),cnames)
return
end
main()


text:
package fr.lab.bbox.bboxapirunner.Application;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import fr.bouyguestelecom.bboxapi.bboxapi.Bbox;
import fr.bouyguestelecom.bboxapi.bboxapi.callback.IBboxStopApplication;
import fr.lab.bbox.bboxapirunner.R;
import okhttp3.Request;

/**
 * Created by dinh on 01/07/16.
 */
public class ApplicationStopAppFragment extends Fragment implements View.OnClickListener {

    private Button mButton;
    private Context ctxt;
    private Handler handler;
    private EditText packageNameEdit;
    private String packageName = " ";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_app_stop, container, false);

        mButton = (Button) view.findViewById(R.id.try_stopapp);
        mButton.setOnClickListener(this);
        packageNameEdit = (EditText) view.findViewById(R.id.app_stop_packagename);

        ctxt = getActivity().getApplicationContext();
        handler = new Handler();

        return view;
    }

    @Override
    public void onClick(final View v) {

        final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getContext().getApplicationContext());
        String ip = sharedPref.getString("bboxip", "");
        packageName = packageNameEdit.getText().toString();
        Bbox.getInstance().stopApp(ip,
                getResources().getString(fr.bouyguestelecom.bboxapi.R.string.APP_ID),
                getResources().getString(fr.bouyguestelecom.bboxapi.R.string.APP_SECRET),
                packageName,
                new IBboxStopApplication() {

                    @Override
                    public void onResponse() {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ctxt, "Stop app success", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onFailure(Request request, int errorCode) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ctxt, "Stop app failed", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
    }

}


text:
define([
    'jquery',
    'underscore',
    'orotranslation/js/translator',
    'routing',
    'oroui/js/tools',
    'oroui/js/mediator',
    './map-filter-module-name',
    './collection-filters-manager'
], function($, _, __, routing, tools, mediator, mapFilterModuleName, FiltersManager) {
    'use strict';

    var cachedFilters = {};

    var methods = {
        /**
         * Reads data from container, collects required modules and runs filters builder
         */
        initBuilder: function() {
            var modules;
            _.defaults(this.metadata, {filters: {}});
            modules = methods.collectModules.call(this);
            tools.loadModules(modules, function(modules) {
                this.modules = modules;
                methods.build.call(this);
            }, this);
        },

        /**
         * Collects required modules
         */
        collectModules: function() {
            var modules = {};
            _.each(this.metadata.filters || {}, function(filter) {
                var type = filter.type;
                modules[type] = mapFilterModuleName(type);
            });
            return modules;
        },

        build: function() {
            if (!this.collection || !this.modules) {
                return;
            }

            var filtersList;
            var options = methods.combineOptions.call(this);
            options.collection = this.collection;
            options.el = $('<div/>').prependTo(this.$el);
            filtersList = new FiltersManager(options);
            filtersList.render();
            mediator.trigger('datagrid_filters:rendered', this.collection, this.$el);
            this.metadata.state.filters = this.metadata.state.filters || [];
            if (this.collection.length === 0 && this.metadata.state.filters.length === 0) {
                filtersList.$el.hide();
            }

            this.grid.filterManager = filtersList;
            this.grid.trigger('filterManager:connected');

            this.deferred.resolve(filtersList);
        },

        /**
         * Process metadata and combines options for filters
         *
         * @returns {Object}
         */
        combineOptions: function() {
            var filters = {};
            var modules = this.modules;
            var collection = this.collection;
            _.each(this.metadata.filters, function(options) {
                if (_.has(options, 'name') && _.has(options, 'type')) {
                    // @TODO pass collection only for specific filters
                    if (options.type === 'selectrow') {
                        options.collection = collection;
                    }
                    if (options.lazy) {
                        options.loader = methods.createFilterLoader.call(this, options);
                    }
                    var Filter = modules[options.type].extend(options);
                    filters[options.name] = new Filter();
                }
            }, this);
            methods.loadFilters.call(this, this.metadata.options.gridName);

            return {
                filters: filters
            };
        },

        loadFilters: function(gridName) {
            var filterNames = _.map(this.filterLoaders, _.property('name'));
            if (!filterNames.length) {
                return;
            }

            _.chain(this.filterLoaders)
                .filter(_.property('useCache'))
                .each(function(loader) {
                    loader.success.call(this, cachedFilters[loader.cacheId]);
                });

            var params = {
                gridName: gridName,
                filterNames: _.map(this.filterLoaders, _.property('name'))
            };
            params[this.metadata.options.gridName] = this.metadata.gridParams;

            var url = routing.generate('oro_datagrid_filter_metadata', params);

            var self = this;
            $.get(url)
                .done(function(data) {
                    _.each(self.filterLoaders, function(loader) {
                        cachedFilters[data[loader.name].cacheId] = data[loader.name];
                        if (!loader.useCache) {
                            loader.success.call(this, data[loader.name]);
                        }
                    });
                })
                .fail(function() {
                    mediator.execute('showFlashMessage', 'error', __('oro.ui.unexpected_error'));
                });
        },

        createFilterLoader: function(filterOptions) {
            return _.bind(function(success) {
                this.filterLoaders.push({
                    name: filterOptions.name,
                    cacheId: filterOptions.cacheId,
                    success: success,
                    useCache: filterOptions.cacheId && cachedFilters[filterOptions.cacheId]
                });
            }, this);
        }
    };

    return {
        /**
         * Builder interface implementation
         *
         * @param {jQuery.Deferred} deferred
         * @param {Object} options
         * @param {jQuery} [options.$el] container for the grid
         * @param {string} [options.gridName] grid name
         * @param {Object} [options.gridPromise] grid builder's promise
         * @param {Object} [options.data] data for grid's collection
         * @param {Object} [options.metadata] configuration for the grid
         */
        init: function(deferred, options) {
            var self;
            self = {
                filterLoaders: [],
                deferred: deferred,
                $el: options.$el,
                gridName: options.gridName,
                metadata: options.metadata,
                collection: null,
                modules: null
            };

            methods.initBuilder.call(self);

            options.gridPromise.done(function(grid) {
                self.collection = grid.collection;
                self.grid = grid;
                methods.build.call(self);
            }).fail(function() {
                deferred.reject();
            });
        }
    };
});


text:
This gem is a Ruby implementation of the Schulze voting method (with help of the Floyd–Warshall algorithm),
a type of the Condorcet voting methods. It's the backend algorithm of [Agreeder](https://agreeder.com) and [Airesis](https://airesis.ue).

## Master

[![Build Status](https://travis-ci.org/coorasse/schulze-vote.svg?branch=master)](https://travis-ci.org/coorasse/schulze-vote)
[![Gem Version](https://badge.fury.io/rb/schulze-vote.svg)](https://badge.fury.io/rb/schulze-vote)

## Develop

[![Build Status](https://travis-ci.org/coorasse/schulze-vote.svg?branch=develop)](https://travis-ci.org/coorasse/schulze-vote)
[![Code Climate](https://codeclimate.com/github/coorasse/schulze-vote/badges/gpa.svg)](https://codeclimate.com/github/coorasse/schulze-vote)
[![Test Coverage](https://codeclimate.com/github/coorasse/schulze-vote/badges/coverage.svg)](https://codeclimate.com/github/coorasse/schulze-vote/coverage)

## Install

``` bash
gem install schulze-vote
```

Gemfile

``` ruby
gem 'schulze-vote', require: 'schulze_vote'
```

## Usage

``` ruby
require 'schulze_vote'
vote_list = <<EOF
C;A;B
C;B;A
A;B;C
A;C;B
B;C;A
B;A;C
EOF
schulze_basic = SchulzeBasic.do(vote_list, candidate_count)
schulze_classifications.classification_with_ties # shows the final classification
```

Input:

* `vote_list`
  * Array of Arrays: votes of each voter as weights `[ [1,2,3],[3,2,1],[1,1,2] ]`
  * String: "A;B;C\nB,A;C\n;3=C;B;A"
  * File: first line **must** be a single integer, following lines like vote_list type String (see vote lists under `examples` directory)
* `candidate_count` Integer: number of options
  * **required** for vote_list types of Array and String
  * leave empty if vote_list is a File

### String/File format:

A typical voters line looks like this:

```
A;B;C;D;E;F
```

You also can say that _n_ voters have the same preferences:

```
n=F;E;D;C;B;A
```

where _n_ is an integer value for the count.

Also it's possible to say that a voter has candidates equally weighted:

```
A,B;C,D;E,F
```

which means, that A + B, C + D and E + F are on the same weight level.

Here only 3 weight levels are used: (A,B) = 3, (C,D) = 2, (E,F) = 1

### Why I must write the candidate count in the first line of the vote file?

_or: Why I must give a candidate count value for Array/String inputs?_

Very easy: The reason is, that voters can leave out candidates (they give no special preferences).

So, schulze-vote needs to know, how many real candidates are in the voting process.

### Examples

#### Array

Only weight values, no letters here

``` ruby
require 'schulze_vote'
vote_list_array = [[3,2,1],[1,3,2],[3,1,2]]
vs = SchulzeBasic.do vote_list_array, 3
```

```
voter  => A D C B

weight => 4,1,2,3

A is on first position = highest prio == 4
B is on last position                 == 1
C is on third position                == 2
D is on second position               == 3
```

Next versions will have an automatic Preference-to-Weight algorithm.
(Internally only integers are used for calculation of ranking.)

#### String

``` ruby
require 'schulze_vote'
vote_list_string = <<EOF
A;B;C
B;C;A
A;C;B
A,C,B
4=C;A;B
EOF
vs = SchulzeBasic.do vote_list_string, 3
```

#### File

``` ruby
require 'schulze_vote'
vs = SchulzeBasic.do File.open('path/to/vote.list')
```

### SchulzeBasic

It doesn't matter if you start counting at 0 (zero) or 1 (one).

Also it's not important, if you use jumps (like `1 3 5 9`).

Internally it will only check if candidate X > candidate Y

Output:

* `.ranking` Array: numbers of total wins for each candidate `[candidate A, candidate B, candidate C, ...]`
* `.winners_array` Array: set 1 if the candidate is a potential winner `[candidate A, candidate B, candidate C, ...]`
* `.vote_matrix` Matrix: it contains the pairwise defeats
* `.play_matrix` Matrix: it contains the strongest paths
* `.result_matrix` Matrix: it contains the beat pairwise
* `.beat_couples` Array of Pairs: it contains the beat pairwise in array format
* `.ties` Array of Array: it contains the ties between candidates
* `.potential_winners` Array: it contains the possible winners

## Example

Example 1 from Wikipedia

<https://en.wikipedia.org/wiki/User:MarkusSchulze/Schulze_method_examples>

Result should be:

``` ruby
votestring = <<EOF
5=A;C;B;E;D
5=A;D;E;C;B
8=B;E;D;A;C
3=C;A;B;E;D
7=C;A;E;B;D
2=C;B;A;D;E
7=D;C;E;B;A
8=E;B;A;D;C
EOF
vs = SchulzeBasic.do(votestring, 5)
puts_m vs.vote_matrix

#=> [0, 20, 26, 30, 22]
    [25, 0, 16, 33, 18]
    [19, 29, 0, 17, 24]
    [15, 12, 28, 0, 14]
    [23, 27, 21, 31, 0]

puts_m vs.play_matrix

#=> [0, 28, 28, 30, 24]
    [25, 0, 28, 33, 24]
    [25, 29, 0, 29, 24]
    [25, 28, 28, 0, 24]
    [25, 28, 28, 31, 0]

puts vs.winners_array.to_s

#=> [0, 0, 0, 0, 1]

puts_m vs.result_matrix

#=> [0, 1, 1, 1, 0]
    [0, 0, 0, 1, 0]
    [0, 1, 0, 1, 0]
    [0, 0, 0, 0, 0]
    [1, 1, 1, 1, 0]

vs.classifications.each do |classification|
  puts classification.map { |e| idx_to_chr(e) }.to_s
end

#=> ["E", "A", "C", "B", "D"]
```

## Classifications

You have a `SchulzeClassifications.new(vs).classifications(limit_results = false)` that you can call.
If the number of results is greater then the `limit_results` parameter then a `TooManyClassificationsException`
is raised.
If you set this parameter to any value other then `false` be careful to catch and manage the exception properly.

## Classification with ties

You have a `SchulzeClassifications.new(vs).classification_with_ties` that you can call.
This method return a uniq classification in array of arrays format to display results on screen.
Please note that for cases like this: <https://en.wikipedia.org/wiki/User:MarkusSchulze/Schulze_method_examples#Example_4>
it will return the following: [[B,D], [A,C]]

## Tests

Run `bundle exec rspec` to run tests.

### Random votation generator

You can run `bundle exec ruby spec/example_generator.rb [CANDIDATES_NUM] [VOTES_NUM] to generate a random election file in the `examples` folder.

## Contributing to schulze-vote

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
* Fork the project
* Use git-flow
* Start a feature/bugfix branch
* Commit and push until you are happy with your contribution
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

## Problems? Questions?

[![Alessandro Rodi](http://www.gravatar.com/avatar/32d80da41830a6e6c1bb3eb977537e3e)](https://github.com/coorasse)

## Thanks

Thanks to Christoph Grabo for providing the idea and base code of the gem

## Links

* [Schulze method](http://en.wikipedia.org/wiki/Schulze_method) ([deutsch](http://de.wikipedia.org/wiki/Schulze-Methode))
* [Schulze method examples](https://en.wikipedia.org/wiki/User:MarkusSchulze/Schulze_method_examples)
* [Floyd-Warshall algorithm](http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm)

## Copyright

See LICENSE for further details.


text:
package org.apache.commons.configuration2;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.configuration2.SynchronizerTestImpl.Methods;
import org.apache.commons.configuration2.builder.FileBasedBuilderParametersImpl;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.sync.ReadWriteSynchronizer;
import org.apache.commons.configuration2.tree.DefaultExpressionEngine;
import org.apache.commons.configuration2.tree.DefaultExpressionEngineSymbols;
import org.apache.commons.configuration2.tree.ImmutableNode;
import org.apache.commons.configuration2.tree.NodeHandler;
import org.apache.commons.configuration2.tree.NodeNameMatchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

/**
 * Test class for {@code INIConfiguration}.
 *
 * @version $Id$
 */
public class TestINIConfiguration
{
    private static String LINE_SEPARATOR = System.getProperty("line.separator");

    /** Constant for the content of an ini file. */
    private static final String INI_DATA = "[section1]" + LINE_SEPARATOR
            + "var1 = foo" + LINE_SEPARATOR + "var2 = 451" + LINE_SEPARATOR
            + LINE_SEPARATOR + "[section2]" + LINE_SEPARATOR + "var1 = 123.45"
            + LINE_SEPARATOR + "var2 = bar" + LINE_SEPARATOR + LINE_SEPARATOR
            + "[section3]" + LINE_SEPARATOR + "var1 = true" + LINE_SEPARATOR
            + "interpolated = ${section3.var1}" + LINE_SEPARATOR
            + "multi = foo" + LINE_SEPARATOR + "multi = bar" + LINE_SEPARATOR
            + LINE_SEPARATOR;

    private static final String INI_DATA2 = "[section4]" + LINE_SEPARATOR
            + "var1 = \"quoted value\"" + LINE_SEPARATOR
            + "var2 = \"quoted value\\nwith \\\"quotes\\\"\"" + LINE_SEPARATOR
            + "var3 = 123 ; comment" + LINE_SEPARATOR
            + "var4 = \"1;2;3\" ; comment" + LINE_SEPARATOR
            + "var5 = '\\'quoted\\' \"value\"' ; comment" + LINE_SEPARATOR
            + "var6 = \"\"" + LINE_SEPARATOR;

    private static final String INI_DATA3 = "[section5]" + LINE_SEPARATOR
            + "multiLine = one \\" + LINE_SEPARATOR
            + "    two      \\" + LINE_SEPARATOR
            + " three" + LINE_SEPARATOR
            + "singleLine = C:\\Temp\\" + LINE_SEPARATOR
            + "multiQuoted = one \\" + LINE_SEPARATOR
            + "\"  two  \" \\" + LINE_SEPARATOR
            + "  three" + LINE_SEPARATOR
            + "multiComment = one \\ ; a comment" + LINE_SEPARATOR
            + "two" + LINE_SEPARATOR
            + "multiQuotedComment = \" one \" \\ ; comment" + LINE_SEPARATOR
            + "two" + LINE_SEPARATOR
            + "noFirstLine = \\" + LINE_SEPARATOR
            + "  line 2" + LINE_SEPARATOR
            + "continueNoLine = one \\" + LINE_SEPARATOR;

    private static final String INI_DATA_SEPARATORS = "[section]"
            + LINE_SEPARATOR + "var1 = value1" + LINE_SEPARATOR
            + "var2 : value2" + LINE_SEPARATOR
            + "var3=value3" + LINE_SEPARATOR
            + "var4:value4" + LINE_SEPARATOR
            + "var5 : value=5" + LINE_SEPARATOR
            + "var:6=value" + LINE_SEPARATOR
            + "var:7=\"value7\"" + LINE_SEPARATOR
            + "var:8 =  \"value8\"" + LINE_SEPARATOR;

    /** An ini file that contains only a property in the global section. */
    private static final String INI_DATA_GLOBAL_ONLY = "globalVar = testGlobal"
            + LINE_SEPARATOR + LINE_SEPARATOR;

    /** An ini file with a global section. */
    private static final String INI_DATA_GLOBAL = INI_DATA_GLOBAL_ONLY
            + INI_DATA;

    /** A helper object for creating temporary files. */
    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    /**
     * Creates a INIConfiguration object that is initialized from
     * the given data.
     *
     * @param data the data of the configuration (an ini file as string)
     * @return the initialized configuration
     * @throws ConfigurationException if an error occurs
     */
    private static INIConfiguration setUpConfig(String data)
            throws ConfigurationException
    {
        INIConfiguration instance = new INIConfiguration();
        instance.setListDelimiterHandler(new DefaultListDelimiterHandler(','));
        load(instance, data);
        return instance;
    }

    /**
     * Loads the specified content into the given configuration instance.
     *
     * @param instance the configuration
     * @param data the data to be loaded
     * @throws ConfigurationException if an error occurs
     */
    private static void load(INIConfiguration instance, String data)
            throws ConfigurationException
    {
        StringReader reader = new StringReader(data);
        try
        {
            instance.read(reader);
        }
        catch (IOException e)
        {
            throw new ConfigurationException(e);
        }
        reader.close();
    }

    /**
     * Saves the specified configuration to a string. The string can be compared
     * with an expected value or again loaded into a configuration.
     *
     * @param config the configuration to be saved
     * @return the content of this configuration saved to a string
     * @throws ConfigurationException if an error occurs
     */
    private static String saveToString(INIConfiguration config)
            throws ConfigurationException
    {
        StringWriter writer = new StringWriter();
        try
        {
            config.write(writer);
        }
        catch (IOException e)
        {
            throw new ConfigurationException(e);
        }
        return writer.toString();
    }

    /**
     * Writes a test ini file.
     *
     * @param content the content of the file
     * @return the newly created file
     * @throws IOException if an error occurs
     */
    private File writeTestFile(String content) throws IOException
    {
        File file = folder.newFile();
        PrintWriter out = new PrintWriter(new FileWriter(file));
        try
        {
            out.println(content);
        }
        finally
        {
            out.close();
        }
        return file;
    }

    /**
     * Test of save method, of class {@link INIConfiguration}.
     */
    @Test
    public void testSave() throws Exception
    {
        Writer writer = new StringWriter();
        INIConfiguration instance = new INIConfiguration();
        instance.addProperty("section1.var1", "foo");
        instance.addProperty("section1.var2", "451");
        instance.addProperty("section2.var1", "123.45");
        instance.addProperty("section2.var2", "bar");
        instance.addProperty("section3.var1", "true");
        instance.addProperty("section3.interpolated", "${section3.var1}");
        instance.addProperty("section3.multi", "foo");
        instance.addProperty("section3.multi", "bar");
        instance.write(writer);

        assertEquals("Wrong content of ini file", INI_DATA, writer.toString());
    }

    /**
     * Helper method for testing a save operation. This method constructs a
     * configuration from the specified content string. Then it saves this
     * configuration and checks whether the result matches the original content.
     *
     * @param content the content of the configuration
     * @throws ConfigurationException if an error occurs
     */
    private void checkSave(String content) throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(content);
        String sOutput = saveToString(config);
        assertEquals("Wrong content of ini file", content, sOutput);
    }

    /**
     * Tests saving a configuration that contains a global section.
     */
    @Test
    public void testSaveWithGlobalSection() throws ConfigurationException
    {
        checkSave(INI_DATA_GLOBAL);
    }

    /**
     * Tests whether a configuration that contains only a global section can be
     * saved correctly.
     */
    @Test
    public void testSaveWithOnlyGlobalSection() throws ConfigurationException
    {
        checkSave(INI_DATA_GLOBAL_ONLY);
    }

    /**
     * Tests whether list delimiter parsing can be disabled.
     */
    @Test
    public void testSaveWithDelimiterParsingDisabled()
            throws ConfigurationException
    {
        INIConfiguration config = new INIConfiguration();
        String data =
                INI_DATA.substring(0, INI_DATA.length() - LINE_SEPARATOR.length())
                        + "nolist = 1,2, 3";
        load(config, data);
        assertEquals("Wrong property value", "1,2, 3",
                config.getString("section3.nolist"));
        String content = saveToString(config);
        INIConfiguration config2 = new INIConfiguration();
        load(config2, content);
        assertEquals("Wrong property value after reload", "1,2, 3",
                config2.getString("section3.nolist"));
    }

    /**
     * Test of load method, of class {@link INIConfiguration}.
     */
    @Test
    public void testLoad() throws Exception
    {
        checkLoad(INI_DATA);
    }

    /**
     * Tests the load() method when the alternative value separator is used (a
     * ':' for '=').
     */
    @Test
    public void testLoadAlternativeSeparator() throws Exception
    {
        checkLoad(INI_DATA.replace('=', ':'));
    }

    /**
     * Tests whether an instance can be created using a file-based builder.
     */
    @Test
    public void testLoadFromBuilder() throws ConfigurationException,
            IOException
    {
        File file = writeTestFile(INI_DATA);
        FileBasedConfigurationBuilder<INIConfiguration> builder =
                new FileBasedConfigurationBuilder<INIConfiguration>(
                        INIConfiguration.class);
        builder.configure(new FileBasedBuilderParametersImpl()
                .setFile(file));
        INIConfiguration config = builder.getConfiguration();
        checkContent(config);
    }

    /**
     * Tests the values of some properties to ensure that the configuration was
     * correctly loaded.
     *
     * @param instance the configuration to check
     */
    private void checkContent(INIConfiguration instance)
    {
        assertEquals("var1", "foo", instance.getString("section1.var1"));
        assertEquals("var2", 451, instance.getInt("section1.var2"));
        assertEquals("section2.var1", 123.45,
                instance.getDouble("section2.var1"), .001);
        assertEquals("section2.var2", "bar",
                instance.getString("section2.var2"));
        assertEquals("section3.var1", true,
                instance.getBoolean("section3.var1"));
        assertEquals("Wrong number of sections", 3, instance.getSections()
                .size());
        assertTrue(
                "Wrong sections",
                instance.getSections().containsAll(
                        Arrays.asList("section1", "section2", "section3")));
    }

    /**
     * Helper method for testing the load operation. Loads the specified content
     * into a configuration and then checks some properties.
     *
     * @param data the data to load
     */
    private void checkLoad(String data) throws ConfigurationException
    {
        INIConfiguration instance = setUpConfig(data);
        checkContent(instance);
    }

    /**
     * Test of isCommentLine method, of class
     * {@link INIConfiguration}.
     */
    @Test
    public void testIsCommentLine()
    {
        INIConfiguration instance = new INIConfiguration();
        assertTrue(instance.isCommentLine("#comment1"));
        assertTrue(instance.isCommentLine(";comment1"));
        assertFalse(instance.isCommentLine("nocomment=true"));
        assertFalse(instance.isCommentLine(null));
    }

    /**
     * Test of isSectionLine method, of class
     * {@link INIConfiguration}.
     */
    @Test
    public void testIsSectionLine()
    {
        INIConfiguration instance = new INIConfiguration();
        assertTrue(instance.isSectionLine("[section]"));
        assertFalse(instance.isSectionLine("nosection=true"));
        assertFalse(instance.isSectionLine(null));
    }

    /**
     * Test of getSections method, of class {@link INIConfiguration}
     * .
     */
    @Test
    public void testGetSections()
    {
        INIConfiguration instance = new INIConfiguration();
        instance.addProperty("test1.foo", "bar");
        instance.addProperty("test2.foo", "abc");
        Set<String> expResult = new HashSet<String>();
        expResult.add("test1");
        expResult.add("test2");
        Set<String> result = instance.getSections();
        assertEquals(expResult, result);
    }

    @Test
    public void testQuotedValue() throws Exception
    {
        INIConfiguration config = setUpConfig(INI_DATA2);
        assertEquals("value", "quoted value", config.getString("section4.var1"));
    }

    @Test
    public void testQuotedValueWithQuotes() throws Exception
    {
        INIConfiguration config = setUpConfig(INI_DATA2);
        assertEquals("value", "quoted value\\nwith \"quotes\"", config
                .getString("section4.var2"));
    }

    @Test
    public void testValueWithComment() throws Exception
    {
        INIConfiguration config = setUpConfig(INI_DATA2);
        assertEquals("value", "123", config.getString("section4.var3"));
    }

    @Test
    public void testQuotedValueWithComment() throws Exception
    {
        INIConfiguration config = setUpConfig(INI_DATA2);
        assertEquals("value", "1;2;3", config.getString("section4.var4"));
    }

    @Test
    public void testQuotedValueWithSingleQuotes() throws Exception
    {
        INIConfiguration config = setUpConfig(INI_DATA2);
        assertEquals("value", "'quoted' \"value\"", config
                .getString("section4.var5"));
    }

    @Test
    public void testWriteValueWithCommentChar() throws Exception
    {
        INIConfiguration config = new INIConfiguration();
        config.setProperty("section.key1", "1;2;3");

        StringWriter writer = new StringWriter();
        config.write(writer);

        INIConfiguration config2 = new INIConfiguration();
        config2.read(new StringReader(writer.toString()));

        assertEquals("value", "1;2;3", config2.getString("section.key1"));
    }

    /**
     * Tests whether whitespace is left unchanged for quoted values.
     */
    @Test
    public void testQuotedValueWithWhitespace() throws Exception
    {
        final String content = "CmdPrompt = \" [test@cmd ~]$ \"";
        INIConfiguration config = setUpConfig(content);
        assertEquals("Wrong propert value", " [test@cmd ~]$ ", config
                .getString("CmdPrompt"));
    }

    /**
     * Tests a quoted value with space and a comment.
     */
    @Test
    public void testQuotedValueWithWhitespaceAndComment() throws Exception
    {
        final String content = "CmdPrompt = \" [test@cmd ~]$ \" ; a comment";
        INIConfiguration config = setUpConfig(content);
        assertEquals("Wrong propert value", " [test@cmd ~]$ ", config
                .getString("CmdPrompt"));
    }

    /**
     * Tests an empty quoted value.
     */
    @Test
    public void testQuotedValueEmpty() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA2);
        assertEquals("Wrong value for empty property", "", config
                .getString("section4.var6"));
    }

    /**
     * Tests a property that has no value.
     */
    @Test
    public void testGetPropertyNoValue() throws ConfigurationException
    {
        final String data = INI_DATA2 + LINE_SEPARATOR + "noValue ="
                + LINE_SEPARATOR;
        INIConfiguration config = setUpConfig(data);
        assertEquals("Wrong value of key", "", config
                .getString("section4.noValue"));
    }

    /**
     * Tests a property that has no key.
     */
    @Test
    public void testGetPropertyNoKey() throws ConfigurationException
    {
        final String data = INI_DATA2 + LINE_SEPARATOR + "= noKey"
                + LINE_SEPARATOR;
        INIConfiguration config = setUpConfig(data);
        assertEquals("Cannot find property with no key", "noKey", config
                .getString("section4. "));
    }

    /**
     * Tests reading a property from the global section.
     */
    @Test
    public void testGlobalProperty() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
        assertEquals("Wrong value of global property", "testGlobal", config
                .getString("globalVar"));
    }

    /**
     * Tests whether the sub configuration for the global section is connected
     * to its parent.
     */
    @Test
    public void testGlobalSectionConnected() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
        HierarchicalConfiguration<ImmutableNode> sub = config.getSection(null);
        config.setProperty("globalVar", "changed");
        assertEquals("Wrong value in sub", "changed",
                sub.getString("globalVar"));
    }

    /**
     * Tests whether the specified configuration contains exactly the expected
     * sections.
     *
     * @param config the configuration to check
     * @param expected an array with the expected sections
     */
    private void checkSectionNames(INIConfiguration config,
            String[] expected)
    {
        Set<String> sectionNames = config.getSections();
        Iterator<String> it = sectionNames.iterator();
        for (int idx = 0; idx < expected.length; idx++)
        {
            assertEquals("Wrong section at " + idx, expected[idx], it.next());
        }
        assertFalse("Too many sections", it.hasNext());
    }

    /**
     * Tests the names of the sections returned by the configuration.
     *
     * @param data the data of the ini configuration
     * @param expected the expected section names
     * @return the configuration instance
     */
    private INIConfiguration checkSectionNames(String data,
            String[] expected) throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(data);
        checkSectionNames(config, expected);
        return config;
    }

    /**
     * Tests querying the sections if a global section if available.
     */
    @Test
    public void testGetSectionsWithGlobal() throws ConfigurationException
    {
        checkSectionNames(INI_DATA_GLOBAL, new String[]{
                null, "section1", "section2", "section3"
        });
    }

    /**
     * Tests querying the sections if there is no global section.
     */
    @Test
    public void testGetSectionsNoGlobal() throws ConfigurationException
    {
        checkSectionNames(INI_DATA, new String[]{
                "section1", "section2", "section3"
        });
    }

    /**
     * Tests whether the sections of a configuration can be queried that
     * contains only a global section.
     */
    @Test
    public void testGetSectionsGlobalOnly() throws ConfigurationException
    {
        checkSectionNames(INI_DATA_GLOBAL_ONLY, new String[]{
                null
        });
    }

    /**
     * Tests whether variables containing a dot are not misinterpreted as
     * sections. This test is related to CONFIGURATION-327.
     */
    @Test
    public void testGetSectionsDottedVar() throws ConfigurationException
    {
        final String data = "dotted.var = 1" + LINE_SEPARATOR + INI_DATA_GLOBAL;
        INIConfiguration config = checkSectionNames(data,
                new String[] {
                        null, "section1", "section2", "section3"
                });
        assertEquals("Wrong value of dotted variable", 1, config
                .getInt("dotted..var"));
    }

    /**
     * Tests whether a section added later is also found by getSections().
     */
    @Test
    public void testGetSectionsAdded() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA2);
        config.addProperty("section5.test", Boolean.TRUE);
        checkSectionNames(config, new String[]{
                "section4", "section5"
        });
    }

    /**
     * Tests querying the properties of an existing section.
     */
    @Test
    public void testGetSectionExisting() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA);
        HierarchicalConfiguration<ImmutableNode> section =
                config.getSection("section1");
        assertEquals("Wrong value of var1", "foo", section.getString("var1"));
        assertEquals("Wrong value of var2", "451", section.getString("var2"));
    }

    /**
     * Tests whether the sub configuration returned by getSection() is connected
     * to the parent.
     */
    @Test
    public void testGetSectionConnected() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA);
        HierarchicalConfiguration<ImmutableNode> section =
                config.getSection("section1");
        section.setProperty("var1", "foo2");
        assertEquals("Not connected to parent", "foo2",
                config.getString("section1.var1"));
    }

    /**
     * Tests querying the properties of a section that was merged from two
     * sections with the same name.
     */
    @Test
    public void testGetSectionMerged() throws ConfigurationException
    {
        final String data = INI_DATA + "[section1]" + LINE_SEPARATOR
                + "var3 = merged" + LINE_SEPARATOR;
        INIConfiguration config = setUpConfig(data);
        HierarchicalConfiguration<ImmutableNode> section = config.getSection("section1");
        assertEquals("Wrong value of var1", "foo", section.getString("var1"));
        assertEquals("Wrong value of var2", "451", section.getString("var2"));
        assertEquals("Wrong value of var3", "merged", section.getString("var3"));
    }

    /**
     * Tests querying the content of the global section.
     */
    @Test
    public void testGetSectionGlobal() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
        HierarchicalConfiguration<ImmutableNode> section = config.getSection(null);
        assertEquals("Wrong value of global variable", "testGlobal", section
                .getString("globalVar"));
    }

    /**
     * Tests concurrent access to the global section.
     */
    @Test
    public void testGetSectionGloabalMultiThreaded()
            throws ConfigurationException, InterruptedException
    {
        INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
        config.setSynchronizer(new ReadWriteSynchronizer());
        final int threadCount = 10;
        GlobalSectionTestThread[] threads = new GlobalSectionTestThread[threadCount];
        for (int i = 0; i < threadCount; i++)
        {
            threads[i] = new GlobalSectionTestThread(config);
            threads[i].start();
        }
        for (int i = 0; i < threadCount; i++)
        {
            threads[i].join();
            assertFalse("Exception occurred", threads[i].error);
        }
    }

    /**
     * Tests querying the content of the global section if there is none.
     */
    @Test
    public void testGetSectionGlobalNonExisting() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA);
        HierarchicalConfiguration<ImmutableNode> section = config.getSection(null);
        assertTrue("Sub config not empty", section.isEmpty());
    }

    /**
     * Tests querying a non existing section.
     */
    @Test
    public void testGetSectionNonExisting() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA);
        HierarchicalConfiguration<ImmutableNode> section = config
                .getSection("Non existing section");
        assertTrue("Sub config not empty", section.isEmpty());
    }

    /**
     * Tests a property whose value spans multiple lines.
     */
    @Test
    public void testLineContinuation() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA3);
        assertEquals("Wrong value", "one" + LINE_SEPARATOR + "two"
                + LINE_SEPARATOR + "three", config
                .getString("section5.multiLine"));
    }

    /**
     * Tests a property value that ends on a backslash, which is no line
     * continuation character.
     */
    @Test
    public void testLineContinuationNone() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA3);
        assertEquals("Wrong value", "C:\\Temp\\", config
                .getString("section5.singleLine"));
    }

    /**
     * Tests a property whose value spans multiple lines when quoting is
     * involved. In this case whitespace must not be trimmed.
     */
    @Test
    public void testLineContinuationQuoted() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA3);
        assertEquals("Wrong value", "one" + LINE_SEPARATOR + "  two  "
                + LINE_SEPARATOR + "three", config
                .getString("section5.multiQuoted"));
    }

    /**
     * Tests a property whose value spans multiple lines with a comment.
     */
    @Test
    public void testLineContinuationComment() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA3);
        assertEquals("Wrong value", "one" + LINE_SEPARATOR + "two", config
                .getString("section5.multiComment"));
    }

    /**
     * Tests a property with a quoted value spanning multiple lines and a
     * comment.
     */
    @Test
    public void testLineContinuationQuotedComment()
            throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA3);
        assertEquals("Wrong value", " one " + LINE_SEPARATOR + "two", config
                .getString("section5.multiQuotedComment"));
    }

    /**
     * Tests a multi-line property value with an empty line.
     */
    @Test
    public void testLineContinuationEmptyLine() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA3);
        assertEquals("Wrong value", LINE_SEPARATOR + "line 2", config
                .getString("section5.noFirstLine"));
    }

    /**
     * Tests a line continuation at the end of the file.
     */
    @Test
    public void testLineContinuationAtEnd() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA3);
        assertEquals("Wrong value", "one" + LINE_SEPARATOR, config
                .getString("section5.continueNoLine"));
    }

    /**
     * Tests whether a configuration can be saved that contains section keys
     * with delimiter characters. This test is related to CONFIGURATION-409.
     */
    @Test
    public void testSaveKeysWithDelimiters() throws ConfigurationException, IOException
    {
        INIConfiguration conf = new INIConfiguration();
        final String section = "Section..with..dots";
        conf.addProperty(section + ".test1", "test1");
        conf.addProperty(section + ".test2", "test2");
        StringWriter writer = new StringWriter();
        conf.write(writer);
        conf = new INIConfiguration();
        conf.read(new StringReader(writer.toString()));
        assertEquals("Wrong value (1)", "test1", conf.getString(section + ".test1"));
        assertEquals("Wrong value (2)", "test2", conf.getString(section + ".test2"));
    }

    /**
     * Tests whether a value which contains a semicolon can be loaded
     * successfully. This test is related to CONFIGURATION-434.
     */
    @Test
    public void testValueWithSemicolon() throws ConfigurationException
    {
        final String path =
                "C:\\Program Files\\jar\\manage.jar;"
                        + "C:\\Program Files\\jar\\guiLauncher.jar";
        final String content =
                "[Environment]" + LINE_SEPARATOR + "Application Type=any"
                        + LINE_SEPARATOR + "Class Path=" + path + "  ;comment"
                        + LINE_SEPARATOR + "Path=" + path
                        + "\t; another comment";
        INIConfiguration config = setUpConfig(content);
        assertEquals("Wrong class path", path,
                config.getString("Environment.Class Path"));
        assertEquals("Wrong path", path, config.getString("Environment.Path"));
    }

    /**
     * Tests whether the different separators with or without whitespace are
     * recognized.
     */
    @Test
    public void testSeparators() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_SEPARATORS);
        for (int i = 1; i <= 4; i++)
        {
            assertEquals("Wrong value", "value" + i,
                    config.getString("section.var" + i));
        }
    }

    /**
     * Tests property definitions containing multiple separators.
     */
    @Test
    public void testMultipleSeparators() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_SEPARATORS);
        assertEquals("Wrong value for var5", "value=5",
                config.getString("section.var5"));
        assertEquals("Wrong value for var6", "6=value",
                config.getString("section.var"));
    }

    /**
     * Tests property definitions containing multiple separators that are
     * quoted.
     */
    @Test
    public void testMultipleSeparatorsQuoted() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_SEPARATORS);
        assertEquals("Wrong value for var7", "value7",
                config.getString("section.var:7"));
        assertEquals("Wrong value for var8", "value8",
                config.getString("section.var:8"));
    }

    /**
     * Tests whether a section that has been cleared can be manipulated and
     * saved later.
     */
    @Test
    public void testSaveClearedSection() throws ConfigurationException, IOException
    {
        final String data = "[section]\ntest = failed\n";
        INIConfiguration config = setUpConfig(data);
        SubnodeConfiguration sub = config.getSection("section");
        assertFalse("No content", sub.isEmpty());
        sub.clear();
        sub.close();
        sub = config.getSection("section");
        sub.setProperty("test", "success");
        StringWriter writer = new StringWriter();
        config.write(writer);
        HierarchicalConfiguration<?> config2 = setUpConfig(writer.toString());
        assertEquals("Wrong value", "success",
                config2.getString("section.test"));
    }

    /**
     * Tests whether a duplicate session is merged.
     */
    @Test
    public void testMergeDuplicateSection() throws ConfigurationException, IOException
    {
        final String data =
                "[section]\nvar1 = sec1\n\n" + "[section]\nvar2 = sec2\n";
        INIConfiguration config = setUpConfig(data);
        assertEquals("Wrong value 1", "sec1", config.getString("section.var1"));
        assertEquals("Wrong value 2", "sec2", config.getString("section.var2"));
        HierarchicalConfiguration<ImmutableNode> sub = config.getSection("section");
        assertEquals("Wrong sub value 1", "sec1", sub.getString("var1"));
        assertEquals("Wrong sub value 2", "sec2", sub.getString("var2"));
        StringWriter writer = new StringWriter();
        config.write(writer);
        String content = writer.toString();
        int pos = content.indexOf("[section]");
        assertTrue("Section not found: " + content, pos >= 0);
        assertTrue("Section found multiple times: " + content,
                content.indexOf("[section]", pos + 1) < 0);
    }

    /**
     * Tests whether a section that was created by getSection() can be
     * manipulated.
     */
    @Test
    public void testGetSectionNonExistingManipulate()
            throws ConfigurationException, IOException
    {
        INIConfiguration config = setUpConfig(INI_DATA);
        HierarchicalConfiguration<ImmutableNode> section = config.getSection("newSection");
        section.addProperty("test", "success");
        assertEquals("Main config not updated", "success",
                config.getString("newSection.test"));
        StringWriter writer = new StringWriter();
        config.write(writer);
        INIConfiguration config2 = setUpConfig(writer.toString());
        section = config2.getSection("newSection");
        assertEquals("Wrong value", "success", section.getString("test"));
    }

    /**
     * Tests whether getSection() can deal with duplicate sections.
     */
    @Test
    public void testGetSectionDuplicate()
    {
        INIConfiguration config =
                new INIConfiguration();
        config.addProperty("section.var1", "value1");
        config.addProperty("section(-1).var2", "value2");
        HierarchicalConfiguration<ImmutableNode> section = config.getSection("section");
        Iterator<String> keys = section.getKeys();
        assertEquals("Wrong key", "var1", keys.next());
        assertFalse("Too many keys", keys.hasNext());
    }

    /**
     * Tests whether the list delimiter character is recognized.
     */
    @Test
    public void testValueWithDelimiters() throws ConfigurationException
    {
        INIConfiguration config =
                setUpConfig("[test]" + LINE_SEPARATOR + "list=1,2,3"
                        + LINE_SEPARATOR);
        List<Object> list = config.getList("test.list");
        assertEquals("Wrong number of elements", 3, list.size());
        assertEquals("Wrong element at 1", "1", list.get(0));
        assertEquals("Wrong element at 2", "2", list.get(1));
        assertEquals("Wrong element at 3", "3", list.get(2));
    }

    /**
     * Tests whether parsing of lists can be disabled.
     */
    @Test
    public void testListParsingDisabled() throws ConfigurationException
    {
        INIConfiguration config =
                new INIConfiguration();
        load(config, "[test]" + LINE_SEPARATOR + "nolist=1,2,3");
        assertEquals("Wrong value", "1,2,3", config.getString("test.nolist"));
    }

    /**
     * Tests whether synchronization is performed when querying the
     * configuration's sections.
     */
    @Test
    public void testGetSectionsSynchronized() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA);
        SynchronizerTestImpl sync = new SynchronizerTestImpl();
        config.setSynchronizer(sync);
        assertFalse("No sections", config.getSections().isEmpty());
        sync.verify(Methods.BEGIN_READ, Methods.END_READ);
    }

    /**
     * Tests whether the configuration deals correctly with list delimiters.
     */
    @Test
    public void testListDelimiterHandling() throws ConfigurationException
    {
        INIConfiguration config = new INIConfiguration();
        config.setListDelimiterHandler(new DefaultListDelimiterHandler(','));
        config.addProperty("list", "a,b,c");
        config.addProperty("listesc", "3\\,1415");
        String output = saveToString(config);
        INIConfiguration config2 = setUpConfig(output);
        assertEquals("Wrong list size", 3, config2.getList("list").size());
        assertEquals("Wrong list element", "b", config2.getList("list").get(1));
        assertEquals("Wrong escaped list element", "3,1415",
                config2.getString("listesc"));
    }

    /**
     * Tests whether property values are correctly escaped even if they are part
     * of a property with multiple values.
     */
    @Test
    public void testListDelimiterHandlingInList() throws ConfigurationException
    {
        String data =
                INI_DATA + "[sectest]" + LINE_SEPARATOR
                        + "list = 3\\,1415,pi,\\\\Test\\,5" + LINE_SEPARATOR;
        INIConfiguration config = setUpConfig(data);
        INIConfiguration config2 = setUpConfig(saveToString(config));
        List<Object> list = config2.getList("sectest.list");
        assertEquals("Wrong number of values", 3, list.size());
        assertEquals("Wrong element 1", "3,1415", list.get(0));
        assertEquals("Wrong element 3", "\\Test,5", list.get(2));
    }

    /**
     * Tests whether only properties with values occur in the enumeration of the
     * global section.
     */
    @Test
    public void testKeysOfGlobalSection() throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
        HierarchicalConfiguration<ImmutableNode> sub = config.getSection(null);
        Iterator<String> keys = sub.getKeys();
        assertEquals("Wrong key", "globalVar", keys.next());
        if (keys.hasNext())
        {
            StringBuilder buf = new StringBuilder();
            do
            {
                buf.append(keys.next()).append(' ');
            } while (keys.hasNext());
            fail("Got additional keys: " + buf);
        }
    }

    /**
     * Tests whether the node handler of a global section correctly filters
     * named children.
     */
    @Test
    public void testGlobalSectionNodeHandlerGetChildrenByName()
            throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
        SubnodeConfiguration sub = config.getSection(null);
        NodeHandler<ImmutableNode> handler = sub.getModel().getNodeHandler();
        assertTrue(
                "Sections not filtered",
                handler.getChildren(
                        sub.getModel().getNodeHandler().getRootNode(),
                        "section1").isEmpty());
    }

    /**
     * Tests whether the node handler of a global section correctly determines
     * the number of children.
     */
    @Test
    public void testGlobalSectionNodeHandlerGetChildrenCount()
            throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
        SubnodeConfiguration sub = config.getSection(null);
        NodeHandler<ImmutableNode> handler = sub.getModel().getNodeHandler();
        assertEquals("Wrong number of children", 1,
                handler.getChildrenCount(handler.getRootNode(), null));
    }

    /**
     * Tests whether the node handler of a global section correctly returns a
     * child by index.
     */
    @Test
    public void testGlobalSectionNodeHandlerGetChildByIndex()
            throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
        SubnodeConfiguration sub = config.getSection(null);
        NodeHandler<ImmutableNode> handler = sub.getModel().getNodeHandler();
        ImmutableNode child = handler.getChild(handler.getRootNode(), 0);
        assertEquals("Wrong child", "globalVar", child.getNodeName());
        try
        {
            handler.getChild(handler.getRootNode(), 1);
            fail("Could obtain child with invalid index!");
        }
        catch (IndexOutOfBoundsException iex)
        {
            // ok
        }
    }

    /**
     * Tests whether the node handler of a global section correctly determines
     * the index of a child.
     */
    @Test
    public void testGlobalSectionNodeHandlerIndexOfChild()
            throws ConfigurationException
    {
        INIConfiguration config = setUpConfig(INI_DATA_GLOBAL);
        SubnodeConfiguration sub = config.getSection(null);
        NodeHandler<ImmutableNode> handler = sub.getModel().getNodeHandler();
        List<ImmutableNode> children = handler.getRootNode().getChildren();
        assertEquals("Wrong index", 0,
                handler.indexOfChild(handler.getRootNode(), children.get(0)));
        assertEquals("Wrong index of section child", -1,
                handler.indexOfChild(handler.getRootNode(), children.get(1)));
    }

    /**
     * Tests whether an expression engine can be used which ignores case.
     */
    @Test
    public void testExpressionEngineIgnoringCase()
            throws ConfigurationException
    {
        DefaultExpressionEngine engine =
                new DefaultExpressionEngine(
                        DefaultExpressionEngineSymbols.DEFAULT_SYMBOLS,
                        NodeNameMatchers.EQUALS_IGNORE_CASE);
        INIConfiguration config = new INIConfiguration();
        config.setExpressionEngine(engine);
        load(config, INI_DATA);

        checkContent(config);
        assertEquals("Wrong result (1)", "foo",
                config.getString("Section1.var1"));
        assertEquals("Wrong result (2)", "foo",
                config.getString("section1.Var1"));
        assertEquals("Wrong result (1)", "foo",
                config.getString("SECTION1.VAR1"));
    }

    /**
     * A thread class for testing concurrent access to the global section.
     */
    private static class GlobalSectionTestThread extends Thread
    {
        /** The configuration. */
        private final INIConfiguration config;

        /** A flag whether an error was found. */
        volatile boolean error;

        /**
         * Creates a new instance of <code>GlobalSectionTestThread</code> and
         * initializes it.
         *
         * @param conf the configuration object
         */
        public GlobalSectionTestThread(INIConfiguration conf)
        {
            config = conf;
        }

        /**
         * Accesses the global section in a loop. If there is no correct
         * synchronization, this can cause an exception.
         */
        @Override
        public void run()
        {
            final int loopCount = 250;

            for (int i = 0; i < loopCount && !error; i++)
            {
                try
                {
                    config.getSection(null);
                }
                catch (IllegalStateException istex)
                {
                    error = true;
                }
            }
        }
    }
}


text:
package sizewhere;

import java.io.File;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public final class Main {
    private static Options getOptions() {
        Option dir = OptionBuilder.withArgName("dir")
            .hasArg()
            .withDescription("give total size of files in given dir")
            .create("dir");
        Option name = OptionBuilder.withArgName("name")
            .hasArg()
            .withDescription("give total size of files with given name")
            .create("name");
        Options options = new Options();

        options.addOption(dir);
        options.addOption(name);

        return options;
    }

    public static void main(String[] args) throws Exception {
      Options options = getOptions();
      try {

        CommandLineParser parser = new GnuParser();

        CommandLine line = parser.parse(options, args);
        File dir = new File(line.getOptionValue("dir", "."));
        String name = line.getOptionValue("name", "jar");
        System.out.println("total size of files in " + dir
            + " containing " + name + ": " + SizeWhere.totalSize(dir, name));
      } catch (ParseException exp) {
          // oops, something went wrong
          System.err.println("Parsing failed.  Reason: " + exp.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sizewhere", options);
      }
    }

    private Main() {
    }
}


text:
import describeHistory from './describeHistory';
import BrowserHistory from '../BrowserHistory';

describe('BrowserHistory', function () {
  describeHistory(BrowserHistory);
});


text:
package com.datasaver.www.sensors.tilt;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.util.Log;

import com.datasaver.www.sensors.SensorMessage;

/**
 * TiltSensor class.
 *
 * @author devetude
 */
public class TiltSensor implements SensorEventListener {
    private static final String TAG = TiltSensor.class.getSimpleName();

    private static final int MAX_RETRY_CNT = 5;

    private SensorManager sm;
    private Sensor s;
    private boolean isMeasuring;
    private Handler h;
    private float x;
    private float y;
    private float z;
    private int retryCnt;

    /**
     * Constructor.
     *
     * @param c
     */
    public TiltSensor(final Context c) {
        Log.d(TAG, "TiltSensor");

        sm = (SensorManager) c.getSystemService(Context.SENSOR_SERVICE);
        s = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    /**
     * Methods to update tilt information.
     *
     * @param h
     */
    public void update(final Handler h) {
        Log.d(TAG, "update");

        if (s == null) {
            Log.e(TAG, "sensor is null.");

            return;
        }

        if (isMeasuring) {
            Log.e(TAG, "already measuring.");
        }

        this.h = h;

        isMeasuring = true;
        sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
    }

    /**
     * Methods to get x.
     *
     * @return
     */
    public float getX() {
        Log.d(TAG, "getX");

        return x;
    }

    /**
     * Methods to get y.
     *
     * @return
     */
    public float getY() {
        Log.d(TAG, "getY");

        return y;
    }

    /**
     * Methods to get z.
     *
     * @return
     */
    public float getZ() {
        Log.d(TAG, "getZ");

        return z;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        Log.d(TAG, "onSensorChanged");
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            if (event.accuracy == SensorManager.SENSOR_STATUS_ACCURACY_LOW) {
                Log.w(TAG, "sensor status accuracy is low.");

                if (retryCnt++ == MAX_RETRY_CNT) {
                    Log.e(TAG, "over max retry count.");

                    h.sendMessage(SensorMessage.create(SensorMessage.UPDATE_FAIL));
                    sm.unregisterListener(this);
                    isMeasuring = false;
                }

                return;
            }

            x = event.values[0];
            y = event.values[1];
            z = event.values[2];

            h.sendMessage(SensorMessage.create(SensorMessage.UPDATE_SUCC));
            sm.unregisterListener(this);
            isMeasuring = false;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        Log.d(TAG, "onAccuracyChanged");

        // Not use.
    }
}


text:
package me.ehlxr.cache;

public class Test {

	public static void main(String[] args) {
		SimpleCacheUtil<Object> cache2 = new SimpleCacheUtil<>(5);
		cache2.put("123", "fdfd");

		System.out.println(cache2.get("123"));
	}
}


text:
require_dependency "renalware/transplants"

module Renalware
  module Transplants
    class LiveDonorsController < BaseController
      include Renalware::Concerns::PatientVisibility
      include Renalware::Concerns::Pageable

      def index
        query = LiveDonorsQuery.new(
          params: params[:q],
          relation: policy_scope(Transplants::Patient.all)
        )
        live_donors = query.call.page(page).per(per_page || 50)

        authorize live_donors
        render locals: {
          live_donors: live_donors,
          q: query.search
        }
      end
    end
  end
end


text:
package akka.persistence.cassandra.journal

import scala.concurrent.duration._

import akka.actor._
import akka.persistence._
import akka.persistence.cassandra.CassandraLifecycle
import akka.testkit._

import com.typesafe.config.ConfigFactory

import org.scalatest._

object CassandraIntegrationSpec {
  val config = ConfigFactory.parseString(
    """
      |akka.persistence.snapshot-store.plugin = "cassandra-snapshot-store"
      |akka.persistence.journal.plugin = "cassandra-journal"
      |akka.persistence.journal.max-deletion-batch-size = 3
      |akka.persistence.publish-confirmations = on
      |akka.persistence.publish-plugin-commands = on
      |akka.test.single-expect-default = 10s
      |cassandra-journal.max-partition-size = 5
      |cassandra-journal.max-result-size = 3
      |cassandra-journal.port = 9142
      |cassandra-snapshot-store.port = 9142
    """.stripMargin)

  var testSnapshotStore: ActorRef = _

  case class DeleteTo(snr: Long, permanent: Boolean)

  class ProcessorA(val persistenceId: String) extends PersistentActor {
    def receiveRecover: Receive = handle

    def receiveCommand: Receive = {
      case DeleteTo(sequenceNr, permanent) =>
        deleteMessages(sequenceNr, permanent)
      case payload: String =>
        persist(payload)(handle)
    }

    def handle: Receive = {
      case payload: String =>
        sender ! payload
        sender ! lastSequenceNr
        sender ! recoveryRunning
    }

    override private[persistence] lazy val snapshotStore: ActorRef = testSnapshotStore
  }

  class ProcessorC(val persistenceId: String, val probe: ActorRef) extends PersistentActor {
    var last: String = _

    def receiveRecover: Receive = {
      case SnapshotOffer(_, snapshot: String) =>
        last = snapshot
        probe ! s"offered-${last}"
      case payload: String =>
        handle(payload)
    }

    def receiveCommand: Receive = {
      case "snap" =>
        saveSnapshot(last)
      case SaveSnapshotSuccess(_) =>
        probe ! s"snapped-${last}"
      case payload: String =>
        persist(payload)(handle)
      case DeleteTo(sequenceNr, permanent) =>
        deleteMessages(sequenceNr, permanent)

    }

    def handle: Receive = {
      case payload: String =>
        last = s"${payload}-${lastSequenceNr}"
        probe ! s"updated-${last}"
    }

    override private[persistence] lazy val snapshotStore: ActorRef = testSnapshotStore
  }

  class ProcessorCNoRecover(override val persistenceId: String, probe: ActorRef) extends ProcessorC(persistenceId, probe) {
    override def preStart() = ()
  }

  class ViewA(val viewId: String, val persistenceId: String, probe: ActorRef) extends PersistentView {
    def receive = {
      case payload =>
        probe ! payload
    }

    override def autoUpdate: Boolean = false

    override def autoUpdateReplayMax: Long = 0
  }
}

import CassandraIntegrationSpec._

class CassandraIntegrationSpec extends TestKit(ActorSystem("test", config)) with ImplicitSender with WordSpecLike with Matchers with CassandraLifecycle {

  testSnapshotStore = Persistence(system).snapshotStoreFor("cassandra-snapshot-store")

  def subscribeToRangeDeletion(probe: TestProbe): Unit =
    system.eventStream.subscribe(probe.ref, classOf[JournalProtocol.DeleteMessagesTo])

  def awaitRangeDeletion(probe: TestProbe): Unit =
    probe.expectMsgType[JournalProtocol.DeleteMessagesTo]

  def testIndividualDelete(persistenceId: String, permanent: Boolean): Unit = {
    val deleteProbe = TestProbe()
    subscribeToRangeDeletion(deleteProbe)

    val processor1 = system.actorOf(Props(classOf[ProcessorA], persistenceId))
    1L to 16L foreach { i =>
      processor1 ! s"a-${i}"
      expectMsgAllOf(s"a-${i}", i, false)
    }

    // delete single message in partition
    processor1 ! DeleteTo(12L, permanent)
    awaitRangeDeletion(deleteProbe)

    system.actorOf(Props(classOf[ProcessorA], persistenceId))
    1L to 16L foreach { i =>
      if (i != 12L) expectMsgAllOf(s"a-${i}", i, true)
    }

    // delete whole partition
    6L to 10L foreach { i =>
      processor1 ! DeleteTo(i, permanent)
      awaitRangeDeletion(deleteProbe)
    }

    system.actorOf(Props(classOf[ProcessorA], persistenceId))
    1L to 5L foreach { i =>
      expectMsgAllOf(s"a-${i}", i, true)
    }
    11L to 16L foreach { i =>
      if (i != 12L) expectMsgAllOf(s"a-${i}", i, true)
    }
  }

  def testRangeDelete(persistenceId: String, permanent: Boolean): Unit = {
    val deleteProbe = TestProbe()
    subscribeToRangeDeletion(deleteProbe)

    val processor1 = system.actorOf(Props(classOf[ProcessorA], persistenceId))
    1L to 16L foreach { i =>
      processor1 ! s"a-${i}"
      expectMsgAllOf(s"a-${i}", i, false)
    }

    processor1 ! DeleteTo(3L, permanent)
    awaitRangeDeletion(deleteProbe)

    system.actorOf(Props(classOf[ProcessorA], persistenceId))
    4L to 16L foreach { i =>
      expectMsgAllOf(s"a-${i}", i, true)
    }

    processor1 ! DeleteTo(7L, permanent)
    awaitRangeDeletion(deleteProbe)

    system.actorOf(Props(classOf[ProcessorA], persistenceId))
    8L to 16L foreach { i =>
      expectMsgAllOf(s"a-${i}", i, true)
    }
  }

  "A Cassandra journal" should {
    "write and replay messages" in {
      val processor1 = system.actorOf(Props(classOf[ProcessorA], "p1"))
      1L to 16L foreach { i =>
        processor1 ! s"a-${i}"
        expectMsgAllOf(s"a-${i}", i, false)
      }

      val processor2 = system.actorOf(Props(classOf[ProcessorA], "p1"))
      1L to 16L foreach { i =>
        expectMsgAllOf(s"a-${i}", i, true)
      }

      processor2 ! "b"
      expectMsgAllOf("b", 17L, false)
    }
    // "not replay messages marked as deleted" in {
    //   testIndividualDelete("p3", false)
    // }
    // "not replay permanently deleted messages" in {
    //   testIndividualDelete("p4", true)
    // }
    "not replay messages marked as range-deleted" in {
      testRangeDelete("p5", false)
    }
    "not replay permanently range-deleted messages" in {
      testRangeDelete("p6", true)
    }
    "replay messages incrementally" in {
      val probe = TestProbe()
      val processor1 = system.actorOf(Props(classOf[ProcessorA], "p7"))
      1L to 6L foreach { i =>
        processor1 ! s"a-${i}"
        expectMsgAllOf(s"a-${i}", i, false)
      }

      val view = system.actorOf(Props(classOf[ViewA], "p7-view", "p7", probe.ref))
      probe.expectNoMsg(200.millis)

      view ! Update(true, replayMax = 3L)
      probe.expectMsg(s"a-1")
      probe.expectMsg(s"a-2")
      probe.expectMsg(s"a-3")
      probe.expectNoMsg(200.millis)

      view ! Update(true, replayMax = 3L)
      probe.expectMsg(s"a-4")
      probe.expectMsg(s"a-5")
      probe.expectMsg(s"a-6")
      probe.expectNoMsg(200.millis)
    }
  }

  "A processor" should {
    "recover from a snapshot with follow-up messages" in {
      val processor1 = system.actorOf(Props(classOf[ProcessorC], "p10", testActor))
      processor1 ! "a"
      expectMsg("updated-a-1")
      processor1 ! "snap"
      expectMsg("snapped-a-1")
      processor1 ! "b"
      expectMsg("updated-b-2")

      system.actorOf(Props(classOf[ProcessorC], "p10", testActor))
      expectMsg("offered-a-1")
      expectMsg("updated-b-2")
    }
    "recover from a snapshot with follow-up messages and an upper bound" in {
      val processor1 = system.actorOf(Props(classOf[ProcessorCNoRecover], "p11", testActor))
      processor1 ! Recover()
      processor1 ! "a"
      expectMsg("updated-a-1")
      processor1 ! "snap"
      expectMsg("snapped-a-1")
      2L to 7L foreach { i =>
        processor1 ! "a"
        expectMsg(s"updated-a-${i}")
      }

      val processor2 = system.actorOf(Props(classOf[ProcessorCNoRecover], "p11", testActor))
      processor2 ! Recover(toSequenceNr = 3L)
      expectMsg("offered-a-1")
      expectMsg("updated-a-2")
      expectMsg("updated-a-3")
      processor2 ! "d"
      expectMsg("updated-d-8")
    }
    "recover from a snapshot without follow-up messages inside a partition" in {
      val processor1 = system.actorOf(Props(classOf[ProcessorC], "p12", testActor))
      processor1 ! "a"
      expectMsg("updated-a-1")
      processor1 ! "snap"
      expectMsg("snapped-a-1")

      val processor2 = system.actorOf(Props(classOf[ProcessorC], "p12", testActor))
      expectMsg("offered-a-1")
      processor2 ! "b"
      expectMsg("updated-b-2")
    }
    "recover from a snapshot without follow-up messages at a partition boundary (where next partition is invalid)" in {
      val processor1 = system.actorOf(Props(classOf[ProcessorC], "p13", testActor))
      1L to 5L foreach { i =>
        processor1 ! "a"
        expectMsg(s"updated-a-${i}")
      }
      processor1 ! "snap"
      expectMsg("snapped-a-5")

      val processor2 = system.actorOf(Props(classOf[ProcessorC], "p13", testActor))
      expectMsg("offered-a-5")
      processor2 ! "b"
      expectMsg("updated-b-6")
    }
    "recover from a snapshot without follow-up messages at a partition boundary (where next partition contains a message marked as deleted)" in {
      val deleteProbe = TestProbe()
      subscribeToRangeDeletion(deleteProbe)

      val processor1 = system.actorOf(Props(classOf[ProcessorC], "p14", testActor))
      1L to 5L foreach { i =>
        processor1 ! "a"
        expectMsg(s"updated-a-${i}")
      }
      processor1 ! "snap"
      expectMsg("snapped-a-5")

      processor1 ! "a"
      expectMsg("updated-a-6")

      processor1 ! DeleteTo(6L, false)
      awaitRangeDeletion(deleteProbe)

      val processor2 = system.actorOf(Props(classOf[ProcessorC], "p14", testActor))
      expectMsg("offered-a-5")
      processor2 ! "b"
      expectMsg("updated-b-7")
    }
    "recover from a snapshot without follow-up messages at a partition boundary (where next partition contains a permanently deleted message)" in {
      val deleteProbe = TestProbe()
      subscribeToRangeDeletion(deleteProbe)

      val processor1 = system.actorOf(Props(classOf[ProcessorC], "p15", testActor))
      1L to 5L foreach { i =>
        processor1 ! "a"
        expectMsg(s"updated-a-${i}")
      }
      processor1 ! "snap"
      expectMsg("snapped-a-5")

      processor1 ! "a"
      expectMsg("updated-a-6")

      processor1 ! DeleteTo(6L, true)
      awaitRangeDeletion(deleteProbe)

      val processor2 = system.actorOf(Props(classOf[ProcessorC], "p15", testActor))
      expectMsg("offered-a-5")
      processor2 ! "b"
      expectMsg("updated-b-6") // sequence number of permanently deleted message can be re-used
    }
    "properly recover after all messages have been deleted" in {
      val deleteProbe = TestProbe()
      subscribeToRangeDeletion(deleteProbe)

      val p = system.actorOf(Props(classOf[ProcessorA], "p16"))

      p ! "a"
      expectMsgAllOf("a", 1L, false)

      p ! DeleteTo(1L, true)
      awaitRangeDeletion(deleteProbe)

      val r = system.actorOf(Props(classOf[ProcessorA], "p16"))

      r ! "b"
      expectMsgAllOf("b", 1L, false)
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://code.alibabatech.com/schema/dubbo
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd ">

    <dubbo:application name="zheng-upms-server"/>

    <dubbo:registry file="./zheng-upms-server-dubbo.cache" address="zookeeper://zkserver:2181"/>

    <!-- 订阅服务 -->
    <dubbo:consumer check="false"/>

    <!-- 系统 -->
    <dubbo:reference id="upmsSystemService" interface="com.zheng.upms.rpc.api.UpmsSystemService" mock="true"/>
    <!-- 组织 -->
    <dubbo:reference id="upmsOrganizationService" interface="com.zheng.upms.rpc.api.UpmsOrganizationService" mock="true"/>
    <!-- 用户组织 -->
    <dubbo:reference id="upmsUserOrganizationService" interface="com.zheng.upms.rpc.api.UpmsUserOrganizationService" mock="true"/>
    <!-- 用户 -->
    <dubbo:reference id="upmsUserService" interface="com.zheng.upms.rpc.api.UpmsUserService" mock="true"/>
    <!-- 角色 -->
    <dubbo:reference id="upmsRoleService" interface="com.zheng.upms.rpc.api.UpmsRoleService" mock="true"/>
    <!-- 权限 -->
    <dubbo:reference id="upmsPermissionService" interface="com.zheng.upms.rpc.api.UpmsPermissionService" mock="true"/>
    <!-- 角色权限 -->
    <dubbo:reference id="upmsRolePermissionService" interface="com.zheng.upms.rpc.api.UpmsRolePermissionService" mock="true"/>
    <!-- 用户权限 -->
    <dubbo:reference id="upmsUserPermissionService" interface="com.zheng.upms.rpc.api.UpmsUserPermissionService" mock="true"/>
    <!-- 用户角色 -->
    <dubbo:reference id="upmsUserRoleService" interface="com.zheng.upms.rpc.api.UpmsUserRoleService" mock="true"/>
    <!-- 操作日志 -->
    <dubbo:reference id="upmsLogService" interface="com.zheng.upms.rpc.api.UpmsLogService" mock="true"/>
    <!-- 接口服务 -->
    <dubbo:reference id="upmsApiService" interface="com.zheng.upms.rpc.api.UpmsApiService" mock="true"/>

</beans>


text:
package org.jdeferred.android;

import java.util.concurrent.CancellationException;

import org.jdeferred.Promise;
import org.jdeferred.DeferredManager.StartPolicy;
import org.jdeferred.impl.DeferredObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.os.AsyncTask;

/**
 * Wrapper for AsyncTask, so that AsyncTask cancellation, completion, and progress callbacks are
 * wired into a promise callback.
 *
 * @author Ray Tsang
 *
 * @param <Params>
 * @param <Progress>
 * @param <Result>
 */
public abstract class DeferredAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result>
{
	protected final Logger log = LoggerFactory.getLogger(DeferredAsyncTask.class);

	private final DeferredObject<Result, Throwable, Progress> deferred = new DeferredObject<Result, Throwable, Progress>();
	private final StartPolicy startPolicy;

	private Throwable throwable;

	public DeferredAsyncTask() {
		this.startPolicy = StartPolicy.DEFAULT;
	}

	public DeferredAsyncTask(StartPolicy startPolicy) {
		this.startPolicy = startPolicy;
	}

	@Override
	protected final void onCancelled() {
		deferred.reject(new CancellationException());
	}

	protected final void onCancelled(Result result) {
		deferred.reject(new CancellationException());
	};

	@Override
	protected final void onPostExecute(Result result) {
		if (throwable != null) {
			deferred.reject(throwable);
		} else {
			deferred.resolve(result);
		}
	}

	@Override
	protected final void onProgressUpdate(Progress ... values) {
		if (values == null || values.length == 0) {
			deferred.notify(null);
		} else if (values.length == 1) {
			deferred.notify(values[0]);
		} else {
			log.warn("There were multiple progress values.  Only the first one was used!");
			deferred.notify(values[0]);
		}
	};

	protected final Result doInBackground(Params ... params) {
		try {
			return doInBackgroundSafe(params);
		} catch (Throwable e) {
			throwable = e;
			return null;
		}
	};

	protected abstract Result doInBackgroundSafe(Params ... params) throws Exception;

	@SuppressWarnings("unchecked")
	protected final void notify(Progress progress) {
		publishProgress(progress);
	}

	public Promise<Result, Throwable, Progress> promise() {
		return deferred.promise();
	}

	public StartPolicy getStartPolicy() {
		return startPolicy;
	}
}


text:
package com.wavesplatform.lang.directives

import com.wavesplatform.lang.directives.values._

case class DirectiveSet(
  stdLibVersion: StdLibVersion,
  scriptType:    ScriptType,
  contentType:   ContentType,
  imports:       Imports
)

object DirectiveSet {
  val contractDirectiveSet = new DirectiveSet(V3, Account, DApp, Imports(Nil))

  def apply(
      stdLibVersion: StdLibVersion,
      scriptType:    ScriptType,
      contentType:   ContentType,
      imports:       Imports = Imports(Nil)
  ): Either[String, DirectiveSet] =
    (stdLibVersion, scriptType, contentType, imports) match {
      case (v, Account, DApp, _) if v >= V3    => Right(new DirectiveSet(v, Account, DApp, imports))
      case (v, sType, Expression, _)           => Right(new DirectiveSet(v, sType, Expression, imports))
      case (v, sType, Library, i@Imports(Nil)) => Right(new DirectiveSet(v, sType, Library, i))
      case (_,     _, Library, _)              => Left("Libraries should not contain imports")
      case wrongSet                            => Left(errorMsg(wrongSet))
    }

  private def errorMsg(wrongSet: (StdLibVersion, ScriptType, ContentType, Imports)) = {
    val (ver, sType, cType, _) = wrongSet
    s"Inconsistent set of directives ${(ver, sType, cType)} " +
    s"could be (V3 or newer, ACCOUNT, DAPP), (<any>, <any>, LIBRARY) or (<any>, <any>, EXPRESSION)"
  }
}


text:
		<meta http-equiv=content-type content="text/html;charset=ISO-8859-1">		<TITLE>Dictionary of Botanical Epithets</TITLE>
Dictionary of Botanical Epithets

eriantherus - erumpens

© 2019

Epithet
Definition

Derivation
Stem
Type/
                  Gender
Meaning

eriantherus
erianthera
eriantherum	wooly anthers

erion	eri	noun/n	εριον
wool

anthera	anther	noun/f	ανϑηρα
Mod L
anther

us		adj	Latinizing suffix

Phelipaea erianthera Engelm.
Penstemon eriantherus Pursh

erianthus
eriantha
erianthum	wooly flower

erion	eri	noun/n	εριον
wool

anthos	anth	noun/n	ανϑοϛ
flower

us		adj	Latinizing suffix

Agrostis eriantha Hack.
Geranium erianthum DC.
Orthocarpus erianthus Benth.

ericaefolius
ericaefolia
ericaefolium	leaves like Erica

erice	eric	noun/f	ερεικη
heath, broom

ae	ae	cnct	connective vowel sometimes used by botanical Latin instead of 'i' to distinguish between two words with the same root, e.g. tuba (trumpet) and tubus (tube); in some cases 'ae' is incorrectly used because it is the genitive singular suffix of the preceeding word but it should be corrected to 'i'

folius	foli	adj	folium
leaf

Spatallopsis ericaefolia E. Phillips

ericaeus
ericaea
ericaeum	of heath

ericaeus	ericae	adj	of the heath flower

eriocarpus
eriocarpa
eriocarpum	woolly fruits

erion	eri	noun/n	εριον
wool

o	o	cnct	connective vowel in botanical Latin, usually for Greek words but in some cases, such as color tingeing, for Latin words

carpos	carp	noun/m	καρποϛ
fruit

us		adj	Latinizing suffix

Asclepias eriocarpa Benth.
Pittosporum eriocarpum Royle
Rubus eriocarpus Liebm.

eriocephalus
eriocephala
eriocephalum	wooly head

erion	eri	noun/n	εριον
wool

o	o	cnct	connective vowel in botanical Latin, usually for Greek words but in some cases, such as color tingeing, for Latin words

cephale	cephal	noun/f	κεφαλη
head; front; end, point; source, top; chief person

us		adj	Latinizing suffix

Navarretia eriocephala Mason
Cirsium eriocephalum Gray
Erigeron eriocephalus J. Vahl

eriophorus
eriophora
eriophorum	wooly

erion	eri	noun/n	εριον
wool

o	o	cnct	connective vowel in botanical Latin, usually for Greek words but in some cases, such as color tingeing, for Latin words

phoros	phor	apar	phoreo
φορεω (φερω)
to carry, bring

us		adj	Latinizing suffix

Centaurea eriophora L.
Cirsium eriophorum (L.) Scop.
Cereus eriophorus Pfeiff.

eriostemon
eriostemones
 	wooly stamens

erion	eri	noun/n	εριον
wool

o	o	cnct	connective vowel in botanical Latin, usually for Greek words but in some cases, such as color tingeing, for Latin words

stemon	stemon	noun/m	στημων
L: stamen
warp in loom; thread

Clematis x eriostemon Decne.

erubescens
erubescens
erubescens	reddening

erubescens	erubescent	apar	erubesco
to redden, to blush

Arthonia erubescens Willey

erumpens
erumpens
erumpens	breaking forth

erumpens	erumpent	apar	erumpo
bursting forth, breaking out

Nolina erumpens (Torr.) S. Wats.


text:
package com.github.jasminb.jsonapi;

import org.junit.Assert;
import org.junit.Test;

/**
 * Testing functionality of JSON API Document methods.
 *
 * @author Marcel Overdijk
 */
public class JSONAPIDocumentTest {

    @Test
    public void testAddMeta() {
        JSONAPIDocument document = new JSONAPIDocument();
        Assert.assertNull(document.getMeta());
        document.addMeta("foo", "bar");
        Assert.assertEquals(1, document.getMeta().size());
        Assert.assertEquals("bar", document.getMeta().get("foo"));
    }

    @Test
    public void testAddLink() {
        JSONAPIDocument document = new JSONAPIDocument();
        Assert.assertNull(document.getLinks());
        document.addLink("foo", new Link("bar"));
        Assert.assertEquals(1, document.getLinks().getLinks().size());
        Assert.assertEquals("bar", document.getLinks().getLink("foo").getHref());
    }
}