text:
module.exports = function (chai, utils) {

    var setContainsFlag = function () {
        utils.flag(this,'contains',true);
    };

    utils.addProperty(chai.Assertion.prototype, "comprise", setContainsFlag);
    utils.addProperty(chai.Assertion.prototype, "comprised", setContainsFlag);
};

redpajama_set_name: RedPajamaGithub


text:
#ifndef _LOCALCHARSET_H
#define _LOCALCHARSET_H

#ifdef LIBCHARSET_STATIC
#define LIBCHARSET_DLL_EXPORTED
#else /* LIBCHARSET_STATIC */
#ifdef BUILDING_LIBCHARSET
#define LIBCHARSET_DLL_EXPORTED __declspec(dllexport)
#else
#define LIBCHARSET_DLL_EXPORTED __declspec(dllimport)
#endif
#endif /* LIBCHARSET_STATIC */

#ifdef __cplusplus
extern "C" {
#endif

/* Determine the current locale's character encoding, and canonicalize it
   into one of the canonical names listed in config.charset.
   The result must not be freed; it is statically allocated.
   If the canonical name cannot be determined, the result is a non-canonical
   name.  */
extern LIBCHARSET_DLL_EXPORTED const char * locale_charset (void);

#ifdef __cplusplus
}
#endif

#endif /* _LOCALCHARSET_H */


text:
package is.hail.types.physical

import is.hail.annotations.{Region, UnsafeOrdering, _}
import is.hail.asm4s.{Code, _}
import is.hail.expr.ir.EmitMethodBuilder
import is.hail.types.virtual.TBoolean

case object PBooleanOptional extends PBoolean(false)
case object PBooleanRequired extends PBoolean(true)

class PBoolean(override val required: Boolean) extends PType with PPrimitive {
  lazy val virtualType: TBoolean.type  = TBoolean

  def _asIdent = "bool"

  override def _pretty(sb: StringBuilder, indent: Int, compact: Boolean): Unit = sb.append("PBoolean")

  override def unsafeOrdering(): UnsafeOrdering = new UnsafeOrdering {
    def compare(o1: Long, o2: Long): Int = {
      java.lang.Boolean.compare(Region.loadBoolean(o1), Region.loadBoolean(o2))
    }
  }

  def codeOrdering(mb: EmitMethodBuilder[_], other: PType): CodeOrdering = {
    assert(other isOfType this)
    new CodeOrderingCompareConsistentWithOthers {
      type T = Boolean

      def compareNonnull(x: Code[T], y: Code[T]): Code[Int] =
        Code.invokeStatic2[java.lang.Boolean, Boolean, Boolean, Int]("compare", x, y)
    }
  }

  override def byteSize: Long = 1

  def storePrimitiveAtAddress(addr: Code[Long], srcPType: PType, value: Code[_]): Code[Unit] =
    Region.storeBoolean(addr, coerce[Boolean](value))
}

object PBoolean {
  def apply(required: Boolean = false): PBoolean = if (required) PBooleanRequired else PBooleanOptional

  def unapply(t: PBoolean): Option[Boolean] = Option(t.required)
}


text:
#include "config.h"
#include "FontCache.h"

#include "Font.h"
#include "FontDescription.h"
#include "FontPlatformData.h"
#include "NotImplemented.h"
#include "SimpleFontData.h"

#include "SkPaint.h"
#include "SkTypeface_android.h"
#include "SkUtils.h"

#include <unicode/locid.h>
#include <wtf/Assertions.h>
#include <wtf/text/AtomicString.h>
#include <wtf/text/CString.h>

