text:
using ceenq.com.AppRoutingServer.ConfigEventHandlers;
using ceenq.com.Core.Applications;
using ceenq.com.RoutingServer.Configuration;
using Moq;
using NUnit.Framework;

namespace ceenq.com.Tests.AppRoutingServer.ConfigEventHandlers
{
    [TestFixture]
    public class RedirectToWwwServerBlockCreationHandlerTests
    {
        [Test]
        public void ShouldCreateServerBlockIfAppHasCustomDomain()
        {
            var application = new Mock<IApplication>();
            application.SetupGet(a => a.Domain).Returns("www.customdomain.com");
            var configContext = new ConfigContext(new Config(), application.Object);

            var handler = new RedirectToWwwServerBlockCreationHandler();
            handler.AddServerBlock(configContext);

            Assert.That(configContext.Config.ServerBlock.Count == 1, "This test expected that 1 server blocks would have been created.");
        }
        [Test]
        public void ShouldCreateReturnValueIfAppHasCustomDomain()
        {
            var application = new Mock<IApplication>();
            application.SetupGet(a => a.Domain).Returns("www.customdomain.com");
            var configContext = new ConfigContext(new Config(), application.Object);

            var handler = new RedirectToWwwServerBlockCreationHandler();
            handler.AddServerBlock(configContext);

            Assert.That(configContext.Config.ServerBlock.Count == 1, "This test expected that 1 server blocks would have been created.");
            Assert.That(!string.IsNullOrEmpty(configContext.Config.ServerBlock[0].Return), "A return value is expected for the server block that has been generate.");
        }
        [Test]
        public void ShouldNotCreateServerBlockIfAppDoesNotHaveCustomDomain()
        {
            //no custom domain setup
            var application = new Mock<IApplication>();
            var configContext = new ConfigContext(new Config(), application.Object);

            var handler = new RedirectToWwwServerBlockCreationHandler();
            handler.AddServerBlock(configContext);

            Assert.That(configContext.Config.ServerBlock.Count == 0, "This test expected that no server blocks would have been created, but at least one was created.");
        }
        [Test]
        public void ShouldNotCreateServerBlockIfAppUsesTransportSecurity()
        {
            //no custom domain setup
            var application = new Mock<IApplication>();
            var configContext = new ConfigContext(new Config(), application.Object);
            application.SetupGet(a => a.TransportSecurity).Returns(true);

            var handler = new RedirectToWwwServerBlockCreationHandler();
            handler.AddServerBlock(configContext);

            Assert.That(configContext.Config.ServerBlock.Count == 0, "This test expected that no server blocks would have been created, but at least one was created.");
        }

        [Test]
        public void ShouldNotCreateServerBlockIfAppHasWwwCustomDomainSetup()
        {
            //no custom domain setup
            var application = new Mock<IApplication>();
            application.SetupGet(a => a.Domain).Returns("customdomain.com");
            var configContext = new ConfigContext(new Config(), application.Object);

            var handler = new RedirectToWwwServerBlockCreationHandler();
            handler.AddServerBlock(configContext);

            Assert.That(configContext.Config.ServerBlock.Count == 0, "This test expected that no server blocks would have been created, but at least one was created.");
        }

        [Test]
        [ExpectedException(typeof(ConfigGenerationException), ExpectedMessage = "Could not generate 'redirect to www' server block.  The config context was not supplied.")]
        public void ShouldThrowExceptionIfConfigContextIsMissingApplicationObject()
        {
            var handler = new RedirectToWwwServerBlockCreationHandler();
            handler.AddServerBlock(null);
        }

    }
}


text:
/// <reference path="../_references.ts"/>

module powerbi {
    export interface ITextMeasurer {
        (textElement: SVGTextElement): number;
    }

    export interface ITextAsSVGMeasurer {
        (textProperties: TextProperties): number;
    }

    export interface ITextTruncator {
        (properties: TextProperties, maxWidth: number): string;
    }

    export interface TextProperties {
        text?: string;
        fontFamily: string;
        fontSize: string;
        fontWeight?: string;
        fontStyle?: string;
        fontVariant?: string;
        whiteSpace?: string;
    }

    interface CanvasContext {
        font: string;
        measureText(text: string): { width: number };
    }

    interface CanvasElement extends HTMLElement {
        getContext(name: string);
    }

    export module TextMeasurementService {
        const ellipsis = '…';
        const OverflowingText = jsCommon.CssConstants.createClassAndSelector('overflowingText');

        let spanElement: JQuery;
        let svgTextElement: D3.Selection;
        let canvasCtx: CanvasContext;
        let fallbackFontFamily: string;

        /**
         * Idempotent function for adding the elements to the DOM.
         */
        function ensureDOM(): void {
            if (spanElement)
                return;

            spanElement = $('<span/>');
            $('body').append(spanElement);
            //The style hides the svg element from the canvas, preventing canvas from scrolling down to show svg black square.
            svgTextElement = d3.select($('body').get(0))
                .append('svg')
                .style({
                    'height': '0px',
                    'width': '0px',
                    'position': 'absolute'
                })
                .append('text');
            canvasCtx = (<CanvasElement>$('<canvas/>').get(0)).getContext("2d");
            fallbackFontFamily = window.getComputedStyle(svgTextElement.node()).fontFamily;
        }

        /**
         * Removes spanElement from DOM.
         */
        export function removeSpanElement() {
            if (spanElement && spanElement.remove) {
                spanElement.remove();
            }

            spanElement = null;
        }

