text:
.. include:: ../../Includes.txt

==========================================================================================================
Deprecation: #63603 - FileController and FileListController overwriteExistingFiles changed to string value
==========================================================================================================

See :issue:`63603`

Description
===========

The GET/POST param to tell the FileController and FileListController whether to override a file or not switched from a bool
value to a string with the possibilities of the `\TYPO3\CMS\Core\Resource\DuplicationBehavior` enumeration.

Impact
======

Extensions still using `overwriteExistingFiles = 1` will throw a deprecation warning.

Affected Installations
======================

All installations with extensions that use the BE upload functionality and supply the file override option.

Migration
=========

Change the `<input name="overwriteExistingFiles" value="1">` to `<input name="overwriteExistingFiles" value="replace">`.

redpajama_set_name: RedPajamaGithub


text:
import json

__all__ = ['MapiResponse']

class MapiResponse(object):
    def __init__(self, status, headers, content):
        self.status = status
        self.headers = headers
        self.content = content

    def json(self):
        return json.loads(self.content)

    def __iter__(self):
        yield self.status
        yield self.headers
        yield self.content


text:
export class HistoryState {
  private _maxPosition = 0
  private _backEnabled = true
  private _forwardEnabled = true
  private _currentPosition = 0

  public get backEnabled() {
    return this._backEnabled
  }

  public get forwardEnabled() {
    return this._forwardEnabled
  }

  public setMaxPosition(newLength: number) {
    this._maxPosition = newLength
    this._currentPosition = 0
    this.updateButtonsState()
  }
  public getMaxPosition() {
    return this._maxPosition
  }

  /**
   * sets the current history position, returns false if newPosition is invalid
   */
  public setCurrentPosition(newPosition: number) {
    if (newPosition < 0 || newPosition > this._maxPosition) {
      return false
    }
    this._currentPosition = newPosition
    this.updateButtonsState()

    return true
  }
  public getCurrentPosition() {
    return this._currentPosition
  }

  private updateButtonsState() {
    this._forwardEnabled = this._currentPosition !== 0
    this._backEnabled = this._currentPosition !== this._maxPosition
  }
}


text:
package reader;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import box.Token;

import properties.ExtractorProperties;
import utilities.Utility;
import extractor.ExtractorCollocationsAbstract;
import extractor.ExtractorCollocations_ITA;
/**
 * Reads from CoNLL 10 columns format; used in PANACEA project
 * @author Valeria Quochi @author Francesca Frontini @author Francesco Rubino
 * Istituto di linguistica Computazionale "A. Zampolli" - CNR Pisa - Italy

 * @param parameter file
 * @param dirname  Name of the directory with corpus files
 */
public class PanaceaCorpusReader extends InputReaderAbstract {

	private String dirname;

	public PanaceaCorpusReader(ExtractorCollocationsAbstract extractor, String dirname) {
		super(extractor);
		this.dirname = dirname;
	}

