text:
package org.elasticsearch.search.aggregations.metrics;

import org.elasticsearch.search.DocValueFormat;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static java.util.Collections.emptyMap;

public class InternalTDigestPercentilesTests extends InternalPercentilesTestCase<InternalTDigestPercentiles> {

    @Override
    protected InternalTDigestPercentiles createTestInstance(
        String name,
        Map<String, Object> metadata,
        boolean keyed,
        DocValueFormat format,
        double[] percents,
        double[] values
    ) {
        final TDigestState state = new TDigestState(100);
        Arrays.stream(values).forEach(state::add);

        assertEquals(state.centroidCount(), values.length);
        return new InternalTDigestPercentiles(name, percents, state, keyed, format, metadata);
    }

    @Override
    protected void assertReduced(InternalTDigestPercentiles reduced, List<InternalTDigestPercentiles> inputs) {
        final TDigestState expectedState = new TDigestState(reduced.state.compression());

        long totalCount = 0;
        for (InternalTDigestPercentiles input : inputs) {
            assertArrayEquals(reduced.keys, input.keys, 0d);
            expectedState.add(input.state);
            totalCount += input.state.size();
        }

        assertEquals(totalCount, reduced.state.size());
        if (totalCount > 0) {
            assertEquals(expectedState.quantile(0), reduced.state.quantile(0), 0d);
            assertEquals(expectedState.quantile(1), reduced.state.quantile(1), 0d);
        }
    }

    @Override
    protected Class<? extends ParsedPercentiles> implementationClass() {
        return ParsedTDigestPercentiles.class;
    }

    @Override
    protected InternalTDigestPercentiles mutateInstance(InternalTDigestPercentiles instance) {
        String name = instance.getName();
        double[] percents = instance.keys;
        TDigestState state = instance.state;
        boolean keyed = instance.keyed;
        DocValueFormat formatter = instance.formatter();
        Map<String, Object> metadata = instance.getMetadata();
        switch (between(0, 4)) {
            case 0:
                name += randomAlphaOfLength(5);
                break;
            case 1:
                percents = Arrays.copyOf(percents, percents.length + 1);
                percents[percents.length - 1] = randomDouble() * 100;
                Arrays.sort(percents);
                break;
            case 2:
                TDigestState newState = new TDigestState(state.compression());
                newState.add(state);
                for (int i = 0; i < between(10, 100); i++) {
                    newState.add(randomDouble());
                }
                state = newState;
                break;
            case 3:
                keyed = keyed == false;
                break;
            case 4:
                if (metadata == null) {
                    metadata = new HashMap<>(1);
                } else {
                    metadata = new HashMap<>(instance.getMetadata());
                }
                metadata.put(randomAlphaOfLength(15), randomInt());
                break;
            default:
                throw new AssertionError("Illegal randomisation branch");
        }
        return new InternalTDigestPercentiles(name, percents, state, keyed, formatter, metadata);
    }

    public void testIterator() {
        final double[] percents = randomPercents(false);
        final double[] values = new double[frequently() ? randomIntBetween(1, 10) : 0];
        for (int i = 0; i < values.length; ++i) {
            values[i] = randomDouble();
        }

        InternalTDigestPercentiles aggregation = createTestInstance(
            "test",
            emptyMap(),
            false,
            randomNumericDocValueFormat(),
            percents,
            values
        );

        Iterator<Percentile> iterator = aggregation.iterator();
        Iterator<String> nameIterator = aggregation.valueNames().iterator();
        for (double percent : percents) {
            assertTrue(iterator.hasNext());

            Percentile percentile = iterator.next();
            String percentileName = nameIterator.next();

            assertEquals(percent, Double.valueOf(percentileName), 0.0d);
            assertEquals(percent, percentile.getPercent(), 0.0d);

            assertEquals(aggregation.percentile(percent), percentile.getValue(), 0.0d);
            assertEquals(aggregation.value(String.valueOf(percent)), percentile.getValue(), 0.0d);
        }
        assertFalse(iterator.hasNext());
        assertFalse(nameIterator.hasNext());
    }
}


