text:
package org.deviceconnect.android.logger;

import android.util.Log;

import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

/**
 * Android用ロガークラス.
 * @author NTT DOCOMO, INC.
 */
public class AndroidHandler extends Handler {

    /**
     * Log Tag.
     */
    private String mTag = null;

    /**
     * コンストラクタ.
     */
    public AndroidHandler() {
        this(null);
    }

    /**
     * タグを指定してハンドラを生成する.
     *
     * @param tag ログ用タグ
     */
    public AndroidHandler(final String tag) {
        setTag(tag);
    }

    @Override
    public void close() {
    }

    @Override
    public void flush() {
    }

    @Override
    public void publish(final LogRecord record) {
        if (record.getLevel().equals(Level.FINEST)) {
            Log.v(mTag, getFormatter().format(record));
        }
        if (record.getLevel().equals(Level.FINER)) {
            Log.v(mTag, getFormatter().format(record));
        }
        if (record.getLevel().equals(Level.FINE)) {
            Log.d(mTag, getFormatter().format(record));
        }
        if (record.getLevel().equals(Level.INFO)) {
            Log.i(mTag, getFormatter().format(record));
        }
        if (record.getLevel().equals(Level.WARNING)) {
            Log.w(mTag, getFormatter().format(record));
        }
        if (record.getLevel().equals(Level.SEVERE)) {
            Log.e(mTag, getFormatter().format(record));
        }
    }

    /**
     * ログ用タグを設定する.
     * @param tag ログ用タグ
     */
    public void setTag(final String tag) {
        mTag = tag;
    }

}


text:
RELEASE_DIR	    = release
TARGET          = release.zip
SRC_DIR         = NetflixRemoveViewingActivities

SRCS            = $(notdir $(shell find $(SRC_DIR) -name "*.js"))
RESORCE_FILES   = $(notdir $(shell find $(SRC_DIR) -name "*.html" -or -name "*.json"))
TARGET_FILES    = $(addprefix $(RELEASE_DIR)/, $(SRCS) $(RESORCE_FILES))

$(info TARGET_FILES = $(TARGET_FILES))

CLOSURE_COMPILER_DIR = /opt/google/closure-compiler

.PHONY: all
all: $(TARGET)

.PHONY: clean
clean:
	rm -rf $(RELEASE_DIR) $(TARGET)

$(TARGET): $(RELEASE_DIR) $(TARGET_FILES)
	zip -r $(TARGET) $(RELEASE_DIR)

$(RELEASE_DIR):
	mkdir $(RELEASE_DIR)

.SUFFIXES: .js .html .json
$(RELEASE_DIR)/%.js: $(SRC_DIR)/%.js
	java -jar $(CLOSURE_COMPILER_DIR)/compiler.jar --js $< --js_output_file $@
#	java -jar $(CLOSURE_COMPILER_DIR)/compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js $< --js_output_file $@

$(RELEASE_DIR)/%.html: $(SRC_DIR)/%.html
	cp $< $@

$(RELEASE_DIR)/%.json: $(SRC_DIR)/%.json
	cp $< $@

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;
    using Newtonsoft.Json;

    /// <summary>
    /// The type SharingLink.
    /// </summary>
    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    [JsonConverter(typeof(DerivedTypeConverter))]
    public partial class SharingLink
    {

        /// <summary>
        /// Gets or sets application.
        /// The app the link is associated with.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "application", Required = Newtonsoft.Json.Required.Default)]
        public Identity Application { get; set; }

        /// <summary>
        /// Gets or sets scope.
        /// The scope of the link represented by this permission. Value anonymous indicates the link is usable by anyone, organization indicates the link is only usable for users signed into the same tenant.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "scope", Required = Newtonsoft.Json.Required.Default)]
        public string Scope { get; set; }

        /// <summary>
        /// Gets or sets type.
        /// The type of the link created.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "type", Required = Newtonsoft.Json.Required.Default)]
        public string Type { get; set; }

        /// <summary>
        /// Gets or sets webUrl.
        /// A URL that opens the item in the browser on the OneDrive website.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "webUrl", Required = Newtonsoft.Json.Required.Default)]
        public string WebUrl { get; set; }

        /// <summary>
        /// Gets or sets additional data.
        /// </summary>
        [JsonExtensionData(ReadData = true)]
        public IDictionary<string, object> AdditionalData { get; set; }

    }
}


text:
//=============================================================================
// GeoManager.js
//=============================================================================

/*:
 * @plugindesc GeoLocation Manager.
 * @author saronpasu
 *
 * @version 0.0.1
 *
 * @param Type
 * @desc Geodetic system Config
 * @default WGS84
 *
 * @help
 *
 * This plugin is inner module about geo location
 *
 * [Developers Note]
 * This plugin is doing the calculation by a simply formula.
 * Use the other plugin if you want a more exact calculation.
 *
 */

/*:ja
 * @plugindesc 位置情報を取得、距離計算をするモジュール
 * @author saronpasu
 *
 * @param Type
 * @desc 測地系の設定
 * @default WGS84
 *
 * @help
 *
 * このプラグインは位置情報を扱う内部モジュールです。
 *
 * [開発者向け]
 * このプラグインでは簡易式による計算を行っています。
 * より正確な計算結果を望む場合は、他のプラグインを使用することを推奨します。
 *
 */

/*
 * Copyright (c) 2015 saronpasu
 *
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 *
 */

var Imported = Imported || {};
Imported.GeoManager = {};

(function() {

    'use strict';

    var parameters = PluginManager.parameters('GeoManager');
    var Type = String(parameters['Type'] || 'WGS48');

    // 測地系、現在は WGS84 のみ対応
    var Types = {
        WGS84 : {
            semiMajorAxis: 6378137,
            semiMinorAxis: 6356752.3142,
            firstEccentricitySquared: 0.00669437999014
        }
    };

    // 単位変換レート
    var UnitRate = {
        m: 1,
        km: 0.001,
        ft: 3.28084,
        ml: 0.000621371
    };

    var GeoManager = function() {
        this.initialize.apply(this, arguments);
    };

    GeoManager.prototype.initialize = function(unit, opts, type) {
        this.setup(unit, type);
        this.setupOpts(opts);
    };

    GeoManager.prototype.setup = function(unit, type) {
        this._type = Types[type] || Types['WGS84'];
        this._unit = unit || 'm';
        this._rate = UnitRate[this._unit] || UnitRate['m'];
        this._watchId = null;
    };

    GeoManager.prototype.setupOpts = function(opts) {
        var defaultOpts = {
            enableHighAccuracy: true,
            maximumAge: 0,
            timeout: 10000
        };
        opts = opts || defaultOpts;
        this._opts = opts;
    };

    GeoManager.prototype.setUnit = function(unit) {
        this._unit = unit || this._unit;
        this._rate  = UnitRate[this._unit] || UnitRate['m'];
    }

    GeoManager.prototype.isSupport = function() {
        return !!(navigator.geolocation && !Utils.isNwjs());
    };

    GeoManager.prototype.successFunction = function(position) {
        var result = {
            latitude: position['coords']['latitude'],
            longitude: position['coords']['longitude'],
            altitude: position['coords']['altitude'],
            accuracy: position['coords']['accuracy'],
            altitudeAccuracy: position['coords']['altitudeAccuracy'],
            heading: position['coords']['heading'],
            speed: position['coords']['heading']
        };
        return result;
    };

    GeoManager.prototype.errorFunction = function(error) {
        switch(error.code) {
           case 0:
               console.error('GeoManager: unknown error.');
               break;
           case 1:
               console.error('GeoManager: permisson denied.');
               break;
           case 2:
               console.error('GeoManager: position unavailable.');
               break;
           case 3:
               console.error('GeoManager: timeout.');
               break;
           default:
               console.error('GeoManager: other error.');
               break;
        }
    };

    GeoManager.prototype.isValidFunc = function(func) {
        return typeof func === 'function';
    };

    GeoManager.prototype.isValidUnit = function(param) {
        return typeof param === 'string' && /^(m|km|ft|ml)$/.test(param);
    };

    GeoManager.prototype.isValidOpts = function(opts) {
        var result = [
            opts.enableHighAccuracy && typeof opts.enableHighAccuracy === 'boolean',
            opts.maximumAge && typeof opts.maximumAge === 'number',
            opts.timeout && typeof opts.timeout === 'number'
        ];
        return (result.filter(function(x){x;}).length === 0);
    };

    // navigator.geolocation.getCurrentPosition をラップしてるだけ。
    GeoManager.prototype.getCurrent = function(successFunc, errorFunc, opts) {
        successFunc = successFunc || this.successFunction;
        if (!this.isValidFunc(successFunc)) {
            console.error('invalid arguments');
            return false;
        }

        errorFunc = errorFunc || this.errorFunction;
        if (!this.isValidFunc(errorFunc)) {
            console.error('invalid arguments');
            return false;
        }
        opts = opts || this._opts;
        if (!this.isValidOpts(opts)) {
            console.error('invalid option');
            return false;
        }

        return navigator.geolocation.getCurrentPosition(successFunc, errorFunc, opts);
    };

    // navigator.geolocation.watchPosition をラップしてるだけ。
    GeoManager.prototype.startWatch = function(successFunc, errorFunc, opts) {
        successFunc = successFunc || this.successFunction;
        if (!this.isValidFunc(successFunc)) {
            console.error('invalid arguments');
            return false;
        }

        errorFunc = errorFunc || this.errorFunction;
        if (!this.isValidFunc(errorFunc)) {
            console.error('invalid arguments');
            return false;
        }
        opts = opts || this._opts;
        if (!this.isValidOpts(opts)) {
            console.error('invalid option');
            return false;
        }

        this._watchId = navigator.geolocation.watchPosition(successFunc, errorFunc, opts);
        return this._watchId;
    };

    // navigator.geolocation.clearWatch をラップしてるだけ。
    GeoManager.prototype.stopWatch = function(watchId) {
        watchId = watchId || this._watchId;
        if (!watchId) {
            console.error('not have watchId');
            return false;
        }

        navigator.geolocation.clearWatch(watchId);
    };

    // 地球上の2座標間の距離を測位して任意の単位で返す
    GeoManager.prototype.distance = function(lat1, lon1, lat2, lon2, unit) {
        unit = unit || this._unit;
        return this.convertUnit(this.calcHubenyFormula(lat1, lon1, lat2, lon2), unit);
    };

    /*
     * 地球上の2座標間の距離を算出するヒュベニの簡易式
     * 返り値の単位はメートル、より正確な測位を望む場合は別の方法で実装して下さい
     * 単位変換の必要がない場合や、まとめて単位変換する場合はこちらの関数を直接実行するのでもいいです
     *
     */
    GeoManager.prototype.calcHubenyFormula = function(lat1, lon1, lat2, lon2) {
        var Rx = this._type.semiMajorAxis;
        var Ry = this._type.semiMinorAxix;
        var E2 = this._type.firstEccentricitySquared;

        var Dy = (lat1 * Math.PI / 180) - (lat2 * Math.PI / 180);
        var Dx = (lon1 * Math.PI / 180) - (lon2 * Math.PI / 180);
        var P = ((lat1 * Math.PI / 180) + (lat2 * Math.PI / 180)) / 2;

        var W = Math.sqrt(1 - E2 * Math.pow(Math.sin(P), 2));
        var N = Rx / W;
        var M = Rx * (1 - E2) / Math.pow(W, 3);

        return Math.sqrt(Math.pow(Dy * M, 2) + Math.pow(Dx * N * Math.cos(P), 2));
    };

    // 単位変換
    GeoManager.prototype.convertUnit = function(value, unit) {
        unit = unit || this._unit;
        return Math.floor(value * UnitRate[unit]);
    };

    // エクスポート
    Imported.GeoManager = GeoManager;

})();


