text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Dynamic.Utils;

namespace System.Linq.Expressions.Interpreter
{
    internal abstract class NotInstruction : Instruction
    {
        public static Instruction s_Boolean, s_Int64, s_Int32, s_Int16, s_UInt64, s_UInt32, s_UInt16, s_Byte, s_SByte;

        private NotInstruction() { }

        public override int ConsumedStack => 1;
        public override int ProducedStack => 1;
        public override string InstructionName => "Not";

        private sealed class NotBoolean : NotInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                object value = frame.Pop();
                if (value == null)
                {
                    frame.Push(null);
                }
                else
                {
                    frame.Push(!(bool)value);
                }
                return 1;
            }
        }

        private sealed class NotInt64 : NotInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                object value = frame.Pop();
                if (value == null)
                {
                    frame.Push(null);
                }
                else
                {
                    frame.Push(~(long)value);
                }
                return 1;
            }
        }

        private sealed class NotInt32 : NotInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                object value = frame.Pop();
                if (value == null)
                {
                    frame.Push(null);
                }
                else
                {
                    frame.Push(~(int)value);
                }
                return 1;
            }
        }

        private sealed class NotInt16 : NotInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                object value = frame.Pop();
                if (value == null)
                {
                    frame.Push(null);
                }
                else
                {
                    frame.Push((short)(~(short)value));
                }
                return 1;
            }
        }

        private sealed class NotUInt64 : NotInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                object value = frame.Pop();
                if (value == null)
                {
                    frame.Push(null);
                }
                else
                {
                    frame.Push(~(ulong)value);
                }
                return 1;
            }
        }

        private sealed class NotUInt32 : NotInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                object value = frame.Pop();
                if (value == null)
                {
                    frame.Push(null);
                }
                else
                {
                    frame.Push(~(uint)value);
                }
                return 1;
            }
        }

        private sealed class NotUInt16 : NotInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                object value = frame.Pop();
                if (value == null)
                {
                    frame.Push(null);
                }
                else
                {
                    frame.Push(unchecked((ushort)(~(ushort)value)));
                }
                return 1;
            }
        }

        private sealed class NotByte : NotInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                object value = frame.Pop();
                if (value == null)
                {
                    frame.Push(null);
                }
                else
                {
                    frame.Push(unchecked((byte)(~(byte)value)));
                }
                return 1;
            }
        }

        private sealed class NotSByte : NotInstruction
        {
            public override int Run(InterpretedFrame frame)
            {
                object value = frame.Pop();
                if (value == null)
                {
                    frame.Push(null);
                }
                else
                {
                    frame.Push((sbyte)(~(sbyte)value));
                }
                return 1;
            }
        }

        public static Instruction Create(Type type)
        {
            switch (type.GetNonNullableType().GetTypeCode())
            {
                case TypeCode.Boolean: return s_Boolean ?? (s_Boolean = new NotBoolean());
                case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new NotInt64());
                case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new NotInt32());
                case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new NotInt16());
                case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new NotUInt64());
                case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new NotUInt32());
                case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new NotUInt16());
                case TypeCode.Byte: return s_Byte ?? (s_Byte = new NotByte());
                case TypeCode.SByte: return s_SByte ?? (s_SByte = new NotSByte());
                default:
                    throw ContractUtils.Unreachable;
            }
        }
    }
}


text:
require 'rails_helper'

feature 'Create student', js: false do
  let!(:user) { FactoryGirl.create(:user) }

  scenario 'with correct data' do
    sign_in user
    create_student

    expect(page).to have_content('Estudante cadastro com sucesso')
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Gt\Database\Test\Migration;

use DateTime;
use Exception;
use Gt\Database\Database;
use Gt\Database\Connection\Settings;
use Gt\Database\DatabaseException;
use Gt\Database\Migration\MigrationDirectoryNotFoundException;
use Gt\Database\Migration\MigrationFileNameFormatException;
use Gt\Database\Migration\MigrationIntegrityException;
use Gt\Database\Migration\MigrationSequenceOrderException;
use Gt\Database\Migration\Migrator;
use Gt\Database\Test\Helper\Helper;
use PHPUnit\Framework\TestCase;
use SplFileObject;
use stdClass;

class MigratorTest extends TestCase {
	const MIGRATION_CREATE
		= "create table `test` (`id` int primary key, `name` varchar(32))";
	const MIGRATION_ALTER = "alter table `test` add `new_column` varchar(32)";

	public function getMigrationDirectory():string {
		$tmp = Helper::getTmpDir();

		$path = implode(DIRECTORY_SEPARATOR, [
			$tmp,
			"query",
			"_migration",
		]);
		mkdir($path, 0775, true);
		return $path;
	}

	public function testMigrationZeroAtStartWithoutTable() {
		$path = $this->getMigrationDirectory();
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$migrator->createMigrationTable();
		self::assertEquals(0, $migrator->getMigrationCount());
	}

	public function testCheckMigrationTableExists() {
		$path = $this->getMigrationDirectory();
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		self::assertFalse($migrator->checkMigrationTableExists());
	}

	public function testCreateMigrationTable() {
		$path = $this->getMigrationDirectory();
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$migrator->createMigrationTable();
		self::assertTrue($migrator->checkMigrationTableExists());
	}

	public function testMigrationZeroAtStartWithTable() {
		$path = $this->getMigrationDirectory();
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$migrator->createMigrationTable();
		self::assertEquals(0, $migrator->getMigrationCount());
	}

	/** @dataProvider dataMigrationFileList */
	public function testGetMigrationFileList(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createFiles($fileList, $path);
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$actualFileList = $migrator->getMigrationFileList();
		self::assertSameSize($fileList, $actualFileList);
	}

	public function testGetMigrationFileListNotExists() {
		$path = $this->getMigrationDirectory();
		$settings = $this->createSettings($path);
		$migrator = new Migrator(
			$settings,
			dirname($path) . "does-not-exist"
		);
		$this->expectException(MigrationDirectoryNotFoundException::class);
		$migrator->getMigrationFileList();
	}

	/** @dataProvider dataMigrationFileList */
	public function testCheckFileListOrder(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createFiles($fileList, $path);

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$actualFileList = $migrator->getMigrationFileList();
		$exception = null;

		try {
			$migrator->checkFileListOrder($actualFileList);
		}
		catch(Exception $exception) {}

		self::assertNull(
			$exception,
			"No exception should be thrown"
		);
	}