	@Override
	public void extract() {
		String line;
		BufferedReader in;

		try {
			File dir = new File(dirname);
			File[] files=new File[0];
			if (dir.isDirectory()) {
				files = dir.listFiles();
			}else if (dir.isFile()){
				//check if file contains a list of URLs
				boolean isFileURL=false;
				try{
					  FileInputStream fstream = new FileInputStream(dir);
					  DataInputStream instream = new DataInputStream(fstream);
					  BufferedReader br = new BufferedReader(new InputStreamReader(instream));
					  String strLine = br.readLine();
					  try {
						    URL url = new URL(strLine);
						    URLConnection conn = url.openConnection();
						    conn.connect();
						    isFileURL=true;
						} catch (Exception e) {
							isFileURL=false;
						}
					  //Close the input stream
					  instream.close();
					    }catch (Exception e){//Catch exception if any
					  System.err.println("Error checking URL file: " + e.getMessage());
					  }
			    ////
				if(isFileURL){
					// URLs file
					try{
						  FileInputStream fstream = new FileInputStream(dir);
						  DataInputStream instream = new DataInputStream(fstream);
						  BufferedReader br = new BufferedReader(new InputStreamReader(instream));
						  String strLine;
						  ArrayList<URL> vetfiles = new ArrayList<URL>();
						while ((strLine = br.readLine()) != null)
						{
								URL url = new URL(strLine);
								vetfiles.add(url);
								in = new BufferedReader(new InputStreamReader(url.openStream()));
								String[] token_splitted;
								while ((line = in.readLine()) != null) {
									if (line.equals("")) {
										extractor.extractMWfromPosTag(sentence);
										sentence.clear();
									} else {
										//System.out.println(line);
										token_splitted = line.split(Utility.__SPLITTER__);
										int idx = Integer.parseInt(token_splitted[Utility.__IDLINE__]);
										String token = token_splitted[Utility.__WORD__];
										String lemma = token_splitted[Utility.__LEMMA__];
										String post = token_splitted[Utility.__WPOS__];
										String posl = token_splitted[Utility.__POS__];
										String morpho = token_splitted[Utility.__MORPHO__];
										int hrel = Integer.parseInt(token_splitted[Utility.__POINTER__]);
										String relation = token_splitted[Utility.__RELATION__];
										Token the_token = new Token(idx, token, lemma, post, posl, morpho, hrel, relation);
										sentence.add(the_token);
									}
								}
								in.close();
								in = null;
						}
						//Close the input stream
						  instream.close();

					}catch (Exception e){//Catch exception if any
						  System.err.println("Error opening files from URLs: " + e.getMessage());
						  e.printStackTrace();}

				}
				else{
					//single file
					files=new File[1];
					files[0]=dir;
				}
			}
			int fileslen=files.length;
			int counterfile=0;
			for (File f : files) {
				//counterfile++; System.out.println("File "+counterfile+" of "+fileslen+";");
				if (f.isFile()) {
					in = new BufferedReader(new FileReader(f));
					//in = new BufferedReader(new InputStreamReader(url));
				    //System.out.println(">>"+f.getName());
					String[] token_splitted;
					int idx;
					String lemma;
					String post;
					String posl;
					String morpho;
					int hrel;
					String relation;
					Token the_token;
					while ((line = in.readLine()) != null) {
						if (line.equals("")) {
							extractor.extractMWfromPosTag(sentence);
							sentence.clear();
						} else {
							token_splitted = line.split(Utility.__SPLITTER__);
							idx = Integer.parseInt(token_splitted[Utility.__IDLINE__]);
							String token = token_splitted[Utility.__WORD__];
							lemma = token_splitted[Utility.__LEMMA__];
							post = token_splitted[Utility.__WPOS__];
							posl = token_splitted[Utility.__POS__];
							morpho = token_splitted[Utility.__MORPHO__];
							hrel = Integer.parseInt(token_splitted[Utility.__POINTER__]);
							relation = token_splitted[Utility.__RELATION__];
							the_token = new Token(idx, token, lemma, post, posl, morpho, hrel, relation);
							sentence.add(the_token);
						}
					}

					in.close();
					in = null;

				}

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {

		if (args.length < 1) {
			System.out.println("Usage: java -jar estrattoreMWv6.jar your_corpus file_properties [window] [aPOS] [bPOS]");
			System.exit(0); // perche v5?
		}
		try{
			ExtractorProperties.loadProperties(args[1]);
		}catch(Exception e){
			System.out.println("Usage: java -jar estrattoreMWv6.jar your_corpus file_properties [window] [aPOS] [bPOS]");
			System.exit(0);
		}
		String dirname = args[0];
		int window = 0;
		String aPOS = null;
		String bPOS=null;

		if(args.length == 3){
			window = Integer.parseInt(args[2]);
			aPOS = ExtractorProperties.getStringProperty(ExtractorProperties.__APOS__);
			bPOS = ExtractorProperties.getStringProperty(ExtractorProperties.__BPOS__);
		}else{
			if(args.length == 5){
				window = Integer.parseInt(args[2]);
				aPOS = args[3];
				bPOS = args[4];
			}else{
				window = ExtractorProperties.getIntProperty(ExtractorProperties.__WINDOW__);
				aPOS = ExtractorProperties.getStringProperty(ExtractorProperties.__APOS__);
				bPOS = ExtractorProperties.getStringProperty(ExtractorProperties.__BPOS__);
			}
		}
		if (ExtractorProperties.getBooleanProperty(ExtractorProperties.__LOG__)) {
			System.out.println("Multiword Extraction in: " + dirname);
			System.out.println("START " + Utility.getCurrentDate());
		}
		ExtractorCollocationsAbstract extractor = null;
		InputReaderAbstract reader;
		File file_descriptor = new File(dirname);
		if(file_descriptor.isDirectory() || file_descriptor.isFile()){
			extractor = new ExtractorCollocations_ITA(aPOS, bPOS,window);
			reader = new PanaceaCorpusReader(extractor, dirname);
			reader.extract();
			//System.out.println("END " + Utility.getCurrentDate());
			extractor.writeResult(dirname);
		}
		else{
			System.out.println("Problem reading "+dirname);
		}
		if (ExtractorProperties.getBooleanProperty(ExtractorProperties.__LOG__)) {
			System.out.println("END " + Utility.getCurrentDate());
		}
	}
}


text:
{% load helplink %}
{% load editor_controls %}

            {% if dynamic_label %}{% else %}{{label}}{% endif %}
            {% if help_url %}{% helplink help_url %}{% endif %}

            {% jme_input property disable=disable parser=parser rules=rules display_property=display_property %}


text:
package org.apache.hadoop.hbase;

import static org.junit.Assert.assertEquals;

import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.chaos.factories.MonkeyConstants;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category(SmallTests.class)
public class TestIntegrationTestBase {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestIntegrationTestBase.class);

  @Test
  public void testMonkeyPropertiesParsing() {
    final Configuration conf = new Configuration(false);
    conf.set(MonkeyConstants.BATCH_RESTART_RS_RATIO, "0.85");
    conf.set(MonkeyConstants.MOVE_REGIONS_MAX_TIME, "60000");
    conf.set("hbase.rootdir", "/foo/bar/baz");

    final Properties props = new Properties();
    IntegrationTestBase testBase = new IntegrationTestDDLMasterFailover();
    assertEquals(0, props.size());
    testBase.loadMonkeyProperties(props, conf);
    assertEquals(2, props.size());
    assertEquals("0.85", props.getProperty(MonkeyConstants.BATCH_RESTART_RS_RATIO));
    assertEquals("60000", props.getProperty(MonkeyConstants.MOVE_REGIONS_MAX_TIME));
  }
}


text:
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;

namespace ClauseLibrary.Common
{
    /// <summary>
    /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
    /// </summary>
    public class SharePointContextToken : JsonWebSecurityToken
    {
        /// <summary>
        /// Creates the specified context token.
        /// </summary>
        /// <param name="contextToken">The context token.</param>
        /// <returns></returns>
        public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
        {
            return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom,
                contextToken.ValidTo, contextToken.Claims);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SharePointContextToken"/> class.
        /// </summary>
        /// <param name="issuer">The issuer.</param>
        /// <param name="audience">The audience.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="claims">The claims.</param>
        public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo,
            IEnumerable<JsonWebTokenClaim> claims)
            : base(issuer, audience, validFrom, validTo, claims)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SharePointContextToken"/> class.
        /// </summary>
        /// <param name="issuer">The issuer.</param>
        /// <param name="audience">The audience.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="claims">The claims.</param>
        /// <param name="issuerToken">The issuer token.</param>
        /// <param name="actorToken">The actor token.</param>
        public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo,
            IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
            : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SharePointContextToken"/> class.
        /// </summary>
        /// <param name="issuer">The issuer.</param>
        /// <param name="audience">The audience.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="claims">The claims.</param>
        /// <param name="signingCredentials">The signing credentials.</param>
        public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo,
            IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
            : base(issuer, audience, validFrom, validTo, claims, signingCredentials)
        {
        }

        /// <summary>
        /// Gets the name identifier.
        /// </summary>
        /// <value>
        /// The name identifier.
        /// </value>
        public string NameId
        {
            get { return GetClaimValue(this, "nameid"); }
        }

        /// <summary>
        /// The principal name portion of the context token's "appctxsender" claim
        /// </summary>
        public string TargetPrincipalName
        {
            get
            {
                string appctxsender = GetClaimValue(this, "appctxsender");

                if (appctxsender == null)
                {
                    return null;
                }

                return appctxsender.Split('@')[0];
            }
        }

        /// <summary>
        /// The context token's "refreshtoken" claim
        /// </summary>
        public string RefreshToken
        {
            get { return GetClaimValue(this, "refreshtoken"); }
        }

        /// <summary>
        /// The context token's "CacheKey" claim
        /// </summary>
        public string CacheKey
        {
            get
            {
                string appctx = GetClaimValue(this, "appctx");
                if (appctx == null)
                {
                    return null;
                }

                ClientContext ctx = new ClientContext("http://tempuri.org");
                Dictionary<string, object> dict = (Dictionary<string, object>) ctx.ParseObjectFromJsonString(appctx);
                string cacheKey = (string) dict["CacheKey"];

                return cacheKey;
            }
        }

        /// <summary>
        /// The context token's "SecurityTokenServiceUri" claim
        /// </summary>
        public string SecurityTokenServiceUri
        {
            get
            {
                string appctx = GetClaimValue(this, "appctx");
                if (appctx == null)
                {
                    return null;
                }

                ClientContext ctx = new ClientContext("http://tempuri.org");
                Dictionary<string, object> dict = (Dictionary<string, object>) ctx.ParseObjectFromJsonString(appctx);
                string securityTokenServiceUri = (string) dict["SecurityTokenServiceUri"];

                return securityTokenServiceUri;
            }
        }

        /// <summary>
        /// The realm portion of the context token's "audience" claim
        /// </summary>
        public string Realm
        {
            get
            {
                string aud = Audience;
                if (aud == null)
                {
                    return null;
                }

                string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);

                return tokenRealm;
            }
        }

        private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }

            foreach (JsonWebTokenClaim claim in token.Claims)
            {
                if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
                {
                    return claim.Value;
                }
            }

            return null;
        }
    }
}

#region License
// ClauseLibrary, https://github.com/OfficeDev/clauselibrary
//
// Copyright 2015(c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#endregion


text:
'use strict';

/**
 * Module dependencies
 */

var path = require('path');
var globalDir = require('global-modules');
var extend = require('extend-shallow');
var lookup = require('look-up');
var read = require('read-data');
var homedir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;

/**
 * Returns an object from parsing JSON or YAML from the given
 * config file. Uses `config.resolve` to resolve the filepath.
 * If no filepath is specified, `config.resolve` falls back to
 * 'package.json'
 *
 * ```js
 * var opts = config('.jshintrc');
 * ```
 * @param {String} `filename` The name of the file to parse
 * @param {Object} `options` Optionally specify `{parse:'json'}` or `{parse:'yaml'}`
 * @return {Object}
 * @api public
 */

function config(filename, options) {
  return config.parse(filename, options);
}

/**
 * Expose `globalDir`
 */

config.globalDir = globalDir;

/**
 * Parse a config file located in a locally installed npm
 * package (in `node_modules`).
 *
 * ```js
 * var data = config.npm('read-data', 'package.json');
 * //=> { name: "read-data", ... }
 * ```
 * @param {String} `moduleName` The name of the npm package to search in `node_modules`
 * @param {String} `filename` Name of the file to find.
 * @param {Object} `options`
 * @api public
 */

config.npm = function npmConfig(moduleName, filename, opts) {
  if (typeof filename === 'object') {
    opts = filename;
    filename = null;
  }

  opts = opts || {};
  var base = path.join('node_modules', opts.base || '', moduleName);
  opts.cwd = path.resolve(opts.cwd || '', base);
  return config.parse(filename, opts);
};

/**
 * Parse a config file in a globally installed npm package.
 *
 * ```js
 * var data = config.global('verb-cli', 'package.json');
 * //=> { name: "verb-cli", ... }
 * ```
 * @param {String} `moduleName` The name of the global module to search
 * @param {String} `filename` Name of the file to find.
 * @param {Object} `options`
 * @api public
 */

config.global = function globalConfig(moduleName, filename, opts) {
  if (typeof filename === 'object') {
    opts = filename;
    filename = null;
  }

  opts = opts || {};
  opts.cwd = path.resolve(globalDir, opts.cwd || '', moduleName);
  return config.parse(filename, opts);
};

/**
 * Return a filepath the user's home directory
 *
 * ```js
 * var data = config.home('.jshintrc');
 * ```
 * @param {String} `filepath` Filepath to find
 * @param {Object} `options`
 * @api public
 */