text:
<include file="public:header" />

    <form name="searchform" method="get" >

            	<input type="hidden" name="g" value="admin" />
                <input type="hidden" name="m" value="flink" />
                <input type="hidden" name="a" value="index" />
                <input type="hidden" name="menuid" value="{$menuid}" />
				所属分类:
                <select name="cate_id">
                        <option value="">--请选择分类--</option>
                        <volist name="cate_list" id="val"> <option value="{$val.id}"
                            <if condition="$search.cate_id eq $val['id']"> selected="selected" </if>
                            >{$val.name}
                         </option>
                         </volist>
                </select>
                关键字 :
                <input name="keyword" type="text" class="input-text" size="25" value="{$search.keyword}" />
                <input type="submit" name="search" class="btn" value="搜索" />

    </form>

                <input type="checkbox" id="checkall_t" class="J_checkall">
                ID
				缩略图
                链接名称
                链接地址
                分类名称
				排序
                {:L('status')}
                {:L('operations_manage')}

            <volist name="list" id="val" >

                <input type="checkbox" class="J_checkitem" value="{$val.id}">
                {$val.id}

				</notempty>

                {$val.name}
                {$val.url}
                {$val.flink_cate.name}
				{$val.ordid}
                <img data-tdtype="toggle" data-id="{$val.id}" data-field="status" data-value="{$val.status}" src="__STATIC__/images/admin/toggle_<if condition="$val.status eq 0">disabled<else/>enabled</if>.gif" />

					$val['id']))}" data-title="{:L('edit')} - {$val.name}"  data-id="edit" data-acttype="ajax" data-width="500" data-height="260">{:L('edit')} |
                    $val['id']))}" data-msg="{:sprintf(L('confirm_delete_one'),$val['name'])}">{:L('delete')}

            </volist>

    	<input type="checkbox" name="checkall" class="J_checkall">{:L('select_all')}/{:L('cancel')}
    	<input type="button" class="btn" data-tdtype="batch_action" data-acttype="ajax" data-uri="{:U('flink/delete')}" data-name="id" data-msg="{:L('confirm_delete')}" value="{:L('delete')}" />

{$page}

<include file="public:footer" />


text:
/**
 * An implementation of a client-side page cache.
 * This object also uses the cache to provide a simple microhistory,
 * that is the ability to use the back and forward buttons in the browser
 */
var MicroHistory = {
    /**
     * @var int The maximum number of pages to keep in the cache
     */
    MAX: 6,
    /**
     * @var object A hash used to prime the cache with data about the initially
     *             loaded page. This is set in the footer, and then loaded
     *             by a double-queued event further down this file.
     */
    primer: {},
    /**
     * @var array Stores the content of the cached pages
     */
    pages: [],
    /**
     * @var int The index of the currently loaded page
     *          This is used to know at which point in the history we are
     */
    current: 0,
    /**
     * Saves a new page in the cache
     *
     * @param string hash    The hash part of the url that is being loaded
     * @param array  scripts A list of scripts that is required for the page
     * @param string menu    A hash that links to a menu stored
     *                       in a dedicated menu cache
     * @param array  params  A list of parameters used by CommonParams()
     * @param string rel     A relationship to the current page:
     *                       'samepage': Forces the response to be treated as
     *                                   the same page as the current one
     *                       'newpage':  Forces the response to be treated as
     *                                   a new page
     *                       undefined:  Default behaviour, 'samepage' if the
     *                                   selflinks of the two pages are the same.
     *                                   'newpage' otherwise
     *
     * @return void
     */
    add: function (hash, scripts, menu, params, rel) {
        if (this.pages.length > MicroHistory.MAX) {
            // Trim the cache, to the maximum number of allowed entries
            // This way we will have a cached menu for every page
            for (var i = 0; i < this.pages.length - this.MAX; i++) {
                delete this.pages[i];
            }
        }
        while (this.current < this.pages.length) {
            // trim the cache if we went back in the history
            // and are now going forward again
            this.pages.pop();
        }
        if (rel === 'newpage' ||
            (
                typeof rel === 'undefined' && (
                    typeof this.pages[this.current - 1] === 'undefined' ||
                    this.pages[this.current - 1].hash !== hash
                )
            )
        ) {
            this.pages.push({
                hash: hash,
                content: $('#page_content').html(),
                scripts: scripts,
                selflink: $('#selflink').html(),
                menu: menu,
                params: params
            });
            MicroHistory.setUrlHash(this.current, hash);
            this.current++;
        }
    },
    /**
     * Restores a page from the cache. This is called when the hash
     * part of the url changes and it's structure appears to be valid
     *
     * @param string index Which page from the history to load
     *
     * @return void
     */
    navigate: function (index) {
        var localIndex = index;
        if (typeof this.pages[localIndex] === 'undefined' ||
            typeof this.pages[localIndex].content === 'undefined' ||
            typeof this.pages[localIndex].menu === 'undefined' ||
            ! MicroHistory.menus.get(this.pages[localIndex].menu)
        ) {
            Functions.ajaxShowMessage(
                '
' + Messages.strInvalidPage + '
',
                false
            );
        } else {
            AJAX.active = true;
            var record = this.pages[localIndex];
            AJAX.scriptHandler.reset(function () {
                $('#page_content').html(record.content);
                $('#selflink').html(record.selflink);
                MicroHistory.menus.replace(MicroHistory.menus.get(record.menu));
                CommonParams.setAll(record.params);
                AJAX.scriptHandler.load(record.scripts);
                MicroHistory.current = ++localIndex;
            });
        }
    },
    /**
     * Resaves the content of the current page in the cache.
     * Necessary in order not to show the user some outdated version of the page
     *
     * @return void
     */
    update: function () {
        var page = this.pages[this.current - 1];
        if (page) {
            page.content = $('#page_content').html();
        }
    },
    /**
     * @var object Dedicated menu cache
     */
    menus: {
        /**
         * Returns the number of items in an associative array
         *
         * @return int
         */
        size: function (obj) {
            var size = 0;
            var key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                    size++;
                }
            }
            return size;
        },
        /**
         * @var hash Stores the content of the cached menus
         */
        data: {},
        /**
         * Saves a new menu in the cache
         *
         * @param string hash    The hash (trimmed md5) of the menu to be saved
         * @param string content The HTML code of the menu to be saved
         *
         * @return void
         */
        add: function (hash, content) {
            if (this.size(this.data) > MicroHistory.MAX) {
                // when the cache grows, we remove the oldest entry
                var oldest;
                var key;
                var init = 0;
                for (var i in this.data) {
                    if (this.data[i]) {
                        if (! init || this.data[i].timestamp.getTime() < oldest.getTime()) {
                            oldest = this.data[i].timestamp;
                            key = i;
                            init = 1;
                        }
                    }
                }
                delete this.data[key];
            }
            this.data[hash] = {
                content: content,
                timestamp: new Date()
            };
        },
        /**
         * Retrieves a menu given its hash
         *
         * @param string hash The hash of the menu to be retrieved
         *
         * @return string
         */
        get: function (hash) {
            if (this.data[hash]) {
                return this.data[hash].content;
            } else {
                // This should never happen as long as the number of stored menus
                // is larger or equal to the number of pages in the page cache
                return '';
            }
        },
        /**
         * Prepares part of the parameter string used during page requests,
         * this is necessary to tell the server which menus we have in the cache
         *
         * @return string
         */
        getRequestParam: function () {
            var param = '';
            var menuHashes = [];
            for (var i in this.data) {
                menuHashes.push(i);
            }
            var menuHashesParam = menuHashes.join('-');
            if (menuHashesParam) {
                param = CommonParams.get('arg_separator') + 'menuHashes=' + menuHashesParam;
            }
            return param;
        },
        /**
         * Replaces the menu with new content
         *
         * @return void
         */
        replace: function (content) {
            $('#floating_menubar').html(content)
                // Remove duplicate wrapper
                // TODO: don't send it in the response
                .children().first().remove();
            $('#topmenu').menuResizer(Functions.mainMenuResizerCallback);
        }
    }
};

/**
 * URL hash management module.
 * Allows direct bookmarking and microhistory.
 */