	/** @dataProvider dataMigrationFileListMissing */
	public function testCheckFileListOrderMissing(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createFiles($fileList, $path);

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$actualFileList = $migrator->getMigrationFileList();
		$this->expectException(MigrationSequenceOrderException::class);
		$migrator->checkFileListOrder($actualFileList);
	}

	/** @dataProvider dataMigrationFileListDuplicate */
	public function testCheckFileListOrderDuplicate(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createFiles($fileList, $path);

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$actualFileList = $migrator->getMigrationFileList();
		$this->expectException(MigrationSequenceOrderException::class);
		$migrator->checkFileListOrder($actualFileList);
	}

	/** @dataProvider dataMigrationFileList */
	public function testCheckIntegrityGood(array $fileList) {
		$path = $this->getMigrationDirectory();

		$this->createMigrationFiles($fileList, $path);
		$this->hashMigrationToDb($fileList, $path);

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		},$fileList);

		self::assertEquals(
			count($absoluteFileList),
			$migrator->checkIntegrity($absoluteFileList)
		);
	}

	/** @dataProvider dataMigrationFileList */
	public function testCheckIntegrityBad(array $fileList) {
		$path = $this->getMigrationDirectory();

		$this->createMigrationFiles($fileList, $path);
		$this->hashMigrationToDb($fileList, $path);

		$migrationToBreak = implode(DIRECTORY_SEPARATOR, [
			$path,
			$fileList[array_rand($fileList)],
		]);
		$sql = file_get_contents($migrationToBreak);
		$sql = substr_replace(
			$sql,
			"EDITED",
			rand(0, 20),
			0
		);
		file_put_contents($migrationToBreak, $sql);

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		},$fileList);

		self::expectException(MigrationIntegrityException::class);
		$migrator->checkIntegrity($absoluteFileList);
	}

	public function testMigrationCountZeroAtStart() {
		$path = $this->getMigrationDirectory();
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$migrator->createMigrationTable();
		self::assertEquals(0, $migrator->getMigrationCount());
	}

	/** @dataProvider dataMigrationFileList */
	public function testMigrationCountNotZeroAfterMigration(array $fileList) {
		$path = $this->getMigrationDirectory();

		$this->createMigrationFiles($fileList, $path);
		$this->hashMigrationToDb($fileList, $path);

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		},$fileList);

		self::assertEquals(
			count($absoluteFileList),
			$migrator->getMigrationCount()
		);
	}

	/** @dataProvider dataMigrationFileList */
	public function testMigrationCountReturnsZeroOnException(array $fileList) {
		$path = $this->getMigrationDirectory();

		$this->createMigrationFiles($fileList, $path);
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		self::assertEquals(0, $migrator->getMigrationCount());
	}

	/**
	 * @dataProvider dataMigrationFileList
	 */
	public function testMigrationFileNameFormat(array $fileList) {
		$path = $this->getMigrationDirectory();

		$this->createMigrationFiles($fileList, $path);
		$this->hashMigrationToDb($fileList, $path);

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		},$fileList);

		$fileToBreakFormat = array_rand($absoluteFileList);
		$absoluteFileList[$fileToBreakFormat] = str_replace(
			".sql",
			".broken",
			$absoluteFileList[$fileToBreakFormat]
		);

		self::expectException(MigrationFileNameFormatException::class);
		$migrator->checkFileListOrder($absoluteFileList);
	}

	/**
	 * @dataProvider dataMigrationFileList
	 */
	public function testForcedMigration(array $fileList) {
		$path = $this->getMigrationDirectory();

		$this->createMigrationFiles($fileList, $path);
		$this->hashMigrationToDb($fileList, $path);

		$settings = $this->createSettings($path);
		$exception = null;

		try {
			new Migrator(
				$settings,
				$path,
				"_migration",
				true
			);
		}
		catch(Exception $exception) {}

		self::assertNull($exception,"Exception should not be thrown");
	}

	/**
	 * @dataProvider dataMigrationFileList
	 * @runInSeparateProcess
	 */
	public function testPerformMigrationGood(array $fileList):void {
		$path = $this->getMigrationDirectory();

		$this->createMigrationFiles($fileList, $path);

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		},$fileList);

		$migrator->createMigrationTable();

		$exception = null;

		try {
			ob_start();
			$migrator->performMigration($absoluteFileList);
			ob_end_clean();
		}
		catch(Exception $exception) {}

		$db = new Database($settings);
		$result = $db->executeSql("PRAGMA table_info(test);");