config.home = function homeConfig(filename, opts) {
  opts = opts || {};
  var cwd = path.join(homedir, opts.cwd || '');
  return config.parse(filename, { cwd: cwd });
};

/**
 * Returns the fully resolve path for the specified config file.
 * Searches the local project first, then the user's home directory.
 *
 * ```js
 * var fp = config.resolve('.jshintrc');
 * //=> '/Users/jonschlinkert/dev/config-file/package.json'
 * ```
 * @param   {String} `filepath` Filepath to find
 * @param   {Object} `options`
 * @returns {String} filepath to config file
 * @api public
 */

config.resolve = function resolveConfig(filename, options) {
  if (typeof filename === 'object') {
    options = filename;
    filename = null;
  }
  var opts = extend({cwd: process.cwd()}, options);
  filename = filename || 'package.json';
  return lookup(filename, opts);
};

/**
 * Parse a config file. Same as using `config()`.
 *
 * ```js
 * var data = config.parse('.jshintrc');
 * ```
 * @param  {String} `filename` Name of the file to parse.
 * @param  {Object} `options`
 * @return {Object}
 * @api public
 */

config.parse = function parseConfig(filename, options) {
  filename = filename || 'package.json';
  var opts = extend({ parse: type(filename, options) }, options);
  var fp = config.resolve(filename, opts);
  try {
    return read.data.sync(fp, opts);
  } catch (err) {}
  return null;
};

/**
 * Detect the type to parse, JSON or YAML. Sometimes this is based on file extension,
 * other times it must be specified on the options.
 *
 * @param  {String} `filename`
 * @param  {Object} `opts` If `filename` does not have an extension, specify the type on the `parse` option.
 * @return {String} The type to parse.
 */

function type(filename, opts) {
  opts = opts || {};
  if (opts.parse && typeof opts.parse === 'string') {
    return opts.parse;
  }
  var ext = path.extname(filename);
  return ext || 'json';
}

/**
 * Expose `config`
 */

module.exports = config;


text:
const {spawnLightningCluster} = require('ln-docker-daemons');
const {test} = require('@alexbosworth/tap');

const {getFeeRates} = require('./../../');
const {setupChannel} = require('./../macros');

const defaultBaseFee = 1;
const defaultFeeRate = 1;
const size = 2;

// Getting fee rates should return the fee rates of nodes in the channel graph
test(`Get fee rates`, async ({end, equal}) => {
  const {kill, nodes} = await spawnLightningCluster({size});

  const [{generate, lnd}, to] = nodes;

  const channelOpen = await setupChannel({generate, lnd, to});

  const {channels} = await getFeeRates({lnd});

  equal(channels.length, [channelOpen].length, 'Channel was opened');

  const [channel] = channels || [{}];

  if (!!channel.id) {
    equal(channel.id, channelOpen.id, 'Channel id is represented');
  }

  equal(channel.base_fee, defaultFeeRate, 'Channel base fee');
  equal(channel.base_fee_mtokens, (defaultFeeRate * 1000)+'', 'Base fee mtok');
  equal(channel.fee_rate, defaultBaseFee, 'Channel fee rate');
  equal(channel.transaction_id, channelOpen.transaction_id, 'Channel tx id');
  equal(channel.transaction_vout, channelOpen.transaction_vout, 'Tx vout');

  await kill({});

  return end();
});


text:
import stts
mystts = stts.kit()
print(mystts.test);


text:
package org.apereo.cas.support.saml;

import org.apereo.cas.support.saml.util.Saml20ObjectBuilderTests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * Tests the module.
 *
 * @author Jerome Leleu
 * @since 6.0.0
 */
@RunWith(Suite.class)
@Suite.SuiteClasses(Saml20ObjectBuilderTests.class)
public class AllTestsSuite {
}


text:
using System;
using Cake.Core.IO;
using NSubstitute;
using Xunit;

namespace Cake.Core.Tests.Unit.IO
{
    public sealed class DirectoryPathTests
    {
        public sealed class TheGetDirectoryNameMethod
        {
            [Theory]
            [InlineData("C:/Data", "Data")]
            [InlineData("C:/Data/Work", "Work")]
            [InlineData("C:/Data/Work/file.txt", "file.txt")]
            public void Should_Return_Directory_Name(string directoryPath, string name)
            {
                // Given
                var path = new DirectoryPath(directoryPath);

                // When
                var result = path.GetDirectoryName();

                // Then
                Assert.Equal(name, result);
            }
        }

        public sealed class TheGetFilePathMethod
        {
            [Fact]
            public void Should_Throw_If_Path_Is_Null()
            {
                // Given
                var path = new DirectoryPath("assets");

                // When
                var result = Record.Exception(() => path.GetFilePath(null));

                // Then
                Assert.IsArgumentNullException(result, "path");
            }

            [Theory]
#if !UNIX
            [InlineData("c:/assets/shaders/", "simple.frag", "c:/assets/shaders/simple.frag")]
            [InlineData("c:/", "simple.frag", "c:/simple.frag")]
            [InlineData("c:/assets/shaders/", "test/simple.frag", "c:/assets/shaders/simple.frag")]
            [InlineData("c:/", "test/simple.frag", "c:/simple.frag")]
#endif
            [InlineData("assets/shaders", "simple.frag", "assets/shaders/simple.frag")]
            [InlineData("assets/shaders/", "simple.frag", "assets/shaders/simple.frag")]
            [InlineData("/assets/shaders/", "simple.frag", "/assets/shaders/simple.frag")]
            [InlineData("assets/shaders", "test/simple.frag", "assets/shaders/simple.frag")]
            [InlineData("assets/shaders/", "test/simple.frag", "assets/shaders/simple.frag")]
            [InlineData("/assets/shaders/", "test/simple.frag", "/assets/shaders/simple.frag")]
            public void Should_Combine_Paths(string first, string second, string expected)
            {
                // Given
                var path = new DirectoryPath(first);

                // When
                var result = path.GetFilePath(new FilePath(second));

                // Then
                Assert.Equal(expected, result.FullPath);
            }
        }

        public sealed class TheCombineWithFilePathMethod
        {
            [Fact]
            public void Should_Throw_If_Path_Is_Null()
            {
                // Given
                var path = new DirectoryPath("assets");

                // When
                var result = Record.Exception(() => path.CombineWithFilePath(null));

                // Then
                Assert.IsArgumentNullException(result, "path");
            }

            [Theory]
#if !UNIX
            [InlineData("c:/assets/shaders/", "simple.frag", "c:/assets/shaders/simple.frag")]
            [InlineData("c:/", "simple.frag", "c:/simple.frag")]
            [InlineData("c:/assets/shaders/", "test/simple.frag", "c:/assets/shaders/test/simple.frag")]
            [InlineData("c:/", "test/simple.frag", "c:/test/simple.frag")]
#endif
            [InlineData("assets/shaders", "simple.frag", "assets/shaders/simple.frag")]
            [InlineData("assets/shaders/", "simple.frag", "assets/shaders/simple.frag")]
            [InlineData("/assets/shaders/", "simple.frag", "/assets/shaders/simple.frag")]
            [InlineData("assets/shaders", "test/simple.frag", "assets/shaders/test/simple.frag")]
            [InlineData("assets/shaders/", "test/simple.frag", "assets/shaders/test/simple.frag")]
            [InlineData("/assets/shaders/", "test/simple.frag", "/assets/shaders/test/simple.frag")]
            public void Should_Combine_Paths(string first, string second, string expected)
            {
                // Given
                var path = new DirectoryPath(first);

                // When
                var result = path.CombineWithFilePath(new FilePath(second));

                // Then
                Assert.Equal(expected, result.FullPath);
            }

            [Fact]
            public void Can_Not_Combine_Directory_Path_With_Absolute_File_Path()
            {
                // Given
                var path = new DirectoryPath("assets");

                // When
                var result = Record.Exception(() => path.CombineWithFilePath(new FilePath("/other/asset.txt")));

                // Then
                Assert.IsType<InvalidOperationException>(result);
                Assert.Equal("Cannot combine a directory path with an absolute file path.", result.Message);
            }
        }