MicroHistory.setUrlHash = (function (jQuery, window) {
    'use strict';
    /**
     * Indicates whether we have already completed
     * the initialization of the hash
     *
     * @access private
     */
    var ready = false;
    /**
     * Stores a hash that needed to be set when we were not ready
     *
     * @access private
     */
    var savedHash = '';
    /**
     * Flag to indicate if the change of hash was triggered
     * by a user pressing the back/forward button or if
     * the change was triggered internally
     *
     * @access private
     */
    var userChange = true;

    // Fix favicon disappearing in Firefox when setting location.hash
    function resetFavicon () {
        if (navigator.userAgent.indexOf('Firefox') > -1) {
            // Move the link tags for the favicon to the bottom
            // of the head element to force a reload of the favicon
            $('head > link[href="favicon\\.ico"]').appendTo('head');
        }
    }

    /**
     * Sets the hash part of the URL
     *
     * @access public
     */
    function setUrlHash (index, hash) {
        /*
         * Known problem:
         * Setting hash leads to reload in webkit:
         * https://www.quirksmode.org/bugreports/archives/2005/05/Safari_13_visual_anomaly_with_windowlocationhref.html
         *
         * so we expect that users are not running an ancient Safari version
         */

        userChange = false;
        if (ready) {
            window.location.hash = 'PMAURL-' + index + ':' + hash;
            resetFavicon();
        } else {
            savedHash = 'PMAURL-' + index + ':' + hash;
        }
    }
    /**
     * Start initialization
     */
    var urlHash = window.location.hash;
    if (urlHash.substring(0, 8) === '#PMAURL-') {
        // We have a valid hash, let's redirect the user
        // to the page that it's pointing to
        var colonPosition = urlHash.indexOf(':');
        var questionMarkPosition = urlHash.indexOf('?');
        if (colonPosition !== -1 && questionMarkPosition !== -1 && colonPosition < questionMarkPosition) {
            var hashUrl = urlHash.substring(colonPosition + 1, questionMarkPosition);
            if (hashUrl === 'index.php') {
                window.location = urlHash.substring(
                    colonPosition + 1
                );
            }
        }
    } else {
        // We don't have a valid hash, so we'll set it up
        // when the page finishes loading
        jQuery(function () {
            /* Check if we should set URL */
            if (savedHash !== '') {
                window.location.hash = savedHash;
                savedHash = '';
                resetFavicon();
            }
            // Indicate that we're done initializing
            ready = true;
        });
    }
    /**
     * Register an event handler for when the url hash changes
     */
    jQuery(function () {
        jQuery(window).hashchange(function () {
            if (userChange === false) {
                // Ignore internally triggered hash changes
                userChange = true;
            } else if (/^#PMAURL-\d+:/.test(window.location.hash)) {
                // Change page if the hash changed was triggered by a user action
                var index = window.location.hash.substring(
                    8, window.location.hash.indexOf(':')
                );
                MicroHistory.navigate(index);
            }
        });
    });
    /**
     * Publicly exposes a reference to the otherwise private setUrlHash function
     */
    return setUrlHash;
}(jQuery, window));


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/locations/specific-locations/church-related-locations/dudley-t-leavitt-home-nevada-usa" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/locations/specific-locations/church-related-locations/dudley-t-leavitt-home-nevada-usa</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Dudley T. Leavitt Home (Nevada, USA)</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/locations/specific-locations/church-related-locations/dudley-t-leavitt-home-nevada-usa</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/locations/specific-locations/church-related-locations/dudley-t-leavitt-home-nevada-usa</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
module Azure::ServiceFabric::V6_4_0_36
  module Models
    #
    # Credential information to connect to container registry.
    #
    class RegistryCredential

      include MsRestAzure

      # @return [String] The user name to connect to container registry.
      attr_accessor :registry_user_name

      # @return [String] The password for supplied username to connect to
      # container registry.
      attr_accessor :registry_password

      # @return [Boolean] Indicates that supplied container registry password
      # is encrypted.
      attr_accessor :password_encrypted

      #
      # Mapper for RegistryCredential class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'RegistryCredential',
          type: {
            name: 'Composite',
            class_name: 'RegistryCredential',
            model_properties: {
              registry_user_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'RegistryUserName',
                type: {
                  name: 'String'
                }
              },
              registry_password: {
                client_side_validation: true,
                required: false,
                serialized_name: 'RegistryPassword',
                type: {
                  name: 'String'
                }
              },
              password_encrypted: {
                client_side_validation: true,
                required: false,
                serialized_name: 'PasswordEncrypted',
                type: {
                  name: 'Boolean'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?php

namespace DevCtrl\Domain\Item\Property\ValuesProvider;

use DevCtrl\Domain\Item\Property\Property;
use DevCtrl\Domain\Item\Type\Type;
use DevCtrl\Domain\Exception;

abstract class AbstractProvider implements ProviderInterface
{
    public function requiresConfiguration()
    {
        return false;
    }

    public function supportsDefaultValue()
    {
        return false;
    }

    /**
     * @param Property $property
     * @param Type $itemType
     * @throws Exception
     */
    public function getValues(Property $property)
    {
        return $this->_getValues($property);
    }

    abstract protected function _getValues(Property $property);

    public function getConfigurationValues()
    {
        if (!$this->requiresConfiguration()) {
            throw new \DevCtrl\Domain\Exception('this ValuesProvider does not require configuration');
        }
        return $this->_getConfigurationValues();
    }

    protected function _getConfigurationValues()
    {
        if ($this->requiresConfiguration()) {
            throw new \DevCtrl\Domain\Exception('no require configuration present! override this method');
        }
        return array();
    }

}


text:
<?php
//============================================================+
// File name   : example_055.php
// Begin       : 2009-10-21
// Last Update : 2013-05-14
//
// Description : Example 055 for TCPDF class
//               Display all characters available on core fonts.
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               www.tecnick.com
//               info@tecnick.com
//============================================================+

/**
 * Display all characters available on core fonts.
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Example: XHTML Forms
 * @author Nicola Asuni
 * @since 2009-10-21
 */

// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 055');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 055', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (file_exists(dirname(__FILE__).'/lang/eng.php')) {
	require_once(dirname(__FILE__).'/lang/eng.php');
	$pdf->setLanguageArray($l);
}

// ---------------------------------------------------------

// set font
$pdf->SetFont('helvetica', '', 14);

// array of font names
$core_fonts = array('courier', 'courierB', 'courierI', 'courierBI', 'helvetica', 'helveticaB', 'helveticaI', 'helveticaBI', 'times', 'timesB', 'timesI', 'timesBI', 'symbol', 'zapfdingbats');

// set fill color
$pdf->SetFillColor(221,238,255);

// create one HTML table for each core font
foreach($core_fonts as $font) {
	// add a page
	$pdf->AddPage();

	// Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=false, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M')

	// set font for title
	$pdf->SetFont('helvetica', 'B', 16);

	// print font name
	$pdf->Cell(0, 10, 'FONT: '.$font, 1, 1, 'C', true, '', 0, false, 'T', 'M');

	// set font for chars
	$pdf->SetFont($font, '', 16);

	// print each character
	for ($i = 0; $i < 256; ++$i) {
		if (($i > 0) AND (($i % 16) == 0)) {
			$pdf->Ln();
		}
		$pdf->Cell(11.25, 11.25, $pdf->unichr($i), 1, 0, 'C', false, '', 0, false, 'T', 'M');
	}

	$pdf->Ln(20);

	// print a pangram
	$pdf->Cell(0, 0, 'The quick brown fox jumps over the lazy dog', 0, 1, 'C', false, '', 0, false, 'T', 'M');
}

// ---------------------------------------------------------

//Close and output PDF document
$pdf->Output('example_055.pdf', 'D');

//============================================================+
// END OF FILE
//============================================================+


text:
define(['./cachePush', '../lang/isNative', './root'], function(cachePush, isNative, root) {

  /** Native method references. */
  var Set = isNative(Set = root.Set) && Set;

  /* Native method references for those with the same name as other `lodash` methods. */
  var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate;

  /**
   *
   * Creates a cache object to store unique values.
   *
   * @private
   * @param {Array} [values] The values to cache.
   */
  function SetCache(values) {
    var length = values ? values.length : 0;

    this.data = { 'hash': nativeCreate(null), 'set': new Set };
    while (length--) {
      this.push(values[length]);
    }
  }

  // Add functions to the `Set` cache.
  SetCache.prototype.push = cachePush;

  return SetCache;
});


text:
package com.xiaomi.mitv.store.network;

import android.content.Context;

import com.tv.ui.metro.loader.TabsGsonLoader;
import com.tv.ui.metro.model.DisplayItem;

public class GameTabsGsonLoader  extends TabsGsonLoader {

    public GameTabsGsonLoader(Context context, DisplayItem item) {
        super(context, item);
    }

    @Override
    public void setLoaderURL(DisplayItem item) {
        String url = "http://172.27.15.32:7071/v2/game";
        calledURL = new CommonUrl(getContext()).addCommonParams(url);
    }
}


text:
'use strict';

angular.module('keta.filters.Unit',
	[
		'keta.services.Tag'
	])
	.filter('ketaUnit', function($filter, ketaTagConstants) {

		var unitFilter = function unitFilter(input, configuration) {

			if (!angular.isNumber(input)) {
				return input;
			}

			var precision = 0,
				precisionRanges = [],
				precisionExcludeIntegers = false,
				precisionExclude = [],
				unit = '',
				isBytes = false,
				separate = false,
				separated = {
					numberFormatted: null,
					numberRaw: null,
					unit: null
				};

			if (angular.isDefined(configuration)) {

				// general precision (defaults to 0)
				precision =
					angular.isNumber(configuration.precision) ?
						configuration.precision : precision;

				// precision ranges (defaults to [])
				precisionRanges =
					angular.isArray(configuration.precisionRanges) ?
						configuration.precisionRanges : precisionRanges;

				// flag if decimal places shouldn't be forced by precision
				precisionExcludeIntegers = angular.isDefined(configuration.precisionExcludeIntegers) ?
					configuration.precisionExcludeIntegers : precisionExcludeIntegers;

				// precision excluded values
				precisionExclude =
					angular.isArray(configuration.precisionExclude) ?
						configuration.precisionExclude : precisionExclude;

				// unit to use (defaults to '')
				unit =
					angular.isDefined(configuration.unit) ?
						configuration.unit : unit;

				// flag if value represents bytes (defaults to false)
				isBytes =
					angular.isDefined(configuration.isBytes) ?
						configuration.isBytes : isBytes;

				// flag if result should be returned separate (defaults to false)
				separate =
					angular.isDefined(configuration.separate) ?
						configuration.separate : separate;

			}

			var excludeFromPrecision = precisionExcludeIntegers;

			// checking if input is an excluded value
			if (!excludeFromPrecision) {
				excludeFromPrecision = precisionExclude.indexOf(input) !== -1;
			}

			// reset precision if precision range matches
			angular.forEach(precisionRanges, function(range) {
				var matching = true;
				if (angular.isDefined(range.min) && input < range.min) {
					matching = false;
				}
				if (angular.isDefined(range.max) && input >= range.max) {
					matching = false;
				}
				if (!angular.isDefined(range.min) && !angular.isDefined(range.max)) {
					matching = false;
				}
				if (matching && angular.isNumber(range.precision)) {
					precision = range.precision;
				}
			});

			if (input === 0 && excludeFromPrecision) {
				precision = 0;
			}

			var sizes = isBytes ? ['Bytes', 'KB', 'MB', 'GB', 'TB'] : ['', 'k', 'M', 'G', 'T'];

			// directly return currencies and distances
			if (unit === ketaTagConstants.UNIT.EURO ||
				unit === ketaTagConstants.UNIT.KILOMETER ||
				unit === ketaTagConstants.UNIT.DOLLAR ||
				unit === ketaTagConstants.UNIT.POUND) {

				if (separate) {
					separated.numberFormatted = $filter('number')(input, precision);
					separated.numberRaw = input;
					separated.unit = unit;
					return separated;
				}

				return $filter('number')(input, precision) + ' ' + unit;
			}

			var multiplicator = input < 0 ? -1 : 1;
			var oneKiloByte = 1024;
			var oneKilo = 1000;
			var parseBase = 10;
			input *= multiplicator;

			if (input >= 1) {

				var i = parseInt(
					Math.floor(Math.log(input) / Math.log(isBytes ? oneKiloByte : oneKilo)),
					parseBase
				);

				var siInput = input / Math.pow(isBytes ? oneKiloByte : oneKilo, i) * multiplicator;
				var siInputFixed = excludeFromPrecision ? siInput : Number(siInput.toFixed(precision));
				if (siInputFixed >= oneKilo) {
					i++;
					siInputFixed /= oneKilo;
				}

				// determine number of decimal places
				var inputPieces = String(siInputFixed).split(/\./);
				var inputsCurrentPrecision = inputPieces.length > 1 ? inputPieces[1].length : 0;

				separated.numberFormatted = excludeFromPrecision ?
					$filter('number')(siInputFixed, inputsCurrentPrecision) :
					$filter('number')(siInputFixed, precision);

				separated.numberRaw = siInputFixed;
				separated.unit = sizes[i] + unit;

				input =	separated.numberFormatted +
						(sizes[i] !== '' ? ' ' + sizes[i] : '');

			} else {

				separated.numberFormatted = $filter('number')(input, precision);
				separated.numberRaw = Number(input.toFixed(precision));
				separated.unit = unit;

				input = separated.numberFormatted;

			}

			if (!isBytes && unit !== '') {
				input += input.indexOf(' ') === -1 ? ' ' + unit : unit;
			}

			if (separate) {
				return separated;
			}

			return input;
		};

		unitFilter.$stateful = true;

		return unitFilter;

	});


text:
//
//  NSIndexPath+AKARowAndSectionAsInteger.h
//  AKACommons
//
//  Created by Michael Utech on 14.04.15.
//  Copyright (c) 2015 Michael Utech & AKA Sarl. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface NSIndexPath (AKARowAndSectionAsInteger)

/**
 * Encodes the section- and row value of the indexPath as
 * unsigned integer value. On 32bit platforms, 12 bits are
 * used for the section (range 0..4094 + NSNotFound) and
 * 20 bits for the row (range 0..1048574 + NSNotFound). On
 * 64bit platforms, section and row each use 32bit.
 */
@property(nonatomic, readonly)NSUInteger aka_unsignedIntegerValue;

/**
 * Decodes the encoded section- and row value returning an
 * indexPath. On 32bit platforms, 12 bits are
 * used for the section (range 0..4095 + NSNotFound) and
 * 20 bits for the row (range 0..1048574 + NSNotFound). On
 * 64bit platforms, section and row each use 32bit.
 */
+ (NSIndexPath*)aka_indexPathFromUnsignedIntegerValue:(NSUInteger)unsignedIntegerValue;

@end


text:
package org.apache.solr.handler;

import org.apache.commons.io.IOUtils;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.TestUtil;
import org.apache.solr.SolrJettyTestBase;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.embedded.JettySolrRunner;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.util.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SolrTestCaseJ4.SuppressSSL     // Currently unknown why SSL does not work with this test
public class TestReplicationHandlerBackup extends SolrJettyTestBase {

  JettySolrRunner masterJetty;
  TestReplicationHandler.SolrInstance master = null;
  SolrClient masterClient;

  private static final String CONF_DIR = "solr"
      + File.separator + "collection1" + File.separator + "conf"
      + File.separator;

  private static String context = "/solr";

  boolean addNumberToKeepInRequest = true;
  String backupKeepParamName = ReplicationHandler.NUMBER_BACKUPS_TO_KEEP_REQUEST_PARAM;

  private static JettySolrRunner createJetty(TestReplicationHandler.SolrInstance instance) throws Exception {
    FileUtils.copyFile(new File(SolrTestCaseJ4.TEST_HOME(), "solr.xml"), new File(instance.getHomeDir(), "solr.xml"));
    JettySolrRunner jetty = new JettySolrRunner(instance.getHomeDir(), "/solr", 0);
    jetty.setDataDir(instance.getDataDir());
    jetty.start();
    return jetty;
  }

  private static SolrClient createNewSolrClient(int port) {
    try {
      // setup the client...
      HttpSolrClient client = new HttpSolrClient(buildUrl(port, context) + "/" + DEFAULT_TEST_CORENAME);
      client.setConnectionTimeout(15000);
      client.setSoTimeout(60000);
      client.setDefaultMaxConnectionsPerHost(100);
      client.setMaxTotalConnections(100);
      return client;
    }
    catch (Exception ex) {
      throw new RuntimeException(ex);
    }
  }

  @Before
  public void setUp() throws Exception {
    super.setUp();
    String configFile = "solrconfig-master1.xml";

    if(random().nextBoolean()) {
      configFile = "solrconfig-master1-keepOneBackup.xml";
      addNumberToKeepInRequest = false;
      backupKeepParamName = ReplicationHandler.NUMBER_BACKUPS_TO_KEEP_INIT_PARAM;
    }
    master = new TestReplicationHandler.SolrInstance(createTempDir("solr-instance").toFile(), "master", null);
    master.setUp();
    master.copyConfigFile(CONF_DIR + configFile, "solrconfig.xml");

    masterJetty = createJetty(master);
    masterClient = createNewSolrClient(masterJetty.getLocalPort());
  }

  @Override
  @After
  public void tearDown() throws Exception {
    super.tearDown();
    masterClient.shutdown();
    masterClient  = null;
    masterJetty.stop();
    master.tearDown();
    masterJetty = null;
    master = null;
  }

  @Test
  public void doTestBackup() throws Exception {

    int nDocs = TestUtil.nextInt(random(), 1, 100);
    masterClient.deleteByQuery("*:*");
    for (int i = 0; i < nDocs; i++) {
      SolrInputDocument doc = new SolrInputDocument();
      doc.addField("id", i);
      doc.addField("name", "name = " + i);
      masterClient.add(doc);
    }

    masterClient.commit();

    File[] snapDir = new File[2];
    boolean namedBackup = random().nextBoolean();
    try {
      String firstBackupTimestamp = null;

      String[] backupNames = null;
      if (namedBackup) {
        backupNames = new String[2];
      }
      for (int i = 0; i < 2; i++) {
        BackupCommand backupCommand;
        final String backupName = TestUtil.randomSimpleString(random(), 1, 20);
        if (!namedBackup) {
          backupCommand = new BackupCommand(addNumberToKeepInRequest, backupKeepParamName, ReplicationHandler.CMD_BACKUP);
        } else {
          backupCommand = new BackupCommand(backupName, ReplicationHandler.CMD_BACKUP);
          backupNames[i] = backupName;
        }
        backupCommand.runCommand();

        File dataDir = new File(master.getDataDir());

        CheckBackupStatus checkBackupStatus = new CheckBackupStatus(firstBackupTimestamp);
        while (true) {
          checkBackupStatus.fetchStatus();
          if (checkBackupStatus.success) {
            if (i == 0) {
              firstBackupTimestamp = checkBackupStatus.backupTimestamp;
              Thread.sleep(1000); //ensure the next backup will have a different timestamp.
            }
            break;
          }
          Thread.sleep(200);
        }

        if (backupCommand.fail != null) {
          fail(backupCommand.fail);
        }
        File[] files = null;
        if (!namedBackup) {
          files = dataDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
              if (name.startsWith("snapshot")) {
                return true;
              }
              return false;
            }
          });
        } else {
          files = dataDir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
              if (name.equals("snapshot." + backupName)) {
                return true;
              }
              return false;
            }
          });
        }
        assertEquals(1, files.length);
        snapDir[i] = files[0];
        Directory dir = new SimpleFSDirectory(snapDir[i].getAbsoluteFile().toPath());
        IndexReader reader = DirectoryReader.open(dir);
        IndexSearcher searcher = new IndexSearcher(reader);
        TopDocs hits = searcher.search(new MatchAllDocsQuery(), 1);
        assertEquals(nDocs, hits.totalHits);
        reader.close();
        dir.close();

      }

      if (!namedBackup && snapDir[0].exists()) {
        fail("The first backup should have been cleaned up because " + backupKeepParamName + " was set to 1.");
      }

      //Test Deletion of named backup
      if(namedBackup) {
        testDeleteNamedBackup(backupNames);
      }

    } finally {
      if(!namedBackup) {
        Path toDelete[] = new Path[snapDir.length];
        for (int i = 0; i < snapDir.length; i++) {
          toDelete[i] = snapDir[i].toPath();
        }
        org.apache.lucene.util.IOUtils.rm(toDelete);
      }
    }
  }

  private void testDeleteNamedBackup(String backupNames[]) throws InterruptedException, IOException {
    String lastTimestamp = null;
    for (int i = 0; i < 2; i++) {
      BackupCommand deleteBackupCommand = new BackupCommand(backupNames[i], ReplicationHandler.CMD_DELETE_BACKUP);
      deleteBackupCommand.runCommand();
      CheckDeleteBackupStatus checkDeleteBackupStatus = new CheckDeleteBackupStatus(backupNames[i], lastTimestamp);
      while (true) {
        boolean success = checkDeleteBackupStatus.fetchStatus();
        if (success) {
          lastTimestamp = checkDeleteBackupStatus.lastTimestamp;
          if (i == 0) {
            Thread.sleep(1000); //make the timestamp change
          }
          break;
        }
        Thread.sleep(200);
      }

      if (deleteBackupCommand.fail != null) {
        fail(deleteBackupCommand.fail);
      }
    }
  }

  private class CheckBackupStatus {
    String response = null;
    boolean success = false;
    String backupTimestamp = null;
    final String lastBackupTimestamp;
    final Pattern p = Pattern.compile("<str name=\"snapshotCompletedAt\">(.*?)</str>");
    final Pattern pException = Pattern.compile("<str name=\"snapShootException\">(.*?)</str>");

    CheckBackupStatus(String lastBackupTimestamp) {
      this.lastBackupTimestamp = lastBackupTimestamp;
    }

    public void fetchStatus() throws IOException {
      String masterUrl = buildUrl(masterJetty.getLocalPort(), "/solr") + "/" + DEFAULT_TEST_CORENAME + "/replication?command=" + ReplicationHandler.CMD_DETAILS;
      URL url;
      InputStream stream = null;
      try {
        url = new URL(masterUrl);
        stream = url.openStream();
        response = IOUtils.toString(stream, "UTF-8");
        if(pException.matcher(response).find()) {
          fail("Failed to create backup");
        }
        if(response.contains("<str name=\"status\">success</str>")) {
          Matcher m = p.matcher(response);
          if(!m.find()) {
            fail("could not find the completed timestamp in response.");
          }
          backupTimestamp = m.group(1);
          if(!backupTimestamp.equals(lastBackupTimestamp)) {
            success = true;
          }
        }
        stream.close();
      } finally {
        IOUtils.closeQuietly(stream);
      }

    };
  }

  private class BackupCommand {
    String fail = null;
    final boolean addNumberToKeepInRequest;
    String backupKeepParamName;
    String backupName;
    String cmd;

    BackupCommand(boolean addNumberToKeepInRequest, String backupKeepParamName, String command) {
      this.addNumberToKeepInRequest = addNumberToKeepInRequest;
      this.backupKeepParamName = backupKeepParamName;
      this.cmd = command;
    }
    BackupCommand(String backupName, String command) {
      this.backupName = backupName;
      addNumberToKeepInRequest = false;
      this.cmd = command;
    }

    public void runCommand() {
      String masterUrl = null;
      if(backupName != null) {
        masterUrl = buildUrl(masterJetty.getLocalPort(), context) + "/" + DEFAULT_TEST_CORENAME + "/replication?command=" + cmd +
            "&name=" +  backupName;
      } else {
        masterUrl = buildUrl(masterJetty.getLocalPort(), context) + "/" + DEFAULT_TEST_CORENAME + "/replication?command=" + cmd +
            (addNumberToKeepInRequest ? "&" + backupKeepParamName + "=1" : "");
      }

      URL url;
      InputStream stream = null;
      try {
        url = new URL(masterUrl);
        stream = url.openStream();
        stream.close();
      } catch (Exception e) {
        fail = e.getMessage();
      } finally {
        IOUtils.closeQuietly(stream);
      }

    };
  }

  private class CheckDeleteBackupStatus {
    String response = null;
    private String backupName;
    final Pattern p = Pattern.compile("<str name=\"snapshotDeletedAt\">(.*?)</str>");
    String lastTimestamp;

    private CheckDeleteBackupStatus(String backupName, String lastTimestamp) {
      this.backupName = backupName;
      this.lastTimestamp = lastTimestamp;
    }

    public boolean fetchStatus() throws IOException {
      String masterUrl = buildUrl(masterJetty.getLocalPort(), context) + "/" + DEFAULT_TEST_CORENAME + "/replication?command=" + ReplicationHandler.CMD_DETAILS;
      URL url;
      InputStream stream = null;
      try {
        url = new URL(masterUrl);
        stream = url.openStream();
        response = IOUtils.toString(stream, "UTF-8");
        if(response.contains("<str name=\"status\">success</str>")) {
          Matcher m = p.matcher(response);
          if(m.find() && (lastTimestamp == null || !lastTimestamp.equals(m.group(1)))) {
            lastTimestamp = m.group(1);
            return true;
          }
        } else if(response.contains("<str name=\"status\">Unable to delete snapshot: " + backupName + "</str>" )) {
          return false;
        }
        stream.close();
      } finally {
        IOUtils.closeQuietly(stream);
      }
      return false;
    };
  }
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Nest.DSL.Query.Behaviour;
using Newtonsoft.Json;
using System.Linq.Expressions;