namespace WebCore {

static const char* getFallbackFontName(const FontDescription& fontDescription)
{
    switch (fontDescription.genericFamily()) {
    case FontDescription::StandardFamily:
    case FontDescription::SerifFamily:
        return "serif";
    case FontDescription::SansSerifFamily:
        return "sans-serif";
    case FontDescription::MonospaceFamily:
        return "monospace";
    case FontDescription::CursiveFamily:
        return "cursive";
    case FontDescription::FantasyFamily:
        return "fantasy";
    case FontDescription::NoFamily:
    default:
        return "";
    }
}

static bool isFallbackFamily(String family)
{
    return family.startsWith("-webkit-")
        || equalIgnoringCase(family, "serif")
        || equalIgnoringCase(family, "sans-serif")
        || equalIgnoringCase(family, "sans")
        || equalIgnoringCase(family, "monospace")
        || equalIgnoringCase(family, "cursive")
        || equalIgnoringCase(family, "fantasy")
        || equalIgnoringCase(family, "times") // Skia aliases for serif
        || equalIgnoringCase(family, "times new roman")
        || equalIgnoringCase(family, "palatino")
        || equalIgnoringCase(family, "georgia")
        || equalIgnoringCase(family, "baskerville")
        || equalIgnoringCase(family, "goudy")
        || equalIgnoringCase(family, "ITC Stone Serif")
        || equalIgnoringCase(family, "arial") // Skia aliases for sans-serif
        || equalIgnoringCase(family, "helvetica")
        || equalIgnoringCase(family, "tahoma")
        || equalIgnoringCase(family, "verdana")
        || equalIgnoringCase(family, "courier") // Skia aliases for monospace
        || equalIgnoringCase(family, "courier new")
        || equalIgnoringCase(family, "monaco");
}

void FontCache::platformInit()
{
}

PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacters(const Font& font, const UChar* characters, int length)
{
    if (!length)
        return 0;

    SkUnichar skiaChar;
    if (U16_IS_LEAD(characters[0])) {
        ASSERT(length >= 2);
        skiaChar = U16_GET_SUPPLEMENTARY(characters[0], characters[1]);
    } else
        skiaChar = characters[0];

    SkString skiaFamilyName;
    if (!SkGetFallbackFamilyNameForChar(skiaChar, &skiaFamilyName) || skiaFamilyName.isEmpty())
        return 0;
    return getCachedFontData(getCachedFontPlatformData(font.fontDescription(), AtomicString(skiaFamilyName.c_str()), DoNotRetain), DoNotRetain);
}

PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
{
    return 0;
}

PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& description, ShouldRetain shouldRetain)
{
    DEFINE_STATIC_LOCAL(const AtomicString, serif, ("Serif"));
    DEFINE_STATIC_LOCAL(const AtomicString, monospace, ("Monospace"));
    DEFINE_STATIC_LOCAL(const AtomicString, sans, ("Sans"));

    FontPlatformData* fontPlatformData = 0;
    switch (description.genericFamily()) {
    case FontDescription::SerifFamily:
        fontPlatformData = getCachedFontPlatformData(description, serif);
        break;
    case FontDescription::MonospaceFamily:
        fontPlatformData = getCachedFontPlatformData(description, monospace);
        break;
    case FontDescription::SansSerifFamily:
    default:
        fontPlatformData = getCachedFontPlatformData(description, sans);
        break;
    }

    ASSERT(fontPlatformData);
    return getCachedFontData(fontPlatformData, shouldRetain);
}

void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
{
    notImplemented();
}

FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
{
    const char* name = 0;
    CString nameString; // Keeps name valid within scope of this function in case that name is from a family.

    // If a fallback font is being created (e.g. "-webkit-monospace"), convert
    // it in to the fallback name (e.g. "monospace").
    if (!family.length() || family.startsWith("-webkit-"))
        name = getFallbackFontName(fontDescription);
    else {
        nameString = family.string().utf8();
        name = nameString.data();
    }

    int style = SkTypeface::kNormal;
    if (fontDescription.weight() >= FontWeightBold)
        style |= SkTypeface::kBold;
    if (fontDescription.italic())
        style |= SkTypeface::kItalic;

    SkTypeface* typeface = 0;
    FontPlatformData* result = 0;
    FallbackScripts fallbackScript = SkGetFallbackScriptFromID(name);
    if (SkTypeface_ValidScript(fallbackScript)) {
        typeface = SkCreateTypefaceForScript(fallbackScript);
        if (typeface)
            result = new FontPlatformData(typeface, name, fontDescription.computedSize(),
                                          (style & SkTypeface::kBold) && !typeface->isBold(),
                                          (style & SkTypeface::kItalic) && !typeface->isItalic(),
                                          fontDescription.orientation(),
                                          fontDescription.textOrientation());
    } else {
        typeface = SkTypeface::CreateFromName(name, SkTypeface::kNormal);

        // CreateFromName always returns a typeface, falling back to a default font
        // if the one requested could not be found. Calling Equal() with a null
        // pointer will compare the returned font against the default, with the
        // caveat that the default is always of normal style. When that happens,
        // ignore the default font and allow WebCore to provide the next font on the
        // CSS fallback list. The only exception to this occurs when the family name
        // is a commonly used generic family, which is the case when called by
        // getSimilarFontPlatformData() or getLastResortFallbackFont(). In that case
        // the default font is an acceptable result.

        if (!SkTypeface::Equal(typeface, 0) || isFallbackFamily(family.string())) {
            // We had to use normal styling to see if this was a default font. If
            // we need bold or italic, replace with the corrected typeface.
            if (style != SkTypeface::kNormal) {
                typeface->unref();
                typeface = SkTypeface::CreateFromName(name, static_cast<SkTypeface::Style>(style));
            }
            result = new FontPlatformData(typeface, name, fontDescription.computedSize(),
                                          (style & SkTypeface::kBold) && !typeface->isBold(),
                                          (style & SkTypeface::kItalic) && !typeface->isItalic(),
                                          fontDescription.orientation(),
                                          fontDescription.textOrientation());
        }
    }

    SkSafeUnref(typeface);
    return result;
}

} // namespace WebCore