// There should be one more column than the number of files, due to the fact that the first
// migration creates the table with two columns.
		self::assertCount(
		count($absoluteFileList) + 1,
			$result->fetchAll()
		);
	}

	/** @dataProvider dataMigrationFileList */
	public function testPerformMigrationBad(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createMigrationFiles($fileList, $path);
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file) use ($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		}, $fileList);

		$fileToMessUp = $absoluteFileList[array_rand($absoluteFileList)];
		file_put_contents($fileToMessUp, "create nothing because nothing really matters");

		$migrator->createMigrationTable();
		$exception = null;

		self::expectException(DatabaseException::class);
		$migrator->performMigration($absoluteFileList);
	}

	/** @dataProvider dataMigrationFileList */
	public function testPerformMigrationAlreadyCompleted(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createMigrationFiles($fileList, $path);
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		}, $fileList);

		$existingCount = count($absoluteFileList);

		$migrator->createMigrationTable();
		$exception = null;

		try {
			ob_start();
			$numCompleted = $migrator->performMigration(
				$absoluteFileList,
				$existingCount
			);
			ob_end_clean();
		}
		catch(Exception $exception) {}

		self::assertNull($exception);
		self::assertEquals(0, $numCompleted);

	}

	/**
	 * @dataProvider dataMigrationFileList
	 */
	public function testNonSqlExtensions(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createMigrationFiles($fileList, $path);

		$extensionsToCreate = ["txt", "md", "sql"];

		for($i = 0; $i < 10; $i++) {
			$randomFile = implode(DIRECTORY_SEPARATOR, [
				$path,
				uniqid() . $extensionsToCreate[array_rand($extensionsToCreate)],
			]);
			file_put_contents($randomFile, "Hello, Database!");
		}

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		},$fileList);

		$migrator->createMigrationTable();

		$exception = null;

		try {
			ob_start();
			$migrator->performMigration($absoluteFileList);
			ob_end_clean();
		}
		catch(Exception $exception) {}

		self::assertNull($exception);
	}

	/** @dataProvider dataMigrationFileList */
	public function testMigrationThrowsExceptionWhenNoMigrationTable(array $fileList) {
		$path = $this->getMigrationDirectory();

		$this->createMigrationFiles($fileList, $path);

		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		},$fileList);

		self::expectException(DatabaseException::class);
		$migrator->performMigration($absoluteFileList);
	}

	public function testMigrationNoOutputEmpty() {
		$path = $this->getMigrationDirectory();
		$settings = $this->createSettings($path);
		$migrator = new Migrator($settings, $path);
		ob_start();
		$migrator->performMigration([]);
		$output = ob_get_clean();
		self::assertEmpty($output);
	}

	/** @dataProvider dataMigrationFileList */
	public function testMigrationNoOutput(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createMigrationFiles($fileList, $path);

		$settings = $this->createSettings($path);

		ob_start();

		$migrator = new Migrator($settings, $path);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		},$fileList);

		$migrator->createMigrationTable();
		$migrator->performMigration($absoluteFileList);

		$output = ob_get_clean();
		self::assertEmpty($output);
	}

	/** @dataProvider dataMigrationFileList */
	public function testMigrationOutputToStream(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createMigrationFiles($fileList, $path);

		$settings = $this->createSettings($path);
		$streamOut = new SplFileObject("php://memory", "w");

		$migrator = new Migrator($settings, $path);
		$migrator->setOutput($streamOut);
		$absoluteFileList = array_map(function($file)use($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		},$fileList);

		$migrator->createMigrationTable();
		$migrator->performMigration($absoluteFileList);

		$streamOut->rewind();
		$output = $streamOut->fread(4096);
		self::assertStringContainsString("Migration 1:", $output);
		self::assertStringContainsString("Completed migrations successfully.", $output);
	}

	/** @dataProvider dataMigrationFileList */
	public function testMigrationErrorOutputToStream(array $fileList) {
		$path = $this->getMigrationDirectory();
		$this->createMigrationFiles($fileList, $path);
		$settings = $this->createSettings($path);

		$streamOut = new SplFileObject("php://memory", "w");
		$streamError = new SplFileObject("php://memory", "w");

		$migrator = new Migrator($settings, $path);
		$migrator->setOutput($streamOut, $streamError);
		$absoluteFileList = array_map(function($file) use ($path) {
			return implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
		}, $fileList);

		$fileToMessUp = $absoluteFileList[array_rand($absoluteFileList)];
		file_put_contents($fileToMessUp, "create nothing because nothing really matters");

		$migrator->createMigrationTable();
		$exception = null;

		try {
			$migrator->performMigration($absoluteFileList);
		}
		catch(DatabaseException $exception) {
			$streamOut->rewind();
			$output = $streamOut->fread(1024);
			$streamError->rewind();
			$outputError = $streamError->fread(1024);
			self::assertStringContainsString(
				"Migration 1:",
				$output
			);
			self::assertStringNotContainsString(
				"Migration 1:",
				$outputError
			);
			self::assertStringContainsString(
				"General error: 1 near \"nothing\": syntax error",
				$outputError
			);
			self::assertStringNotContainsString(
				"General error: 1 near \"nothing\": syntax error",
				$output
			);
		}
	}

	public function dataMigrationFileList():array {
		$fileList = $this->generateFileList();
		return [
			[$fileList]
		];
	}

	public function dataMigrationFileListMissing():array {
		$fileList = $this->generateFileList(
			true,
			false
		);
		return [
			[$fileList]
		];
	}

	public function dataMigrationFileListDuplicate():array {
		$fileList = $this->generateFileList(
			false,
			true
		);
		return [
			[$fileList]
		];
	}

	protected function createMigrationFiles(array $fileList, string $path):void {
		foreach($fileList as $i => $fileName) {
			$migPathName = implode(DIRECTORY_SEPARATOR, [
				$path,
				$fileName,
			]);
			if($i === 0) {
				$mig = self::MIGRATION_CREATE;
			}
			else {
				$mig = self::MIGRATION_ALTER;
				$mig = str_replace(
					"`new_column`",
					"`new_column_$i`",
					$mig
				);
			}

			file_put_contents($migPathName, $mig);
		}
	}

	protected function hashMigrationToDb(
		array $fileList,
		string $path,
		bool $stopEarly = false
	):void {
		$hashUpTo = null;

		if($stopEarly) {
			$hashUpTo = count($fileList) - rand(0, count($fileList) - 5);
		}

		$settings = $this->createSettings($path);
		$db = new Database($settings);
		$db->executeSql(implode("\n", [
			"create table `_migration` (",
			"`" . Migrator::COLUMN_QUERY_NUMBER . "` int primary key,",
			"`" . Migrator::COLUMN_QUERY_HASH . "` varchar(32) not null,",
			"`" . Migrator::COLUMN_MIGRATED_AT . "` datetime not null )",
		]));

		foreach($fileList as $i => $file) {
			if(!is_null($hashUpTo)
			&& $i >= $hashUpTo) {
				break;
			}

			$migNum = $i + 1;
			$migPathName = implode(DIRECTORY_SEPARATOR, [
				$path,
				$file,
			]);
			$hash = md5_file($migPathName);

			$sql = implode("\n", [
				"insert into `_migration` (",
				"`" . Migrator::COLUMN_QUERY_NUMBER . "`, ",
				"`" . Migrator::COLUMN_QUERY_HASH . "`, ",
				"`" . Migrator::COLUMN_MIGRATED_AT . "` ",
				") values (",
				"?, ?, datetime('now')",
				")",
			]);

			$db->executeSql($sql, [$migNum, $hash]);
		}
	}

	private function generateFileList($missingFiles = false, $duplicateFiles = false) {
		$fileList = [];

		$migLength = rand(10, 30);
		for($migNum = 1; $migNum <= $migLength; $migNum++) {
			$fileName = str_pad(
				$migNum,
				4,
				"0",
				STR_PAD_LEFT
			);
			$fileName .= "-";
			$fileName .= uniqid();
			$fileName .= ".sql";

			$fileList []= $fileName;
		}

		if($missingFiles) {
			$numToRemove = rand(1, $migLength / 10);
			for($i = 0; $i < $numToRemove; $i++) {
				$keyToRemove = array_rand($fileList);
				unset($fileList[$keyToRemove]);
			}
		}

		if($duplicateFiles) {
			$numToDuplicate = rand(1, 10);
			for($i = 0; $i < $numToDuplicate; $i++) {
				$keyToDuplicate = array_rand($fileList);
				$newFilename = $fileList[$keyToDuplicate];
				$newFilename = strtok($newFilename, "-");
				$newFilename .= "-";
				$newFilename .= uniqid();
				$newFilename .= ".sql";
				$fileList []= $newFilename;
			}

			$fileList = array_values($fileList);
			sort($fileList);
		}

		$fileList = array_values($fileList);
		return $fileList;
	}

	protected function createSettings(string $path):Settings {
		$sqlitePath = implode(DIRECTORY_SEPARATOR, [
			dirname($path),
			"migrator-test.db",
		]);
		$sqlitePath = str_replace("\\", "/", $sqlitePath);

		return new Settings(
			dirname(dirname($path)),
			Settings::DRIVER_SQLITE,
			$sqlitePath
		);
	}

	protected function createFiles(array $files, string $path):void {
		foreach($files as $filename) {
			$pathName = implode(DIRECTORY_SEPARATOR, [
				$path,
				$filename
			]);

			touch($pathName);
		}
	}
}


text:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="TCK\Blog\Api\Data\PostInterface" type="TCK\Blog\Model\Post" />
    <preference for="TCK\Blog\Api\CategoryRepositoryInterface" type="TCK\Blog\Model\CategoryRepository"/>
    <preference for="TCK\Blog\Api\Data\CategoryInterface" type="TCK\Blog\Model\Category"/>
    <preference for="TCK\Blog\Api\Data\CategorySearchResultsInterface" type="Magento\Framework\Api\SearchResults"/>
    <virtualType name="BlogGirdFilterPool" type="Magento\Framework\View\Element\UiComponent\DataProvider\FilterPool">
        <arguments>
            <argument name="appliers" xsi:type="array">
                <item name="regular" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\RegularFilter</item>
                <item name="fulltext" xsi:type="object">Magento\Framework\View\Element\UiComponent\DataProvider\FulltextFilter</item>
            </argument>
        </arguments>
    </virtualType>
    <virtualType name="PostGridDataProvider" type="Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider">
        <arguments>
            <argument name="collection" xsi:type="object" shared="false">TCK\Blog\Model\Resource\Post\Collection</argument>
            <argument name="filterPool" xsi:type="object" shared="false">BlogGirdFilterPool</argument>
        </arguments>
    </virtualType>
    <virtualType name="TCK\Blog\Model\ResourceModel\Post\Grid\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
        <arguments>
            <argument name="mainTable" xsi:type="string">tck_blog_post</argument>
            <argument name="resourceModel" xsi:type="string">TCK\Blog\Model\ResourceModel\Post</argument>
        </arguments>
    </virtualType>
    <type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
        <arguments>
            <argument name="collections" xsi:type="array">
                <item name="blog_post_listing_data_source" xsi:type="string">TCK\Blog\Model\ResourceModel\Post\Grid\Collection</item>
            </argument>
        </arguments>
    </type>
</config>


text:
label.tabular{
text-align: right;
width: 270px;
display: inline-block;
}

label.tabular2{
text-align: right;
width: 100px;
display: inline-block;
}


text:
'use strict';

var unique = require('array-unique');

module.exports = function union(init/*, arrays*/) {
  var arrays = [].slice.call(arguments, 1);

  return unique(arrays.reduce(function (acc, arr) {
    return acc.concat(arr);
  }, init));
};


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

declare function asDiagram(arg: string): Function;

const Observable = Rx.Observable;

/** @test {defaultIfEmpty} */
describe('Observable.prototype.defaultIfEmpty', () => {
  asDiagram('defaultIfEmpty(42)')('should return the Observable if not empty with a default value', () => {
    const e1 =   hot('--------|');
    const expected = '--------(x|)';

    expectObservable(e1.defaultIfEmpty(42)).toBe(expected, { x: 42 });
  });

  it('should return the argument if Observable is empty', () => {
    const e1 =  cold('|');
    const e1subs =   '(^!)';
    const expected = '(x|)';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return null if the Observable is empty and no arguments', () => {
    const e1 =  cold('|');
    const e1subs =   '(^!)';
    const expected = '(x|)';

    expectObservable(e1.defaultIfEmpty()).toBe(expected, { x: null });
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return the Observable if not empty with a default value', () => {
    const e1 =   hot('--a--b--|');
    const e1subs =   '^       !';
    const expected = '--a--b--|';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return the Observable if not empty with no default value', () => {
    const e1 =   hot('--a--b--|');
    const e1subs =   '^       !';
    const expected = '--a--b--|';

    expectObservable(e1.defaultIfEmpty()).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

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

    const result = e1.defaultIfEmpty('x');

    expectObservable(result, unsub).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should not break unsubscription chains when unsubscribed explicitly', () => {
    const e1 =   hot('--a--b--|');
    const e1subs =   '^   !    ';
    const expected = '--a--    ';
    const unsub =    '    !    ';

    const result = e1
      .mergeMap((x: any) => Observable.of(x))
      .defaultIfEmpty('x')
      .mergeMap((x: any) => Observable.of(x));

    expectObservable(result, unsub).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should error if the Observable errors', () => {
    const e1 =  cold('#');
    const e1subs =   '(^!)';
    const expected = '#';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });
});


text:
import sys
import os

# on_rtd is whether we are on readthedocs.org,
# this line of code grabbed from docs.readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if on_rtd:
    class Mock(object):

        __all__ = []

        def __init__(self, *args, **kwargs):
            pass

        def __call__(self, *args, **kwargs):
            return Mock()

        @classmethod
        def __getattr__(cls, name):
            if name in ('__file__', '__path__'):
                return '/dev/null'
            elif name[0] == name[0].upper():
                mockType = type(name, (), {})
                mockType.__module__ = __name__
                return mockType
            else:
                return Mock()

    MOCK_MODULES = ['numpy', 'scipy', 'PIL', 'sklearn', 'skimage',
                    'scipy.linalg', 'numpy.stats', 'scipy.misc', 'PIL.Image',
                    'matplotlib', 'mayavi',
                    'skimage.transform', 'matplotlib.pyplot', 'scipy.spatial',
                    'skimage.transform.pyramids', 'scipy.spatial.distance',
                    'numpy.dtype', 'scipy.ndimage',
                    'scipy.linalg.blas']
    # Masking our Cython modules
    MOCK_MODULES += ['menpo.transform.piecewiseaffine.fastpwa',
                     'menpo.image.feature.cppimagewindowiterator',
                     'menpo.shape.mesh.normals']
    for mod_name in MOCK_MODULES:
        sys.modules[mod_name] = Mock()

# Add the folder above so we can grab the sphinx extensions
sys.path.insert(0, os.path.abspath('..'))
# Add the menpo root so we can grab the version
sys.path.insert(0, os.path.abspath('../../'))

import menpofit