namespace Nest
{
	[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
	public interface IRangeQuery : IFieldNameQuery
	{
		[JsonProperty("gte")]
		string GreaterThanOrEqualTo { get; set; }

		[JsonProperty("lte")]
		string LowerThanOrEqualTo { get; set; }

		[JsonProperty("gt")]
		string GreaterThan { get; set; }

		[JsonProperty("lt")]
		string LowerThan { get; set; }

		[JsonProperty(PropertyName = "boost")]
		double? Boost { get; set; }

		[JsonProperty(PropertyName = "_cache")]
		bool? Cache { get; set; }

		[JsonProperty(PropertyName = "_name")]
		string Name { get; set; }

		PropertyPathMarker Field { get; set; }
	}
	public class RangeQuery : PlainQuery, IRangeQuery
	{
		protected override void WrapInContainer(IQueryContainer container)
		{
			container.Range = this;
		}

		bool IQuery.IsConditionless { get { return false; } }
		PropertyPathMarker IFieldNameQuery.GetFieldName()
		{
			return this.Field;
		}

		void IFieldNameQuery.SetFieldName(string fieldName)
		{
			this.Field = fieldName;
		}

		public string GreaterThanOrEqualTo { get; set; }
		public string LowerThanOrEqualTo { get; set; }
		public string GreaterThan { get; set; }
		public string LowerThan { get; set; }
		public double? Boost { get; set; }
		public bool? Cache { get; set; }
		public string Name { get; set; }
		public PropertyPathMarker Field { get; set; }
	}
	[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
	public class RangeQueryDescriptor<T> : IRangeQuery where T : class
	{
		string IRangeQuery.GreaterThanOrEqualTo { get; set; }

		string IRangeQuery.LowerThanOrEqualTo { get; set; }

		string IRangeQuery.GreaterThan { get; set; }

		string IRangeQuery.LowerThan { get; set; }

		double? IRangeQuery.Boost { get; set; }

		bool? IRangeQuery.Cache { get; set; }

		string IRangeQuery.Name { get; set; }

		PropertyPathMarker IRangeQuery.Field { get; set; }

		bool IQuery.IsConditionless
		{
			get
			{
				var rangeQuery = ((IRangeQuery)this);
				return rangeQuery.Field.IsConditionless()
					|| (
						rangeQuery.GreaterThanOrEqualTo == null
						&& rangeQuery.LowerThanOrEqualTo == null
						&& rangeQuery.GreaterThan == null
						&& rangeQuery.LowerThan == null
					);
			}
		}

		void IFieldNameQuery.SetFieldName(string fieldName)
		{
			((IRangeQuery)this).Field = fieldName;
		}

		PropertyPathMarker IFieldNameQuery.GetFieldName()
		{
			return ((IRangeQuery)this).Field;
		}

		public RangeQueryDescriptor<T> OnField(string field)
		{
			((IRangeQuery)this).Field = field;
			return this;
		}

		public RangeQueryDescriptor<T> OnField(Expression<Func<T, object>> objectPath)
		{
			((IRangeQuery)this).Field = objectPath;
			return this;
		}

		/// <summary>
		/// Boosts the range query by the specified boost factor
		/// </summary>
		/// <param name="boost">Boost factor</param>
		public RangeQueryDescriptor<T> Boost(double boost)
		{
			((IRangeQuery)this).Boost = boost;
			return this;
		}

		public RangeQueryDescriptor<T> Greater(double? from)
		{
			((IRangeQuery)this).GreaterThan = from.HasValue ? from.Value.ToString(CultureInfo.InvariantCulture) : null;
			return this;
		}
		public RangeQueryDescriptor<T> GreaterOrEquals(double? from)
		{
			((IRangeQuery)this).GreaterThanOrEqualTo = from.HasValue ? from.Value.ToString(CultureInfo.InvariantCulture) : null;
			return this;
		}
		public RangeQueryDescriptor<T> Lower(double? to)
		{
			((IRangeQuery)this).LowerThan = to.HasValue ? to.Value.ToString(CultureInfo.InvariantCulture) : null;
			return this;
		}
		public RangeQueryDescriptor<T> LowerOrEquals(double? to)
		{
			((IRangeQuery)this).LowerThanOrEqualTo = to.HasValue ? to.Value.ToString(CultureInfo.InvariantCulture) : null;
			return this;
		}

		public RangeQueryDescriptor<T> Greater(string from)
		{
			((IRangeQuery)this).GreaterThan = from;
			return this;
		}

		public RangeQueryDescriptor<T> GreaterOrEquals(string from)
		{
			((IRangeQuery)this).GreaterThanOrEqualTo = from;
			return this;
		}
		public RangeQueryDescriptor<T> Lower(string to)
		{
			((IRangeQuery)this).LowerThan = to;
			return this;
		}
		public RangeQueryDescriptor<T> LowerOrEquals(string to)
		{
			((IRangeQuery)this).LowerThanOrEqualTo = to;
			return this;
		}

		public RangeQueryDescriptor<T> Greater(DateTime? from, string format = "yyyy-MM-dd'T'HH:mm:ss.fff")
		{
			((IRangeQuery)this).GreaterThan = from.HasValue ? from.Value.ToString(format) : null;
			return this;
		}

		public RangeQueryDescriptor<T> GreaterOrEquals(DateTime? from, string format = "yyyy-MM-dd'T'HH:mm:ss.fff")
		{
			((IRangeQuery)this).GreaterThanOrEqualTo = from.HasValue ? from.Value.ToString(format) : null;
			return this;
		}

		public RangeQueryDescriptor<T> Lower(DateTime? to, string format = "yyyy-MM-dd'T'HH:mm:ss.fff")
		{
			((IRangeQuery)this).LowerThan = to.HasValue ? to.Value.ToString(format) : null;
			return this;
		}

		public RangeQueryDescriptor<T> LowerOrEquals(DateTime? to, string format = "yyyy-MM-dd'T'HH:mm:ss.fff")
		{
			((IRangeQuery)this).LowerThanOrEqualTo = to.HasValue ? to.Value.ToString(format) : null;
			return this;
		}

	}
}


text:
/**
 * @file
 * Libass subtitles burning filter.
 *
 * @see{http://www.matroska.org/technical/specs/subtitles/ssa.html}
 */

#include <ass/ass.h>

#include "config.h"
#if CONFIG_SUBTITLES_FILTER
# include "libavcodec/avcodec.h"
# include "libavformat/avformat.h"
#endif
#include "libavutil/avstring.h"
#include "libavutil/imgutils.h"
#include "libavutil/opt.h"
#include "libavutil/parseutils.h"
#include "drawutils.h"
#include "avfilter.h"
#include "internal.h"
#include "formats.h"
#include "video.h"

typedef struct {
    const AVClass *class;
    ASS_Library  *library;
    ASS_Renderer *renderer;
    ASS_Track    *track;
    char *filename;
    char *charenc;
    int stream_index;
    uint8_t rgba_map[4];
    int     pix_step[4];       ///< steps per pixel for each plane of the main output
    int original_w, original_h;
    FFDrawContext draw;
} AssContext;

#define OFFSET(x) offsetof(AssContext, x)
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM

#define COMMON_OPTIONS \
    {"filename",       "set the filename of file to read",                         OFFSET(filename),   AV_OPT_TYPE_STRING,     {.str = NULL},  CHAR_MIN, CHAR_MAX, FLAGS }, \
    {"f",              "set the filename of file to read",                         OFFSET(filename),   AV_OPT_TYPE_STRING,     {.str = NULL},  CHAR_MIN, CHAR_MAX, FLAGS }, \
    {"original_size",  "set the size of the original video (used to scale fonts)", OFFSET(original_w), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL},  CHAR_MIN, CHAR_MAX, FLAGS }, \

/* libass supports a log level ranging from 0 to 7 */
static const int ass_libavfilter_log_level_map[] = {
    AV_LOG_QUIET,               /* 0 */
    AV_LOG_PANIC,               /* 1 */
    AV_LOG_FATAL,               /* 2 */
    AV_LOG_ERROR,               /* 3 */
    AV_LOG_WARNING,             /* 4 */
    AV_LOG_INFO,                /* 5 */
    AV_LOG_VERBOSE,             /* 6 */
    AV_LOG_DEBUG,               /* 7 */
};

static void ass_log(int ass_level, const char *fmt, va_list args, void *ctx)
{
    int level = ass_libavfilter_log_level_map[ass_level];

    av_vlog(ctx, level, fmt, args);
    av_log(ctx, level, "\n");
}

static av_cold int init(AVFilterContext *ctx)
{
    AssContext *ass = ctx->priv;

    if (!ass->filename) {
        av_log(ctx, AV_LOG_ERROR, "No filename provided!\n");
        return AVERROR(EINVAL);
    }

    ass->library = ass_library_init();
    if (!ass->library) {
        av_log(ctx, AV_LOG_ERROR, "Could not initialize libass.\n");
        return AVERROR(EINVAL);
    }
    ass_set_message_cb(ass->library, ass_log, ctx);

    ass->renderer = ass_renderer_init(ass->library);
    if (!ass->renderer) {
        av_log(ctx, AV_LOG_ERROR, "Could not initialize libass renderer.\n");
        return AVERROR(EINVAL);
    }

    return 0;
}

static av_cold void uninit(AVFilterContext *ctx)
{
    AssContext *ass = ctx->priv;

    if (ass->track)
        ass_free_track(ass->track);
    if (ass->renderer)
        ass_renderer_done(ass->renderer);
    if (ass->library)
        ass_library_done(ass->library);
}

static int query_formats(AVFilterContext *ctx)
{
    ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
    return 0;
}

static int config_input(AVFilterLink *inlink)
{
    AssContext *ass = inlink->dst->priv;

    ff_draw_init(&ass->draw, inlink->format, 0);

    ass_set_frame_size  (ass->renderer, inlink->w, inlink->h);
    if (ass->original_w && ass->original_h)
        ass_set_aspect_ratio(ass->renderer, (double)inlink->w / inlink->h,
                             (double)ass->original_w / ass->original_h);

    return 0;
}

/* libass stores an RGBA color in the format RRGGBBTT, where TT is the transparency level */
#define AR(c)  ( (c)>>24)
#define AG(c)  (((c)>>16)&0xFF)
#define AB(c)  (((c)>>8) &0xFF)
#define AA(c)  ((0xFF-c) &0xFF)

static void overlay_ass_image(AssContext *ass, AVFrame *picref,
                              const ASS_Image *image)
{
    for (; image; image = image->next) {
        uint8_t rgba_color[] = {AR(image->color), AG(image->color), AB(image->color), AA(image->color)};
        FFDrawColor color;
        ff_draw_color(&ass->draw, &color, rgba_color);
        ff_blend_mask(&ass->draw, &color,
                      picref->data, picref->linesize,
                      picref->width, picref->height,
                      image->bitmap, image->stride, image->w, image->h,
                      3, 0, image->dst_x, image->dst_y);
    }
}

static int filter_frame(AVFilterLink *inlink, AVFrame *picref)
{
    AVFilterContext *ctx = inlink->dst;
    AVFilterLink *outlink = ctx->outputs[0];
    AssContext *ass = ctx->priv;
    int detect_change = 0;
    double time_ms = picref->pts * av_q2d(inlink->time_base) * 1000;
    ASS_Image *image = ass_render_frame(ass->renderer, ass->track,
                                        time_ms, &detect_change);

    if (detect_change)
        av_log(ctx, AV_LOG_DEBUG, "Change happened at time ms:%f\n", time_ms);

    overlay_ass_image(ass, picref, image);

    return ff_filter_frame(outlink, picref);
}

static const AVFilterPad ass_inputs[] = {
    {
        .name             = "default",
        .type             = AVMEDIA_TYPE_VIDEO,
        .filter_frame     = filter_frame,
        .config_props     = config_input,
        .needs_writable   = 1,
    },
    { NULL }
};

static const AVFilterPad ass_outputs[] = {
    {
        .name = "default",
        .type = AVMEDIA_TYPE_VIDEO,
    },
    { NULL }
};

#if CONFIG_ASS_FILTER

static const AVOption ass_options[] = {
    COMMON_OPTIONS
    {NULL},
};

AVFILTER_DEFINE_CLASS(ass);

static av_cold int init_ass(AVFilterContext *ctx)
{
    AssContext *ass = ctx->priv;
    int ret = init(ctx);

    if (ret < 0)
        return ret;

    /* Initialize fonts */
    ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);