        public sealed class TheCombineWithDirectoryPathMethod
        {
            [Theory]
#if !UNIX
            [InlineData("c:/assets/shaders/", "simple", "c:/assets/shaders/simple")]
            [InlineData("c:/", "simple", "c:/simple")]
#endif
            [InlineData("assets/shaders", "simple", "assets/shaders/simple")]
            [InlineData("assets/shaders/", "simple", "assets/shaders/simple")]
            [InlineData("/assets/shaders/", "simple", "/assets/shaders/simple")]
            public void Should_Combine_Paths(string first, string second, string expected)
            {
                // Given
                var path = new DirectoryPath(first);

                // When
                var result = path.Combine(new DirectoryPath(second));

                // Then
                Assert.Equal(expected, result.FullPath);
            }

            [Fact]
            public void Should_Throw_If_Path_Is_Null()
            {
                // Given
                var path = new DirectoryPath("assets");

                // When
                var result = Record.Exception(() => path.Combine(null));

                // Then
                Assert.IsArgumentNullException(result, "path");
            }

            [Fact]
            public void Can_Not_Combine_Directory_Path_With_Absolute_Directory_Path()
            {
                // Given
                var path = new DirectoryPath("assets");

                // When
                var result = Record.Exception(() => path.Combine(new DirectoryPath("/other/assets")));

                // Then
                Assert.IsType<InvalidOperationException>(result);
                Assert.Equal("Cannot combine a directory path with an absolute directory path.", result.Message);
            }
        }

        public sealed class TheMakeAbsoluteMethod
        {
            public sealed class ThatTakesAnEnvironment
            {
                [Fact]
                public void Should_Throw_If_Provided_Environment_Is_Null()
                {
                    // Given
                    var path = new DirectoryPath("assets");

                    // When
                    var result = Record.Exception(
                        () => path.MakeAbsolute((ICakeEnvironment) null));

                    // Then
                    Assert.IsArgumentNullException(result, "environment");
                }

                [Fact]
                public void Should_Create_New_Absolute_Path_When_Path_Is_Relative()
                {
                    // Given
                    var environment = Substitute.For<ICakeEnvironment>();
                    environment.WorkingDirectory.Returns("/Working");
                    var path = new DirectoryPath("assets");

                    // When
                    var result = path.MakeAbsolute(environment);

                    // Then
                    Assert.Equal("/Working/assets", result.FullPath);
                }

                [Fact]
                public void Should_Create_New_Absolute_Path_Identical_To_The_Path()
                {
                    // Given
                    var environment = Substitute.For<ICakeEnvironment>();
                    var path = new DirectoryPath("/assets");

                    // When
                    var result = path.MakeAbsolute(environment);

                    // Then
                    Assert.Equal("/assets", result.FullPath);
                }
            }

            public sealed class ThatTakesAnotherDirectoryPath
            {
                [Fact]
                public void Should_Throw_If_Provided_Path_Is_Null()
                {
                    // Given
                    var path = new DirectoryPath("assets");

                    // When
                    var result = Record.Exception(
                        () => path.MakeAbsolute((DirectoryPath)null));

                    // Then
                    Assert.IsArgumentNullException(result, "path");
                }

                [Fact]
                public void Should_Throw_If_Provided_Path_Is_Relative()
                {
                    // Given
                    var path = new DirectoryPath("assets");

                    // When
                    var result = Record.Exception(() => path.MakeAbsolute("Working"));

                    // Then
                    Assert.IsType<CakeException>(result);
                    Assert.Equal("The provided path cannot be relative.", result.Message);
                }

                [Fact]
                public void Should_Create_New_Absolute_Path_When_Path_Is_Relative()
                {
                    // Given
                    var path = new DirectoryPath("assets");

                    // When
                    var result = path.MakeAbsolute("/absolute");

                    // Then
                    Assert.Equal("/absolute/assets", result.FullPath);
                }

                [Fact]
                public void Should_Create_New_Absolute_Path_Identical_To_The_Path()
                {
                    // Given
                    var path = new DirectoryPath("/assets");

                    // When
                    var result = path.MakeAbsolute("/absolute");

                    // Then
                    Assert.Equal("/assets", result.FullPath);
                }
            }
        }
    }
}


text:
package redis

import (
	"runtime/debug"
	"testing"
)

func Test_redisIterator(t *testing.T) {
	assertRedisIterator(t, &redisIterator{
		current: 0,
		keys: []string{
			"key1",
			"val1",
			offsetKey,
			"123",
			"key2",
			"val2",
		},
	})
	assertRedisIterator(t, &redisIterator{
		current: 0,
		keys: []string{
			offsetKey,
			"123",
			"key1",
			"val1",
			"key2",
			"val2",
		},
	})
	assertRedisIterator(t, &redisIterator{
		current: 0,
		keys: []string{
			"key1",
			"val1",
			"key2",
			"val2",
			offsetKey,
			"123",
		},
	})
}

func assertRedisIterator(t *testing.T, it *redisIterator) {
	// the iterator contract implies we must call `Next()` first
	it.Next()
	assertRedisIteratorKey(t, it, "key1", "val1")

	it.Next()
	assertRedisIteratorKey(t, it, "key2", "val2")

	it.Next()
	if !it.exhausted() {
		t.Fatalf("Expected iterator to be exhausted in %s", string(debug.Stack()))
	}
}

func assertRedisIteratorKey(t *testing.T, it *redisIterator, expectedKey string, expectedValue string) {
	if it.exhausted() {
		t.Fatalf("Did not expect iterator to be exhausted in %s", string(debug.Stack()))
	}

	actualKey := string(it.Key())
	if actualKey != expectedKey {
		t.Fatalf("Expected iterator key to be '%s', but was '%s' in %s", expectedKey, actualKey, string(debug.Stack()))
	}

	actualValue, _ := it.Value()
	if string(actualValue) != expectedValue {
		t.Fatalf("Expected iterator value to be '%s', but was '%s' in %s", expectedValue, actualValue, string(debug.Stack()))
	}
}


text:
	import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test1  extends Test2{

	@Test
	public void firstTest(){
	 login();
	 driver.quit();
	}
	@Test
    public void firefoxTest() throws InterruptedException{

    WebDriver driver = new FirefoxDriver();
		//WebDriver driver = new ChromeDriver();
		driver.get("http://www.google.com");

		Thread.sleep(700);
		//driver.close();
		driver.quit();

	}
}


text:
using System;
using JSIL.Meta;
using JSIL.Proxy;

public static class ProxiedClass {
    public static int Fn (int x) {
        return x * 2;
    }
}

[JSProxy(
    typeof(ProxiedClass),
    JSProxyMemberPolicy.ReplaceDeclared
)]
public abstract class ProxiedClassProxy {
    [JSReplacement("($value * 2)")]
    public static AnyType Fn (AnyType value) {
        throw new InvalidOperationException();
    }
}

public static class Program {
    public static void Main (string[] args) {
        Console.WriteLine("{0} {1}", ProxiedClass.Fn(1), ProxiedClass.Fn(2));
    }
}


text:
import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[hoverHighlight]'
})
export class HoverHighlightDirective {
  private el: HTMLElement;

  constructor(el: ElementRef) {
    this.el = el.nativeElement;
  }

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string) {
    this.el.style.backgroundColor = color;
  }
}


text:
package io.crate.sql.tree;

import java.util.Objects;

import static java.util.Objects.requireNonNull;

public class ComparisonExpression extends Expression {

    public enum Type {
        EQUAL("="),
        NOT_EQUAL("<>"),
        LESS_THAN("<"),
        LESS_THAN_OR_EQUAL("<="),
        GREATER_THAN(">"),
        GREATER_THAN_OR_EQUAL(">="),
        CONTAINED_WITHIN("<<"),
        IS_DISTINCT_FROM("IS DISTINCT FROM"),
        REGEX_MATCH("~"),
        REGEX_NO_MATCH("!~"),
        REGEX_MATCH_CI("~*"),
        REGEX_NO_MATCH_CI("!~*");

        private final String value;

        Type(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

    }

    private final Type type;
    private final Expression left;
    private final Expression right;

    public ComparisonExpression(Type type, Expression left, Expression right) {
        this.type = type;
        this.left = requireNonNull(left, "left is null");
        this.right = requireNonNull(right, "right is null");
    }

    public Type getType() {
        return type;
    }

    public Expression getLeft() {
        return left;
    }

    public Expression getRight() {
        return right;
    }

    @Override
    public <R, C> R accept(AstVisitor<R, C> visitor, C context) {
        return visitor.visitComparisonExpression(this, context);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        ComparisonExpression that = (ComparisonExpression) o;
        return type == that.type &&
               Objects.equals(left, that.left) &&
               Objects.equals(right, that.right);
    }