# -- General configuration -----------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc',
              'sphinx.ext.todo',
              'sphinx.ext.coverage',
              'sphinx.ext.mathjax',
              'sphinx.ext.viewcode',
              'sphinx.ext.autosummary',
              'numpydoc',
              'sphinxext.ref_prettify',
              'sphinxmapxrefrole']

# Import the mapping dictionary and set it for sphinxmapxrefrole
from xref_map import xref_map
xref_mapping_dict = xref_map

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# Otherwise Sphinx emits thousands of warnings
numpydoc_show_class_members = False
numpydoc_class_members_toctree = False

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# Sort attributes by type (functions seperate from properties)
autodoc_member_order = 'groupwise'

# General information about the project.
project = u'MenpoFit'
authors = (u'Joan Alabort-i-Medina, Epameinondas Antonakos, James Booth,'
           u' Patrick Snape, and Stefanos Zafeiriou')
copyright = u'2014, ' + authors

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = menpofit.__version__
# The full version, including alpha/beta/rc tags.
release = menpofit.__version__

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', '**/test/**']

# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# -- Options for HTML output ---------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
if not on_rtd:  # only import and set the theme if we're building docs locally
    import sphinx_rtd_theme

    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'Menpofitdoc'

# -- Options for LaTeX output --------------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #'papersize': 'letterpaper',

    # The font size ('10pt', '11pt' or '12pt').
    #'pointsize': '10pt',

    # Additional stuff for the LaTeX preamble.
    #'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
    ('index', 'Menpofit.tex', u'MenpoFit Documentation',
     authors, 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output --------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'menpofit', u'MenpoFit Documentation',
     [authors], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output ------------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    ('index', 'MenpoFit', u'MenpoFit Documentation',
     authors,
     'MenpoFit',
     'Deformable modelling toolkit built on top of the Menpo project.',
     'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False


text:
/* applies to anything of class "example-class-selector" */
.example-class-selector {
	margin-top: 2em;
}

/* applies to any <p> descendants of an element of class "example-class-selector" */
.example-class-selector p {
	/* Colors are in hexadecimal: http://www.colorpicker.com/ */
	color: #CC00AA;
}

.project p {
    font-variant: small-caps;
}
.project{
     float: right;
}
.thumbnail{
     background-color: rgba(204, 221, 221, .3);
}

/* this style exists to make it obvious that you've successfully linked
   the CSS to the page. feel free to remove it once the link is working. */
body {
     width: 100%;
     height: 100%;
     background: url("http://miriadna.com/desctopwalls/images/max/Sunset-beach.jpg") no-repeat top center fixed;
     padding: 20px;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     background-size: cover;
     -o-background-size: cover;
}
.thumbnail:hover {
     opacity: 0.2;
}

.jumbotron {
	position: relative;
	background: none;
     color: white;
     text-shadow: -2px 0 black, 0 2px black, 2px 0 black, 0 -2px black;
}
.jumbotron:hover{
     text-decoration: underline;
     text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
.container{
     padding-top: 20px;
     background: rgba(36, 46, 53, .4);
}

.jumbotron:after {
     content:"";
     background: url("http://lorempixel.com/1140/283");
     top: 0;
     left: 0;
     bottom: 0;
     right: 0;
     position: absolute;
     z-index: -1;
}


text:
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Components\GoogleCalendar\FetchGoogleCalendarEvents::class,
        \App\Components\InternetConnectionStatus\SendHeartbeat::class,
        \App\Components\LastFm\FetchCurrentTrack::class,
        //\App\Components\RainForecast\FetchRainForecast::class,
        \App\Components\Packagist\FetchTotals::class,
        //\App\Components\GitHub\FetchGitHubFileContent::class,
    ];

    /**
     * Define the application's command schedule.
     *
     * @param \Illuminate\Console\Scheduling\Schedule $schedule
     *
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command(\App\Components\GoogleCalendar\FetchGoogleCalendarEvents::class)->everyFiveMinutes();
        $schedule->command(\App\Components\InternetConnectionStatus\SendHeartbeat::class)->everyMinute();
        $schedule->command(\App\Components\LastFm\FetchCurrentTrack::class)->everyMinute();
        //$schedule->command(\App\Components\RainForecast\FetchRainForecast::class)->everyMinute();
        $schedule->command(\App\Components\Packagist\FetchTotals::class)->everyThirtyMinutes();
        //$schedule->command(\App\Components\GitHub\FetchGitHubFileContent::class)->everyFiveMinutes();
    }
}


text:
package org.lielas.micdataloggerstudio.main.Tasks;

import org.lielas.dataloggerstudio.lib.Logger.mic.MicUSBStick;
import org.lielas.micdataloggerstudio.main.CommunicationInterface.mic.MicSerialInterface;
import org.lielas.micdataloggerstudio.main.UpdateManager;

/**
 * Created by Andi on 02.05.2015.
 */
public class SaveNameTask extends MicTask<Void, Void, MicUSBStick> {

    MicUSBStick stick;
    String name;

    public SaveNameTask(MicUSBStick stick, UpdateManager updateManager, String name){
        super(updateManager);
        this.stick = stick;
        this.name = name;
    }

    @Override
    protected MicUSBStick doInBackground(Void... params) {
        if(stick == null){
            return null;
        }

        MicSerialInterface com = (MicSerialInterface) stick.getCommunicationInterface();

        if(!com.isOpen()){
            return null;
        }

        if(!com.saveId(name, stick)){
            return null;
        }

        return stick;
    }