    ass->track = ass_read_file(ass->library, ass->filename, NULL);
    if (!ass->track) {
        av_log(ctx, AV_LOG_ERROR,
               "Could not create a libass track when reading file '%s'\n",
               ass->filename);
        return AVERROR(EINVAL);
    }
    return 0;
}

AVFilter ff_vf_ass = {
    .name          = "ass",
    .description   = NULL_IF_CONFIG_SMALL("Render ASS subtitles onto input video using the libass library."),
    .priv_size     = sizeof(AssContext),
    .init          = init_ass,
    .uninit        = uninit,
    .query_formats = query_formats,
    .inputs        = ass_inputs,
    .outputs       = ass_outputs,
    .priv_class    = &ass_class,
};
#endif

#if CONFIG_SUBTITLES_FILTER

static const AVOption subtitles_options[] = {
    COMMON_OPTIONS
    {"charenc",      "set input character encoding", OFFSET(charenc),      AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
    {"stream_index", "set stream index",             OFFSET(stream_index), AV_OPT_TYPE_INT,    { .i64 = -1 }, -1,       INT_MAX,  FLAGS},
    {"si",           "set stream index",             OFFSET(stream_index), AV_OPT_TYPE_INT,    { .i64 = -1 }, -1,       INT_MAX,  FLAGS},
    {NULL},
};

static const char *font_mimetypes[] = {
    "application/x-truetype-font",
    "application/vnd.ms-opentype",
    "application/x-font-ttf",
    NULL
};

static int attachment_is_font(AVStream * st)
{
    const AVDictionaryEntry *tag = NULL;
    int n;

    tag = av_dict_get(st->metadata, "mimetype", NULL, AV_DICT_MATCH_CASE);

    if (tag) {
        for (n = 0; font_mimetypes[n]; n++) {
            if (av_strcasecmp(font_mimetypes[n], tag->value) == 0)
                return 1;
        }
    }
    return 0;
}

AVFILTER_DEFINE_CLASS(subtitles);

static av_cold int init_subtitles(AVFilterContext *ctx)
{
    int j, ret, sid;
    int k = 0;
    AVDictionary *codec_opts = NULL;
    AVFormatContext *fmt = NULL;
    AVCodecContext *dec_ctx = NULL;
    AVCodec *dec = NULL;
    const AVCodecDescriptor *dec_desc;
    AVStream *st;
    AVPacket pkt;
    AssContext *ass = ctx->priv;

    /* Init libass */
    ret = init(ctx);
    if (ret < 0)
        return ret;
    ass->track = ass_new_track(ass->library);
    if (!ass->track) {
        av_log(ctx, AV_LOG_ERROR, "Could not create a libass track\n");
        return AVERROR(EINVAL);
    }

    /* Open subtitles file */
    ret = avformat_open_input(&fmt, ass->filename, NULL, NULL);
    if (ret < 0) {
        av_log(ctx, AV_LOG_ERROR, "Unable to open %s\n", ass->filename);
        goto end;
    }
    ret = avformat_find_stream_info(fmt, NULL);
    if (ret < 0)
        goto end;

    /* Locate subtitles stream */
    if (ass->stream_index < 0)
        ret = av_find_best_stream(fmt, AVMEDIA_TYPE_SUBTITLE, -1, -1, NULL, 0);
    else {
        ret = -1;
        if (ass->stream_index < fmt->nb_streams) {
            for (j = 0; j < fmt->nb_streams; j++) {
                if (fmt->streams[j]->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
                    if (ass->stream_index == k) {
                        ret = j;
                        break;
                    }
                    k++;
                }
            }
        }
    }

    if (ret < 0) {
        av_log(ctx, AV_LOG_ERROR, "Unable to locate subtitle stream in %s\n",
               ass->filename);
        goto end;
    }
    sid = ret;
    st = fmt->streams[sid];

    /* Load attached fonts */
    for (j = 0; j < fmt->nb_streams; j++) {
        AVStream *st = fmt->streams[j];
        if (st->codec->codec_type == AVMEDIA_TYPE_ATTACHMENT &&
            attachment_is_font(st)) {
            const AVDictionaryEntry *tag = NULL;
            tag = av_dict_get(st->metadata, "filename", NULL,
                              AV_DICT_MATCH_CASE);

            if (tag) {
                av_log(ctx, AV_LOG_DEBUG, "Loading attached font: %s\n",
                       tag->value);
                ass_add_font(ass->library, tag->value,
                             st->codec->extradata,
                             st->codec->extradata_size);
            } else {
                av_log(ctx, AV_LOG_WARNING,
                       "Font attachment has no filename, ignored.\n");
            }
        }
    }

    /* Initialize fonts */
    ass_set_fonts(ass->renderer, NULL, NULL, 1, NULL, 1);

    /* Open decoder */
    dec_ctx = st->codec;
    dec = avcodec_find_decoder(dec_ctx->codec_id);
    if (!dec) {
        av_log(ctx, AV_LOG_ERROR, "Failed to find subtitle codec %s\n",
               avcodec_get_name(dec_ctx->codec_id));
        return AVERROR(EINVAL);
    }
    dec_desc = avcodec_descriptor_get(dec_ctx->codec_id);
    if (dec_desc && !(dec_desc->props & AV_CODEC_PROP_TEXT_SUB)) {
        av_log(ctx, AV_LOG_ERROR,
               "Only text based subtitles are currently supported\n");
        return AVERROR_PATCHWELCOME;
    }
    if (ass->charenc)
        av_dict_set(&codec_opts, "sub_charenc", ass->charenc, 0);
    ret = avcodec_open2(dec_ctx, dec, &codec_opts);
    if (ret < 0)
        goto end;

    /* Decode subtitles and push them into the renderer (libass) */
    if (dec_ctx->subtitle_header)
        ass_process_codec_private(ass->track,
                                  dec_ctx->subtitle_header,
                                  dec_ctx->subtitle_header_size);
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;
    while (av_read_frame(fmt, &pkt) >= 0) {
        int i, got_subtitle;
        AVSubtitle sub = {0};

        if (pkt.stream_index == sid) {
            ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_subtitle, &pkt);
            if (ret < 0) {
                av_log(ctx, AV_LOG_WARNING, "Error decoding: %s (ignored)\n",
                       av_err2str(ret));
            } else if (got_subtitle) {
                for (i = 0; i < sub.num_rects; i++) {
                    char *ass_line = sub.rects[i]->ass;
                    if (!ass_line)
                        break;
                    ass_process_data(ass->track, ass_line, strlen(ass_line));
                }
            }
        }
        av_free_packet(&pkt);
        avsubtitle_free(&sub);
    }

end:
    av_dict_free(&codec_opts);
    if (dec_ctx)
        avcodec_close(dec_ctx);
    if (fmt)
        avformat_close_input(&fmt);
    return ret;
}