    @Override
    public int hashCode() {
        return Objects.hash(type, left, right);
    }
}


text:
module Capistrano
  class Configuration
    module Connections
      def execute_on_servers(options={})
        raise ArgumentError, "expected a block" unless block_given?

        if task = current_task
          servers = find_servers_for_task(task, options)

          if servers.empty?
            #raise Capistrano::NoMatchingServersError, "`#{task.fully_qualified_name}' is only run for servers matching #{task.options.inspect}, but no servers matched"
            logger.info "skipping `#{task.fully_qualified_name}' because no servers matched"
            return
          end

          if task.continue_on_error?
            servers.delete_if { |s| has_failed?(s) }
            return if servers.empty?
          end
        else
          servers = find_servers(options)
          raise Capistrano::NoMatchingServersError, "no servers found to match #{options.inspect}" if servers.empty?
        end

        servers = [servers.first] if options[:once]
        logger.trace "servers: #{servers.map { |s| s.host }.inspect}"

        max_hosts = (options[:max_hosts] || (task && task.max_hosts) || servers.size).to_i
        is_subset = max_hosts < servers.size

        # establish connections to those servers in groups of max_hosts, as necessary
        servers.each_slice(max_hosts) do |servers_slice|
          begin
            establish_connections_to(servers_slice)
          rescue ConnectionError => error
            raise error unless task && task.continue_on_error?
            error.hosts.each do |h|
              servers_slice.delete(h)
              failed!(h)
            end
          end

          begin
            yield servers_slice
          rescue RemoteError => error
            raise error unless task && task.continue_on_error?
            error.hosts.each { |h| failed!(h) }
          end

          # if dealing with a subset (e.g., :max_hosts is less than the
          # number of servers available) teardown the subset of connections
          # that were just made, so that we can make room for the next subset.
          teardown_connections_to(servers_slice) if is_subset
        end
      end
    end
  end
end


text:
let midnight = new Date(2019, 3, 4, 0);
let noon = new Date(2019, 3, 4, 12);
let df_11 = new Intl.DateTimeFormat(
    "en", {hour: "numeric", minute: "numeric", hourCycle: "h11"})
assertEquals("h11", df_11.resolvedOptions().hourCycle);
assertEquals("0:00 AM", df_11.formatRange(midnight, midnight));
assertEquals("0:00 PM", df_11.formatRange(noon, noon));

let df_11_t = new Intl.DateTimeFormat(
    "en", {timeStyle: "short", hourCycle: "h11"})
assertEquals("h11", df_11_t.resolvedOptions().hourCycle);
assertEquals("0:00 AM", df_11_t.formatRange(midnight, midnight));
assertEquals("0:00 PM", df_11_t.formatRange(noon, noon));

let df_11_dt = new Intl.DateTimeFormat(
    "en", {timeStyle: "short", dateStyle: "short", hourCycle: "h11"})
assertEquals("h11", df_11_dt.resolvedOptions().hourCycle);
assertEquals("4/4/19, 0:00 AM", df_11_dt.formatRange(midnight, midnight));
assertEquals("4/4/19, 0:00 PM", df_11_dt.formatRange(noon, noon));

let df_12 = new Intl.DateTimeFormat(
    "en", {hour: "numeric", minute: "numeric", hourCycle: "h12"})
assertEquals("h12", df_12.resolvedOptions().hourCycle);
assertEquals("12:00 AM", df_12.formatRange(midnight, midnight));
assertEquals("12:00 PM", df_12.formatRange(noon, noon));

let df_12_t = new Intl.DateTimeFormat(
    "en", {timeStyle: "short", hourCycle: "h12"})
assertEquals("h12", df_12_t.resolvedOptions().hourCycle);
assertEquals("12:00 AM", df_12_t.formatRange(midnight, midnight));
assertEquals("12:00 PM", df_12_t.formatRange(noon, noon));

let df_12_dt = new Intl.DateTimeFormat(
    "en", {timeStyle: "short", dateStyle: "short", hourCycle: "h12"})
assertEquals("h12", df_12_dt.resolvedOptions().hourCycle);
assertEquals("4/4/19, 12:00 AM", df_12_dt.formatRange(midnight, midnight));
assertEquals("4/4/19, 12:00 PM", df_12_dt.formatRange(noon, noon));

let df_23 = new Intl.DateTimeFormat(
    "en", {hour: "numeric", minute: "numeric", hourCycle: "h23"})
assertEquals("h23", df_23.resolvedOptions().hourCycle);
assertEquals("00:00", df_23.formatRange(midnight, midnight));
assertEquals("12:00" ,df_23.formatRange(noon, noon));

let df_23_t = new Intl.DateTimeFormat(
    "en", {timeStyle: "short", hourCycle: "h23"})
assertEquals("h23", df_23_t.resolvedOptions().hourCycle);
assertEquals("00:00", df_23_t.formatRange(midnight, midnight));
assertEquals("12:00" ,df_23_t.formatRange(noon, noon));

let df_23_dt = new Intl.DateTimeFormat(
    "en", {timeStyle: "short", dateStyle: "short", hourCycle: "h23"})
assertEquals("h23", df_23_dt.resolvedOptions().hourCycle);
assertEquals("4/4/19, 00:00", df_23_dt.formatRange(midnight, midnight));
assertEquals("4/4/19, 12:00" ,df_23_dt.formatRange(noon, noon));

let df_24 = new Intl.DateTimeFormat(
    "en", {hour: "numeric", minute: "numeric", hourCycle: "h24"})
assertEquals("h24", df_24.resolvedOptions().hourCycle);
assertEquals("24:00", df_24.formatRange(midnight, midnight));
assertEquals("12:00", df_24.formatRange(noon, noon));

let df_24_t = new Intl.DateTimeFormat(
    "en", {timeStyle: "short", hourCycle: "h24"})
assertEquals("h24", df_24_t.resolvedOptions().hourCycle);
assertEquals("24:00", df_24_t.formatRange(midnight, midnight));
assertEquals("12:00", df_24_t.formatRange(noon, noon));

let df_24_dt = new Intl.DateTimeFormat(
    "en", {timeStyle: "short", dateStyle: "short", hourCycle: "h24"})
assertEquals("h24", df_24_dt.resolvedOptions().hourCycle);
assertEquals("4/4/19, 24:00", df_24_dt.formatRange(midnight, midnight));
assertEquals("4/4/19, 12:00", df_24_dt.formatRange(noon, noon));

let df_11_ja = new Intl.DateTimeFormat(
    "ja-JP", {hour: "numeric", minute: "numeric", hourCycle: "h11"})
assertEquals("h11", df_11_ja.resolvedOptions().hourCycle);
assertEquals("午前0:00", df_11_ja.formatRange(midnight, midnight));
assertEquals("午後0:00", df_11_ja.formatRange(noon, noon));

let df_11_ja_t = new Intl.DateTimeFormat(
    "ja-JP", {timeStyle: "short", hourCycle: "h11"})
assertEquals("h11", df_11_ja_t.resolvedOptions().hourCycle);
assertEquals("午前0:00", df_11_ja_t.formatRange(midnight, midnight));
assertEquals("午後0:00", df_11_ja_t.formatRange(noon, noon));

let df_11_ja_dt = new Intl.DateTimeFormat(
    "ja-JP", {timeStyle: "short", dateStyle: "short", hourCycle: "h11"})
assertEquals("h11", df_11_ja_dt.resolvedOptions().hourCycle);
assertEquals("2019/04/04 午前0:00", df_11_ja_dt.formatRange(midnight, midnight));
assertEquals("2019/04/04 午後0:00", df_11_ja_dt.formatRange(noon, noon));

let df_12_ja = new Intl.DateTimeFormat(
    "ja-JP", {hour: "numeric", minute: "numeric", hourCycle: "h12"})
assertEquals("h12", df_12_ja.resolvedOptions().hourCycle);
assertEquals("午前12:00", df_12_ja.formatRange(midnight, midnight));
assertEquals("午後12:00", df_12_ja.formatRange(noon, noon));

let df_12_ja_t = new Intl.DateTimeFormat(
    "ja-JP", {timeStyle: "short", hourCycle: "h12"})
assertEquals("h12", df_12_ja_t.resolvedOptions().hourCycle);
assertEquals("午前12:00", df_12_ja_t.formatRange(midnight, midnight));
assertEquals("午後12:00", df_12_ja_t.formatRange(noon, noon));

let df_12_ja_dt = new Intl.DateTimeFormat(
    "ja-JP", {timeStyle: "short", dateStyle: "short", hourCycle: "h12"})
assertEquals("h12", df_12_ja_dt.resolvedOptions().hourCycle);
assertEquals("2019/04/04 午前12:00", df_12_ja_dt.formatRange(midnight, midnight));
assertEquals("2019/04/04 午後12:00", df_12_ja_dt.formatRange(noon, noon));

let df_23_ja = new Intl.DateTimeFormat(
    "ja-JP", {hour: "numeric", minute: "numeric", hourCycle: "h23"})
assertEquals("h23", df_23_ja.resolvedOptions().hourCycle);
assertEquals("0:00", df_23_ja.formatRange(midnight, midnight));
assertEquals("12:00", df_23_ja.formatRange(noon, noon));

let df_23_ja_t = new Intl.DateTimeFormat(
    "ja-JP", {timeStyle: "short", hourCycle: "h23"})
assertEquals("h23", df_23_ja_t.resolvedOptions().hourCycle);
assertEquals("0:00", df_23_ja_t.formatRange(midnight, midnight));
assertEquals("12:00", df_23_ja_t.formatRange(noon, noon));

let df_23_ja_dt = new Intl.DateTimeFormat(
    "ja-JP", {timeStyle: "short", dateStyle: "short", hourCycle: "h23"})
assertEquals("h23", df_23_ja_dt.resolvedOptions().hourCycle);
assertEquals("2019/04/04 0:00", df_23_ja_dt.formatRange(midnight, midnight));
assertEquals("2019/04/04 12:00", df_23_ja_dt.formatRange(noon, noon));

let df_24_ja = new Intl.DateTimeFormat(
    "ja-JP", {hour: "numeric", minute: "numeric", hourCycle: "h24"})
assertEquals("h24", df_24_ja.resolvedOptions().hourCycle);
assertEquals("24:00", df_24_ja.formatRange(midnight, midnight));
assertEquals("12:00", df_24_ja.formatRange(noon, noon));

let df_24_ja_t = new Intl.DateTimeFormat(
    "ja-JP", {timeStyle: "short", hourCycle: "h24"})
assertEquals("h24", df_24_ja_t.resolvedOptions().hourCycle);
assertEquals("24:00", df_24_ja_t.formatRange(midnight, midnight));
assertEquals("12:00", df_24_ja_t.formatRange(noon, noon));

let df_24_ja_dt = new Intl.DateTimeFormat(
    "ja-JP", {timeStyle: "short", dateStyle: "short", hourCycle: "h24"})
assertEquals("h24", df_24_ja_dt.resolvedOptions().hourCycle);
assertEquals("2019/04/04 24:00", df_24_ja_dt.formatRange(midnight, midnight));
assertEquals("2019/04/04 12:00", df_24_ja_dt.formatRange(noon, noon));


text:
package org.apache.lucene.search;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.store.RAMDirectory;

import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.Version;

/**
 * Tests MatchAllDocsQuery.
 *
 */
public class TestMatchAllDocsQuery extends LuceneTestCase {
  private Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);