    @Override
    protected void onPostExecute(MicUSBStick stick){
        try{
            if(get() != null){
                updateManager.update("Loggername successfully set");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}


text:
<?php
namespace Darth\Model;

class Temp_Partner extends Model
{

}


text:
<?php

namespace Cubiche\Core\Async\Tests\Units\Promise;

use Cubiche\Core\Async\Promise\PromiseDeferred;

/**
 * Promise Deferred As Deferred Tests class.
 *
 * @author Ivannis Suárez Jerez <ivannis.suarez@gmail.com>
 * @author Karel Osorio Ramírez <osorioramirez@gmail.com>
 */
class PromiseDeferredAsDeferredTests extends DeferredInterfaceTestCase
{
    /**
     * @return object
     */
    public function newDefaultTestedInstance()
    {
        /** @var \Cubiche\Core\Async\Promise\PromiseDeferred $instance */
        $instance = parent::newDefaultTestedInstance();
        $instance->then();

        return $instance;
    }

    /**
     * {@inheritdoc}
     */
    public function getTestedClassName()
    {
        return PromiseDeferred::class;
    }
}


text:
#pragma once

#include <mutex>

namespace wangle {

/**
 * A guard that provides write and read access to a mutex type.
 */
template<typename MutexT>
struct CacheLockGuard;

// Specialize on std::mutex by providing exclusive access
template<>
struct CacheLockGuard<std::mutex> {
  using Read = std::lock_guard<std::mutex>;
  using Write = std::lock_guard<std::mutex>;
};

/**
 * A counter that represents a "version" of the data.  This is used to determine
 * if two components have been synced to the same version.
 * A valid version is 1 or higher.  A version of 0 implies no version.
 */
using CacheDataVersion = uint64_t;

}


text:
SPAM = 1

#! python

print "Hello, Python"

#! python
# string variable

STRING = "# This is not a comment."

print STRING


text:
(function($){

    $("document").ready(function () {

		//***********************************************************************************************************************
        // MODELS AND COLLECTIONS
        //***********************************************************************************************************************

        //model definition
		var modelDef = Backbone.Model.extend({});

		//collection definition
		var collectionDef = Backbone.Collection.extend({

            localStorage : new Backbone.LocalStorage("gridView-select"),
			model        : modelDef,

            //initialize
            initialize: function()
            {
                //call parent
                Backbone.Collection.prototype.initialize.apply(this,arguments);

                //store name of localstorage
                this.localStorageName = "gridView-select";
            }

		});

        //***********************************************************************************************************************
        // VIEWS
        //***********************************************************************************************************************

        //view definition (extends from custom view)
		var viewDef = baseGridViewWithCommands.extend({

            //on click single checkbox
            onClickSingleCheckbox: function()
            {
                //call parent
                baseGridViewWithCommands.prototype.onClickSingleCheckbox.apply(this,arguments);

                //compute number of report
                var reports = this.collection.where({status_id: this.status_id.end});

                //add reports
                this.model.set({reports: reports && reports.length || 0});
            },

            //on click email
            onClickEmail: function(evt)
            {
                //call filter function
                this.filterCollection(evt, 'participant', null, _.matcher({status_id: this.status_id.wait}));
            },

            //on click remind
            onClickRemind: function(evt)
            {
                //call filter function
                this.filterCollection(evt, 'participant', null, function(m)
                {return _.chain(this.status_id).pick(['emailSent', 'remindSent', 'start']).values().indexOf(parseInt(m.status_id),true).value() > -1});
            },

            //onclick paypal modal confirm button
            onClickReport: function(evt)
            {
                //call parent
                baseGridViewWithCommands.prototype.onClickReport.apply(this, arguments);

                //call filter function
                this.filterCollection(evt, 'participant', null, _.matcher({status_id: this.status_id.end}));
            },

            //on click download
            onClickDownload: function(evt)
            {
                //cache this
                var _this = this;

                //cache clicked button
                var $elm = $(evt.target);

                //filter collection
                var data = this.filterCollection(evt, 'participant', null, _.matcher({status_id: this.status_id.reportAvailable}), true);

                //if we have a valid download request
                if (data)
                {
                    //hack: call onclickAnyCommand
                    //due to events order we have to stop propagation
                    //and call onclickAnyCommand manually
                    this.onClickAnyCommand(evt);

                    //if user has selected more than 1 report to download
                    if ((data.ids).indexOf(',') > 0)
                    {
                        //submit ghost electron form
                        this.$('#electron-ids').val(data.ids);
                        this.$('#electron').submit();

                        //reload gridview and show message
                        $.when($.pjax.reload('#w0')).then(

                            function()
                            {
                                //hide spin
                                _this.hideSpin($elm);

                                //show success message
                                _this.notify(_this.ntfs[5], 'success')
                            });

                    //if user has selected just 1 report to download
                    } else {

                        //hide spin
                        this.hideSpin($elm);

                        //direct download of single report
                        window.location.href = '/backend/participant/download-single?report_id=' + this.collection.at(0).get('id');
                    }

                    //destroy collection
                    _.invoke(this.collection.toArray(),'destroy');

                    //stop propagation
                    return false;
                }
            },

            //on click reset
            onClickReset: function(evt)
            {
                //call filter function
                this.filterCollection(evt, 'participant', null, null);
            },

            //on click delete
            onClickDelete: function(evt)
            {
                //call filter function
                this.filterCollection(evt, 'participant', null, null);
            }

        });

        //***********************************************************************************************************************
        // APP INIT
        //***********************************************************************************************************************

        //start view and attach it to body
		var view = new viewDef({
            el         : 'body',
            collection : new collectionDef(), //will hold data from selected gridview rows
            model      : new modelDef() //will hold data for paypal calculations
        });

    });
})(jQuery);


text:
@interface BBXShimmeringSwitchSlider ()

@property (nonatomic, strong) CJSwitchSlider *switchSlider;

@end

@implementation BBXShimmeringSwitchSlider

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)setStatusModels:(NSMutableArray<CJSwitchSliderStatusModel *> *)statusModels {
    _statusModels = statusModels;

    self.switchSlider.statusModels = statusModels;

    [self.switchSlider showStep:0];
}

- (void)setSwitchEventOccuBlock:(void (^)(NSInteger))switchEventOccuBlock {
    _switchEventOccuBlock = switchEventOccuBlock;

    self.switchSlider.switchEventOccuBlock = switchEventOccuBlock;
}

- (void)commonInit {
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = 15;

    self.shimmering = YES;
    self.shimmeringOpacity = 1;
    self.shimmeringAnimationOpacity = 0.6;
    self.shimmeringPauseDuration = 2;

    self.shimmeringSpeed = 100;

    self.shimmeringBeginFadeDuration = 0.3;
    self.shimmeringEndFadeDuration = 2;

    self.switchSlider = [[CJSwitchSlider alloc] initWithFrame:CGRectZero];
    [self commonSetupToSwitchSlider:self.switchSlider];
    [self cj_makeView:self addSubView:self.switchSlider withEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    ((FBShimmeringLayer *)self.layer).contentLayer = self.switchSlider.layer;
}

- (void)commonSetupToSwitchSlider:(CJSwitchSlider *)switchSlider {
    UIView * (^createTrackViewBlock)(void) = ^(void) {
        UILabel *label = [DemoLabelFactory whiteLabelWithCornerRadius:15];
        return label;
    };

    UIView * (^createMinimumTrackViewBlock)(void) = ^(void) {
        UILabel *label = [DemoLabelFactory whiteLabelWithCornerRadius:15];
        return label;
    };

    UIView * (^createMaximumTrackViewBlock)(void) = ^(void) {
        UILabel *label = [DemoLabelFactory whiteLabelWithCornerRadius:15];
        return label;
    };

    void(^updateMaximumTrackViewBlock)(UIView *maximumTrackView, CJSwitchSliderStatusModel *statusModel, BOOL useDragingStauts) = ^ (UIView *maximumTrackView, CJSwitchSliderStatusModel *statusModel, BOOL isDragingStauts) {
        if (!isDragingStauts) {
            UILabel *c_maximumTrackView = (UILabel *)maximumTrackView;
            [c_maximumTrackView setText:statusModel.normalText];
            [c_maximumTrackView setBackgroundColor:statusModel.normalColor];

        } else {
            UILabel *c_maximumTrackView = (UILabel *)maximumTrackView;
            [c_maximumTrackView setText:statusModel.dragingText];
            [c_maximumTrackView setBackgroundColor:statusModel.dragingColor];
        }
    };

    void(^updateTrackViewBlock)(UIView *maximumTrackView, CJSwitchSliderStatusModel *statusModel, BOOL useDragingStauts) = ^ (UIView *maximumTrackView, CJSwitchSliderStatusModel *statusModel, BOOL isDragingStauts) {
        if (!isDragingStauts) {
            UILabel *c_maximumTrackView = (UILabel *)maximumTrackView;
            [c_maximumTrackView setText:statusModel.normalText];
            [c_maximumTrackView setBackgroundColor:statusModel.normalColor];

        } else {
            UILabel *c_maximumTrackView = (UILabel *)maximumTrackView;
            [c_maximumTrackView setText:statusModel.dragingText];
            [c_maximumTrackView setBackgroundColor:statusModel.dragingColor];
        }
    };
    [switchSlider setupViewWithCreateTrackViewBlock:createTrackViewBlock
                        createMinimumTrackViewBlock:createMinimumTrackViewBlock
                        createMaximumTrackViewBlock:createMaximumTrackViewBlock];
    [switchSlider setupUpdateTrackViewBlock:updateTrackViewBlock
                updateMinimumTrackViewBlock:nil
                updateMaximumTrackViewBlock:updateMaximumTrackViewBlock];

    UIImage *mainThumbImage = [UIImage imageNamed:@"btn_hd.png"];
    [switchSlider.mainThumb setImage:mainThumbImage forState:UIControlStateNormal];
    [switchSlider.mainThumb setImageEdgeInsets:UIEdgeInsetsMake(0, 20, 0 ,0 )];
    [switchSlider.mainThumb setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];

    switchSlider.trackHeight = 45;
    switchSlider.criticalValue = 0.3;
    switchSlider.thumbSize = CGSizeMake(350, 88);

    switchSlider.moveType = CJSliderMoveTypeMaximumTrackImageViewWidthAspectFit;
    switchSlider.switchAnimatedType = CJSwitchAnimatedTypeCurrentStepInMaximumTrackImageView;
    switchSlider.thumbMoveMaxXMargin = -switchSlider.thumbSize.width;
}

#pragma mark - addSubView
- (void)cj_makeView:(UIView *)superView addSubView:(UIView *)subView withEdgeInsets:(UIEdgeInsets)edgeInsets {
    [superView addSubview:subView];
    subView.translatesAutoresizingMaskIntoConstraints = NO;

    [superView addConstraint:
     [NSLayoutConstraint constraintWithItem:subView
                                  attribute:NSLayoutAttributeLeft   //left
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superView
                                  attribute:NSLayoutAttributeLeft
                                 multiplier:1
                                   constant:edgeInsets.left]];

    [superView addConstraint:
     [NSLayoutConstraint constraintWithItem:subView
                                  attribute:NSLayoutAttributeRight  //right
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superView
                                  attribute:NSLayoutAttributeRight
                                 multiplier:1
                                   constant:edgeInsets.right]];

    [superView addConstraint:
     [NSLayoutConstraint constraintWithItem:subView
                                  attribute:NSLayoutAttributeTop    //top
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superView
                                  attribute:NSLayoutAttributeTop
                                 multiplier:1
                                   constant:edgeInsets.top]];

    [superView addConstraint:
     [NSLayoutConstraint constraintWithItem:subView
                                  attribute:NSLayoutAttributeBottom //bottom
                                  relatedBy:NSLayoutRelationEqual
                                     toItem:superView
                                  attribute:NSLayoutAttributeBottom
                                 multiplier:1
                                   constant:edgeInsets.bottom]];
}

@end


text:
class FinishCancelledDonorsJob < DollarADayJob.new
  @priority = 3
  @queue    = 'default'

  # Keeping this in a job so we get notified if anything goes wrong
  def perform
    Donor.finish_cancelled_donors
  end
end


text:
<?php

$secret = "axyz";
$dir = 'sqlite:./data.db';
$dbh  = new PDO($dir) or die("cannot open the database");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );


text:
<?php
/**
 * @package SeanMorris\Theme\Test
 */
namespace SeanMorris\Theme\Test\TestTheme;
class Theme extends \SeanMorris\Theme\Theme
{
	protected static
		$view = [
			'SeanMorris\Theme\Test\Foo' => 'SeanMorris\Theme\Test\TestTheme\FooView'
			, 'SeanMorris\Theme\Test\Bar' => [
				'list' => 'SeanMorris\Theme\Test\TestTheme\BarView'
				, 'single' => 'SeanMorris\Theme\Test\TestTheme\BarListView'
			]
		]
		, $wrap = [
			'SeanMorris\Theme\Test\TestTheme\Wrapper'
		]
	;
}


text:
package me.lsbengine.api.admin.security

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.headers.HttpChallenge
import akka.http.scaladsl.server.AuthenticationFailedRejection.CredentialsRejected
import akka.http.scaladsl.server.{AuthenticationFailedRejection, Directive1, Directives}
import me.lsbengine.api.admin.security.CredentialsAuthenticator.Credentials
import me.lsbengine.database.model.User
import reactivemongo.api.{DefaultDB, MongoConnection}
import spray.json.{DefaultJsonProtocol, RootJsonFormat}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

object CredentialsAuthenticator {

  case class Credentials(username: String, password: String)

}

trait CredentialsAuthenticator extends Directives with SprayJsonSupport with DefaultJsonProtocol {

  val dbConnection: MongoConnection
  val dbName: String

  implicit val credentialsFormat: RootJsonFormat[Credentials] = jsonFormat2(Credentials)

  def isPasswordValid(actual: String, salt: String, provided: String): Boolean = {
    val decodedSalt = base64Decode(salt)
    val decodedActual = base64Decode(actual)
    val hashedProvided = PasswordHasher.hashPassword(provided, decodedSalt)
    val sameLength = decodedActual.length == hashedProvided.length
    val sameContent = decodedActual.zip(hashedProvided).forall {
      case (actByte, provByte) => actByte == provByte
    }
    sameLength && sameContent
  }

  def getUserAndValidatePassword(db: DefaultDB, creds: Credentials): Future[Option[User]] = {
    val usersAccessor = new UsersAccessor(db)
    usersAccessor.getUser(creds.username).map {
      case Some(user) =>
        if (isPasswordValid(user.password, user.salt, creds.password)) {
          Some(user)
        } else {
          None
        }
      case None =>
        //Does not give away that the username is invalid because of timing
        val dummy = base64Encode(Array[Byte](22, 22, 22))
        isPasswordValid(dummy, dummy, dummy)
        None
    }
  }

  def credentialsAuthenticator: Directive1[User] = {
    entity(as[Credentials]).flatMap {
      creds =>
        onSuccess(dbConnection.database(dbName)).flatMap {
          db =>
            onSuccess(getUserAndValidatePassword(db, creds)).flatMap {
              case Some(user) =>
                provide(user)
              case None =>
                reject(AuthenticationFailedRejection(CredentialsRejected, HttpChallenge("Nope", "admin access")))
            }
        }
    }
  }
}


text:
(function ($) {
    "use strict"; // Start of use strict

    // Smooth scrolling using jQuery easing
    $('a[href*="#"]:not([href="#"])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: (target.offset().top - 48)
                }, 1000, "easeInOutExpo");
                return false;
            }
        }
    });

    // Activate scrollspy to add active class to navbar items on scroll
    $('body').scrollspy({
        target: '#mainNav',
        offset: 48
    });

    // Closes responsive menu when a link is clicked
    $('.navbar-collapse>ul>li>a').click(function () {
        $('.navbar-collapse').collapse('hide');
    });

    // Collapse the navbar when page is scrolled
    $(window).scroll(function () {
        if ($("#mainNav").offset().top > 100) {
            $("#mainNav").addClass("navbar-shrink");
        } else {
            $("#mainNav").removeClass("navbar-shrink");
        }
    });

    // Scroll reveal calls
    window.sr = ScrollReveal();
    sr.reveal('.sr-icons', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 200);
    sr.reveal('.sr-button', {
        duration: 1000,
        delay: 200
    });
    sr.reveal('.sr-contact', {
        duration: 600,
        scale: 0.3,
        distance: '0px'
    }, 300);

    // Magnific popup calls
    $('.popup-gallery').magnificPopup({
        delegate: 'a',
        type: 'image',
        tLoading: 'Loading image #%curr%...',
        mainClass: 'mfp-img-mobile',
        gallery: {
            enabled: true,
            navigateByImgClick: true,
            preload: [0, 1]
        },
        image: {
            tError: 'The image #%curr% could not be loaded.'
        }
    });

})(jQuery); // End of use strict