AVFilter ff_vf_subtitles = {
    .name          = "subtitles",
    .description   = NULL_IF_CONFIG_SMALL("Render text subtitles onto input video using the libass library."),
    .priv_size     = sizeof(AssContext),
    .init          = init_subtitles,
    .uninit        = uninit,
    .query_formats = query_formats,
    .inputs        = ass_inputs,
    .outputs       = ass_outputs,
    .priv_class    = &subtitles_class,
};
#endif


text:
package com.cloudera.recordbreaker.fisheye;

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

/*****************************************************************
 * Class that serves as singleton for storing recent page views.
 * The page-specific classes log requests here; we can then
 * return listings of the most recently-seen items
 *
 * @author Mike Cafarella
 *****************************************************************/
public class RecentPages {
  static final int MAX_RECENT = 10;
  static List<String> recentLabels = new ArrayList<String>();
  static List<String> recentURLs = new ArrayList<String>();

  public static void addView(String label, String url) {
    recentLabels.add(0, label);
    recentURLs.add(0, url);
    if (recentLabels.size() > MAX_RECENT) {
      recentLabels.remove(recentLabels.size()-1);
      recentURLs.remove(recentURLs.size()-1);
    }
  }
  public static List<String> getRecentK(int k) {
    List<String> results = new ArrayList<String>();
    for (int i = 0; i < k; i++) {
      results.add(recentLabels.get(i));
      results.add(recentURLs.get(i));
    }
    return results;
  }
}


text:
<?php

namespace HtmlValidator;

/**
 * @author Espen Hovlandsdal <espen@hovlandsdal.com>
 */
class ValidatorIntegrationTest extends \PHPUnit_Framework_TestCase {

    public function setUp() {
        if (!HTML_VALIDATOR_ENABLE_INTEGRATION_TESTS) {
            $this->markTestSkipped('Integration tests disabled in configuration');
        }
    }

    public function testCanValidateUtf8Html5Document() {
        $validator = $this->getValidator();

        $document  = file_get_contents(FIXTURES_DIR . '/document-valid-utf8-html5.html');
        $response  = $validator->validateDocument($document, Validator::CHARSET_UTF_8);

        $this->assertFalse($response->hasErrors(), 'Valid UTF-8 document should produce no errors');
        $this->assertFalse($response->hasWarnings(), 'Valid UTF-8 document should produce no errors');
    }

    public function testCanValidateXmlDocument() {
        $validator = $this->getValidator(Validator::PARSER_XML);

        $document  = file_get_contents(FIXTURES_DIR . '/document-valid-xml.xml');
        $response  = $validator->validateDocument($document);

        $this->assertFalse($response->hasErrors(), 'Valid XML document should produce no errors');
        $this->assertFalse($response->hasWarnings(), 'Valid XML document should produce no warnings');
    }

    public function testCanValidateHtml4Document() {
        $validator = $this->getValidator(Validator::PARSER_HTML4);

        $document  = file_get_contents(FIXTURES_DIR . '/document-valid-html4.html');
        $response  = $validator->validateDocument($document);

        $this->assertCount(1, $response->getErrors());
        $this->assertSame('Obsolete doctype. Expected "<!DOCTYPE html>".', $response->getErrors()[0]->getText());
        $this->assertFalse($response->hasWarnings(), 'Valid HTML document should produce no warnings');
    }

    public function testDetectsErrorsOnInvalidHtml5() {
        $validator = $this->getValidator();

        $document  = file_get_contents(FIXTURES_DIR . '/document-invalid-utf8-html5.html');
        $response  = $validator->validateDocument($document, Validator::CHARSET_UTF_8);

        $this->assertTrue($response->hasErrors(), 'Invalid HTML5 should produce errors');

        // Can't guarantee order of messages, but assume this one won't go away
        $strayTagFound = false;
        foreach ($response->getErrors() as $error) {
            $strayTagFound = $strayTagFound || strpos($error->getText(), 'Stray end tag "span".') !== false;
        }

        $this->assertTrue($strayTagFound, 'Stray <span>-tag was not discovered by validator found');
    }