text:
<?php

declare(strict_types=1);

namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ODM\MongoDB\Id\UuidGenerator;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Tests\BaseTest;

class GH1525Test extends BaseTest
{
    public function testEmbedCloneTwoFlushesPerDocument(): void
    {
        $embedded = new GH1525Embedded('embedded');

        $embedMany = new GH1525Embedded('embedMany');

        for ($i = 0; $i < 2; ++$i) {
            $parent = new GH1525Document('test' . $i);
            $this->dm->persist($parent);
            $this->dm->flush();

            $parent->embedded = $embedded;
            $parent->embedMany->add($embedMany);
            $this->dm->flush();
        }

        $this->dm->clear();

        for ($i = 0; $i < 2; ++$i) {
            $test = $this->dm->getRepository(GH1525Document::class)->findOneBy(['name' => 'test' . $i]);

            self::assertInstanceOf(GH1525Document::class, $test);

            self::assertInstanceOf(GH1525Embedded::class, $test->embedded);
            self::assertSame($test->embedded->name, $embedded->name);

            self::assertCount(1, $test->embedMany);
            self::assertInstanceOf(GH1525Embedded::class, $test->embedMany[0]);
            self::assertSame($test->embedMany[0]->name, $embedMany->name);
        }
    }

    public function testEmbedCloneWithIdStrategyNoneOnParentAndEarlyPersist(): void
    {
        $uuidGen  = new UuidGenerator();
        $embedded = new GH1525Embedded('embedded');

        $count = 2;
        for ($i = 0; $i < $count; ++$i) {
            $parent = new GH1525DocumentIdStrategyNone($uuidGen->generateV4(), 'test' . $i);
            $this->dm->persist($parent);
            $parent->embedded = $embedded;
            $this->dm->flush();
        }

        $this->dm->clear();

        for ($i = 0; $i < $count; ++$i) {
            $test = $this->dm->getRepository(GH1525DocumentIdStrategyNone::class)->findOneBy(['name' => 'test' . $i]);

            self::assertInstanceOf(GH1525DocumentIdStrategyNone::class, $test);

            self::assertInstanceOf(GH1525Embedded::class, $test->embedded);
            self::assertSame($test->embedded->name, $embedded->name);
        }
    }

    public function testEmbedCloneWithIdStrategyNoneOnParentAndLatePersist(): void
    {
        $uuidGen  = new UuidGenerator();
        $embedded = new GH1525Embedded('embedded');

        $count = 2;
        for ($i = 0; $i < $count; ++$i) {
            $parent           = new GH1525DocumentIdStrategyNone($uuidGen->generateV4(), 'test' . $i);
            $parent->embedded = $embedded;
            $this->dm->persist($parent);
            $this->dm->flush();
        }

        $this->dm->clear();

        for ($i = 0; $i < $count; ++$i) {
            $test = $this->dm->getRepository(GH1525DocumentIdStrategyNone::class)->findOneBy(['name' => 'test' . $i]);

            self::assertInstanceOf(GH1525DocumentIdStrategyNone::class, $test);

            self::assertInstanceOf(GH1525Embedded::class, $test->embedded);
            self::assertSame($test->embedded->name, $embedded->name);
        }
    }
}

/** @ODM\Document(collection="document_test") */
class GH1525Document
{
    /**
     * @ODM\Id
     *
     * @var string|null
     */
    public $id;

    /**
     * @ODM\Field(type="string")
     *
     * @var string
     */
    public $name;

    /**
     * @ODM\EmbedOne(targetDocument=GH1525Embedded::class)
     *
     * @var GH1525Embedded|null
     */
    public $embedded;

    /**
     * @ODM\EmbedMany(targetDocument=GH1525Embedded::class)
     *
     * @var Collection<int, GH1525Embedded>
     */
    public $embedMany;

    public function __construct(string $name)
    {
        $this->name      = $name;
        $this->embedMany = new ArrayCollection();
    }
}

/** @ODM\Document(collection="document_test_with_auto_ids") */
class GH1525DocumentIdStrategyNone
{
    /**
     * @ODM\Id(strategy="NONE")
     *
     * @var string
     */
    public $id;

    /**
     * @ODM\Field(type="string")
     *
     * @var string
     */
    public $name;

    /**
     * @ODM\EmbedOne(targetDocument=GH1525Embedded::class)
     *
     * @var GH1525Embedded|null
     */
    public $embedded;

    public function __construct(string $id, string $name)
    {
        $this->id   = $id;
        $this->name = $name;
    }
}

/** @ODM\EmbeddedDocument */
class GH1525Embedded
{
    /**
     * @ODM\Field(type="string")
     *
     * @var string
     */
    public $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }
}