function validate(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    var regex = /[0-9]|\./;
    if (!regex.test(key) && evt.keyCode != 8) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) theEvent.preventDefault();
    }
}

function checkWhich() {
    var inny = $("#innyholder").find("input:last");
    if($("#output h3").text() != "") {
        return;
    }
    console.log(inny.attr("id"));
    switch (inny.attr("id")) {
        case "magdmg":
            inny.attr("type", "text");
            inny.addClass("maskInput");
            inny.attr("disabled", "disabled");
                inny.css("transform", "translateY(-35%");
                $("#innyholder").append("<input type='number' id='critdmg' class='input-control' pattern=\"\d*\" placeholder='critical damage'>");
                console.log("doing");
            break;
        case "critdmg":
            inny.attr("type", "text");
            inny.addClass("maskInput");
            inny.attr("disabled", true);
            doCalc();
            $("#dmgCalc").text("Reset");
            $("#dmgCalc").on("click", function () {
                resetDmg();
            });
            break;
    }
}

function resetDmg() {
    $("#critdmg").remove();
    $("#magdmg").val("");
    $("#magdmg").attr("disabled", false);
    $("#magdmg").css("transform", "translateY(0%)");
    $("#dmgCalc").text("Continue");
    $("#dmgCalc").off("click");
    $("#output h3").text("");
}

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