        /**
         * This method measures the width of the text with the given SVG text properties.
         * @param textProperties The text properties to use for text measurement.
         * @param text The text to measure.
         */
        export function measureSvgTextWidth(textProperties: TextProperties, text?: string): number {
            debug.assertValue(textProperties, 'textProperties');
            debug.assert(_.isEmpty(textProperties.fontSize) || textProperties.fontSize.indexOf("px") !== -1, "TextProperties' text size should be in px.");

            ensureDOM();

            canvasCtx.font =
                    (textProperties.fontStyle || "") + " " +
                    (textProperties.fontVariant || "") + " " +
                    (textProperties.fontWeight || "") + " " +
                    textProperties.fontSize + " " +
                    (textProperties.fontFamily || fallbackFontFamily);

            return canvasCtx.measureText(text || textProperties.text).width;
        }

        /**
         * This method return the rect with the given SVG text properties.
         * @param textProperties The text properties to use for text measurement.
         * @param text The text to measure.
         */
        export function measureSvgTextRect(textProperties: TextProperties, text?: string): SVGRect {
            debug.assertValue(textProperties, 'textProperties');
            debug.assert(_.isEmpty(textProperties.fontSize) || textProperties.fontSize.indexOf("px") !== -1, "TextProperties' text size should be in px.");

            ensureDOM();

            svgTextElement.style(null);
            svgTextElement
                .text(text || textProperties.text)
                .attr({
                    'visibility': 'hidden',
                    'font-family': textProperties.fontFamily || fallbackFontFamily,
                    'font-variant': textProperties.fontVariant,
                    'font-size': textProperties.fontSize,
                    'font-weight': textProperties.fontWeight,
                    'font-style': textProperties.fontStyle,
                    'white-space': textProperties.whiteSpace || 'nowrap'
                });

            // We're expecting the browser to give a synchronous measurement here
            // We're using SVGTextElement because it works across all browsers
            return svgTextElement.node<SVGTextElement>().getBBox();
        }

        /**
         * This method measures the height of the text with the given SVG text properties.
         * @param textProperties The text properties to use for text measurement.
         * @param text The text to measure.
         */
        export function measureSvgTextHeight(textProperties: TextProperties, text?: string): number {
            return measureSvgTextRect(textProperties, text).height;
        }

        /**
         * This method returns the text Rect with the given SVG text properties.
         * Does NOT return text width; obliterates text value
         * @param {TextProperties} textProperties - The text properties to use for text measurement
         */
        function estimateSvgTextRect(textProperties: TextProperties): SVGRect {
            debug.assertValue(textProperties, 'textProperties');
            debug.assert(_.isEmpty(textProperties.fontSize) || textProperties.fontSize.indexOf("px") !== -1, "TextProperties' text size should be in px.");

            let propertiesKey = textProperties.fontFamily + textProperties.fontSize;
            let rect: SVGRect = ephemeralStorageService.getData(propertiesKey);

            if (rect == null) {
                // To estimate we check the height of a particular character, once it is cached, subsequent
                // calls should always get the height from the cache (regardless of the text).
                let estimatedTextProperties: TextProperties = {
                    fontFamily: textProperties.fontFamily,
                    fontSize: textProperties.fontSize,
                    text: "M",
                };

                rect = TextMeasurementService.measureSvgTextRect(estimatedTextProperties);

                // NOTE: In some cases (disconnected/hidden DOM) we may provide incorrect measurement results (zero sized bounding-box), so
                // we only store values in the cache if we are confident they are correct.
                if (rect.height > 0)
                    ephemeralStorageService.setData(propertiesKey, rect);
            }

            return rect;
        }

        /**
         * This method returns the text Rect with the given SVG text properties.
         * @param {TextProperties} textProperties - The text properties to use for text measurement
         */
        export function estimateSvgTextBaselineDelta(textProperties: TextProperties): number {
            let rect = estimateSvgTextRect(textProperties);
            return rect.y + rect.height;
        }

        /**
         * This method estimates the height of the text with the given SVG text properties.
         * @param {TextProperties} textProperties - The text properties to use for text measurement
         */
        export function estimateSvgTextHeight(textProperties: TextProperties, tightFightForNumeric: boolean = false): number {
            let height = estimateSvgTextRect(textProperties).height;

            //TODO: replace it with new baseline calculation
            if (tightFightForNumeric)
                height *= 0.7;

            return height;
        }

        /**
         * This method measures the width of the svgElement.
         * @param svgElement The SVGTextElement to be measured.
         */
        export function measureSvgTextElementWidth(svgElement: SVGTextElement): number {
            debug.assertValue(svgElement, 'svgElement');
            return measureSvgTextWidth(getSvgMeasurementProperties(svgElement));
        }

        /**
         * This method fetches the text measurement properties of the given DOM element.
         * @param element The selector for the DOM Element.
         */
        export function getMeasurementProperties(element: JQuery): TextProperties {
            debug.assertValue(element, 'element');

            return {
                text: element.val() || element.text(),
                fontFamily: element.css('font-family'),
                fontSize: element.css('font-size'),
                fontWeight: element.css('font-weight'),
                fontStyle: element.css('font-style'),
                fontVariant: element.css('font-variant'),
                whiteSpace: element.css('white-space')
            };
        }

        /**
         * This method fetches the text measurement properties of the given SVG text element.
         * @param svgElement The SVGTextElement to be measured.
         */
        export function getSvgMeasurementProperties(svgElement: SVGTextElement): TextProperties {
            debug.assertValue(svgElement, 'svgElement');

            let style = window.getComputedStyle(svgElement, null);
            return {
                text: svgElement.textContent,
                fontFamily: style.fontFamily,
                fontSize: style.fontSize,
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
                fontVariant: style.fontVariant,
                whiteSpace: style.whiteSpace
            };
        }