    public function testDetectsErrorsOnInvalidXml() {
        $validator = $this->getValidator(Validator::PARSER_XML);

        $document  = file_get_contents(FIXTURES_DIR . '/document-invalid-xml.xml');
        $response  = $validator->validateDocument($document, Validator::CHARSET_UTF_8);

        $this->assertTrue($response->hasErrors());

        // Can't guarantee order of messages, but assume this one won't go away
        $nameExpectedFound = false;
        foreach ($response->getErrors() as $error) {
            $nameExpectedFound = $nameExpectedFound || ($error->getText() === 'name expected');
        }

        $this->assertTrue($nameExpectedFound, '"name expected"-message was not found');
    }

    public function testDetectsErrorsOnInvalidHtml4() {
        $validator = $this->getValidator(Validator::PARSER_HTML4);

        $document  = file_get_contents(FIXTURES_DIR . '/document-invalid-html4.html');
        $response  = $validator->validateDocument($document, Validator::CHARSET_UTF_8);

        $this->assertTrue($response->hasErrors(), 'Invalid HTML4 should produce errors');

        // Can't guarantee order of messages, but assume this one won't go away
        $strayTagFound = false;
        foreach ($response->getErrors() as $error) {
            $strayTagFound = $strayTagFound || strpos($error->getText(), 'Stray end tag "span".') !== false;
        }

        $this->assertTrue($strayTagFound, 'Stray <span>-tag was not discovered by validator found');
    }

    public function testValidateUrl() {
        $validator = $this->getValidator();
        $response  = $validator->validateUrl('https://html-validator-fixtures.netlify.com/document-invalid-utf8-html5.html');

        $this->assertInstanceOf('\HtmlValidator\Response', $response);
        $this->assertTrue($response->hasErrors(), 'Invalid HTML5 should produce errors');

        // Can't guarantee order of messages, but assume this one won't go away
        $strayTagFound = false;
        foreach ($response->getErrors() as $error) {
            $strayTagFound = $strayTagFound || strpos($error->getText(), 'Stray end tag "span".') !== false;
        }

        $this->assertTrue($strayTagFound, 'Stray <span>-tag was not discovered by validator found');
    }

    public function testValidateUrlWith404() {
        $validator = $this->getValidator();
        $response  = $validator->validateUrl('https://www.w3.org/404');

        $this->assertInstanceOf('\HtmlValidator\Response', $response);
        $this->assertTrue($response->hasErrors(), 'Invalid HTML5 should produce errors');

        $error = $response->getErrors()[0];
        $this->assertTrue(strpos($error->getText(), '404') !== false);
    }

    public function testValidateUrlWithAllowed404() {
        $validator = $this->getValidator();
        $response  = $validator->validateUrl('https://www.w3.org/404', ['checkErrorPages' => true]);

        $fourOhFourFound = false;
        foreach ($response->getErrors() as $error) {
            $fourOhFourFound = $fourOhFourFound || strpos($error->getText(), '404') >= 0;
        }

        $this->assertTrue($fourOhFourFound, '404 was found in errors when it should have been allowed');
    }

    private function getValidator($parser = Validator::PARSER_HTML5) {
        return new Validator(HTML_VALIDATOR_URL, $parser);
    }
}


text:
#ifndef INTERFACE_WORLD_VIEW_GUI_H
#define INTERFACE_WORLD_VIEW_GUI_H

#include "Modeling/World.h"
#include "NavigationGUI.h"
#include <KrisLibrary/math3d/Ray3D.h>
using namespace Math3D;

/** @brief A generic gui with a RobotWorld which allows clicking on entities
 * and loading files.
 *
 * Note: if anything is connected to a ROS topic, OnIdle will call the ROSUpdate() hook
 * and request a redraw.
 *
 * Accepts commands:
 * - load_file fn: loads a file into the world.
 */
class WorldGUIBackend : public GLNavigationBackend
{
public:
  WorldGUIBackend(RobotWorld* world);
  virtual ~WorldGUIBackend();

  bool LoadCommandLine(int argc,const char** argv);
  bool LoadFile(const char* fn);
  //backend overloads
  virtual void Start();
  virtual bool OnIdle();
  virtual bool OnCommand(const string& cmd,const string& args);
  //GLNavigationBackend overloads
  virtual void SetWorldLights() { world->SetGLLights(); }
  Robot* ClickRobot(int x,int y,int& body,Vector3& localpt) const;
  Robot* ClickRobot(const Ray3D& r,int& body,Vector3& localpt) const;
  RigidObject* ClickObject(int x,int y,Vector3& localpt) const;
  RigidObject* ClickObject(const Ray3D& r,Vector3& localpt) const;
  virtual void RefreshIdle() { SendPauseIdle(0); }
  virtual void RenderWorld();

  virtual void DoFreeDrag(int dx,int dy,int button)
  {
    if(button == 0)  DragRotate(dx,dy);
  }

  virtual void DoCtrlDrag(int dx,int dy,int button)
  {
    if(button == 0)  DragPan(dx,dy);
  }

  virtual void DoAltDrag(int dx,int dy,int button)
  {
    if(button == 0)  DragZoom(dx,dy);
  }

  virtual void DoShiftDrag(int dx,int dy,int button)
  {
    if(button == 0) { camera.dist *= (1 + 0.01*Real(dy)); SendRefresh(); }
  }

  virtual bool OnMouseWheel(int dwheel);

  RobotWorld* world;
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Plethora.Linq;

namespace Plethora.Test.Linq
{
    [TestClass]
    public class ListHelper_Test
    {
        private readonly IList<Tuple<int, string>> orderedList = new List<Tuple<int, string>>
            {
                new Tuple<int, string>(21, "Twenty One"),
                new Tuple<int, string>(22, "Twenty Two"),
                new Tuple<int, string>(23, "Twenty Three"),
                new Tuple<int, string>(24, "Twenty Four"),
                //25 missing
                //26 missing
                new Tuple<int, string>(27, "Twenty Seven"),
                new Tuple<int, string>(28, "Twenty Eight"),
                new Tuple<int, string>(29, "Twenty Nine"),
            };

        [TestMethod]
        public void BinarySearch_Found()
        {
            // Action
            int index = orderedList.BinarySearch(tuple => tuple.Item1, 24);

            // Assert
            Assert.AreEqual(3, index);
        }

        [TestMethod]
        public void BinarySearch_NotFound()
        {
            // Action
            int index = orderedList.BinarySearch(tuple => tuple.Item1, 25);

            // Assert
            Assert.IsTrue(index < 0);
            Assert.AreEqual(4, ~index);
        }

        [TestMethod]
        public void SubList_Index()
        {
            // Action
            List<Tuple<int, string>> subList = orderedList.SubList(2).ToList();

            // Assert
            Assert.AreEqual(5, subList.Count);
            Assert.AreEqual(23, subList[0].Item1);
            Assert.AreEqual("Twenty Three", subList[0].Item2);
            Assert.AreEqual(24, subList[1].Item1);
            Assert.AreEqual("Twenty Four", subList[1].Item2);
            Assert.AreEqual(27, subList[2].Item1);
            Assert.AreEqual("Twenty Seven", subList[2].Item2);
            Assert.AreEqual(28, subList[3].Item1);
            Assert.AreEqual("Twenty Eight", subList[3].Item2);
            Assert.AreEqual(29, subList[4].Item1);
            Assert.AreEqual("Twenty Nine", subList[4].Item2);
        }

        [TestMethod]
        public void SubList_Index_Count()
        {
            // Action
            List<Tuple<int, string>> subList = orderedList.SubList(2, 3).ToList();

            // Assert
            Assert.AreEqual(3, subList.Count);
            Assert.AreEqual(23, subList[0].Item1);
            Assert.AreEqual("Twenty Three", subList[0].Item2);
            Assert.AreEqual(24, subList[1].Item1);
            Assert.AreEqual("Twenty Four", subList[1].Item2);
            Assert.AreEqual(27, subList[2].Item1);
            Assert.AreEqual("Twenty Seven", subList[2].Item2);
        }

        [TestMethod]
        public void SubList_Error_IndexPastEnd()
        {
            try
            {
                // Action
                orderedList.SubList(7);

                Assert.Fail();
            }
            catch (ArgumentException)
            {
            }
        }

        [TestMethod]
        public void SubList_Error_CountPastEnd()
        {
            try
            {
                // Action
                orderedList.SubList(3, 7);

                Assert.Fail();
            }
            catch (ArgumentException)
            {
            }
        }

        [TestMethod]
        public void SubListOrEmpty_Index()
        {
            // Action
            List<Tuple<int, string>> subList = orderedList.SubListOrEmpty(2).ToList();

            // Assert
            Assert.AreEqual(5, subList.Count);
            Assert.AreEqual(23, subList[0].Item1);
            Assert.AreEqual("Twenty Three", subList[0].Item2);
            Assert.AreEqual(24, subList[1].Item1);
            Assert.AreEqual("Twenty Four", subList[1].Item2);
            Assert.AreEqual(27, subList[2].Item1);
            Assert.AreEqual("Twenty Seven", subList[2].Item2);
            Assert.AreEqual(28, subList[3].Item1);
            Assert.AreEqual("Twenty Eight", subList[3].Item2);
            Assert.AreEqual(29, subList[4].Item1);
            Assert.AreEqual("Twenty Nine", subList[4].Item2);
        }

        [TestMethod]
        public void SubListOrEmpty_IndexPastEnd()
        {
            // Action
            List<Tuple<int, string>> subList = orderedList.SubListOrEmpty(7).ToList();

            // Assert
            Assert.AreEqual(0, subList.Count);
        }

        [TestMethod]
        public void SubListOrEmpty_Index_Count()
        {
            // Action
            List<Tuple<int, string>> subList = orderedList.SubListOrEmpty(2, 3).ToList();

            // Assert
            Assert.AreEqual(3, subList.Count);
            Assert.AreEqual(23, subList[0].Item1);
            Assert.AreEqual("Twenty Three", subList[0].Item2);
            Assert.AreEqual(24, subList[1].Item1);
            Assert.AreEqual("Twenty Four", subList[1].Item2);
            Assert.AreEqual(27, subList[2].Item1);
            Assert.AreEqual("Twenty Seven", subList[2].Item2);
        }

        [TestMethod]
        public void SubListOrEmpty_CountPastEnd()
        {
            // Action
            List<Tuple<int, string>> subList = orderedList.SubListOrEmpty(2, 7).ToList();

            // Assert
            Assert.AreEqual(5, subList.Count);
            Assert.AreEqual(23, subList[0].Item1);
            Assert.AreEqual("Twenty Three", subList[0].Item2);
            Assert.AreEqual(24, subList[1].Item1);
            Assert.AreEqual("Twenty Four", subList[1].Item2);
            Assert.AreEqual(27, subList[2].Item1);
            Assert.AreEqual("Twenty Seven", subList[2].Item2);
            Assert.AreEqual(28, subList[3].Item1);
            Assert.AreEqual("Twenty Eight", subList[3].Item2);
            Assert.AreEqual(29, subList[4].Item1);
            Assert.AreEqual("Twenty Nine", subList[4].Item2);
        }
    }
}


text:
require File.join(File.dirname(__FILE__), "drawable")
require File.join(File.dirname(__FILE__), "color")
require File.join(File.dirname(__FILE__), "region")
require File.join(File.dirname(__FILE__), "..", "mm2pixcel")

require "nkf"

module PREP # nodoc
  module Core # nodoc
    # 文字列描画構成要素クラス
    class Label < Drawable
      ALIGNS = {
        :left    => HPDFDoc::HPDF_TALIGN_LEFT,
        :right   => HPDFDoc::HPDF_TALIGN_RIGHT,
        :center  => HPDFDoc::HPDF_TALIGN_CENTER,
        :justify => HPDFDoc::HPDF_TALIGN_JUSTIFY,
      }