text:
This is a collection of information that will be useful to anyone visiting Warwick Bethel. It contains, subjectively, our favorite audio clips in the [Warwick Bethel Museums](https://www.jw.org/en/jehovahs-witnesses/offices/united-states/). In the future some suggested local attractions that you may find helpful will be added.

If you would like to add to these lists, you can! Read how to [submit a pull request](https://kirstiejane.github.io/friendly-github-intro/exercises/my-first-pullrequest/) in order to add your own favorites. [Click here to see the source code for this website](https://github.com/kmuncie/warwick-gems).

Visiting Warwick Bethel and want some restaurant recommendations?

   See Restaurant Recommendations

## THE BIBLE AND THE DIVINE NAME
### ROTATING EXHIBIT
* 515
  * [The oldest Bible on display, ancient Syriac Bible](https://www.jw.org/en/publications/magazines/wp20140901/syriac-peshitta/)
* 533
  * [Complutensian Polyglot Bible](https://en.wikipedia.org/wiki/Complutensian_Polyglot_Bible)
* 552, 553
  * [Tyndale's New Testament](http://www.bl.uk/onlinegallery/sacredtexts/tyndale.html)
* 566, 567
  * [Reina Bible - First Edition](https://en.wikipedia.org/wiki/Reina-Valera)
* 574
  * [List of prohibited books](https://en.wikipedia.org/wiki/Index_Librorum_Prohibitorum)
* 588
  * Chinese Bible

### STANDARD EXHIBIT
* 109, 110
  * Facsimile of [the Dead Sea Scroll, Book of Isaiah](https://wol.jw.org/en/wol/d/r1/lp-e/1001072081)
* 112, 113
  * Reproduction of [the Moabite Stone](https://wol.jw.org/en/wol/d/r1/lp-e/1200273876)
* 126
  * Facsimile of [the Vatican Codex](https://wol.jw.org/en/wol/d/r1/lp-e/2009727)
* 129, 130
  * [Aleppo Codex](https://wol.jw.org/en/wol/d/r1/lp-e/1200002893#h=23:361-23:641)
* 132
  * [Latin Vulgate](https://wol.jw.org/en/wol/d/r1/lp-e/1200273371)
* 179
  * [Geneva Bible](https://wol.jw.org/en/wol/d/r1/lp-e/102004604)
* 183
  * [First Edition King James Version](https://en.wikipedia.org/wiki/King_James_Version)
* 186
  * [Reina Valera Bible, Spanish](https://en.wikipedia.org/wiki/Reina-Valera)
* 192
  * Jehovah Bible
* 207
  * [Bay Psalm](https://wol.jw.org/en/wol/d/r1/lp-e/2013122#h=25:0-25:416), the first piece of literature published in England's American colonies in 1640.
* 224
  * [Julia Smith, translation by a woman](https://en.wikipedia.org/wiki/Julia_E._Smith_Parker_Translation)
* 242
  * Nuremberg Polyglot

## A PEOPLE FOR JEHOVAH'S NAME
* 805
  * Zion's Watchtower Letter
* 807
  * Story of postmaster in Virginia
* 809
  * Bible Students held their first large convention in 1893
* 811
  * Baptist member
* 812
  * Public debate of C.T. Russell and well-known clergyman
* 813
  * Around the world tour of C.T. Russell
* 815, 816
  * Photodrama of Creation story
* 823
  * Pilgrims and Russell artifacts
* 824
  * Deep study in early days
* 826
  * Counsel on giving long talks
* 827
  * Experience of Emma Martin when she was imprisoned
* 829
  * Experience of [Herbert Senior](https://wol.jw.org/en/wol/d/r1/lp-e/1102014253#h=11) who was imprisoned in Britain for refusing military service
* 844
  * Food pail used by a brother while imprisoned for his faith (Netherland)
* 836
  * Printers in Africa
* 837
  * WBBR
* 843
  * Report card and class photo of Johanna Hartman (Germany)
* 849
  * Persecution blanket passed down from father to son
* 852
  * Message written in his shirt to his family by a brother who were imprisoned for his faith (South Korea)
* 734
  * Part of the "Live Forever" book hand written on prison toilet paper
* 855, 856
  * Christmas at Bethel (Outstanding)
* 862
  * Experience of [Elsa Abt](https://wol.jw.org/en/wol/d/r1/lp-e/1102009076#h=25:0-25:853)
* 876, 877, 878, 879, 880
  * Story of [Sibia boat](https://wol.jw.org/en/wol/d/r1/lp-e/2016601#h=39:0-40:66) told by missionary that served on it
* 891
  * Br. Franz concluding remarks to Gilead class
* 906
  * Br. Knorr releasing the New World Translation
* 930
  * Sister relating how she observed the memorial by herself in secret
* 943
  * "All Scripture is Beneficial" WBBR radio episode narrated by Ulysses Glass
* 944
  * Many Governing Body members give comments on love and brotherhood
* 951
  * Childrens' bedtime story on WBBR
* 959
  * Very old recorded message from missionary to wife
* 966, 967, 968
  * Hidden Bibles of Andrei Hanak (Hungary), [Simone Arnold](https://wol.jw.org/en/wol/d/r1/lp-e/1200273453#h=267) (France), Manuel Rodriguez (Cuba)
* 969
  * Table with hidden compartment in Nazi Germany

## FAITH IN ACTION

redpajama_set_name: RedPajamaGithub


text:
<?php
declare(strict_types=1);

namespace ManaPHP\Http\Filter;

use Psr\Container\ContainerInterface;

class Factory implements FactoryInterface
{
    protected ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function get(string $filter): mixed
    {
        return $this->container->get($filter);
    }
}


text:
<?php

namespace SugarCli\Console\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

use Inet\SugarCRM\System as SugarSystem;

class SystemClearCacheCommand extends AbstractConfigOptionCommand
{
    protected $messages = array();

    protected function configure()
    {
        $this->setName('system:clearCache')
            ->setDescription('Clears SugarCRM Cache directory and metadata_cache table.')
            ->enableStandardOption('path');
            //->enableStandardOption('user-id')
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        //$sugarEP = $this->getService('sugarcrm.entrypoint');

        $output->writeln('<comment>Clear Cache</comment>: ');

        exec("rm -Rfv " . $input->getOption('path') . "/cache/*", $commandOutput);

        //$sugarSystem = new SugarSystem($sugarEP);
        $pdo = $this->getService('sugarcrm.pdo');
        $this->getService('sugarcrm.entrypoint'); // go to sugar folder to make sure we are in the right folder
        $pdo->query("TRUNCATE TABLE `metadata_cache`");
        $output->writeln(PHP_EOL . "<info>--> Removed everything from 'metadata_cache'</info>");

        if ($output->isVerbose()) {
            $output->writeln(PHP_EOL . '<comment>General Messages</comment>: ');
            $output->writeln(implode(PHP_EOL, $commandOutput));
        }

        return;
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\user\Tests\Migrate\MigrateUserProfileFieldInstanceTest.
 */

namespace Drupal\user\Tests\Migrate;

use Drupal\field\Entity\FieldConfig;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;

/**
 * Tests the user profile field instance migration.
 *
 * @group migrate_drupal_6
 */
class MigrateUserProfileFieldInstanceTest extends MigrateDrupal6TestBase {

  static $modules = array('field', 'link', 'options', 'datetime', 'text');

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    // Add some id mappings for the dependant migrations.
    $id_mappings = array(
      'user_profile_field' => array(
        array(array(1), array('user', 'profile_color')),
      ),
    );
    $this->prepareMigrations($id_mappings);
    $this->createFields();
    $this->executeMigration('user_profile_field_instance');
  }

  /**
   * Tests migration of user profile fields.
   */
  public function testUserProfileFields() {
    // Migrated a text field.
    $field = FieldConfig::load('user.user.profile_color');
    $this->assertIdentical('Favorite color', $field->label());
    $this->assertIdentical('List your favorite color', $field->getDescription());

    // Migrated a textarea.
    $field = FieldConfig::load('user.user.profile_biography');
    $this->assertIdentical('Biography', $field->label());
    $this->assertIdentical('Tell people a little bit about yourself', $field->getDescription());

    // Migrated checkbox field.
    $field = FieldConfig::load('user.user.profile_sell_address');
    $this->assertIdentical('Sell your email address?', $field->label());
    $this->assertIdentical("If you check this box, we'll sell your address to spammers to help line the pockets of our shareholders. Thanks!", $field->getDescription());

    // Migrated selection field.
    $field = FieldConfig::load('user.user.profile_sold_to');
    $this->assertIdentical('Sales Category', $field->label());
    $this->assertIdentical("Select the sales categories to which this user's address was sold.", $field->getDescription());

    // Migrated list field.
    $field = FieldConfig::load('user.user.profile_bands');
    $this->assertIdentical('Favorite bands', $field->label());
    $this->assertIdentical("Enter your favorite bands. When you've saved your profile, you'll be able to find other people with the same favorites.", $field->getDescription());

/*
    // Migrated URL field.
    $field = FieldConfig::load('user.user.profile_blog');
    $this->assertIdentical('Your blog', $field->label());
    $this->assertIdentical("Paste the full URL, $field->getDescription(), including http://, of your personal blog.");
*/

    // Migrated date field.
    $field = FieldConfig::load('user.user.profile_birthdate');
    $this->assertIdentical('Birthdate', $field->label());
    $this->assertIdentical("Enter your birth date and we'll send you a coupon.", $field->getDescription());

    // Another migrated checkbox field, with a different source visibility setting.
    $field = FieldConfig::load('user.user.profile_love_migrations');
    $this->assertIdentical('I love migrations', $field->label());
    $this->assertIdentical("If you check this box, you love migrations.", $field->getDescription());
  }

  /**
   * Helper to create fields.
   */
  protected function createFields() {
    $fields = array(
      'profile_color' => 'text',
      'profile_biography' => 'text_long',
      'profile_sell_address' => 'boolean',
      'profile_sold_to' => 'list_string',
      'profile_bands' => 'text',
      'profile_blog' => 'link',
      'profile_birthdate' => 'datetime',
      'profile_love_migrations' => 'boolean',
    );
    foreach ($fields as $name => $type) {
      entity_create('field_storage_config', array(
        'field_name' => $name,
        'entity_type' => 'user',
        'type' => $type,
      ))->save();
    }
  }

}


text:
extern const NSTimeInterval AT_VAST_INVALID_DURATION;

@class ATVASTVideoClicks;
@class ATVASTTracking;

@interface ATVASTLinear : ATVASTTrackable

@property (nonatomic, readonly) NSMutableArray *icons; // array of Icon
@property (nonatomic, assign) NSTimeInterval duration;
@property (nonatomic, copy) NSString *adParameters;
@property (nonatomic, copy) NSString *skipOffset;
@property (nonatomic, strong) ATVASTVideoClicks *videoClicks;
@property (nonatomic, readonly) NSMutableArray *mediaFiles; // array of ATVASTMediaFile
@property (nonatomic, readonly) NSMutableArray *creativeExtensions; // array of NSString objects containing any valid XML documents

@end


text:
@interface MiddayState : State <State>

@end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
J. S. African Bot. 41:100. 1975

#### Original name
null

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.RecipeFramework;
using System.Runtime.Serialization;
using Microsoft.Practices.RecipeFramework.VisualStudio.Templates;
using EnvDTE;

namespace SPALM.SPSF.Library.References
{
    [Serializable]
  public class AnyElementReferenceTemplate : UnboundTemplateReference
    {
        public AnyElementReferenceTemplate(string recipe) : base(recipe) { }

        protected AnyElementReferenceTemplate(SerializationInfo info, StreamingContext context) : base(info, context) { }

        public override bool IsEnabledFor(object target)
        {
            Helpers.Log("AnyElementReferenceTemplate");

					try
					{
						if (target is ProjectItem)
						{
							if ((target as ProjectItem).Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
							{
								return false;
							}
						}
					}
					catch (Exception)
					{
					}
          return true;
        }

        public override string AppliesTo
        {
            get { return "Any solution element"; }
        }
    }
}


text:
layout: post
title:  "String substitution"
keywords: "string, substitution, interpolation"
category: strings
comments: true
---

You can perform string substitution using `#{}`

{% highlight elixir %}
iex> name = "José"
iex> IO.puts("Hello, #{name}!")
Hello, José!
:ok
{% endhighlight %}


text:
import asposepdfcloud
from asposepdfcloud.PdfApi import PdfApi
from asposepdfcloud.PdfApi import ApiException
from asposepdfcloud.models import Stamp

import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
from asposestoragecloud.StorageApi import ResponseMessage

apiKey = "XXXXX" #sepcify App Key
appSid = "XXXXX" #sepcify App SID
apiServer = "http://api.aspose.com/v1.1"
data_folder = "../../data/"

#Instantiate Aspose Storage API SDK
storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True)
storageApi = StorageApi(storage_apiClient)
#Instantiate Aspose Pdf API SDK
api_client = asposepdfcloud.ApiClient.ApiClient(apiKey, appSid, True)
pdfApi = PdfApi(api_client);

#set input file name
name = "sample-input.pdf"
pdfName = "Sample.pdf"
pageNumber = 1

body = Stamp.Stamp()

body.FileName = pdfName
body.PageIndex = 1
body.Value = ""
body.Background = True
body.Type = "Page"
body.LeftMargin = 0.0
body.Opacity = 0.5
body.RightMargin = 0.0
body.TopMargin = 0.0
body.YIndent = 100.0
body.XIndent = 100.0
body.Zoom = 1.0
body.Width = 300.0
body.Height = 300.0
body.StartingNumber = 0

try:
    #upload file to aspose cloud storage
    response = storageApi.PutCreate(name, data_folder + name)
    response = storageApi.PutCreate(pdfName, data_folder + pdfName)

    #invoke Aspose.Pdf Cloud SDK API to insert page of one PDF as watermark or stamp to another PDF page
    response = pdfApi.PutPageAddStamp(name, pageNumber, body)

    if response.Status == "OK":
        #download updated pdf from cloud storage
        response = storageApi.GetDownload(Path=name)
        outfilename = "c:/temp/" + name
        with open(outfilename, 'wb') as f:
                    for chunk in response.InputStream:
                        f.write(chunk)

except ApiException as ex:
            print "ApiException:"
            print "Code:" + str(ex.code)
            print "Message:" + ex.message


text:
<?php
namespace TYPO3\CMS\Core\Core;

use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;

/**
 * This class encapsulates bootstrap related methods.
 * It is required directly as the very first thing in entry scripts and
 * used to define all base things like constants and pathes and so on.
 *
 * Most methods in this class have dependencies to each other. They can
 * not be called in arbitrary order. The methods are ordered top down, so
 * a method at the beginning has lower dependencies than a method further
 * down. Do not fiddle with the load order in own scripts except you know
 * exactly what you are doing!
 */
class Bootstrap
{
    /**
     * @var \TYPO3\CMS\Core\Core\Bootstrap
     */
    protected static $instance = null;

    /**
     * Unique Request ID
     *
     * @var string
     */
    protected $requestId;

    /**
     * The application context
     *
     * @var \TYPO3\CMS\Core\Core\ApplicationContext
     */
    protected $applicationContext;

    /**
     * @var array List of early instances
     */
    protected $earlyInstances = [];

    /**
     * @var string Path to install tool
     */
    protected $installToolPath;

    /**
     * A list of all registered request handlers, see the Application class / entry points for the registration
     * @var \TYPO3\CMS\Core\Http\RequestHandlerInterface[]|\TYPO3\CMS\Core\Console\RequestHandlerInterface[]
     */
    protected $availableRequestHandlers = [];

    /**
     * The Response object when using Request/Response logic
     * @var \Psr\Http\Message\ResponseInterface
     * @see shutdown()
     */
    protected $response;

    /**
     * @var bool
     */
    protected static $usesComposerClassLoading = false;

    /**
     * Disable direct creation of this object.
     * Set unique requestId and the application context
     *
     * @var string Application context
     */
    protected function __construct($applicationContext)
    {
        $this->requestId = substr(md5(uniqid('', true)), 0, 13);
        $this->applicationContext = new ApplicationContext($applicationContext);
    }

    /**
     * @return bool
     */
    public static function usesComposerClassLoading()
    {
        return self::$usesComposerClassLoading;
    }

    /**
     * Disable direct cloning of this object.
     */
    protected function __clone()
    {
    }

    /**
     * Return 'this' as singleton
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            $applicationContext = getenv('TYPO3_CONTEXT') ?: (getenv('REDIRECT_TYPO3_CONTEXT') ?: 'Production');
            self::$instance = new static($applicationContext);
        }
        return static::$instance;
    }

    /**
     * Gets the request's unique ID
     *
     * @return string Unique request ID
     * @internal This is not a public API method, do not use in own extensions
     */
    public function getRequestId()
    {
        return $this->requestId;
    }

    /**
     * Returns the application context this bootstrap was started in.
     *
     * @return \TYPO3\CMS\Core\Core\ApplicationContext The application context encapsulated in an object
     * @internal This is not a public API method, do not use in own extensions.
     * Use \TYPO3\CMS\Core\Utility\GeneralUtility::getApplicationContext() instead
     */
    public function getApplicationContext()
    {
        return $this->applicationContext;
    }

    /**
     * Prevent any unwanted output that may corrupt AJAX/compression.
     * This does not interfere with "die()" or "echo"+"exit()" messages!
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function startOutputBuffering()
    {
        ob_start();
        return $this;
    }

    /**
     * Main entry point called at every request usually from Global scope. Checks if everything is correct,
     * and loads the Configuration.
     *
     * Make sure that the baseSetup() is called before and the class loader is present
     *
     * @return Bootstrap
     */
    public function configure()
    {
        $this->startOutputBuffering()
            ->loadConfigurationAndInitialize()
            ->loadTypo3LoadedExtAndExtLocalconf(true)
            ->setFinalCachingFrameworkCacheConfiguration()
            ->defineLoggingAndExceptionConstants()
            ->unsetReservedGlobalVariables()
            ->initializeTypo3DbGlobal();

        return $this;
    }

    /**
     * Run the base setup that checks server environment, determines pathes,
     * populates base files and sets common configuration.
     *
     * Script execution will be aborted if something fails here.
     *
     * @param string $relativePathPart Relative path of entry script back to document root
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function baseSetup($relativePathPart = '')
    {
        SystemEnvironmentBuilder::run($relativePathPart);
        if (!self::$usesComposerClassLoading && ClassLoadingInformation::isClassLoadingInformationAvailable()) {
            ClassLoadingInformation::registerClassLoadingInformation();
        }
        GeneralUtility::presetApplicationContext($this->applicationContext);
        return $this;
    }

    /**
     * Sets the class loader to the bootstrap
     *
     * @param \Composer\Autoload\ClassLoader $classLoader an instance of the class loader
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function initializeClassLoader($classLoader)
    {
        $this->setEarlyInstance(\Composer\Autoload\ClassLoader::class, $classLoader);
        if (defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE) {
            self::$usesComposerClassLoading = true;
        }
        return $this;
    }

    /**
     * checks if LocalConfiguration.php or PackageStates.php is missing,
     * used to see if a redirect to the install tool is needed
     *
     * @return bool TRUE when the essential configuration is available, otherwise FALSE
     * @internal This is not a public API method, do not use in own extensions
     */
    public function checkIfEssentialConfigurationExists()
    {
        $configurationManager = new \TYPO3\CMS\Core\Configuration\ConfigurationManager;
        $this->setEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class, $configurationManager);
        return file_exists($configurationManager->getLocalConfigurationFileLocation()) && file_exists(PATH_typo3conf . 'PackageStates.php');
    }

    /**
     * Redirect to install tool if LocalConfiguration.php is missing.
     *
     * @internal This is not a public API method, do not use in own extensions
     */
    public function redirectToInstallTool($relativePathPart = '')
    {
        $backPathToSiteRoot = str_repeat('../', count(explode('/', $relativePathPart)) - 1);
        header('Location: ' . $backPathToSiteRoot . 'typo3/sysext/install/Start/Install.php');
        die;
    }

    /**
     * Adds available request handlers usually done via an application from the outside.
     *
     * @param string $requestHandler class which implements the request handler interface
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function registerRequestHandlerImplementation($requestHandler)
    {
        $this->availableRequestHandlers[] = $requestHandler;
        return $this;
    }

    /**
     * Fetches the request handler that suits the best based on the priority and the interface
     * Be sure to always have the constants that are defined in $this->defineTypo3RequestTypes() are set,
     * so most RequestHandlers can check if they can handle the request.
     *
     * @param \Psr\Http\Message\ServerRequestInterface|\Symfony\Component\Console\Input\InputInterface $request
     * @return \TYPO3\CMS\Core\Http\RequestHandlerInterface|\TYPO3\CMS\Core\Console\RequestHandlerInterface
     * @throws \TYPO3\CMS\Core\Exception
     * @internal This is not a public API method, do not use in own extensions
     */
    protected function resolveRequestHandler($request)
    {
        $suitableRequestHandlers = [];
        foreach ($this->availableRequestHandlers as $requestHandlerClassName) {
            /** @var \TYPO3\CMS\Core\Http\RequestHandlerInterface|\TYPO3\CMS\Core\Console\RequestHandlerInterface $requestHandler */
            $requestHandler = GeneralUtility::makeInstance($requestHandlerClassName, $this);
            if ($requestHandler->canHandleRequest($request)) {
                $priority = $requestHandler->getPriority();
                if (isset($suitableRequestHandlers[$priority])) {
                    throw new \TYPO3\CMS\Core\Exception('More than one request handler with the same priority can handle the request, but only one handler may be active at a time!', 1176471352);
                }
                $suitableRequestHandlers[$priority] = $requestHandler;
            }
        }
        if (empty($suitableRequestHandlers)) {
            throw new \TYPO3\CMS\Core\Exception('No suitable request handler found.', 1225418233);
        }
        ksort($suitableRequestHandlers);
        return array_pop($suitableRequestHandlers);
    }

    /**
     * Builds a Request instance from the current process, and then resolves the request
     * through the request handlers depending on Frontend, Backend, CLI etc.
     *
     * @param \Psr\Http\Message\RequestInterface|\Symfony\Component\Console\Input\InputInterface $request
     * @return Bootstrap
     * @throws \TYPO3\CMS\Core\Exception
     * @internal This is not a public API method, do not use in own extensions
     */
    public function handleRequest($request)
    {

        // Resolve request handler that were registered based on the Application
        $requestHandler = $this->resolveRequestHandler($request);

        // Execute the command which returns a Response object or NULL
        $this->response = $requestHandler->handleRequest($request);
        return $this;
    }

    /**
     * Outputs content if there is a proper Response object.
     *
     * @return Bootstrap
     */
    protected function sendResponse()
    {
        if ($this->response instanceof \Psr\Http\Message\ResponseInterface) {
            if (!headers_sent()) {
                // If the response code was not changed by legacy code (still is 200)
                // then allow the PSR-7 response object to explicitly set it.
                // Otherwise let legacy code take precedence.
                // This code path can be deprecated once we expose the response object to third party code
                if (http_response_code() === 200) {
                    header('HTTP/' . $this->response->getProtocolVersion() . ' ' . $this->response->getStatusCode() . ' ' . $this->response->getReasonPhrase());
                }

                foreach ($this->response->getHeaders() as $name => $values) {
                    header($name . ': ' . implode(', ', $values));
                }
            }
            echo $this->response->getBody()->__toString();
        }
        return $this;
    }

    /**
     * Registers the instance of the specified object for an early boot stage.
     * On finalizing the Object Manager initialization, all those instances will
     * be transferred to the Object Manager's registry.
     *
     * @param string $objectName Object name, as later used by the Object Manager
     * @param object $instance The instance to register
     * @return void
     * @internal This is not a public API method, do not use in own extensions
     */
    public function setEarlyInstance($objectName, $instance)
    {
        $this->earlyInstances[$objectName] = $instance;
    }

    /**
     * Returns an instance which was registered earlier through setEarlyInstance()
     *
     * @param string $objectName Object name of the registered instance
     * @return object
     * @throws \TYPO3\CMS\Core\Exception
     * @internal This is not a public API method, do not use in own extensions
     */
    public function getEarlyInstance($objectName)
    {
        if (!isset($this->earlyInstances[$objectName])) {
            throw new \TYPO3\CMS\Core\Exception('Unknown early instance "' . $objectName . '"', 1365167380);
        }
        return $this->earlyInstances[$objectName];
    }

    /**
     * Returns all registered early instances indexed by object name
     *
     * @return array
     * @internal This is not a public API method, do not use in own extensions
     */
    public function getEarlyInstances()
    {
        return $this->earlyInstances;
    }

    /**
     * Includes LocalConfiguration.php and sets several
     * global settings depending on configuration.
     *
     * @param bool $allowCaching Whether to allow caching - affects cache_core (autoloader)
     * @param string $packageManagerClassName Define an alternative package manager implementation (usually for the installer)
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function loadConfigurationAndInitialize($allowCaching = true, $packageManagerClassName = \TYPO3\CMS\Core\Package\PackageManager::class)
    {
        $this->populateLocalConfiguration()
            ->initializeErrorHandling();
        if (!$allowCaching) {
            $this->disableCoreCache();
        }
        $this->initializeCachingFramework()
            ->initializePackageManagement($packageManagerClassName)
            ->initializeRuntimeActivatedPackagesFromConfiguration()
            ->defineDatabaseConstants()
            ->defineUserAgentConstant()
            ->registerExtDirectComponents()
            ->setCacheHashOptions()
            ->setDefaultTimezone()
            ->initializeL10nLocales()
            ->convertPageNotFoundHandlingToBoolean()
            ->setMemoryLimit()
            ->defineTypo3RequestTypes();
        if ($allowCaching) {
            $this->ensureClassLoadingInformationExists();
        }
        return $this;
    }

    /**
     * Initializes the package system and loads the package configuration and settings
     * provided by the packages.
     *
     * @param string $packageManagerClassName Define an alternative package manager implementation (usually for the installer)
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function initializePackageManagement($packageManagerClassName)
    {
        /** @var \TYPO3\CMS\Core\Package\PackageManager $packageManager */
        $packageManager = new $packageManagerClassName();
        $this->setEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager::class, $packageManager);
        ExtensionManagementUtility::setPackageManager($packageManager);
        $packageManager->injectCoreCache($this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_core'));
        $dependencyResolver = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Package\DependencyResolver::class);
        $dependencyResolver->injectDependencyOrderingService(GeneralUtility::makeInstance(\TYPO3\CMS\Core\Service\DependencyOrderingService::class));
        $packageManager->injectDependencyResolver($dependencyResolver);
        $packageManager->initialize($this);
        GeneralUtility::setSingletonInstance(\TYPO3\CMS\Core\Package\PackageManager::class, $packageManager);
        return $this;
    }

    /**
     * Writes class loading information if not yet present
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function ensureClassLoadingInformationExists()
    {
        if (!self::$usesComposerClassLoading && !ClassLoadingInformation::isClassLoadingInformationAvailable()) {
            ClassLoadingInformation::dumpClassLoadingInformation();
            ClassLoadingInformation::registerClassLoadingInformation();
        }
        return $this;
    }

    /**
     * Activates a package during runtime. This is used in AdditionalConfiguration.php
     * to enable extensions under conditions.
     *
     * @return Bootstrap
     */
    protected function initializeRuntimeActivatedPackagesFromConfiguration()
    {
        if (!empty($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages']) && is_array($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages'])) {
            /** @var \TYPO3\CMS\Core\Package\PackageManager $packageManager */
            $packageManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager::class);
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXT']['runtimeActivatedPackages'] as $runtimeAddedPackageKey) {
                $packageManager->activatePackageDuringRuntime($runtimeAddedPackageKey);
            }
        }
        return $this;
    }

    /**
     * Load ext_localconf of extensions
     *
     * @param bool $allowCaching
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function loadTypo3LoadedExtAndExtLocalconf($allowCaching = true)
    {
        ExtensionManagementUtility::loadExtLocalconf($allowCaching);
        return $this;
    }

    /**
     * We need an early instance of the configuration manager.
     * Since makeInstance relies on the object configuration, we create it here with new instead.
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function populateLocalConfiguration()
    {
        try {
            $configurationManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class);
        } catch (\TYPO3\CMS\Core\Exception $exception) {
            $configurationManager = new \TYPO3\CMS\Core\Configuration\ConfigurationManager();
            $this->setEarlyInstance(\TYPO3\CMS\Core\Configuration\ConfigurationManager::class, $configurationManager);
        }
        $configurationManager->exportConfiguration();
        return $this;
    }

    /**
     * Set cache_core to null backend, effectively disabling eg. the cache for ext_localconf and PackageManager etc.
     *
     * @return \TYPO3\CMS\Core\Core\Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function disableCoreCache()
    {
        $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_core']['backend']
            = \TYPO3\CMS\Core\Cache\Backend\NullBackend::class;
        unset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['cache_core']['options']);
        return $this;
    }

    /**
     * Define database constants
     *
     * @return \TYPO3\CMS\Core\Core\Bootstrap
     */
    protected function defineDatabaseConstants()
    {
        define('TYPO3_db', $GLOBALS['TYPO3_CONF_VARS']['DB']['database']);
        define('TYPO3_db_username', $GLOBALS['TYPO3_CONF_VARS']['DB']['username']);
        define('TYPO3_db_password', $GLOBALS['TYPO3_CONF_VARS']['DB']['password']);
        define('TYPO3_db_host', $GLOBALS['TYPO3_CONF_VARS']['DB']['host']);
        // Constant TYPO3_extTableDef_script is deprecated since TYPO3 CMS 7 and will be dropped with TYPO3 CMS 8
        define('TYPO3_extTableDef_script',
            isset($GLOBALS['TYPO3_CONF_VARS']['DB']['extTablesDefinitionScript'])
            ? $GLOBALS['TYPO3_CONF_VARS']['DB']['extTablesDefinitionScript']
            : 'extTables.php');
        return $this;
    }

    /**
     * Define user agent constant
     *
     * @return \TYPO3\CMS\Core\Core\Bootstrap
     */
    protected function defineUserAgentConstant()
    {
        define('TYPO3_user_agent', 'User-Agent: ' . $GLOBALS['TYPO3_CONF_VARS']['HTTP']['userAgent']);
        return $this;
    }

    /**
     * Register default ExtDirect components
     *
     * @return Bootstrap
     */
    protected function registerExtDirectComponents()
    {
        if (TYPO3_MODE === 'BE') {
            ExtensionManagementUtility::registerExtDirectComponent(
                'TYPO3.Components.PageTree.DataProvider',
                \TYPO3\CMS\Backend\Tree\Pagetree\ExtdirectTreeDataProvider::class
            );
            ExtensionManagementUtility::registerExtDirectComponent(
                'TYPO3.Components.PageTree.Commands',
                \TYPO3\CMS\Backend\Tree\Pagetree\ExtdirectTreeCommands::class
            );
            ExtensionManagementUtility::registerExtDirectComponent(
                'TYPO3.Components.PageTree.ContextMenuDataProvider',
                \TYPO3\CMS\Backend\ContextMenu\Pagetree\Extdirect\ContextMenuConfiguration::class
            );
            ExtensionManagementUtility::registerExtDirectComponent(
                'TYPO3.ExtDirectStateProvider.ExtDirect',
                \TYPO3\CMS\Backend\InterfaceState\ExtDirect\DataProvider::class
            );
            ExtensionManagementUtility::registerExtDirectComponent(
                'TYPO3.Components.DragAndDrop.CommandController',
                ExtensionManagementUtility::extPath('backend') . 'Classes/View/PageLayout/Extdirect/ExtdirectPageCommands.php:' . \TYPO3\CMS\Backend\View\PageLayout\ExtDirect\ExtdirectPageCommands::class
            );
        }
        return $this;
    }

    /**
     * Initialize caching framework, and re-initializes it (e.g. in the install tool) by recreating the instances
     * again despite the Singleton instance
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function initializeCachingFramework()
    {
        $cacheManager = new \TYPO3\CMS\Core\Cache\CacheManager();
        $cacheManager->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
        GeneralUtility::setSingletonInstance(\TYPO3\CMS\Core\Cache\CacheManager::class, $cacheManager);

        $cacheFactory = new \TYPO3\CMS\Core\Cache\CacheFactory('production', $cacheManager);
        GeneralUtility::setSingletonInstance(\TYPO3\CMS\Core\Cache\CacheFactory::class, $cacheFactory);

        $this->setEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class, $cacheManager);
        return $this;
    }

    /**
     * Set cacheHash options
     *
     * @return Bootstrap
     */
    protected function setCacheHashOptions()
    {
        $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash'] = [
            'cachedParametersWhiteList' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashOnlyForParameters'], true),
            'excludedParameters' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParameters'], true),
            'requireCacheHashPresenceParameters' => GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashRequiredParameters'], true),
            'includePageId' => $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashIncludePageId']
        ];
        if (trim($GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty']) === '*') {
            $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludeAllEmptyParameters'] = true;
        } else {
            $GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParametersIfEmpty'] = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParametersIfEmpty'], true);
        }
        return $this;
    }

    /**
     * Set default timezone
     *
     * @return Bootstrap
     */
    protected function setDefaultTimezone()
    {
        $timeZone = $GLOBALS['TYPO3_CONF_VARS']['SYS']['phpTimeZone'];
        if (empty($timeZone)) {
            // Time zone from the server environment (TZ env or OS query)
            $defaultTimeZone = @date_default_timezone_get();
            if ($defaultTimeZone !== '') {
                $timeZone = $defaultTimeZone;
            } else {
                $timeZone = 'UTC';
            }
        }
        // Set default to avoid E_WARNINGs with PHP > 5.3
        date_default_timezone_set($timeZone);
        return $this;
    }

    /**
     * Initialize the locales handled by TYPO3
     *
     * @return Bootstrap
     */
    protected function initializeL10nLocales()
    {
        \TYPO3\CMS\Core\Localization\Locales::initialize();
        return $this;
    }

    /**
     * Convert type of "pageNotFound_handling" setting in case it was written as a
     * string (e.g. if edited in Install Tool)
     *
     * @TODO : Remove, if the Install Tool handles such data types correctly
     * @return Bootstrap
     */
    protected function convertPageNotFoundHandlingToBoolean()
    {
        if (!strcasecmp($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], 'TRUE')) {
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] = true;
        }
        return $this;
    }

    /**
     * Configure and set up exception and error handling
     *
     * @return Bootstrap
     * @throws \RuntimeException
     */
    protected function initializeErrorHandling()
    {
        $productionExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['productionExceptionHandler'];
        $debugExceptionHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['debugExceptionHandler'];

        $errorHandlerClassName = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandler'];
        $errorHandlerErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['errorHandlerErrors'];
        $exceptionalErrors = $GLOBALS['TYPO3_CONF_VARS']['SYS']['exceptionalErrors'];

        $displayErrorsSetting = (int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['displayErrors'];
        switch ($displayErrorsSetting) {
            case 2:
                GeneralUtility::deprecationLog('The option "$TYPO3_CONF_VARS[SYS][displayErrors]" is set to "2" which is deprecated as of TYPO3 CMS 7, and will be removed with TYPO3 CMS 8. Please change the value to "-1"');
                // intentionally fall through
            case -1:
                $ipMatchesDevelopmentSystem = GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']);
                $exceptionHandlerClassName = $ipMatchesDevelopmentSystem ? $debugExceptionHandlerClassName : $productionExceptionHandlerClassName;
                $displayErrors = $ipMatchesDevelopmentSystem ? 1 : 0;
                $exceptionalErrors = $ipMatchesDevelopmentSystem ? $exceptionalErrors : 0;
                break;
            case 0:
                $exceptionHandlerClassName = $productionExceptionHandlerClassName;
                $displayErrors = 0;
                break;
            case 1:
                $exceptionHandlerClassName = $debugExceptionHandlerClassName;
                $displayErrors = 1;
                break;
            default:
                // Throw exception if an invalid option is set.
                throw new \RuntimeException('The option $TYPO3_CONF_VARS[SYS][displayErrors] is not set to "-1", "0" or "1".');
        }
        @ini_set('display_errors', $displayErrors);

        if (!empty($errorHandlerClassName)) {
            // Register an error handler for the given errorHandlerError
            $errorHandler = GeneralUtility::makeInstance($errorHandlerClassName, $errorHandlerErrors);
            $errorHandler->setExceptionalErrors($exceptionalErrors);
            if (is_callable([$errorHandler, 'setDebugMode'])) {
                $errorHandler->setDebugMode($displayErrors === 1);
            }
        }
        if (!empty($exceptionHandlerClassName)) {
            // Registering the exception handler is done in the constructor
            GeneralUtility::makeInstance($exceptionHandlerClassName);
        }
        return $this;
    }

    /**
     * Set PHP memory limit depending on value of
     * $GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit']
     *
     * @return Bootstrap
     */
    protected function setMemoryLimit()
    {
        if ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] > 16) {
            @ini_set('memory_limit', ((int)$GLOBALS['TYPO3_CONF_VARS']['SYS']['setMemoryLimit'] . 'm'));
        }
        return $this;
    }

    /**
     * Define TYPO3_REQUESTTYPE* constants
     * so devs exactly know what type of request it is
     *
     * @return Bootstrap
     */
    protected function defineTypo3RequestTypes()
    {
        define('TYPO3_REQUESTTYPE_FE', 1);
        define('TYPO3_REQUESTTYPE_BE', 2);
        define('TYPO3_REQUESTTYPE_CLI', 4);
        define('TYPO3_REQUESTTYPE_AJAX', 8);
        define('TYPO3_REQUESTTYPE_INSTALL', 16);
        define('TYPO3_REQUESTTYPE', (TYPO3_MODE == 'FE' ? TYPO3_REQUESTTYPE_FE : 0) | (TYPO3_MODE == 'BE' ? TYPO3_REQUESTTYPE_BE : 0) | (defined('TYPO3_cliMode') && TYPO3_cliMode ? TYPO3_REQUESTTYPE_CLI : 0) | (defined('TYPO3_enterInstallScript') && TYPO3_enterInstallScript ? TYPO3_REQUESTTYPE_INSTALL : 0) | ($GLOBALS['TYPO3_AJAX'] ? TYPO3_REQUESTTYPE_AJAX : 0));
        return $this;
    }

    /**
     * Extensions may register new caches, so we set the
     * global cache array to the manager again at this point
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function setFinalCachingFrameworkCacheConfiguration()
    {
        $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->setCacheConfigurations($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']);
        return $this;
    }

    /**
     * Define logging and exception constants
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function defineLoggingAndExceptionConstants()
    {
        define('TYPO3_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']);
        define('TYPO3_ERROR_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_errorDLOG']);
        define('TYPO3_EXCEPTION_DLOG', $GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_exceptionDLOG']);
        return $this;
    }

    /**
     * Unsetting reserved global variables:
     * Those are set in "ext:core/ext_tables.php" file:
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function unsetReservedGlobalVariables()
    {
        unset($GLOBALS['PAGES_TYPES']);
        unset($GLOBALS['TCA']);
        unset($GLOBALS['TBE_MODULES']);
        unset($GLOBALS['TBE_STYLES']);
        unset($GLOBALS['BE_USER']);
        // Those set otherwise:
        unset($GLOBALS['TBE_MODULES_EXT']);
        unset($GLOBALS['TCA_DESCR']);
        unset($GLOBALS['LOCAL_LANG']);
        unset($GLOBALS['TYPO3_AJAX']);
        return $this;
    }

    /**
     * Initialize database connection in $GLOBALS and connect if requested
     *
     * @return \TYPO3\CMS\Core\Core\Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function initializeTypo3DbGlobal()
    {
        /** @var $databaseConnection \TYPO3\CMS\Core\Database\DatabaseConnection */
        $databaseConnection = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\DatabaseConnection::class);
        $databaseConnection->setDatabaseName(TYPO3_db);
        $databaseConnection->setDatabaseUsername(TYPO3_db_username);
        $databaseConnection->setDatabasePassword(TYPO3_db_password);

        $databaseHost = TYPO3_db_host;
        if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['port'])) {
            $databaseConnection->setDatabasePort($GLOBALS['TYPO3_CONF_VARS']['DB']['port']);
        } elseif (strpos($databaseHost, ':') > 0) {
            // @TODO: Find a way to handle this case in the install tool and drop this
            list($databaseHost, $databasePort) = explode(':', $databaseHost);
            $databaseConnection->setDatabasePort($databasePort);
        }
        if (isset($GLOBALS['TYPO3_CONF_VARS']['DB']['socket'])) {
            $databaseConnection->setDatabaseSocket($GLOBALS['TYPO3_CONF_VARS']['DB']['socket']);
        }
        $databaseConnection->setDatabaseHost($databaseHost);

        $databaseConnection->debugOutput = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sqlDebug'];

        if (
            isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect'])
            && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['no_pconnect']
        ) {
            $databaseConnection->setPersistentDatabaseConnection(true);
        }

        $isDatabaseHostLocalHost = $databaseHost === 'localhost' || $databaseHost === '127.0.0.1' || $databaseHost === '::1';
        if (
            isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress'])
            && $GLOBALS['TYPO3_CONF_VARS']['SYS']['dbClientCompress']
            && !$isDatabaseHostLocalHost
        ) {
            $databaseConnection->setConnectionCompression(true);
        }

        if (!empty($GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit'])) {
            $commandsAfterConnect = GeneralUtility::trimExplode(
                LF,
                str_replace('\' . LF . \'', LF, $GLOBALS['TYPO3_CONF_VARS']['SYS']['setDBinit']),
                true
            );
            $databaseConnection->setInitializeCommandsAfterConnect($commandsAfterConnect);
        }

        $GLOBALS['TYPO3_DB'] = $databaseConnection;
        // $GLOBALS['TYPO3_DB'] needs to be defined first in order to work for DBAL
        $GLOBALS['TYPO3_DB']->initialize();

        return $this;
    }

    /**
     * Check adminOnly configuration variable and redirects
     * to an URL in file typo3conf/LOCK_BACKEND or exit the script
     *
     * @throws \RuntimeException
     * @param bool $forceProceeding if this option is set, the bootstrap will proceed even if the user is logged in (usually only needed for special AJAX cases, see AjaxRequestHandler)
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function checkLockedBackendAndRedirectOrDie($forceProceeding = false)
    {
        if ($GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'] < 0) {
            throw new \RuntimeException('TYPO3 Backend locked: Backend and Install Tool are locked for maintenance. [BE][adminOnly] is set to "' . (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['adminOnly'] . '".', 1294586847);
        }
        if (@is_file(PATH_typo3conf . 'LOCK_BACKEND') && $forceProceeding === false) {
            $fileContent = GeneralUtility::getUrl(PATH_typo3conf . 'LOCK_BACKEND');
            if ($fileContent) {
                header('Location: ' . $fileContent);
            } else {
                throw new \RuntimeException('TYPO3 Backend locked: Browser backend is locked for maintenance. Remove lock by removing the file "typo3conf/LOCK_BACKEND" or use CLI-scripts.', 1294586848);
            }
            die;
        }
        return $this;
    }

    /**
     * Compare client IP with IPmaskList and exit the script run
     * if the client is not allowed to access the backend
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     * @throws \RuntimeException
     */
    public function checkBackendIpOrDie()
    {
        if (trim($GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
            if (!GeneralUtility::cmpIP(GeneralUtility::getIndpEnv('REMOTE_ADDR'), $GLOBALS['TYPO3_CONF_VARS']['BE']['IPmaskList'])) {
                throw new \RuntimeException('TYPO3 Backend access denied: The IP address of your client does not match the list of allowed IP addresses.', 1389265900);
            }
        }
        return $this;
    }

    /**
     * Check lockSSL configuration variable and redirect
     * to https version of the backend if needed
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     * @throws \RuntimeException
     */
    public function checkSslBackendAndRedirectIfNeeded()
    {
        if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL']) {
            if (!GeneralUtility::getIndpEnv('TYPO3_SSL')) {
                if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] === 2) {
                    if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']) {
                        $sslPortSuffix = ':' . (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
                    } else {
                        $sslPortSuffix = '';
                    }
                    list(, $url) = explode('://', GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir, 2);
                    list($server, $address) = explode('/', $url, 2);
                    header('Location: https://' . $server . $sslPortSuffix . '/' . $address);
                    die;
                } else {
                    throw new \RuntimeException('TYPO3 Backend not accessed via SSL: TYPO3 Backend is configured to only be accessible through SSL. Change the URL in your browser and try again.', 1389265726);
                }
            }
        }
        return $this;
    }

    /**
     * Load TCA for frontend
     *
     * This method is *only* executed in frontend scope. The idea is to execute the
     * whole TCA and ext_tables (which manipulate TCA) on first frontend access,
     * and then cache the full TCA on disk to be used for the next run again.
     *
     * This way, ext_tables.php ist not executed every time, but $GLOBALS['TCA']
     * is still always there.
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function loadCachedTca()
    {
        $cacheIdentifier = 'tca_fe_' . sha1((TYPO3_version . PATH_site . 'tca_fe'));
        /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
        $codeCache = $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_core');
        if ($codeCache->has($cacheIdentifier)) {
            // substr is necessary, because the php frontend wraps php code around the cache value
            $GLOBALS['TCA'] = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
        } else {
            $this->loadExtensionTables(true);
            $codeCache->set($cacheIdentifier, serialize($GLOBALS['TCA']));
        }
        return $this;
    }

    /**
     * Load ext_tables and friends.
     *
     * This will mainly set up $TCA and several other global arrays
     * through API's like extMgm.
     * Executes ext_tables.php files of loaded extensions or the
     * according cache file if exists.
     *
     * @param bool $allowCaching True, if reading compiled ext_tables file from cache is allowed
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function loadExtensionTables($allowCaching = true)
    {
        ExtensionManagementUtility::loadBaseTca($allowCaching);
        ExtensionManagementUtility::loadExtTables($allowCaching);
        $this->executeExtTablesAdditionalFile();
        $this->runExtTablesPostProcessingHooks();
        return $this;
    }

    /**
     * Execute TYPO3_extTableDef_script if defined and exists
     *
     * Note: For backwards compatibility some global variables are
     * explicitly set as global to be used without $GLOBALS[] in
     * the extension table script. It is discouraged to access variables like
     * $TBE_MODULES directly, but we can not prohibit
     * this without heavily breaking backwards compatibility.
     *
     * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8
     * @return void
     */
    protected function executeExtTablesAdditionalFile()
    {
        // It is discouraged to use those global variables directly, but we
        // can not prohibit this without breaking backwards compatibility
        global $T3_SERVICES, $T3_VAR, $TYPO3_CONF_VARS;
        global $TBE_MODULES, $TBE_MODULES_EXT, $TCA;
        global $PAGES_TYPES, $TBE_STYLES;
        global $_EXTKEY;
        // Load additional ext tables script if the file exists
        $extTablesFile = PATH_typo3conf . TYPO3_extTableDef_script;
        if (file_exists($extTablesFile) && is_file($extTablesFile)) {
            GeneralUtility::deprecationLog(
                'Using typo3conf/' . TYPO3_extTableDef_script . ' is deprecated and will be removed with TYPO3 CMS 8. Please move your TCA overrides'
                . ' to Configuration/TCA/Overrides of your project specific extension, or slot the signal "tcaIsBeingBuilt" for further processing.'
            );
            include $extTablesFile;
        }
    }

    /**
     * Check for registered ext tables hooks and run them
     *
     * @throws \UnexpectedValueException
     * @return void
     */
    protected function runExtTablesPostProcessingHooks()
    {
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'])) {
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['extTablesInclusion-PostProcessing'] as $classReference) {
                /** @var $hookObject \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface */
                $hookObject = GeneralUtility::getUserObj($classReference);
                if (!$hookObject instanceof \TYPO3\CMS\Core\Database\TableConfigurationPostProcessingHookInterface) {
                    throw new \UnexpectedValueException(
                        '$hookObject "' . $classReference . '" must implement interface TYPO3\\CMS\\Core\\Database\\TableConfigurationPostProcessingHookInterface',
                        1320585902
                    );
                }
                $hookObject->processData();
            }
        }
    }

    /**
     * Initialize sprite manager
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     * @deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8
     */
    public function initializeSpriteManager()
    {
        // This method is deprecated since TYPO3 CMS 7, will be removed with TYPO3 CMS 8
        // This method does not log a deprecation message, because it is used only in the request handlers
        // and would break icons from IconUtility::getSpriteIcon() if we remove it yet.
        \TYPO3\CMS\Backend\Sprite\SpriteManager::initialize();
        return $this;
    }

    /**
     * Initialize the Routing for the TYPO3 Backend
     * Loads all routes registered inside all packages and stores them inside the Router
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function initializeBackendRouter()
    {
        // See if the Routes.php from all active packages have been built together already
        $cacheIdentifier = 'BackendRoutesFromPackages_' . sha1((TYPO3_version . PATH_site . 'BackendRoutesFromPackages'));

        /** @var $codeCache \TYPO3\CMS\Core\Cache\Frontend\PhpFrontend */
        $codeCache = $this->getEarlyInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('cache_core');
        $routesFromPackages = [];
        if ($codeCache->has($cacheIdentifier)) {
            // substr is necessary, because the php frontend wraps php code around the cache value
            $routesFromPackages = unserialize(substr($codeCache->get($cacheIdentifier), 6, -2));
        } else {
            // Loop over all packages and check for a Configuration/Backend/Routes.php file
            $packageManager = $this->getEarlyInstance(\TYPO3\CMS\Core\Package\PackageManager::class);
            $packages = $packageManager->getActivePackages();
            foreach ($packages as $package) {
                $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/Routes.php';
                if (file_exists($routesFileNameForPackage)) {
                    $definedRoutesInPackage = require $routesFileNameForPackage;
                    if (is_array($definedRoutesInPackage)) {
                        $routesFromPackages = array_merge($routesFromPackages, $definedRoutesInPackage);
                    }
                }
                $routesFileNameForPackage = $package->getPackagePath() . 'Configuration/Backend/AjaxRoutes.php';
                if (file_exists($routesFileNameForPackage)) {
                    $definedRoutesInPackage = require $routesFileNameForPackage;
                    if (is_array($definedRoutesInPackage)) {
                        foreach ($definedRoutesInPackage as $routeIdentifier => $routeOptions) {
                            // prefix the route with "ajax_" as "namespace"
                            $routeOptions['path'] = '/ajax' . $routeOptions['path'];
                            $routesFromPackages['ajax_' . $routeIdentifier] = $routeOptions;
                            $routesFromPackages['ajax_' . $routeIdentifier]['ajax'] = true;
                        }
                    }
                }
            }
            // Store the data from all packages in the cache
            $codeCache->set($cacheIdentifier, serialize($routesFromPackages));
        }

        // Build Route objects from the data
        $router = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Router::class);
        foreach ($routesFromPackages as $name => $options) {
            $path = $options['path'];
            unset($options['path']);
            $route = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Routing\Route::class, $path, $options);
            $router->addRoute($name, $route);
        }
        return $this;
    }

    /**
     * Initialize backend user object in globals
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function initializeBackendUser()
    {
        /** @var $backendUser \TYPO3\CMS\Core\Authentication\BackendUserAuthentication */
        $backendUser = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Authentication\BackendUserAuthentication::class);
        $backendUser->warningEmail = $GLOBALS['TYPO3_CONF_VARS']['BE']['warning_email_addr'];
        $backendUser->lockIP = $GLOBALS['TYPO3_CONF_VARS']['BE']['lockIP'];
        $backendUser->auth_timeout_field = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['sessionTimeout'];
        if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI) {
            $backendUser->dontSetCookie = true;
        }
        // The global must be available very early, because methods below
        // might trigger code which relies on it. See: #45625
        $GLOBALS['BE_USER'] = $backendUser;
        $backendUser->start();
        return $this;
    }

    /**
     * Initializes and ensures authenticated access
     *
     * @internal This is not a public API method, do not use in own extensions
     * @param bool $proceedIfNoUserIsLoggedIn if set to TRUE, no forced redirect to the login page will be done
     * @return \TYPO3\CMS\Core\Core\Bootstrap
     */
    public function initializeBackendAuthentication($proceedIfNoUserIsLoggedIn = false)
    {
        $GLOBALS['BE_USER']->backendCheckLogin($proceedIfNoUserIsLoggedIn);
        return $this;
    }

    /**
     * Initialize language object
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function initializeLanguageObject()
    {
        /** @var $GLOBALS['LANG'] \TYPO3\CMS\Lang\LanguageService */
        $GLOBALS['LANG'] = GeneralUtility::makeInstance(\TYPO3\CMS\Lang\LanguageService::class);
        $GLOBALS['LANG']->init($GLOBALS['BE_USER']->uc['lang']);
        return $this;
    }

    /**
     * Throw away all output that may have happened during bootstrapping by weird extensions
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function endOutputBufferingAndCleanPreviousOutput()
    {
        ob_clean();
        return $this;
    }

    /**
     * Initialize output compression if configured
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function initializeOutputCompression()
    {
        if (extension_loaded('zlib') && $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']) {
            if (MathUtility::canBeInterpretedAsInteger($GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel'])) {
                @ini_set('zlib.output_compression_level', $GLOBALS['TYPO3_CONF_VARS']['BE']['compressionLevel']);
            }
            ob_start('ob_gzhandler');
        }
        return $this;
    }

    /**
     * Send HTTP headers if configured
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function sendHttpHeaders()
    {
        if (!empty($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers']) && is_array($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'])) {
            foreach ($GLOBALS['TYPO3_CONF_VARS']['BE']['HTTP']['Response']['Headers'] as $header) {
                header($header);
            }
        }
        return $this;
    }

    /**
     * Things that should be performed to shut down the framework.
     * This method is called in all important scripts for a clean
     * shut down of the system.
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function shutdown()
    {
        $this->sendResponse();
        return $this;
    }

    /**
     * Provides an instance of "template" for backend-modules to
     * work with.
     *
     * @return Bootstrap
     * @internal This is not a public API method, do not use in own extensions
     */
    public function initializeBackendTemplate()
    {
        $GLOBALS['TBE_TEMPLATE'] = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Template\DocumentTemplate::class);
        return $this;
    }
}