        /**
         * This method returns the width of a div element.
         * @param element The div element.
         */
        export function getDivElementWidth(element: JQuery): string {
            debug.assert(element.is('div'), 'Given element is not a div type. Cannot get width');
            return getComputedStyle(element[0]).width;
        }

        /**
         * Compares labels text size to the available size and renders ellipses when the available size is smaller.
         * @param textProperties The text properties (including text content) to use for text measurement.
         * @param maxWidth The maximum width available for rendering the text.
         */
        export function getTailoredTextOrDefault(textProperties: TextProperties, maxWidth: number): string {
            debug.assertValue(textProperties, 'properties');
            debug.assertValue(textProperties.text, 'properties.text');
            debug.assert(_.isEmpty(textProperties.fontSize) || textProperties.fontSize.indexOf("px") !== -1, "TextProperties' text size should be in px.");

            ensureDOM();

            let strLength = textProperties.text.length;

            if (strLength === 0)
                return textProperties.text;

            let width = measureSvgTextWidth(textProperties);

            if (width < maxWidth)
                return textProperties.text;

            // Create a copy of the textProperties so we don't modify the one that's passed in.
            let copiedTextProperties = Prototype.inherit(textProperties);

            // Take the properties and apply them to svgTextElement
            // Then, do the binary search to figure out the substring we want
            // Set the substring on textElement argument
            let text = copiedTextProperties.text = ellipsis + copiedTextProperties.text;

            let min = 1;
            let max = text.length;
            let i = ellipsis.length;

            while (min <= max) {
                // num | 0 prefered to Math.floor(num) for performance benefits
                i = (min + max) / 2 | 0;

                copiedTextProperties.text = text.substr(0, i);
                width = measureSvgTextWidth(copiedTextProperties);

                if (maxWidth > width)
                    min = i + 1;
                else if (maxWidth < width)
                    max = i - 1;
                else
                    break;
            }

            // Since the search algorithm almost never finds an exact match,
            // it will pick one of the closest two, which could result in a
            // value bigger with than 'maxWidth' thus we need to go back by
            // one to guarantee a smaller width than 'maxWidth'.
            copiedTextProperties.text = text.substr(0, i);
            width = measureSvgTextWidth(copiedTextProperties);
            if (width > maxWidth)
                i--;

            return text.substr(ellipsis.length, i - ellipsis.length) + ellipsis;
        }

        /**
         * Compares labels text size to the available size and renders ellipses when the available size is smaller.
         * @param textElement The SVGTextElement containing the text to render.
         * @param maxWidth The maximum width available for rendering the text.
         */
        export function svgEllipsis(textElement: SVGTextElement, maxWidth: number): void {
            debug.assertValue(textElement, 'textElement');

            let properties = getSvgMeasurementProperties(textElement);
            let originalText = properties.text;
            let tailoredText = getTailoredTextOrDefault(properties, maxWidth);

            if (originalText !== tailoredText) {
                textElement.textContent = tailoredText;
            }
        }

        /**
         * Word break textContent of <text> SVG element into <tspan>s
         * Each tspan will be the height of a single line of text
         * @param textElement - the SVGTextElement containing the text to wrap
         * @param maxWidth - the maximum width available
         * @param maxHeight - the maximum height available (defaults to single line)
         * @param linePadding - (optional) padding to add to line height
         */
        export function wordBreak(textElement: SVGTextElement, maxWidth: number, maxHeight: number, linePadding: number = 0): void {
            debug.assertValue(textElement, 'textElement');

            let properties = getSvgMeasurementProperties(textElement);
            let height = estimateSvgTextHeight(properties) + linePadding;
            let maxNumLines = Math.max(1, Math.floor(maxHeight / height));
            let node = d3.select(textElement);

            // Save y of parent textElement to apply as first tspan dy
            let firstDY = node.attr('y');

            // Store and clear text content
            let labelText = textElement.textContent;
            textElement.textContent = null;

            // Append a tspan for each word broken section
            let words = jsCommon.WordBreaker.splitByWidth(labelText, properties, measureSvgTextWidth, maxWidth, maxNumLines);
            for (let i = 0, ilen = words.length; i < ilen; i++) {
                properties.text = words[i];
                node
                    .append('tspan')
                    .attr({
                        'x': 0,
                        'dy': i === 0 ? firstDY : height,
                    })
                // Truncate
                    .text(getTailoredTextOrDefault(properties, maxWidth));
            }
        }