text:
package org.acme.bar;

/**
 * @version $Revision$ $Date$
 */
@java.lang.annotation.Target(value = {java.lang.annotation.ElementType.PARAMETER})
@java.lang.annotation.Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
public @interface Optional {
}


text:
.. _ch-refs:

************************
References and Citations
************************

You can reference a section by its label. This chapter is
Chapter |nbsp| :ref:`ch-refs`.

.. _sec-refs-sub1:

Subsection
==========

This subsection is Section |nbsp| :ref:`sec-refs-sub1`.

Citations
=========

COLLADA |nbsp| :cite:p:`collada` is a cool 3D file format. I wrote a paper about
3D stuff |nbsp| :cite:p:`icmepaper`. The website we built is running |nbsp|
:cite:p:`open3dhub`. The bibliography is in bibtex format.

Footnotes
=========

Reference a footnote |nbsp| [#foot-something]_.

External Links
==============

You can link to a `website <http://google.com/>`_.

.. rubric:: Footnotes

.. [#foot-something] This is a footnote at the end of the page or document.


text:
Provides jobs  from RabbitMQ

## Usage

```
 jobs from rabbibmq

Usage:
  ferrariworker process rabbit [flags]

Flags:
      --consumer-auto-ack               Consumer Auto ACK
      --consumer-no-local               Consumer no local
      --consumer-no-wait                Consumer no wait
      --consumer-tag string             Consumer tag
      --exchange string                 Exchange name. If exchange name is empty all other exchange flags are ignored
      --exchange-delete-when-complete   Exchange delete when complete
      --exchange-durable                Exchange durable (default true)
      --exchange-internal               Exchange internal
      --exchange-no-wait                Exchange no wait
      --exchange-type string            Exchange type - direct|fanout|topic|x-custom (default "direct")
      --queue-delete-when-used          Queue delete queue when used
      --queue-durable                   Queue durable
      --queue-exclusive                 Queue exclusive
      --queue-name string               Rabbit queue name
      --queue-no-wait                   Queue no wait
      --uri string                      Rabbit instance uri e.g. amqp://guest:guest@localhost:5672/ (default "amqp://guest:guest@localhost:5672/")

Global Flags:
      --command string            Command to be run when a new job arrives  (default "echo \"You should  set your own command :)\"")
      --command-run-path string   Running path for the command (default ".")
      --config string             config file (default is $HOME/.ferrariworker.yaml)
      --max-concurrency int       Max number of jobs proccessed concurrently. (default 1)
      --wait-timeout int          Time to wait in milliseconds for existing jobs to be processed.  (default 200)
```


text:
<?php

namespace App\Http\Controllers;

use App\Models\News;
use App\Models\Anime;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class AdminController extends Controller {

	/**
	 * Shows the administration dashboard.
	 *
	 * @return View
	 */
	public function index() {
		return view('admin.index');
	}

	public function config() {
		return view('admin.config');
	}
}


text:
/sbin/chkconfig --level 0123456 cups off

#
# Stop cups if currently running
#
/sbin/service cups stop


text:
class Account
  attr_reader :name, :balance
  def initialize(name, balance=100)
    @name = name
    @balance = balance
  end

  def display_balance(pin_number)
    puts pin_number == pin ? "Balance: $#{@balance}." : pin_error
  end

  def withdraw(pin_number, amount)
    if pin_number == pin
      @balance -= amount
      puts "Withdrew #{amount}. New balance: $#{@balance}."
    else
      puts pin_error
    end
  end

  private

  def pin
    @pin = 1234
  end

  def pin_error
    "Access denied: incorrect PIN."
  end
end

my_account = Account.new("Eric", 1_000_000)
my_account.withdraw(11, 500_000)
my_account.display_balance(1234)
my_account.withdraw(1234, 500_000)
my_account.display_balance(1234)


text:
<!doctype html>
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<html>
<head>
  <meta charset="UTF-8">
  <title>dnd-dice-result tests</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

  <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
  <script src="../../web-component-tester/browser.js"></script>

  <link rel="import" href="../dnd-dice-result.html">

</head>
<body>

  <test-fixture id="dndDiceResult">
    <template>
      <dnd-dice-result></dnd-dice-result>
    </template>
  </test-fixture>

  <test-fixture id="dndDiceResultWithSpec">
    <template>
      <dnd-dice-result spec="3d6"></dnd-dice-result>
    </template>
  </test-fixture>

  <test-fixture id="dndDiceResultNoInput">
    <template>
      <dnd-dice-result hide-input></dnd-dice-result>
    </template>
  </test-fixture>

  <script>
    suite('Basic dnd-dice-result tests', function() {
      var result;

      setup(function() {
        result = fixture('dndDiceResult');
      });

      test('Spec starts out blank', function() {
        expect(result.getValidSpec()).to.equal(undefined);
        result.roll();
        expect(result.$.button.innerText).to.equal('\u00a0');
      });

      test('Setting spec property rolls', function() {
        result.spec = '1d4';
        expect(result.getValidSpec()).to.equal('1d4');
        expect(result.$.button.innerText).to.not.equal('');
      });

      test('Setting spec twice does not roll', function() {
        result.spec = '1d4';
        expect(result.$.button.innerText).to.not.equal('');

        // Change the inner text of the button to make sure that spec=...
        // will really not change the text.  Must use upper case text since
        // the paper-button uses a text filter that converts to that case.
        result.$.button.innerText = 'NO-RESULT';
        result.spec = '1d4';
        expect(result.$.button.innerText).to.equal('NO-RESULT');
      });

      test('Setting different spec always rolls', function() {
        result.spec = '1d4';
        var previousValue = result.$.button.innerText;
        expect(previousValue).to.not.equal('');

        for (var i = 4; i < 100; i += 4) {
          result.spec = '1d4+' + i;
          expect(result.$.button.innerText).to.not.equal(previousValue);
          previousValue = result.$.button.innerText;
        }
      });

      test('setSpec always rolls', function() {
        result.setSpec('99d100');
        expect(result.$.button.innerText).to.not.equal('');

        for (var i = 0; i < 100; i += 4) {
          // Change the inner text of the button to make sure that setSpec()
          // will really change the text.  Must use upper case text since
          // the paper-button uses a text filter that converts to that case.
          result.$.button.innerText = 'NO-RESULT';
          result.setSpec('99d100');
          expect(result.$.button.innerText).to.not.equal('NO-RESULT');
        }
      });

      test('Inc and dec change spec', function() {
        // If spec is undefined, it stays undefined.
        result.inc();
        expect(result.getValidSpec()).to.equal(undefined);

        result.spec = '1d4';
        expect(result.getValidSpec()).to.equal('1d4');
        result.inc();
        expect(result.getValidSpec()).to.equal('1d4+1');
        result.dec();
        expect(result.getValidSpec()).to.equal('1d4');
        result.dec();
        expect(result.getValidSpec()).to.equal('1d4-1');
      });
    });

    suite('dnd-dice-result spec', function() {
      var result;

      setup(function() {
        result = fixture('dndDiceResultWithSpec');
      });

      test('Spec set in html', function() {
        expect(result.getValidSpec()).to.equal('3d6');
      });
    });

    suite('dnd-dice-result no input', function() {
      var result;

      setup(function() {
        result = fixture('dndDiceResultNoInput');
      });

      test('Input field is not visible', function() {
        expect(result.$.input).to.equal(undefined);
      });
    });
  </script>
</body>
</html>


text:
using System;
using ExcelAbstraction.Entities;
using ExcelAbstraction.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ExcelAbstraction.NPOI.Tests
{
	[TestClass]
	public class NpoiMemoryXlsxTests : ExcelServiceMemoryTests
	{
		public NpoiMemoryXlsxTests() : base(new ExcelService(), ExcelVersion.Xlsx) { }

		[TestInitialize]
		public override void TestInitialize()
		{
			base.TestInitialize();
		}

		[TestCleanup]
		public override void TestCleanup()
		{
			base.TestCleanup();
		}

		[TestMethod]
		public override void ExcelService_AddValidations()
		{
			base.ExcelService_AddValidations();
		}

		[TestMethod]
		public override void ExcelService_AddValidations_Hack()
		{
			base.ExcelService_AddValidations_Hack();
		}

		[TestMethod, ExpectedException(typeof(InvalidOperationException))]
		public override void ExcelService_AddValidations_EmptyListThrows()
		{
			base.ExcelService_AddValidations_EmptyListThrows();
		}

		[TestMethod, ExpectedException(typeof(InvalidOperationException))]
		public override void ExcelService_AddValidations_NullListThrows()
		{
			base.ExcelService_AddValidations_NullListThrows();
		}

		[TestMethod]
		public override void ExcelService_Worksheet_IsHidden()
		{
			base.ExcelService_Worksheet_IsHidden();
		}

		[TestMethod]
		public override void ExcelService_AddValidations_LotsOfItems()
		{
			base.ExcelService_AddValidations_LotsOfItems();
		}
	}
}


text:
using System;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
using umbraco.cms.businesslogic.template;
using System.Collections.Generic;

namespace Umbraco.Web.Mvc
{
    public class RenderRouteHandler : IRouteHandler
    {
        // Define reserved dictionary keys for controller, action and area specified in route additional values data
        private static class ReservedAdditionalKeys
        {
            internal const string Controller = "c";
            internal const string Action = "a";
            internal const string Area = "ar";
        }

        public RenderRouteHandler(IControllerFactory controllerFactory)
        {
            if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
            _controllerFactory = controllerFactory;
        }

        /// <summary>
        /// Contructor generally used for unit testing
        /// </summary>
        /// <param name="controllerFactory"></param>
        /// <param name="umbracoContext"></param>
        internal RenderRouteHandler(IControllerFactory controllerFactory, UmbracoContext umbracoContext)
        {
            if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
            if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
            _controllerFactory = controllerFactory;
            _umbracoContext = umbracoContext;
        }

        private readonly IControllerFactory _controllerFactory;
        private readonly UmbracoContext _umbracoContext;

        /// <summary>
        /// Returns the current UmbracoContext
        /// </summary>
        public UmbracoContext UmbracoContext
        {
            get { return _umbracoContext ?? UmbracoContext.Current; }
        }

        #region IRouteHandler Members

        /// <summary>
        /// Assigns the correct controller based on the Umbraco request and returns a standard MvcHandler to prcess the response,
        /// this also stores the render model into the data tokens for the current RouteData.
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (UmbracoContext == null)
            {
                throw new NullReferenceException("There is not current UmbracoContext, it must be initialized before the RenderRouteHandler executes");
            }
            var docRequest = UmbracoContext.PublishedContentRequest;
            if (docRequest == null)
            {
                throw new NullReferenceException("There is not current PublishedContentRequest, it must be initialized before the RenderRouteHandler executes");
            }

            SetupRouteDataForRequest(
                new RenderModel(docRequest.PublishedContent, docRequest.Culture),
                requestContext,
                docRequest);

            return GetHandlerForRoute(requestContext, docRequest);

        }

        #endregion

        /// <summary>
        /// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
        /// </summary>
        /// <param name="renderModel"></param>
        /// <param name="requestContext"></param>
        /// <param name="docRequest"></param>
        internal void SetupRouteDataForRequest(RenderModel renderModel, RequestContext requestContext, PublishedContentRequest docRequest)
        {
            //put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
            requestContext.RouteData.DataTokens.Add("umbraco", renderModel); //required for the RenderModelBinder and view engine
            requestContext.RouteData.DataTokens.Add("umbraco-doc-request", docRequest); //required for RenderMvcController
            requestContext.RouteData.DataTokens.Add("umbraco-context", UmbracoContext); //required for UmbracoTemplatePage
        }

        private void UpdateRouteDataForRequest(RenderModel renderModel, RequestContext requestContext)
        {
            if (renderModel == null) throw new ArgumentNullException("renderModel");
            if (requestContext == null) throw new ArgumentNullException("requestContext");

            requestContext.RouteData.DataTokens["umbraco"] = renderModel;
            // the rest should not change -- it's only the published content that has changed
        }

        /// <summary>
        /// Checks the request and query strings to see if it matches the definition of having a Surface controller
        /// posted/get value, if so, then we return a PostedDataProxyInfo object with the correct information.
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        private static PostedDataProxyInfo GetFormInfo(RequestContext requestContext)
        {
            if (requestContext == null) throw new ArgumentNullException("requestContext");

            //if it is a POST/GET then a value must be in the request
            if (requestContext.HttpContext.Request.QueryString["ufprt"].IsNullOrWhiteSpace()
                && requestContext.HttpContext.Request.Form["ufprt"].IsNullOrWhiteSpace())
            {
                return null;
            }

            string encodedVal;

            switch (requestContext.HttpContext.Request.RequestType)
            {
                case "POST":
                    //get the value from the request.
                    //this field will contain an encrypted version of the surface route vals.
                    encodedVal = requestContext.HttpContext.Request.Form["ufprt"];
                    break;
                case "GET":
                    //this field will contain an encrypted version of the surface route vals.
                    encodedVal = requestContext.HttpContext.Request.QueryString["ufprt"];
                    break;
                default:
                    return null;
            }

            string decryptedString;
            try
            {
                decryptedString = encodedVal.DecryptWithMachineKey();
            }
            catch (FormatException)
            {
                LogHelper.Warn<RenderRouteHandler>("A value was detected in the ufprt parameter but Umbraco could not decrypt the string");
                return null;
            }

            var parsedQueryString = HttpUtility.ParseQueryString(decryptedString);
            var decodedParts = new Dictionary<string, string>();

            foreach (var key in parsedQueryString.AllKeys)
            {
                decodedParts[key] = parsedQueryString[key];
            }

            //validate all required keys exist

            //the controller
            if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Controller))
                return null;
            //the action
            if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Action))
                return null;
            //the area
            if (decodedParts.All(x => x.Key != ReservedAdditionalKeys.Area))
                return null;

            foreach (var item in decodedParts.Where(x => new[] {
			    ReservedAdditionalKeys.Controller,
			    ReservedAdditionalKeys.Action,
			    ReservedAdditionalKeys.Area }.Contains(x.Key) == false))
            {
                // Populate route with additional values which aren't reserved values so they eventually to action parameters
                requestContext.RouteData.Values[item.Key] = item.Value;
            }

            //return the proxy info without the surface id... could be a local controller.
            return new PostedDataProxyInfo
            {
                ControllerName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value),
                ActionName = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value),
                Area = HttpUtility.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value),
            };
        }

        /// <summary>
        /// Handles a posted form to an Umbraco Url and ensures the correct controller is routed to and that
        /// the right DataTokens are set.
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="postedInfo"></param>
        private IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo)
        {
            if (requestContext == null) throw new ArgumentNullException("requestContext");
            if (postedInfo == null) throw new ArgumentNullException("postedInfo");

            //set the standard route values/tokens
            requestContext.RouteData.Values["controller"] = postedInfo.ControllerName;
            requestContext.RouteData.Values["action"] = postedInfo.ActionName;

            IHttpHandler handler;

            //get the route from the defined routes
            using (RouteTable.Routes.GetReadLock())
            {
                Route surfaceRoute;
                if (postedInfo.Area.IsNullOrWhiteSpace())
                {
                    //find the controller in the route table without an area
                    var surfaceRoutes = RouteTable.Routes.OfType<Route>()
                                                  .Where(x => x.Defaults != null &&
                                                              x.Defaults.ContainsKey("controller") &&
                                                              x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
                                                              x.DataTokens.ContainsKey("area") == false).ToList();

                    // If more than one route is found, find one with a matching action
                    if (surfaceRoutes.Count() > 1)
                    {
                        surfaceRoute = surfaceRoutes.SingleOrDefault(x =>
                                        x.Defaults["action"].ToString().InvariantEquals(postedInfo.ActionName));
                    }
                    else
                    {
                        surfaceRoute = surfaceRoutes.SingleOrDefault();
                    }

                }
                else
                {
                    //find the controller in the route table with the specified area
                    surfaceRoute = RouteTable.Routes.OfType<Route>()
                                             .SingleOrDefault(x => x.Defaults != null &&
                                                                   x.Defaults.ContainsKey("controller") &&
                                                                   x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
                                                                   x.DataTokens.ContainsKey("area") &&
                                                                   x.DataTokens["area"].ToString().InvariantEquals(postedInfo.Area));
                }

                if (surfaceRoute == null)
                    throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName);

                //set the area if one is there.
                if (surfaceRoute.DataTokens.ContainsKey("area"))
                {
                    requestContext.RouteData.DataTokens["area"] = surfaceRoute.DataTokens["area"];
                }

                //set the 'Namespaces' token so the controller factory knows where to look to construct it
                if (surfaceRoute.DataTokens.ContainsKey("Namespaces"))
                {
                    requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"];
                }
                handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext);

            }

            return handler;
        }

        /// <summary>
        /// Returns a RouteDefinition object based on the current renderModel
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="publishedContentRequest"></param>
        /// <returns></returns>
        internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
        {
            if (requestContext == null) throw new ArgumentNullException("requestContext");
            if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");

            var defaultControllerType = DefaultRenderMvcControllerResolver.Current.GetDefaultControllerType();
            var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType);
            //creates the default route definition which maps to the 'UmbracoController' controller
            var def = new RouteDefinition
                {
                    ControllerName = defaultControllerName,
                    ControllerType = defaultControllerType,
                    PublishedContentRequest = publishedContentRequest,
                    ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(),
                    HasHijackedRoute = false
                };

            //check that a template is defined), if it doesn't and there is a hijacked route it will just route
            // to the index Action
            if (publishedContentRequest.HasTemplate)
            {
                //the template Alias should always be already saved with a safe name.
                //if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed
                // with the action name attribute.
                var templateName = publishedContentRequest.TemplateAlias.Split('.')[0].ToSafeAlias();
                def.ActionName = templateName;
            }

            //check if there's a custom controller assigned, base on the document type alias.
            var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias);

            //check if that controller exists
            if (controllerType != null)
            {
                //ensure the controller is of type 'IRenderMvcController' and ControllerBase
                if (TypeHelper.IsTypeAssignableFrom<IRenderMvcController>(controllerType)
                    && TypeHelper.IsTypeAssignableFrom<ControllerBase>(controllerType))
                {
                    //set the controller and name to the custom one
                    def.ControllerType = controllerType;
                    def.ControllerName = ControllerExtensions.GetControllerName(controllerType);
                    if (def.ControllerName != defaultControllerName)
                    {
                        def.HasHijackedRoute = true;
                    }
                }
                else
                {
                    LogHelper.Warn<RenderRouteHandler>(
                        "The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must implement '{2}' and inherit from '{3}'.",
                        () => publishedContentRequest.PublishedContent.DocumentTypeAlias,
                        () => controllerType.FullName,
                        () => typeof(IRenderMvcController).FullName,
                        () => typeof(ControllerBase).FullName);

                    //we cannot route to this custom controller since it is not of the correct type so we'll continue with the defaults
                    // that have already been set above.
                }
            }

            //store the route definition
            requestContext.RouteData.DataTokens["umbraco-route-def"] = def;

            return def;
        }

        internal IHttpHandler GetHandlerOnMissingTemplate(PublishedContentRequest pcr)
        {
            if (pcr == null) throw new ArgumentNullException("pcr");

            // missing template, so we're in a 404 here
            // so the content, if any, is a custom 404 page of some sort

            if (!pcr.HasPublishedContent)
                // means the builder could not find a proper document to handle 404
                return new PublishedContentNotFoundHandler();

            if (!pcr.HasTemplate)
                // means the engine could find a proper document, but the document has no template
                // at that point there isn't much we can do and there is no point returning
                // to Mvc since Mvc can't do much
                return new PublishedContentNotFoundHandler("In addition, no template exists to render the custom 404.");

            // so we have a template, so we should have a rendering engine
            if (pcr.RenderingEngine == RenderingEngine.WebForms) // back to webforms ?
                return GetWebFormsHandler();

            if (pcr.RenderingEngine != RenderingEngine.Mvc) // else ?
                return new PublishedContentNotFoundHandler("In addition, no rendering engine exists to render the custom 404.");

            return null;
        }

        /// <summary>
        /// this will determine the controller and set the values in the route data
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="publishedContentRequest"></param>
        internal IHttpHandler GetHandlerForRoute(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
        {
            if (requestContext == null) throw new ArgumentNullException("requestContext");
            if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest");

            var routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);

            //Need to check for a special case if there is form data being posted back to an Umbraco URL
            var postedInfo = GetFormInfo(requestContext);
            if (postedInfo != null)
            {
                return HandlePostedValues(requestContext, postedInfo);
            }

            //Now we can check if we are supposed to render WebForms when the route has not been hijacked
            if (publishedContentRequest.RenderingEngine == RenderingEngine.WebForms
                && publishedContentRequest.HasTemplate
                && routeDef.HasHijackedRoute == false)
            {
                return GetWebFormsHandler();
            }

            //here we need to check if there is no hijacked route and no template assigned, if this is the case
            //we want to return a blank page, but we'll leave that up to the NoTemplateHandler.
            if (!publishedContentRequest.HasTemplate && !routeDef.HasHijackedRoute)
            {
                publishedContentRequest.UpdateOnMissingTemplate(); // will go 404

                // HandleHttpResponseStatus returns a value indicating that the request should
                // not be processed any further, eg because it has been redirect. then, exit.
                if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, publishedContentRequest))
                    return null;

                var handler = GetHandlerOnMissingTemplate(publishedContentRequest);

                // if it's not null it can be either the PublishedContentNotFoundHandler (no document was
                // found to handle 404, or document with no template was found) or the WebForms handler
                // (a document was found and its template is WebForms)

                // if it's null it means that a document was found and its template is Mvc

                // if we have a handler, return now
                if (handler != null)
                    return handler;

                // else we are running Mvc
                // update the route data - because the PublishedContent has changed
                UpdateRouteDataForRequest(
                    new RenderModel(publishedContentRequest.PublishedContent, publishedContentRequest.Culture),
                    requestContext);
                // update the route definition
                routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
            }

            //no post values, just route to the controller/action requried (local)

            requestContext.RouteData.Values["controller"] = routeDef.ControllerName;
            if (!string.IsNullOrWhiteSpace(routeDef.ActionName))
            {
                requestContext.RouteData.Values["action"] = routeDef.ActionName;
            }

            // Set the session state requirements
            requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext, routeDef.ControllerName));

            // reset the friendly path so in the controllers and anything occuring after this point in time,
            //the URL is reset back to the original request.
            requestContext.HttpContext.RewritePath(UmbracoContext.OriginalRequestUrl.PathAndQuery);

            return new UmbracoMvcHandler(requestContext);
        }

        /// <summary>
        /// Returns the handler for webforms requests
        /// </summary>
        /// <returns></returns>
        internal static IHttpHandler GetWebFormsHandler()
        {
            return (global::umbraco.UmbracoDefault)BuildManager.CreateInstanceFromVirtualPath("~/default.aspx", typeof(global::umbraco.UmbracoDefault));
        }

        private SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext, string controllerName)
        {
            return _controllerFactory.GetControllerSessionBehavior(requestContext, controllerName);
        }

    }
}


text:
python manage.py migrate

exec $@