  public void testQuery() throws Exception {

    RAMDirectory dir = new RAMDirectory();
    IndexWriter iw = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);
    iw.setMaxBufferedDocs(2);  // force multi-segment
    addDoc("one", iw, 1f);
    addDoc("two", iw, 20f);
    addDoc("three four", iw, 300f);
    iw.close();

    IndexReader ir = IndexReader.open(dir);
    IndexSearcher is = new IndexSearcher(ir);
    ScoreDoc[] hits;

    // assert with norms scoring turned off

    hits = is.search(new MatchAllDocsQuery(), null, 1000).scoreDocs;
    assertEquals(3, hits.length);
    assertEquals("one", ir.document(hits[0].doc).get("key"));
    assertEquals("two", ir.document(hits[1].doc).get("key"));
    assertEquals("three four", ir.document(hits[2].doc).get("key"));

    // assert with norms scoring turned on

    MatchAllDocsQuery normsQuery = new MatchAllDocsQuery("key");
    hits = is.search(normsQuery, null, 1000).scoreDocs;
    assertEquals(3, hits.length);

    assertEquals("three four", ir.document(hits[0].doc).get("key"));
    assertEquals("two", ir.document(hits[1].doc).get("key"));
    assertEquals("one", ir.document(hits[2].doc).get("key"));

    // change norm & retest
    ir.setNorm(0, "key", 400f);
    normsQuery = new MatchAllDocsQuery("key");
    hits = is.search(normsQuery, null, 1000).scoreDocs;
    assertEquals(3, hits.length);

    assertEquals("one", ir.document(hits[0].doc).get("key"));
    assertEquals("three four", ir.document(hits[1].doc).get("key"));
    assertEquals("two", ir.document(hits[2].doc).get("key"));

    // some artificial queries to trigger the use of skipTo():

    BooleanQuery bq = new BooleanQuery();
    bq.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
    bq.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
    hits = is.search(bq, null, 1000).scoreDocs;
    assertEquals(3, hits.length);

    bq = new BooleanQuery();
    bq.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
    bq.add(new TermQuery(new Term("key", "three")), BooleanClause.Occur.MUST);
    hits = is.search(bq, null, 1000).scoreDocs;
    assertEquals(1, hits.length);

    // delete a document:
    is.getIndexReader().deleteDocument(0);
    hits = is.search(new MatchAllDocsQuery(), null, 1000).scoreDocs;
    assertEquals(2, hits.length);

    // test parsable toString()
    QueryParser qp = new QueryParser("key", analyzer);
    hits = is.search(qp.parse(new MatchAllDocsQuery().toString()), null, 1000).scoreDocs;
    assertEquals(2, hits.length);

    // test parsable toString() with non default boost
    Query maq = new MatchAllDocsQuery();
    maq.setBoost(2.3f);
    Query pq = qp.parse(maq.toString());
    hits = is.search(pq, null, 1000).scoreDocs;
    assertEquals(2, hits.length);

    is.close();
    ir.close();
    dir.close();
  }

  public void testEquals() {
    Query q1 = new MatchAllDocsQuery();
    Query q2 = new MatchAllDocsQuery();
    assertTrue(q1.equals(q2));
    q1.setBoost(1.5f);
    assertFalse(q1.equals(q2));
  }

  private void addDoc(String text, IndexWriter iw, float boost) throws IOException {
    Document doc = new Document();
    Field f = new Field("key", text, Field.Store.YES, Field.Index.ANALYZED);
    f.setBoost(boost);
    doc.add(f);
    iw.addDocument(doc);
  }

}


text:
namespace SqlGenerator
{
    public interface ISelect : IQuery
    {
        IFrom AllColumns();

        IFrom Columns(params string[] properties);
    }
}


text:
package com.orientechnologies.orient.core.sql;

import com.orientechnologies.orient.core.command.OCommandDistributedReplicateRequest;
import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.OCluster.ATTRIBUTES;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OLocalPaginatedStorage;

import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SQL ALTER PROPERTY command: Changes an attribute of an existent property in the target class.
 *
 * @author Luca Garulli
 *
 */
@SuppressWarnings("unchecked")
public class OCommandExecutorSQLAlterCluster extends OCommandExecutorSQLAbstract implements OCommandDistributedReplicateRequest {
  public static final String KEYWORD_ALTER   = "ALTER";
  public static final String KEYWORD_CLUSTER = "CLUSTER";

  protected String           clusterName;
  protected int              clusterId       = -1;
  protected ATTRIBUTES       attribute;
  protected String           value;

  public OCommandExecutorSQLAlterCluster parse(final OCommandRequest iRequest) {
    final ODatabaseDocument database = getDatabase();

    init((OCommandRequestText) iRequest);

    StringBuilder word = new StringBuilder();

    int oldPos = 0;
    int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
    if (pos == -1 || !word.toString().equals(KEYWORD_ALTER))
      throw new OCommandSQLParsingException("Keyword " + KEYWORD_ALTER + " not found. Use " + getSyntax(), parserText, oldPos);

    oldPos = pos;
    pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
    if (pos == -1 || !word.toString().equals(KEYWORD_CLUSTER))
      throw new OCommandSQLParsingException("Keyword " + KEYWORD_CLUSTER + " not found. Use " + getSyntax(), parserText, oldPos);

    oldPos = pos;
    pos = nextWord(parserText, parserTextUpperCase, oldPos, word, false);
    if (pos == -1)
      throw new OCommandSQLParsingException("Expected <cluster-name>. Use " + getSyntax(), parserText, oldPos);

    clusterName = word.toString();

    final Pattern p = Pattern.compile("([0-9]*)");
    final Matcher m = p.matcher(clusterName);
    if (m.matches())
      clusterId = Integer.parseInt(clusterName);

    oldPos = pos;
    pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true);
    if (pos == -1)
      throw new OCommandSQLParsingException("Missing cluster attribute to change. Use " + getSyntax(), parserText, oldPos);