        /**
         * Word break textContent of span element into <span>s
         * Each span will be the height of a single line of text
         * @param textElement - the element containing the text to wrap
         * @param maxWidth - the maximum width available
         * @param maxHeight - the maximum height available (defaults to single line)
         * @param linePadding - (optional) padding to add to line height
         */
        export function wordBreakOverflowingText(textElement: any, maxWidth: number, maxHeight: number, linePadding: number = 0): void {
            debug.assertValue(textElement, 'textElement');

            let properties = getSvgMeasurementProperties(<SVGTextElement>textElement);
            let height = estimateSvgTextHeight(properties) + linePadding;
            let maxNumLines = Math.max(1, Math.floor(maxHeight / height));

            // Store and clear text content
            let labelText = textElement.textContent;
            textElement.textContent = null;

            // Append a span for each word broken section
            let words = jsCommon.WordBreaker.splitByWidth(labelText, properties, measureSvgTextWidth, maxWidth, maxNumLines);
            let spanItem = d3.select(textElement)
                .selectAll(OverflowingText.selector)
                .data(words, (d: String) => $.inArray(d, words));

            spanItem
                .enter()
                .append("span")
                .classed(OverflowingText.class, true)
                .text((d: string) => d)
                .style("width", jsCommon.PixelConverter.toString(maxWidth));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
 * 32d155e - [Travis] Add composer prefer lowest build
 * a1d0446 - [Travis] Move Symfony 2.6.*@dev to 2.6.*
 * dcdefd3 - [Travis] Update config
 * 3f2dc88 - Add .gitattributes
 * 8cf11b8 - [Readme] Fix badge uri
 * 1bad1be - [Composer] Rely on autoload-dev
 * 1d8b472 - [Encapsulation] Move everything from protected to private (except for entry point)

### 1.1.1 (2014-11-08)

 * a31f4c5 - [Gitignore] Remove Composer installer and phar
 * d505420 - Migrate to PSR-4
 * a8be876 - [README] Rely on relative link
 * 69c0bcc - Add contributing doc

### 1.1.0 (2014-08-12)

 * 3a78b79 - [Travis] Improve build matrix
 * 369a2ad - [Doc] Fix typo
 * 8377a8b - Reorganize tests + Improve code coverage
 * 4a9051b - [Orderer] Rename detectedSymetricDiffered to detectedSymmetricDiffered
 * 01f7562 - [Orderer] Remove form stored in the form orderer
 * 723d36f - [Orderer] Remove form orderer factory
 * a25cda7 - [README] Add versioneye badge
 * f746b68 - [README] Add packagist badges
 * 3f30c8e - [Travis] Increase build matrix
 * b4059bf - [Composer] Bump PHP to 5.3.3 + PHPUnit to 4.0
 * 75c3a79 - [Composer] Upgrade to PSR-4

### 1.0.2 (2014-06-17)

 * 39082db - [Travis] Add Symfony 2.5
 * bf993e9 - [README] Add scrutinizer CI badge
 * c15ac7e - [Exception] Fix PHPDoc

### 1.0.1 (2014-05-16)

 * 9240dc1 - Add coveralls support
 * df1b0b2 - Fix CSRF error due to missing form view child
 * 7a57e9b - Make the library compatible with Symfony >= 2.4
 * 9060519 - Introduce ordered form extension
 * 162f98f - Update new year

### 1.0.0 (2013-12-29)


text:
<?php namespace Redooor\Redminportal\App\Models\Traits;

use Redooor\Redminportal\App\Models\Revision;

trait Revisionable
{
    /**
     * @var array
     */
    private $originalData = array();

    /**
     * @var array
     */
    private $updatedData = array();

    /**
     * @var boolean
     */
    private $updating = false;

    /**
     * Keeps the list of values that have been updated
     *
     * @var array
     */
    protected $dirtyData = array();

    /**
     * Morph to Revision
     **/
    public function revisions()
    {
        return $this->morphMany('Redooor\Redminportal\App\Models\Revision', 'revisionable');
    }

    /**
     * Create the event listeners for the saving and saved events
     * This lets us save revisions whenever a save is made, no matter the
     * http method.
     *
     */
    public static function bootRevisionable()
    {
        static::updating(function ($model) {
            $model->preSave();
        });

        static::updated(function ($model) {
            $model->postSave();
        });

        static::created(function ($model) {
            $model->postCreate();
        });

        static::deleted(function ($model) {
            $model->preSave();
            $model->postDelete();
        });
    }

    /**
    * Invoked before a model is saved. Return false to abort the operation.
    *
    * @return bool
    */
    public function preSave()
    {
        $this->originalData = $this->original;
        $this->updatedData = $this->attributes;

        // Disregard all object based items, like DateTime
        foreach ($this->updatedData as $key => $val) {
            if (gettype($val) == 'object' && !method_exists($val, '__toString')) {
                unset($this->originalData[$key]);
                unset($this->updatedData[$key]);
            }
        }

        $this->dirtyData = $this->getDirty();
        $this->updating = $this->exists;
    }

    /**
     * Called after a model is successfully saved.
     *
     * @return void
     */
    public function postSave()
    {
        // Check for revised fields
        $changes_to_record = $this->changedRevisionableFields();

        $revisions = array();

        // Loop through all attributes and create a new revision record each
        foreach (array_keys($changes_to_record) as $key) {
            $revisions[] = array(
                'revisionable_type' => get_class($this),
                'revisionable_id' => $this->getKey(),
                'attribute' => $key,
                'old_value' => array_get($this->originalData, $key),
                'new_value' => $this->updatedData[$key],
                'user_id' => $this->getUserId(),
                'created_at' => new \DateTime(),
                'updated_at' => new \DateTime(),
            );
        }

        if (count($revisions) > 0) {
            $revision = new Revision;
            \DB::table($revision->getTable())->insert($revisions);
        }
    }

    /**
    * Called after record successfully created
    */
    public function postCreate()
    {
        $revisions[] = array(
            'revisionable_type' => get_class($this),
            'revisionable_id' => $this->getKey(),
            'attribute' => 'created_at',
            'old_value' => null,
            'new_value' => $this->created_at,
            'user_id' => $this->getUserId(),
            'created_at' => new \DateTime(),
            'updated_at' => new \DateTime(),
        );
        $revision = new Revision;
        \DB::table($revision->getTable())->insert($revisions);
    }

    /**
     * If softdeletes are enabled, store the deleted time
     */
    public function postDelete()
    {
        // If model is softDelete
        if (isset($this->isSoftDelete) and $this->isSoftDelete) {
            $revisions[] = array(
                'revisionable_type' => get_class($this),
                'revisionable_id' => $this->getKey(),
                'attribute' => 'deleted_at',
                'old_value' => null,
                'new_value' => $this->deleted_at,
                'user_id' => $this->getUserId(),
                'created_at' => new \DateTime(),
                'updated_at' => new \DateTime(),
            );
            $revision = new Revision;
            \DB::table($revision->getTable())->insert($revisions);
        } else {
            // Delete all associated revisions
            $this->revisions()->delete();
        }
    }

    /**
     * Get all of the changes that have been made, that are also supposed
     * to have their changes recorded
     *
     * @return array fields with new data, that should be recorded
     */
    private function changedRevisionableFields()
    {
        $changes_to_record = array();

        foreach ($this->dirtyData as $key => $value) {
            if (!is_array($value)) {
                if (!isset($this->originalData[$key]) || $this->originalData[$key] != $this->updatedData[$key]) {
                    $changes_to_record[$key] = $value;
                }
            }
        }

        return $changes_to_record;
    }

    /**
     * Attempt to find the user id of the currently logged in user
     * Supports Cartalyst Sentry/Sentinel based authentication, as well as stock Auth
     **/
    public function getUserId()
    {
        try {
            if (class_exists($class = '\SleepingOwl\AdminAuth\Facades\AdminAuth')
                || class_exists($class = '\Cartalyst\Sentry\Facades\Laravel\Sentry')
                || class_exists($class = '\Cartalyst\Sentinel\Laravel\Facades\Sentinel')
            ) {
                return ($class::check()) ? $class::getUser()->id : null;
            } elseif (\Auth::check()) {
                return \Auth::user()->getAuthIdentifier();
            }
        } catch (\Exception $e) {
            return null;
        }

        return null;
    }
}


text:
package opaide.editors.config;

import java.io.File;
import opaide.preferences.OpaPreferencesInitializer;

public class OpaBinCompiler {
	private OpaPreferencesInitializer prefs;
	public OpaBinCompiler(OpaPreferencesInitializer prefs) {
		this.prefs = prefs;
	}
	public File getFile() {
		return new File(prefs.getOpaCompilerPath());
	}
}


text:
import { expect } from 'chai';
import * as Rx from '../../src/internal/Rx';
import { hot, cold, expectObservable, expectSubscriptions } from '../helpers/marble-testing';

declare function asDiagram(arg: string): Function;

const Observable = Rx.Observable;

/** @test {elementAt} */
describe('Observable.prototype.elementAt', () => {
  asDiagram('elementAt(2)')('should return last element by zero-based index', () => {
    const source = hot('--a--b--c-d---|');
    const subs =       '^       !      ';
    const expected =   '--------(c|)   ';

    expectObservable((<any>source).elementAt(2)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should return first element by zero-based index', () => {
    const source = hot('--a--b--c--|');
    const subs =       '^ !';
    const expected =   '--(a|)';

    expectObservable((<any>source).elementAt(0)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should return non-first element by zero-based index', () => {
    const source = hot('--a--b--c--d--e--f--|');
    const subs =       '^          !';
    const expected =   '-----------(d|)';

    expectObservable((<any>source).elementAt(3)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should return last element by zero-based index', () => {
    const source = hot('--a--b--c--|');
    const subs =       '^       !';
    const expected =   '--------(c|)';

    expectObservable((<any>source).elementAt(2)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should raise error if source is Empty Observable', () => {
    const source = cold('|');
    const subs =        '(^!)';
    const expected =    '#';

    expectObservable((<any>source).elementAt(0)).toBe(expected, undefined, new Rx.ArgumentOutOfRangeError());
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should propagate error if source is Throw Observable', () => {
    const source = cold('#');
    const subs =        '(^!)';
    const expected =    '#';

    expectObservable((<any>source).elementAt(0)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should return Never if source is Never Observable', () => {
    const source = cold('-');
    const subs =        '^';
    const expected =    '-';

    expectObservable((<any>source).elementAt(0)).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should allow unsubscribing early and explicitly', () => {
    const source = hot('--a--b--c--|');
    const subs =       '^     !     ';
    const expected =   '-------     ';
    const unsub =      '      !     ';

    const result = (<any>source).elementAt(2);

    expectObservable(result, unsub).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should not break unsubscription chains when result Observable is unsubscribed', () => {
    const source = hot('--a--b--c--|');
    const subs =       '^     !     ';
    const expected =   '-------     ';
    const unsub =      '      !     ';

    const result = (<any>source)
      .mergeMap((x: any) => Observable.of(x))
      .elementAt(2)
      .mergeMap((x: any) => Observable.of(x));

    expectObservable(result, unsub).toBe(expected);
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should throw if index is smaller than zero', () => {
    expect(() => { (<any>Observable.range(0, 10)).elementAt(-1); })
      .to.throw(Rx.ArgumentOutOfRangeError);
  });

  it('should raise error if index is out of range but does not have default value', () => {
    const source = hot('--a--|');
    const subs =       '^    !';
    const expected =   '-----#';

    expectObservable((<any>source).elementAt(3))
      .toBe(expected, null, new Rx.ArgumentOutOfRangeError());
    expectSubscriptions(source.subscriptions).toBe(subs);
  });

  it('should return default value if index is out of range', () => {
    const source = hot('--a--|');
    const subs =       '^    !';
    const expected =   '-----(x|)';
    const defaultValue = '42';

    expectObservable((<any>source).elementAt(3, defaultValue)).toBe(expected, { x: defaultValue });
    expectSubscriptions(source.subscriptions).toBe(subs);
  });
});


text:
module.exports = function(context) {

    var fs = context.requireCordovaModule('fs'),
        path = context.requireCordovaModule('path');

    var platformRoot = path.join(context.opts.projectRoot, 'platforms/android');
    var manifestFile = path.join(platformRoot, 'AndroidManifest.xml');

    if (fs.existsSync(manifestFile)) {

        fs.readFile(manifestFile, 'utf8', function (err,data) {
            if (err) {
                throw new Error('Unable to find AndroidManifest.xml: ' + err);
            }

            var reg = /(android:theme=\".*?\")/;
            var result = data.replace(reg, "android:theme=\"@style/AppTheme.NoActionBar\"");

            fs.writeFile(manifestFile, result, 'utf8', function (err) {
                if (err) throw new Error('Unable to write into AndroidManifest.xml: ' + err);
            });

        });
    }
};


text:
package org.scm4j.releaser.scmactions.procs;

import org.apache.commons.lang3.StringUtils;
import org.scm4j.commons.Version;
import org.scm4j.commons.progress.IProgress;
import org.scm4j.releaser.*;
import org.scm4j.releaser.branch.ReleaseBranchFactory;
import org.scm4j.releaser.conf.Component;
import org.scm4j.releaser.conf.MDepsFile;
import org.scm4j.releaser.conf.VCSRepository;
import org.scm4j.releaser.conf.VCSRepositoryFactory;
import org.scm4j.vcs.api.IVCS;
import org.scm4j.vcs.api.VCSChangeListNode;

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

public class SCMProcLockMDeps implements ISCMProc {

	private final IVCS vcs;
	private final ExtendedStatus status;
	private final CachedStatuses cache;
	private final VCSRepositoryFactory repoFactory;
	private final VCSRepository repo;
	private final List<VCSChangeListNode> vcsChangeList;

	public SCMProcLockMDeps(CachedStatuses cache, VCSRepositoryFactory repoFactory, VCSRepository repo,
							List<VCSChangeListNode> vcsChangeList) {
		this.repo = repo;
		this.vcsChangeList = vcsChangeList;
		status = cache.get(repo.getUrl());
		vcs = repo.getVCS();
		this.cache = cache;
		this.repoFactory = repoFactory;
	}

	@Override
	public void execute(IProgress progress) {
		ReleaseBranchFactory.getCRB(repo);
		if (status.getSubComponents().isEmpty()) {
			progress.reportStatus("no mdeps to lock");
			if (!vcsChangeList.isEmpty()) {
				String rbName = Utils.getReleaseBranchName(repo, status.getNextVersion());
				commitChangeList(rbName, "-SNAPSHOT truncate", progress);
			}
			return;
		}
		String rbName = Utils.getReleaseBranchName(repo, status.getNextVersion());
		MDepsFile currentMDepsFile = new MDepsFile(vcs.getFileContent(rbName, Constants.MDEPS_FILE_NAME, null));

		StringBuilder sb = new StringBuilder();
		Version newVersion;
		for (Component currentMDep : currentMDepsFile.getMDeps()) {
			newVersion = cache.get(repoFactory.getUrl(currentMDep)).getNextVersion();
			if (!newVersion.getPatch().equals(Constants.ZERO_PATCH)) {
				newVersion = newVersion.toPreviousPatch();
			}
			sb.append("" + currentMDep.getName() + ": " + currentMDep.getVersion() + " -> " + newVersion + "\r\n");
			currentMDepsFile.replaceMDep(currentMDep.clone(newVersion));
		}
		List<String> statusMessages = new ArrayList<>();
		if (!vcsChangeList.isEmpty()) {
			statusMessages.add("-SNAPSHOT truncate");
		}
		if (sb.length() > 0) {
			sb.setLength(sb.length() - 2);
			progress.reportStatus("mdeps to lock:\r\n" + sb.toString());
			statusMessages.add("lock mdeps");
			vcsChangeList.add(new VCSChangeListNode(Constants.MDEPS_FILE_NAME, currentMDepsFile.toFileContent(),
					Constants.SCM_MDEPS));
		}

		commitChangeList(rbName, StringUtils.join(statusMessages, ", "), progress);
	}

	private void commitChangeList(String branchName, String statusMessage, IProgress progress) {
		Utils.reportDuration(() -> vcs.setFileContent(branchName, vcsChangeList),
				statusMessage, null, progress);
}
}


text:
package ru.job4j.vacancies;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.TimerTask;

public class Parser extends TimerTask {

    private static final Logger LOGGER = Logger.getLogger(Parser.class);

    Properties properties;

    /**
     * Starting date.
     */
    String start;

    /**
     * Database to store data in.
     */
    Database db;

    Parser(Properties properties) {
        this.properties = properties;
        db = new Database(properties);
    }

    /**
     * Запуск парсинга вакансий.
     */
    public void run() {
        LOGGER.info("Start parsing");

        this.start = this.isLastParsingDate();
        this.parsePages();
        this.updateProperties();

        LOGGER.info("Parsing finished");
    }

    /**
     * Consistently parses each page.
     */
    private void parsePages() {
        int last = this.getLastPage();
        for (int i = 1; i <= last; i++) {
            if (!this.parseEachPage(i)) {
                break;
            }
        }
    }

    /**
     * Searches the last page of vacancies forum..
     * @return page number.
     */
    private Integer getLastPage() {
        Integer lastpage = 0;
        try {
            Document document = Jsoup.connect("http://www.sql.ru/forum/job-offers").get();
            Element table = document.select("table.sort_options").last();
            Element link = table.select("a").last();
            lastpage = Integer.valueOf(link.text());
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return lastpage;
    }

    /**
     * Scans each page until found vacancy with publish date older than last launch.
     * @param number page number.
     * @return false if found vacancy older than compare date.
     */
    private boolean parseEachPage(int number) {
        try {
            Document document = Jsoup.connect("http://www.sql.ru/forum/job-offers/" + number).get();
            Element table = document.selectFirst("table.forumTable");
            Elements els = table.select("tr");

            for (int i = 4; i < els.size(); i++) {
                String date = this.normalizeDate(els.get(i).select("td").last().text());
                if (this.isNewDate(date)) {
                    String text = els.get(i).select("td.postslisttopic").text();
                    if (this.isRelevantText(text)) {
                        String href = els.get(i).select("a").first().attr("href");
                        this.db.addVacancy(text, href, date);
                    }
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return false;
    }

    /**
     * Convert date to normal format if it is 'today' or 'yesterday'.
     * @param date vacancy date.
     * @return formatted date.
     */
    private String normalizeDate(String date) {

        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM YY", new Locale("ru"));
        if (date.contains("сегодня")) {
            String today = sdf.format(new Date());
            String time = date.substring(7, date.length());
            date = today + time;
        }

        if (date.contains("вчера")) {
            Date today = new Date();
            Long timing = today.getTime() - (24 * 60 * 60 * 1000);
            Date dayBefore = new Date(timing);
            String yesterday = sdf.format(dayBefore);
            String time = date.substring(5, date.length());
            date = yesterday + time;
        }
        return date;
    }

    /**
     * Checks if vacancy date is actual.
     * @param date vacancy date.
     * @return true if vacancy is new, false if vacancy hava been published before last launch.
     */
    private boolean isNewDate(String date) {
        boolean result = true;
        try {
            SimpleDateFormat format = new SimpleDateFormat("dd MMM yy, HH:mm", new Locale("ru"));
            Date vacancyDate = format.parse(date);
            Date startDate = format.parse(this.start);
            if (startDate.after(vacancyDate)) {
                result = false;
            }

        } catch (ParseException e) {
            LOGGER.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Gets last launch date.
     * @return last launch date or 01.01.18.
     */
    private String isLastParsingDate() {
        String date = properties.getProperty("lastDayLaunched");
        if (date.equals("")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yy");
            date = String.format("01 янв %s, 00:00", sdf.format(new Date()));
            System.out.println("startDate = " + date);
        }
        return date;
    }

    /**
     * Checks if title is not JavaScript or Java Script. If so - replaces it.
     * Then checks final string for 'java'
     * @param text
     * @return
     */
    private boolean isRelevantText(String text) {
        boolean relevant = false;

        String low = text.toLowerCase();
        String low1 = low.replace("javascript", "0");
        String low2 = low1.replace("java script", "0");

        if (low2.contains("java")) {
            relevant = true;
        }
        return relevant;
    }

    /**
     * Updates last launch date in properties file.
     */
    private void updateProperties() {
        try (Writer writer = new OutputStreamWriter(new FileOutputStream("chapter_007\\src\\main\\resources\\parse.properties"))) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yy, HH:mm", new Locale("ru"));
            String today = sdf.format(new Date());

            properties.setProperty("lastDayLaunched", today);
            properties.store(writer, null);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }
}


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.WebPubSub;

namespace Azure.ResourceManager.WebPubSub.Models
{
    /// <summary> Hub setting list. </summary>
    internal partial class WebPubSubHubList
    {
        /// <summary> Initializes a new instance of WebPubSubHubList. </summary>
        internal WebPubSubHubList()
        {
            Value = new ChangeTrackingList<WebPubSubHubData>();
        }

        /// <summary> Initializes a new instance of WebPubSubHubList. </summary>
        /// <param name="value"> List of hub settings to this resource. </param>
        /// <param name="nextLink">
        /// The URL the client should use to fetch the next page (per server side paging).
        /// It's null for now, added for future use.
        /// </param>
        internal WebPubSubHubList(IReadOnlyList<WebPubSubHubData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> List of hub settings to this resource. </summary>
        public IReadOnlyList<WebPubSubHubData> Value { get; }
        /// <summary>
        /// The URL the client should use to fetch the next page (per server side paging).
        /// It's null for now, added for future use.
        /// </summary>
        public string NextLink { get; }
    }
}


text:
require 'test_helper'

class DraftsControllerTest < ActionController::TestCase
  setup do
    @draft = drafts(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:drafts)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create draft" do
    assert_difference('Draft.count') do
      post :create, draft: { fantasy_draft_style_id: @draft.fantasy_draft_style_id, fantasy_league_id: @draft.fantasy_league_id, max_amount: @draft.max_amount, player_id: @draft.player_id, rounds: @draft.rounds }
    end

    assert_redirected_to draft_path(assigns(:draft))
  end

  test "should show draft" do
    get :show, id: @draft
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @draft
    assert_response :success
  end

  test "should update draft" do
    patch :update, id: @draft, draft: { fantasy_draft_style_id: @draft.fantasy_draft_style_id, fantasy_league_id: @draft.fantasy_league_id, max_amount: @draft.max_amount, player_id: @draft.player_id, rounds: @draft.rounds }
    assert_redirected_to draft_path(assigns(:draft))
  end

  test "should destroy draft" do
    assert_difference('Draft.count', -1) do
      delete :destroy, id: @draft
    end

    assert_redirected_to drafts_path
  end
end


text:
/**
 * \file LegacyDAS.h
 * \brief Header file for Legacy DAS defines.
 * \author Dale V. Stansberry
 * \date June 6, 2012
 */

#include "PVStreamerSupport.h"

#define LDAS_PROTOCOL               1


text:
package com.tlongdev.spicio.presentation.ui.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tlongdev.spicio.R;
import com.tlongdev.spicio.domain.model.Episode;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author Long
 * @since 2016. 03. 10.
 */
public class SeasonEpisodesAdapter extends RecyclerView.Adapter<SeasonEpisodesAdapter.ViewHolder> {

    private Context mContext;

    private List<Episode> mDataSet;
    private OnItemSelectedListener listener;

    public SeasonEpisodesAdapter(Context context) {
        mContext = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_seasons, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (mDataSet != null) {
            final Episode episode = mDataSet.get(position);

            holder.title.setText(String.format("Episode %d", episode.getNumber()));

            Glide.with(mContext)
                    .load(episode.getImages().getScreenshot().getThumb())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(holder.thumb);

            holder.root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onItemSelected(episode);
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mDataSet == null ? 0 : mDataSet.size();
    }

    public void setDataSet(List<Episode> dataSet) {
        mDataSet = dataSet;
    }

    public void setListener(OnItemSelectedListener listener) {
        this.listener = listener;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.thumb) ImageView thumb;
        @Bind(R.id.title) TextView title;

        View root;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            root = view;
        }
    }

    public interface OnItemSelectedListener {
        void onItemSelected(Episode episode);
    }
}


text:
.field-set {
    background: rgba(255, 255, 255, 0.4);
    border: 1px solid #b3b3b3;
    padding: 0 7px;
    line-height: 16px;
    margin: 0;
    outline: none;
    -moz-transition: 0.2s box-shadow ease-in;
    -webkit-transition: 0.2s box-shadow ease-in;
    -o-transition: 0.2s box-shadow ease-in;
    transition: 0.2s box-shadow ease-in;
    -moz-transition: 0.2s border ease-in;
    -webkit-transition: 0.2s border ease-in;
    -o-transition: 0.2s border ease-in;
    transition: 0.2s border ease-in;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px;
    background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgi…gd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0idXJsKCNncmFkKSIgLz48L3N2Zz4g');
    background-size: 100%;
    background-image: none;
    width: 100%;
    max-width: 512px;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.field-set .field-part {
    display: inline-block;
    white-space: nowrap;
}

.field-set .field-part span {
    display: inline-block;
    white-space: nowrap;
}

.field-set .field-part span input.text {
    border: transparent;
}

.field-set .field-part span input.text:focus {
    border: none;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
}

.field select.customizabledropdownpart {
    height: 30px;
    background: #fff;
    border: none;
    margin: 0;
}

.field select.customizabledropdownpart:focus {
    outline: none;
}

.field.nolabel .customizableinputfieldset .middleColumn {
    margin-left: 184px;
}


text:
This example demonstrates how to run [`set-namespace`] function
to replace the  `namespace` resource type in a variety of KRM resources.

### Fetch the example package

Get the example package by running the following commands:

```shell
$ kpt pkg get https://github.com/GoogleContainerTools/kpt-functions-catalog.git/examples/set-namespace-simple
```

We use the following `Kptfile` to configure the function.

```yaml
apiVersion: kpt.dev/v1
kind: Kptfile
metadata:
  name: example
pipeline:
  mutators:
    - image: gcr.io/kpt-fn/set-namespace:unstable
      configMap:
        namespace: example-ns
```

The function configuration is provided using a `ConfigMap`. We set only one
key-value pair:
- `namespace: example-ns`: The desired namespace.

### Function invocation

Invoke the function by running the following commands:

```shell
$ kpt fn render set-namespace-simple
```

### Expected result

Check all resources have `metadata.namespace` set to `example-ns`

[`set-namespace`]: https://catalog.kpt.dev/set-namespace/v0.3/


text:
class User < ApplicationRecord
  devise :database_authenticatable, :rememberable, :trackable,
    :omniauthable, omniauth_providers: [:keltec]

  validates :email, presence: true, uniqueness: true
  validates :firstname, presence: true
  validates :lastname, presence: true

  def self.from_omniauth(auth)
    user = where(provider: auth.provider, uid: auth.uid).first_or_initialize
    user.email = auth.info.email
    user.lastname = auth.info.lastname
    user.firstname = auth.info.firstname
    user.save!
    user
  end

  def fullname
    "#{firstname} #{lastname}"
  end
end


text:
r"""Library for creating different blackbox objects.

Library for creating different blackbox objects providing ways to manipulate
blackbox functions to be optimized (obtaining starting points for their
optimization, executing them and getting metaparameters needed to set
up certain algorithms optimizing them).
"""

import abc
from typing import List, Any
import numpy as np

class BlackboxObject(abc.ABC):
  """Abstract class used to execute and restart blackbox functions.

  Abstract class responsible for executing and restarting blackbox fuctions.
  """

  @abc.abstractmethod
  def get_initial(self):
    """Returns input where optimization starts.

    Returns input where optimization starts.

    Args:

    Returns:
      Initial input where optimization starts.
    """
    raise NotImplementedError('Abstract method')

  @abc.abstractmethod
  def execute(self, params, hyperparams):
    """Executes blackbox function.

    Executes blackbox function.

    Args:
      params: parameters of the blackbox function
      hyperparams: hyperparameters of the blackbox function

    Returns:
      The value of the blackbox function for given parameters and
      hyperparameters as well as evaluation statistics from the evaluation.
    """
    raise NotImplementedError('Abstract method')

  @abc.abstractmethod
  def get_metaparams(self):
    """Returns metaparameters of the blackbox function.

    Returns the list of metaparameters of the blackbox function.

    Args:

    Returns:
      The list of metaparameters of the blackbox function.
    """
    raise NotImplementedError('Abstract method')