text:
[![dependencies](https://david-dm.org/michaelcontento/mocca.svg)](https://david-dm.org/michaelcontento/mocca)
[![devDependencies](https://david-dm.org/michaelcontento/mocca/dev-status.svg)](https://david-dm.org/michaelcontento/mocca#info=devDependencies)

[![license](https://img.shields.io/npm/l/mocca.svg?style=flat-square)](https://www.npmjs.com/package/mocca)
[![npm version](https://img.shields.io/npm/v/mocca.svg?style=flat-square)](https://www.npmjs.com/package/mocca)
[![npm downloads](https://img.shields.io/npm/dm/mocca.svg?style=flat-square)](https://www.npmjs.com/package/mocca)

## Overview

It's quite cumbersome to install [mocha][], all awesome plugin you love and
call it with the right arguments...

... but [mocca][] is here to help you!

## Features

- A whole bunch of awesome plugins
    - [chai][]
    - [chai-as-promised][]
    - [chai-string][]
    - [mocha][]
    - [mocha-clean][]
    - [mocha-junit-reporter][]
    - [sinon][]
    - [sinon-as-promised][]
    - [sinon-chai][]
- Auto detects [babel][]
    - `npm install babel-core` and `babel-core/register` will be used as compiler
- Overwrite options from either `.mocha.opts` or `.moccarc`
- Creates a JUnit compliant `test-results.xml` on [TravisCI][] and [CircleCI][]
   - To be honest: It's based on the existance of the environment variable `CI`
- Detect test files based on the `__test__/someFile-test.js` naming scheme

## Installation

It's simple as:

    $ npm install --save-dev mocca

And running your tests is also pretty simple:

    $ ./node_modules/.bin/mocca

  [mocca]: https://github.com/michaelcontento/mocca
  [babel]: babeljs.io
  [TravisCI]: https://travis-ci.org/
  [CircleCI]: https://circleci.com/
  [chai]: https://www.npmjs.com/package/chai
  [chai-as-promised]: https://www.npmjs.com/package/chai-as-promised
  [chai-string]: https://www.npmjs.com/package/chai-string
  [mocha]: https://www.npmjs.com/package/mocha
  [mocha-clean]: https://www.npmjs.com/package/mocha-clean
  [mocha-junit-reporter]: https://www.npmjs.com/package/mocha-junit-reporter
  [sinon]: https://www.npmjs.com/package/sinon
  [sinon-as-promised]: https://www.npmjs.com/package/sinon-as-promised
  [sinon-chai]: https://www.npmjs.com/package/sinon-chai


text:
cask 'jtool' do
  version :latest
  sha256 :no_check

  url 'http://www.newosxbook.com/tools/jtool.tar'
  name 'jtool'
  homepage 'http://newosxbook.com/tools/jtool.html'

  binary 'jtool'
end


text:
package org.oclc.firefly.hadoop.backup;

import java.io.IOException;
import java.util.List;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;

/**
 * Input format for back up map reduce
 * @param <Text>
 * @param <HRegionInfo>
 */
public class BackupInputFormat<Text, HRegionInfo> extends FileInputFormat<Text, HRegionInfo> {

    @SuppressWarnings("unchecked")
    @Override
    public RecordReader<Text, HRegionInfo> createRecordReader(InputSplit split, TaskAttemptContext context)
        throws IOException {
        return (RecordReader<Text, HRegionInfo>)new BackupRecordReader();
    }

    @Override
    protected long getFormatMinSplitSize() {
        return SequenceFile.SYNC_INTERVAL;
    }

    @Override
    protected List<FileStatus> listStatus(JobContext job) throws IOException {
        List<FileStatus> files = super.listStatus(job);
        int len = files.size();

        for (int i = 0; i < len; ++i) {
            FileStatus file = files.get(i);
            if (file.isDir()) {
                Path p = file.getPath();
                FileSystem fs = p.getFileSystem(job.getConfiguration());
                files.set(i, fs.getFileStatus(new Path(p, MapFile.DATA_FILE_NAME)));
            }
        }

        return files;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="navigation_drawer_width">240dp</dimen>

    <dimen name="com_sgc_text_field_bottom_margin">10dp</dimen>
    <dimen name="com_sgc_mainactivity_button_width">250dp</dimen>

    <dimen name="com_facebook_loginview_padding_left">12dip</dimen>
    <dimen name="com_facebook_loginview_padding_right">16dp</dimen>
    <dimen name="com_facebook_loginview_padding_top">12dp</dimen>
    <dimen name="com_facebook_loginview_padding_bottom">12dp</dimen>
    <dimen name="com_facebook_loginview_compound_drawable_padding">12dp</dimen>
    <dimen name="com_facebook_loginview_text_size">16.0sp</dimen>
</resources>


text:
package org.apache.samoa.learners.classifiers.ensemble;

import java.util.Arrays;
import java.util.Random;

/**
 * License
 */

import org.apache.samoa.core.ContentEvent;
import org.apache.samoa.core.Processor;
import org.apache.samoa.instances.Instance;
import org.apache.samoa.learners.InstanceContentEvent;
import org.apache.samoa.topology.Stream;

/**
 * The Class BaggingDistributorPE.
 */
public class ShardingDistributorProcessor implements Processor {

  private static final long serialVersionUID = -1550901409625192730L;

  /** The ensemble size. */
  private int ensembleSize;

  /** The stream ensemble. */
  private Stream[] ensembleStreams;

  /** Ramdom number generator. */
  protected Random random = new Random(); //TODO make random seed configurable

  /**
   * On event.
   *
   * @param event
   *          the event
   * @return true, if successful
   */
  public boolean process(ContentEvent event) {
    InstanceContentEvent inEvent = (InstanceContentEvent) event;
    if (inEvent.isLastEvent()) {
      // end learning
      for (Stream stream : ensembleStreams)
        stream.put(event);
      return false;
    }

    if (inEvent.isTesting()) {
      Instance testInstance = inEvent.getInstance();
      for (int i = 0; i < ensembleSize; i++) {
        Instance instanceCopy = testInstance.copy();
        InstanceContentEvent instanceContentEvent = new InstanceContentEvent(inEvent.getInstanceIndex(), instanceCopy,
            false, true);
        instanceContentEvent.setClassifierIndex(i); //TODO probably not needed anymore
        instanceContentEvent.setEvaluationIndex(inEvent.getEvaluationIndex()); //TODO probably not needed anymore
        ensembleStreams[i].put(instanceContentEvent);
      }
    }

    // estimate model parameters using the training data
    if (inEvent.isTraining()) {
      train(inEvent);
    }
    return false;
  }

  /**
   * Train.
   *
   * @param inEvent
   *          the in event
   */
  protected void train(InstanceContentEvent inEvent) {
    Instance trainInst = inEvent.getInstance().copy();
    InstanceContentEvent instanceContentEvent = new InstanceContentEvent(inEvent.getInstanceIndex(), trainInst,
        true, false);
    int i = random.nextInt(ensembleSize);
    instanceContentEvent.setClassifierIndex(i);
    instanceContentEvent.setEvaluationIndex(inEvent.getEvaluationIndex());
    ensembleStreams[i].put(instanceContentEvent);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.s4.core.ProcessingElement#onCreate()
   */
  @Override
  public void onCreate(int id) {
    // do nothing
  }

  public Stream[] getOutputStreams() {
    return ensembleStreams;
  }

  public void setOutputStreams(Stream[] ensembleStreams) {
    this.ensembleStreams = ensembleStreams;
  }

  /**
   * Gets the size ensemble.
   *
   * @return the size ensemble
   */
  public int getEnsembleSize() {
    return ensembleSize;
  }

  /**
   * Sets the size ensemble.
   *
   * @param ensembleSize
   *          the new size ensemble
   */
  public void setEnsembleSize(int ensembleSize) {
    this.ensembleSize = ensembleSize;
  }

  /*
   * (non-Javadoc)
   *
   * @see samoa.core.Processor#newProcessor(samoa.core.Processor)
   */
  @Override
  public Processor newProcessor(Processor sourceProcessor) {
    ShardingDistributorProcessor newProcessor = new ShardingDistributorProcessor();
    ShardingDistributorProcessor originProcessor = (ShardingDistributorProcessor) sourceProcessor;
    if (originProcessor.getOutputStreams() != null) {
      newProcessor.setOutputStreams(Arrays.copyOf(originProcessor.getOutputStreams(),
          originProcessor.getOutputStreams().length));
    }
    newProcessor.setEnsembleSize(originProcessor.getEnsembleSize());
    /*
     * if (originProcessor.getLearningCurve() != null){
     * newProcessor.setLearningCurve((LearningCurve)
     * originProcessor.getLearningCurve().copy()); }
     */
    return newProcessor;
  }
}


text:
package com.albedinsky.android.dialog.view;

import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;

import com.albedinsky.android.dialog.widget.DialogRecyclerContent;
import com.albedinsky.android.dialog.RecyclerDialog;

import java.util.List;

/**
 * A {@link BaseAdapterDialogView} extension used by {@link RecyclerDialog RecyclerDialog} as interface
 * layer for its content view.
 * <p/>
 * See default {@link DialogRecyclerContent implementation}
 * for more info.
 *
 * @author Martin Albedinsky
 */
public interface RecyclerDialogView extends BaseAdapterDialogView<RecyclerView.Adapter, RecyclerView> {

    /**
     * Interface ===================================================================================
     */

    /**
     * Simple interface for recycler adapters that are to be used within context of {@link RecyclerDialog}.
     * This adapter interface specifies simple API layer to provide a {@link android.support.v7.widget.RecyclerView.LayoutManager LayoutManager}
     * via {@link #provideLayoutManager()} and a list of {@link android.support.v7.widget.RecyclerView.ItemDecoration ItemDecorations}
     * via {@link #provideItemDecorations()} for the {@link RecyclerView} to which will be this
     * RecyclerAdapter implementation attached.
     *
     * @author Martin Albedinsky
     * @see RecyclerView#setLayoutManager(RecyclerView.LayoutManager)
     * @see RecyclerView#addItemDecoration(RecyclerView.ItemDecoration)
     */
    interface RecyclerAdapter {

        /**
         * Provides an instance of layout manager that should be set to the {@link RecyclerView} to
         * which is this adapter attached.
         *
         * @return Layout manager to be used for the recycler view or {@code null} to use default
         * {@link android.support.v7.widget.LinearLayoutManager LinearLayoutManager}.
         * @see RecyclerView#setLayoutManager(RecyclerView.LayoutManager)
         */
        @Nullable
        RecyclerView.LayoutManager provideLayoutManager();

        /**
         * Provides a list of item decorations that should be added into the {@link RecyclerView} to
         * which is this adapter attached.
         *
         * @return List of item decorations or {@code null} to not add any item decorations.
         * @see RecyclerView#addItemDecoration(RecyclerView.ItemDecoration)
         */
        @Nullable
        List<RecyclerView.ItemDecoration> provideItemDecorations();
    }

    /**
     * Methods =====================================================================================
     */

    /**
     * Sets a layout manager for the RecyclerView of this dialog view.
     *
     * @param layoutManager The desired layout manager. May be {@code null} to clear the current one.
     * @see RecyclerView#setLayoutManager(RecyclerView.LayoutManager)
     * @see #getLayoutManager()
     */
    void setLayoutManager(@Nullable RecyclerView.LayoutManager layoutManager);

    /**
     * Returns the RecyclerView's layout manager specified for this dialog view.
     *
     * @return Current layout manager or {@code null} if no layout manager has been specified yet.
     * @see #setLayoutManager(RecyclerView.LayoutManager)
     */
    @Nullable
    RecyclerView.LayoutManager getLayoutManager();
}


text:
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace DayHoliday.Models
{
    public class DayLTParser
    {
        public HtmlDocument doc { get; set; }
        /// <summary>
        /// Loads page with specified encoding.
        /// </summary>
        /// <param name="page">page to load.</param>
        /// <param name="encoding">encoding to use.</param>
        private void loadPage(string page, string encoding)
        {
            HtmlWeb web = new HtmlWeb();
            // Set encoding.
            web.OverrideEncoding = Encoding.GetEncoding(encoding);
            // Load page.
            doc = web.Load(page);
        }
        /// <summary>
        /// Parse holiday names from "day.lt" website at the specified date.
        /// </summary>
        /// <param name="date">date.</param>
        /// <returns>List of Strings which represent holidays at the specified date.</returns>
        public List<String> parseHolidays(string date)
        {
            loadPage("http://day.lt/diena/" + date, "windows-1257");
            List<String> holidays = new List<String>();
            try
            {
                // Find nodes.
                HtmlNode node = doc.DocumentNode.SelectSingleNode("//p[@class='sventes']");
                foreach (HtmlNode node2 in node.SelectNodes(".//span"))
                {
                    string holiday = node2.InnerText;
                    // Add parsed text.
                    holidays.Add(holiday);
                }
            }
            catch (Exception e)
            {
                Console.Write(e.StackTrace);
            }
            // Return found holidays.
            return holidays;
        }
    }
}


text:
/**
 * Created by IntelliJ IDEA.
 * User: Lennart
 * Date: 22-sep-2005
 * Time: 21:05:31
 */
package com.compomics.cell_motility.util;

import com.compomics.cell_motility.interfaces.AverageDisplacements;
import com.compomics.cell_motility.interfaces.CellMotionCalculator;
import com.compomics.cell_motility.interfaces.CellMotionPath;
import flanagan.analysis.Regression;
import flanagan.analysis.RegressionFunction;
/*
 * CVS information:
 *
 * $Revision: 1.6 $
 * $Date: 2007/05/20 16:28:30 $
 */

/**
 * This class computes the statistics for a cell motion path as described by
 * DiMilla et al., The Journal of Cell Biology 1993, Volume 122, Number 3, 729-737.
 *
 * @author Lennart Martens
 * @version $Id: CellMotionCalculatorImpl.java,v 1.6 2007/05/20 16:28:30 lennart Exp $
 */
public class CellMotionCalculatorImpl implements CellMotionCalculator {

    /**
     * The function to fit.
     */
    private RegressionFunction iFunction = null;

    /**
     * The average displacements calculator.
     */
    private AverageDisplacements iAverageDisplacements = null;

    /**
     * Fitted values for the function coefficients.
     */
    private double[] iCoefficients = null;

    /**
     * The number of iterations it took for the fitting to complete.
     */
    private int iNumberOfIterations = 0;

    /**
     * This boolean indicates whether the number of iterations were sufficient
     * for the completion of the fitting.
     */
    private boolean iComplete = false;

    /**
     * Goodness of fit measure.
     */
    private double iGoodnessOfFit = 0.0;

    /**
     * This constructor takes the CellMotionPathImpl and calculates the
     * relevant statistics.
     *
     * @param aAverageDisplacementsCalculator   AverageDisplacements instance that provides MSD data.
     * @param aNumberOfFittingIterations    int with the maximum number of curve fitting iterations.
     */
    public CellMotionCalculatorImpl(AverageDisplacements aAverageDisplacementsCalculator, int aNumberOfFittingIterations, double aInitialS, double aInitialP) {
        // First set up the time scale and averages.
        iAverageDisplacements = aAverageDisplacementsCalculator;
        // Then do the fitting.
        performFitting(aNumberOfFittingIterations, aInitialS, aInitialP);
    }

    public double[] getAverageDisplacements() {
        return iAverageDisplacements.getAverageDisplacements();
    }

    public double[] getTimeScale() {
        return iAverageDisplacements.getTimeScale();
    }

    /**
     * This method returns the coefficients of the fitted function.
     *
     * @return double[] with the coefficients.
     */
    public double[] getCoefficients() {
        return iCoefficients;
    }

    /**
     * This method returns the function that is fitted.
     *
     * @return RegressionFunction with the fitted function.
     */
    public RegressionFunction getFunction() {
        return iFunction;
    }

    public boolean isComplete() {
        return iComplete;
    }

    public double getGoodnessOfFit() {
        return iGoodnessOfFit;
    }

    public int getNumberOfIterations() {
        return iNumberOfIterations;
    }

    /**
     * This method returns the label for this calculator for display
     * to the user.
     *
     * @return String with the label for this calculator.
     */
    public String getLabel() {
        return iAverageDisplacements.getLabel();
    }

    /**
     * This method sets the label on the implementation.
     *
     * @param aLabel String with the label for this implementation.
     */
    public void setLabel(String aLabel) {
        iAverageDisplacements.setLabel(aLabel);
    }

    /**
     * This method initializes the AverageDisplacements instance in lieu of a constructor.
     * It also directly calculates the average displacements.
     *
     * @param aSourceData CellMotionPathImpl with the raw data to process.
     * @param aTimeDelta  double with the time between each recorded position in seconds.
     * @param aLabel      String with the display label for this instance.
     */
    public void initialize(CellMotionPath aSourceData, double aTimeDelta, String aLabel) {
        if(iAverageDisplacements != null) {
            iAverageDisplacements.initialize(aSourceData, aTimeDelta, aLabel);
        }
    }

    /**
     * This method performs the fitting of the random walk equation parameters
     * 'S' and 'P' to the observed values.
     *
     * @param aIterations   int with the maximum number of iterations to use
     *                      during curve fitting.
     */
    private void performFitting(int aIterations, double aInitialS, double aInitialP) {
        // Okay, we'll need an X-array, Y-array and a weight for each.
        // The Y-array are the average displacements, so we already have those.
        double[] lAverageDisplacements = iAverageDisplacements.getAverageDisplacements();
        // The X-array will be the time scales
        // and the weights will simply be '1.0' for each (x, y) pair.
        double[] weights = new double[lAverageDisplacements.length];
        for (int i = 0; i < lAverageDisplacements.length; i++) {
            weights[i] = 1.0;
        }

        // Create an instance of the function we want to fit.
        iFunction = new RandomWalkFunction();
        // Initial estimates of S and P.
        double[] startValues = new double[2];
        startValues[0] = aInitialS;
        startValues[1] = aInitialP;

        // Initial step sizes.
        double[] stepSizes = new double[2];
        stepSizes[0] = 0.01;
        stepSizes[1] = 5;

        // Create an instance of the Regression class.
        Regression regression = new Regression(iAverageDisplacements.getTimeScale(), lAverageDisplacements, weights);
        // Do the regression with default stepvalues and a maximum number of iterations of
        // 300000.
        regression.simplex(iFunction, startValues, aIterations);
        iCoefficients = regression.getCoeff();
        iNumberOfIterations = regression.getNiter();
        iComplete = regression.getNlrStatus();
        //iGoodnessOfFit = regression.getSumOfSquares()/iAverageDisplacements[iAverageDisplacements.length-1];
        iGoodnessOfFit = regression.getSumOfSquares();
    }
}


text:
    <ion-icon class="icon" name="logo-angular"></ion-icon>
    {{ APP_TITLE }}

    <ion-icon class="icon" name="reorder-three"></ion-icon>

            <ion-icon class="icon" name="settings"></ion-icon>
            设置/资料

            <ion-icon class="icon" name="power"></ion-icon>
            退出登录


text:
package com.hazelcast.security.permission;

public class MultiMapPermission extends MapPermission {

    public MultiMapPermission(String name, String... actions) {
        super(name, actions);
    }
}


text:
"""
django informer checker base
"""

import logging
from importlib import import_module

from informer.models import post_check

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('Django Infomer')

class InformerException(Exception):
    """
    A class to deal with exceptions.
    """
    pass

class BaseInformer(object):
    """
    A (base) class to serve as infrastructure to new 'Informers'.
    """

    def __str__(self):
        return u'A small and explicit description from informer.'

    def __new__(cls, *args, **kwargs):
        """
        On instantiation, the trigger's is added.
        """
        measures = cls.get_measures()

        for measure in measures:
            func = getattr(cls, measure)
            setattr(cls, measure, save(func))

        # Bind 'run all' on default check.
        func = getattr(cls, 'check_availability')
        setattr(cls, 'check_availability', run(func))

        return super(BaseInformer, cls).__new__(cls)

    def check_availability(self):
        """
        Each informer need check the availability from resource or service.
        """
        raise NotImplementedError

    @staticmethod
    def get_class(namespace, classname):
        """
        Dynamic import from Informer
        """
        try:
            module = import_module(namespace)
            cls = getattr(module, classname)
        except ImportError:
            raise InformerException(
                '%s is unknown or undefined.' % classname)
        except AttributeError:
            raise InformerException(
                'The %s does not exists on %s.' % (classname, namespace))
        except Exception as error:
            raise InformerException(
                'A general exception occurred: %s.' % error)

        if not issubclass(cls, BaseInformer):
            raise InformerException('%s is not a Informer.' % classname)

        return cls

    @classmethod
    def get_measures(cls):
        """
        Get measures
        """
        return [attr for attr in dir(cls) if attr.startswith('check_')]

def save(func):
    """
    When a verification is done, the signal to save data is sent.
    """
    def trigger(cls, *args, **kwargs):
        measure = func.__name__
        values = func(cls)

        if measure not in cls.get_measures():
            return values

        post_check.send(sender=cls, measure=measure, value=values[0])

        message = ' %s (%s) collected values %s'
        message %= (measure, cls.__class__.__name__, values)

        logger.info(message)

        return values

    return trigger

def run(func):
    """
    When 'check availability' is called, all others run on cascade.
    """
    def trigger(cls, *args, **kwargs):
        values = func(cls)

        measures = cls.get_measures()
        measures.remove('check_availability')  # Remove to avoid double run.

        for measure in measures:
            getattr(cls, measure)()

        return values

    return trigger


text:
package varz_test

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/F5Networks/cf-bigip-ctlr/config"
	"github.com/F5Networks/cf-bigip-ctlr/logger"
	"github.com/F5Networks/cf-bigip-ctlr/metrics/fakes"
	"github.com/F5Networks/cf-bigip-ctlr/registry"
	"github.com/F5Networks/cf-bigip-ctlr/route"
	"github.com/F5Networks/cf-bigip-ctlr/test_util"
	. "github.com/F5Networks/cf-bigip-ctlr/varz"

	"code.cloudfoundry.org/routing-api/models"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Varz", func() {
	var Varz Varz
	var Registry *registry.RouteRegistry
	var logger logger.Logger

	BeforeEach(func() {
		logger = test_util.NewTestZapLogger("test")
		Registry = registry.NewRouteRegistry(logger, config.DefaultConfig(), nil, new(fakes.FakeRouteRegistryReporter), "")
		Varz = NewVarz(Registry)
	})

	It("contains the following items", func() {
		v := Varz

		members := []string{
			"responses_2xx",
			"responses_3xx",
			"responses_4xx",
			"responses_5xx",
			"responses_xxx",
			"latency",
			"rate",
			"tags",
			"urls",
			"droplets",
			"requests",
			"bad_requests",
			"bad_gateways",
			"requests_per_sec",
			"top10_app_requests",
			"ms_since_last_registry_update",
		}

		b, e := json.Marshal(v)
		Expect(e).ToNot(HaveOccurred())

		d := make(map[string]interface{})
		e = json.Unmarshal(b, &d)
		Expect(e).ToNot(HaveOccurred())

		for _, k := range members {
			_, ok := d[k]
			Expect(ok).To(BeTrue(), k)
		}
	})

	It("reports seconds since last registry update", func() {
		Registry.Register("foo", &route.Endpoint{})

		time.Sleep(10 * time.Millisecond)

		timeSince := findValue(Varz, "ms_since_last_registry_update").(float64)
		Expect(timeSince).To(BeNumerically("<", 1000))
		Expect(timeSince).To(BeNumerically(">=", 10))
	})

	It("has urls", func() {
		Expect(findValue(Varz, "urls")).To(Equal(float64(0)))

		var fooReg = route.NewEndpoint("12345", "192.168.1.1", 1234, "", "", map[string]string{}, -1, "", models.ModificationTag{})

		// Add a route
		Registry.Register("foo.vcap.me", fooReg)
		Registry.Register("fooo.vcap.me", fooReg)

		Expect(findValue(Varz, "urls")).To(Equal(float64(2)))
	})

	It("updates bad requests", func() {
		Varz.CaptureBadRequest()
		Expect(findValue(Varz, "bad_requests")).To(Equal(float64(1)))

		Varz.CaptureBadRequest()
		Expect(findValue(Varz, "bad_requests")).To(Equal(float64(2)))
	})

	It("updates bad gateways", func() {
		Varz.CaptureBadGateway()
		Expect(findValue(Varz, "bad_gateways")).To(Equal(float64(1)))

		Varz.CaptureBadGateway()
		Expect(findValue(Varz, "bad_gateways")).To(Equal(float64(2)))
	})

	It("updates requests", func() {
		b := &route.Endpoint{}

		Varz.CaptureRoutingRequest(b)
		Expect(findValue(Varz, "requests")).To(Equal(float64(1)))

		Varz.CaptureRoutingRequest(b)
		Expect(findValue(Varz, "requests")).To(Equal(float64(2)))
	})

	It("updates requests with tags", func() {
		b1 := &route.Endpoint{
			Tags: map[string]string{
				"component": "cc",
			},
		}

		b2 := &route.Endpoint{
			Tags: map[string]string{
				"component": "cc",
			},
		}

		Varz.CaptureRoutingRequest(b1)
		Varz.CaptureRoutingRequest(b2)

		Expect(findValue(Varz, "tags", "component", "cc", "requests")).To(Equal(float64(2)))
	})

	It("updates responses", func() {
		var b *route.Endpoint = &route.Endpoint{}
		var t time.Time
		var d time.Duration

		r1 := http.StatusOK

		r2 := http.StatusNotFound

		Varz.CaptureRoutingResponseLatency(b, r1, t, d)
		Varz.CaptureRoutingResponseLatency(b, r2, t, d)
		Varz.CaptureRoutingResponseLatency(b, r2, t, d)

		Expect(findValue(Varz, "responses_2xx")).To(Equal(float64(1)))
		Expect(findValue(Varz, "responses_4xx")).To(Equal(float64(2)))
	})

	It("update responses with tags", func() {
		var t time.Time
		var d time.Duration

		b1 := &route.Endpoint{
			Tags: map[string]string{
				"component": "cc",
			},
		}

		b2 := &route.Endpoint{
			Tags: map[string]string{
				"component": "cc",
			},
		}

		r1 := http.StatusOK

		r2 := http.StatusNotFound

		Varz.CaptureRoutingResponseLatency(b1, r1, t, d)
		Varz.CaptureRoutingResponseLatency(b2, r2, t, d)
		Varz.CaptureRoutingResponseLatency(b2, r2, t, d)

		Expect(findValue(Varz, "tags", "component", "cc", "responses_2xx")).To(Equal(float64(1)))
		Expect(findValue(Varz, "tags", "component", "cc", "responses_4xx")).To(Equal(float64(2)))
	})

	It("updates response latency", func() {
		var routeEndpoint *route.Endpoint = &route.Endpoint{}
		var startedAt = time.Now()
		var duration = 1 * time.Millisecond

		statusCode := http.StatusOK

		Varz.CaptureRoutingResponseLatency(routeEndpoint, statusCode, startedAt, duration)

		Expect(findValue(Varz, "latency", "50").(float64)).To(Equal(float64(duration) / float64(time.Second)))
		Expect(findValue(Varz, "latency", "75").(float64)).To(Equal(float64(duration) / float64(time.Second)))
		Expect(findValue(Varz, "latency", "90").(float64)).To(Equal(float64(duration) / float64(time.Second)))
		Expect(findValue(Varz, "latency", "95").(float64)).To(Equal(float64(duration) / float64(time.Second)))
		Expect(findValue(Varz, "latency", "99").(float64)).To(Equal(float64(duration) / float64(time.Second)))
	})
})

// Extract value using key(s) from JSON data
// For example, when extracting value from
//       {
//         "foo": { "bar" : 1 },
//         "foobar": 2,
//        }
// findValue(Varz,"foo", "bar") returns 1
// findValue(Varz,"foobar") returns 2
func findValue(varz Varz, x ...string) interface{} {
	var z interface{}
	var ok bool

	b, err := json.Marshal(varz)
	Expect(err).ToNot(HaveOccurred())

	y := make(map[string]interface{})
	err = json.Unmarshal(b, &y)
	Expect(err).ToNot(HaveOccurred())
	z = y

	for _, e := range x {
		u := z.(map[string]interface{})
		z, ok = u[e]
		Expect(ok).To(BeTrue(), fmt.Sprintf("no key: %s", e))
	}

	return z
}


text:
Access object and array properties using dot path

##Usage
```js
var dot = require('dot-obj-arr');

var temp = {
  one: 'first',
  two: [
    'one',
    { one: 'second first' }
  ]
}

dot(temp, 'two.[1].one') // second first
```

##Install
```
npm install temp-name-here/dot-obj-arr
```