    final String attributeAsString = word.toString();

    try {
      attribute = OCluster.ATTRIBUTES.valueOf(attributeAsString.toUpperCase(Locale.ENGLISH));
    } catch (IllegalArgumentException e) {
      throw new OCommandSQLParsingException("Unknown class attribute '" + attributeAsString + "'. Supported attributes are: "
          + Arrays.toString(OCluster.ATTRIBUTES.values()), parserText, oldPos, e);
    }

    value = parserText.substring(pos + 1).trim();

    if (value.length() == 0)
      throw new OCommandSQLParsingException("Missing property value to change for attribute '" + attribute + "'. Use "
          + getSyntax(), parserText, oldPos);

    if (value.equalsIgnoreCase("null"))
      value = null;

    return this;
  }

  /**
   * Execute the ALTER CLASS.
   */
  public Object execute(final Map<Object, Object> iArgs) {
    if (attribute == null)
      throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");

    final OCluster cluster = getCluster();

    if (cluster == null)
      throw new OCommandExecutionException("Cluster '" + clusterName + "' not found");

    if (clusterId > -1 && clusterName.equals(String.valueOf(clusterId))) {
      clusterName = cluster.getName();
    } else {
      clusterId = cluster.getId();
    }

    Object result;
    try {
      result = cluster.set(attribute, value);
      final OStorage storage = getDatabase().getStorage();
      if (storage instanceof OLocalPaginatedStorage)
        ((OLocalPaginatedStorage) storage).synch();
    } catch (IOException ioe) {
      throw new OCommandExecutionException("Error altering cluster '" + clusterName + "'", ioe);
    }

    return result;
  }

  @Override
  public long getDistributedTimeout() {
    return OGlobalConfiguration.DISTRIBUTED_COMMAND_TASK_SYNCH_TIMEOUT.getValueAsLong();
  }

  protected OCluster getCluster() {
    final ODatabaseDocumentInternal database = getDatabase();
    if (clusterId > -1) {
      return database.getStorage().getClusterById(clusterId);
    } else {
      return database.getStorage().getClusterById(database.getStorage().getClusterIdByName(clusterName));
    }
  }

  public String getSyntax() {
    return "ALTER CLUSTER <cluster-name>|<cluster-id> <attribute-name> <attribute-value>";
  }

  @Override
  public QUORUM_TYPE getQuorumType() {
    return QUORUM_TYPE.ALL;
  }
}


text:
package ev3dev.bridge.client;

import org.junit.Test;

public class ClientFactoryTest {

    @Test
    public void doNothing() throws Exception {
    }

}


text:
class Chef
  module RVM
    module StringHelpers
      ##
      # Filters out any gemset declarations in an RVM Ruby string
      #
      # @param [String, #to_s] the RVM Ruby string
      # @return [String] the Ruby string, minus gemset
      def select_ruby(ruby_string)
        ruby_string.split('@').first
      end

      ##
      # Filters out any Ruby declaration in an RVM Ruby string
      #
      # @param [String, #to_s] the RVM Ruby string
      # @return [String] the gemset string, minus Ruby or nil if no gemset given
      def select_gemset(ruby_string)
        if ruby_string.include?('@')
          ruby_string.split('@').last
        else
          nil
        end
      end

      ##
      # Sanitizes a Ruby string so that it's more normalized.
      #
      # @param [String, #to_s] an RVM Ruby string
      # @param [String] a specific user RVM or nil for system-wide
      # @return [String] a fully qualified RVM Ruby string
      def normalize_ruby_string(ruby_string, user = new_resource.user)
        return "system" if ruby_string == "system"
        StringCache.fetch(ruby_string, user)
      end
    end
  end
end


text:
package persistence.graph;

import persistence.lifecycle.states.NodeState;
import persistence.metadata.MetadataManager;
import persistence.metadata.model.EntityMetadata;
import persistence.context.PersistenceCache;
import util.DeepEquals;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import com.ibm.commons.util.StringUtil;

import persistence.metadata.model.Relation;
import util.CloneUtil;
import util.JSFUtil;
import util.ReflectionUtils;

import model.notes.ModelBase;

/**
 * by giving an entity, wrap this entity as Node object, build object graph
 * using this Node object as head Node. recursively populate the children
 * objects and the NodeLinks defining the relations between Nodes
 *
 * @author weihang chen
 *
 */
public class ObjectGraphBuilder {
	PersistenceCache persistenceCache;

	/**
	 * builds the graph by populating new nodes or fetching them from cache
	 *
	 * @param entity
	 * @param initialNodeState
	 * @param persistenceCache
	 * @return
	 */

	public ObjectGraph getObjectGraph(Object entity,
			NodeState initialNodeState, PersistenceCache persistenceCache) {
		ObjectGraph objectGraph = new ObjectGraph();
		this.persistenceCache = persistenceCache;
		Collection<Node> allNodes = this.persistenceCache.getMainCache()
				.getAllNodes();
		System.out.println("all entities in cache: " + allNodes.size());

		System.out.println("----------------------SUB GRAPH BUILD FOR ENTITY "
				+ entity + " STARTS----------------------");
		Node headNode = getNode(entity, objectGraph, initialNodeState);

		if (headNode != null) {
			objectGraph.setHeadNode(headNode);
		}

		// PRINT TO CHECK STARTS: code below is just used to print the object
		// graph
		Map<String, Node> nodeMap = objectGraph.getNodeMapping();
		Set<Entry<String, Node>> nodeSet = nodeMap.entrySet();
		Iterator<Entry<String, Node>> iter = nodeSet.iterator();
		while (iter.hasNext()) {
			Entry<String, Node> nodeEntry = iter.next();
			Node n = nodeEntry.getValue();
			if (!StringUtil.equals(n.getData().toString(), headNode.getData()
					.toString()))
				System.out.print("subgraph node: " + n + "/");
		}
		// PUSH THIS HEAD NODE TO XPAGES REQUESTMAP, TO VIASUALIZE THE GRAPH
		JSFUtil.pushData(objectGraph, headNode.getNodeId());
		// PRINT TO CHECK END
		System.out.println("----------------------SUB GRAPH BUILD FINISHS "
				+ objectGraph + " IN SIZE OF " + nodeMap.size() + " with "
				+ objectGraph.getHeadNode() + " as head node");
		return objectGraph;
	}