function doCalc() {
    var magdmg = $("#magdmg").val();
    var critdmg = $("#critdmg").val();
    critdmg = critdmg / 100; //percentage to decimal
    var adjdmg = magdmg * 1.555556; //get damage while in shadow tower. Assumes 300 Mastery and 0% boost
    adjdmg = adjdmg * 4; //Multiplier for charged shot
    adjdmg = adjdmg * 2.5; //multiplier for emblem
    adjdmg = adjdmg * critdmg;
    var adder = (magdmg * 1.55556) * .1; //unsure of what they did here. Get emblem damage again based on damage in tower and 1% for ultra
    adjdmg = adjdmg * .01;
    adjdmg = adder + adjdmg;
    adjdmg = Math.floor(adjdmg);
    adjdmg = numberWithCommas(adjdmg);
    $("#output h3").text("Estimated Damage: " + adjdmg);
    console.log("Calculated");
}


text:
package org.nem.ncc.services;

import org.junit.Test;
import org.mockito.Mockito;
import org.nem.core.connect.client.*;
import org.nem.core.time.NetworkTimeStamp;
import org.nem.core.time.synchronization.CommunicationTimeStamps;
import org.nem.ncc.test.ServicesUtils;

public class TimeSynchronizationServicesTest {

	// region getCommunicationTimeStamps

	@Test
	public void getCommunicationTimeStampsAsyncReturnsCommunicationTimeStampsOnSuccess() {
		// Arrange:
		final TestContext context = new TestContext();

		// Assert:
		ServicesUtils.assertSuccessfulDelegationToConnector(
				endpoint -> context.services.getCommunicationTimeStampsAsync(endpoint).join(),
				context.connector,
				NisApiId.NIS_REST_TIME_SYNC_NETWORK_TIME,
				new CommunicationTimeStamps(new NetworkTimeStamp(10), new NetworkTimeStamp(20)));
	}

	@Test
	public void getCommunicationTimeStampsAsyncThrowsExceptionOnError() {
		// Assert:
		final TestContext context = new TestContext();
		ServicesUtils.assertFailureDelegationToConnector(
				endpoint -> context.services.getCommunicationTimeStampsAsync(endpoint).join(),
				context.connector,
				NisApiId.NIS_REST_TIME_SYNC_NETWORK_TIME);
	}

	//endregion

	private static class TestContext {
		final AsyncNisConnector connector = Mockito.mock(AsyncNisConnector.class);
		final TimeSynchronizationServices services = new TimeSynchronizationServices(this.connector);
	}
}