      @@default_values = {
        :align => "left",
        :font => "MS-Mincyo",
        :size => 12,
        :color => { :red => 0, :green => 0, :blue => 0 },
        :layer => 3,
        :expand => false,
      }

      attr_reader :region, :label, :align, :font, :color, :size, :expand

      def initialize(identifier, values = { })
        values = @@default_values.merge(key_string_to_symbol(values))
        super(identifier, values[:layer])

        @region = Region.new(values[:region][:x].mm2pixcel,
                             values[:region][:y].mm2pixcel,
                             values[:region][:width].mm2pixcel,
                             values[:region][:height].mm2pixcel)
        if values[:label].nil?
          raise "Label string cannot be blank for \"#{identifier}\""
        else
          @label = values[:label]
        end

        if ALIGNS.keys.include?(values[:align].to_sym)
          @align = ALIGNS[values[:align].to_sym]
        else
          raise "Unknown label alignment option \"#{values[:align]}\"."
        end
        if values[:font].nil? || values[:font] == ""
          raise "Lable font must be specified."
        else
          @font = values[:font]
        end
        @color = Color.new(values[:color][:red],
                           values[:color][:green],
                           values[:color][:blue])
        if values[:size].nil? || values[:size] == ""
          raise "Label size must be specified."
        else
          @size = values[:size]
        end
        @expand = values[:expand]
      end

      def expand_region(setting)
        @expand_region = @region.dup
        @expand_region.width = setting[:width] if setting[:width]
        @expand_region.height = setting[:height] if setting[:height]
      end

      # 幅と高さを返却
      def calculate_region(prep, region, value, stop_on_drawable = nil)
        if self === stop_on_drawable
          raise ReRenderJump.new(region)
        end
        puts "Calculate region for #{self.class}: #{self.identifier} region: #{region}" if ENV["DEBUG"]
        ret_region = Region.new(0, 0,
                                region.width - (@region.x + @region.width),
                                region.height - (@region.y + @region.height))
        return @region.x + @region.width, @region.y + @region.height
      end

      # 指定された領域を元に再計算して描画を実施
      def draw(prep, region, value, stop_on_drawable = nil)
        if self === stop_on_drawable
          raise ReRenderJump.new(region)
        end
        STDERR.puts("Draw on #{self.class} #{self.identifier}") if ENV['DEBUG']
        # 領域判定
        calculate_region(prep, region, value)
        # 文字列指定があるかを確認
        if value.nil? || value.to_s == ""
          string = self.label.dup
        else
          string = value.to_s
        end
        # 文字列指定に変数がある場合は判定
        string.gsub!("[[[current_page_number]]]", prep.current_page_number.to_s)
        string.gsub!("[[[total_page_count]]]", prep.total_pages.to_s)
        # 文字列の描画
        font = prep.pdf.get_font(self.font, "90ms-RKSJ-H")
        prep.current_page.begin_text
        prep.current_page.set_rgb_fill(@color.red.to_f, @color.green.to_f, @color.blue.to_f)
        region_backup = @region.dup
        if @expand_region
          @region = @expand_region.dup
          @expand_region = nil
        end
        left, top = calculate_pos(prep.current_page, region, @region.x, @region.y)
        right, bottom = left + @region.width, top - @region.height
        prep.current_page.set_font_and_size(font, @size)
        prep.current_page.text_rect(left, top, right, bottom,
                                    NKF.nkf("--oc=cp932 -W8", string), @align)
        prep.current_page.end_text
        @region = region_backup
        prep.current_page.drawed = true
      end
    end
  end
end


text:
namespace Localization.Net.Parsing
{
    /// <summary>
    /// A very simple parser that treats the entire pattern as text
    /// </summary>
    public class TextParser : ExpressionParser
    {
        public override Expression Parse(System.IO.TextReader reader, TextManager manager)
        {
            var expr = new Expression();
            expr.Parts.Add(new Text { Spelling = reader.ReadToEnd() });

            return expr;
        }
    }
}


text:
@extends('uiadmin::layouts.master')

@section('content')

Hello World

		This view is loaded from module: {!! config('uiadmin.name') !!}

@stop


text:
import postal from 'postal';

import notifications from './notifications';

/**
 * Open API spots handler.
 *
 * @author Chris Spiliotopoulos
 */
export default (function() {

  /**
   * Called when an Open API
   * definition is to be opened.
   * @param  {[type]} data [description]
   * @return {[type]}      [description]
   */
  const _onOpenApiDefinition = function(data) {
    try {

      const query = {
        active: true,
        currentWindow: true
      };

      // get the Open API URL
      const url = `pages/openapis.html?spec=${data.url}`;

      chrome.tabs.query(query, (tabs) => {
        if (tabs.length === 0) {
          return;
        }

        chrome.tabs.create({
          active: true,
          url
        });
      });

    } catch (e) {
      console.error(e);
    }
  };

  /**
   * Called when the content scanner
   * has detected an Open API spec.
   * @param  {[type]} data [description]
   * @return {[type]}      [description]
   */
  const _onOpenApiDetected = function(data) {
    try {

      // show a notification to the user
      chrome.notifications.create({
        type: 'basic',
        iconUrl: 'assets/images/logos/logo-64.png',
        title: 'The API Spots',
        message: `This page describes an Open API titled '${data.title}'.`,
        contextMessage: 'Click to explore'
      }, (notificationId) => {

        // add it to the notifications map
        notifications.addToMap(notificationId, {
          channel: 'openapis',
          topic: 'openapi.definition.open',
          data: {
            url: data.url
          }
        });
      });

    } catch (e) {
      console.error(e);
    }
  };

  /*
   * Subscribe to events
   */
  postal.subscribe({
    channel: 'openapis',
    topic: 'openapi.definition.open',
    callback: _onOpenApiDefinition
  });

  postal.subscribe({
    channel: 'content',
    topic: 'openapi.detected',
    callback: _onOpenApiDetected
  });

}());


text:
package javax.obex;

import net.sf.jour.signature.SignatureTestCase;

/**
 *
 */
public class JSR82APIObexDeclarationsTest extends SignatureTestCase {

    /* (non-Javadoc)
     * @see net.sf.jour.signature.SignatureTestCase#getAPIPath()
     */
    public String getAPIPath() {
        return getClassPath(Authenticator.class);
    }

    /* (non-Javadoc)
     * @see net.sf.jour.signature.SignatureTestCase#getSignatureXMLPath()
     */
    public String getSignatureXMLPath() {
        return "jsr82-obex-signature.xml";
    }

}


text:
package io.thebrother.tusrx.handler;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;

import org.junit.Before;
import org.junit.Test;

import io.thebrother.tusrx.handler.RequestHandlerTest.ResponseHeaderAssert;
import io.thebrother.tusrx.response.TusResponse;
import io.thebrother.tusrx.upload.TusUpload;

import rx.Observable;

public class HeadHandlerTest extends RequestHandlerTest {
    @Before
    public void init() {
        this.handler = new HeadHandler(options, request, pool);
    }

    @Test
    public void testHeadNoUploadReturns404() {
        when(pool.getUploader(any())).thenReturn(Optional.empty());

        Observable<TusResponse> response = handler.handle();

        response.single().toBlocking().subscribe(tr -> {
            assertThat(tr.getStatusCode() == 404);
        });
    }

    @Test
    public void testHeadUploadInProgressReturns200() {
        TusUpload mockUpload = mock(TusUpload.class);
        when(mockUpload.getUploadLength()).thenReturn(200L);
        when(mockUpload.getOffset()).thenReturn(new AtomicLong(10L));
        when(pool.getUploader(any())).thenReturn(Optional.of(mockUpload));

        Observable<TusResponse> response = handler.handle();

        response.single().toBlocking().subscribe(tr -> {
            assertThat(tr.getStatusCode() == 200);
        });
    }
}


text:
package index

import (
	"testing"
)

func TestLeafKDTreePoints(t *testing.T) {
	i := NewLeafKDTree(points)
	testPoints(t, i)
}

func TestLeafKDTreeBoundingBox(t *testing.T) {
	i := NewLeafKDTree(points)
	testBoundingBox(t, i)
}

func TestLeafKDTreeCircle(t *testing.T) {
	i := NewLeafKDTree(points)
	testCircle(t, i)
}


text:
/*
 *                        AT&T - PROPRIETARY
 *          THIS FILE CONTAINS PROPRIETARY INFORMATION OF
 *        AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN
 *             ACCORDANCE WITH APPLICABLE AGREEMENTS.
 *
 *          Copyright (c) 2013 AT&T Knowledge Ventures
 *              Unpublished and Not for Publication
 *                     All Rights Reserved
 */
package org.apache.openaz.xacml.api.pip;

import java.util.Properties;

import org.apache.openaz.xacml.util.FactoryException;
import org.apache.openaz.xacml.util.FactoryFinder;
import org.apache.openaz.xacml.util.XACMLProperties;

/**
 * PIPFinderFactory is the factory class for getting the configured {@link PIPFinder}.
 */
public abstract class PIPFinderFactory {
    private static final String	FACTORYID = XACMLProperties.PROP_PIPFINDERFACTORY;
    private static final String	DEFAULT_FACTORY_CLASSNAME = "org.apache.openaz.xacml.std.pip.StdPIPFinderFactory";

    protected Properties properties = null;

    /**
     * Protected constructor so this class cannot be instantiated.
     */
    protected PIPFinderFactory() {
    }

    /**
     * Gets an instance of the configured PIPFinderFactory class.
     *
     * @return the configured PIPFinderFactory
     * @throws FactoryException if there is an error instantiating the factory
     */
    public static PIPFinderFactory newInstance() throws FactoryException {
        return FactoryFinder.find(FACTORYID, DEFAULT_FACTORY_CLASSNAME, PIPFinderFactory.class);
    }

    public static PIPFinderFactory newInstance(Properties properties) throws FactoryException {
        return FactoryFinder.find(FACTORYID, DEFAULT_FACTORY_CLASSNAME, PIPFinderFactory.class, properties);
    }

    public static PIPFinderFactory newInstance(String factoryClassName, ClassLoader classLoader)
        throws FactoryException {
        return FactoryFinder.newInstance(factoryClassName, PIPFinderFactory.class, classLoader, false);
    }

    public static PIPFinderFactory newInstance(String factoryClassName) throws FactoryException {
        return FactoryFinder.newInstance(factoryClassName, PIPFinderFactory.class, null, true);
    }

    /**
     * Gets an instance of the configured PIPFinder class.
     *
     * @return an instance of the configured PIPFinder
     */
    abstract public PIPFinder getFinder() throws PIPException;

    /**
     * Gets an instance of the configured PIPFinder class.
     *
     * @return an instance of the configured PIPFinder
     */
    abstract public PIPFinder getFinder(Properties properties) throws PIPException;
}


text:
<?php

namespace MessageConsumer;

class ExampleMessageConsumer
{
    public function ProcessText($message)
    {
        $obj = \json_decode($message);
        print ' [x] Processed ' . \print_r($obj->contents->text, true) . "\n";

        return $obj;
    }

    public function ProcessSong($message)
    {
        $obj = \json_decode($message);
        print ' [x] Processed ' . \print_r($obj->contents->song, true) . "\n";

        return $obj;
    }
}