	// 1. returns a cache node as headNode if it's found in cache
	// 2. assign cached data back to the pojo Fields
	@SuppressWarnings("unchecked")
	private Node getNode(Object entity, ObjectGraph graph,
			NodeState initialNodeState) {
		// EntityMetadata is stored for POJO classes, not for Enhanced
		// ones, therefore always need to perform check to get the real POJO
		// class
		Class realClass = JSFUtil.getRealClass(entity.getClass());
		EntityMetadata entityMetadata = persistence.metadata.MetadataManager
				.getEntityMetadata(realClass);
		if (entityMetadata == null) {
			return null;
		}

		String id = ((ModelBase) entity).getUnid();
		String nodeId = getNodeId(id);
		// graph is temporary graph with one head node, if there are duplicated
		// nodes, they still share the same relations, therefore no need to
		// build again for duplicated nodes

		Node node = null;
		// try to get the node from cache
		Node nodeInPersistenceCache = this.persistenceCache.getMainCache()
				.getNodeFromCache(nodeId);
		// delete1123
		// Object nodeDataCopy = CloneUtil.cloneDominoEntity(entity);
		// delete1123 end

		// try to get the node from graph
		Node nodeInGraph = graph.getNode(nodeId);

		// if it already exists in the graph return null
		// System.out.println("nodeInGraph: " + nodeInGraph
		// + " /nodeInPersistenceCache: " + nodeInPersistenceCache);
		if (nodeInGraph != null && nodeInPersistenceCache == null) {
			return null;
		}

		// if it does not exist in the one-time graph nor the cache, clone the
		// entity, wrap the clone in a new Node object, indicate the Node object
		// as dirty so it will be flush later.
		if (nodeInPersistenceCache == null) {
			Object nodeDataCopy = CloneUtil.cloneDominoEntity(entity);
			node = new Node(nodeId, nodeDataCopy, initialNodeState,
					this.persistenceCache);
			// 1108 added code, a new node should always be dirty
			node.setDirty(true);
			// 1108
		} else {
			// if it does not exist in one-time graph but exists in cache,it is
			// possible that related nodes (parents/children) might not exist in
			// persistence cache, therefore perform deepequal test to see if two
			// entities have same Field
			// values
			node = nodeInPersistenceCache;
			boolean isDeepEqual = DeepEquals.deepEquals(node.getData(), entity);

			// IMPORTANT: in the CloneUtil.cloneDominoEntity(entity), a new
			// entity is never cloned, since its wrapping a new document. A
			// clone wrapping another new notes document will never override the
			// a existing one from database. therefore if it is the same entity
			// in the persistence cache as being exposed to user. We know for
			// sure that this entity was wrapping a new document in the previous
			// request. Therefore need to make a clone for it in the current
			// request

			// if two entities with same id are not deepequal, then replace the
			// managed entity with a clone of the detached entity
			// if the entity in persistence cache is the same as the one being
			// exposed to user, clone the entity, put the clone into the node in
			// persistence cache
			if (node.getData() == entity || !isDeepEqual) {
				Object nodeDataCopy = CloneUtil.cloneDominoEntity(entity);
				// assign the new POJO entity to the Node object inside of the
				// persistence cache and mark it as dirty
				node.setData(nodeDataCopy);
				node.setDirty(true);
			} else {
				// if two objects are deepequal, then mark it as not dirty so it
				// not be picked in flush to save computation time
				node.setDirty(false);
			}
			// System.out.println("is the node dirty " + node.isDirty());
			// delete 1123 since deep equal is finished, no need to hard code
			// all nodes as dirty
			// node.setData(nodeDataCopy);
			// node.setDirty(true);
			// delete 1123 since deep equal is finished
		}
		// the new Node or the updated Node object is added to currently
		// building grapH (note: the new Node object is not added to persistence
		// cache)
		graph.addNode(nodeId, node);
		// 1111 old code does not require clearing the children/parent map,
		// since its method scope(remove an entity in request1, close the
		// entityManager, start a new one, all cache are gone, child/parent map
		// are new as well). The cache is always new one between methods,
		// in the demo application, the cache is by default being viewscope but
		// can be closed programmatically anytime. if the parent/children map is
		// not cleared first, the old reference will be seen when you navigate
		// from one Node to another Node through NodeLink, then you might try to
		// merge an entity in REMOVESTATE which will yield an exception(do not
		// do explict nulling, it never works on reference)
		if (node.getChildren() != null) {
			node.getChildren().clear();
		}
		// 111

		// System.out.println("relation amounts for entity " + entity + ": "
		// + entityMetadata.getRelations().size());

		// go through relations, get the Field objects and recursively populate
		// the graph
		for (Relation relation : entityMetadata.getRelations()) {
			// do not invoke any getter if the relation is lazy
			Field relationTargetField = relation.getProperty();
			// IMPORTANT************: experience technical difficulty here, do
			// not know how to check if lazy loaded object/collection has
			// already been loaded, correct mechanism is that if lazy collection
			// is not initialised, then it should not be part of the object
			// graph building
			/*
			 * if (FetchType.LAZY == relation.getFetchType()) continue;
			 */
			// IMPORTANT END********
			Object childObject = ReflectionUtils.getFieldObject(entity,
					relationTargetField);

			// what objectgraphbuilder does is to eliminate duplication and
			// build a unique graph

			System.out.println("PROCESS RELATION " + relation + " STARTS/"
					+ childObject);

			if (childObject != null) {
				// if Field value is Collection, get each object from the
				// collection, invoke addChildNodesToGraph
				if (Collection.class.isAssignableFrom(childObject.getClass())) {
					Collection childrenObjects = (Collection) childObject;
					Iterator i = childrenObjects.iterator();
					while (i.hasNext()) {
						Object childObj = i.next();
						if (childObj != null) {
							addChildNodesToGraph(graph, node, relation,
									childObj, initialNodeState);
						}
					}
				} else {
					// if its not Collection but single object,
					// addChildNodesToGraph
					addChildNodesToGraph(graph, node, relation, childObject,
							initialNodeState);
				}
			}

			System.out.println("PROCESS RELATION " + relation + " ENDS");
		}

		return node;
	}

	/**
	 * 1.recursively populate children by calling getNode()<br>
	 * 2.populate NodeLink between Nodes
	 *
	 * @param graph
	 * @param parentNode
	 * @param relation
	 * @param childObject
	 * @param initialNodeState
	 */
	private void addChildNodesToGraph(ObjectGraph graph, Node parentNode,
			Relation relation, Object childObject, NodeState initialNodeState) {
		Node childNode = getNode(childObject, graph, initialNodeState);
		if (childNode == null) {
			return;
		}
		NodeLink nodeLink = new NodeLink(parentNode.getNodeId(), childNode
				.getNodeId());
		nodeLink.setMultiplicity(relation.getType());

		EntityMetadata metadata = MetadataManager.getEntityMetadata(parentNode
				.getDataClass());
		nodeLink.setLinkProperties(getLinkProperties(metadata, relation));
		childNode.addParentNode(nodeLink, parentNode);
		parentNode.addChildNode(nodeLink, childNode);

	}

	/**
	 * populate Link properties for a NodeLink object
	 *
	 * @param metadata
	 * @param relation
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<NodeLink.LinkProperty, Object> getLinkProperties(
			EntityMetadata metadata, Relation relation) {
		Map linkProperties = new HashMap();

		linkProperties.put(NodeLink.LinkProperty.LINK_NAME, getMappedName(
				metadata, relation));
		linkProperties.put(NodeLink.LinkProperty.IS_SHARED_BY_PRIMARY_KEY,
				Boolean.valueOf(relation.isJoinedByPrimaryKey()));
		linkProperties.put(NodeLink.LinkProperty.IS_BIDIRECTIONAL, Boolean
				.valueOf(!(relation.isUnary())));
		linkProperties.put(NodeLink.LinkProperty.IS_RELATED_VIA_JOIN_TABLE,
				Boolean.valueOf(relation.isRelatedViaJoinTable()));
		linkProperties.put(NodeLink.LinkProperty.PROPERTY, relation
				.getProperty());

		linkProperties.put(NodeLink.LinkProperty.CASCADE, relation
				.getCascades());

		// if (relation.isRelatedViaJoinTable())
		// {
		// linkProperties.put(NodeLink.LinkProperty.JOIN_TABLE_METADATA,
		// relation.getJoinTableMetadata());
		// }

		return linkProperties;
	}

	/**
	 * not used
	 *
	 * @param parentMetadata
	 * @param relation
	 * @return
	 */
	public String getMappedName(EntityMetadata parentMetadata, Relation relation) {
		if (relation != null) {
			String joinColumn = relation.getJoinColumnName();
			// if (joinColumn == null)
			// {
			// Class clazz = relation.getTargetEntity();
			// EntityMetadata metadata =
			// KunderaMetadataManager.getEntityMetadata(clazz);
			// joinColumn =
			// (relation.getType().equals(Relation.ForeignKey.ONE_TO_MANY)) ?
			// parentMetadata.getIdColumn().getName() :
			// metadata.getIdColumn().getName();
			// }

			return joinColumn;
		}
		return null;
	}

	/**
	 *
	 * @param entityId
	 * @return $+document uniqueid
	 */
	public static String getNodeId(String entityId) {
		StringBuffer strBuffer = new StringBuffer();
		strBuffer.append("$");
		strBuffer.append(entityId);
		return strBuffer.toString();
	}

	/**
	 * not used
	 *
	 * @param pk
	 * @param objectClass
	 * @return
	 */
	public static String getNodeId(Object pk, Class<?> objectClass) {
		StringBuffer strBuffer = new StringBuffer();
		strBuffer.append("$");
		strBuffer.append(pk);
		return strBuffer.toString();
	}

	/**
	 *
	 * @param nodeId
	 * @return document uniqueid
	 */
	public static String getEntityId(String nodeId) {
		return nodeId.substring(nodeId.indexOf("$") + 1, nodeId.length());
	}
}